gamegold 5.3.2 → 5.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/gamegold-worker.js +4 -4
- package/lib/gamegold.js +5 -5
- package/package.json +1 -1
package/lib/gamegold.js
CHANGED
|
@@ -206,7 +206,7 @@ var r=i(126),s=r.Buffer;function n(e,t){for(var i in e)t[i]=e[i]}function a(e,t,
|
|
|
206
206
|
* pkg.js - package constants
|
|
207
207
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
208
208
|
* https://github.com/bookmansoft/gamegold
|
|
209
|
-
*/t.protocol="vallnet",t.version="v5.3.
|
|
209
|
+
*/t.protocol="vallnet",t.version="v5.3.3",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,i){"use strict";
|
|
210
210
|
/*!
|
|
211
211
|
* common.js - p2p constants for vallnet
|
|
212
212
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -287,7 +287,7 @@ const r=i(19).opcodes;function s(e){let t=null;var i=s.list[e.type];return new(i
|
|
|
287
287
|
/*!
|
|
288
288
|
* wallet.js - wallet object for vallnet
|
|
289
289
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
290
|
-
*/const r=i(0);var s=i(16);const n=i(15),a=i(2),o=i(3),c=i(35),h=i(197),u=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(70),g=i(332);i(216);const y=i(109),v=i(73),b=i(13),w=i(69),k=i(17),x=i(217),S=i(156),_=i(28),E=i(157),R=i(335),A=i(64),O=i(26),C=i(29),I=i(7),j=i(307),P=i(39),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),M=i(165),L=i(77),F=i(78),z=i(142),H=i(45),D=i(20),U=i(50),q=i(53),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),X=i(32).VerifyError,G=i(153).ErItem,Y=i(154).ErAbolishItem,J=i(226).EnchancementItem,Z=i(68),Q=i(59),ee=i(82),te=i(85).txdb,ie=i(37);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)}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 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){var t;e=b.getHash(e,"hex",this.network.type);return(e=await this.getPath(e))&&(t=await this.getAccount(e.account))?t.derivePath(e,this.master):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 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.hasAddress(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.belongToAccount(i,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){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new L(F.errors.TYPE_ERROR,"Invalid hex string.");let i=0;3<=e.outputs.length&&(i=2);var s=(a=e.outputs[i]).getReturnData();if(!s||s.oper!==W.propExchange&&s.oper!==W.propCreate)throw new L(F.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new X(block,"invalid","prop found supertoken",100);var n=new w,a=(e=(n.addInputFromTx(e,i),_.fromScript(a.getAddress(),a.value)),n.outputs.push(e),t?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:t}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),n.commit());return await this.db.send(a[0]),r(a[0].verify(a[1],k.flags.STANDARD_VERIFY_FLAGS)),a.push(s),a}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.");n.outputs[0].getReturnType(k.opcodes.OP_RETURN)&&(t=2);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.belongToAccount(s,n.outputs[t].getAddress()))throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");if(!(s=await this.getCoin(e,t))||-1===s.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=(s=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),s.outputs.push(a),await this.sign(s,null,N.SINGLE|N.ANYONECANPAY),e=s.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.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";
|
|
290
|
+
*/const r=i(0);var s=i(16);const n=i(15),a=i(2),o=i(3),c=i(35),h=i(197),u=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(70),g=i(332);i(216);const y=i(109),v=i(73),b=i(13),w=i(69),k=i(17),x=i(217),S=i(156),_=i(28),E=i(157),R=i(335),A=i(64),O=i(26),C=i(29),I=i(7),j=i(307),P=i(39),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),M=i(165),L=i(77),F=i(78),z=i(142),H=i(45),D=i(20),U=i(50),q=i(53),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),X=i(32).VerifyError,G=i(153).ErItem,Y=i(154).ErAbolishItem,J=i(226).EnchancementItem,Z=i(68),Q=i(59),ee=i(82),te=i(85).txdb,ie=i(37);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)}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 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){var t;e=b.getHash(e,"hex",this.network.type);return(e=await this.getPath(e))&&(t=await this.getAccount(e.account))?t.derivePath(e,this.master):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 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.hasAddress(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.belongToAccount(i,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.");n.outputs[0].getReturnType(k.opcodes.OP_RETURN)&&(t=2);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.belongToAccount(s,n.outputs[t].getAddress()))throw new L(F.errors.TYPE_ERROR,"Invalid tx info.");if(!(s=await this.getCoin(e,t))||-1===s.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=(s=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),s.outputs.push(a),await this.sign(s,null,N.SINGLE|N.ANYONECANPAY),e=s.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.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";
|
|
291
291
|
/*!
|
|
292
292
|
* BlockMeta.js - walletdb records
|
|
293
293
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -438,7 +438,7 @@ function r(e){let t=null;var i=r.list[e.contract.options.type];return i?new(t=i.
|
|
|
438
438
|
*
|
|
439
439
|
* @note 为了让打包程序正常工作,没有使用自动化方案来引入类文件
|
|
440
440
|
*/
|
|
441
|
-
const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.oper){case r.cpRegister:return i(191);case r.cpChange:return i(193);case r.coinbase:return i(194);case r.contractPromise:return i(195);case r.scRegister:return i(580);case r.scUpdate:return i(198);case r.scState:return i(199);case r.scRun:return i(200);case r.scNotify:return i(206);case r.propFound:return i(207);case r.vote:return i(208);case r.propSale:return i(209);case r.notify:return i(210);case r.contractCreate:return i(211);case r.contractExecute:return i(212);case r.erIssue:return i(213);case r.erAbolish:return i(214);case r.enchanceCp:return i(215);default:try{return i(581)("./"+e.oper)}catch(e){return i(14)}}}},function(e,t,i){var r=i(14);const s=i(19).nestingCodes,n=i(117);e.exports=class extends r{async insert(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++){var t=""+e.hash+i;e.env.middleHashMem.has(t)||this.setOptIndex(e,i)&&(await n(e).insert(),e.env.middleHashMem.add(t))}}async erase(){var e=this.getOpt();for(let t=0;t<e.tx.outputs.length;t++)e.env.middleHashMem.delete(""+e.hash+t),this.setOptIndex(e,t)&&await n(e).erase()}async confirm(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++){var t=""+e.hash+i;e.env.middleHashChain.has(t)||this.setOptIndex(e,i)&&(await n(e).confirm(),e.env.middleHashChain.add(t))}}async unconfirm(){var e=this.getOpt();for(let t=0;t<e.tx.outputs.length;t++)e.env.middleHashChain.delete(""+e.hash+t),this.setOptIndex(e,t)&&await n(e).unconfirm()}async verify(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++)if(this.setOptIndex(e,i)){var t=await n(e).verify();if(1!=t)return t}return!0}getOpt(){return{env:this.options.env,tx:this.options.tx,block:this.options.block,height:this.options.coinbaseHeight,hash:this.options.hash}}setOptIndex(e,t){return e.i=t,e.output=e.tx.outputs[t],e.type=e.output.getReturnType(),e.data=e.output.getReturnData(s),!!e.data}}},function(e,t,i){const{ContractEnvType:r,PropStatus:s}=i(5);var n=i(58);const a=i(7),o=i(148);e.exports=class extends n{async confirm(){var{env:e,i:t,output:i,data:n,hash:a,block:o,tx:c}=this.options,h=await e.propList.getVp(n.pid);!h||h.current.hash==a&&h.current.index==t?(n.current={hash:a,index:t,address:i.getAddress().toString()},n.height=0<e.curHeight?e.curHeight+1:0,n.pst=s.Ready,n.gold=i.value,await e.propList.setVp(n,c),e.mode==r.Block&&(i={pid:n.pid,oid:n.oid,cid:n.cid,dst:n.current.address,time:o.time,height:n.height},e.node.transmit("prop.create",i))):e.logger.warning("PropCreate.conflict",n.pid,", height: ",o?o.height:0,"mode: ",e.mode,a,t,h.current.hash,h.current.index)}async unconfirm(){var e,{env:t,i:i,data:e,hash:r}=this.options;(e=await t.propList.getVp(e.pid))&&e.current.hash==r&&e.current.index==i&&await t.propList.delVp(e)}async verify(){var{env:e,output:t,data:i}=this.options;if(!o.unittest){var r=e.cpList.getItem(i.cid);if(!r||r.current.address!=t.getAddress().toString())return"PropCreate.errorAddress"}return t.value<a.MINPROPVALUE?"PropCreate.MINPROPVALUE":!e.network.tokenReg.test(i.pid)||"PropCreate.invalidPid"}}},function(e,t,i){const r=i(0),s=i(19).opcodes,n=i(38).broadcast,a=i(132).vpItem;var o=i(58);const{ContractEnvType:c,PropStatus:h}=i(5);e.exports=class extends o{async confirm(){let{env:e,i:t,output:i,data:r,hash:o,tx:u,block:l}=this.options;if(e.mode==c.Wallet){var p=await e.propList.getVp(r.pid);if(p&&(p.current.hash!=r.prev.hash||p.current.index!=r.prev.index))return void e.logger.warning("PropExchange.conflict",r.pid,", height: ",l?l.height:0,"mode: ",e.mode,"sim: ",o,t,"ori: ",p.current.hash,p.current.index);p=new a({pid:r.pid,cid:r.cid,oid:r.oid,gold:i.value,current:{hash:o,index:t,address:i.getAddress().toString()},height:0<e.curHeight?e.curHeight+1:0,pst:h.Ready,wid:0,account:""}),await e.propList.setVp(p,u),p={pid:p.pid,address:p.current.address,wid:p.wid,account:p.account,time:l.time,height:p.height,cid:p.cid},e.emit("prop/receive",p),n("prop/receive",p)}else{if(!(p=await e.propList.getVp(r.pid))||p.current.hash!=r.prev.hash||p.current.index!=r.prev.index)return void e.logger.warning("PropExchange.conflict",r.pid,", height: ",l?l.height:0,"mode: ",e.mode,"sim: ",o,t,"ori: ",p.current.hash,p.current.index);var d,f=p.current.address,m=i.getAddress().toString();if(p.current={hash:o,index:t,address:m},p.height=0<e.curHeight?e.curHeight+1:0,p.pst=h.Ready,await e.propList.setVp(p,u),e.mode==c.Block){if(p.cid==e.network.genesisId){for(d of(await e.propList.getVpByAddress(f)).list){if(d.cid==e.network.genesisId)break;e.voteMgr.delTokenAddress(f)}e.voteMgr.addTokenAddress(m)}m={pid:p.pid,oid:p.oid,cid:p.cid,src:f,dst:m,time:l.time,height:p.height},e.node.transmit("prop.exchange",m)}}let g=0,y=r;for(;i&&i.getReturnType(s.OP_PROPEXCHANGE)&&g++<2e3;){var v=y.prev,b=(e.middleHashChain.add(v.hash+v.index.toString()),await e.finder(v.hash));if(!b)break;if(i=b.outputs[v.index],!(y=i.getReturnData())||!y.prev||e.middleHashChain.has(y.prev.hash+y.prev.index.toString()))break}}async unconfirm(){var{env:e,data:t}=this.options,i=await e.finder(t.prev.hash);if(i&&i.outputs[t.prev.index]&&(a=i.outputs[t.prev.index]).getReturnData([s.OP_PROPEXCHANGE,s.OP_PROPCREATE])){var r=await e.propList.getVp(t.pid);if(r){var n,a=a.getAddress().toString(),o=r.current.address;if(r.current.hash=t.prev.hash,r.current.index=t.prev.index,r.current.address=a,await e.propList.setVp(r,i),e.mode==c.Block&&r.cid==e.network.genesisId){for(n of(await e.propList.getVpByAddress(o)).list){if(n.cid==e.network.genesisId)break;e.voteMgr.delTokenAddress(o)}e.voteMgr.addTokenAddress(a)}}}}async verify(){var{env:e,tx:t,i:i,data:s}=this.options;return r.strictEqual(s.prev.hash,t.inputs[i].prevout.hash),r.strictEqual(s.prev.index,t.inputs[i].prevout.index),await e.propList.getVp(s.pid),!0}}},function(e,t,i){var r=i(14);const s=i(5).ContractEnvType,n=i(32).VerifyError;var{}=i(19);const a=i(192);e.exports=class extends r{async insert(){var e=this.options.env,t=this.options.tx,i=t.hash("hex"),r=this.data;r.current={hash:i,index:0,address:t.outputs[0].getAddress().toString()},r.height=-1,await e.cpMemList.addItem(r)}async erase(){var e=this.options.env,t=this.data;await e.cpMemList.delItem(t)}async confirm(){var e=this.options.env,t=this.options.tx,i=t.hash("hex"),r=this.data;r.current={hash:i,index:0,address:t.outputs[0].getAddress().toString()},r.height=this.options.coinbaseHeight,r.status=1,await e.cpList.addItem(r),e.mode==s.Block&&(i={cid:r.cid,name:r.name,address:r.current.address},e.node.transmit("cp.create",i)),this.mode==s.Block&&await e.chain.node.mempool.cpMemList.delItem(r)}async unconfirm(){var e=this.options.env,t=this.data;this.options.tx,await e.cpList.delItem(t)}async verify(){var e=this.options.env,t=this.options.tx;if(!this.data)throw new n(t,"invalid","null cpRegister data",100);var i=a.verifyDataFormat(this.data);if(i)throw new n(t,"invalid",i,100);if((this.mode!=s.Block||"spv"!=e.node.nodeType)&&(i=this.mode!=s.Mempool,!await e.rpcExecute({method:"canExecute",params:[{confirm:i,cid:this.data.cid,name:this.data.name,oper:this.data.oper}]})))throw new n(t,"invalid info on "+this.data.oper,"cp.create",0);return!0}}},function(e,t,i){"use strict";
|
|
441
|
+
const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.oper){case r.cpRegister:return i(191);case r.cpChange:return i(193);case r.coinbase:return i(194);case r.contractPromise:return i(195);case r.scRegister:return i(580);case r.scUpdate:return i(198);case r.scState:return i(199);case r.scRun:return i(200);case r.scNotify:return i(206);case r.propFound:return i(207);case r.vote:return i(208);case r.propSale:return i(209);case r.notify:return i(210);case r.contractCreate:return i(211);case r.contractExecute:return i(212);case r.erIssue:return i(213);case r.erAbolish:return i(214);case r.enchanceCp:return i(215);default:try{return i(581)("./"+e.oper)}catch(e){return i(14)}}}},function(e,t,i){var r=i(14);const s=i(19).nestingCodes,n=i(117);e.exports=class extends r{async insert(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++){var t=""+e.hash+i;e.env.middleHashMem.has(t)||this.setOptIndex(e,i)&&(await n(e).insert(),e.env.middleHashMem.add(t))}}async erase(){var e=this.getOpt();for(let t=0;t<e.tx.outputs.length;t++)e.env.middleHashMem.delete(""+e.hash+t),this.setOptIndex(e,t)&&await n(e).erase()}async confirm(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++){var t=""+e.hash+i;e.env.middleHashChain.has(t)||this.setOptIndex(e,i)&&(await n(e).confirm(),e.env.middleHashChain.add(t))}}async unconfirm(){var e=this.getOpt();for(let t=0;t<e.tx.outputs.length;t++)e.env.middleHashChain.delete(""+e.hash+t),this.setOptIndex(e,t)&&await n(e).unconfirm()}async verify(){var e=this.getOpt();for(let i=0;i<e.tx.outputs.length;i++)if(this.setOptIndex(e,i)){var t=await n(e).verify();if(1!=t)return t}return!0}getOpt(){return{env:this.options.env,tx:this.options.tx,block:this.options.block,height:this.options.coinbaseHeight,hash:this.options.hash}}setOptIndex(e,t){return e.i=t,e.output=e.tx.outputs[t],e.type=e.output.getReturnType(),e.data=e.output.getReturnData(s),!!e.data}}},function(e,t,i){const{ContractEnvType:r,PropStatus:s}=i(5);var n=i(58);const a=i(7),o=i(148);e.exports=class extends n{async confirm(){var{env:e,i:t,output:i,data:n,hash:a,block:o,tx:c}=this.options,h=await e.propList.getVp(n.pid);!h||h.current.hash==a&&h.current.index==t?(n.current={hash:a,index:t,address:i.getAddress().toString()},n.height=0<e.curHeight?e.curHeight+1:0,n.pst=s.Ready,n.gold=i.value,await e.propList.setVp(n,c),e.mode==r.Block&&(i={pid:n.pid,oid:n.oid,cid:n.cid,dst:n.current.address,time:o.time,height:n.height,value:n.gold},e.node.transmit("prop.create",i))):e.logger.warning("PropCreate.conflict",n.pid,", height: ",o?o.height:0,"mode: ",e.mode,a,t,h.current.hash,h.current.index)}async unconfirm(){var e,{env:t,i:i,data:e,hash:r}=this.options;(e=await t.propList.getVp(e.pid))&&e.current.hash==r&&e.current.index==i&&await t.propList.delVp(e)}async verify(){var{env:e,output:t,data:i}=this.options;if(!o.unittest){var r=e.cpList.getItem(i.cid);if(!r||r.current.address!=t.getAddress().toString())return"PropCreate.errorAddress"}return t.value<a.MINPROPVALUE?"PropCreate.MINPROPVALUE":!e.network.tokenReg.test(i.pid)||"PropCreate.invalidPid"}}},function(e,t,i){const r=i(0),s=i(19).opcodes,n=i(38).broadcast,a=i(132).vpItem;var o=i(58);const{ContractEnvType:c,PropStatus:h}=i(5);e.exports=class extends o{async confirm(){let{env:e,i:t,output:i,data:r,hash:o,tx:u,block:l}=this.options;if(e.mode==c.Wallet){var p=await e.propList.getVp(r.pid);if(p&&(p.current.hash!=r.prev.hash||p.current.index!=r.prev.index))return void e.logger.warning("PropExchange.conflict",r.pid,", height: ",l?l.height:0,"mode: ",e.mode,"sim: ",o,t,"ori: ",p.current.hash,p.current.index);p=new a({pid:r.pid,cid:r.cid,oid:r.oid,gold:i.value,current:{hash:o,index:t,address:i.getAddress().toString()},height:0<e.curHeight?e.curHeight+1:0,pst:h.Ready,wid:0,account:""}),await e.propList.setVp(p,u),p={pid:p.pid,address:p.current.address,wid:p.wid,account:p.account,time:l.time,height:p.height,cid:p.cid},e.emit("prop/receive",p),n("prop/receive",p)}else{if(!(p=await e.propList.getVp(r.pid))||p.current.hash!=r.prev.hash||p.current.index!=r.prev.index)return void e.logger.warning("PropExchange.conflict",r.pid,", height: ",l?l.height:0,"mode: ",e.mode,"sim: ",o,t,"ori: ",p.current.hash,p.current.index);var d,f=p.current.address,m=i.getAddress().toString();if(p.current={hash:o,index:t,address:m},p.height=0<e.curHeight?e.curHeight+1:0,p.pst=h.Ready,await e.propList.setVp(p,u),e.mode==c.Block){if(p.cid==e.network.genesisId){for(d of(await e.propList.getVpByAddress(f)).list){if(d.cid==e.network.genesisId)break;e.voteMgr.delTokenAddress(f)}e.voteMgr.addTokenAddress(m)}m={pid:p.pid,oid:p.oid,cid:p.cid,src:f,dst:m,time:l.time,height:p.height},e.node.transmit("prop.exchange",m)}}let g=0,y=r;for(;i&&i.getReturnType(s.OP_PROPEXCHANGE)&&g++<2e3;){var v=y.prev,b=(e.middleHashChain.add(v.hash+v.index.toString()),await e.finder(v.hash));if(!b)break;if(i=b.outputs[v.index],!(y=i.getReturnData())||!y.prev||e.middleHashChain.has(y.prev.hash+y.prev.index.toString()))break}}async unconfirm(){var{env:e,data:t}=this.options,i=await e.finder(t.prev.hash);if(i&&i.outputs[t.prev.index]&&(a=i.outputs[t.prev.index]).getReturnData([s.OP_PROPEXCHANGE,s.OP_PROPCREATE])){var r=await e.propList.getVp(t.pid);if(r){var n,a=a.getAddress().toString(),o=r.current.address;if(r.current.hash=t.prev.hash,r.current.index=t.prev.index,r.current.address=a,await e.propList.setVp(r,i),e.mode==c.Block&&r.cid==e.network.genesisId){for(n of(await e.propList.getVpByAddress(o)).list){if(n.cid==e.network.genesisId)break;e.voteMgr.delTokenAddress(o)}e.voteMgr.addTokenAddress(a)}}}}async verify(){var{env:e,tx:t,i:i,data:s}=this.options;return r.strictEqual(s.prev.hash,t.inputs[i].prevout.hash),r.strictEqual(s.prev.index,t.inputs[i].prevout.index),await e.propList.getVp(s.pid),!0}}},function(e,t,i){var r=i(14);const s=i(5).ContractEnvType,n=i(32).VerifyError;var{}=i(19);const a=i(192);e.exports=class extends r{async insert(){var e=this.options.env,t=this.options.tx,i=t.hash("hex"),r=this.data;r.current={hash:i,index:0,address:t.outputs[0].getAddress().toString()},r.height=-1,await e.cpMemList.addItem(r)}async erase(){var e=this.options.env,t=this.data;await e.cpMemList.delItem(t)}async confirm(){var e=this.options.env,t=this.options.tx,i=t.hash("hex"),r=this.data;r.current={hash:i,index:0,address:t.outputs[0].getAddress().toString()},r.height=this.options.coinbaseHeight,r.status=1,await e.cpList.addItem(r),e.mode==s.Block&&(i={cid:r.cid,name:r.name,address:r.current.address},e.node.transmit("cp.create",i)),this.mode==s.Block&&await e.chain.node.mempool.cpMemList.delItem(r)}async unconfirm(){var e=this.options.env,t=this.data;this.options.tx,await e.cpList.delItem(t)}async verify(){var e=this.options.env,t=this.options.tx;if(!this.data)throw new n(t,"invalid","null cpRegister data",100);var i=a.verifyDataFormat(this.data);if(i)throw new n(t,"invalid",i,100);if((this.mode!=s.Block||"spv"!=e.node.nodeType)&&(i=this.mode!=s.Mempool,!await e.rpcExecute({method:"canExecute",params:[{confirm:i,cid:this.data.cid,name:this.data.name,oper:this.data.oper}]})))throw new n(t,"invalid info on "+this.data.oper,"cp.create",0);return!0}}},function(e,t,i){"use strict";
|
|
442
442
|
/*!
|
|
443
443
|
* cpHelper.js
|
|
444
444
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -918,7 +918,7 @@ var r=i(775),s=i(777),n=i(778),a=i(779),o=i(780),c=i(781),h=i(782);i=i(783),s=[]
|
|
|
918
918
|
* rpc.js - bitcoind-compatible json rpc for vallnet.
|
|
919
919
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
920
920
|
* https://github.com/bookmansoft/gamegold
|
|
921
|
-
*/const r=i(0),s=i(73);i(119);const n=i(85).walletdb,a=i(157),o=i(78),c=o.errors,h=o.MAGIC_STRING,u=i(77),l=i(59),p=i(107),d=i(2),f=i(192),m=i(3),g=i(84),y=i(33),v=i(17),b=i(7),w=i(6),k=i(26),x=i(13),S=i(39),_=i(131),E=i(69),R=i(45),A=i(20),O=i(136),C=i(137),{ContractType:I,ContractState:j,PropStatus:P,HtlcStatus:T}=i(5),B=i(138),N=i(123),M=i(142),L=i(19).opcodes,F=i(34),z=i(612);e.exports=class extends o{constructor(e){super(e),r(e,"RPC requires a WalletDB."),this.wdb=e,this.keys=e.keys,this.network=e.network,this.logger=e.logger.context("rpc"),this.client=e.client,this.init()}init(){this.add("sys.alliance.create",this.allianceCreate),this.add("sys.alliance.import",this.allianceImport),this.add("sys.alliance.delete",this.allianceDelete),this.add("sys.alliance.refresh",this.refreshAlliance),this.add("sys.alliance.refresh.async",this.refreshAllianceAsync),this.add("sys.alliance.gettoken",this.getAllianceNodeToken),this.add("sys.alliance.user",this.allianceUserCreate),this.add("wallet",this.routerOfWallet),this.add("wallet.create",this.mkwallet),this.add("wallet.exportmnemonic.admin",this.exportMnemonic),this.add("wallet.importmnemonic.admin",this.importMnemonic),this.add("wallet.export",this.dumpWallet),this.add("wallet.exports.admin",this.dumpWallets),this.add("wallet.import",this.importWallet),this.add("wallet.list",this.getWallets),this.add("wallet.info",this.getWalletInfo),this.add("wallet.block",this.getWalletBlock),this.add("wallet.layouth",this.getWalletLayoutH),this.add("wallet.encrypt",this.encryptWallet),this.add("wallet.decrypt",this.decryptWallet),this.add("wallet.changepassphrase",this.changePassphrase),this.add("wallet.lock",this.walletLock),this.add("wallet.unlock",this.unlock),this.add("wallet.blocks",this.getblocks),this.add("wallet.auth",this.walletAuth),this.add("wallet.rescan",this.rescan),this.add("key",this.routerOfKey),this.add("key.export.private",this.dumpPrivKey),this.add("key.export.public",this.getKey),this.add("key.master.admin",this.masterkey),this.add("key.import.private",this.importPrivKey),this.add("key.import.public",this.importPubkey),this.add("key.import.address",this.importAddress),this.add("key.shared.add",this.addShared),this.add("key.shared.del",this.removeShared),this.add("account",this.routerOfAccount),this.add("account.list",this.listAccounts),this.add("account.get",this.accountGet),this.add("account.create",this.accountCreate),this.add("account.received",this.getReceivedByAccount),this.add("account.listreceived",this.listReceivedByAccount),this.add("account.virtualadd.admin",this.accountVirtualAdd),this.add("account.checkamount",this.accountCheckAmount),this.add("balance.confirmed",this.getBalance),this.add("balance.all",this.getBalanceAll),this.add("balance.check",this.checkBalance),this.add("balance.unconfirmed",this.getUnconfirmedBalance),this.add("balance.log",this.getBalanceLog),this.add("comm.notify",this.commNotify),this.add("comm.hash",this.calcHash),this.add("comm.listNotify",this.listNotify),this.add("comm.secret",this.sendSecret),this.add("comm.listContact",this.listContact),this.add("comm.scanContact",this.scanContact),this.add("comm.comment",this.sendComment),this.add("comm.comment.query",this.commentQuery),this.add("sys.walletdb.stop",this.stop),this.add("sys.walletnode.shutdown",this.shutdown),this.add("sys.walletdb.create",this.createWalletDb),this.add("sys.walletdb.destroy",this.destroyWalletDb),this.add("sys.zap",this.zap),this.add("sys.setfee",this.setTXFee),this.add("sys.message.sign",this.signMessage),this.add("sys.log",this.sysLog),this.add("address",this.routerOfAddress),this.add("address.list",this.getAddressesByAccount),this.add("address.index",this.getAddressesByIndex),this.add("address.receive",this.getAccountAddress),this.add("address.change",this.getAccountChangeAddress),this.add("address.nested",this.getAccountNestedAddress),this.add("address.calc",this.calcAddress),this.add("address.create",this.createAddress),this.add("address.create.admin",this.createAddressAdmin),this.add("address.receive.create",this.createAddress),this.add("address.change.create",this.createChange),this.add("address.nested.create",this.createNested),this.add("address.import",this.importAddress),this.add("address.key.admin",this.getPrivKey),this.add("address.wif.admin",this.getwif),this.add("address.has",this.hasAddress),this.add("address.amount",this.getReceivedByAddress),this.add("address.account",this.getAccount),this.add("address.received",this.getReceivedByAddress),this.add("address.received.list",this.listReceivedByAddress),this.add("cp",this.routerOfCp),this.add("cp.create",this.cpRegister),this.add("cp.create.async",this.cpRegisterAsync),this.add("cp.change",this.cpChange),this.add("cp.query",this.cpQuery),this.add("cp.query.remote",this.cpQueryRemote),this.add("cp.mine",this.cpMine),this.add("cp.user",this.getUserToken),this.add("sc",this.routerOfSc),this.add("sc.register",this.scRegister),this.add("sc.run",this.scRun),this.add("ca",this.routerOfCa),this.add("ca.issue",this.caIssue),this.add("ca.user.status",this.caUserStatus),this.add("ca.user.log",this.caUserLog),this.add("ca.abolish",this.caAbolish),this.add("ca.enchance",this.enchanceCp),this.add("ca.list.me",this.queryMyErlist),this.add("ca.list.remote",this.queryErList),this.add("ca.issue.async",this.caIssueAsync),this.add("ca.abolish.async",this.caAbolishAsync),this.add("ca.issue.public",this.caIssuePublic),this.add("ca.abolish.public",this.caAbolishPublic),this.add("prop",this.routerOfProp),this.add("inscription.create",this.inscriptionCreate),this.add("prop.create",this.propCreate),this.add("prop.send",this.propExchange),this.add("prop.donate",this.propDonate),this.add("prop.receive",this.propReceive),this.add("prop.createlist",this.propCreateList),this.add("prop.sendlist",this.propSendList),this.add("prop.sendlist.admin",this.propSendListAdmin),this.add("prop.found",this.propFound),this.add("prop.sale",this.propSale),this.add("prop.buy",this.propBuy),this.add("prop.query",this.propQuery),this.add("prop.query.auction",this.mySaleList),this.add("prop.query.bid",this.onSaleList),this.add("prop.wallet.byid",this.propGet),this.add("prop.wallet.byoid",this.listPropByOid),this.add("prop.wallet.byaddress",this.listProp),this.add("contract",this.routerOfContract),this.add("contract.create",this.contractCreate),this.add("contract.promise",this.contractPromise),this.add("contract.execute",this.contractExecute),this.add("contract.mine",this.contractOfMine),this.add("htlc",this.routerOfHTLC),this.add("htlc.suggest",this.htlcSuggest),this.add("htlc.suggest.cancel",this.htlcSuggestCancel),this.add("htlc.suggest.deal",this.htlcSuggestDeal),this.add("htlc.assent",this.htlcAssent),this.add("htlc.assent.cancel",this.htlcAssentCancel),this.add("htlc.assent.deal",this.htlcAssentDeal),this.add("htlc.query",this.htlcQuery),this.add("vote.send",this.sendVote),this.add("vote.send.async",this.sendVoteAsync),this.add("oracle.send",this.sendOracle),this.add("tx.get.wallet",this.getTransaction),this.add("tx.list",this.listTransactions),this.add("tx.create",this.createTX),this.add("tx.send",this.sendTX),this.add("tx.send.async",this.sendTXAsync),this.add("tx.last",this.getLast),this.add("tx.pending",this.getPending),this.add("tx.pending.get",this.getPendingItem),this.add("tx.pending.hash",this.getPendingHash),this.add("tx.pending.count",this.getPendingCount),this.add("tx.resend.admin",this.resendWalletTransactions),this.add("tx.mstrans",this.listMSTrans),this.add("tx.mstrans.sign",this.signMSTrans),this.add("tx.history",this.getHistory),this.add("tx.history.since",this.listSinceBlock),this.add("tx.range",this.getRange),this.add("tx.abandon.admin",this.abandonTransaction),this.add("tx.abandonall.admin",this.abandonPending),this.add("tx.importprunedfunds.admin",this.importPrunedFunds),this.add("tx.removeprunedfunds.admin",this.removePrunedFunds),this.add("tx.resendall.admin",this.resend),this.add("tx.sign.admin",this.signTX),this.add("tx.fund.admin",this.fundRawTransaction),this.add("coin",this.routerOfCoin),this.add("coin.get",this.getCoin),this.add("coin.spender",this.getSpender),this.add("coin.spent",this.getSpent),this.add("coin.cache",this.getCoincacheSize),this.add("coin.check",this.checkUnspent),this.add("coin.list",this.listUnspent),this.add("coin.selectone",this.selectone),this.add("coin.conserved.get",this.getConservedCoins),this.add("coin.conserved.add",this.conserveCoin),this.add("coin.conserved.del",this.unConserveCoin),this.add("coin.conserved.list",this.listConservedUnspent),this.add("coin.conserved.oper.list",this.listOperUnspent),this.add("coin.locked.list",this.listLockedUnspent)}async routerOfCoin(e){throw new u(c.MISC_ERROR,"\n coin.get 查询硬币-UTXO\n coin.remove.admin 移除指定硬币(管理员判断为状态异常者)\n coin.spender 查询硬币的消费者\n coin.list 列表硬币-UTXO\n coin.conserved.get 获取钱包保持的Coin的信息\n coin.conserved.add 钱包增加需要保持的Coin\n coin.conserved.del 钱包减少需要保持的Coin\n coin.conserved.list 列表钱包保持的UTXO\n coin.conserved.oper.list 批量锁定/解锁一组UTXO \n coin.locked.list 列表目前交易层锁定的UTXO\n ")}async routerOfContract(e){throw new u(c.MISC_ERROR,"\n contract.create 发布交易对合约\n contract.promise 签署交易对合约\n contract.execute 执行交易对合约\n contract.mine 获取已签署交易对合约列表\n contract.list 查询并返回交易对\n ")}async routerOfHTLC(e){throw new u(c.MISC_ERROR,"\n htlc.suggest 发布跨链合约\n htlc.suggest.deal 兑现合约\n htlc.suggest.cancel 取消合约\n htlc.assent 响应跨链合约\n htlc.assent.deal 兑现响应\n htlc.assent.cancel 取消响应\n htlc.query 查询合约\n ")}async routerOfWallet(e){throw new u(c.MISC_ERROR,"\n wallet.create 创建钱包\n wallet.list 列表钱包\n wallet.info 查询钱包概要\n wallet.block 查询区块信息\n wallet.exportmnemonic.admin 导出钱包助记词备份\n wallet.importmnemonic.admin 导入钱包助记词备份\n wallet.export 导出钱包备份\n wallet.import 导入钱包备份\n wallet.encrypt 将主私钥永久加密\n wallet.decrypt 将主私钥永久解密\n wallet.changepassphrase 在主私钥已经加密的情况下,修改其加密密码,要提交旧/新两个密码。如果尚未加密则执行失败\n wallet.lock 在主私钥已加密的前提下,清理内存中的密钥信息以确保锁定,相当于手工执行自动锁定\n wallet.unlock 在主私钥已加密的前提下,解密主私钥,持续一段时间后自动锁定\n wallet.blocks 列表钱包相关区块\n ")}async routerOfAddress(e){throw new u(c.MISC_ERROR,"\n address.list 列表指定账户下地址\n address.receive 列表指定账户下收款地址\n address.change 列表指定账户下找零地址\n address.nested 列表指定账户下嵌套地址\n address.create 创建一个收款地址\n address.create.admin 创建一个收款地址,回显私钥\n address.receive.create 创建一个收款地址\n address.change.create 创建一个找零地址\n address.nested.create 创建一个嵌套地址\n address.import 导入一个地址\n address.key.admin 查询地址的密钥\n address.amount 查询指定地址上的余额\n address.account 查询指定地址对应的账户\n address.wif.admin 查询地址对应的私钥\n address.has 判断钱包是否包含地址\n address.received 根据地址查询进项总额\n address.received.list 根据地址查询进项\n address.filter 在订单流水中,查询符合筛选条件的地址集\n ")}async routerOfAccount(e){throw new u(c.MISC_ERROR,"\n account.list 列表账户\n account.get 查询账户\n account.create 创建账户\n account.received 查询收款总额\n account.listreceived 列表收款记录\n balance.confirmed 已确认余额\n balance.all 余额\n balance.unconfirmed 未确认余额\n balance.log 查询指定账户变更日志\n ")}async routerOfKey(e){throw new u(c.MISC_ERROR,"\n key.export.private 根据输入地址,导出私钥\n key.export.public 根据输入地址,打出公钥\n key.master.admin 导出根密钥和助记词, 注意 encrypt 状态下无法导出私钥\n key.import.private 导入私钥\n key.import.public 导入公钥\n key.import.address 导入地址\n key.shared.add 新增共享公钥\n key.shared.del 删除共享公钥\n ")}async routerOfCp(e){throw new u(c.MISC_ERROR,"\n cp.create 创建CP记录\n cp.change 修改CP记录\n cp.remoteQuery 查询全节点中的CP列表\n cp.query 查询本地CP列表\n cp.byClass 根据游戏类别查询CP记录\n cp.byName 根据名称查询CP记录\n cp.byId 根据ID查询CP记录\n cp.mine 当前操作员注册的CP\n cp.user 生成用户令牌(钱包)\n ")}async routerOfSc(e){throw new u(c.MISC_ERROR,"\n sc.model 查询托管合约模板列表\n sc.register 指定托管合约模板,创建新的实例\n sc.query 查询托管合约实例列表\n sc.run 调用托管合约实例\n ")}async routerOfCa(e){throw new u(c.MISC_ERROR,"\n ca.issue 电子证书签发\n ca.abolish 电子证书废止记录\n ca.verify 电子证书验证\n ca.user.status 根据企业证书编号和用户编号查询\n ca.user.log 根据企业证书编号和用户编号查询日志\n ca.enchance CA机构间增信\n ca.rank 查询CA信用等级\n ca.list 查询电子证书列表\n ca.list.ab 查询电子证书废止记录列表\n ca.list.me 查询钱包内证书列表\n ")}async routerOfProp(e){throw new u(c.MISC_ERROR,"\n prop.create 创建道具\n prop.send 转移道具\n prop.donate 捐赠道具\n prop.receive 接收捐赠道具\n prop.createlist 批量创建道具\n prop.sendlist 批量转移道具\n prop.found 熔铸道具\n prop.sale 拍卖道具\n prop.buy 购买道具\n prop.query 条件查询自己拥有的道具\n prop.byaddress 根据地址查询道具\n prop.byid 根据PID查询道具\n prop.wallet.byaddress 根据地址查询自己拥有的道具\n prop.wallet.byid 根据PID查询自己拥有的道具\n prop.wallet.byoid 根据OID查询自己拥有的道具\n ")}async allianceCreate(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"sys.alliance.create password nodeid alliancename (host): 创建联盟节点证书 备份密码 节点编号 盟友名称 (节点地址)");e=(t=new g([e])).str(0);var r=t.uint(1,0),s=t.str(2,"").trim();t=t.str(3,"");if(!r||!e)throw new u(c.MISC_ERROR,"节点编号、备份密码都不能为空");if(s==this.wdb.$parent.config.allianceName)throw new u(c.MISC_ERROR,`子网名称不能和当前网络名称[${this.wdb.$parent.config.allianceName}]相同`);if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new u(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");var[i,n]=await this.accessControl(i,""),a={body:{language:(a=await i.createAllianceInfo(s,r)).mnemonic.language,phrase:a.mnemonic.getPhrase(),passphrase:a.mnemonic.passphrase,alliancePrivateKey:a.alliancePrivateKey.toString("hex"),allianceName:s,allianceNodeId:r,awardAddress:a.awardAddress,allianceNodeToken:{network:this.network.type,alliancename:s,sn:r,prv:a.prv.toString("hex"),pub:a.pub.toString("hex"),address:a.address},notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${s}-${r}.keystore`};let o=N.encrypt(a);if(this.wdb.$parent){let i=!1;for(var h of this.wdb.$parent.config.alliances)if((h=h.split("|"))[0]==s&&h[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(a.body.allianceNodeToken.pub,"hex")),o=N.encrypt(a),this.wdb.$parent.config.alliances.push(`${s}|${r}|${o}|${e}|${a.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}e={host:t,an:a.body.allianceNodeToken.alliancename,ai:a.body.allianceNodeToken.sn,key:a.body.allianceNodeToken.pub};var d=p.signObj(e,i.notifyKey.privateKey);return await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:e,sig:d,pub:i.notifyKey.publicKey.toString("hex")})}),l.unsupported||await l.writeFile(a.file,o,"utf8"),e=(await i.getAccount(n)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.create",hash:s+"."+r,index:0}),{nodeid:r,alliancename:s,host:t,peerPubkey:a.body.allianceNodeToken.pub,awardAddress:a.body.awardAddress,file:a.file,notifyAddress:i.notifyAddress}}async allianceImport(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"sys.alliance.import password nodeid alliancename key (host): 导入联盟节点 备份密码 节点编号 盟友名称 节点公钥 (节点地址)");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new u(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");e=(t=new g([e])).str(0);var r=t.uint(1,0),s=t.str(2,""),n=t.str(3,"");t=t.str(4,"");if(!r||!e||!n)throw new u(c.MISC_ERROR,"节点编号、备份密码、节点公钥都不能为空");var[i,a]=await this.accessControl(i,""),o={body:{alliancePrivateKey:(o=await i.createAllianceInfo(s,r,n)).alliancePrivateKey.toString("hex"),allianceName:s,allianceNodeId:r,allianceNodeToken:{network:this.network.type,alliancename:s,sn:r,pub:o.pub.toString("hex"),address:o.address},awardAddress:o.awardAddress,notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${s}-${r}.keystore`};let h;if(this.wdb.$parent){let i=!1;for(var d of this.wdb.$parent.config.alliances)if((d=d.split("|"))[0]==s&&d[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(n,"hex")),h=N.encrypt(o),this.wdb.$parent.config.alliances.push(`${s}|${r}|${h}|${e}|${o.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}else h=N.encrypt(o);return l.unsupported||await l.writeFile(o.file,h,"utf8"),n={host:t,key:o.body.allianceNodeToken.pub,an:o.body.allianceNodeToken.alliancename,ai:o.body.allianceNodeToken.sn},e=p.signObj(n,i.notifyKey.privateKey),await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:e,pub:i.notifyKey.publicKey.toString("hex")})}),n=(await i.getAccount(a)).getReceive().toString(),await this.wdb.logAudit({address:n,oper:"node.create",hash:s+"."+r,index:0}),{nodeid:r,alliancename:s,host:t,peerPubkey:o.body.allianceNodeToken.pub,awardAddress:o.body.awardAddress,file:o.file,notifyAddress:i.notifyAddress}}async refreshAlliance(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.alliance.refresh amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new u(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[s,n]=await this.accessControl(i);if(this.wdb.$parent)for(var a of this.wdb.$parent.config.alliances){a=a.split("|");var o=(x.fromString(a[4],this.network.type).isWitnessPubkeyhash()&&await s.send({outputs:[{address:a[4],value:r}]},n),N.decrypt({network:this.network.type,password:a[3],body:a[2]}));a=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([a[5],o.allianceNodeToken.pub]),{host:a[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(a,s.notifyKey.privateKey);await s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:a,sig:o,pub:s.notifyKey.publicKey.toString("hex")})})}}async refreshAllianceAsync(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.alliance.refresh.async amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new u(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[s,n]=await this.accessControl(i);if(this.wdb.$parent)for(var a of this.wdb.$parent.config.alliances){a=a.split("|");var o=(x.fromString(a[4],this.network.type).isWitnessPubkeyhash()&&s.send({outputs:[{address:a[4],value:r}]},n),N.decrypt({network:this.network.type,password:a[3],body:a[2]}));a=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([a[5],o.allianceNodeToken.pub]),{host:a[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(a,s.notifyKey.privateKey);s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:a,sig:o,pub:s.notifyKey.publicKey.toString("hex")})})}}async allianceDelete(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"sys.alliance.delete nodeid alliancename: 删除联盟节点证书 节点编号 盟友名称");var r=(t=new g([e])).uint(0,0),s=t.str(1,""),[n,e]=await this.accessControl(i,"");if(!r||!s)throw new u(c.MISC_ERROR,"节点编号、节点名称都不能为空");if(this.wdb.$parent)for(let e=0;e<this.wdb.$parent.config.alliances.length;e++){var a,o=this.wdb.$parent.config.alliances[e].split("|");o[0]==s&&o[1]==r&&(this.wdb.$parent.config.alliances.splice(e,1),await this.wdb.$parent.config.saveAsync(),o[5])&&(o={host:o[5],an:s,ai:r},a=p.signObj(o,n.notifyKey.privateKey),await n.commNotify({dst:n.notifyAddress,content:JSON.stringify({cmd:"peerdel",payload:o,sig:a,pub:n.notifyKey.publicKey.toString("hex")})}))}return t=(await n.getAccount(e)).getReceive().toString(),await this.wdb.logAudit({address:t,oper:"node.delete",hash:s+"."+r,index:0}),!0}async getAllianceNodeToken(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.alliance.gettoken (nodeid alliancename pubkey): 创建联盟节点信道密钥 (节点编号 盟友名称)");e=(t=new g([e])).uint(0,0);var r=t.str(1);t=t.str(2);if(this.wdb.$parent)return[i]=await this.accessControl(i),i=await i.createAllianceInfo(r,e,t),r||(this.wdb.$parent.config.identityKey?(i.prv=Buffer.from(this.wdb.$parent.config.identityKey,"hex"),i.pub=k.publicKeyCreate(i.prv,!0),i.address=x.fromWitnessPubkeyhash(w.hash160(i.pub),this.network.type).toString()):(this.wdb.$parent.pool.options.identityKey=i.prv,this.wdb.$parent.config.identityKey=i.prv.toString("hex"),await this.wdb.$parent.saveConfigAsync())),{network:this.network.type,alliancename:r,sn:e,prv:i.prv.toString("hex"),pub:i.pub.toString("hex"),address:i.address};throw new u(c.MISC_ERROR,"this cmd can only run on fullnode.")}async allianceUserCreate(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.alliance.user cid uid (alliancename): 创建企业用户 企业编号 用户编号 (盟友名称)");return this.$allianceUserCreate(e,i)}async $allianceUserCreate(e,t,i){var r=(e=new g([e])).str(0),s=e.uint(1);let n=null,a=null;return a=(e=e.str(2,""))?([t]=await this.accessControl(t),w.hash256(Buffer.concat([Buffer.from(e),t.master.key.privateKey]))):Buffer.from(this.wdb.$parent.config.alliancePrivateKey,"hex"),e=S.fromPrivate(a,!0,this.network),(t=S.fromPrivate(w.hash256(Buffer.concat([Buffer.from(r+"-"+s),e.privateKey]),!0,this.network))).witness=!0,n=t.signData({cid:r,uid:s}),i&&(n.prvkey=t.privateKey.toString("hex")),n}async isReady(e){return this.wdb.isFull()}async shutdown(e,t){return this.wdb.$parent&&this.wdb.$parent.close().catch(e=>{setImmediate(()=>{throw e})}).finally(async()=>{await new Promise(e=>{setTimeout(e,1e4)}),process.exit(0)}),"Stopping."}async stop(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"sys.walletdb.stop");return this.wdb.close(),"Stopping walletdb..."}async destroyWalletDb(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"sys.walletdb.destroy: 删除钱包数据库");return await this.wdb.close(),await this.wdb.destroy(),"Destroyed."}async createWalletDb(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"sys.walletdb.create: 删除原有钱包数据库并重建");return await this.wdb.close(),await this.wdb.destroy(),await this.wdb.open(),"Created."}async fundRawTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'tx.fund.admin "hexstring" ( options openid )');const r=new g([e]);var[t,e]=await this.accessControl(i,r.str(2,"")),s=(i=r.buf(0),r.obj(1));if(!i)throw new u(c.TYPE_ERROR,"Invalid hex string.");if(0===(i=E.fromRaw(i)).outputs.length)throw new u(c.INVALID_PARAMETER,"TX must have at least one output.");let n=null,a=null;if(s){const e=new g([s]);n=e.ufixed("feeRate",8),a=(a=e.str("changeAddress"))&&o.parseAddress(a,this.network)}return await t.fund(i,{rate:n,changeAddress:a,account:e}),{hex:i.toRaw().toString("hex"),changepos:i.changeIndex,fee:y.btc(i.getFee(),!0)}}async dumpPrivKey(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"key.export.private address [account]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0,"");if(!await e.belongToAccount(i,t))throw new u(c.MISC_ERROR,"Invald Account.");if(i=o.parseHash(t,this.network),t=await e.getPrivateKey(i))return t.toSecret();throw new u(c.MISC_ERROR,"Key not found.")}async exportMnemonic(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,"wallet.exportmnemonic.admin password: 备份钱包助记符 备份密码");t=new g([e]);var[e,i]=await this.accessControl(i);if(!(t=t.str(0)))throw new u(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid password");if("primary"==e.id&&"default"!=i)throw new u(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid Account");return i={body:{phrase:e.master.mnemonic.getPhrase(),language:e.master.mnemonic.language,passphrase:e.master.mnemonic.passphrase},password:t,network:this.network,file:`./${this.network.type}-wallet${e.db.options.spv?"-spv":""}.keystore`},this.wdb.$parent&&(i.body.awardAddress=this.wdb.$parent.config.coinbaseAddress),await N.writeEncryptFile(i),N.encrypt(i)}async importMnemonic(e,t,i){if(t||2!==e.length)throw new u(c.MISC_ERROR,"wallet.importmnemonic.admin encrypt password: 导入钱包助记符 备份文本 备份密码");var r;t=new g([e]);let s=N.decrypt({body:t.str(0),password:t.str(1),network:this.network});for(r of("string"==typeof s&&(s=JSON.parse(s)),this.wdb.$parent&&(s.awardAddress=this.wdb.$parent.config.coinbaseAddress),await this.wdb.getWallets()))if((await this.wdb.get(r)).master.mnemonic.getPhrase()===s.phrase)throw new u(c.MISC_ERROR,"wallet.importmnemonic.admin: 相同助记词已被使用");return(e=await this.wdb.ensure({id:M(),type:"pubkeyhash",m:1,n:1,mnemonic:s,passphrase:null,master:null,witness:!0,watchOnly:!1,accountKey:null}))?e.toJSON(!1):null}async dumpWallet(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"wallet.export filename (fragment): 导出钱包备份 备份文件全路径 (分片存储 true/false)");t=new g([e]);var[e,,]=await this.accessControl(i);if(i=t.str(0))return t=t.bool(1,!1),await e.exportToFile({file:i,fragment:t}),!0;throw new u(c.TYPE_ERROR,"Invalid filename.")}async dumpWallets(e,t,i){if(t)throw new u(c.MISC_ERROR,"wallet.exports.admin: 导出所有钱包备份");for(var r of await this.wdb.getWallets())await(await this.wdb.get(r)).exportToFile({file:`backup-${r}.txt`});return!0}async encryptWallet(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'wallet.encrypt "passphrase"');t=new g([e]);var[e,i]=await this.accessControl(i);t=t.str(0,"");if("primary"==e.id&&"default"!=i)throw new u(c.MISC_ERROR,"Invalid Account");if(e.master.encrypted)throw new u(c.WALLET_WRONG_ENC_STATE,"Already running with an encrypted wallet.");if(t.length<1)throw new u(c.MISC_ERROR,'wallet.encrypt "passphrase"');try{await e.setPassphrase(null,t)}catch(e){throw new u(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}return"wallet encrypted"}async getAccount(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'address.account "address"');t=new g([e]);var[e,i]=await this.accessControl(i);return("primary"!=e.id||"default"==i)&&(i=t.str(0,""),t=o.parseHash(i,this.network),i=await e.getPath(t))?i.name:""}async getAddressesByIndex(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,'address.index "index"');t=new g([e]);var[e,i]=await this.accessControl(i);if("primary"!=e.id||"default"==i){var r=t.uint(0);for(const t of await e.getPaths("default")){var s=t.toAddress();if(0==t.branch&&t.index==r)return s.toString(this.network)}}}async accessControl(e,t){let i=await this.wdb.get("primary");if(this.wdb.options.acl.isRoot(e.options.cid))"primary"!==e.options.wid?(i=await this.wdb.get(e.options.wid),t=null):"*"===(t=t||"default")&&(t=null);else if("primary"!==e.options.wid){if(!await i.belongToAccount(e.options.cid,e.options.wid))throw new u(c.TYPE_ERROR,"Invalid wid.");i=await this.wdb.get(e.options.wid),t=null}else t=e.options.cid;return await i.ensureAccount({name:t,witness:!0}),[i,t]}async getAddressesByAccount(e,t,i){if(t)throw new u(c.MISC_ERROR,'address.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[],s=[],n=[];for(const t of await e.getPaths(i)){var a=t.toAddress();(0==t.branch?r:1==t.branch?s:n).push(a.toString(this.network))}return[r,s,n]}async getAccountAddress(e,t,i){if(t)throw new u(c.MISC_ERROR,'address.receive "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.receive.getAddress("string")}async getAccountChangeAddress(e,t,i){if(t)throw new u(c.MISC_ERROR,"address.change account");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.change.getAddress("string")}async getAccountNestedAddress(e,t,i){if(t)throw new u(c.MISC_ERROR,'address.nested.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.nested.getAddress("string")}async getBalance(e,t,i){if(t||3<e.length)throw new u(c.MISC_ERROR,'balance.confirmed ( "account" minconf includeWatchonly )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return 0;let s;return t=await e.getBalance(i),s=0<r?t.confirmed:t.unconfirmed,y.btc(s,!0)}async getBalanceLog(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,'balance.log "account" (height)');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0));t=t.uint(1,0);return e.queryBalanceLog(i,t)}async getBalanceAll(e,t,i){if(t||3<e.length)throw new u(c.MISC_ERROR,'balance.all ( "account" minconf includeWatchonly )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0));return(await e.getBalance(i)).toJSON()}async checkBalance(e,t,i){if(t)throw new u(c.MISC_ERROR,"balance.check");t=new g([e]);var[e,,]=await this.accessControl(i,t.str(0));return(await e.resetBalance()).toJSON()}async getUserToken(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"cp.user cid uid: 生成登录令牌 厂商编码 用户编码");e=(t=new g([e])).str(0),t=t.str(1);var[i]=await this.accessControl(i);return i.tokenCreate({cid:e,uid:t},t)}async masterkey(e,t,i){var[i,r]=await this.accessControl(i);if("primary"==i.id||"default"==r)return i.master.toJSON(!0)}async getHistory(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,"tx.history (page acct):查询交易历史记录 (页码 账号)");var r=(t=new g([e])).uint(0,1);if(r<1)throw new u(c.MISC_ERROR,"页面必须是大于0的数字");var[e,i]=await this.accessControl(i,t.str(1));t=await e.getHistory(i);s.sortTX(t);let n=0;var a,o=[];for(a of t){if(n<10*(r-1));else{if(n>=10*r)break;o.push(a)}n++}return i=await e.toDetails(o),(e={}).items=i,e.pageSize=10,e.pageNum=r,e.total=t.length,e}async sendSecret(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"comm.secret dst message (openid): 安全通信消息 收信地址 信息内容 (玩家账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0,"");t=t.str(1,"");if(o.parseAddress(r,this.network))return e.sendSecret(r,t,i);throw new u(c.TYPE_ERROR,"Invalid Destination Address.")}async calcHash(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"comm.hash content: 计算输入的哈希值");return t=new g([e]).str(0,""),w.hash256(Buffer.from(t)).toString("hex")}async commNotify(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"comm.notify addr content (openid): 发送点对点消息 地址 内容 (玩家账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0,"");t=t.obj(1,{});return e.commNotify({dst:r,content:t,account:i})}async scanContact(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'comm.scanContact "txid" ( index )');t=new g([e]);var[e,,]=await this.accessControl(i);i=t.hash(0),r(i,"Hash is required."),t=t.uint(1,-1);if(!i)throw new u(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(i))return this.wdb.scanContact(e.tx,t);throw new u(c.WALLET_ERROR,"TX not found.")}async listContact(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.listContact: 列表联系人");return t=new g([e]).array(0,[]),this.wdb.listContact(t,null,["address"])}async listNotify(e,t,i){if(t)throw new u(c.MISC_ERROR,"comm.listNotify (query): 通知列表 (查询条件,使用 account 参数可分账号查询)");return t=new g([e]).array(0,[]),this.wdb.listNotify(t)}async getReceivedByAccount(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'account.received "account" ( minconf )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.u32(1,0),s=this.wdb.curHeight,n=(t=await e.getPaths(i),new Set);for(const e of t)n.add(e.hash);let a=0,o=-1;for(const t of await e.getHistory(i)){var h=t.getDepth(s);if(!(h<r)){(-1===o||h<o)&&(o=h);for(const e of t.tx.outputs){var l=e.getHash("hex");l&&n.has(l)&&(a+=e.value)}}}return y.btc(a,!0)}async getReceivedByAddress(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'address.received "address" ( minconf )');t=new g([e]);var[e,,]=await this.accessControl(i),r=(i=t.str(0,""),t.u32(1,0)),s=this.wdb.curHeight,n=o.parseHash(i,this.network);let a=0;for(const t of await e.getHistory())if(!(t.getDepth(s)<r))for(const e of t.tx.outputs)e.getHash("hex")===n&&(a+=e.value);return y.btc(a,!0)}async _toWalletTX(e,t){var[e,,]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new u(c.WALLET_ERROR,"TX not found.");let r=!0;for(const e of i.inputs)if(e.path){r=!1;break}var s=[];let n=0,a=0;for(let e=0;e<i.outputs.length;e++){var o=i.outputs[e];o.path?1!==o.path.branch&&(s.push({account:o.path.name,address:o.address.toString(this.network),category:"receive",amount:y.btc(o.value,!0),label:o.path.name,vout:e}),a+=o.value):r||(s.push({account:"",address:o.address?o.address.toString(this.network):null,category:"send",amount:-y.btc(o.value,!0),fee:-y.btc(i.getFee(),!0),vout:e}),n+=o.value)}return{amount:y.btc(r?a:-n,!0),confirmations:i.confirmations,blockhash:i.block?d.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:d.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no",details:s,hex:i.tx.toRaw().toString("hex")}}async getTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'tx.get.wallet "txid" ( includeWatchonly )');t=new g([e]);var[e,,]=await this.accessControl(i),s=t.hash(0);r(s,"Hash is required."),t=t.bool(1,!1);if(!s)throw new u(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(s))return this._toWalletTX(i,e,t);throw new u(c.WALLET_ERROR,"TX not found.")}async abandonPending(e,t,i){if(t)throw new u(c.MISC_ERROR,"tx.abandonall.admin [account]: 废弃所有挂起的交易");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(0,""));for(const t of await r.getPending(e))try{await r.abandon(t.hash)}catch(e){this.logger.warning(e.message)}return null}async abandonTransaction(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'tx.abandon.admin "txid"');t=new g([e]);var[e,,]=await this.accessControl(i);if(!(i=t.hash(0)))throw new u(c.TYPE_ERROR,"Invalid parameter.");if(await e.abandon(i))return null;throw new u(c.WALLET_ERROR,"Transaction not in wallet.")}async getUnconfirmedBalance(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,"balance.unconfirmed");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=await e.getBalance(i);return y.btc(t.unconfirmed,!0)}async importPrivKey(e,t,i){if(t||e.length<1||4<e.length)throw new u(c.MISC_ERROR,'key.import.private account "privatekey" passphrase [rescan]');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.str(1),s=t.str(2);t=t.bool(3,!1);return(r=o.parseSecret(r,this.network)).witness=!0,await e.importKey(i,r,s),t&&await this.wdb.rescan(0),!0}async walletAuth(e,t,i){return!0}async importWallet(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,'wallet.import "filename" ( rescan )');t=new g([e]);var[,]=await this.accessControl(i);e=t.str(0),i=t.bool(1,!1);return await this.wdb.loadBackup(e),i&&await this.wdb.rescan(0),!0}async importAddress(e,t,i){if(t||e.length<1||4<e.length)throw new u(c.MISC_ERROR,"address.import account address [rescan p2sh]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));let r=t.str(1,"");var s=t.bool(2,!1);if(t.bool(3,!1)){let e=t.buf(0);if(!e)throw new u(c.TYPE_ERROR,"Invalid parameters.");e=v.fromRaw(e),e=v.createScript(e.hash160(),v.types.SCRIPTHASH),r=x.fromScript(e)}else r=o.parseAddress(r,this.network);return await e.importAddress(i,r),s&&await this.wdb.rescan(0),!0}async importPubkey(e,t,i){if(t||e.length<1||4<e.length)throw new u(c.MISC_ERROR,"key.import.public account pubkey [rescan]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.buf(1);t=t.bool(2,!1);if(r)return r=S.fromPublic(r,this.network),await e.importKey(i,r),t&&await this.wdb.rescan(0),!0;throw new u(c.TYPE_ERROR,"Invalid parameter.")}async listAccounts(e,t,i){if(t||2<e.length)throw new u(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[r]=await this.accessControl(i),s=t.u32(0,0),n=t.bool(1,!1),a={};for(const e of await r.getAccounts()){var o=await r.getBalance(e);let t=o.unconfirmed;0<s&&(t=o.confirmed),r.watchOnly!==n&&(t=0),a[e]=y.btc(t,!0)}return a}async listConservedUnspent(e,t,i){if(t||0<e.length)throw new u(c.MISC_ERROR,"coin.conserved.list: 查询已经保持的Unspent列表");var[t]=await this.accessControl(i),r=[];for(const e of t.getConserved())r.push({txid:e.txid(),vout:e.index});return r}async accountVirtualAdd(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"account.virtualadd.admin account amount: 虚增账户余额 账户名称 金额");t=new g([e]);var[e]=await this.accessControl(i,t.str(2,""));i=t.str(0),t=t.u64(1),i=await e.ensureIndex(i);return e.txdb.addAccountAmount(i,t),!0}async accountCheckAmount(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"account.checkamount account: 验证账户余额 账户名称");t=new g([e]);var[e]=await this.accessControl(i,t.str(2,""));i=t.str(0),t=await e.ensureIndex(i);return e.txdb.checkAccountAmount(t),!0}async listReceivedByAccount(e,t,i){if(t||3<e.length)throw new u(c.MISC_ERROR,"account.listreceived ( minconf includeempty includeWatchonly )");e=(t=new g([e])).u32(0,0);var r=t.bool(1,!1);t=t.bool(2,!1);return this._listReceived(i,e,r,t,!0)}async listReceivedByAddress(e,t,i){if(t||3<e.length)throw new u(c.MISC_ERROR,"address.received.list ( minconf includeempty includeWatchonly )");e=(t=new g([e])).u32(0,0);var r=t.bool(1,!1);t=t.bool(2,!1);return this._listReceived(i,e,r,t,!1)}async _listReceived(e,t,i,r,s){var[n]=await this.accessControl(e),a=(e=await n.getPaths(),this.wdb.curHeight);const o=new Map;for(const t of e){var c=t.toAddress();o.set(t.hash,{involvesWatchonly:n.watchOnly,address:c.toString(this.network),account:t.name,amount:0,confirmations:-1,label:""})}for(const e of await n.getHistory()){var h=e.getDepth(a);if(!(h<t))for(const t of e.tx.outputs){var u,l=t.getAddress();l&&(u=l.getHash("hex"),u=o.get(u))&&((-1===u.confirmations||h<u.confirmations)&&(u.confirmations=h),u.address=l.toString(this.network),u.amount+=t.value)}}let p=[];for(const e of o.values())p.push(e);if(s){const e=new Map;for(const t of p){var d=e.get(t.account);d?d.amount+=t.amount:(e.set(t.account,t),t.address=void 0)}p=[];for(const t of e.values())p.push(t)}var f=[];for(const t of p)if(i||0!==t.amount){-1===t.confirmations&&(t.confirmations=0);try{t.amount=y.btc(t.amount,!0),f.push(t)}catch(e){this.logger.error("invalid amount:entry(%s) msg(%s)",JSON.stringify(t),e.message)}}return f}async listSinceBlock(e,t,i){if(t)throw new u(c.MISC_ERROR,'tx.history.since ( "blockhash" target-confirmations includeWatchonly account)');var r=this.wdb.curHeight,[e,s]=(t=new g([e]),await this.accessControl(i,t.str(3,""))),n=t.hash(0),a=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return[];let o=-1;-1===(o=n&&(t=await this.client.getEntry(n))?t.height:o)&&(o=r);var h,l=[];let p;for(const t of await e.getHistory(s))t.height<o||t.getDepth(r)<a||((!p||t.height>p)&&(p=t),h=await this._toListTX(i,t),l.push(h));return{transactions:l,lastblock:p&&p.block?d.revHex(p.block):m.NULL_HASH}}async _toListTX(e,t){var[e]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new u(c.WALLET_ERROR,"TX not found.");let s=!0;for(const e of i.inputs)if(e.path){s=!1;break}let n,a,o,h,l,p,f=0,m=0;for(let e=0;e<i.outputs.length;e++){const t=i.outputs[e];t.path?1!==t.path.branch&&(m+=t.value,a=t,h=e):(f+=t.value,n=t,o=e)}return p=s?(l=a,h):(l=n,o),l||(r(!s),s=!0,l=a,p=h),{account:l.path?l.path.name:"",address:l.address?l.address.toString(this.network):null,category:s?"receive":"send",amount:y.btc(s?m:-f,!0),label:l.path?l.path.name:void 0,vout:p,confirmations:i.getDepth(),blockhash:i.block?d.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:d.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no"}}async listTransactions(e,t,i){if(t||4<e.length)throw new u(c.MISC_ERROR,'tx.list ( "account" count from includeWatchonly)');t=new g([e]);var[e,r]=await this.accessControl(i,t.str(0,"")),n=t.u32(1,10),a=t.u32(2,0);t=t.bool(3,!1);if(e.watchOnly!==t)return[];var o=await e.getHistory(r),h=(t=(s.sortTX(o),a+n),Math.min(t,o.length)),l=[];for(let e=a;e<h;e++){var p=o[e];p=await this._toListTX(i,p);l.push(p)}return l}async selectone(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"coin.selectone options (account)");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),s=t.obj(0,{}),n=[];for(const t of await r.getCoins(e)){var a=t.getDepth(this.wdb.curHeight),o=t.getAddress();if(o){var h=t.getHash("hex");if(h&&!t.isColored&&!(s.value&&t.value<s.value||t.coinbase&&0<t.height&&this.wdb.curHeight<t.height+b.COINBASE_MATURITY)&&(h=await r.getKey(h),n.push({txid:t.txid(),vout:t.index,address:o?o.toString(this.network):null,account:h?h.name:void 0,redeemScript:h&&h.script?h.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:y.btc(t.value,!0),confirmations:a,spendable:!r.isConserved(t),solvable:!0}),s.len&&n.length>=s.len))break}}return n}async listUnspent(e,t,i){if(t||4<e.length)throw new u(c.MISC_ERROR,'coin.list ( minconf maxconf ["address", account] )');const r=new g([e]);var[n,t]=await this.accessControl(i,r.str(3,"")),a=r.u32(0,1),h=r.u32(1,9999999),l=r.array(2),p=this.wdb.curHeight,d=new Set;if(l&&0<l.length){const e=new g([l]);for(let t=0;t<l.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(d.has(f))throw new u(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await n.getCoins(t);var m,v,b,w=(s.sortCoins(e),[]);for(const t of e)t.isColored||(m=t.getDepth(p))<a||h<m||((v=t.getAddress())?(b=t.getHash("hex"),l&&0<l.length&&(!b||!d.has(b))||(b=await n.getKey(b),w.push({txid:t.txid(),vout:t.index,address:v?v.toString(this.network):null,account:b?b.name:void 0,redeemScript:b&&b.script?b.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:y.btc(t.value,!0),confirmations:m,spendable:!n.isConserved(t),solvable:!0}))):this.logger.error("mistaken coin: miss address",t.hash,t.index));return w}async checkUnspent(e,t,i){if(t)throw new u(c.MISC_ERROR,"coin.check (account)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[];if(this.wdb.$parent)for(const t of await e.getCoins(i))await this.wdb.$parent.getCoin(t.hash,t.index)||r.push(t.txid(),t.index);return r}async listProp(e,t,i){if(t||4<e.length)throw new u(c.MISC_ERROR,"prop.wallet.byaddress ( minconf maxconf [address, account] )");const r=new g([e]);var[n,t]=await this.accessControl(i,r.str(3,"")),a=r.u32(0,1),h=r.u32(1,9999999),l=r.array(2),p=this.wdb.curHeight,d=new Set;if(l){const e=new g([l]);for(let t=0;t<l.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(d.has(f))throw new u(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await n.getCoins(t);var m=(s.sortCoins(e),[]);for(const t of e){var v,b,w,k=t.getDepth(p);k<a||h<k||(v=t.getAddress())&&(b=t.getHash("hex"),!l||b&&d.has(b))&&(b=await n.getKey(b),w=t.getReturnData([L.OP_PROPCREATE,L.OP_PROPCREATE]))&&m.push({txid:t.txid(),vout:t.index,address:v?v.toString(this.network):null,account:b?b.name:void 0,amount:y.btc(t.value,!0),confirmations:k,spendable:!n.isConserved(t),solvable:!0,nd:w})}return m}async listPropByOid(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.wallet.byoid oid");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),n=t.str(0),a=this.wdb.curHeight,o=(i=await r.getCoins(e),s.sortCoins(i),[]);for(const e of i){var h,l,p,d=e.getDepth(a);d<0||9999999<d||(h=e.getAddress())&&(l=e.getHash("hex"),l=await r.getKey(l),p=e.getReturnData([L.OP_PROPCREATE,L.OP_PROPEXCHANGE]))&&p.oid==n&&o.push({txid:e.txid(),vout:e.index,address:h?h.toString(this.network):null,account:l?l.name:void 0,amount:y.btc(e.value,!0),confirmations:d,spendable:!r.isConserved(e),solvable:!0,nd:p})}return{list:o,count:o.length}}async listLockedUnspent(e,t,i){if(t||2<e.length)throw new u(c.MISC_ERROR,'coin.list.locked ["address", account]');const r=new g([e]);var[n,t]=await this.accessControl(i,r.str(1,"")),a=r.array(0),h=this.wdb.curHeight,l=d.now(),p=new Set;if(a){const e=new g([a]);for(let t=0;t<a.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(p.has(f))throw new u(c.INVALID_PARAMETER,"Duplicate address.");p.add(f)}}let m;m=account?await n.getCoins(t):n.getLockedCoins(),s.sortCoins(m);var v,b,w,k,x,S,_=[];for(const e of m)(e.lockedByLocktime(h,l)||e.lockedBySequence(h,l))&&(v=e.getAddress())&&(b=e.getDepth(h),S=e.getHash("hex"),!a||S&&p.has(S))&&([w,k,x]=e.getLockStatus(),S=await n.getKey(S),_.push({txid:e.txid(),vout:e.index,address:v?v.toString(this.network):null,account:S?S.name:void 0,redeemScript:S&&S.script?S.script.toJSON():void 0,scriptPubKey:e.script.toJSON(),amount:y.btc(e.value,!0),confirmations:b,spendable:!1,solvable:!0,locktype:w,lockheight:k,locktime:x}));return _}async listOperUnspent(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'coin.conserved.oper.list unlock ([{"txid":"txid","vout":n},...]) 保持/解除保持一组UTXO: true/false [{"txid": "交易id","vout": "输出序号"}]');const r=new g([e]);var[s]=await this.accessControl(i),n=r.bool(0,!1);if(!(t=r.array(1)))throw new u(c.TYPE_ERROR,"Invalid parameter.");for(const e of t){const t=new g([e]);var a=t.hash("txid"),o=t.u32("vout");if(null==a||null==o)throw new u(c.INVALID_PARAMETER,"Invalid parameter.");a=new R(a,o),n?s.unConserveCoin(a):s.conserveCoin(a)}return!0}async setTXFee(e,t,i){if(t||e.length<1||1<e.length)throw new u(c.MISC_ERROR,"sys.setfee rate");if(null==(t=new g([e]).ufixed(0,8)))throw new u(c.TYPE_ERROR,"Invalid parameter.");return this.wdb.feeRate=t,!0}async signMessage(e,t,i){if(t||2!==e.length)throw new u(c.MISC_ERROR,'sys.message.sign "address" "message"');t=new g([e]);var[e]=await this.accessControl(i);if(!e.master.key)throw new u(c.WALLET_UNLOCK_NEEDED,"Wallet is locked.");i=t.str(0,""),i=o.parseHash(i,this.network);if(e=await e.getKey(i))return i=t.str(1,""),e.sign(w.hash256(Buffer.from(h+i,"utf8"))).toString("base64");throw new u(c.WALLET_ERROR,"Address not found.")}async changePassphrase(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,'wallet.changepassphrase "oldpassphrase" "newpassphrase"');t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0,""),t=t.str(1,"");if(!e.master.encrypted)throw new u(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(i.length<1||t.length<1)throw new u(c.INVALID_PARAMETER,"Invalid parameter");return await e.setPassphrase(i,t),null}async unlock(e,t,i){var r=new g([e]),[i]=await this.accessControl(i),s=r.str(0);r=r.u32(1,60);if(t||i.master.encrypted&&0==e.length)throw new u(c.MISC_ERROR,'wallet.unlock "passphrase" timeout');if(!i.master.encrypted)throw new u(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(s.length<1)throw new u(c.INVALID_PARAMETER,"Invalid parameter");if(null==r)throw new u(c.TYPE_ERROR,"Invalid parameter");return await i.unlock(s,r),null}async decryptWallet(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'wallet.decrypt "passphrase"');t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0,"");if(!e.master.encrypted)throw new u(c.WALLET_WRONG_ENC_STATE,"Running with an decrypted wallet.");if(i.length<1)throw new u(c.MISC_ERROR,'wallet.decrypt "passphrase"');try{await e.setPassphrase(i)}catch(e){throw new u(c.WALLET_ENCRYPTION_FAILED,"Decryption failed.")}return"wallet decrypted"}async importPrunedFunds(e,t,i){if(t||e.length<2||3<e.length)throw new u(c.MISC_ERROR,'tx.importprunedfunds.admin "rawtransaction" "txoutproof" ( "label" )');if(e=(t=new g([e])).buf(0),t=t.buf(1),!e||!t)throw new u(c.TYPE_ERROR,"Invalid parameter.");e=A.fromRaw(e);var r=(t=_.fromRaw(t)).hash("hex");if(!t.verify())throw new u(c.VERIFY_ERROR,"Invalid proof.");if(!t.hasTX(e.hash("hex")))throw new u(c.VERIFY_ERROR,"Invalid proof.");var s=await this.client.getEntry(r);if(-1===s)throw new u(c.VERIFY_ERROR,"Invalid proof.");if(r={hash:r,time:t.time,mtp:t.mtp,height:s},await this.wdb.addTX(e,r))return null;throw new u(c.WALLET_ERROR,"No tracked address for TX.")}async removePrunedFunds(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'tx.removeprunedfunds.admin "txid"');t=new g([e]);var[e]=await this.accessControl(i);if(!(i=t.hash(0)))throw new u(c.TYPE_ERROR,"Invalid parameter.");if(await e.remove(i))return null;throw new u(c.WALLET_ERROR,"Transaction not in wallet.")}async getWallets(e,t,i){return this.wdb.getWallets()}async getWalletBlock(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"wallet.block height");t=new g([e]);var[e]=await this.accessControl(i);i=t.uint(0);return(t=await e.getBlock(i))?t.toJSON():null}async getWalletLayoutH(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"wallet.layouth height");return t=new g([e]).uint(0),(e=await this.wdb.getBlock(t))?e.toJSON():null}async getWalletInfo(e,t,i){if(t)throw new u(c.MISC_ERROR,"wallet.info");return((t=new g([e]).str(0,""))?await this.wdb.get(t):(await this.accessControl(i))[0]).toJSON(!1)}async scRegister(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"sc.register options (account): 发布合约 合约参数列表 (子账户)");t=new g([e]);var[r,s]=await this.accessControl(i,t.str(1,""));let n=t.obj(0);if(!n)throw new u(c.MISC_ERROR,"sc.register: options is null");let a=1e5;switch(n.oper){case"change":if(n.oper=I.scState,!n.dst||!n.state)throw new u(c.TYPE_ERROR,"sc.register: dst or state is null.");if(!this.wdb.$parent)throw new u(c.TYPE_ERROR,"sc.register: not support this operation.");var o=await this.wdb.$parent.chain.db.getSCList([["options.dst",n.dst]]);if(!o||0==o.list.length)throw new u(c.TYPE_ERROR,"sc.register: contract not exist.");switch(o.list[0].options.state){case j.Normal:if(n.state!=j.Frozen&&n.state!=j.Destroy)throw new u(c.TYPE_ERROR,"Contract State Error");break;case j.Frozen:if(n.state!=j.Normal&&n.state!=j.Destroy)throw new u(c.TYPE_ERROR,"Contract State Error");break;default:throw new u(c.TYPE_ERROR,"Contract State Error")}if(n.addr=o.list[0].options.addr,await r.belongToAccount(s,n.addr))break;throw new u(c.MISC_ERROR,"sc.register: Invald Account.");case"update":if(n.oper=I.scUpdate,!n.dst)throw new u(c.TYPE_ERROR,"sc.register: dst is null.");if(!this.wdb.$parent)throw new u(c.TYPE_ERROR,"sc.register: not support this operation.");if(!(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",n.dst]]))||0==o.list.length)throw new u(c.TYPE_ERROR,"sc.register: contract not exist.");if(o.list[0].options.state!=j.Normal)throw new u(c.TYPE_ERROR,"sc.register: contract state error.");if(n.addr=o.list[0].options.addr,await r.belongToAccount(s,n.addr))break;throw new u(c.MISC_ERROR,"sc.register: Invald Account.");default:if(a=1e8,n.oper=I.scRegister,n.addr=(await r.createReceive(s)).getAddress("string"),n.dst=r.getSCAddress(d.hashInt(n.addr)).toString(),this.wdb.$parent&&(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",n.dst]]))&&0<o.list.length)throw new u(c.TYPE_ERROR,"sc.register: contract address conflict.")}return(e=(await r.getPrivateKey(n.addr)).signData(n)).data.sig=e.sig,n=e.data,i=await r.send({subtractFee:!1,sort:!1,outputs:[{address:n.dst,value:a}],comment:JSON.stringify(n)},s),await this.wdb.logAudit({address:n.addr,oper:n.oper,hash:i.hash("hex"),index:0}),n.txid=i.rhash(),n}async scRun(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,'sc.run str options (account): 调用合约 逗分参数字符串("合约收款地址,转账金额") 参数对象 (子账户)');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0).split(","),s=(t=t.obj(1,{}),r.shift());if(!this.wdb.$parent)throw new u(c.TYPE_ERROR,"sc.run: not support this operation.");var n=await this.wdb.$parent.chain.db.getSCList([["options.dst",s]]);if(!n||0==n.list.length)throw new u(c.TYPE_ERROR,"sc.run: contract not exist.");if(1!=n.list[0].options.state)throw new u(c.TYPE_ERROR,`sc.run: contract execute disabled(state ${n.list[0].options.state}).`);if(t.ver&&t.ver!=n.list[0].options.ver)throw new u(c.TYPE_ERROR,"sc.run: contract version inconsistency.");return n=(0|parseInt(r.shift()))>>>0,o.parseAddress(s,this.network),r=await e.send({subtractFee:!1,sort:!1,outputs:[{address:s,value:n}],comment:JSON.stringify({oper:"scrun",params:t})},i),s=await e.getAccount(i),await this.wdb.logAudit({address:s.receive.getAddress("string"),oper:I.scRun,hash:r.hash("hex"),index:0}),(await e.getDetails(r.hash("hex"))).toJSON()}async cpRegister(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,'cp.create name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(e,i,!1)}async cpRegisterAsync(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,'cp.create.async name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(e,i,!0)}async $cpRegister(e,t,i){e=new g([e]);var r=decodeURIComponent(e.str(0)),s=(o=e.str(1,"").split(","))[0],n=o[1],a=o[2],o=o[3]?parseInt(o[3]):15,[t,e]=await this.accessControl(t,e.str(2,"")),h=f.verifyDataFormat({name:r,ip:s,grate:o,cls:a});if(h)throw new u(c.MISC_ERROR,h);return h={cid:M(),oper:I.cpRegister,name:r,ip:s,grate:o,cls:a},await t.cpRegister(d.isBech32(n)?n:null,h,e,i),h}async cpChange(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,'cp.change cid "newname,ip,addr,class,rate" "openid": 修改厂商信息 CP编号 "新的名称,IP,新的注册地址,类别,分成比例" 授权账号');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),s=t.str(0),n=(t=decodeURIComponent(t.str(1,"")).split(","))[0],a=t[1];let o=t[2];var h=t[3];t=parseInt(t[4])||null;if(l=f.verifyDataFormat({name:n,ip:a,grate:t,cls:h}))throw new u(c.MISC_ERROR,l);o&&(o=x.fromString(o),r(o instanceof x,"Not an address."));var l={cid:s,newName:n,ip:a,addr:o,grate:t,cls:h},[,,]=await e.cpChange(l,i);return l.addr=l.addr.toString(),l}async cpQuery(e,t,i){if(t)throw new u(c.MISC_ERROR,"cp.query (conditions account): 查询钱包中的厂商列表 (复合条件 子帐号)");t=new g([e]);var r,[s,n]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=s.db.cpList.query(e);for(r of i.list)r.owned=await s.belongToAccount(n,r.current.address);return i}async cpQueryRemote(e,t,i){if(t)throw new u(c.MISC_ERROR,"cp.query.remote conditions: 查询厂商列表 (复合条件)");t=new g([e]);var r,[s,n]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=await s.db.client.execute("cp.remoteQuery",[e]);for(r of i.list)r.owned=await s.belongToAccount(n,r.current.address);return i}async cpMine(e,t,i){if(t)throw new u(c.MISC_ERROR,"cp.mine (conditions account): 查询钱包中归属当前操作员/指定账户的厂商列表 (复合条件 子帐号)");t=new g([e]);let[r,s]=await this.accessControl(i,t.str(1,""));return(e=t.array(0,[])).push(["size",-1]),(await r.db.cpList.predict(async(e,t)=>r.belongToAccount(s,t.current.address))).query(e)}async htlcSuggest(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.suggest params [account]: 发起HTLC 参数对象({alice, bob, amount, rate}) [子账户]");e=(t=new g([e])).obj(0,{});var r,[i,t]=await this.accessControl(i,t.str(1,""));if(!e.ab)throw new u(c.MISC_ERROR,"htlc.suggest: params.ab(alice bchain address) is null");if(!Number.isInteger(e.amount))throw new u(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.amount=parseInt(e.amount),e.amount<0||e.amount>1e4*b.COIN)throw new u(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.rate=parseFloat(e.rate),e.rate<0||e.amount*e.rate>b.MAX_MONEY)throw new u(c.MISC_ERROR,"htlc.suggest: illegal params.rate");if(e.target)return r=(await i.createReceive(t)).getAddress().toString(this.network),e={amount:e.amount,rate:e.rate,dst:e.target,aa:x.fromString(r).hash,ab:x.fromString(e.ab).hash,ba:x.fromString(e.ba).hash},[i]=await i.sendContracts([e],t,O),i?{txid:i.rhash(),aa:r}:null;throw new u(c.MISC_ERROR,"htlc.suggest: params.target is null")}async htlcAssent(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.assent params({txid}) [account]: 响应HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.obj(0,{});if(!Number.isInteger(t.amount))throw new u(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new u(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.rate=parseFloat(t.rate),t.rate<0||t.amount*t.rate>b.MAX_MONEY)throw new u(c.MISC_ERROR,"htlc.assent: illegal params.rate");var r=(await e.createReceive(i)).getAddress().toString(this.network),[t]=(r={src:t.src,dst:t.dst,hash:t.hash,index:t.index,ab:Buffer.from(t.ab,"hex"),ba:Buffer.from(t.ba,"hex"),bb:x.fromString(r).hash,amount:t.amount*t.rate},await e.sendContracts([r],i,C));return t?{txid:t.rhash()}:null}async htlcSuggestDeal(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.suggest.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={suggest:!0,hash:d.revHex(t.txid),index:t.index,sa:t.sa},await e.htlcDeal(t,i));return e?{txid:e.rhash()}:null}async htlcQuery(e,t,i){if(t)throw new u(c.MISC_ERROR,"htlc.query query: 条件查询HTLC合约 条件数组");return(t=new g([e]).array(0,[])).push(["pst","!=",T.Cancel]),this.wdb.htlcList.query(t)}async htlcAssentDeal(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.assent.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={hash:d.revHex(t.txid),index:t.index,sa:t.sa},await e.htlcDeal(t,i));return e?{txid:e.rhash()}:null}async htlcAssentCancel(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.assent.cancel params({txid, index, master}) [account]: 取消HTLC应答 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={hash:d.revHex(t.txid),index:t.index,master:t.bb},await e.htlcCancel(t,i));return e?{txid:e.rhash()}:null}async htlcSuggestCancel(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.suggest.cancel params({txid, index, sa, master}) [account]: 取消HTLC请求 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={suggest:!0,hash:d.revHex(t.txid),index:t.index,sa:t.sa,master:t.aa},await e.htlcCancel(t,i));return e?{txid:e.rhash()}:null}async sendComment(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"comm.comment params [account]: 发起附言交易 参数对象({body, bob}) [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.obj(0,{});if(!Number.isInteger(t.amount))throw new u(c.MISC_ERROR,"comm.comment: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new u(c.MISC_ERROR,"comm.comment: illegal params.amount");var r={bob:t.bob,body:t.body,amount:t.amount};t.alice||(t.alice=e.getAddress(),i&&(s=await e.createReceive(i),t.alice=s.getAddress()));var s=(await e.getPrivateKey(t.alice)).signData(r),[t]=(s.data.sig=s.sig,await e.sendContracts([s.data],i,B));return t?{txid:t.rhash()}:null}async commentQuery(e,t,i){if(t)throw new u(c.MISC_ERROR,"comm.comment.query query: 条件查询附言输出 条件数组");return t=new g([e]).array(0,[]),this.wdb.commentList.query(t)}async contractExecute(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"contract.execute tid master: 执行交易对合约 交易编号 执行方(1-发起人,2-承兑人)");t=new g([e]);var[e]=await this.accessControl(i),[e,,]=(i=t.str(0),t=t.u32(1,2),await e.contractExecute(i,t));return e.toJSON()}async contractPromise(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"contract.promise tid [openid]: 签署交易对合约 交易编号(type.address) [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.str(0),await e.contractPromise(t,i));return e.toJSON()}async contractOfMine(e,t,i){if(t||e.length<1||3<e.length)throw new u(c.MISC_ERROR,"contract.mine type page [openid]: 获取已签署交易对合约列表 交易对类型 页码 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.uint(0,1);t=t.uint(1,1);return e.db.getContracts(r,t,i)}async contractCreate(e,t,i){if(t||e.length<4||5<e.length)throw new u(c.MISC_ERROR,"contract.create type src dst addr [openid] : 发布一个交易对合约 交易对类型 出让游戏金数值 换取兑换币数值 兑换币收款地址 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(4,"")),r=t.u64(0),s=t.u64(1),n=t.u64(2),[e,,]=(t=t.str(3),await e.contractCreate(r,s,n,t,i));return e.toJSON()}async propGet(e,t,i){if(t)throw new u(c.MISC_ERROR,"prop.wallet.byid pid: 查询自己的物品 PID");return t=new g([e]).str(0,""),e=[],(t=await this.wdb.propList.getVp(t))&&t.pst!=P.Delete&&e.push(t),e}async propQuery(e,t,i){if(t)throw new u(c.MISC_ERROR,"prop.query query: 条件查询自己的物品 条件数组");t=new g([e]);var[e]=await this.accessControl(i,t.str(1,""));return(i=t.array(0,[])).push(["pst","!=",P.Delete]),(await e.getPropList()).query(i)}async mySaleList(e,t,i){if(t)throw new u(c.MISC_ERROR,"prop.query.auction (page acct): 查询自己拍卖的物品 (页码 账户)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.uint(0,1);return e.mySaleList(t,i)}async onSaleList(e,t,i){e=new g([e]);var[i,r]=await this.accessControl(i,e.str(1,""));e=e.uint(0,1);return i.onSaleList(e,r)}async propBuy(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"prop.buy pid price [openid] : 竞拍道具 道具编号 出价 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0),[e,,]=(t=t.u64(1),await e.propBuy(r,t,i));return e.toJSON()}async propFound(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.found pid (openid): 熔铸道具 道具编号 (账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new u(c.MISC_ERROR,"prop.found prop not exist");if(!await e.belongToAccount(i,t.current.address))throw new u(c.MISC_ERROR,"prop.found: current account not owned prop.");if(t.pst!=P.Ready)throw new u(c.MISC_ERROR,"prop.found prop can not be found on current status");var[e,,t]=await e.propFound(t.current.hash,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),index:0,cid:t.cid,pid:t.pid,oid:t.oid,gold:e.outputs[0].value}}async propSale(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"prop.sale pid fixedPrice [openid]: 拍卖道具 道具编号 一口价 [子帐号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);if(!(r=await e.db.propList.getVp(r))||r.pst==P.Delete)throw new u(c.MISC_ERROR,"prop.sale prop not exist");if(r.pst!=P.Ready)throw new u(c.MISC_ERROR,"prop.sale prop cannt be sent on current status");t=t.u64(1,0);var[e,,]=await e.propSale(r.current.hash,r.current.index,t,i);return e.toJSON()}async propSendListAdmin(e,t,i){return this.propSendList(e,t,i,!0)}async propSendList(e,t,i,r=!1){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.sendlist (addr|txid|index)(n,) [openid]: 批量转移道具 道具数组(地址|交易ID|输出索引) [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),s=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var n of t){var a,o;3<=(n=n.split("|")).length&&(a=n[0],o=new R(d.revHex(n[1]),parseInt(n[2])),4<=n.length?s.push([o,x.fromString(a),n[3]]):s.push([o,x.fromString(a)]))}var[t,,e]=await e.propExchangeList(s,i,r);if(t&&e){let i=t.hash("hex"),r=t.rhash();return e.map(e=>({hash:i,txid:r,cid:e.cid,pid:e.pid,oid:e.oid,gold:e.gold,addr:e.addr}))}}async propReceive(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.receive tx [account]: 捐赠接收函数 捐赠交易字符串 [接收账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));if(!(t=t.buf(0)))throw new u(c.TYPE_ERROR,"Invalid TX Info.");t=A.fromRaw(t);var[e,,t]=await e.propReceive(t,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,addr:t.simAddr,gaddr:t.gaddr}}async propDonate(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.donate pid [openid]: 捐赠道具函数 道具ID [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new u(c.MISC_ERROR,"prop not exist");if(t.pst!=P.Ready)throw new u(c.MISC_ERROR,"prop cannt be sent on current status");t=new R(t.current.hash,t.current.index);var[e,,t]=await e.propDonate(t,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,raw:e.toRaw().toString("hex")}}async propExchange(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"prop.send addr pid [openid]: 转移道具函数 接收地址 物品编号 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.str(1);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new u(c.MISC_ERROR,"prop.send prop not exist");if(t.pst!=P.Ready)throw new u(c.MISC_ERROR,"prop.send prop cannt be sent on current status");var[e,,t]=await e.propExchange(new R(t.current.hash,t.current.index),x.fromString(r),i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,addr:r}}async propCreateList(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.createlist (cid|oid|gold|pid)(n,) [openid]: 批量创建道具 道具信息数组 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));let r=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var s of t)if(3<=(s=s.split("|")).length){var n=s[0],a=s[1],o=parseInt(s[2]);let e=null;4<=s.length&&(e=s[3]),o<b.MINPROPVALUE||r.push([n,a,o,e])}r=r.map(e=>{var[e,t,i,r]=e;return{oper:I.propCreate,cid:e,oid:t,gold:i,pid:r}});var[t,,]=await e.propCreate(r,i);return t?r:null}readImageAsBlob(e,t){l.readFile(e).then(i=>{var r=z.getType(F.basename(e));t(null,{hex:i.toString("hex"),type:r})}).catch(e=>{t(e,null)})}async inscriptionCreate(e,t,i){if(!(t||e.length<2)){t=new g([e]);var[e,r]=await this.accessControl(i,t.str(4,"")),s=t.str(0);let h=t.str(1);if((t=t.u64(2,b.MINPROPVALUE))<b.MINPROPVALUE)throw new u(c.PROP_MINVALUE,"prop.create: not a valid value");if(0<=h.indexOf("file:")){const e=h.replace("file:","")||"docs/eth.jpg";h=await new Promise(t=>{this.readImageAsBlob(e,(e,i)=>{e?console.error("Error reading inscription:",e):t(i)})})}else{if(!(0<=h.indexOf("data:")))throw new u(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]");h=JSON.parse(h.replace("data:",""))}var n,a=await e.createReceive(r),o=w.sha256(Buffer.from(JSON.stringify(h))).toString("hex");if(o=await this.caIssuePublic([JSON.stringify({blob:h,hash:o,height:0}),a.getAddress("string"),"",r],null,i))return a={oper:I.propCreate,cid:s,gold:t,type:"inscription",oid:o.erid},[i,n]=await e.propCreate([a],r),i?a:null}throw new u(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]")}async propCreate(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"prop.create cid oid gold pid (openid): 创建道具 厂商编码 道具类别码 含金量 道具编码(可填空) [账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(4,"")),r=t.str(0),s=t.str(1),n=t.u64(2,b.MINPROPVALUE);t=t.str(3,null);if(n<b.MINPROPVALUE)throw new u(c.PROP_MINVALUE,"prop.create: not a valid value");r={oper:I.propCreate,cid:r,oid:s,gold:n,pid:t};var[s,,]=await e.propCreate([r],i);return s?r:null}async walletLock(e,t,i){if(t)throw new u(c.MISC_ERROR,"wallet.lock [passphrase]");var[t]=await this.accessControl(i);if(!t.master.encrypted){if((i=new g([e]).str(0,"")).length<1)throw new u(c.MISC_ERROR,"Wallet is not encrypted, please run wallet.lock passphrase");try{await t.setPassphrase(null,i)}catch(e){throw new u(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}}return await t.lock(),null}async listMSTrans(e,t,i){if(t)throw new u(c.MISC_ERROR,"tx.mstrans");return t=new g([e]).str(0,""),this.wdb.listMSTrans(t)}async signMSTrans(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"tx.mstrans.sign txid");e=(t=new g([e])).str(0,"");var r=t.str(1,""),[i,t]=await this.accessControl(i,t.str(2,""));if(!(e=await this.wdb.db.get(n.ms(x.getHash(e,"hex"),r))))throw new u(c.MISC_ERROR,"tx.mstrans.sign txid");if(e=JSON.parse(e.toString()),!await i.belongToAccount(t,e.addr))throw new u(c.MISC_ERROR,"tx.mstrans.sign invalid account");var s,o=await this.wdb.get(e.addr);o&&o.account.type==a.types.MULTISIG&&((s=E.fromRaw(e.data,"hex")).view=await o.getCoinView(s),await o.sign(s),s.isSigned()?await o.sendMTX(s):await i.send({subtractFee:!1,sort:!1,outputs:[{address:e.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"sign",addr:e.addr,tx:s.toRaw().toString("hex")}})},t),await this.wdb.delMSTrans(e.addr,r))}async resendWalletTransactions(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"tx.resend.admin");var[t]=await this.accessControl(i),r=[];for(const e of await t.resend())r.push(e.txid());return r}async resend(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"tx.resendall.admin: 重发挂起交易");var r=await this.wdb.resend();if(r)for(var s of Object.keys(r))if(s)for(const e of r[s])await this.wdb.send(e);return!0}async rescan(e,t,i){if(t)throw new u(c.MISC_ERROR,'wallet.rescan ( "height" )');return t=new g([e]).u32(0),await this.wdb.rescan(t),this.logger.info("Rescanning..."),!0}async createAddress(e,t,i){if(t||2<e.length)throw new u(c.MISC_ERROR,'address.create ( "account" "uid" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.u32(1,0);return(e=await e.createReceive(i,t))?e.toJSON():null}async calcAddress(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"address.calc account(must be typeof number) branch index");t=new g([e]);let[s,n]=await this.accessControl(i,t.int(0,0));return e=t.u32(1,0),i=t.u32(2,0),"default"==n&&(n=0),t=(await s.deriveKey(n,e,i,s.master)).toJSON(),i=(e=await s.deriveKey(n,e,i))?e.toJSON():null,r(t.address==i.address,"address derived from prv not equals which derived from pub."),i}async createAddressAdmin(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,'address.create.admin ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createReceive(i,0,e.master))?t.toJSON(!0):null}async createChange(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,'address.change.create ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createChange(i))?t.toJSON():null}async createNested(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,'address.nested.create ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createNested(i))?t.toJSON():null}async mkwallet(e,t,i){var r=(e=new g([e])).str(4);if(r)for(var s of await this.wdb.getWallets())if((await this.wdb.get(s)).master.mnemonic.getPhrase()===body.phrase)throw new u(c.MISC_ERROR,"wallet.create: 相同助记词已被使用");return(r=await this.wdb.ensure({id:M(),type:e.str(1),m:e.u32(2),n:e.u32(3),mnemonic:r,passphrase:e.str(5),master:e.str(6),witness:e.bool(7),watchOnly:e.bool(8),accountKey:e.str(9)}))?r.toJSON(!1):null}async accountGet(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"account.get account: 查询账户");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.getAccount(i))?t.toJSON():null}async getPending(e,t,i){if(t)throw new u(c.MISC_ERROR,"tx.pending [account]: 查询挂起的交易");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=(t=await e.getPending(i),s.sortTX(t),[]);for(const i of await e.toDetails(t))r.push(i.toJSON());return r}async getPendingItem(e,t,i){var r,s=(e=new g([e])).hash(0,""),[n,i]=await this.accessControl(i,e.str(1,""));for(r of await n.getPending(i))if(r.hash==s)return(r=await n.toDetails(r)).toJSON()}async getPendingHash(e,t,i){e=new g([e]);var[i,e]=await this.accessControl(i,e.str(0,"")),r=(e=await i.getPending(e),s.sortTX(e),[]);for(const t of await i.toDetails(e))r.push(d.revHex(t.hash));return r}async getPendingCount(e,t,i){if(t)throw new u(c.MISC_ERROR,"tx.pending.count [account]: 查询挂起的交易数");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=await e.ensureIndex(i);return(await e.txdb.getPendingHashes(t)).length}async accountCreate(e,t,i){e=new g([e]);var r,[i]=await this.accessControl(i),s=e.obj(0);e=e.str(1),s={name:(s=new g([s])).str("name"),witness:s.bool("witness",!0),type:s.str("type","pubkeyhash"),m:s.u32("m",1),n:s.u32("n",1),watchOnly:s.bool("watch",!1),accountKey:s.str("key",null),lookahead:s.u32("lookahead",10)};try{let t=await i.getAccount(s.name);return t?t.toJSON():((r=(t=await i.createAccount(s,e)).toJSON()).isNew=!0,r)}catch(t){return null}}async getblocks(e,t,i){if(t)throw new u(c.MISC_ERROR,"wallet.blocks");var[t]=await this.accessControl(i);return await t.getBlocks()}async getKey(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,"key.export.public address: 查询地址的密钥");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.getKey(i)))?t.toJSON():null}async getPrivKey(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,"address.key.admin address: 查询地址的密钥");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.getKey(i)))?t.toJSON(!0):null}async getwif(e,t,i){if(t||1!=e.length)throw new u(c.MISC_ERROR,"address.wif.admin address: 查询地址对应的私钥 地址");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0),t=t.str(1);return(e=(r(i,"Address is required."),await e.getPrivateKey(i,t)))?e.toSecret():null}async hasAddress(e,t,i){if(t||1!=e.length)throw new u(c.MISC_ERROR,"address.has address: 查询钱包是否包含一个地址 地址");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.hasAddress(i)))||!1}async getCoin(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),s=e.hash(0);e=e.u32(1);return(i=(r(s,"Hash is required."),r(null!=e,"Index is required."),await i.getCoin(s,e)))?i.getJSON(this.network):null}async getSpender(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),s=e.hash(0);e=e.u32(1);return(i=(r(s,"Hash is required."),r(null!=e,"Index is required."),await i.txdb.getSpender(s,e)))?{hash:d.revHex(i.hash),index:i.index}:null}async getSpent(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),s=e.hash(0);e=e.u32(1),r(s,"Hash is required."),r(null!=e,"Index is required."),i=await i.txdb.getSpentCoin({hash:s,index:e});return{hash:d.revHex(i.hash),index:i.index,value:i.value,height:i.height,version:i.version,time:i.time}}async getCoincacheSize(e,t,i){var[i]=await this.accessControl(i);return i.txdb.coinCache.size}async conserveCoin(e,t,i){if(t||2!=e.length)throw new u(c.MISC_ERROR,"coin.conserved.add txhash index: 新增需要保持的硬币: 交易Hash 输出序号");t=new g([e]);var[e]=await this.accessControl(i);i=t.hash(0),t=t.u32(1),r(i,"Hash is required."),r(null!=t,"Index is required."),i=new R(i,t);return e.conserveCoin(i),!0}async getConservedCoins(e,t,i){if(t||0<e.length)throw new u(c.MISC_ERROR,"coin.conserved.get: 查询已经保持的Coin列表");var[t]=await this.accessControl(i),r=[];for(const e of t.getConserved())r.push(e.toJSON());return r}async unConserveCoin(e,t,i){if(t||2!=e.length)throw new u(c.MISC_ERROR,"coin.conserved.del: 减少需要保持的硬币: 交易Hash 输出序号");t=new g([e]);var[e]=await this.accessControl(i);i=t.hash(0),t=t.u32(1),r(i,"Hash is required."),r(null!=t,"Index is required."),i=new R(i,t);return e.unConserveCoin(i),!0}async addShared(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"key.shared.add [account] key: 新增共享公钥 [账号] 公钥");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.str(1);return await e.addSharedKey(i,t),!0}async removeShared(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"key.shared.del [account] key: 删除共享公钥 [账号] 公钥");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.str(1);return await e.removeSharedKey(i,t),!0}async zap(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.zap [age]: 移除挂起交易 挂起时长(默认三天)");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0),t=t.u32(1,259200);return r(t,"Age is required."),await e.zap(i,t),!0}async sendOracle(e,t,i){if(!(t||e.length<3||4<e.length)){t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0,null),s=t.str(1,null);if(null==(t=t.u64(2)))throw new u(c.TYPE_ERROR,"Invalid parameter.");if(r&&s)return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:JSON.stringify({oper:I.vote,type:"oracle",k:r,v:s})},r=await e.send(t,i),(await e.getDetails(r.hash("hex"))).toJSON()}throw new u(c.MISC_ERROR,"oracle.send k v amount [openid]")}async sendVote(e,t,i){if(t||e.length<2||3<e.length)throw new u(c.MISC_ERROR,"vote.send addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),s=t.str(0);if(null==(t=t.u64(1)))throw new u(c.TYPE_ERROR,"Invalid parameter.");for(r of s.split(","))if(!o.parseAddress(r,this.network))throw new u(c.TYPE_ERROR,"Invalid address.");return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${I.vote}", "type": "mine", "ca": "${s}"}`},s=await e.send(t,i),(await e.getDetails(s.hash("hex"))).toJSON()}async sendVoteAsync(e,t,i){if(t||e.length<2||3<e.length)throw new u(c.MISC_ERROR,"vote.send.async addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),s=t.str(0);if(null==(t=t.u64(1)))throw new u(c.TYPE_ERROR,"Invalid parameter.");for(r of s.split(","))if(!o.parseAddress(r,this.network))throw new u(c.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${I.vote}", "type": "mine", "ca": "${s}"}`},e.send(t,i)}async sendTX(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"tx.send addr amount [openid]:发送交易 地址 金额 [发起账户]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new u(c.MISC_ERROR,"Alliance Cert Invalid.");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.u64(1),r=await e.send({outputs:[{address:r,value:t}]},i);return(await e.getDetails(r.hash("hex"))).toJSON()}async sendTXAsync(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"tx.send.async addr amount [openid]:发送交易 地址 金额 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.u64(1);e.send({outputs:[{address:r,value:t}]},i)}async signTX(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"tx.sign.admin txdata [sendnow passphrase]: 对交易签名/发送 交易原始数据 [立即发送 解锁密码]");t=new g([e]);var[e]=await this.accessControl(i),s=(i=t.buf(0),r(i,"TX is required."),t.bool(1,!1));t=t.str(2);(i=E.fromRaw(i)).view=await e.getCoinView(i),await e.sign(i,t);let n=null;return n=(s&&i.isSigned()?await e.sendMTX(i):i).getJSON(this.network),e.account.type==a.types.MULTISIG&&(t=i.getMultisig(this.network),n.ms={m:t.m,n:t.n,c:t.c}),n}async createTX(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"tx.create options outputs [openid]: 创建交易 参数对象 输出数组 [子账号]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new u(c.MISC_ERROR,"Alliance Cert Invalid.");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(2,""));i=t.obj(0),t=t.array(1);if(Array.isArray(i.in))for(var s of i.in)s.hash=d.revHex(s.hash);var n={comment:(i=new g([i])).obj("comment",null),sendnow:i.bool("sendnow",!0),account:i.str("account"),rate:i.u64("rate"),blocks:i.u32("blocks"),maxFee:i.u64("maxFee"),selection:i.str("selection"),smart:i.bool("smart"),subtractFee:i.bool("subtractFee"),subtractIndex:i.get("subtractIndex"),depth:i.u32(["confirmations","depth"]),inputs:i.array("in",null),outputs:[]};for(const e of t){var o=new g([e]),h={value:o.u64("value")};if(h.address=o.str("address"),!h.address){var l=o.str("account");if(l){await r.ensureAccount({name:l,witness:!0});var p=await r.createReceive(l);if(!p)throw new u(c.MISC_ERROR,`tx.create: account ${l} not exist`);h.address=p.getAddress("string")}}if((l=o.buf("script"))&&(h.script=v.fromRaw(l)),(p=o.str("locktype"))&&(o=o.u64("locktime",0))){if("no"!=p&&"clb"!=p&&"clt"!=p&&"csb"!=p&&"cst"!=p)throw new u(c.MISC_ERROR,'locktype should be "no"-不锁定 or "clb"-绝对高度锁定 or clt(绝对时间锁定) or "csb"-相对高度锁定 or "cst"-相对时间锁定 !');if(p==v.outputLockType.CHECKABSOLUTETIME&&o<=b.LOCKTIME_THRESHOLD)throw new u(c.MISC_ERROR,"lock absolute time should not less than 500000000!");if(p==v.outputLockType.CHECKABSOLUTEBLOCK&&o>b.LOCKTIME_THRESHOLD)throw new u(c.MISC_ERROR,"lock absolute block should not more than 500000000!");if((p==v.outputLockType.CHECKRELATIVEBLOCK||p==v.outputLockType.CHECKRELATIVETIME)&&65535<o)throw new u(c.MISC_ERROR,"lock relative block/time should not more than 65535!");h.locktype=p,h.locktime=o}n.outputs.push(h)}e&&(n.account=e);let f=null;return n.sendnow?(i=await r.send(n),f=(t=await r.getDetails(i.hash("hex"))).toJSON()):(e=await r.createTX(n),await r.sign(e),f=e.getJSON(this.network),r.account.type==a.types.MULTISIG&&(i=e.getMultisig(this.network),f.ms={m:i.m,n:i.n,c:i.c})),f}async getLast(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"tx.last account [limit]: 最近的交易 账号 [最大记录数]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0)),r=(t=t.u32(1),[]);i=await e.getLast(i,t);for(const t of await e.toDetails(i))r.push(t.toJSON());return r}async getRange(e,t,i){if(t||e.length<4)throw new u(c.MISC_ERROR,"tx.range account start end limit [reserve]: 指定时限内的交易 账号 开始时间 结束时间 最大记录数 [反转]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=(t={start:t.u32(1),end:t.u32(2),limit:t.u32(3),reverse:t.bool(4)},i=await e.getRange(i,t),[]);for(const t of await e.toDetails(i))r.push(t.toJSON());return r}async caUserStatus(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"ca.user.status cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),s=t.array(2,[]);let n=null;for(let e=0;e<s.length;e++){var a=s[e];a&&Array.isArray(a)?"alliancename"==a[0]&&(n=a[1],delete s[e]):delete s[e]}var[t]=await this.accessControl(i);e=await this.$allianceUserCreate([e,r,n],i);return s.push(["pubkey",e.data.pubkey]),s.push(["merge",!0]),t.db.client.execute("ca.list",[s])}async caUserLog(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"ca.user.log cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),s=t.array(2,[]);let n=null;for(let e=0;e<s.length;e++){var a=s[e];a&&Array.isArray(a)?"alliancename"==a[0]&&(n=a[1],delete s[e]):delete s[e]}var[t,,]=await this.accessControl(i,e);e=await this.$allianceUserCreate([e,r,n],i);return s.push(["pubkey",e.data.pubkey]),t.db.client.execute("ca.list",[s])}async sysLog(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.log (query openid)");e=(t=new g([e])).array(0,[]);var r,[s,,]=await this.accessControl(i,t.str(1,"")),n=[];for(r of(await this.wdb.auditList.query(e)).list){var a=Object.assign({},r),h=o.parseHash(r.address,this.network);(h=await s.getPath(h))&&(a.account=h.name),a.time=new Date(1e3*r.time).toLocaleString(),n.push(a)}return n}async caIssuePublic(e,t,i){if(t||e.length<2||4<e.length)throw new u(c.MISC_ERROR,"ca.issue.public cert witness [pubkey openid]: 签发证书 证书对象 见证地址 [原始存证签名公钥 支付账户]");e=(t=new g([e])).obj(0,{});var r=t.str(1,""),s=t.str(2,""),[i,t]=await this.accessControl(i,t.str(3,""));if(64!=e.hash.length)throw new u(c.TYPE_ERROR,"err hash length");var n=await i.db.client.execute("ca.byId",[e.hash]);if(n)return n;if(n=await i.getPrivateKey(r))return e.height||(e.height=b.retargetInterval),await i.issueCreate({erid:e.hash,key:n.privateKey.toString("hex"),address:n.getAddress().toString(),witness:n.publicKey.toString("hex"),validHeight:this.wdb.curHeight+e.height,source:{subjectName:e.name||"",pubkey:s,subjectHash:e.hash,cluster:e.cluster,blob:e.blob}},t);throw new u(c.TYPE_ERROR,"Invalid witness.")}async caAbolishPublic(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"ca.abolish.public array[[erid height [openid]]]: 废止授信交易 废止交易信息数组");var r,s=[];for(r of new g([e]).array(0,[])){var[n,a]=await this.accessControl(i,r[3]),o=r[0],h=parseInt(r[1]),l=await this.wdb.erList.query([["erid",o]]),p=(l=x.fromWitnessPubkeyhash(w.hash160(Buffer.from(l.list[0].witness,"hex")),this.network.type).toString(),await n.getKey(l));if(!p)throw new u(c.TYPE_ERROR,"Invalid witness.");(n=await n.caAbolish({key:p.privateKey.toString("hex"),witness:p.publicKey.toString("hex"),address:l,erid:o,abolishHeight:h,cid:"",uid:0},a))&&s.push(n)}return s}async caIssue(e,t,i){if(t||e.length<3||4<e.length)throw new u(c.MISC_ERROR,"ca.issue cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(e,i,!1)}async caIssueAsync(e,t,i){if(t||e.length<3||4<e.length)throw new u(c.MISC_ERROR,"ca.issue.async cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(e,i,!0)}async $caIssue(e,t,i){var r=(e=new g([e])).obj(0,{}),s=e.uint(1,0),n=e.str(2,""),[e,a]=await this.accessControl(t,e.str(3,""));if(!(o=await e.ensureCp(n))||"forbidden"==o.cls)throw new u(c.MISC_ERROR,"Invalid Account");if(64!=r.hash.length)throw new u(c.TYPE_ERROR,"err hash length");var o=await this.$allianceUserCreate([n,s],t),h=[];if(h.push(["pubkey",o.data.pubkey]),h.push(["source.subjectHash",r.hash]),0<(await e.db.client.execute("ca.list",[h])).count)throw new u(c.TYPE_ERROR,"cert.hash conflicted");if(await e.db.client.execute("ca.byId",[r.hash]))throw new u(c.TYPE_ERROR,"cert.hash conflicted");return r.height||(r.height=b.retargetInterval),o=await this.$allianceUserCreate([n,s],t,!0),await e.issueCreate({erid:r.hash,key:o.prvkey,witness:o.data.pubkey,address:o.data.addr,validHeight:this.wdb.curHeight+r.height,source:{subjectName:r.name,pubkey:o.data.pubkey,subjectHash:r.hash,cluster:r.cluster,cid:n,uid:s}},a,i)}async caAbolish(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"ca.abolish [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!1)}async caAbolishAsync(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"ca.abolish.async [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!0)}async $caAbolish(e,t,i){var r,s=[];for(r of new g([e]).array(0,[])){var n,a=r[0],o=r[1],c=r[2],h=parseInt(r[3]),[n,u]=await this.accessControl(t,r[4]),l=await this.$allianceUserCreate([o,a],t,!0);(n=await n.caAbolish({cid:o,uid:a,key:l.prvkey,witness:l.data.pubkey,address:l.data.addr,erid:c,abolishHeight:h},u,i))&&s.push(n)}return s}async enchanceCp(e,t,i){if(t||e.length<2||4<e.length)throw new u(c.MISC_ERROR,"ca.enchance toCid fromCid height [openid]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3)),r=t.str(0,0),s=t.str(1,0);let n=t.uint(2,0);(!n||n<this.wdb.curHeight)&&(n=this.wdb.curHeight+b.retargetInterval);var[t,e]=await e.enchanceCp({to:r,from:s,enchanceHeight:n},i);return t&&e?e:null}async queryErList(e,t,i){if(t)throw new u(c.MISC_ERROR,"ca.query.remote conditions: 查询存证列表 (复合条件)");t=new g([e]);var[e,,]=await this.accessControl(i,t.str(1,""));i=t.array(0,[]);return e.db.client.execute("ca.list",[i])}async queryMyErlist(e,t,i){if(t)throw new u(c.MISC_ERROR,"ca.list.me query: 条件查询自己的电子权利 条件数组");return t=new g([e]).array(0,[]),this.wdb.erList.query(t)}}},function(e,t,i){var r=i(37);const{ContractEnvType:s,ContractStatus:n}=i(5),a=i(6),o=i(108);e.exports=class extends r{constructor(e){super(),this.db=e}async loadHistory(){var e;for(e of await this.db.getContracts())e&&(e.period<this.db.curHeight&&e.transStatus==n.CreatedOnMem?await this.delTransContract(e,!0):(e.id=e.type+"."+e.addr,await this.saveContract(e),e.transStatus==n.Promised&&this.db.autoTaskMgr.addTask(new o(this.db.network.txcheckpoint,e),this.db.network.txchecktime[e.type])))}query(e,t){return(e=this.get(e+"."+t))?e.transStatus:n.None}async addTransContract(e,t,i=!1){t.id=t.type+"."+t.addr;var r=this.get(t.id);e===s.Mempool&&((t=r||t).transStatus||(t.transStatus=n.CreatedOnMem),await this.saveContract(t,i))}async saveContract(e,t=!1){e.id=e.id||e.type+"."+e.addr,this.set(e.id,e),t&&(t=a.hash256(Buffer.from(e.id)).toString("hex"),await this.db.batchPut(this.db.tidCreator(t),Buffer.from(JSON.stringify(e))))}async promiseContract(e,t=!1){let i=!1;var r=e.type+"."+e.addr;let s=this.get(r);return s&&s.oper==e.oper||(i=!0,s=e),(!s.transStatus||s.transStatus<n.Promised)&&(i=!0,s.transStatus=n.Promised),i&&await this.saveContract(s,t),i}async confirmContract(e,t,i){e=e.type+"."+e.addr,!(e=this.get(e))||e.transStatus!=n.Promised||t!=n.Confirmed&&t!=n.Expired||(e.transStatus=t,await this.saveContract(e,i))}async delTransContract(e,t){var i=e.type+"."+e.addr,r=this.get(i);r&&r.oper==e.oper&&(this.delete(i),t)&&(r=a.hash256(Buffer.from(i)).toString("hex"),await this.db.batchDel(this.db.tidCreator(r)))}}},function(e,t,i){const r=i(5).HtlcStatus;i=i(37);class s extends i{constructor(e){super(),this.db=e}async loadHistory(){var e,t;for(e of(this.clear(),await this.db.loadHtlcList()))this.set(e.id,e),e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t)||this.account.set(t,new Map),this.account.get(t).set(e.id,e))}setAccount(e,t,i){this.delAccount(e),t&&i&&(e.wid=t,e.account=i,t=e.wid+"."+e.account,this.account.get(t)||this.account.set(t,new Map),this.account.get(t).set(e.id,e))}delAccount(e){var t;e&&e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t))&&this.account.get(t).delete(e.id)}}s.vpItem=class e{constructor(e){this.fromOptions(e||{})}fromOptions(e){this.shash=e.shash,this.sidx=e.sidx,this.sheight=e.sheight,this.ahash=e.ahash,this.aidx=e.aidx,this.aheight=e.aheight,this.src=e.src,this.dst=e.dst,this.aa=e.aa,this.ab=e.ab,this.ba=e.ba,this.bb=e.bb,this.amount=e.amount,this.rate=e.rate,this.pst=e.pst}toRaw(){var e={};return e.shash=this.shash,e.sidx=this.sidx,e.sheight=this.sheight,e.ahash=this.ahash,e.aidx=this.aidx,e.aheight=this.aheight,e.src=this.src,e.dst=this.dst,e.amount=this.amount,e.rate=this.rate,e.pst=this.pst||r.Init,e.aa=this.aa||"",e.ab=this.ab||"",e.ba=this.ba||"",e.bb=this.bb||"",Buffer.from(JSON.stringify(e),"utf-8")}get id(){return""+this.shash+this.sidx}fromRaw(e){return e=JSON.parse(e.toString("utf8")),this.fromOptions(e),this}static fromRaw(t){return(new e).fromRaw(t)}},e.exports=s},function(e,t,i){"use strict";
|
|
921
|
+
*/const r=i(0),s=i(73);i(119);const n=i(85).walletdb,a=i(157),o=i(78),c=o.errors,h=o.MAGIC_STRING,u=i(77),l=i(59),p=i(107),d=i(2),f=i(192),m=i(3),g=i(84),y=i(33),v=i(17),b=i(7),w=i(6),k=i(26),x=i(13),S=i(39),_=i(131),E=i(69),R=i(45),A=i(20),O=i(136),C=i(137),{ContractType:I,ContractState:j,PropStatus:P,HtlcStatus:T}=i(5),B=i(138),N=i(123),M=i(142),L=i(19).opcodes,F=i(34),z=i(612);e.exports=class extends o{constructor(e){super(e),r(e,"RPC requires a WalletDB."),this.wdb=e,this.keys=e.keys,this.network=e.network,this.logger=e.logger.context("rpc"),this.client=e.client,this.init()}init(){this.add("sys.alliance.create",this.allianceCreate),this.add("sys.alliance.import",this.allianceImport),this.add("sys.alliance.delete",this.allianceDelete),this.add("sys.alliance.refresh",this.refreshAlliance),this.add("sys.alliance.refresh.async",this.refreshAllianceAsync),this.add("sys.alliance.gettoken",this.getAllianceNodeToken),this.add("sys.alliance.user",this.allianceUserCreate),this.add("wallet",this.routerOfWallet),this.add("wallet.create",this.mkwallet),this.add("wallet.exportmnemonic.admin",this.exportMnemonic),this.add("wallet.importmnemonic.admin",this.importMnemonic),this.add("wallet.export",this.dumpWallet),this.add("wallet.exports.admin",this.dumpWallets),this.add("wallet.import",this.importWallet),this.add("wallet.list",this.getWallets),this.add("wallet.info",this.getWalletInfo),this.add("wallet.block",this.getWalletBlock),this.add("wallet.layouth",this.getWalletLayoutH),this.add("wallet.encrypt",this.encryptWallet),this.add("wallet.decrypt",this.decryptWallet),this.add("wallet.changepassphrase",this.changePassphrase),this.add("wallet.lock",this.walletLock),this.add("wallet.unlock",this.unlock),this.add("wallet.blocks",this.getblocks),this.add("wallet.auth",this.walletAuth),this.add("wallet.rescan",this.rescan),this.add("key",this.routerOfKey),this.add("key.export.private",this.dumpPrivKey),this.add("key.export.public",this.getKey),this.add("key.master.admin",this.masterkey),this.add("key.import.private",this.importPrivKey),this.add("key.import.public",this.importPubkey),this.add("key.import.address",this.importAddress),this.add("key.shared.add",this.addShared),this.add("key.shared.del",this.removeShared),this.add("account",this.routerOfAccount),this.add("account.list",this.listAccounts),this.add("account.get",this.accountGet),this.add("account.create",this.accountCreate),this.add("account.received",this.getReceivedByAccount),this.add("account.listreceived",this.listReceivedByAccount),this.add("account.virtualadd.admin",this.accountVirtualAdd),this.add("account.checkamount",this.accountCheckAmount),this.add("balance.confirmed",this.getBalance),this.add("balance.all",this.getBalanceAll),this.add("balance.check",this.checkBalance),this.add("balance.unconfirmed",this.getUnconfirmedBalance),this.add("balance.log",this.getBalanceLog),this.add("comm.notify",this.commNotify),this.add("comm.hash",this.calcHash),this.add("comm.listNotify",this.listNotify),this.add("comm.secret",this.sendSecret),this.add("comm.listContact",this.listContact),this.add("comm.scanContact",this.scanContact),this.add("comm.comment",this.sendComment),this.add("comm.comment.query",this.commentQuery),this.add("sys.walletdb.stop",this.stop),this.add("sys.walletnode.shutdown",this.shutdown),this.add("sys.walletdb.create",this.createWalletDb),this.add("sys.walletdb.destroy",this.destroyWalletDb),this.add("sys.zap",this.zap),this.add("sys.setfee",this.setTXFee),this.add("sys.message.sign",this.signMessage),this.add("sys.log",this.sysLog),this.add("address",this.routerOfAddress),this.add("address.list",this.getAddressesByAccount),this.add("address.index",this.getAddressesByIndex),this.add("address.receive",this.getAccountAddress),this.add("address.change",this.getAccountChangeAddress),this.add("address.nested",this.getAccountNestedAddress),this.add("address.calc",this.calcAddress),this.add("address.create",this.createAddress),this.add("address.create.admin",this.createAddressAdmin),this.add("address.receive.create",this.createAddress),this.add("address.change.create",this.createChange),this.add("address.nested.create",this.createNested),this.add("address.import",this.importAddress),this.add("address.key.admin",this.getPrivKey),this.add("address.wif.admin",this.getwif),this.add("address.has",this.hasAddress),this.add("address.amount",this.getReceivedByAddress),this.add("address.account",this.getAccount),this.add("address.received",this.getReceivedByAddress),this.add("address.received.list",this.listReceivedByAddress),this.add("cp",this.routerOfCp),this.add("cp.create",this.cpRegister),this.add("cp.create.async",this.cpRegisterAsync),this.add("cp.change",this.cpChange),this.add("cp.query",this.cpQuery),this.add("cp.query.remote",this.cpQueryRemote),this.add("cp.mine",this.cpMine),this.add("cp.user",this.getUserToken),this.add("sc",this.routerOfSc),this.add("sc.register",this.scRegister),this.add("sc.run",this.scRun),this.add("ca",this.routerOfCa),this.add("ca.issue",this.caIssue),this.add("ca.user.status",this.caUserStatus),this.add("ca.user.log",this.caUserLog),this.add("ca.abolish",this.caAbolish),this.add("ca.enchance",this.enchanceCp),this.add("ca.list.me",this.queryMyErlist),this.add("ca.list.remote",this.queryErList),this.add("ca.issue.async",this.caIssueAsync),this.add("ca.abolish.async",this.caAbolishAsync),this.add("ca.issue.public",this.caIssuePublic),this.add("ca.abolish.public",this.caAbolishPublic),this.add("prop",this.routerOfProp),this.add("prop.create",this.propCreate),this.add("prop.createlist",this.propCreateList),this.add("prop.send",this.propExchange),this.add("prop.sendlist",this.propSendList),this.add("prop.sendlist.admin",this.propSendListAdmin),this.add("prop.found",this.propFound),this.add("inscription.create",this.inscriptionCreate),this.add("prop.wallet.byid",this.propGet),this.add("prop.wallet.byoid",this.listPropByOid),this.add("prop.wallet.byaddress",this.listProp),this.add("contract",this.routerOfContract),this.add("contract.create",this.contractCreate),this.add("contract.promise",this.contractPromise),this.add("contract.execute",this.contractExecute),this.add("contract.mine",this.contractOfMine),this.add("htlc",this.routerOfHTLC),this.add("htlc.suggest",this.htlcSuggest),this.add("htlc.suggest.cancel",this.htlcSuggestCancel),this.add("htlc.suggest.deal",this.htlcSuggestDeal),this.add("htlc.assent",this.htlcAssent),this.add("htlc.assent.cancel",this.htlcAssentCancel),this.add("htlc.assent.deal",this.htlcAssentDeal),this.add("htlc.query",this.htlcQuery),this.add("vote.send",this.sendVote),this.add("vote.send.async",this.sendVoteAsync),this.add("oracle.send",this.sendOracle),this.add("tx.get.wallet",this.getTransaction),this.add("tx.list",this.listTransactions),this.add("tx.create",this.createTX),this.add("tx.send",this.sendTX),this.add("tx.send.async",this.sendTXAsync),this.add("tx.last",this.getLast),this.add("tx.pending",this.getPending),this.add("tx.pending.get",this.getPendingItem),this.add("tx.pending.hash",this.getPendingHash),this.add("tx.pending.count",this.getPendingCount),this.add("tx.resend.admin",this.resendWalletTransactions),this.add("tx.mstrans",this.listMSTrans),this.add("tx.mstrans.sign",this.signMSTrans),this.add("tx.history",this.getHistory),this.add("tx.history.since",this.listSinceBlock),this.add("tx.range",this.getRange),this.add("tx.abandon.admin",this.abandonTransaction),this.add("tx.abandonall.admin",this.abandonPending),this.add("tx.importprunedfunds.admin",this.importPrunedFunds),this.add("tx.removeprunedfunds.admin",this.removePrunedFunds),this.add("tx.resendall.admin",this.resend),this.add("tx.sign.admin",this.signTX),this.add("tx.fund.admin",this.fundRawTransaction),this.add("coin",this.routerOfCoin),this.add("coin.get",this.getCoin),this.add("coin.spender",this.getSpender),this.add("coin.spent",this.getSpent),this.add("coin.cache",this.getCoincacheSize),this.add("coin.check",this.checkUnspent),this.add("coin.list",this.listUnspent),this.add("coin.selectone",this.selectone),this.add("coin.conserved.get",this.getConservedCoins),this.add("coin.conserved.add",this.conserveCoin),this.add("coin.conserved.del",this.unConserveCoin),this.add("coin.conserved.list",this.listConservedUnspent),this.add("coin.conserved.oper.list",this.listOperUnspent),this.add("coin.locked.list",this.listLockedUnspent)}async routerOfCoin(e){throw new u(c.MISC_ERROR,"\n coin.get 查询硬币-UTXO\n coin.remove.admin 移除指定硬币(管理员判断为状态异常者)\n coin.spender 查询硬币的消费者\n coin.list 列表硬币-UTXO\n coin.conserved.get 获取钱包保持的Coin的信息\n coin.conserved.add 钱包增加需要保持的Coin\n coin.conserved.del 钱包减少需要保持的Coin\n coin.conserved.list 列表钱包保持的UTXO\n coin.conserved.oper.list 批量锁定/解锁一组UTXO \n coin.locked.list 列表目前交易层锁定的UTXO\n ")}async routerOfContract(e){throw new u(c.MISC_ERROR,"\n contract.create 发布交易对合约\n contract.promise 签署交易对合约\n contract.execute 执行交易对合约\n contract.mine 获取已签署交易对合约列表\n contract.list 查询并返回交易对\n ")}async routerOfHTLC(e){throw new u(c.MISC_ERROR,"\n htlc.suggest 发布跨链合约\n htlc.suggest.deal 兑现合约\n htlc.suggest.cancel 取消合约\n htlc.assent 响应跨链合约\n htlc.assent.deal 兑现响应\n htlc.assent.cancel 取消响应\n htlc.query 查询合约\n ")}async routerOfWallet(e){throw new u(c.MISC_ERROR,"\n wallet.create 创建钱包\n wallet.list 列表钱包\n wallet.info 查询钱包概要\n wallet.block 查询区块信息\n wallet.exportmnemonic.admin 导出钱包助记词备份\n wallet.importmnemonic.admin 导入钱包助记词备份\n wallet.export 导出钱包备份\n wallet.import 导入钱包备份\n wallet.encrypt 将主私钥永久加密\n wallet.decrypt 将主私钥永久解密\n wallet.changepassphrase 在主私钥已经加密的情况下,修改其加密密码,要提交旧/新两个密码。如果尚未加密则执行失败\n wallet.lock 在主私钥已加密的前提下,清理内存中的密钥信息以确保锁定,相当于手工执行自动锁定\n wallet.unlock 在主私钥已加密的前提下,解密主私钥,持续一段时间后自动锁定\n wallet.blocks 列表钱包相关区块\n ")}async routerOfAddress(e){throw new u(c.MISC_ERROR,"\n address.list 列表指定账户下地址\n address.receive 列表指定账户下收款地址\n address.change 列表指定账户下找零地址\n address.nested 列表指定账户下嵌套地址\n address.create 创建一个收款地址\n address.create.admin 创建一个收款地址,回显私钥\n address.receive.create 创建一个收款地址\n address.change.create 创建一个找零地址\n address.nested.create 创建一个嵌套地址\n address.import 导入一个地址\n address.key.admin 查询地址的密钥\n address.amount 查询指定地址上的余额\n address.account 查询指定地址对应的账户\n address.wif.admin 查询地址对应的私钥\n address.has 判断钱包是否包含地址\n address.received 根据地址查询进项总额\n address.received.list 根据地址查询进项\n address.filter 在订单流水中,查询符合筛选条件的地址集\n ")}async routerOfAccount(e){throw new u(c.MISC_ERROR,"\n account.list 列表账户\n account.get 查询账户\n account.create 创建账户\n account.received 查询收款总额\n account.listreceived 列表收款记录\n balance.confirmed 已确认余额\n balance.all 余额\n balance.unconfirmed 未确认余额\n balance.log 查询指定账户变更日志\n ")}async routerOfKey(e){throw new u(c.MISC_ERROR,"\n key.export.private 根据输入地址,导出私钥\n key.export.public 根据输入地址,打出公钥\n key.master.admin 导出根密钥和助记词, 注意 encrypt 状态下无法导出私钥\n key.import.private 导入私钥\n key.import.public 导入公钥\n key.import.address 导入地址\n key.shared.add 新增共享公钥\n key.shared.del 删除共享公钥\n ")}async routerOfCp(e){throw new u(c.MISC_ERROR,"\n cp.create 创建CP记录\n cp.change 修改CP记录\n cp.remoteQuery 查询全节点中的CP列表\n cp.query 查询本地CP列表\n cp.byClass 根据游戏类别查询CP记录\n cp.byName 根据名称查询CP记录\n cp.byId 根据ID查询CP记录\n cp.mine 当前操作员注册的CP\n cp.user 生成用户令牌(钱包)\n ")}async routerOfSc(e){throw new u(c.MISC_ERROR,"\n sc.model 查询托管合约模板列表\n sc.register 指定托管合约模板,创建新的实例\n sc.query 查询托管合约实例列表\n sc.run 调用托管合约实例\n ")}async routerOfCa(e){throw new u(c.MISC_ERROR,"\n ca.issue 电子证书签发\n ca.abolish 电子证书废止记录\n ca.verify 电子证书验证\n ca.user.status 根据企业证书编号和用户编号查询\n ca.user.log 根据企业证书编号和用户编号查询日志\n ca.enchance CA机构间增信\n ca.rank 查询CA信用等级\n ca.list 查询电子证书列表\n ca.list.ab 查询电子证书废止记录列表\n ca.list.me 查询钱包内证书列表\n ")}async routerOfProp(e){throw new u(c.MISC_ERROR,"\n prop.create 创建道具\n prop.send 转移道具\n prop.createlist 批量创建道具\n prop.sendlist 批量转移道具\n prop.found 熔铸道具\n prop.byaddress 根据地址查询道具\n prop.byid 根据PID查询道具\n prop.wallet.byaddress 根据地址查询自己拥有的道具\n prop.wallet.byid 根据PID查询自己拥有的道具\n prop.wallet.byoid 根据OID查询自己拥有的道具\n ")}async allianceCreate(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"sys.alliance.create password nodeid alliancename (host): 创建联盟节点证书 备份密码 节点编号 盟友名称 (节点地址)");e=(t=new g([e])).str(0);var r=t.uint(1,0),s=t.str(2,"").trim();t=t.str(3,"");if(!r||!e)throw new u(c.MISC_ERROR,"节点编号、备份密码都不能为空");if(s==this.wdb.$parent.config.allianceName)throw new u(c.MISC_ERROR,`子网名称不能和当前网络名称[${this.wdb.$parent.config.allianceName}]相同`);if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new u(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");var[i,n]=await this.accessControl(i,""),a={body:{language:(a=await i.createAllianceInfo(s,r)).mnemonic.language,phrase:a.mnemonic.getPhrase(),passphrase:a.mnemonic.passphrase,alliancePrivateKey:a.alliancePrivateKey.toString("hex"),allianceName:s,allianceNodeId:r,awardAddress:a.awardAddress,allianceNodeToken:{network:this.network.type,alliancename:s,sn:r,prv:a.prv.toString("hex"),pub:a.pub.toString("hex"),address:a.address},notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${s}-${r}.keystore`};let o=N.encrypt(a);if(this.wdb.$parent){let i=!1;for(var h of this.wdb.$parent.config.alliances)if((h=h.split("|"))[0]==s&&h[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(a.body.allianceNodeToken.pub,"hex")),o=N.encrypt(a),this.wdb.$parent.config.alliances.push(`${s}|${r}|${o}|${e}|${a.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}e={host:t,an:a.body.allianceNodeToken.alliancename,ai:a.body.allianceNodeToken.sn,key:a.body.allianceNodeToken.pub};var d=p.signObj(e,i.notifyKey.privateKey);return await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:e,sig:d,pub:i.notifyKey.publicKey.toString("hex")})}),l.unsupported||await l.writeFile(a.file,o,"utf8"),e=(await i.getAccount(n)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.create",hash:s+"."+r,index:0}),{nodeid:r,alliancename:s,host:t,peerPubkey:a.body.allianceNodeToken.pub,awardAddress:a.body.awardAddress,file:a.file,notifyAddress:i.notifyAddress}}async allianceImport(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"sys.alliance.import password nodeid alliancename key (host): 导入联盟节点 备份密码 节点编号 盟友名称 节点公钥 (节点地址)");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new u(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");e=(t=new g([e])).str(0);var r=t.uint(1,0),s=t.str(2,""),n=t.str(3,"");t=t.str(4,"");if(!r||!e||!n)throw new u(c.MISC_ERROR,"节点编号、备份密码、节点公钥都不能为空");var[i,a]=await this.accessControl(i,""),o={body:{alliancePrivateKey:(o=await i.createAllianceInfo(s,r,n)).alliancePrivateKey.toString("hex"),allianceName:s,allianceNodeId:r,allianceNodeToken:{network:this.network.type,alliancename:s,sn:r,pub:o.pub.toString("hex"),address:o.address},awardAddress:o.awardAddress,notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${s}-${r}.keystore`};let h;if(this.wdb.$parent){let i=!1;for(var d of this.wdb.$parent.config.alliances)if((d=d.split("|"))[0]==s&&d[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(n,"hex")),h=N.encrypt(o),this.wdb.$parent.config.alliances.push(`${s}|${r}|${h}|${e}|${o.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}else h=N.encrypt(o);return l.unsupported||await l.writeFile(o.file,h,"utf8"),n={host:t,key:o.body.allianceNodeToken.pub,an:o.body.allianceNodeToken.alliancename,ai:o.body.allianceNodeToken.sn},e=p.signObj(n,i.notifyKey.privateKey),await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:e,pub:i.notifyKey.publicKey.toString("hex")})}),n=(await i.getAccount(a)).getReceive().toString(),await this.wdb.logAudit({address:n,oper:"node.create",hash:s+"."+r,index:0}),{nodeid:r,alliancename:s,host:t,peerPubkey:o.body.allianceNodeToken.pub,awardAddress:o.body.awardAddress,file:o.file,notifyAddress:i.notifyAddress}}async refreshAlliance(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.alliance.refresh amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new u(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[s,n]=await this.accessControl(i);if(this.wdb.$parent)for(var a of this.wdb.$parent.config.alliances){a=a.split("|");var o=(x.fromString(a[4],this.network.type).isWitnessPubkeyhash()&&await s.send({outputs:[{address:a[4],value:r}]},n),N.decrypt({network:this.network.type,password:a[3],body:a[2]}));a=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([a[5],o.allianceNodeToken.pub]),{host:a[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(a,s.notifyKey.privateKey);await s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:a,sig:o,pub:s.notifyKey.publicKey.toString("hex")})})}}async refreshAllianceAsync(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.alliance.refresh.async amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new u(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[s,n]=await this.accessControl(i);if(this.wdb.$parent)for(var a of this.wdb.$parent.config.alliances){a=a.split("|");var o=(x.fromString(a[4],this.network.type).isWitnessPubkeyhash()&&s.send({outputs:[{address:a[4],value:r}]},n),N.decrypt({network:this.network.type,password:a[3],body:a[2]}));a=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([a[5],o.allianceNodeToken.pub]),{host:a[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(a,s.notifyKey.privateKey);s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:a,sig:o,pub:s.notifyKey.publicKey.toString("hex")})})}}async allianceDelete(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"sys.alliance.delete nodeid alliancename: 删除联盟节点证书 节点编号 盟友名称");var r=(t=new g([e])).uint(0,0),s=t.str(1,""),[n,e]=await this.accessControl(i,"");if(!r||!s)throw new u(c.MISC_ERROR,"节点编号、节点名称都不能为空");if(this.wdb.$parent)for(let e=0;e<this.wdb.$parent.config.alliances.length;e++){var a,o=this.wdb.$parent.config.alliances[e].split("|");o[0]==s&&o[1]==r&&(this.wdb.$parent.config.alliances.splice(e,1),await this.wdb.$parent.config.saveAsync(),o[5])&&(o={host:o[5],an:s,ai:r},a=p.signObj(o,n.notifyKey.privateKey),await n.commNotify({dst:n.notifyAddress,content:JSON.stringify({cmd:"peerdel",payload:o,sig:a,pub:n.notifyKey.publicKey.toString("hex")})}))}return t=(await n.getAccount(e)).getReceive().toString(),await this.wdb.logAudit({address:t,oper:"node.delete",hash:s+"."+r,index:0}),!0}async getAllianceNodeToken(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.alliance.gettoken (nodeid alliancename pubkey): 创建联盟节点信道密钥 (节点编号 盟友名称)");e=(t=new g([e])).uint(0,0);var r=t.str(1);t=t.str(2);if(this.wdb.$parent)return[i]=await this.accessControl(i),i=await i.createAllianceInfo(r,e,t),r||(this.wdb.$parent.config.identityKey?(i.prv=Buffer.from(this.wdb.$parent.config.identityKey,"hex"),i.pub=k.publicKeyCreate(i.prv,!0),i.address=x.fromWitnessPubkeyhash(w.hash160(i.pub),this.network.type).toString()):(this.wdb.$parent.pool.options.identityKey=i.prv,this.wdb.$parent.config.identityKey=i.prv.toString("hex"),await this.wdb.$parent.saveConfigAsync())),{network:this.network.type,alliancename:r,sn:e,prv:i.prv.toString("hex"),pub:i.pub.toString("hex"),address:i.address};throw new u(c.MISC_ERROR,"this cmd can only run on fullnode.")}async allianceUserCreate(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.alliance.user cid uid (alliancename): 创建企业用户 企业编号 用户编号 (盟友名称)");return this.$allianceUserCreate(e,i)}async $allianceUserCreate(e,t,i){var r=(e=new g([e])).str(0),s=e.uint(1);let n=null,a=null;return a=(e=e.str(2,""))?([t]=await this.accessControl(t),w.hash256(Buffer.concat([Buffer.from(e),t.master.key.privateKey]))):Buffer.from(this.wdb.$parent.config.alliancePrivateKey,"hex"),e=S.fromPrivate(a,!0,this.network),(t=S.fromPrivate(w.hash256(Buffer.concat([Buffer.from(r+"-"+s),e.privateKey]),!0,this.network))).witness=!0,n=t.signData({cid:r,uid:s}),i&&(n.prvkey=t.privateKey.toString("hex")),n}async isReady(e){return this.wdb.isFull()}async shutdown(e,t){return this.wdb.$parent&&this.wdb.$parent.close().catch(e=>{setImmediate(()=>{throw e})}).finally(async()=>{await new Promise(e=>{setTimeout(e,1e4)}),process.exit(0)}),"Stopping."}async stop(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"sys.walletdb.stop");return this.wdb.close(),"Stopping walletdb..."}async destroyWalletDb(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"sys.walletdb.destroy: 删除钱包数据库");return await this.wdb.close(),await this.wdb.destroy(),"Destroyed."}async createWalletDb(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"sys.walletdb.create: 删除原有钱包数据库并重建");return await this.wdb.close(),await this.wdb.destroy(),await this.wdb.open(),"Created."}async fundRawTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'tx.fund.admin "hexstring" ( options openid )');const r=new g([e]);var[t,e]=await this.accessControl(i,r.str(2,"")),s=(i=r.buf(0),r.obj(1));if(!i)throw new u(c.TYPE_ERROR,"Invalid hex string.");if(0===(i=E.fromRaw(i)).outputs.length)throw new u(c.INVALID_PARAMETER,"TX must have at least one output.");let n=null,a=null;if(s){const e=new g([s]);n=e.ufixed("feeRate",8),a=(a=e.str("changeAddress"))&&o.parseAddress(a,this.network)}return await t.fund(i,{rate:n,changeAddress:a,account:e}),{hex:i.toRaw().toString("hex"),changepos:i.changeIndex,fee:y.btc(i.getFee(),!0)}}async dumpPrivKey(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"key.export.private address [account]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0,"");if(!await e.belongToAccount(i,t))throw new u(c.MISC_ERROR,"Invald Account.");if(i=o.parseHash(t,this.network),t=await e.getPrivateKey(i))return t.toSecret();throw new u(c.MISC_ERROR,"Key not found.")}async exportMnemonic(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,"wallet.exportmnemonic.admin password: 备份钱包助记符 备份密码");t=new g([e]);var[e,i]=await this.accessControl(i);if(!(t=t.str(0)))throw new u(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid password");if("primary"==e.id&&"default"!=i)throw new u(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid Account");return i={body:{phrase:e.master.mnemonic.getPhrase(),language:e.master.mnemonic.language,passphrase:e.master.mnemonic.passphrase},password:t,network:this.network,file:`./${this.network.type}-wallet${e.db.options.spv?"-spv":""}.keystore`},this.wdb.$parent&&(i.body.awardAddress=this.wdb.$parent.config.coinbaseAddress),await N.writeEncryptFile(i),N.encrypt(i)}async importMnemonic(e,t,i){if(t||2!==e.length)throw new u(c.MISC_ERROR,"wallet.importmnemonic.admin encrypt password: 导入钱包助记符 备份文本 备份密码");var r;t=new g([e]);let s=N.decrypt({body:t.str(0),password:t.str(1),network:this.network});for(r of("string"==typeof s&&(s=JSON.parse(s)),this.wdb.$parent&&(s.awardAddress=this.wdb.$parent.config.coinbaseAddress),await this.wdb.getWallets()))if((await this.wdb.get(r)).master.mnemonic.getPhrase()===s.phrase)throw new u(c.MISC_ERROR,"wallet.importmnemonic.admin: 相同助记词已被使用");return(e=await this.wdb.ensure({id:M(),type:"pubkeyhash",m:1,n:1,mnemonic:s,passphrase:null,master:null,witness:!0,watchOnly:!1,accountKey:null}))?e.toJSON(!1):null}async dumpWallet(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"wallet.export filename (fragment): 导出钱包备份 备份文件全路径 (分片存储 true/false)");t=new g([e]);var[e,,]=await this.accessControl(i);if(i=t.str(0))return t=t.bool(1,!1),await e.exportToFile({file:i,fragment:t}),!0;throw new u(c.TYPE_ERROR,"Invalid filename.")}async dumpWallets(e,t,i){if(t)throw new u(c.MISC_ERROR,"wallet.exports.admin: 导出所有钱包备份");for(var r of await this.wdb.getWallets())await(await this.wdb.get(r)).exportToFile({file:`backup-${r}.txt`});return!0}async encryptWallet(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'wallet.encrypt "passphrase"');t=new g([e]);var[e,i]=await this.accessControl(i);t=t.str(0,"");if("primary"==e.id&&"default"!=i)throw new u(c.MISC_ERROR,"Invalid Account");if(e.master.encrypted)throw new u(c.WALLET_WRONG_ENC_STATE,"Already running with an encrypted wallet.");if(t.length<1)throw new u(c.MISC_ERROR,'wallet.encrypt "passphrase"');try{await e.setPassphrase(null,t)}catch(e){throw new u(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}return"wallet encrypted"}async getAccount(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'address.account "address"');t=new g([e]);var[e,i]=await this.accessControl(i);return("primary"!=e.id||"default"==i)&&(i=t.str(0,""),t=o.parseHash(i,this.network),i=await e.getPath(t))?i.name:""}async getAddressesByIndex(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,'address.index "index"');t=new g([e]);var[e,i]=await this.accessControl(i);if("primary"!=e.id||"default"==i){var r=t.uint(0);for(const t of await e.getPaths("default")){var s=t.toAddress();if(0==t.branch&&t.index==r)return s.toString(this.network)}}}async accessControl(e,t){let i=await this.wdb.get("primary");if(this.wdb.options.acl.isRoot(e.options.cid))"primary"!==e.options.wid?(i=await this.wdb.get(e.options.wid),t=null):"*"===(t=t||"default")&&(t=null);else if("primary"!==e.options.wid){if(!await i.belongToAccount(e.options.cid,e.options.wid))throw new u(c.TYPE_ERROR,"Invalid wid.");i=await this.wdb.get(e.options.wid),t=null}else t=e.options.cid;return await i.ensureAccount({name:t,witness:!0}),[i,t]}async getAddressesByAccount(e,t,i){if(t)throw new u(c.MISC_ERROR,'address.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[],s=[],n=[];for(const t of await e.getPaths(i)){var a=t.toAddress();(0==t.branch?r:1==t.branch?s:n).push(a.toString(this.network))}return[r,s,n]}async getAccountAddress(e,t,i){if(t)throw new u(c.MISC_ERROR,'address.receive "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.receive.getAddress("string")}async getAccountChangeAddress(e,t,i){if(t)throw new u(c.MISC_ERROR,"address.change account");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.change.getAddress("string")}async getAccountNestedAddress(e,t,i){if(t)throw new u(c.MISC_ERROR,'address.nested.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));if(t=await e.getAccount(i))return t.nested.getAddress("string")}async getBalance(e,t,i){if(t||3<e.length)throw new u(c.MISC_ERROR,'balance.confirmed ( "account" minconf includeWatchonly )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return 0;let s;return t=await e.getBalance(i),s=0<r?t.confirmed:t.unconfirmed,y.btc(s,!0)}async getBalanceLog(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,'balance.log "account" (height)');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0));t=t.uint(1,0);return e.queryBalanceLog(i,t)}async getBalanceAll(e,t,i){if(t||3<e.length)throw new u(c.MISC_ERROR,'balance.all ( "account" minconf includeWatchonly )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0));return(await e.getBalance(i)).toJSON()}async checkBalance(e,t,i){if(t)throw new u(c.MISC_ERROR,"balance.check");t=new g([e]);var[e,,]=await this.accessControl(i,t.str(0));return(await e.resetBalance()).toJSON()}async getUserToken(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"cp.user cid uid: 生成登录令牌 厂商编码 用户编码");e=(t=new g([e])).str(0),t=t.str(1);var[i]=await this.accessControl(i);return i.tokenCreate({cid:e,uid:t},t)}async masterkey(e,t,i){var[i,r]=await this.accessControl(i);if("primary"==i.id||"default"==r)return i.master.toJSON(!0)}async getHistory(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,"tx.history (page acct):查询交易历史记录 (页码 账号)");var r=(t=new g([e])).uint(0,1);if(r<1)throw new u(c.MISC_ERROR,"页面必须是大于0的数字");var[e,i]=await this.accessControl(i,t.str(1));t=await e.getHistory(i);s.sortTX(t);let n=0;var a,o=[];for(a of t){if(n<10*(r-1));else{if(n>=10*r)break;o.push(a)}n++}return i=await e.toDetails(o),(e={}).items=i,e.pageSize=10,e.pageNum=r,e.total=t.length,e}async sendSecret(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"comm.secret dst message (openid): 安全通信消息 收信地址 信息内容 (玩家账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0,"");t=t.str(1,"");if(o.parseAddress(r,this.network))return e.sendSecret(r,t,i);throw new u(c.TYPE_ERROR,"Invalid Destination Address.")}async calcHash(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"comm.hash content: 计算输入的哈希值");return t=new g([e]).str(0,""),w.hash256(Buffer.from(t)).toString("hex")}async commNotify(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"comm.notify addr content (openid): 发送点对点消息 地址 内容 (玩家账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0,"");t=t.obj(1,{});return e.commNotify({dst:r,content:t,account:i})}async scanContact(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'comm.scanContact "txid" ( index )');t=new g([e]);var[e,,]=await this.accessControl(i);i=t.hash(0),r(i,"Hash is required."),t=t.uint(1,-1);if(!i)throw new u(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(i))return this.wdb.scanContact(e.tx,t);throw new u(c.WALLET_ERROR,"TX not found.")}async listContact(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.listContact: 列表联系人");return t=new g([e]).array(0,[]),this.wdb.listContact(t,null,["address"])}async listNotify(e,t,i){if(t)throw new u(c.MISC_ERROR,"comm.listNotify (query): 通知列表 (查询条件,使用 account 参数可分账号查询)");return t=new g([e]).array(0,[]),this.wdb.listNotify(t)}async getReceivedByAccount(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'account.received "account" ( minconf )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.u32(1,0),s=this.wdb.curHeight,n=(t=await e.getPaths(i),new Set);for(const e of t)n.add(e.hash);let a=0,o=-1;for(const t of await e.getHistory(i)){var h=t.getDepth(s);if(!(h<r)){(-1===o||h<o)&&(o=h);for(const e of t.tx.outputs){var l=e.getHash("hex");l&&n.has(l)&&(a+=e.value)}}}return y.btc(a,!0)}async getReceivedByAddress(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'address.received "address" ( minconf )');t=new g([e]);var[e,,]=await this.accessControl(i),r=(i=t.str(0,""),t.u32(1,0)),s=this.wdb.curHeight,n=o.parseHash(i,this.network);let a=0;for(const t of await e.getHistory())if(!(t.getDepth(s)<r))for(const e of t.tx.outputs)e.getHash("hex")===n&&(a+=e.value);return y.btc(a,!0)}async _toWalletTX(e,t){var[e,,]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new u(c.WALLET_ERROR,"TX not found.");let r=!0;for(const e of i.inputs)if(e.path){r=!1;break}var s=[];let n=0,a=0;for(let e=0;e<i.outputs.length;e++){var o=i.outputs[e];o.path?1!==o.path.branch&&(s.push({account:o.path.name,address:o.address.toString(this.network),category:"receive",amount:y.btc(o.value,!0),label:o.path.name,vout:e}),a+=o.value):r||(s.push({account:"",address:o.address?o.address.toString(this.network):null,category:"send",amount:-y.btc(o.value,!0),fee:-y.btc(i.getFee(),!0),vout:e}),n+=o.value)}return{amount:y.btc(r?a:-n,!0),confirmations:i.confirmations,blockhash:i.block?d.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:d.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no",details:s,hex:i.tx.toRaw().toString("hex")}}async getTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'tx.get.wallet "txid" ( includeWatchonly )');t=new g([e]);var[e,,]=await this.accessControl(i),s=t.hash(0);r(s,"Hash is required."),t=t.bool(1,!1);if(!s)throw new u(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(s))return this._toWalletTX(i,e,t);throw new u(c.WALLET_ERROR,"TX not found.")}async abandonPending(e,t,i){if(t)throw new u(c.MISC_ERROR,"tx.abandonall.admin [account]: 废弃所有挂起的交易");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(0,""));for(const t of await r.getPending(e))try{await r.abandon(t.hash)}catch(e){this.logger.warning(e.message)}return null}async abandonTransaction(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'tx.abandon.admin "txid"');t=new g([e]);var[e,,]=await this.accessControl(i);if(!(i=t.hash(0)))throw new u(c.TYPE_ERROR,"Invalid parameter.");if(await e.abandon(i))return null;throw new u(c.WALLET_ERROR,"Transaction not in wallet.")}async getUnconfirmedBalance(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,"balance.unconfirmed");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=await e.getBalance(i);return y.btc(t.unconfirmed,!0)}async importPrivKey(e,t,i){if(t||e.length<1||4<e.length)throw new u(c.MISC_ERROR,'key.import.private account "privatekey" passphrase [rescan]');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.str(1),s=t.str(2);t=t.bool(3,!1);return(r=o.parseSecret(r,this.network)).witness=!0,await e.importKey(i,r,s),t&&await this.wdb.rescan(0),!0}async walletAuth(e,t,i){return!0}async importWallet(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,'wallet.import "filename" ( rescan )');t=new g([e]);var[,]=await this.accessControl(i);e=t.str(0),i=t.bool(1,!1);return await this.wdb.loadBackup(e),i&&await this.wdb.rescan(0),!0}async importAddress(e,t,i){if(t||e.length<1||4<e.length)throw new u(c.MISC_ERROR,"address.import account address [rescan p2sh]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));let r=t.str(1,"");var s=t.bool(2,!1);if(t.bool(3,!1)){let e=t.buf(0);if(!e)throw new u(c.TYPE_ERROR,"Invalid parameters.");e=v.fromRaw(e),e=v.createScript(e.hash160(),v.types.SCRIPTHASH),r=x.fromScript(e)}else r=o.parseAddress(r,this.network);return await e.importAddress(i,r),s&&await this.wdb.rescan(0),!0}async importPubkey(e,t,i){if(t||e.length<1||4<e.length)throw new u(c.MISC_ERROR,"key.import.public account pubkey [rescan]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=t.buf(1);t=t.bool(2,!1);if(r)return r=S.fromPublic(r,this.network),await e.importKey(i,r),t&&await this.wdb.rescan(0),!0;throw new u(c.TYPE_ERROR,"Invalid parameter.")}async listAccounts(e,t,i){if(t||2<e.length)throw new u(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[r]=await this.accessControl(i),s=t.u32(0,0),n=t.bool(1,!1),a={};for(const e of await r.getAccounts()){var o=await r.getBalance(e);let t=o.unconfirmed;0<s&&(t=o.confirmed),r.watchOnly!==n&&(t=0),a[e]=y.btc(t,!0)}return a}async listConservedUnspent(e,t,i){if(t||0<e.length)throw new u(c.MISC_ERROR,"coin.conserved.list: 查询已经保持的Unspent列表");var[t]=await this.accessControl(i),r=[];for(const e of t.getConserved())r.push({txid:e.txid(),vout:e.index});return r}async accountVirtualAdd(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"account.virtualadd.admin account amount: 虚增账户余额 账户名称 金额");t=new g([e]);var[e]=await this.accessControl(i,t.str(2,""));i=t.str(0),t=t.u64(1),i=await e.ensureIndex(i);return e.txdb.addAccountAmount(i,t),!0}async accountCheckAmount(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"account.checkamount account: 验证账户余额 账户名称");t=new g([e]);var[e]=await this.accessControl(i,t.str(2,""));i=t.str(0),t=await e.ensureIndex(i);return e.txdb.checkAccountAmount(t),!0}async listReceivedByAccount(e,t,i){if(t||3<e.length)throw new u(c.MISC_ERROR,"account.listreceived ( minconf includeempty includeWatchonly )");e=(t=new g([e])).u32(0,0);var r=t.bool(1,!1);t=t.bool(2,!1);return this._listReceived(i,e,r,t,!0)}async listReceivedByAddress(e,t,i){if(t||3<e.length)throw new u(c.MISC_ERROR,"address.received.list ( minconf includeempty includeWatchonly )");e=(t=new g([e])).u32(0,0);var r=t.bool(1,!1);t=t.bool(2,!1);return this._listReceived(i,e,r,t,!1)}async _listReceived(e,t,i,r,s){var[n]=await this.accessControl(e),a=(e=await n.getPaths(),this.wdb.curHeight);const o=new Map;for(const t of e){var c=t.toAddress();o.set(t.hash,{involvesWatchonly:n.watchOnly,address:c.toString(this.network),account:t.name,amount:0,confirmations:-1,label:""})}for(const e of await n.getHistory()){var h=e.getDepth(a);if(!(h<t))for(const t of e.tx.outputs){var u,l=t.getAddress();l&&(u=l.getHash("hex"),u=o.get(u))&&((-1===u.confirmations||h<u.confirmations)&&(u.confirmations=h),u.address=l.toString(this.network),u.amount+=t.value)}}let p=[];for(const e of o.values())p.push(e);if(s){const e=new Map;for(const t of p){var d=e.get(t.account);d?d.amount+=t.amount:(e.set(t.account,t),t.address=void 0)}p=[];for(const t of e.values())p.push(t)}var f=[];for(const t of p)if(i||0!==t.amount){-1===t.confirmations&&(t.confirmations=0);try{t.amount=y.btc(t.amount,!0),f.push(t)}catch(e){this.logger.error("invalid amount:entry(%s) msg(%s)",JSON.stringify(t),e.message)}}return f}async listSinceBlock(e,t,i){if(t)throw new u(c.MISC_ERROR,'tx.history.since ( "blockhash" target-confirmations includeWatchonly account)');var r=this.wdb.curHeight,[e,s]=(t=new g([e]),await this.accessControl(i,t.str(3,""))),n=t.hash(0),a=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return[];let o=-1;-1===(o=n&&(t=await this.client.getEntry(n))?t.height:o)&&(o=r);var h,l=[];let p;for(const t of await e.getHistory(s))t.height<o||t.getDepth(r)<a||((!p||t.height>p)&&(p=t),h=await this._toListTX(i,t),l.push(h));return{transactions:l,lastblock:p&&p.block?d.revHex(p.block):m.NULL_HASH}}async _toListTX(e,t){var[e]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new u(c.WALLET_ERROR,"TX not found.");let s=!0;for(const e of i.inputs)if(e.path){s=!1;break}let n,a,o,h,l,p,f=0,m=0;for(let e=0;e<i.outputs.length;e++){const t=i.outputs[e];t.path?1!==t.path.branch&&(m+=t.value,a=t,h=e):(f+=t.value,n=t,o=e)}return p=s?(l=a,h):(l=n,o),l||(r(!s),s=!0,l=a,p=h),{account:l.path?l.path.name:"",address:l.address?l.address.toString(this.network):null,category:s?"receive":"send",amount:y.btc(s?m:-f,!0),label:l.path?l.path.name:void 0,vout:p,confirmations:i.getDepth(),blockhash:i.block?d.revHex(i.block):null,blockindex:i.index,blocktime:i.time,txid:d.revHex(i.hash),walletconflicts:[],time:i.mtime,timereceived:i.mtime,"bip125-replaceable":"no"}}async listTransactions(e,t,i){if(t||4<e.length)throw new u(c.MISC_ERROR,'tx.list ( "account" count from includeWatchonly)');t=new g([e]);var[e,r]=await this.accessControl(i,t.str(0,"")),n=t.u32(1,10),a=t.u32(2,0);t=t.bool(3,!1);if(e.watchOnly!==t)return[];var o=await e.getHistory(r),h=(t=(s.sortTX(o),a+n),Math.min(t,o.length)),l=[];for(let e=a;e<h;e++){var p=o[e];p=await this._toListTX(i,p);l.push(p)}return l}async selectone(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"coin.selectone options (account)");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),s=t.obj(0,{}),n=[];for(const t of await r.getCoins(e)){var a=t.getDepth(this.wdb.curHeight),o=t.getAddress();if(o){var h=t.getHash("hex");if(h&&!t.isColored&&!(s.value&&t.value<s.value||t.coinbase&&0<t.height&&this.wdb.curHeight<t.height+b.COINBASE_MATURITY)&&(h=await r.getKey(h),n.push({txid:t.txid(),vout:t.index,address:o?o.toString(this.network):null,account:h?h.name:void 0,redeemScript:h&&h.script?h.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:y.btc(t.value,!0),confirmations:a,spendable:!r.isConserved(t),solvable:!0}),s.len&&n.length>=s.len))break}}return n}async listUnspent(e,t,i){if(t||4<e.length)throw new u(c.MISC_ERROR,'coin.list ( minconf maxconf ["address", account] )');const r=new g([e]);var[n,t]=await this.accessControl(i,r.str(3,"")),a=r.u32(0,1),h=r.u32(1,9999999),l=r.array(2),p=this.wdb.curHeight,d=new Set;if(l&&0<l.length){const e=new g([l]);for(let t=0;t<l.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(d.has(f))throw new u(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await n.getCoins(t);var m,v,b,w=(s.sortCoins(e),[]);for(const t of e)t.isColored||(m=t.getDepth(p))<a||h<m||((v=t.getAddress())?(b=t.getHash("hex"),l&&0<l.length&&(!b||!d.has(b))||(b=await n.getKey(b),w.push({txid:t.txid(),vout:t.index,address:v?v.toString(this.network):null,account:b?b.name:void 0,redeemScript:b&&b.script?b.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:y.btc(t.value,!0),confirmations:m,spendable:!n.isConserved(t),solvable:!0}))):this.logger.error("mistaken coin: miss address",t.hash,t.index));return w}async checkUnspent(e,t,i){if(t)throw new u(c.MISC_ERROR,"coin.check (account)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[];if(this.wdb.$parent)for(const t of await e.getCoins(i))await this.wdb.$parent.getCoin(t.hash,t.index)||r.push(t.txid(),t.index);return r}async listProp(e,t,i){if(t||4<e.length)throw new u(c.MISC_ERROR,"prop.wallet.byaddress ( minconf maxconf [address, account] )");const r=new g([e]);var[n,t]=await this.accessControl(i,r.str(3,"")),a=r.u32(0,1),h=r.u32(1,9999999),l=r.array(2),p=this.wdb.curHeight,d=new Set;if(l){const e=new g([l]);for(let t=0;t<l.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(d.has(f))throw new u(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await n.getCoins(t);var m=(s.sortCoins(e),[]);for(const t of e){var v,b,w,k=t.getDepth(p);k<a||h<k||(v=t.getAddress())&&(b=t.getHash("hex"),!l||b&&d.has(b))&&(b=await n.getKey(b),w=t.getReturnData([L.OP_PROPCREATE,L.OP_PROPCREATE]))&&m.push({txid:t.txid(),vout:t.index,address:v?v.toString(this.network):null,account:b?b.name:void 0,amount:y.btc(t.value,!0),confirmations:k,spendable:!n.isConserved(t),solvable:!0,nd:w})}return m}async listPropByOid(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.wallet.byoid oid");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),n=t.str(0),a=this.wdb.curHeight,o=(i=await r.getCoins(e),s.sortCoins(i),[]);for(const e of i){var h,l,p,d=e.getDepth(a);d<0||9999999<d||(h=e.getAddress())&&(l=e.getHash("hex"),l=await r.getKey(l),p=e.getReturnData([L.OP_PROPCREATE,L.OP_PROPEXCHANGE]))&&p.oid==n&&o.push({txid:e.txid(),vout:e.index,address:h?h.toString(this.network):null,account:l?l.name:void 0,amount:y.btc(e.value,!0),confirmations:d,spendable:!r.isConserved(e),solvable:!0,nd:p})}return{list:o,count:o.length}}async listLockedUnspent(e,t,i){if(t||2<e.length)throw new u(c.MISC_ERROR,'coin.list.locked ["address", account]');const r=new g([e]);var[n,t]=await this.accessControl(i,r.str(1,"")),a=r.array(0),h=this.wdb.curHeight,l=d.now(),p=new Set;if(a){const e=new g([a]);for(let t=0;t<a.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(p.has(f))throw new u(c.INVALID_PARAMETER,"Duplicate address.");p.add(f)}}let m;m=account?await n.getCoins(t):n.getLockedCoins(),s.sortCoins(m);var v,b,w,k,x,S,_=[];for(const e of m)(e.lockedByLocktime(h,l)||e.lockedBySequence(h,l))&&(v=e.getAddress())&&(b=e.getDepth(h),S=e.getHash("hex"),!a||S&&p.has(S))&&([w,k,x]=e.getLockStatus(),S=await n.getKey(S),_.push({txid:e.txid(),vout:e.index,address:v?v.toString(this.network):null,account:S?S.name:void 0,redeemScript:S&&S.script?S.script.toJSON():void 0,scriptPubKey:e.script.toJSON(),amount:y.btc(e.value,!0),confirmations:b,spendable:!1,solvable:!0,locktype:w,lockheight:k,locktime:x}));return _}async listOperUnspent(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,'coin.conserved.oper.list unlock ([{"txid":"txid","vout":n},...]) 保持/解除保持一组UTXO: true/false [{"txid": "交易id","vout": "输出序号"}]');const r=new g([e]);var[s]=await this.accessControl(i),n=r.bool(0,!1);if(!(t=r.array(1)))throw new u(c.TYPE_ERROR,"Invalid parameter.");for(const e of t){const t=new g([e]);var a=t.hash("txid"),o=t.u32("vout");if(null==a||null==o)throw new u(c.INVALID_PARAMETER,"Invalid parameter.");a=new R(a,o),n?s.unConserveCoin(a):s.conserveCoin(a)}return!0}async setTXFee(e,t,i){if(t||e.length<1||1<e.length)throw new u(c.MISC_ERROR,"sys.setfee rate");if(null==(t=new g([e]).ufixed(0,8)))throw new u(c.TYPE_ERROR,"Invalid parameter.");return this.wdb.feeRate=t,!0}async signMessage(e,t,i){if(t||2!==e.length)throw new u(c.MISC_ERROR,'sys.message.sign "address" "message"');t=new g([e]);var[e]=await this.accessControl(i);if(!e.master.key)throw new u(c.WALLET_UNLOCK_NEEDED,"Wallet is locked.");i=t.str(0,""),i=o.parseHash(i,this.network);if(e=await e.getKey(i))return i=t.str(1,""),e.sign(w.hash256(Buffer.from(h+i,"utf8"))).toString("base64");throw new u(c.WALLET_ERROR,"Address not found.")}async changePassphrase(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,'wallet.changepassphrase "oldpassphrase" "newpassphrase"');t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0,""),t=t.str(1,"");if(!e.master.encrypted)throw new u(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(i.length<1||t.length<1)throw new u(c.INVALID_PARAMETER,"Invalid parameter");return await e.setPassphrase(i,t),null}async unlock(e,t,i){var r=new g([e]),[i]=await this.accessControl(i),s=r.str(0);r=r.u32(1,60);if(t||i.master.encrypted&&0==e.length)throw new u(c.MISC_ERROR,'wallet.unlock "passphrase" timeout');if(!i.master.encrypted)throw new u(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(s.length<1)throw new u(c.INVALID_PARAMETER,"Invalid parameter");if(null==r)throw new u(c.TYPE_ERROR,"Invalid parameter");return await i.unlock(s,r),null}async decryptWallet(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'wallet.decrypt "passphrase"');t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0,"");if(!e.master.encrypted)throw new u(c.WALLET_WRONG_ENC_STATE,"Running with an decrypted wallet.");if(i.length<1)throw new u(c.MISC_ERROR,'wallet.decrypt "passphrase"');try{await e.setPassphrase(i)}catch(e){throw new u(c.WALLET_ENCRYPTION_FAILED,"Decryption failed.")}return"wallet decrypted"}async importPrunedFunds(e,t,i){if(t||e.length<2||3<e.length)throw new u(c.MISC_ERROR,'tx.importprunedfunds.admin "rawtransaction" "txoutproof" ( "label" )');if(e=(t=new g([e])).buf(0),t=t.buf(1),!e||!t)throw new u(c.TYPE_ERROR,"Invalid parameter.");e=A.fromRaw(e);var r=(t=_.fromRaw(t)).hash("hex");if(!t.verify())throw new u(c.VERIFY_ERROR,"Invalid proof.");if(!t.hasTX(e.hash("hex")))throw new u(c.VERIFY_ERROR,"Invalid proof.");var s=await this.client.getEntry(r);if(-1===s)throw new u(c.VERIFY_ERROR,"Invalid proof.");if(r={hash:r,time:t.time,mtp:t.mtp,height:s},await this.wdb.addTX(e,r))return null;throw new u(c.WALLET_ERROR,"No tracked address for TX.")}async removePrunedFunds(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,'tx.removeprunedfunds.admin "txid"');t=new g([e]);var[e]=await this.accessControl(i);if(!(i=t.hash(0)))throw new u(c.TYPE_ERROR,"Invalid parameter.");if(await e.remove(i))return null;throw new u(c.WALLET_ERROR,"Transaction not in wallet.")}async getWallets(e,t,i){return this.wdb.getWallets()}async getWalletBlock(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"wallet.block height");t=new g([e]);var[e]=await this.accessControl(i);i=t.uint(0);return(t=await e.getBlock(i))?t.toJSON():null}async getWalletLayoutH(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"wallet.layouth height");return t=new g([e]).uint(0),(e=await this.wdb.getBlock(t))?e.toJSON():null}async getWalletInfo(e,t,i){if(t)throw new u(c.MISC_ERROR,"wallet.info");return((t=new g([e]).str(0,""))?await this.wdb.get(t):(await this.accessControl(i))[0]).toJSON(!1)}async scRegister(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"sc.register options (account): 发布合约 合约参数列表 (子账户)");t=new g([e]);var[r,s]=await this.accessControl(i,t.str(1,""));let n=t.obj(0);if(!n)throw new u(c.MISC_ERROR,"sc.register: options is null");let a=1e5;switch(n.oper){case"change":if(n.oper=I.scState,!n.dst||!n.state)throw new u(c.TYPE_ERROR,"sc.register: dst or state is null.");if(!this.wdb.$parent)throw new u(c.TYPE_ERROR,"sc.register: not support this operation.");var o=await this.wdb.$parent.chain.db.getSCList([["options.dst",n.dst]]);if(!o||0==o.list.length)throw new u(c.TYPE_ERROR,"sc.register: contract not exist.");switch(o.list[0].options.state){case j.Normal:if(n.state!=j.Frozen&&n.state!=j.Destroy)throw new u(c.TYPE_ERROR,"Contract State Error");break;case j.Frozen:if(n.state!=j.Normal&&n.state!=j.Destroy)throw new u(c.TYPE_ERROR,"Contract State Error");break;default:throw new u(c.TYPE_ERROR,"Contract State Error")}if(n.addr=o.list[0].options.addr,await r.belongToAccount(s,n.addr))break;throw new u(c.MISC_ERROR,"sc.register: Invald Account.");case"update":if(n.oper=I.scUpdate,!n.dst)throw new u(c.TYPE_ERROR,"sc.register: dst is null.");if(!this.wdb.$parent)throw new u(c.TYPE_ERROR,"sc.register: not support this operation.");if(!(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",n.dst]]))||0==o.list.length)throw new u(c.TYPE_ERROR,"sc.register: contract not exist.");if(o.list[0].options.state!=j.Normal)throw new u(c.TYPE_ERROR,"sc.register: contract state error.");if(n.addr=o.list[0].options.addr,await r.belongToAccount(s,n.addr))break;throw new u(c.MISC_ERROR,"sc.register: Invald Account.");default:if(a=1e8,n.oper=I.scRegister,n.addr=(await r.createReceive(s)).getAddress("string"),n.dst=r.getSCAddress(d.hashInt(n.addr)).toString(),this.wdb.$parent&&(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",n.dst]]))&&0<o.list.length)throw new u(c.TYPE_ERROR,"sc.register: contract address conflict.")}return(e=(await r.getPrivateKey(n.addr)).signData(n)).data.sig=e.sig,n=e.data,i=await r.send({subtractFee:!1,sort:!1,outputs:[{address:n.dst,value:a}],comment:JSON.stringify(n)},s),await this.wdb.logAudit({address:n.addr,oper:n.oper,hash:i.hash("hex"),index:0}),n.txid=i.rhash(),n}async scRun(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,'sc.run str options (account): 调用合约 逗分参数字符串("合约收款地址,转账金额") 参数对象 (子账户)');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0).split(","),s=(t=t.obj(1,{}),r.shift());if(!this.wdb.$parent)throw new u(c.TYPE_ERROR,"sc.run: not support this operation.");var n=await this.wdb.$parent.chain.db.getSCList([["options.dst",s]]);if(!n||0==n.list.length)throw new u(c.TYPE_ERROR,"sc.run: contract not exist.");if(1!=n.list[0].options.state)throw new u(c.TYPE_ERROR,`sc.run: contract execute disabled(state ${n.list[0].options.state}).`);if(t.ver&&t.ver!=n.list[0].options.ver)throw new u(c.TYPE_ERROR,"sc.run: contract version inconsistency.");return n=(0|parseInt(r.shift()))>>>0,o.parseAddress(s,this.network),r=await e.send({subtractFee:!1,sort:!1,outputs:[{address:s,value:n}],comment:JSON.stringify({oper:"scrun",params:t})},i),s=await e.getAccount(i),await this.wdb.logAudit({address:s.receive.getAddress("string"),oper:I.scRun,hash:r.hash("hex"),index:0}),(await e.getDetails(r.hash("hex"))).toJSON()}async cpRegister(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,'cp.create name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(e,i,!1)}async cpRegisterAsync(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,'cp.create.async name "ip,addr,class,rate" (openid): 注册厂商 名称(不少于4个字符) "IP地址,注册地址,类别,媒体分成比例" (子账号)');return this.$cpRegister(e,i,!0)}async $cpRegister(e,t,i){e=new g([e]);var r=decodeURIComponent(e.str(0)),s=(o=e.str(1,"").split(","))[0],n=o[1],a=o[2],o=o[3]?parseInt(o[3]):15,[t,e]=await this.accessControl(t,e.str(2,"")),h=f.verifyDataFormat({name:r,ip:s,grate:o,cls:a});if(h)throw new u(c.MISC_ERROR,h);return h={cid:M(),oper:I.cpRegister,name:r,ip:s,grate:o,cls:a},await t.cpRegister(d.isBech32(n)?n:null,h,e,i),h}async cpChange(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,'cp.change cid "newname,ip,addr,class,rate" "openid": 修改厂商信息 CP编号 "新的名称,IP,新的注册地址,类别,分成比例" 授权账号');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),s=t.str(0),n=(t=decodeURIComponent(t.str(1,"")).split(","))[0],a=t[1];let o=t[2];var h=t[3];t=parseInt(t[4])||null;if(l=f.verifyDataFormat({name:n,ip:a,grate:t,cls:h}))throw new u(c.MISC_ERROR,l);o&&(o=x.fromString(o),r(o instanceof x,"Not an address."));var l={cid:s,newName:n,ip:a,addr:o,grate:t,cls:h},[,,]=await e.cpChange(l,i);return l.addr=l.addr.toString(),l}async cpQuery(e,t,i){if(t)throw new u(c.MISC_ERROR,"cp.query (conditions account): 查询钱包中的厂商列表 (复合条件 子帐号)");t=new g([e]);var r,[s,n]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=s.db.cpList.query(e);for(r of i.list)r.owned=await s.belongToAccount(n,r.current.address);return i}async cpQueryRemote(e,t,i){if(t)throw new u(c.MISC_ERROR,"cp.query.remote conditions: 查询厂商列表 (复合条件)");t=new g([e]);var r,[s,n]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=await s.db.client.execute("cp.remoteQuery",[e]);for(r of i.list)r.owned=await s.belongToAccount(n,r.current.address);return i}async cpMine(e,t,i){if(t)throw new u(c.MISC_ERROR,"cp.mine (conditions account): 查询钱包中归属当前操作员/指定账户的厂商列表 (复合条件 子帐号)");t=new g([e]);let[r,s]=await this.accessControl(i,t.str(1,""));return(e=t.array(0,[])).push(["size",-1]),(await r.db.cpList.predict(async(e,t)=>r.belongToAccount(s,t.current.address))).query(e)}async htlcSuggest(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.suggest params [account]: 发起HTLC 参数对象({alice, bob, amount, rate}) [子账户]");e=(t=new g([e])).obj(0,{});var r,[i,t]=await this.accessControl(i,t.str(1,""));if(!e.ab)throw new u(c.MISC_ERROR,"htlc.suggest: params.ab(alice bchain address) is null");if(!Number.isInteger(e.amount))throw new u(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.amount=parseInt(e.amount),e.amount<0||e.amount>1e4*b.COIN)throw new u(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.rate=parseFloat(e.rate),e.rate<0||e.amount*e.rate>b.MAX_MONEY)throw new u(c.MISC_ERROR,"htlc.suggest: illegal params.rate");if(e.target)return r=(await i.createReceive(t)).getAddress().toString(this.network),e={amount:e.amount,rate:e.rate,dst:e.target,aa:x.fromString(r).hash,ab:x.fromString(e.ab).hash,ba:x.fromString(e.ba).hash},[i]=await i.sendContracts([e],t,O),i?{txid:i.rhash(),aa:r}:null;throw new u(c.MISC_ERROR,"htlc.suggest: params.target is null")}async htlcAssent(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.assent params({txid}) [account]: 响应HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.obj(0,{});if(!Number.isInteger(t.amount))throw new u(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new u(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.rate=parseFloat(t.rate),t.rate<0||t.amount*t.rate>b.MAX_MONEY)throw new u(c.MISC_ERROR,"htlc.assent: illegal params.rate");var r=(await e.createReceive(i)).getAddress().toString(this.network),[t]=(r={src:t.src,dst:t.dst,hash:t.hash,index:t.index,ab:Buffer.from(t.ab,"hex"),ba:Buffer.from(t.ba,"hex"),bb:x.fromString(r).hash,amount:t.amount*t.rate},await e.sendContracts([r],i,C));return t?{txid:t.rhash()}:null}async htlcSuggestDeal(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.suggest.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={suggest:!0,hash:d.revHex(t.txid),index:t.index,sa:t.sa},await e.htlcDeal(t,i));return e?{txid:e.rhash()}:null}async htlcQuery(e,t,i){if(t)throw new u(c.MISC_ERROR,"htlc.query query: 条件查询HTLC合约 条件数组");return(t=new g([e]).array(0,[])).push(["pst","!=",T.Cancel]),this.wdb.htlcList.query(t)}async htlcAssentDeal(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.assent.deal params({txid,index,sa}) [account]: 兑付HTLC 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={hash:d.revHex(t.txid),index:t.index,sa:t.sa},await e.htlcDeal(t,i));return e?{txid:e.rhash()}:null}async htlcAssentCancel(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.assent.cancel params({txid, index, master}) [account]: 取消HTLC应答 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={hash:d.revHex(t.txid),index:t.index,master:t.bb},await e.htlcCancel(t,i));return e?{txid:e.rhash()}:null}async htlcSuggestCancel(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"htlc.suggest.cancel params({txid, index, sa, master}) [account]: 取消HTLC请求 参数对象 [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.obj(0),t={suggest:!0,hash:d.revHex(t.txid),index:t.index,sa:t.sa,master:t.aa},await e.htlcCancel(t,i));return e?{txid:e.rhash()}:null}async sendComment(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"comm.comment params [account]: 发起附言交易 参数对象({body, bob}) [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.obj(0,{});if(!Number.isInteger(t.amount))throw new u(c.MISC_ERROR,"comm.comment: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new u(c.MISC_ERROR,"comm.comment: illegal params.amount");var r={bob:t.bob,body:t.body,amount:t.amount};t.alice||(t.alice=e.getAddress(),i&&(s=await e.createReceive(i),t.alice=s.getAddress()));var s=(await e.getPrivateKey(t.alice)).signData(r),[t]=(s.data.sig=s.sig,await e.sendContracts([s.data],i,B));return t?{txid:t.rhash()}:null}async commentQuery(e,t,i){if(t)throw new u(c.MISC_ERROR,"comm.comment.query query: 条件查询附言输出 条件数组");return t=new g([e]).array(0,[]),this.wdb.commentList.query(t)}async contractExecute(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"contract.execute tid master: 执行交易对合约 交易编号 执行方(1-发起人,2-承兑人)");t=new g([e]);var[e]=await this.accessControl(i),[e,,]=(i=t.str(0),t=t.u32(1,2),await e.contractExecute(i,t));return e.toJSON()}async contractPromise(e,t,i){if(t||e.length<1||2<e.length)throw new u(c.MISC_ERROR,"contract.promise tid [openid]: 签署交易对合约 交易编号(type.address) [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),[e,,]=(t=t.str(0),await e.contractPromise(t,i));return e.toJSON()}async contractOfMine(e,t,i){if(t||e.length<1||3<e.length)throw new u(c.MISC_ERROR,"contract.mine type page [openid]: 获取已签署交易对合约列表 交易对类型 页码 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.uint(0,1);t=t.uint(1,1);return e.db.getContracts(r,t,i)}async contractCreate(e,t,i){if(t||e.length<4||5<e.length)throw new u(c.MISC_ERROR,"contract.create type src dst addr [openid] : 发布一个交易对合约 交易对类型 出让游戏金数值 换取兑换币数值 兑换币收款地址 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(4,"")),r=t.u64(0),s=t.u64(1),n=t.u64(2),[e,,]=(t=t.str(3),await e.contractCreate(r,s,n,t,i));return e.toJSON()}async propGet(e,t,i){if(t)throw new u(c.MISC_ERROR,"prop.wallet.byid pid: 查询自己的物品 PID");return t=new g([e]).str(0,""),e=[],(t=await this.wdb.propList.getVp(t))&&t.pst!=P.Delete&&e.push(t),e}async propQuery(e,t,i){if(t)throw new u(c.MISC_ERROR,"prop.query query: 条件查询自己的物品 条件数组");t=new g([e]);var[e]=await this.accessControl(i,t.str(1,""));return(i=t.array(0,[])).push(["pst","!=",P.Delete]),(await e.getPropList()).query(i)}async mySaleList(e,t,i){if(t)throw new u(c.MISC_ERROR,"prop.query.auction (page acct): 查询自己拍卖的物品 (页码 账户)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.uint(0,1);return e.mySaleList(t,i)}async onSaleList(e,t,i){e=new g([e]);var[i,r]=await this.accessControl(i,e.str(1,""));e=e.uint(0,1);return i.onSaleList(e,r)}async propBuy(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"prop.buy pid price [openid] : 竞拍道具 道具编号 出价 [子账号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0),[e,,]=(t=t.u64(1),await e.propBuy(r,t,i));return e.toJSON()}async propFound(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.found pid (openid): 熔铸道具 道具编号 (账号)");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new u(c.MISC_ERROR,"prop.found prop not exist");if(!await e.belongToAccount(i,t.current.address))throw new u(c.MISC_ERROR,"prop.found: current account not owned prop.");if(t.pst!=P.Ready)throw new u(c.MISC_ERROR,"prop.found prop can not be found on current status");var[e,,t]=await e.propFound(t.current.hash,t.current.index,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),index:0,cid:t.cid,pid:t.pid,oid:t.oid,gold:e.outputs[0].value}}async propSale(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"prop.sale pid fixedPrice [openid]: 拍卖道具 道具编号 一口价 [子帐号]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);if(!(r=await e.db.propList.getVp(r))||r.pst==P.Delete)throw new u(c.MISC_ERROR,"prop.sale prop not exist");if(r.pst!=P.Ready)throw new u(c.MISC_ERROR,"prop.sale prop cannt be sent on current status");t=t.u64(1,0);var[e,,]=await e.propSale(r.current.hash,r.current.index,t,i);return e.toJSON()}async propSendListAdmin(e,t,i){return this.propSendList(e,t,i,!0)}async propSendList(e,t,i,r=!1){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.sendlist (addr|txid|index)(n,) [openid]: 批量转移道具 道具数组(地址|交易ID|输出索引) [子账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,"")),s=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var n of t){var a,o;3<=(n=n.split("|")).length&&(a=n[0],o=new R(d.revHex(n[1]),parseInt(n[2])),4<=n.length?s.push([o,x.fromString(a),n[3]]):s.push([o,x.fromString(a)]))}var[t,,e]=await e.propExchangeList(s,i,r);if(t&&e){let i=t.hash("hex"),r=t.rhash();return e.map(e=>({hash:i,txid:r,cid:e.cid,pid:e.pid,oid:e.oid,gold:e.gold,addr:e.addr}))}}async propReceive(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.receive tx [account]: 捐赠接收函数 捐赠交易字符串 [接收账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));if(!(t=t.buf(0)))throw new u(c.TYPE_ERROR,"Invalid TX Info.");t=A.fromRaw(t);var[e,,t]=await e.propReceive(t,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,addr:t.simAddr,gaddr:t.gaddr}}async propDonate(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.donate pid [openid]: 捐赠道具函数 道具ID [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));t=t.str(0);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new u(c.MISC_ERROR,"prop not exist");if(t.pst!=P.Ready)throw new u(c.MISC_ERROR,"prop cannt be sent on current status");t=new R(t.current.hash,t.current.index);var[e,,t]=await e.propDonate(t,i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,raw:e.toRaw().toString("hex")}}async propExchange(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"prop.send addr pid [openid]: 转移道具函数 接收地址 物品编号 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.str(1);if(!(t=await e.db.propList.getVp(t))||t.pst==P.Delete)throw new u(c.MISC_ERROR,"prop.send prop not exist");if(t.pst!=P.Ready)throw new u(c.MISC_ERROR,"prop.send prop cannt be sent on current status");var[e,,t]=await e.propExchange(new R(t.current.hash,t.current.index),x.fromString(r),i);if(e&&t)return{hash:e.hash("hex"),txid:e.rhash(),cid:t.cid,pid:t.pid,oid:t.oid,gold:t.gold,addr:r}}async propCreateList(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"prop.createlist (cid|oid|gold|pid)(n,) [openid]: 批量创建道具 道具信息数组 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(1,""));let r=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var s of t)if(3<=(s=s.split("|")).length){var n=s[0],a=s[1],o=parseInt(s[2]);let e=null;4<=s.length&&(e=s[3]),o<b.MINPROPVALUE||r.push([n,a,o,e])}r=r.map(e=>{var[e,t,i,r]=e;return{oper:I.propCreate,cid:e,oid:t,gold:i,pid:r}});var[t,,]=await e.propCreate(r,i);return t?r:null}readImageAsBlob(e,t){l.readFile(e).then(i=>{var r=z.getType(F.basename(e));t(null,{hex:i.toString("hex"),type:r})}).catch(e=>{t(e,null)})}async inscriptionCreate(e,t,i){if(!(t||e.length<2)){t=new g([e]);var[e,r]=await this.accessControl(i,t.str(4,"")),s=t.str(0);let h=t.str(1);if((t=t.u64(2,b.MINPROPVALUE))<b.MINPROPVALUE)throw new u(c.PROP_MINVALUE,"prop.create: not a valid value");if(0<=h.indexOf("file:")){const e=h.replace("file:","")||"docs/eth.jpg";h=await new Promise(t=>{this.readImageAsBlob(e,(e,i)=>{e?console.error("Error reading inscription:",e):t(i)})})}else{if(!(0<=h.indexOf("data:")))throw new u(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]");h=JSON.parse(h.replace("data:",""))}var n,a=await e.createReceive(r),o=w.sha256(Buffer.from(JSON.stringify(h))).toString("hex");if(o=await this.caIssuePublic([JSON.stringify({blob:h,hash:o,height:0}),a.getAddress("string"),"",r],null,i))return a={oper:I.propCreate,cid:s,gold:t,type:"inscription",oid:o.erid},[i,n]=await e.propCreate([a],r),i?a:null}throw new u(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]")}async propCreate(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"prop.create cid oid gold pid (openid): 创建道具 厂商编码 道具类别码 含金量 道具编码(可填空) [账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(4,"")),r=t.str(0),s=t.str(1),n=t.u64(2,b.MINPROPVALUE);t=t.str(3,null);if(n<b.MINPROPVALUE)throw new u(c.PROP_MINVALUE,"prop.create: not a valid value");r={oper:I.propCreate,cid:r,oid:s,gold:n,pid:t};var[s,,]=await e.propCreate([r],i);return s?r:null}async walletLock(e,t,i){if(t)throw new u(c.MISC_ERROR,"wallet.lock [passphrase]");var[t]=await this.accessControl(i);if(!t.master.encrypted){if((i=new g([e]).str(0,"")).length<1)throw new u(c.MISC_ERROR,"Wallet is not encrypted, please run wallet.lock passphrase");try{await t.setPassphrase(null,i)}catch(e){throw new u(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}}return await t.lock(),null}async listMSTrans(e,t,i){if(t)throw new u(c.MISC_ERROR,"tx.mstrans");return t=new g([e]).str(0,""),this.wdb.listMSTrans(t)}async signMSTrans(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"tx.mstrans.sign txid");e=(t=new g([e])).str(0,"");var r=t.str(1,""),[i,t]=await this.accessControl(i,t.str(2,""));if(!(e=await this.wdb.db.get(n.ms(x.getHash(e,"hex"),r))))throw new u(c.MISC_ERROR,"tx.mstrans.sign txid");if(e=JSON.parse(e.toString()),!await i.belongToAccount(t,e.addr))throw new u(c.MISC_ERROR,"tx.mstrans.sign invalid account");var s,o=await this.wdb.get(e.addr);o&&o.account.type==a.types.MULTISIG&&((s=E.fromRaw(e.data,"hex")).view=await o.getCoinView(s),await o.sign(s),s.isSigned()?await o.sendMTX(s):await i.send({subtractFee:!1,sort:!1,outputs:[{address:e.contract,value:1e4}],comment:JSON.stringify({oper:"scrun",params:{oper:"sign",addr:e.addr,tx:s.toRaw().toString("hex")}})},t),await this.wdb.delMSTrans(e.addr,r))}async resendWalletTransactions(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"tx.resend.admin");var[t]=await this.accessControl(i),r=[];for(const e of await t.resend())r.push(e.txid());return r}async resend(e,t,i){if(t||0!==e.length)throw new u(c.MISC_ERROR,"tx.resendall.admin: 重发挂起交易");var r=await this.wdb.resend();if(r)for(var s of Object.keys(r))if(s)for(const e of r[s])await this.wdb.send(e);return!0}async rescan(e,t,i){if(t)throw new u(c.MISC_ERROR,'wallet.rescan ( "height" )');return t=new g([e]).u32(0),await this.wdb.rescan(t),this.logger.info("Rescanning..."),!0}async createAddress(e,t,i){if(t||2<e.length)throw new u(c.MISC_ERROR,'address.create ( "account" "uid" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.u32(1,0);return(e=await e.createReceive(i,t))?e.toJSON():null}async calcAddress(e,t,i){if(t||e.length<3)throw new u(c.MISC_ERROR,"address.calc account(must be typeof number) branch index");t=new g([e]);let[s,n]=await this.accessControl(i,t.int(0,0));return e=t.u32(1,0),i=t.u32(2,0),"default"==n&&(n=0),t=(await s.deriveKey(n,e,i,s.master)).toJSON(),i=(e=await s.deriveKey(n,e,i))?e.toJSON():null,r(t.address==i.address,"address derived from prv not equals which derived from pub."),i}async createAddressAdmin(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,'address.create.admin ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createReceive(i,0,e.master))?t.toJSON(!0):null}async createChange(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,'address.change.create ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createChange(i))?t.toJSON():null}async createNested(e,t,i){if(t||1<e.length)throw new u(c.MISC_ERROR,'address.nested.create ( "account" )');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.createNested(i))?t.toJSON():null}async mkwallet(e,t,i){var r=(e=new g([e])).str(4);if(r)for(var s of await this.wdb.getWallets())if((await this.wdb.get(s)).master.mnemonic.getPhrase()===body.phrase)throw new u(c.MISC_ERROR,"wallet.create: 相同助记词已被使用");return(r=await this.wdb.ensure({id:M(),type:e.str(1),m:e.u32(2),n:e.u32(3),mnemonic:r,passphrase:e.str(5),master:e.str(6),witness:e.bool(7),watchOnly:e.bool(8),accountKey:e.str(9)}))?r.toJSON(!1):null}async accountGet(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"account.get account: 查询账户");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));return(t=await e.getAccount(i))?t.toJSON():null}async getPending(e,t,i){if(t)throw new u(c.MISC_ERROR,"tx.pending [account]: 查询挂起的交易");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=(t=await e.getPending(i),s.sortTX(t),[]);for(const i of await e.toDetails(t))r.push(i.toJSON());return r}async getPendingItem(e,t,i){var r,s=(e=new g([e])).hash(0,""),[n,i]=await this.accessControl(i,e.str(1,""));for(r of await n.getPending(i))if(r.hash==s)return(r=await n.toDetails(r)).toJSON()}async getPendingHash(e,t,i){e=new g([e]);var[i,e]=await this.accessControl(i,e.str(0,"")),r=(e=await i.getPending(e),s.sortTX(e),[]);for(const t of await i.toDetails(e))r.push(d.revHex(t.hash));return r}async getPendingCount(e,t,i){if(t)throw new u(c.MISC_ERROR,"tx.pending.count [account]: 查询挂起的交易数");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=await e.ensureIndex(i);return(await e.txdb.getPendingHashes(t)).length}async accountCreate(e,t,i){e=new g([e]);var r,[i]=await this.accessControl(i),s=e.obj(0);e=e.str(1),s={name:(s=new g([s])).str("name"),witness:s.bool("witness",!0),type:s.str("type","pubkeyhash"),m:s.u32("m",1),n:s.u32("n",1),watchOnly:s.bool("watch",!1),accountKey:s.str("key",null),lookahead:s.u32("lookahead",10)};try{let t=await i.getAccount(s.name);return t?t.toJSON():((r=(t=await i.createAccount(s,e)).toJSON()).isNew=!0,r)}catch(t){return null}}async getblocks(e,t,i){if(t)throw new u(c.MISC_ERROR,"wallet.blocks");var[t]=await this.accessControl(i);return await t.getBlocks()}async getKey(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,"key.export.public address: 查询地址的密钥");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.getKey(i)))?t.toJSON():null}async getPrivKey(e,t,i){if(t||1!==e.length)throw new u(c.MISC_ERROR,"address.key.admin address: 查询地址的密钥");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.getKey(i)))?t.toJSON(!0):null}async getwif(e,t,i){if(t||1!=e.length)throw new u(c.MISC_ERROR,"address.wif.admin address: 查询地址对应的私钥 地址");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0),t=t.str(1);return(e=(r(i,"Address is required."),await e.getPrivateKey(i,t)))?e.toSecret():null}async hasAddress(e,t,i){if(t||1!=e.length)throw new u(c.MISC_ERROR,"address.has address: 查询钱包是否包含一个地址 地址");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0);return(t=(r(i,"Address is required."),await e.hasAddress(i)))||!1}async getCoin(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),s=e.hash(0);e=e.u32(1);return(i=(r(s,"Hash is required."),r(null!=e,"Index is required."),await i.getCoin(s,e)))?i.getJSON(this.network):null}async getSpender(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),s=e.hash(0);e=e.u32(1);return(i=(r(s,"Hash is required."),r(null!=e,"Index is required."),await i.txdb.getSpender(s,e)))?{hash:d.revHex(i.hash),index:i.index}:null}async getSpent(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),s=e.hash(0);e=e.u32(1),r(s,"Hash is required."),r(null!=e,"Index is required."),i=await i.txdb.getSpentCoin({hash:s,index:e});return{hash:d.revHex(i.hash),index:i.index,value:i.value,height:i.height,version:i.version,time:i.time}}async getCoincacheSize(e,t,i){var[i]=await this.accessControl(i);return i.txdb.coinCache.size}async conserveCoin(e,t,i){if(t||2!=e.length)throw new u(c.MISC_ERROR,"coin.conserved.add txhash index: 新增需要保持的硬币: 交易Hash 输出序号");t=new g([e]);var[e]=await this.accessControl(i);i=t.hash(0),t=t.u32(1),r(i,"Hash is required."),r(null!=t,"Index is required."),i=new R(i,t);return e.conserveCoin(i),!0}async getConservedCoins(e,t,i){if(t||0<e.length)throw new u(c.MISC_ERROR,"coin.conserved.get: 查询已经保持的Coin列表");var[t]=await this.accessControl(i),r=[];for(const e of t.getConserved())r.push(e.toJSON());return r}async unConserveCoin(e,t,i){if(t||2!=e.length)throw new u(c.MISC_ERROR,"coin.conserved.del: 减少需要保持的硬币: 交易Hash 输出序号");t=new g([e]);var[e]=await this.accessControl(i);i=t.hash(0),t=t.u32(1),r(i,"Hash is required."),r(null!=t,"Index is required."),i=new R(i,t);return e.unConserveCoin(i),!0}async addShared(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"key.shared.add [account] key: 新增共享公钥 [账号] 公钥");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.str(1);return await e.addSharedKey(i,t),!0}async removeShared(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"key.shared.del [account] key: 删除共享公钥 [账号] 公钥");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,""));t=t.str(1);return await e.removeSharedKey(i,t),!0}async zap(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.zap [age]: 移除挂起交易 挂起时长(默认三天)");t=new g([e]);var[e]=await this.accessControl(i);i=t.str(0),t=t.u32(1,259200);return r(t,"Age is required."),await e.zap(i,t),!0}async sendOracle(e,t,i){if(!(t||e.length<3||4<e.length)){t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0,null),s=t.str(1,null);if(null==(t=t.u64(2)))throw new u(c.TYPE_ERROR,"Invalid parameter.");if(r&&s)return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:JSON.stringify({oper:I.vote,type:"oracle",k:r,v:s})},r=await e.send(t,i),(await e.getDetails(r.hash("hex"))).toJSON()}throw new u(c.MISC_ERROR,"oracle.send k v amount [openid]")}async sendVote(e,t,i){if(t||e.length<2||3<e.length)throw new u(c.MISC_ERROR,"vote.send addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),s=t.str(0);if(null==(t=t.u64(1)))throw new u(c.TYPE_ERROR,"Invalid parameter.");for(r of s.split(","))if(!o.parseAddress(r,this.network))throw new u(c.TYPE_ERROR,"Invalid address.");return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${I.vote}", "type": "mine", "ca": "${s}"}`},s=await e.send(t,i),(await e.getDetails(s.hash("hex"))).toJSON()}async sendVoteAsync(e,t,i){if(t||e.length<2||3<e.length)throw new u(c.MISC_ERROR,"vote.send.async addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),s=t.str(0);if(null==(t=t.u64(1)))throw new u(c.TYPE_ERROR,"Invalid parameter.");for(r of s.split(","))if(!o.parseAddress(r,this.network))throw new u(c.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${I.vote}", "type": "mine", "ca": "${s}"}`},e.send(t,i)}async sendTX(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"tx.send addr amount [openid]:发送交易 地址 金额 [发起账户]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new u(c.MISC_ERROR,"Alliance Cert Invalid.");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.u64(1),r=await e.send({outputs:[{address:r,value:t}]},i);return(await e.getDetails(r.hash("hex"))).toJSON()}async sendTXAsync(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"tx.send.async addr amount [openid]:发送交易 地址 金额 [发起账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(2,"")),r=t.str(0);t=t.u64(1);e.send({outputs:[{address:r,value:t}]},i)}async signTX(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"tx.sign.admin txdata [sendnow passphrase]: 对交易签名/发送 交易原始数据 [立即发送 解锁密码]");t=new g([e]);var[e]=await this.accessControl(i),s=(i=t.buf(0),r(i,"TX is required."),t.bool(1,!1));t=t.str(2);(i=E.fromRaw(i)).view=await e.getCoinView(i),await e.sign(i,t);let n=null;return n=(s&&i.isSigned()?await e.sendMTX(i):i).getJSON(this.network),e.account.type==a.types.MULTISIG&&(t=i.getMultisig(this.network),n.ms={m:t.m,n:t.n,c:t.c}),n}async createTX(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"tx.create options outputs [openid]: 创建交易 参数对象 输出数组 [子账号]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new u(c.MISC_ERROR,"Alliance Cert Invalid.");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(2,""));i=t.obj(0),t=t.array(1);if(Array.isArray(i.in))for(var s of i.in)s.hash=d.revHex(s.hash);var n={comment:(i=new g([i])).obj("comment",null),sendnow:i.bool("sendnow",!0),account:i.str("account"),rate:i.u64("rate"),blocks:i.u32("blocks"),maxFee:i.u64("maxFee"),selection:i.str("selection"),smart:i.bool("smart"),subtractFee:i.bool("subtractFee"),subtractIndex:i.get("subtractIndex"),depth:i.u32(["confirmations","depth"]),inputs:i.array("in",null),outputs:[]};for(const e of t){var o=new g([e]),h={value:o.u64("value")};if(h.address=o.str("address"),!h.address){var l=o.str("account");if(l){await r.ensureAccount({name:l,witness:!0});var p=await r.createReceive(l);if(!p)throw new u(c.MISC_ERROR,`tx.create: account ${l} not exist`);h.address=p.getAddress("string")}}if((l=o.buf("script"))&&(h.script=v.fromRaw(l)),(p=o.str("locktype"))&&(o=o.u64("locktime",0))){if("no"!=p&&"clb"!=p&&"clt"!=p&&"csb"!=p&&"cst"!=p)throw new u(c.MISC_ERROR,'locktype should be "no"-不锁定 or "clb"-绝对高度锁定 or clt(绝对时间锁定) or "csb"-相对高度锁定 or "cst"-相对时间锁定 !');if(p==v.outputLockType.CHECKABSOLUTETIME&&o<=b.LOCKTIME_THRESHOLD)throw new u(c.MISC_ERROR,"lock absolute time should not less than 500000000!");if(p==v.outputLockType.CHECKABSOLUTEBLOCK&&o>b.LOCKTIME_THRESHOLD)throw new u(c.MISC_ERROR,"lock absolute block should not more than 500000000!");if((p==v.outputLockType.CHECKRELATIVEBLOCK||p==v.outputLockType.CHECKRELATIVETIME)&&65535<o)throw new u(c.MISC_ERROR,"lock relative block/time should not more than 65535!");h.locktype=p,h.locktime=o}n.outputs.push(h)}e&&(n.account=e);let f=null;return n.sendnow?(i=await r.send(n),f=(t=await r.getDetails(i.hash("hex"))).toJSON()):(e=await r.createTX(n),await r.sign(e),f=e.getJSON(this.network),r.account.type==a.types.MULTISIG&&(i=e.getMultisig(this.network),f.ms={m:i.m,n:i.n,c:i.c})),f}async getLast(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"tx.last account [limit]: 最近的交易 账号 [最大记录数]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0)),r=(t=t.u32(1),[]);i=await e.getLast(i,t);for(const t of await e.toDetails(i))r.push(t.toJSON());return r}async getRange(e,t,i){if(t||e.length<4)throw new u(c.MISC_ERROR,"tx.range account start end limit [reserve]: 指定时限内的交易 账号 开始时间 结束时间 最大记录数 [反转]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=(t={start:t.u32(1),end:t.u32(2),limit:t.u32(3),reverse:t.bool(4)},i=await e.getRange(i,t),[]);for(const t of await e.toDetails(i))r.push(t.toJSON());return r}async caUserStatus(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"ca.user.status cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),s=t.array(2,[]);let n=null;for(let e=0;e<s.length;e++){var a=s[e];a&&Array.isArray(a)?"alliancename"==a[0]&&(n=a[1],delete s[e]):delete s[e]}var[t]=await this.accessControl(i);e=await this.$allianceUserCreate([e,r,n],i);return s.push(["pubkey",e.data.pubkey]),s.push(["merge",!0]),t.db.client.execute("ca.list",[s])}async caUserLog(e,t,i){if(t||e.length<2)throw new u(c.MISC_ERROR,"ca.user.log cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),s=t.array(2,[]);let n=null;for(let e=0;e<s.length;e++){var a=s[e];a&&Array.isArray(a)?"alliancename"==a[0]&&(n=a[1],delete s[e]):delete s[e]}var[t,,]=await this.accessControl(i,e);e=await this.$allianceUserCreate([e,r,n],i);return s.push(["pubkey",e.data.pubkey]),t.db.client.execute("ca.list",[s])}async sysLog(e,t,i){if(t)throw new u(c.MISC_ERROR,"sys.log (query openid)");e=(t=new g([e])).array(0,[]);var r,[s,,]=await this.accessControl(i,t.str(1,"")),n=[];for(r of(await this.wdb.auditList.query(e)).list){var a=Object.assign({},r),h=o.parseHash(r.address,this.network);(h=await s.getPath(h))&&(a.account=h.name),a.time=new Date(1e3*r.time).toLocaleString(),n.push(a)}return n}async caIssuePublic(e,t,i){if(t||e.length<2||4<e.length)throw new u(c.MISC_ERROR,"ca.issue.public cert witness [pubkey openid]: 签发证书 证书对象 见证地址 [原始存证签名公钥 支付账户]");e=(t=new g([e])).obj(0,{});var r=t.str(1,""),s=t.str(2,""),[i,t]=await this.accessControl(i,t.str(3,""));if(64!=e.hash.length)throw new u(c.TYPE_ERROR,"err hash length");var n=await i.db.client.execute("ca.byId",[e.hash]);if(n)return n;if(n=await i.getPrivateKey(r))return e.height||(e.height=b.retargetInterval),await i.issueCreate({erid:e.hash,key:n.privateKey.toString("hex"),address:n.getAddress().toString(),witness:n.publicKey.toString("hex"),validHeight:this.wdb.curHeight+e.height,source:{subjectName:e.name||"",pubkey:s,subjectHash:e.hash,cluster:e.cluster,blob:e.blob}},t);throw new u(c.TYPE_ERROR,"Invalid witness.")}async caAbolishPublic(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"ca.abolish.public array[[erid height [openid]]]: 废止授信交易 废止交易信息数组");var r,s=[];for(r of new g([e]).array(0,[])){var[n,a]=await this.accessControl(i,r[3]),o=r[0],h=parseInt(r[1]),l=await this.wdb.erList.query([["erid",o]]),p=(l=x.fromWitnessPubkeyhash(w.hash160(Buffer.from(l.list[0].witness,"hex")),this.network.type).toString(),await n.getKey(l));if(!p)throw new u(c.TYPE_ERROR,"Invalid witness.");(n=await n.caAbolish({key:p.privateKey.toString("hex"),witness:p.publicKey.toString("hex"),address:l,erid:o,abolishHeight:h,cid:"",uid:0},a))&&s.push(n)}return s}async caIssue(e,t,i){if(t||e.length<3||4<e.length)throw new u(c.MISC_ERROR,"ca.issue cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(e,i,!1)}async caIssueAsync(e,t,i){if(t||e.length<3||4<e.length)throw new u(c.MISC_ERROR,"ca.issue.async cert uid cid [openid]: 签发证书 证书对象 见证人 见证人归属单位 [消费账户]");return this.$caIssue(e,i,!0)}async $caIssue(e,t,i){var r=(e=new g([e])).obj(0,{}),s=e.uint(1,0),n=e.str(2,""),[e,a]=await this.accessControl(t,e.str(3,""));if(!(o=await e.ensureCp(n))||"forbidden"==o.cls)throw new u(c.MISC_ERROR,"Invalid Account");if(64!=r.hash.length)throw new u(c.TYPE_ERROR,"err hash length");var o=await this.$allianceUserCreate([n,s],t),h=[];if(h.push(["pubkey",o.data.pubkey]),h.push(["source.subjectHash",r.hash]),0<(await e.db.client.execute("ca.list",[h])).count)throw new u(c.TYPE_ERROR,"cert.hash conflicted");if(await e.db.client.execute("ca.byId",[r.hash]))throw new u(c.TYPE_ERROR,"cert.hash conflicted");return r.height||(r.height=b.retargetInterval),o=await this.$allianceUserCreate([n,s],t,!0),await e.issueCreate({erid:r.hash,key:o.prvkey,witness:o.data.pubkey,address:o.data.addr,validHeight:this.wdb.curHeight+r.height,source:{subjectName:r.name,pubkey:o.data.pubkey,subjectHash:r.hash,cluster:r.cluster,cid:n,uid:s}},a,i)}async caAbolish(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"ca.abolish [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!1)}async caAbolishAsync(e,t,i){if(t||e.length<1)throw new u(c.MISC_ERROR,"ca.abolish.async [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!0)}async $caAbolish(e,t,i){var r,s=[];for(r of new g([e]).array(0,[])){var n,a=r[0],o=r[1],c=r[2],h=parseInt(r[3]),[n,u]=await this.accessControl(t,r[4]),l=await this.$allianceUserCreate([o,a],t,!0);(n=await n.caAbolish({cid:o,uid:a,key:l.prvkey,witness:l.data.pubkey,address:l.data.addr,erid:c,abolishHeight:h},u,i))&&s.push(n)}return s}async enchanceCp(e,t,i){if(t||e.length<2||4<e.length)throw new u(c.MISC_ERROR,"ca.enchance toCid fromCid height [openid]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3)),r=t.str(0,0),s=t.str(1,0);let n=t.uint(2,0);(!n||n<this.wdb.curHeight)&&(n=this.wdb.curHeight+b.retargetInterval);var[t,e]=await e.enchanceCp({to:r,from:s,enchanceHeight:n},i);return t&&e?e:null}async queryErList(e,t,i){if(t)throw new u(c.MISC_ERROR,"ca.query.remote conditions: 查询存证列表 (复合条件)");t=new g([e]);var[e,,]=await this.accessControl(i,t.str(1,""));i=t.array(0,[]);return e.db.client.execute("ca.list",[i])}async queryMyErlist(e,t,i){if(t)throw new u(c.MISC_ERROR,"ca.list.me query: 条件查询自己的电子权利 条件数组");return t=new g([e]).array(0,[]),this.wdb.erList.query(t)}}},function(e,t,i){var r=i(37);const{ContractEnvType:s,ContractStatus:n}=i(5),a=i(6),o=i(108);e.exports=class extends r{constructor(e){super(),this.db=e}async loadHistory(){var e;for(e of await this.db.getContracts())e&&(e.period<this.db.curHeight&&e.transStatus==n.CreatedOnMem?await this.delTransContract(e,!0):(e.id=e.type+"."+e.addr,await this.saveContract(e),e.transStatus==n.Promised&&this.db.autoTaskMgr.addTask(new o(this.db.network.txcheckpoint,e),this.db.network.txchecktime[e.type])))}query(e,t){return(e=this.get(e+"."+t))?e.transStatus:n.None}async addTransContract(e,t,i=!1){t.id=t.type+"."+t.addr;var r=this.get(t.id);e===s.Mempool&&((t=r||t).transStatus||(t.transStatus=n.CreatedOnMem),await this.saveContract(t,i))}async saveContract(e,t=!1){e.id=e.id||e.type+"."+e.addr,this.set(e.id,e),t&&(t=a.hash256(Buffer.from(e.id)).toString("hex"),await this.db.batchPut(this.db.tidCreator(t),Buffer.from(JSON.stringify(e))))}async promiseContract(e,t=!1){let i=!1;var r=e.type+"."+e.addr;let s=this.get(r);return s&&s.oper==e.oper||(i=!0,s=e),(!s.transStatus||s.transStatus<n.Promised)&&(i=!0,s.transStatus=n.Promised),i&&await this.saveContract(s,t),i}async confirmContract(e,t,i){e=e.type+"."+e.addr,!(e=this.get(e))||e.transStatus!=n.Promised||t!=n.Confirmed&&t!=n.Expired||(e.transStatus=t,await this.saveContract(e,i))}async delTransContract(e,t){var i=e.type+"."+e.addr,r=this.get(i);r&&r.oper==e.oper&&(this.delete(i),t)&&(r=a.hash256(Buffer.from(i)).toString("hex"),await this.db.batchDel(this.db.tidCreator(r)))}}},function(e,t,i){const r=i(5).HtlcStatus;i=i(37);class s extends i{constructor(e){super(),this.db=e}async loadHistory(){var e,t;for(e of(this.clear(),await this.db.loadHtlcList()))this.set(e.id,e),e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t)||this.account.set(t,new Map),this.account.get(t).set(e.id,e))}setAccount(e,t,i){this.delAccount(e),t&&i&&(e.wid=t,e.account=i,t=e.wid+"."+e.account,this.account.get(t)||this.account.set(t,new Map),this.account.get(t).set(e.id,e))}delAccount(e){var t;e&&e.wid&&e.account&&(t=e.wid+"."+e.account,this.account.get(t))&&this.account.get(t).delete(e.id)}}s.vpItem=class e{constructor(e){this.fromOptions(e||{})}fromOptions(e){this.shash=e.shash,this.sidx=e.sidx,this.sheight=e.sheight,this.ahash=e.ahash,this.aidx=e.aidx,this.aheight=e.aheight,this.src=e.src,this.dst=e.dst,this.aa=e.aa,this.ab=e.ab,this.ba=e.ba,this.bb=e.bb,this.amount=e.amount,this.rate=e.rate,this.pst=e.pst}toRaw(){var e={};return e.shash=this.shash,e.sidx=this.sidx,e.sheight=this.sheight,e.ahash=this.ahash,e.aidx=this.aidx,e.aheight=this.aheight,e.src=this.src,e.dst=this.dst,e.amount=this.amount,e.rate=this.rate,e.pst=this.pst||r.Init,e.aa=this.aa||"",e.ab=this.ab||"",e.ba=this.ba||"",e.bb=this.bb||"",Buffer.from(JSON.stringify(e),"utf-8")}get id(){return""+this.shash+this.sidx}fromRaw(e){return e=JSON.parse(e.toString("utf8")),this.fromOptions(e),this}static fromRaw(t){return(new e).fromRaw(t)}},e.exports=s},function(e,t,i){"use strict";
|
|
922
922
|
/*!
|
|
923
923
|
* walletdb.js - storage for wallets
|
|
924
924
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -936,7 +936,7 @@ var r=i(775),s=i(777),n=i(778),a=i(779),o=i(780),c=i(781),h=i(782);i=i(783),s=[]
|
|
|
936
936
|
* rpc.js - bitcoind-compatible json rpc for vallnet.
|
|
937
937
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
938
938
|
* https://github.com/bookmansoft/gamegold
|
|
939
|
-
*/const r=i(59),s=i(0),n=i(78),a=n.errors,o=n.MAGIC_STRING,c=i(77),h=i(82),u=i(7),l=i(6),p=i(158),d=i(26),f=i(124),m=i(121),g=i(33),y=i(17),v=i(107),b=i(36),w=i(2),k=i(3),x=i(84),S=i(68),_=i(232).openapi,E=i(152);i(132).vpItem,i(219);const R=i(13),A=i(75),O=i(89),C=i(113),I=i(131),j=i(69),P=i(45),T=i(28),B=i(20),N=i(19).opcodes;function M(e){for(let i=0;i<e.length;i+=4){var t=e.readUInt32LE(i,!0);e.writeUInt32BE(t,i,!0)}}e.exports=class extends n{constructor(e){super(e),s(e,"RPC requires a Node."),this.node=e,this.keys=e.keys,this.workers=e.workers,this.chain=e.chain,this.mempool=e.mempool,this.pool=e.pool,this.fees=e.fees,this.miner=e.miner,this.logger=e.logger.context("rpc"),this.procLimit=0,this.attempt=null,this.lastActivity=0,this.boundChain=!1,this.nonce1=0,this.nonce2=0,this.merkleMap=new Map,this.pollers=[],this.generating=!1,this.init()}init(){this.add("help",this.help),this.add("miner",this.routerOfMiner),this.add("miner.generate.admin",this.generate),this.add("miner.generateto.admin",this.generateToAddress),this.add("miner.setsync.admin",this.setSync),this.add("miner.setaddr.admin",this.setMinerAddr),this.add("miner.addaddr.admin",this.addMinerAddr),this.add("miner.getaddr.admin",this.getMinerAddr),this.add("miner.set.admin",this.setGenerate),this.add("miner.check",this.getGenerate),this.add("miner.difficulty",this.getDifficulty),this.add("vote",this.routerOfVote),this.add("vote.show",this.voteShow),this.add("vote.check",this.voteCheck),this.add("oracle.check",this.oracleCheck),this.add("block",this.routerOfBlock),this.add("block.best",this.getBestBlockHash),this.add("block.count",this.getBlockCount),this.add("block.info",this.getBlock),this.add("block.info.byheight",this.getBlockByHeight),this.add("block.hash",this.getBlockHash),this.add("block.header",this.getBlockHeader),this.add("block.verify",this.verifyBlock),this.add("block.tips",this.getChainTips),this.add("block.template.admin",this.getBlockTemplate),this.add("block.submit.admin",this.submitBlock),this.add("block.reset.admin",this.resetBlock),this.add("block.rollback.admin",this.rollbackBlock),this.add("block.invalidate.admin",this.invalidateBlock),this.add("block.reconsider.admin",this.reconsiderBlock),this.add("cp.byClass",this.cpByClass),this.add("cp.byName",this.cpByName),this.add("cp.byId",this.cpById),this.add("remoteNotify.set",this.remoteNotifySet),this.add("sc.query",this.querySCList),this.add("sc.balance",this.scBalance),this.add("sc.model",this.querySCModel),this.add("comm",this.routerOfComm),this.add("tx",this.routerOfTx),this.add("tx.raw.get",this.getRawTransaction),this.add("tx.raw.decode",this.decodeRawTransaction),this.add("tx.raw.create",this.createRawTransaction),this.add("tx.raw.send",this.sendRawTransaction),this.add("tx.raw.sign.admin",this.signRawTransaction),this.add("tx.get",this.getTXByHash),this.add("tx.list.address",this.getTXByAddress),this.add("tx.list.addresses",this.getTXByAddresses),this.add("tx.broadcast",this.broadcast),this.add("tx.prioritise",this.prioritiseTransaction),this.add("tx.utxo",this.getTXOut),this.add("tx.txo.proof",this.getTXOutProof),this.add("tx.txo.verifyproof",this.verifyTXOutProof),this.add("tx.coins",this.getCoins),this.add("tx.coincache",this.getCoinCache),this.add("tx.coins.byoutpoint",this.getCoinByOutpoint),this.add("tx.spender",this.getSpender),this.add("prop.byaddress",this.getVpByAddress),this.add("prop.byid",this.getVpById),this.add("prop.byHashIndex",this.getVpByHashIndex),this.add("sys",this.routerOfSys),this.add("sys.info",this.getInfo),this.add("sys.dump",this.heapDump),this.add("sys.blockinfo",this.getBlockchainInfo),this.add("sys.peerinfo",this.getPeerInfo),this.add("sys.networkinfo",this.getNetworkInfo),this.add("sys.memoryinfo",this.getMemoryInfo),this.add("sys.mempoolinfo",this.getMempoolInfo),this.add("sys.mininginfo",this.getMiningInfo),this.add("sys.addednodeinfo",this.getAddedNodeInfo),this.add("sys.txoinfo",this.getTXOutSetInfo),this.add("sys.connectioncount",this.getConnectionCount),this.add("sys.disconnectnode",this.disconnectNode),this.add("sys.nettotals",this.getNetTotals),this.add("sys.prune",this.pruneBlockchain),this.add("sys.ping",this.ping),this.add("sys.setloglevel",this.setLogLevel),this.add("sys.setban",this.setBan),this.add("sys.listbanned",this.listBanned),this.add("sys.clearbanned",this.clearBanned),this.add("sys.addnode",this.addNode),this.add("sys.hashrate",this.getNetworkHashPS),this.add("sys.work",this.getWork),this.add("sys.worklp",this.getWorkLongpoll),this.add("sys.setmocktime",this.setMockTime),this.add("sys.message.verify",this.verifyMessage),this.add("sys.message.signk",this.signMessageWithPrivkey),this.add("sys.stop.admin",this.stop),this.add("sys.decodescript",this.decodeScript),this.add("sys.validateaddress",this.validateAddress),this.add("sys.createmultisig",this.createMultisig),this.add("sys.createwitnessaddress",this.createWitnessAddress),this.add("sys.createAuthToken",this.authtoken),this.add("sys.groupPrefix",this.addGroupPrefix),this.add("sys.devmode",this.setDevMode),this.add("sys.groupSuffix",this.addGroupSuffix),this.add("sys.changeSpecialCp",this.changeSpecialCp),this.add("sys.rescan",this.rescan),this.add("sys.alliance",this.routerOfAlliance),this.add("sys.alliance.info",this.getAllianceInfo),this.add("sys.alliance.addpeer",this.addPeer),this.add("sys.alliance.list",this.listAlliance),this.add("sys.alliance.export",this.exportAlliance),this.add("sys.alliance.getpeer",this.getPeer),this.add("sys.alliance.delpeer",this.delPeer),this.add("estimate",this.routerOfEstimate),this.add("estimate.fee",this.estimateFee),this.add("estimate.smartfee",this.estimateSmartFee),this.add("estimate.priority",this.estimatePriority),this.add("estimate.smartpriority",this.estimateSmartPriority),this.add("mempool",this.routerOfMempool),this.add("mempool.info",this.getMempoolInfo),this.add("mempool.orphans",this.getMempoolOrphans),this.add("mempool.reset",this.resetMempool),this.add("mempool.ancestors",this.getMempoolAncestors),this.add("mempool.descendants",this.getMempoolDescendants),this.add("mempool.entry",this.getMempoolEntry),this.add("mempool.raw",this.getRawMempool),this.add("mempool.snap",this.getMempool),Object.values(_).map(e=>{this.add(e.name,async(t,i)=>this.node.conn_s2local.execute(e.name,t))})}get wallet(){return null}set wallet(e){}async routerOfMiner(e){throw new c(a.MISC_ERROR,"\n miner.generate.admin 生产一个区块\n miner.generateto.admin 使用指定的令牌地址生产一个区块\n miner.set.admin 设置矿机运行状态\n miner.setsync.admin 设置块链同步完成\n miner.setaddr.admin 动态设置奖励地址\n miner.addaddr.admin 动态添加奖励地址\n miner.getaddr.admin 查询实时奖励地址\n miner.check 检查矿机运行状态\n miner.difficulty 检查当前挖矿难度\n ")}async routerOfVote(e){throw new c(a.MISC_ERROR,"\n vote.check 查询指定地址的选举结果\n vote.show 查询当前或指定区间票仓信息\n vote.send 进行投票\n oracle.check 查询指定标记的数据上链情况\n oracle.send 进行数据上链操作\n ")}async routerOfBlock(e){throw new c(a.MISC_ERROR,"\n block.best 获取当前主链顶部区块哈希(小端)\n block.count 获取当前主链区块数量\n block.info 查询区块内容\n block.info.byheight 根据高度查询区块内容\n block.hash 根据高度查询区块哈希(小端)\n block.header 根据哈希(小端)查询区块头\n block.verify 校验区块数据\n block.tips 列表所有分叉的头部信息\n block.invalidate.admin 标记区块无效\n block.reconsider.admin 取消区块无效标记\n block.template.admin 生成或校验区块数据模板\n block.submit.admin 提交区块数据\n block.reset.admin 重置区块头至指定区块\n block.rollback.admin 回滚区块至指定区块\n ")}async routerOfMempool(e){throw new c(a.MISC_ERROR,"\n mempool.info 查看交易池概要信息\n mempool.ancestors 向前搠源交易池中指定交易\n mempool.descendants 向后搠源交易池中指定交易\n mempool.entry 查询交易记录\n mempool.raw 查询交易池中原始数据\n mempool.snap 查询交易池中原始数据\n mempool.reset 重置内存池\n ")}async routerOfEstimate(e){throw new c(a.MISC_ERROR,"\n estimate.fee 评估费用\n estimate.smartfee 评估智能费用\n estimate.priority 评估优先权\n estimate.smartpriority 评估智能优先权\n ")}async routerOfSys(e){throw new c(a.MISC_ERROR,"\n sys.info 查询系统概要信息\n sys.blockinfo 查询块链概要信息\n sys.memoryinfo 查询交易池概要信息\n sys.networkinfo 查询网络概要信息\n sys.nettotals 查询网速概要\n sys.peerinfo 查询对等节点概要信息\n sys.mininginfo 查询矿机概要信息\n sys.txoinfo 查询TXO概要信息\n sys.prune 修剪块链数据\n sys.ping PING所有管道\n sys.setloglevel 设置日志等级\n sys.setban 禁止管道\n sys.listbanned 列表已禁管道\n sys.clearbanned 清除已禁管道\n sys.addnode 添加管道\n sys.addednodeinfo 查询管道信息\n sys.connectioncount 查询连接数\n sys.disconnectnode 断开管道\n sys.hashrate 查询网络哈希速率\n sys.work 获取工作量\n sys.worklp 获取工作量\n sys.setmocktime 修改网络时间戳\n sys.message.sign 签署网络消息\n sys.message.signk 指定私钥签署网络消息\n sys.message.verify 验证网络消息\n sys.stop.admin 停止节点运行\n sys.decodescript 解码脚本\n sys.validateaddress 校验地址\n sys.zap 移除超龄挂起交易\n sys.createmultisig 生成多签脚本\n sys.walletdb.stop 停止钱包数据库的运行\n sys.walletdb.create 重新创立钱包数据库\n sys.walletdb.destroy 新增RPC指令:彻底删除钱包数据库\n sys.createwitnessaddress 生成见证地址\n sys.groupPrefix 添加/删除ACL前缀成员\n sys.groupSuffix 添加/删除ACL后缀成员\n sys.createAuthToken 制备令牌固定量\n sys.changeSpecialCp 添加特约商户\n sys.alliance 联盟管理\n sys.log 审计日志查询\n ")}async routerOfAlliance(e){throw new c(a.MISC_ERROR,"\n sys.alliance.info 查询联盟节点信息\n sys.alliance.gettoken 生成信道令牌\n sys.alliance.addpeer 添加认证信道\n sys.alliance.delpeer 删除认证信道\n sys.alliance.getpeer 查看信道列表\n sys.alliance.create 创建联盟节点证书\n sys.alliance.delete 吊销联盟节点证书\n sys.alliance.list 列表联盟节点证书\n sys.alliance.export 导出联盟节点证书\n ")}async routerOfComm(e){throw new c(a.MISC_ERROR,"\n comm.notify 通知(钱包)\n comm.listNotify 查询通知列表(钱包)\n comm.secret 安全通信(钱包)\n comm.listContact 列表安全通信联系人\n comm.scanContact 扫描指定交易,用关联地址建立通信联系人\n ")}async routerOfTx(e){throw new c(a.MISC_ERROR,"\n tx.raw.get 获取交易原始数据\n tx.raw.decode 解码交易原始数据\n tx.raw.create 创建交易,返回交易原始数据\n tx.raw.send 发送交易数据返回交易ID\n tx.get 查询交易记录\n tx.list.address 按地址查询交易列表\n tx.list.addresses 按地址列表查询交易列表\n tx.broadcast 广播交易\n tx.prioritise 优化交易池中的交易\n tx.utxo 查询UTXO信息\n tx.spender 查询硬币的消费者\n tx.mstrans 列表待处理多签交易\n tx.mstrans.sign 签署待处理多签交易\n tx.coins 查询硬币信息\n tx.coins.byoutpoint 查询硬币信息\n tx.txo.proof 查询TXO工作量信息\n tx.txo.verifyproof 校验TXO工作量信息\n tx.get.wallet 查询交易记录(钱包)\n tx.list 交易列表(钱包)\n tx.create 创建交易(钱包)\n tx.send 发送交易(钱包)\n tx.last 最近的交易\n tx.pending 查询挂起交易\n tx.range 范围查询\n tx.history 查询历史交易\n tx.history.since 查询指定日期后的历史交易\n tx.resend.admin 重发当前钱包的挂起交易\n tx.resendall.admin 重发所有钱包的挂起交易\n tx.importprunedfunds.admin 导入修剪资金\n tx.removeprunedfunds.admin 移除已导入修剪资金\n tx.fund.admin 填充资金\n tx.sign.admin 签署交易(钱包)\n tx.abandon.admin 丢弃指定交易\n tx.abandonall.admin 废弃所有挂起的交易\n tx.raw.sign.admin 签署交易\n ")}async exportAlliance(e,t,i){if(t)throw new c(a.MISC_ERROR,"sys.alliance.export: 批量导出联盟成员证书");for(var s of this.node.config.alliances)s=s.split("|"),r.unsupported||r.writeFile(`${this.network.type}-${s[0]}-${s[1]}.keystore`,s[2],"utf8")}async listAlliance(e,t,i){if(t)throw new c(a.MISC_ERROR,"sys.alliance.list: 列表现有联盟成员");var r,s=[];t={name:this.node.config.allianceName,id:this.node.config.allianceNodeId,address:this.node.config.allianceAwardAddress,host:this.node.config.host+":"+this.node.config.port};for(r of(t.voted=(await this.chain.db.voteMgr.checkVote(t.address)).result,s.push(t),this.node.config.alliances)){var n;(n={name:(n=r.split("|"))[0],id:n[1],address:n[4],host:n[5]}).voted=(await this.chain.db.voteMgr.checkVote(n.address)).result,s.push(n)}return s}async addPeer(e,t,i){if(t||e.length<2)throw new c(a.MISC_ERROR,"sys.alliance.addpeer host key: 添加授信信道 地址 信道公钥");return this._addPeer(e)}async _addPeer(e){var t=(e=new x([e])).str(0),i=e.str(1),r=e.str(2);e=e.uint(3);return t&&i?(i==d.publicKeyCreate(Buffer.from(this.node.config.identityKey,"hex"),!0).toString("hex")||this.node.pool.authdb.getKnown(t)||(await this.node.rpc.addNode([t,"add"]),this.node.pool.authdb.addKnown(t,Buffer.from(i,"hex"))),r==this.node.config.allianceName&&e==this.node.config.allianceNodeId&&(this.node.config.abandon=!1,this.node.config.saveAsync()),{host:t,key:i}):null}async getPeer(e,t,i){if(t)throw new c(a.MISC_ERROR,"sys.alliance.getpeer: 查看授信信道");return{peer:this.node.config.knownPeers}}async delPeer(e,t,i){if(t||e.length<1)throw new c(a.MISC_ERROR,"sys.alliance.delpeer hostname: 删除授信信道 信道地址");var r;t={host:new x([e]).str(0)};return(e=this.node.require("walletdb"))&&(e=await e.get("primary"))&&(r=v.signObj(t,e.notifyKey.privateKey),await e.commNotify({dst:e.notifyAddress,content:JSON.stringify({cmd:"peerdel",payload:t,sig:r,pub:e.notifyKey.publicKey.toString("hex")})})),t}async _delPeer(e){let t={host:(e=new x([e])).str(0),allianceName:e.str(1),allianceNodeId:e.uint(2)};var i=this.node.config.knownPeers.length;for(let e=0;e<i;e++)if(-1!=this.node.config.knownPeers[e].indexOf(t.host)){var r=this.node.config.knownPeers.splice(e,1);t.key=r[0].split(" ")[1].replace(" ",""),this.pool.authdb.delKnown(t.host),await this.node.rpc.addNode([t.host,"remove"]),setTimeout(()=>{var e,i;for(e of this.pool.peers.getbyhost(t.host))e.destroy();for(i of this.pool.peers.getInbound())i.destroy()},6e3);break}return t.allianceName==this.node.config.allianceName&&t.allianceNodeId==this.node.config.allianceNodeId&&(this.node.config.abandon=!0,this.node.config.saveAsync()),t}async getAllianceInfo(e,t,i){if(t)throw new c(a.MISC_ERROR,"sys.alliance.info: 获取联盟信息");t=this.node.config.identityKey;var r=(t=d.publicKeyCreate(Buffer.from(t,"hex"),!0)).toString("hex");t=R.fromWitnessPubkeyhash(l.hash160(t),this.network.type).toString();return{alliancePrivateKey:this.node.config.alliancePrivateKey,peerIdentity:r,awardAddress:t,allianceName:this.node.config.allianceName,allianceNodeId:this.node.config.allianceNodeId}}async voteShow(e,t){if(t)throw new c(a.MISC_ERROR,"vote.show [zoneId]: 查询选举结果 [指定区间]");return t=new x([e]).uint(0,0),this.chain.db.voteMgr.getVote(t)}async oracleCheck(e,t){if(t)throw new c(a.MISC_ERROR,"oracle.check key: 查询上链数据 数据标记");return{k:t=new x([e]).str(0,""),v:(e=await this.chain.db.voteMgr.checkOracle(t)).v,vote:e.vote}}async voteCheck(e,t){if(t)throw new c(a.MISC_ERROR,"vote.check address: 查询选举结果 指定地址");return t=new x([e]).str(0,""),this.chain.db.voteMgr.checkVote(t)}async changeSpecialCp(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'sys.changeSpecialCp action[0-view 1-add 2-remove 3-clear] "[cid]": 添加/删除/清空特约商户');e=(t=new x([e])).uint(0,0);var i=t.array(1);if(e){switch(e){case 1:for(var r of i)this.node.specialCp.add(r);break;case 2:for(var s of i)this.node.specialCp.del(s);break;case 3:this.node.specialCp.clear()}await this.node.config.saveAsync()}return this.node.specialCp.content()}async setDevMode(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,"sys.devMode remove[true,false]: 设置/取消开发模式");return t=new x([e]).bool(0,!1),this.node.config.devMode=t,(e=this.node.require("walletdb"))&&(e.options.devMode=t),(e=this.node.require("contractdb"))&&(e.options.devMode=t),await this.node.config.saveAsync(),t}async addGroupPrefix(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'sys.groupPrefix "[[prefix, cid]]" remove[true,false]: 添加/删除前缀成员');e=(t=new x([e])).array(0);var i,r=t.bool(1,!1);for(i of e)r?(this.node.acl.delGroupPrefix(i[0],i[1]),await this.logAudit({address:this.node.config.coinbaseAddress||"",oper:"usermanager",hash:"unforbid/"+i[1],index:0})):(this.node.acl.addGroupPrefix(i[0],i[1]),await this.logAudit({address:this.node.config.coinbaseAddress||"",oper:"usermanager",hash:"forbid/"+i[1],index:0}));return await this.node.config.saveAsync(),!0}async logAudit(e){var t=this.node.require("walletdb");t&&await t.logAudit(e)}async rescan(e,t){if(t)throw new c(a.MISC_ERROR,'sys.rescan ( "height" )');return t=new x([e]).u32(0),this.node.scan(t,null,async(e,t)=>{await this.node.fire("sys.rescan",e,t)}),!0}async addGroupSuffix(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'sys.groupSuffix "[[suffix, cid]]" remove[true,false]: 添加/删除后缀成员');e=(t=new x([e])).array(0);var i,r=t.bool(1,!1);for(i of e)r?this.node.acl.delGroupSuffix(i[0],i[1]):this.node.acl.addGroupSuffix(i[0],i[1]);return await this.node.config.saveAsync(),!0}async heapDump(e,t){return this.node.config.heapDump(),!0}async getInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.info");t=this.mempool?this.mempool.map.size:0,e=this.mempool?this.mempool.getSize():0;let i=this.pool.hosts.getLocal();return i=i||this.pool.hosts.address,{version:h.version,testnet:"main"!=this.network.type,paytxfee:g.btc(this.network.feeRate,!0),relayfee:g.btc(this.network.minRelay,!0),network:this.network.type,chain:{height:this.chain.height,tip:this.chain.tip.rhash(),progress:this.chain.getProgress(),difficulty:m.bits2Diff(this.chain.tip.bits)},mempool:{tx:t,size:e},time:{uptime:this.node.uptime(),system:w.now(),adjusted:this.network.now(),offset:this.network.time.offset},memory:w.memoryUsage(),pool:{host:i.host,port:i.port,agent:this.pool.options.agent,protocolversion:this.pool.options.version,services:this.pool.options.services.toString(2),outbound:this.pool.peers.outbound,inbound:this.pool.peers.inbound,connections:this.pool.peers.size()},walletversion:0,balance:0,proxy:"",keypoololdest:0,keypoolsize:0,unlocked_until:0,errors:""}}async help(e){if(0===e.length)throw new c(a.MISC_ERROR,"\n miner 记账相关\n block 区块相关\n cp 实体管理\n prop 道具相关\n contract 交易对相关\n tx 交易相关\n sys 系统管理和状态监控\n estimate 评估\n mempool 交易池\n wallet 钱包管理\n key 密钥管理\n account 账户管理\n address 地址管理\n coin 硬币管理\n vote 投票管理\n htlc 跨链操作\n ");return e={method:e[0],params:[]},this.execute(e,!0)}async broadcast(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"tx.broadcast tx-hex: 广播交易 交易HEX字符串");return t=new x([e]).buf(0),s(t,"tx.broadcast: tx-hex is required."),e=B.fromRaw(t),await this.node.sendTX(e),!0}async authtoken(e,t,i){if(t||1!==e.length)throw new c(a.TYPE_ERROR,"sys.createAuthToken tids: 制备令牌固定量 终端编码列表(逗分字符串)");if(t=new x([e]).array(0),!Array.isArray(t))throw new c(a.TYPE_ERROR,"sys.createAuthToken tids: 制备令牌固定量 终端编码列表(逗分字符串)");var r,{aeskey:s,aesiv:n}=S.fromKey(k.ONE_HASH,this.node.keys.hmacSalt,this.network.type).getAes(i.options.cid),o=[];for(r of t){if(!("string"==typeof r&&r.length<=40))throw new c(a.TYPE_ERROR,"各终端编码必须是最大长度40字节的字符串");var h=S.getHmac(r.toString(),this.node.keys.hmacSalt).token,u=this.node.require("walletdb");u&&await u.logAudit({address:this.node.config.coinbaseAddress||"",oper:"usermanager",hash:"create/"+r,index:0}),this.node.config.devMode?o.push({cid:r,encry:w.encrypt(s,n,h),token:h}):o.push({cid:r,encry:w.encrypt(s,n,h)})}return o}async querySCModel(e,t){return Object.keys(E.list).map(e=>E.list[e])}async querySCList(e,t){if(t)throw new c(a.MISC_ERROR,"sc.query (conditions): 查询合约 (查询条件)");t=new x([e]).array(0,[]),e=await this.chain.db.getSCList(t);var i,r=await this.node.cdb.get("primary");for(i of e.list){var s=await r.getBalance(i.options.addr);i.options.confirmed=s.toJSON().confirmed}return e}async scBalance(e,t){if(t)throw new c(a.MISC_ERROR,"sc.balance address: 查询合约库地址余额 指定地址");return t=new x([e]).str(0,""),(await(await this.node.cdb.get("primary")).getBalance(t)).toJSON()}async cpByClass(e,t){if(t||e.length<1||3<e.length)throw new c(a.MISC_ERROR,"cp.byClass cls: 查询CP编码集合 游戏类别 页码 页宽");e=(t=new x([e])).str(0,"");var i=t.uint(1,1),r=(t=t.uint(2,10),[]);return r.push(["size",t]),r.push(["page",i]),r.push(["cls",e]),this.chain.db.cpList.query(r)}async cpById(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'cp.byId "clientNo": 根据编码查询厂商记录');return(t=new x([e]).str(0))?this.chain.db.cpList.getRecord(t):null}async cpByName(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'cp.byName "name": 根据名称查询厂商记录');return(t=new x([e]).str(0))?this.chain.db.cpList.getItemByName(decodeURIComponent(t)):null}async resetBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"block.reset.admin [hash | height]: 重置区块头 [区块哈希 | 区块高度]");let i=new x([e]).str(0);if(s(i,"Height is required."),1==this.node.config.mining)throw new c(a.MISC_ERROR,'Use "miner.set.admin false" stop miner first!');if(this.generating||this.node.miner&&this.node.miner.cpu.running)throw new c(a.MISC_ERROR,"Miner is running, stop it first!");return 64!==i.length&&(i=parseInt(i,10)),await this.chain.reset(i),this.logger.info("Chain has been reset: %s.",i),!0}async rollbackBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"block.rollback.admin [hash | height]: 回滚区块 [区块哈希| 区块高度]");if(t=new x([e]).str(0),s(t,"Height is required."),1==this.node.config.mining)throw new c(a.MISC_ERROR,'Use "miner.set.admin false" stop miner first!');if(this.generating||this.node.miner&&this.node.miner.cpu.running)throw new c(a.MISC_ERROR,"Miner is running, stop it first!");let i=null;if(i=64!==t.length?await this.chain.getEntry(parseInt(t,10)):await this.chain.getEntry(w.revHex(t)))return await this.chain.reorganize(i),this.logger.info("Chain has been reorganize: %s.",t),!0;throw new c(a.MISC_ERROR,"Block not found.")}async stop(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.stop.admin");return this.node.close().catch(e=>{setImmediate(()=>{throw e})}).finally(async()=>{await new Promise(e=>{setTimeout(e,1e4)}),process.exit(0)}),"Stopping."}async getNetworkInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.networkinfo");var i=[];for(const e of this.pool.hosts.local.values())i.push({address:e.addr.host,port:e.addr.port,score:e.score});return{version:h.version,subversion:this.pool.options.agent,protocolversion:this.pool.options.version,localservices:w.hex32(this.pool.options.services),localrelay:!this.pool.options.noRelay,timeoffset:this.network.time.offset,networkactive:this.pool.connected,connections:this.pool.peers.size(),networks:[],relayfee:g.btc(this.network.minRelay,!0),incrementalfee:0,localaddresses:i,warnings:""}}async addNode(e,t){if(t||2!==e.length)throw new c(a.MISC_ERROR,'sys.addnode "node" "add|remove|onetry"');var i=(e=new x([e])).str(0,"");switch(e.str(1,"")){case"add":if(-1!=this.node.config.nodes.indexOf(i))break;this.node.config.nodes.push(i),await this.node.config.saveAsync(),this.pool.hosts.addNode(i);case"onetry":var r=n.parseNetAddress(i,this.network);this.pool.peers.get(r.hostname)||(r=this.pool.createOutbound(r),this.pool.peers.add(r));break;case"remove":-1!=(r=this.node.config.nodes.indexOf(i))&&(this.node.config.nodes.splice(r,1),await this.node.config.saveAsync()),this.pool.hosts.removeNode(i)}return this.getAddedNodeInfo([],t)}async disconnectNode(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.disconnectnode "node"');return t=new x([e]).str(0,""),e=n.parseIP(t,this.network),(t=this.pool.peers.get(e.hostname))&&t.destroy(),null}async getAddedNodeInfo(e,t){if(t||1<e.length)throw new c(a.MISC_ERROR,'sys.addednodeinfo ( "node" )');t=this.pool.hosts;var i=new x([e]).str(0,"");let r;1===e.length&&(r=n.parseIP(i,this.network));var s=[];for(const e of t.nodes){if(r){if(e.host!==r.host)continue;if(e.port!==r.port)continue}var o=this.pool.peers.get(e.hostname);o&&o.connected?s.push({addednode:e.hostname,connected:o.connected,addresses:[{address:o.hostname(),connected:o.outbound?"outbound":"inbound"}]}):s.push({addednode:e.hostname,connected:!1,addresses:[]})}if(r&&0===s.length)throw new c(a.CLIENT_NODE_NOT_ADDED,"Node has not been added.");return s}async getConnectionCount(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.connectioncount");return this.pool.peers.size()}async getNetTotals(e,t){if(t||0<e.length)throw new c(a.MISC_ERROR,"sys.nettotals");let i=0,r=0;for(let e=this.pool.peers.head();e;e=e.next)i+=e.socket.bytesWritten,r+=e.socket.bytesRead;return{totalbytesrecv:r,totalbytessent:i,timemillis:w.ms()}}async getPeerInfo(e,t){if(t)throw new c(a.MISC_ERROR,"sys.peerinfo onlyOutbound");var i=new x([e]).bool(0,!1),r=[];for(let e=this.pool.peers.head();e;e=e.next)if(!i||e.outbound){let t=this.network.time.known.get(e.hostname());var s=[];null==t&&(t=0);for(const t in e.blockMap.keys()){var n=w.revHex(t);s.push(n)}r.push({id:e.id,addr:e.hostname(),addrlocal:e.local.isNull()?void 0:e.local.hostname,services:w.hex32(e.services),relaytxes:!e.noRelay,lastsend:e.lastSend/1e3|0,lastrecv:e.lastRecv/1e3|0,bytessent:e.socket.bytesWritten,bytesrecv:e.socket.bytesRead,conntime:0!==e.time?(w.ms()-e.time)/1e3|0:0,timeoffset:t,pingtime:-1!==e.lastPong?(e.lastPong-e.lastPing)/1e3:-1,minping:-1!==e.minPing?e.minPing/1e3:-1,version:e.version,subver:e.agent,inbound:!e.outbound,startingheight:e.height,besthash:null,bestheight:0,banscore:e.banScore,inflight:s,whitelisted:!1})}return r}async ping(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.ping");for(let e=this.pool.peers.head();e;e=e.next)e.sendPing();return null}async setBan(e,t){var i=(r=new x([e])).str(0,""),r=r.str(1,"");if(t||e.length<2||"add"!==r&&"remove"!==r)throw new c(a.MISC_ERROR,'sys.setban "ip(/netmask)" "add|remove" (bantime) (absolute)');var s=n.parseNetAddress(i,this.network);switch(r){case"add":this.pool.ban(s);break;case"remove":this.pool.unban(s)}return null}async listBanned(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.listbanned");var i,r,s=[];for([i,r]of this.pool.hosts.banned)s.push({address:i,banned_until:r+this.pool.options.banTime,ban_created:r,ban_reason:""});return s}async clearBanned(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.clearbanned");return this.pool.hosts.clearBanned(),null}async getBlockchainInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.blockinfo");return{chain:"testnet"!==this.network.type?this.network.type:"test",blocks:this.chain.height,headers:this.chain.height,orphan:this.chain.orphanMap.size,bestblockhash:this.chain.tip.rhash(),difficulty:m.bits2Diff(this.chain.tip.bits),mediantime:await this.chain.getMedianTime(this.chain.tip),verificationprogress:this.chain.getProgress(),chainwork:this.chain.tip.chainwork.toString("hex",64),pruned:this.chain.options.prune,softforks:this.getSoftforks(),bip9_softforks:await this.getBIP9Softforks(),pruneheight:this.chain.options.prune?Math.max(0,this.chain.height-this.network.block.keepBlocks):null}}async getBestBlockHash(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"block.best: 获取当前主链顶部区块哈希(小端)");return this.chain.tip.rhash()}async getBlockCount(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"block.count: 获取当前主链区块数量");return this.chain.tip.height}async getBlock(e,t){if(t||e.length<1||3<e.length)throw new c(a.MISC_ERROR,"block.info hash ( bool-verbose bool-details ): 查询区块内容 小端哈希 (展开为对象 更多细节)");e=(t=new x([e])).hash(0);var i=t.bool(1,!0);t=t.bool(2,!1);if(!e)throw new c(a.TYPE_ERROR,"Invalid block hash.");if(!(e=await this.chain.getEntry(e)))throw new c(a.MISC_ERROR,"Block not found");var r=await this.chain.getBlock(e.hash);if(r)return i?this.blockToJSON(e,r,t):r.toRaw().toString("hex");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Block not available (spv mode)");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Block not available (pruned data)");throw new c(a.MISC_ERROR,"Can't read block from disk")}async getBlockByHeight(e,t){if(t||e.length<1||3<e.length)throw new c(a.MISC_ERROR,'block.info.byheight "height" ( bool-verbose bool-details ): 根据高度查询区块 高度 (展开为对象 更多细节)');e=(t=new x([e])).u32(0,-1);var i=t.bool(1,!0);t=t.bool(2,!1);if(-1===e)throw new c(a.TYPE_ERROR,"Invalid block height.");if(!(e=await this.chain.getEntry(e)))throw new c(a.MISC_ERROR,"Block not found");var r=await this.chain.getBlock(e.hash);if(r)return i?this.blockToJSON(e,r,t):r.toRaw().toString("hex");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Block not available (spv mode)");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Block not available (pruned data)");throw new c(a.DATABASE_ERROR,"Can't read block from disk")}async getBlockHash(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"block.hash height: 根据高度查询区块哈希(小端)");if(null==(t=new x([e]).u32(0))||t>this.chain.height)throw new c(a.INVALID_PARAMETER,"Block height out of range.");if(e=await this.chain.getHash(t))return w.revHex(e);throw new c(a.MISC_ERROR,"Not found.")}async getCoinByOutpoint(e,t){if(t||2!=e.length)throw new c(a.MISC_ERROR,"tx.coins.byoutpoint txid index: 查询硬币列表 交易ID 交易内索引");return e=(t=new x([e])).hash(0),t=t.u32(1),s(e,"Hash is required."),s(null!=t,"Index is required."),s(!this.chain.options.spv,"Cannot get coins in SPV mode."),(e=await this.node.getCoin(e,t))?e.getJSON(this.network):null}async getSpender(e,t,i){var r=(e=new x([e])).hash(0);e=e.u32(1);return(r=(s(r,"Hash is required."),s(null!=e,"Index is required."),await this.chain.db.getSpender(r,e)))&&(r.txid=w.revHex(r.txid)),r}async getCoins(e,t){if(t||1!=e.length)throw new c(a.MISC_ERROR,"tx.coins addr: 查询硬币列表 地址");t=new x([e]).str(0,""),s(t,"Address is required."),s(!this.chain.options.spv,"Cannot get coins in SPV mode."),e=await this.node.getCoinsByAddress(t.split(","));var i=[];for(const t of e)i.push(t.getJSON(this.network));return i}async getCoinCache(e,t){return this.chain.db.coinCache.size}async getBlockHeader(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,'block.header "hash" ( verbose ): 查询区块头 哈希(小端) (展开为对象)');if(e=(t=new x([e])).hash(0),t=t.bool(1,!0),!e)throw new c(a.MISC_ERROR,"Invalid block hash.");if(e=await this.chain.getEntry(e))return t?this.headerToJSON(e):e.toRaw().toString("hex",0,80);throw new c(a.MISC_ERROR,"Block not found")}async getChainTips(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"block.tips: 列表所有分叉的头部信息");var i=[];for(const e of await this.chain.getTips()){var r=await this.chain.getEntry(e),n=(s(r),await this.findFork(r)),o=await this.chain.isMainChain(r);i.push({height:r.height,hash:r.rhash(),branchlen:r.height-n.height,status:o?"active":"valid-headers"})}return i}async getDifficulty(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"miner.difficulty: 查看当前挖矿难度");return m.bits2Diff(this.chain.tip.bits)}async resetMempool(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"mempool.reset");if(this.mempool)return this.mempool.reset();throw new c(a.MISC_ERROR,"No mempool available.")}async getMempoolInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.mempoolinfo");if(this.mempool)return{waiting:this.mempool.waiting.keys().length,orphans:this.mempool.orphans.size,size:this.mempool.map.size,bytes:this.mempool.getSize(),usage:this.mempool.getSize(),maxmempool:this.mempool.options.maxSize,mempoolminfee:g.btc(this.mempool.options.minRelay,!0)};throw new c(a.MISC_ERROR,"No mempool available.")}async getMempoolOrphans(e,t){if(!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");let i=[];return this.mempool.orphans.forEach((e,t)=>{i.push(w.revHex(t))}),i}async getMempoolAncestors(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,"mempool.ancestors txid (bool-verbose): 向前搠源 交易哈希小端 [展开为对象]");if(e=(t=new x([e])).hash(0),t=t.bool(1,!1),!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(!e)throw new c(a.TYPE_ERROR,"Invalid TXID.");const i=this.mempool.getEntry(e);if(!i)throw new c(a.MISC_ERROR,"Transaction not in mempool.");e=this.mempool.getAncestors(i);var r=[];if(t)for(const t of e)r.push(this.entryToJSON(t));else for(const t of e)r.push(t.txid());return r}async getMempoolDescendants(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,"mempool.descendants txid (bool-verbose): 向后搠源 交易哈希小端 [展开为对象]");if(e=(t=new x([e])).hash(0),t=t.bool(1,!1),!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(!e)throw new c(a.TYPE_ERROR,"Invalid TXID.");const i=this.mempool.getEntry(e);if(!i)throw new c(a.MISC_ERROR,"Transaction not in mempool.");e=this.mempool.getDescendants(i);var r=[];if(t)for(const t of e)r.push(this.entryToJSON(t));else for(const t of e)r.push(t.txid());return r}async getMempoolEntry(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"mempool.entry txid: 查询交易记录");if(t=new x([e]).hash(0),!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(!t)throw new c(a.TYPE_ERROR,"Invalid TXID.");if(e=this.mempool.getEntry(t))return this.entryToJSON(e);throw new c(a.MISC_ERROR,"Transaction not in mempool.")}async getMempool(e,t){if(t||0<e.length)throw new c(a.MISC_ERROR,"mempool.snap: 查询交易池原始记录");s(this.mempool,"No mempool available.");var i=[];for(const e of this.mempool.getSnapshot())i.push(w.revHex(e));return i}async getRawMempool(e,t){if(t||1<e.length)throw new c(a.MISC_ERROR,"mempool.raw ( bool-verbose ): 查询交易池原始记录 [展开为对象]");if(t=new x([e]).bool(0,!1),!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(t){var i={};for(const e of this.mempool.map.values())i[e.txid()]=this.entryToJSON(e);return i}return this.mempool.getSnapshot().map(w.revHex)}async getTXOut(e,t){if(t||e.length<2||3<e.length)throw new c(a.MISC_ERROR,'tx.utxo "txid" n ( includemempool )');e=(t=new x([e])).hash(0);var i=t.u32(1);t=t.bool(2,!0);if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Cannot get coins in SPV mode.");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Cannot get coins when pruned.");if(!e||null==i)throw new c(a.TYPE_ERROR,"Invalid outpoint.");let r;if(t){if(!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");r=this.mempool.getCoin(e,i)}return(r=r||await this.chain.getCoin(e,i))?{bestblock:this.chain.tip.rhash(),confirmations:r.getDepth(this.chain.height),value:g.btc(r.value,!0),scriptPubKey:this.scriptToJSON(r.script,!0),version:r.version,coinbase:r.coinbase}:null}async getTXOutProof(e,t){if(t||1!==e.length&&2!==e.length)throw new c(a.MISC_ERROR,'tx.txo.proof ["txid",...] ( blockhash )');var i=(t=new x([e])).array(0);const r=t.hash(1);if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Cannot get coins in SPV mode.");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Cannot get coins when pruned.");if(!i||0===i.length)throw new c(a.INVALID_PARAMETER,"Invalid TXIDs.");var s=new x([i]),n=new Set,o=[];let h=null;for(let e=0;e<i.length;e++){const t=s.hash(e);if(!t)throw new c(a.TYPE_ERROR,"Invalid TXID.");if(n.has(t))throw new c(a.INVALID_PARAMETER,"Duplicate txid.");n.add(t),o.push(t),h=t}let u=null;if(r?u=await this.chain.getBlock(r):this.chain.options.indexTX?(e=await this.chain.getMeta(h))&&(u=await this.chain.getBlock(e.block)):(t=await this.chain.getCoin(h,0))&&(u=await this.chain.getBlock(t.height)),!u)throw new c(a.MISC_ERROR,"Block not found.");for(const e of o)if(!u.hasTX(e))throw new c(a.VERIFY_ERROR,"Block does not contain all txids.");return(u=I.fromHashes(u,o)).toRaw().toString("hex")}async verifyTXOutProof(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'tx.txo.verifyproof "proof"');if(!(t=new x([e]).buf(0)))throw new c(a.TYPE_ERROR,"Invalid hex string.");if(!(e=I.fromRaw(t)).verify())return[];if(!await this.chain.getEntry(e.hash("hex")))throw new c(a.MISC_ERROR,"Block not found in chain.");var i=[];for(const t of e.getTree().matches)i.push(w.revHex(t.toString("hex")));return i}async getTXOutSetInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.txoinfo");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Chainstate not available (SPV mode).");return{height:this.chain.height,bestblock:this.chain.tip.rhash(),transactions:this.chain.db.state.tx,txouts:this.chain.db.state.coin,bytes_serialized:0,hash_serialized:0,total_amount:g.btc(this.chain.db.state.value,!0)}}async pruneBlockchain(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.prune: 修剪块链数据");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Cannot prune chain in SPV mode.");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Chain is already pruned.");if(this.chain.height<this.network.block.pruneAfterHeight)throw new c(a.MISC_ERROR,"Chain is too short for pruning.");try{await this.chain.prune()}catch(e){throw new c(a.DATABASE_ERROR,e.message)}}async submitWork(e){var t=await this.locker.lock();try{return await this._submitWork(e)}finally{t()}}async _submitWork(e){var t=this.attempt;if(!t)return!1;if(128!==e.length)throw new c(a.INVALID_PARAMETER,"Invalid work size.");if(M(e=e.slice(0,80)),(e=O.fromHead(e)).prevBlock!==t.prevBlock||e.bits!==t.bits)return!1;if(!e.verify())return!1;if(!(i=this.merkleMap.get(e.merkleRoot)))return!1;var i,[i,r]=i,s=e.nonce;e=e.time;if(!(i=t.getProof(i,r,e,s)).verify(t.target))return!1;let n;r=t.commit(i);try{n=await this.chain.add(r)}catch(e){if("VerifyError"===e.type)return this.logger.warning("RPC block rejected: %s (%s).",r.rhash(),e.reason),!1;throw e}return!!n||(this.logger.warning("RPC block rejected: %s (bad-prevblk).",r.rhash()),!1)}async createWork(e){var t=await this.locker.lock();try{return await this._createWork(e)}finally{t()}}async _createWork(){var e=await this.updateWork(),t=this.nonce1,i=this.nonce2,r=e.time,s=Buffer.allocUnsafe(128);s.fill(0),t=e.getRoot(t,i);return e.getHeader(t,r,0).copy(s,0),s[80]=128,s.writeUInt32BE(640,s.length-4,!0),M(s),{data:s.toString("hex"),target:e.target.toString("hex"),height:e.height}}async getWorkLongpoll(e,t){if(t||0!=e.length)throw new c(a.MISC_ERROR,"sys.worklp");return await this.longpoll(),this.createWork()}async getWork(e,t){if(t||1<e.length)throw new c(a.MISC_ERROR,'sys.work ( "data" )');if(1!==e.length)return this.createWork();if(t=new x([e]).buf(0))return this.submitWork(t);throw new c(a.TYPE_ERROR,"Invalid work data.")}async submitBlock(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,'block.submit.admin "hexdata" ( "jsonparametersobject" ): 提交区块数据 区块数据HEX串');return t=new x([e]).buf(0),e=A.fromRaw(t),this.addBlock(e)}async getBlockTemplate(e,t){if(t||1<e.length)throw new c(a.MISC_ERROR,"block.template.admin ( \"{'mode':'template | proposal', 'data': '{hex}', 'rules':['segwit']}\" ): 生成或校验区块数据模板");if(t=new x([e]).obj(0,{}),"template"!==(t=(e=new x([t])).str("mode","template"))&&"proposal"!==t)throw new c(a.INVALID_PARAMETER,"Invalid mode.");if("proposal"===t){if(!(t=e.buf("data")))throw new c(a.TYPE_ERROR,"Missing data parameter.");if((t=A.fromRaw(t)).prevBlock!==this.chain.tip.hash)return"inconclusive-not-best-prevblk";try{await this.chain.verifyBlock(t)}catch(e){if("VerifyError"===e.type)return e.reason;throw e}return null}let i=e.u32("maxversion",-1),r=e.array("rules");r&&(i=-1);let s=!1;if(t=e.array("capabilities")){let e=!1,i=!1;for(const r of t){if("string"!=typeof r)throw new c(a.TYPE_ERROR,"Invalid capability.");switch(r){case"coinbasetxn":e=!0;break;case"coinbasevalue":i=!0}}if(i=!0,e&&!i){if(0===this.miner.addresses.length)throw new c(a.MISC_ERROR,"No addresses available for coinbase.");s=!0}}return(t=e.str("longpollid"))&&await this.handleLongpoll(t),r=r||[],this.createTemplate(i,s,r)}async createTemplate(e,t,i){var r=await this.locker.lock();try{return await this._createTemplate(e,t,i)}finally{r()}}async _createTemplate(e,t,i){var r=await this.getTemplate(),n=r.witness?1:u.WITNESS_SCALE_FACTOR,o=["time","transactions","prevblock"],h=(2<=e&&o.push("version/force"),t&&(o.push("coinbase"),o.push("coinbase/append"),o.push("generation")),new Map);for(let e=0;e<r.items.length;e++){var l=r.items[e];h.set(l.hash,e+1)}var p=[];for(let e=0;e<r.items.length;e++){var d=r.items[e],m=d.tx,g=[];for(let t=0;t<m.inputs.length;t++){var y=m.inputs[t];null!=(y=h.get(y.prevout.hash))&&-1===g.indexOf(y)&&(s(y<e+1),g.push(y))}p.push({data:m.toRaw().toString("hex"),txid:m.txid(),hash:m.wtxid(),depends:g,fee:d.fee,sigops:d.sigops/n|0,weight:m.getWeight()})}let v=r.version;var b={},k=[];for(const e of this.network.deploys){var x=await this.chain.getState(this.chain.tip,e);let t=e.name;switch(x){case f.thresholdStates.DEFINED:case f.thresholdStates.FAILED:break;case f.thresholdStates.LOCKED_IN:v|=1<<e.bit;case f.thresholdStates.STARTED:e.force||(-1===i.indexOf(t)&&(v&=~(1<<e.bit)),e.required&&(t="!"+t)),b[t]=e.bit;break;case f.thresholdStates.ACTIVE:if(!e.force&&e.required){if(-1===i.indexOf(t))throw new c(a.INVALID_PARAMETER,`Client must support ${t}.`);t="!"+t}k.push(t);break;default:s(!1,"Bad state.")}}var S;e={capabilities:["proposal"],mutable:o,version:v>>>=0,rules:k,vbavailable:b,vbrequired:0,height:r.height,previousblockhash:w.revHex(r.prevBlock),target:w.revHex(r.target.toString("hex")),bits:w.hex32(r.bits),noncerange:"00000000ffffffff",curtime:r.time,mintime:r.mtp+1,maxtime:r.time+7200,expires:r.time+7200,sigoplimit:u.MAX_BLOCK_SIGOPS_COST/n|0,sizelimit:u.MAX_BLOCK_SIZE,weightlimit:void 0,longpollid:this.chain.tip.rhash()+w.pad32(this.totalTX()),submitold:!1,coinbaseaux:{flags:r.coinbaseFlags.toString("hex")},coinbasevalue:void 0,coinbasetxn:void 0,default_witness_commitment:void 0,transactions:p};return r.witness&&(e.sizelimit=u.MAX_RAW_BLOCK_SIZE,e.weightlimit=u.MAX_BLOCK_WEIGHT),t?((t=(o=r.toCoinbase()).inputs[0]).script.pop(),t.script.compile(),r.witness&&(S=o.outputs.pop(),s(S.script.isCommitment()),t.witness.clear()),o.refresh(),e.coinbasetxn={data:o.toRaw().toString("hex"),txid:o.txid(),hash:o.wtxid(),depends:[],fee:0,sigops:o.getSigopsCost()/n|0,weight:o.getWeight()}):e.coinbasevalue=r.getReward(),-1!==i.indexOf("segwit")&&(e.default_witness_commitment=r.getWitnessScript().toJSON()),e}async getMiningInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.mininginfo");let i=0,r=0,s=0,n=0;if(t=this.attempt){r=t.weight,s=t.items.length+1,n=t.getDifficulty(),i=1e3;for(const e of t.items)i+=e.tx.getBaseSize()}return{blocks:this.chain.height,currentblocksize:i,currentblockweight:r,currentblocktx:s,difficulty:n,errors:"",genproclimit:this.procLimit,networkhashps:await this.getHashRate(120),pooledtx:this.totalTX(),testnet:"main"!=this.network.type,chain:"testnet"!==this.network.type?this.network.type:"test",generate:this.node.config.mining}}async getNetworkHashPS(e,t){if(t||2<e.length)throw new c(a.MISC_ERROR,"getnetworkhashps ( blocks height )");return e=(t=new x([e])).u32(0,120),t=t.u32(1),this.getHashRate(e,t)}async prioritiseTransaction(e,t){if(t||3!==e.length)throw new c(a.MISC_ERROR,"tx.prioritise <txid> <priority delta> <fee delta>");e=(t=new x([e])).hash(0);var i=t.i64(1);t=t.i64(2);if(!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(!e)throw new c(a.TYPE_ERROR,"Invalid TXID");if(null==i||null==t)throw new c(a.TYPE_ERROR,"Invalid fee or priority.");if(e=this.mempool.getEntry(e))return this.mempool.prioritise(e,i,t),!0;throw new c(a.MISC_ERROR,"Transaction not in mempool.")}async verifyBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'block.verify "hexdata": 校验区块数据 区块数据HEX串');if(!(t=new x([e]).buf(0)))throw new c(a.TYPE_ERROR,"Invalid block hex.");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Cannot verify block in SPV mode.");e=A.fromRaw(t);try{await this.chain.verifyBlock(e)}catch(e){if("VerifyError"===e.type)return e.reason;throw e}return null}async getGenerate(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"miner.check: 检查矿机运行状态");return{mode:this.node.config.mining}}async setSync(e,t){this.chain.synced=!0,this.chain.emit("chain.full")}async getMinerAddr(e,t){if(t)throw new c(a.MISC_ERROR,"miner.getaddr.admin: 查询矿机奖励地址");return{address:this.node.config.coinbaseAddress}}async addMinerAddr(e,t){if(t)throw new c(a.MISC_ERROR,"miner.addaddr.admin address: 添加矿机奖励地址");(t=new x([e]).str(0,""))&&(this.miner.addresses.unshift(t),this.node.config.coinbaseAddress=this.miner.addresses.reduce((e,t)=>e+(e?","+t:t),""),await this.node.config.saveAsync())}async setMinerAddr(e,t){if(t)throw new c(a.MISC_ERROR,"miner.setaddr.admin addresses: 设置矿机奖励地址");let i=new x([e]).array(0,"");if(!i||0==i.length){if((t=await this.execute({method:"address.index",params:[1]})).error)throw new c(a.MISC_ERROR,"获取默认矿机奖励地址出错");i=[t.result]}this.miner.addresses=i.reduce((e,t)=>(e.push(new R(t)),e),[]),this.node.config.coinbaseAddress=i.reduce((e,t)=>e+(e?","+t:t),""),await this.node.config.saveAsync()}async remoteNotifySet(e,t){if(t)throw new c(a.MISC_ERROR,"remoteNotify.set url secret: 设置远程消息推送 远程地址 签名密钥");return e.length<1||(e=(t=new x([e])).str(0,""),t=t.str(1,""),this.node.config.remotenotify=e,this.node.config.remotesecret=t,this.node.config.saveAsync()),{url:this.node.config.remotenotify,secret:this.node.config.remotesecret}}async setGenerate(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,"miner.set.admin mine ( proclimit ): 设置矿机运行状态 [true|false] (进程数限制)");if(e=(t=new x([e])).bool(0,!1),t=t.u32(1,0),e&&0===this.miner.addresses.length)throw new c(a.MISC_ERROR,"No addresses available for coinbase.");return this.node.config.mining!=e&&(this.node.config.mining=e,this.node.config.saveAsync(),this.procLimit=t,e?this.miner.cpu.start():this.miner.cpu.stop()),{mode:this.node.config.mining}}async generate(e,t){if(this.node.spv)throw new c(a.INVALID_REQUEST,"spv node can not generate new block");if(this.node.config.mining)throw new c(a.INVALID_REQUEST,"Miner is auto-running.");if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,"miner.generate.admin numblocks ( passphrase tip ): 生产区块 生产数量 ( 解锁密码 区块头 )");e=(t=new x([e])).u32(0,1);var i=t.str(1);t=t.hash(2);if(0===this.miner.addresses.length)throw new c(a.MISC_ERROR,"No addresses available for coinbase.");return this.mineBlocks(e,null,i,t)}async generateToAddress(e,t){if(this.node.spv)throw new c(a.INVALID_REQUEST,"spv node can not generate new block");if(this.node.config.mining)throw new c(a.INVALID_REQUEST,"Miner is auto-running.");if(t||2!==e.length)throw new c(a.MISC_ERROR,"miner.generateto.admin numblocks address: 生产区块并发奖至 生产数量 奖励地址 ( 解锁密码 区块头 )");e=(t=new x([e])).u32(0,1);var i=t.str(1,""),r=t.str(2);t=t.str(3),i=n.parseAddress(i,this.network);return this.mineBlocks(e,i,r,t)}async createRawTransaction(e,t){if(t||e.length<2||3<e.length)throw new c(a.MISC_ERROR,'tx.raw.create [{"txid":"id","vout":n},...] {"address":amount,"data":"hex",...} ( locktime ): 创建交易,返回交易原始数据');const i=new x([e]);t=i.array(0),e=i.obj(1);var r=i.u32(2);if(!t||!e)throw new c(a.TYPE_ERROR,"Invalid parameters (inputs and sendTo).");var s=new j;null!=r&&(s.locktime=r);for(const e of t){const t=new x([e]);var o=t.hash("txid"),h=t.u32("vout");let i=t.u32("sequence",4294967295);if(s.locktime&&i--,!o||null==h)throw new c(a.TYPE_ERROR,"Invalid outpoint.");var u=new C;u.prevout.hash=o,u.prevout.index=h,u.sequence=i,s.inputs.push(u)}var l=new x([e]),p=new Set;for(const t of Object.keys(e))if("data"===t){var d=l.buf(t);if(!d)throw new c(a.TYPE_ERROR,"Invalid nulldata..");var f=new T;f.value=0,f.script.createScript(d,y.types.NULLDATA),s.outputs.push(f)}else{if(f=(d=n.parseAddress(t,this.network)).toString(this.network),p.has(f))throw new c(a.INVALID_PARAMETER,"Duplicate address");p.add(f);var m=l.ufixed(t,8);if(null==m)throw new c(a.TYPE_ERROR,"Invalid output value.");var g=new T;g.value=m,g.script.fromAddress(d),s.outputs.push(g)}return s.toRaw().toString("hex")}async decodeRawTransaction(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'tx.raw.decode "hexstring": 解码交易原始数据 交易原始数据');if(s(!this.chain.options.spv,"Cannot get TX in SPV mode."),!(t=new x([e]).buf(0)))throw new c(a.TYPE_ERROR,"Invalid hex string.");e=B.fromRaw(t);if((t=await this.node.getMeta(e.hash("hex")))&&t.block)return t=await this.chain.getEntry(t.block),this.txToJSON(e,t);throw new c(a.TYPE_ERROR,"TX Not Confirmed.")}async decodeScript(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.decodescript "hex"');t=new x([e]).buf(0);let i=new y;return t&&(i=y.fromRaw(t)),e=R.fromScripthash(i.hash160()),(t=this.scriptToJSON(i)).p2sh=e.toString(this.network),t}async getRawTransaction(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,'tx.raw.get "txid" ( verbose ): 获取交易原始数据 交易哈希小端 [展开为对象]');if(s(!this.chain.options.spv,"Cannot get TX in SPV mode."),e=(t=new x([e])).hash(0),t=t.bool(1,!1),!e)throw new c(a.TYPE_ERROR,"Invalid TXID.");if(!(e=await this.node.getMeta(e)))throw new c(a.MISC_ERROR,"Transaction not found.");var i=e.tx;if(!t)return i.toRaw().toString("hex");let r;return e.block&&(r=await this.chain.getEntry(e.block)),(t=this.txToJSON(i,r)).time=e.mtime,t.hex=i.toRaw().toString("hex"),t}async getTXByHash(e,t){if(t||1!=e.length)throw new c(a.MISC_ERROR,'tx.get "txid": 查询交易记录 交易哈希小端');t=new x([e]).hash(0);return(e=(s(t,"Hash is required."),s(!this.chain.options.spv,"Cannot get TX in SPV mode."),await this.node.getMeta(t)))?(t=await this.node.getMetaView(e),e.getJSON(this.network,t,this.chain.height)):null}async sendRawTransaction(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,'tx.raw.send "hexstring" ( allowhighfees ): 发送交易数据返回交易ID 交易原始数据 [允许高手续费]');if(t=new x([e]).buf(0))return e=B.fromRaw(t),await this.node.relay(e),e.txid();throw new c(a.TYPE_ERROR,"Invalid hex string.")}async signRawTransaction(e,t){if(t||e.length<1||4<e.length)throw new c(a.MISC_ERROR,'tx.raw.sign.admin "hexstring" ( [{"txid":"id","vout":n,"scriptPubKey":"hex",redeemScript":"hex"},...] ["privatekey1",...] sighashtype ): 签署交易');const i=new x([e]);t=i.buf(0),e=i.array(1);var r=i.array(2),s=i.str(3);if(!t)throw new c(a.TYPE_ERROR,"Invalid hex string.");if(!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");var o=j.fromRaw(t),h=(o.view=await this.mempool.getSpentView(o),new Map),u=[];if(r){const e=new x([r]);for(let t=0;t<r.length;t++){var l=e.str(t,"");l=n.parseSecret(l,this.network);h.set(l.getPublicKey("hex"),l),u.push(l)}}if(e)for(const t of e){const e=new x([t]);var p=e.hash("txid"),d=e.u32("vout"),f=e.buf("scriptPubKey"),m=e.ufixed("amount",8),g=e.buf("redeemScript");if(!p||null==d||!f||null==m)throw new c(a.INVALID_PARAMETER,"Invalid UTXO.");p=new P(p,d);var v=y.fromRaw(f);d=T.fromScript(v,m);if(o.view.addOutput(p,d),0!==u.length&&g&&(v.isScripthash()||v.isWitnessScripthash())){if(!g)throw new c(a.INVALID_PARAMETER,"P2SH requires redeem script.");var b=y.fromRaw(g);for(const e of b.code)if(e.data){var w=h.get(e.data.toString("hex"));if(w){w.script=b,w.witness=v.isWitnessScripthash(),w.refresh();break}}}}let k=y.hashType.ALL;if(s){if((t=s.split("|")).length<1||2<t.length)throw new c(a.INVALID_PARAMETER,"Invalid sighash type.");if(null==(k=y.hashType[t[0]]))throw new c(a.INVALID_PARAMETER,"Invalid sighash type.");if(2===t.length){if("ANYONECANPAY"!==t[1])throw new c(a.INVALID_PARAMETER,"Invalid sighash type.");k|=y.hashType.ANYONECANPAY}}return await o.signAsync(u,k,this.workers),{hex:o.toRaw().toString("hex"),complete:o.isSigned()}}async createMultisig(e,t){if(t||e.length<2||2<e.length)throw new c(a.MISC_ERROR,'sys.createmultisig nrequired ["key",...]');e=(t=new x([e])).u32(0,0);var i=t.array(1,[]);t=i.length;if(e<1||t<e||16<t)throw new c(a.INVALID_PARAMETER,"Invalid m and n values.");var r=new x([i]);for(let e=0;e<i.length;e++){var s=r.buf(e);if(!s)throw new c(a.TYPE_ERROR,"Invalid key.");if(!d.publicKeyVerify(s))throw new c(a.INVALID_ADDRESS_OR_KEY,"Invalid key.");i[e]=s}if((e=y.createScript([e,t,i],y.types.MULTISIG)).getSize()>u.MAX_SCRIPT_PUSH)throw new c(a.VERIFY_ERROR,"Redeem script exceeds size limit.");return{address:R.fromScript(e).toString(this.network),redeemScript:e.toJSON()}}async createWitnessAddress(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.createwitnessaddress "script"');if(t=new x([e]).buf(0))return e=y.fromRaw(t).forWitness(),{address:R.fromScript(e).toString(this.network),witnessScript:e.toJSON()};throw new c(a.TYPE_ERROR,"Invalid script hex.")}async validateAddress(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.validateaddress "address"');let i;t=new x([e]).str(0,"");try{i=R.fromString(t,this.network)}catch(e){return{isvalid:!1}}return e=y.fromAddress(i),{isvalid:!0,address:i.toString(this.network),scriptPubKey:e.toJSON(),ismine:!1,iswatchonly:!1}}async verifyMessage(e,t){if(t||3!==e.length)throw new c(a.MISC_ERROR,'sys.message.verify "bitcoinaddress" "signature" "message"');e=(t=new x([e])).str(0,"");var i,r,s,h=t.buf(1,null,"base64");t=t.str(2);if(h&&t)return e=n.parseAddress(e,this.network),t=Buffer.from(o+t,"utf8"),t=l.hash256(t),i=d.recover(t,h,0,!0),r=d.recover(t,h,1,!0),s=d.recover(t,h,2,!0),t=d.recover(t,h,3,!0),!!i&&p(l.hash160(i),e.hash)||!!r&&p(l.hash160(r),e.hash)||!!s&&p(l.hash160(s),e.hash)||!!t&&p(l.hash160(t),e.hash);throw new c(a.TYPE_ERROR,"Invalid parameters.")}async signMessageWithPrivkey(e,t){if(t||2!==e.length)throw new c(a.MISC_ERROR,'sys.message.signk "privkey" "message"');return e=(t=new x([e])).str(0,""),t=t.str(1,""),e=n.parseSecret(e,this.network),t=Buffer.from(o+t,"utf8"),t=l.hash256(t),e.sign(t).toString("base64")}async estimateFee(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"estimate.fee nblocks");if(t=new x([e]).u32(0,1),this.fees)return 0===(e=this.fees.estimateFee(t,!1))?-1:g.btc(e,!0);throw new c(a.MISC_ERROR,"Fee estimation not available.")}async estimatePriority(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"estimate.priority nblocks");if(t=new x([e]).u32(0,1),this.fees)return this.fees.estimatePriority(t,!1);throw new c(a.MISC_ERROR,"Priority estimation not available.")}async estimateSmartFee(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"estimate.smartfee nblocks");if(t=new x([e]).u32(0,1),!this.fees)throw new c(a.MISC_ERROR,"Fee estimation not available.");let i=this.fees.estimateFee(t,!0);return{fee:i=0===i?-1:g.btc(i,!0),blocks:t}}async estimateSmartPriority(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"estimate.smartpriority nblocks");if(t=new x([e]).u32(0,1),this.fees)return{priority:this.fees.estimatePriority(t,!0),blocks:t};throw new c(a.MISC_ERROR,"Priority estimation not available.")}async invalidateBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'block.invalidate.admin "hash": 标记区块为无效 区块哈希(小端)');if(t=new x([e]).hash(0))return await this.chain.invalidate(t),null;throw new c(a.TYPE_ERROR,"Invalid block hash.")}async reconsiderBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'block.reconsider.admin "hash": 取消区块无效标记 区块哈希(小端)');if(t=new x([e]).hash(0))return this.chain.removeInvalid(t),null;throw new c(a.TYPE_ERROR,"Invalid block hash.")}async setMockTime(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"sys.setmocktime timestamp");if(null==(t=new x([e]).u32(0)))throw new c(a.TYPE_ERROR,"Invalid timestamp.");return this.network.time.offset=0,e=this.network.now()-t,this.network.time.offset=-e,null}async getMemoryInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.memoryinfo");return w.memoryUsage()}async setLogLevel(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.setloglevel "level"');return t=new x([e]).str(0,""),this.logger.setLevel(t),null}async handleLongpoll(e){if(74!==e.length)throw new c(a.INVALID_PARAMETER,"Invalid longpoll ID.");var t=e.slice(0,64);e=parseInt(e.slice(64,74),10);if(!w.isHex(t)||!w.isU32(e))throw new c(a.INVALID_PARAMETER,"Invalid longpoll ID.");e=w.revHex(t),this.chain.tip.hash===e&&await this.longpoll()}longpoll(){return new Promise((e,t)=>{this.pollers.push(b.job(e,t))})}refreshBlock(){var e=this.pollers;this.attempt=null,this.lastActivity=0,this.merkleMap.clear(),this.nonce1=0,this.nonce2=0,this.pollers=[];for(const t of e)t.resolve()}bindChain(){this.boundChain||(this.boundChain=!0,this.node.on("block.connect",()=>{this.attempt&&this.refreshBlock()}),this.mempool&&this.node.on("tx",()=>{this.attempt&&10<w.now()-this.lastActivity&&this.refreshBlock()}))}async getTemplate(){this.bindChain();let e=this.attempt;return e?this.miner.updateTime(e):(e=await this.miner.createBlock(),this.attempt=e,this.lastActivity=w.now()),e}async updateWork(){this.bindChain();let e=this.attempt;if(e){if(e.address.isNull())throw new c(a.MISC_ERROR,"No addresses available for coinbase.");this.miner.updateTime(e),4294967296==++this.nonce2&&(this.nonce2=0,this.nonce1++);const t=this.nonce1,i=this.nonce2,r=e.getRoot(t,i).toString("hex");this.merkleMap.set(r,[t,i])}else{if(0===this.miner.addresses.length)throw new c(a.MISC_ERROR,"No addresses available for coinbase.");e=await this.miner.createBlock();const t=this.nonce1,i=this.nonce2,r=e.getRoot(t,i).toString("hex");this.attempt=e,this.lastActivity=w.now(),this.merkleMap.set(r,[t,i])}return e}async addBlock(e){var t=await this.locker.lock(),i=await this.chain.locker.lock();try{return await this._addBlock(e)}finally{i(),t()}}async _addBlock(e){this.logger.info("Handling submitted block: %s.",e.rhash());var t,i=await this.chain.getEntry(e.prevBlock);let r;i&&(await this.chain.getDeployments(e.time,i)).hasWitness()&&e.getCommitmentHash()&&(t=(i=e.txs[0]).inputs[0],i.hasWitness()||(this.logger.warning("Submitted block had no witness nonce."),this.logger.debug(i),t.witness.push(k.ZERO_HASH),t.witness.compile(),i.refresh(),e.refresh()));try{r=await this.chain._add(e)}catch(t){if("VerifyError"===t.type)return this.logger.warning("RPC block rejected: %s (%s).",e.rhash(),t.reason),"rejected: "+t.reason;throw t}return r?null:(this.logger.warning("RPC block rejected: %s (bad-prevblk).",e.rhash()),"rejected: bad-prevblk")}totalTX(){return this.mempool?this.mempool.map.size:0}getSoftforks(){return[{id:"bip66",version:3,reject:{status:this.chain.state.hasBIP66()}}]}async getBIP9Softforks(){var e=this.chain.tip,t={};for(const r of this.network.deploys){var i=await this.chain.getState(e,r);i=f.thresholdStates.getName(i);t[r.name]={status:i,bit:r.bit,startTime:r.startTime,timeout:r.timeout}}return t}async getTXByAddress(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"tx.list.address address: 按地址查询交易列表");t=new x([e]).str(0);var i=(s(t,"Address is required."),s(!this.chain.options.spv,"Cannot get TX in SPV mode."),[]);for(const e of await this.node.getMetaByAddress(t)){var r=await this.node.getMetaView(e);i.push(e.getJSON(this.network,r,this.chain.height))}return i}async getVpByAddress(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"prop.byaddress address: 按地址查询道具列表");return t=new x([e]).str(0),s(t,"Address is required."),s(!this.chain.options.spv,"Cannot get TX in SPV mode."),this.chain.db.getVpByAddress(t)}async getVpByHashIndex(e,t){if(t||2!==e.length)throw new c(a.MISC_ERROR,"prop.byHashIndex hash index: 按输出查询道具");var i,r;e=(t=new x([e])).hash(0),t=t.int(1,0);return(e=(s(e,"Hash is required."),await this.node.getMeta(e)))&&(i=e.tx.outputs[t])?((r=i.getReturnData([N.OP_PROPCREATE,N.OP_PROPEXCHANGE]))&&(r.current={hash:e.tx.rhash("hex"),index:t,address:i.getAddress().toString()}),r):null}async getVpById(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"prop.byid pid: 按道具编码查询道具列表");t=new x([e]).str(0);var i=[];if(e=await this.chain.db.propList.getVp(t)){t=e.current.hash,e.oper="exchange",i.push({oper:"exchange",pid:e.pid,oid:e.oid,cid:e.cid,current:{hash:w.revHex(e.current.hash),index:e.current.index,address:e.current.address},height:e.height});let a=[t,e.current.index];for(;;){var r=await this.node.getMeta(a[0]),s=r.tx;if(!s)break;if(!(s=s.outputs[a[1]]))break;var n=s.getReturnData([N.OP_PROPCREATE,N.OP_PROPEXCHANGE]);if(!n)break;if("new"==n.oper){n.current={hash:w.revHex(a[0]),index:a[1],address:s.getAddress().toString()},n.height=r.height,i.push(n);break}if(!n.prev)break;a=[n.prev.hash,n.prev.index]}}return i}async getTXByAddresses(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"tx.list.addresses addresses: 按地址集合查询交易列表");t=new x([e]).array(0);var i=(s(t,"Address is required."),s(!this.chain.options.spv,"Cannot get TX in SPV mode."),[]);for(const e of await this.node.getMetaByAddress(t)){var r=await this.node.getMetaView(e);i.push(e.getJSON(this.network,r,this.chain.height))}return i}async getHashRate(e,t){let i=this.chain.tip;if(!(i=null!=t?await this.chain.getEntry(t):i))return 0;s("number"==typeof e),s(0<=e),(e=0===e?i.height%this.network.pow.retargetInterval+1:e)>i.height&&(e=i.height);let r=i.time,n=r,o=i;for(let t=0;t<e;t++){if(!(o=await this.chain.getPrevious(o)))throw new c(a.DATABASE_ERROR,"Not found.");r=Math.min(o.time,r),n=Math.max(o.time,n)}var h;return 0==(t=n-r)?0:(h=i.chainwork.sub(o.chainwork),Number(h.toString())/t)}async mineBlocks(e,t,i,r){var s=await this.locker.lock();try{return await this._mineBlocks(e,t,i,r)}finally{s()}}async _mineBlocks(e,t,i,r){var n=[];for(let o=0;o<e;o++){var a=await this.miner.mineBlock(r,t,i);a=await this.chain.add(a);s(a),n.push(a.rhash())}return n}async findFork(e){for(;e;){if(await this.chain.isMainChain(e))return e;e=await this.chain.getPrevious(e)}throw new Error("Fork not found.")}txToJSON(e,t){var i;let r=0,s=null,n=0;t&&(i=t.height,r=t.time,s=t.rhash(),n=this.chain.height-i+1);var a=[];for(const t of e.inputs){var o={coinbase:void 0,txid:void 0,scriptSig:void 0,txinwitness:void 0,sequence:t.sequence};e.isCoinbase()?o.coinbase=t.script.toJSON():(o.txid=t.prevout.txid(),o.vout=t.prevout.index,o.scriptSig={asm:t.script.toASM(),hex:t.script.toJSON()}),0<t.witness.items.length&&(o.txinwitness=t.witness.items.map(e=>e.toString("hex"))),a.push(o)}var c=[];for(let t=0;t<e.outputs.length;t++){var h=e.outputs[t];c.push({value:g.btc(h.value,!0),n:t,scriptPubKey:this.scriptToJSON(h.script,!0)})}return{txid:e.txid(),hash:e.wtxid(),size:e.getSize(),vsize:e.getVirtualSize(),version:e.version,locktime:e.locktime,vin:a,vout:c,blockhash:s,confirmations:n,time:r,blocktime:r,hex:void 0}}scriptToJSON(e,t){var i=e.getType(),[t]=(i={asm:e.toASM(),hex:void 0,type:y.typesByVal[i],reqSigs:1,addresses:[],p2sh:void 0},t&&(i.hex=e.toJSON()),e.getMultisig());return(t=(-1!==t&&(i.reqSigs=t),R.fromScript(e)))&&(e=t.toString(this.network),i.addresses.push(e)),i}async headerToJSON(e){var t=await this.chain.getMedianTime(e),i=await this.chain.getNextHash(e.hash);return{hash:e.rhash(),confirmations:this.chain.height-e.height+1,height:e.height,version:e.version,versionHex:w.hex32(e.version),merkleroot:w.revHex(e.merkleRoot),time:e.time,mediantime:t,bits:e.bits,difficulty:m.bits2Diff(e.bits),chainwork:e.chainwork.toString("hex",64),previousblockhash:e.prevBlock!==k.NULL_HASH?w.revHex(e.prevBlock):null,nextblockhash:i?w.revHex(i):null}}async blockToJSON(e,t,i){var r,s=await this.chain.getMedianTime(e),n=await this.chain.getNextHash(e.hash),a=[];for(const s of t.txs)i?(r=this.txToJSON(s,e),a.push(r)):a.push(s.txid());return{hash:e.rhash(),confirmations:this.chain.height-e.height+1,strippedsize:t.getBaseSize(),size:t.getSize(),weight:t.getWeight(),height:e.height,version:e.version,versionHex:w.hex32(e.version),merkleroot:w.revHex(e.merkleRoot),coinbase:t.txs[0].inputs[0].script.toJSON(),tx:a,time:e.time,mediantime:s,bits:e.bits,nonce:t.nonce,difficulty:m.bits2Diff(e.bits),chainwork:e.chainwork.toString("hex",64),previousblockhash:e.prevBlock!==k.NULL_HASH?w.revHex(e.prevBlock):null,nextblockhash:n?w.revHex(n):null}}entryToJSON(e){return{size:e.size,fee:g.btc(e.deltaFee,!0),modifiedfee:0,time:e.time,height:e.height,startingpriority:e.priority,currentpriority:e.getPriority(this.chain.height),descendantcount:this.mempool.countDescendants(e),descendantsize:e.descSize,descendantfees:e.descFee,ancestorcount:this.mempool.countAncestors(e),ancestorsize:0,ancestorfees:0,depends:this.mempool.getDepends(e.tx).map(w.revHex)}}}},function(e,t,i){"use strict";
|
|
939
|
+
*/const r=i(59),s=i(0),n=i(78),a=n.errors,o=n.MAGIC_STRING,c=i(77),h=i(82),u=i(7),l=i(6),p=i(158),d=i(26),f=i(124),m=i(121),g=i(33),y=i(17),v=i(107),b=i(36),w=i(2),k=i(3),x=i(84),S=i(68),_=i(232).openapi,E=i(152);i(132).vpItem,i(219);const R=i(13),A=i(75),O=i(89),C=i(113),I=i(131),j=i(69),P=i(45),T=i(28),B=i(20),N=i(19).opcodes;function M(e){for(let i=0;i<e.length;i+=4){var t=e.readUInt32LE(i,!0);e.writeUInt32BE(t,i,!0)}}e.exports=class extends n{constructor(e){super(e),s(e,"RPC requires a Node."),this.node=e,this.keys=e.keys,this.workers=e.workers,this.chain=e.chain,this.mempool=e.mempool,this.pool=e.pool,this.fees=e.fees,this.miner=e.miner,this.logger=e.logger.context("rpc"),this.procLimit=0,this.attempt=null,this.lastActivity=0,this.boundChain=!1,this.nonce1=0,this.nonce2=0,this.merkleMap=new Map,this.pollers=[],this.generating=!1,this.init()}init(){this.add("help",this.help),this.add("miner",this.routerOfMiner),this.add("miner.generate.admin",this.generate),this.add("miner.generateto.admin",this.generateToAddress),this.add("miner.setsync.admin",this.setSync),this.add("miner.setaddr.admin",this.setMinerAddr),this.add("miner.addaddr.admin",this.addMinerAddr),this.add("miner.getaddr.admin",this.getMinerAddr),this.add("miner.set.admin",this.setGenerate),this.add("miner.check",this.getGenerate),this.add("miner.difficulty",this.getDifficulty),this.add("vote",this.routerOfVote),this.add("vote.show",this.voteShow),this.add("vote.check",this.voteCheck),this.add("oracle.check",this.oracleCheck),this.add("block",this.routerOfBlock),this.add("block.best",this.getBestBlockHash),this.add("block.count",this.getBlockCount),this.add("block.info",this.getBlock),this.add("block.info.byheight",this.getBlockByHeight),this.add("block.hash",this.getBlockHash),this.add("block.header",this.getBlockHeader),this.add("block.verify",this.verifyBlock),this.add("block.tips",this.getChainTips),this.add("block.template.admin",this.getBlockTemplate),this.add("block.submit.admin",this.submitBlock),this.add("block.reset.admin",this.resetBlock),this.add("block.rollback.admin",this.rollbackBlock),this.add("block.invalidate.admin",this.invalidateBlock),this.add("block.reconsider.admin",this.reconsiderBlock),this.add("cp.byClass",this.cpByClass),this.add("cp.byName",this.cpByName),this.add("cp.byId",this.cpById),this.add("remoteNotify.set",this.remoteNotifySet),this.add("sc.query",this.querySCList),this.add("sc.balance",this.scBalance),this.add("sc.model",this.querySCModel),this.add("comm",this.routerOfComm),this.add("tx",this.routerOfTx),this.add("tx.raw.get",this.getRawTransaction),this.add("tx.raw.decode",this.decodeRawTransaction),this.add("tx.raw.create",this.createRawTransaction),this.add("tx.raw.send",this.sendRawTransaction),this.add("tx.raw.sign.admin",this.signRawTransaction),this.add("tx.get",this.getTXByHash),this.add("tx.list.address",this.getTXByAddress),this.add("tx.list.addresses",this.getTXByAddresses),this.add("tx.broadcast",this.broadcast),this.add("tx.prioritise",this.prioritiseTransaction),this.add("tx.utxo",this.getTXOut),this.add("tx.txo.proof",this.getTXOutProof),this.add("tx.txo.verifyproof",this.verifyTXOutProof),this.add("tx.coins",this.getCoins),this.add("tx.coincache",this.getCoinCache),this.add("tx.coins.byoutpoint",this.getCoinByOutpoint),this.add("tx.spender",this.getSpender),this.add("prop.byaddress",this.getVpByAddress),this.add("prop.byid",this.getVpById),this.add("prop.byHashIndex",this.getVpByHashIndex),this.add("sys",this.routerOfSys),this.add("sys.info",this.getInfo),this.add("sys.dump",this.heapDump),this.add("sys.blockinfo",this.getBlockchainInfo),this.add("sys.peerinfo",this.getPeerInfo),this.add("sys.networkinfo",this.getNetworkInfo),this.add("sys.memoryinfo",this.getMemoryInfo),this.add("sys.mempoolinfo",this.getMempoolInfo),this.add("sys.mininginfo",this.getMiningInfo),this.add("sys.addednodeinfo",this.getAddedNodeInfo),this.add("sys.txoinfo",this.getTXOutSetInfo),this.add("sys.connectioncount",this.getConnectionCount),this.add("sys.disconnectnode",this.disconnectNode),this.add("sys.nettotals",this.getNetTotals),this.add("sys.prune",this.pruneBlockchain),this.add("sys.ping",this.ping),this.add("sys.setloglevel",this.setLogLevel),this.add("sys.setban",this.setBan),this.add("sys.listbanned",this.listBanned),this.add("sys.clearbanned",this.clearBanned),this.add("sys.addnode",this.addNode),this.add("sys.hashrate",this.getNetworkHashPS),this.add("sys.work",this.getWork),this.add("sys.worklp",this.getWorkLongpoll),this.add("sys.setmocktime",this.setMockTime),this.add("sys.message.verify",this.verifyMessage),this.add("sys.message.signk",this.signMessageWithPrivkey),this.add("sys.stop.admin",this.stop),this.add("sys.decodescript",this.decodeScript),this.add("sys.validateaddress",this.validateAddress),this.add("sys.createmultisig",this.createMultisig),this.add("sys.createwitnessaddress",this.createWitnessAddress),this.add("sys.createAuthToken",this.authtoken),this.add("sys.groupPrefix",this.addGroupPrefix),this.add("sys.devmode",this.setDevMode),this.add("sys.groupSuffix",this.addGroupSuffix),this.add("sys.changeSpecialCp",this.changeSpecialCp),this.add("sys.rescan",this.rescan),this.add("sys.alliance",this.routerOfAlliance),this.add("sys.alliance.info",this.getAllianceInfo),this.add("sys.alliance.addpeer",this.addPeer),this.add("sys.alliance.list",this.listAlliance),this.add("sys.alliance.export",this.exportAlliance),this.add("sys.alliance.getpeer",this.getPeer),this.add("sys.alliance.delpeer",this.delPeer),this.add("estimate",this.routerOfEstimate),this.add("estimate.fee",this.estimateFee),this.add("estimate.smartfee",this.estimateSmartFee),this.add("estimate.priority",this.estimatePriority),this.add("estimate.smartpriority",this.estimateSmartPriority),this.add("mempool",this.routerOfMempool),this.add("mempool.info",this.getMempoolInfo),this.add("mempool.orphans",this.getMempoolOrphans),this.add("mempool.reset",this.resetMempool),this.add("mempool.ancestors",this.getMempoolAncestors),this.add("mempool.descendants",this.getMempoolDescendants),this.add("mempool.entry",this.getMempoolEntry),this.add("mempool.raw",this.getRawMempool),this.add("mempool.snap",this.getMempool),Object.values(_).map(e=>{this.add(e.name,async(t,i)=>this.node.conn_s2local.execute(e.name,t))})}get wallet(){return null}set wallet(e){}async routerOfMiner(e){throw new c(a.MISC_ERROR,"\n miner.generate.admin 生产一个区块\n miner.generateto.admin 使用指定的令牌地址生产一个区块\n miner.set.admin 设置矿机运行状态\n miner.setsync.admin 设置块链同步完成\n miner.setaddr.admin 动态设置奖励地址\n miner.addaddr.admin 动态添加奖励地址\n miner.getaddr.admin 查询实时奖励地址\n miner.check 检查矿机运行状态\n miner.difficulty 检查当前挖矿难度\n ")}async routerOfVote(e){throw new c(a.MISC_ERROR,"\n vote.check 查询指定地址的选举结果\n vote.show 查询当前或指定区间票仓信息\n vote.send 进行投票\n oracle.check 查询指定标记的数据上链情况\n oracle.send 进行数据上链操作\n ")}async routerOfBlock(e){throw new c(a.MISC_ERROR,"\n block.best 获取当前主链顶部区块哈希(小端)\n block.count 获取当前主链区块数量\n block.info 查询区块内容\n block.info.byheight 根据高度查询区块内容\n block.hash 根据高度查询区块哈希(小端)\n block.header 根据哈希(小端)查询区块头\n block.verify 校验区块数据\n block.tips 列表所有分叉的头部信息\n block.invalidate.admin 标记区块无效\n block.reconsider.admin 取消区块无效标记\n block.template.admin 生成或校验区块数据模板\n block.submit.admin 提交区块数据\n block.reset.admin 重置区块头至指定区块\n block.rollback.admin 回滚区块至指定区块\n ")}async routerOfMempool(e){throw new c(a.MISC_ERROR,"\n mempool.info 查看交易池概要信息\n mempool.ancestors 向前搠源交易池中指定交易\n mempool.descendants 向后搠源交易池中指定交易\n mempool.entry 查询交易记录\n mempool.raw 查询交易池中原始数据\n mempool.snap 查询交易池中原始数据\n mempool.reset 重置内存池\n ")}async routerOfEstimate(e){throw new c(a.MISC_ERROR,"\n estimate.fee 评估费用\n estimate.smartfee 评估智能费用\n estimate.priority 评估优先权\n estimate.smartpriority 评估智能优先权\n ")}async routerOfSys(e){throw new c(a.MISC_ERROR,"\n sys.info 查询系统概要信息\n sys.blockinfo 查询块链概要信息\n sys.memoryinfo 查询交易池概要信息\n sys.networkinfo 查询网络概要信息\n sys.nettotals 查询网速概要\n sys.peerinfo 查询对等节点概要信息\n sys.mininginfo 查询矿机概要信息\n sys.txoinfo 查询TXO概要信息\n sys.prune 修剪块链数据\n sys.ping PING所有管道\n sys.setloglevel 设置日志等级\n sys.setban 禁止管道\n sys.listbanned 列表已禁管道\n sys.clearbanned 清除已禁管道\n sys.addnode 添加管道\n sys.addednodeinfo 查询管道信息\n sys.connectioncount 查询连接数\n sys.disconnectnode 断开管道\n sys.hashrate 查询网络哈希速率\n sys.work 获取工作量\n sys.worklp 获取工作量\n sys.setmocktime 修改网络时间戳\n sys.message.sign 签署网络消息\n sys.message.signk 指定私钥签署网络消息\n sys.message.verify 验证网络消息\n sys.stop.admin 停止节点运行\n sys.decodescript 解码脚本\n sys.validateaddress 校验地址\n sys.zap 移除超龄挂起交易\n sys.createmultisig 生成多签脚本\n sys.walletdb.stop 停止钱包数据库的运行\n sys.walletdb.create 重新创立钱包数据库\n sys.walletdb.destroy 新增RPC指令:彻底删除钱包数据库\n sys.createwitnessaddress 生成见证地址\n sys.groupPrefix 添加/删除ACL前缀成员\n sys.groupSuffix 添加/删除ACL后缀成员\n sys.createAuthToken 制备令牌固定量\n sys.changeSpecialCp 添加特约商户\n sys.alliance 联盟管理\n sys.log 审计日志查询\n ")}async routerOfAlliance(e){throw new c(a.MISC_ERROR,"\n sys.alliance.info 查询联盟节点信息\n sys.alliance.gettoken 生成信道令牌\n sys.alliance.addpeer 添加认证信道\n sys.alliance.delpeer 删除认证信道\n sys.alliance.getpeer 查看信道列表\n sys.alliance.create 创建联盟节点证书\n sys.alliance.delete 吊销联盟节点证书\n sys.alliance.list 列表联盟节点证书\n sys.alliance.export 导出联盟节点证书\n ")}async routerOfComm(e){throw new c(a.MISC_ERROR,"\n comm.notify 通知(钱包)\n comm.listNotify 查询通知列表(钱包)\n comm.secret 安全通信(钱包)\n comm.listContact 列表安全通信联系人\n comm.scanContact 扫描指定交易,用关联地址建立通信联系人\n ")}async routerOfTx(e){throw new c(a.MISC_ERROR,"\n tx.raw.get 获取交易原始数据\n tx.raw.decode 解码交易原始数据\n tx.raw.create 创建交易,返回交易原始数据\n tx.raw.send 发送交易数据返回交易ID\n tx.get 查询交易记录\n tx.list.address 按地址查询交易列表\n tx.list.addresses 按地址列表查询交易列表\n tx.broadcast 广播交易\n tx.prioritise 优化交易池中的交易\n tx.utxo 查询UTXO信息\n tx.spender 查询硬币的消费者\n tx.mstrans 列表待处理多签交易\n tx.mstrans.sign 签署待处理多签交易\n tx.coins 查询硬币信息\n tx.coins.byoutpoint 查询硬币信息\n tx.txo.proof 查询TXO工作量信息\n tx.txo.verifyproof 校验TXO工作量信息\n tx.get.wallet 查询交易记录(钱包)\n tx.list 交易列表(钱包)\n tx.create 创建交易(钱包)\n tx.send 发送交易(钱包)\n tx.last 最近的交易\n tx.pending 查询挂起交易\n tx.range 范围查询\n tx.history 查询历史交易\n tx.history.since 查询指定日期后的历史交易\n tx.resend.admin 重发当前钱包的挂起交易\n tx.resendall.admin 重发所有钱包的挂起交易\n tx.importprunedfunds.admin 导入修剪资金\n tx.removeprunedfunds.admin 移除已导入修剪资金\n tx.fund.admin 填充资金\n tx.sign.admin 签署交易(钱包)\n tx.abandon.admin 丢弃指定交易\n tx.abandonall.admin 废弃所有挂起的交易\n tx.raw.sign.admin 签署交易\n ")}async exportAlliance(e,t,i){if(t)throw new c(a.MISC_ERROR,"sys.alliance.export: 批量导出联盟成员证书");for(var s of this.node.config.alliances)s=s.split("|"),r.unsupported||r.writeFile(`${this.network.type}-${s[0]}-${s[1]}.keystore`,s[2],"utf8")}async listAlliance(e,t,i){if(t)throw new c(a.MISC_ERROR,"sys.alliance.list: 列表现有联盟成员");var r,s=[];t={name:this.node.config.allianceName,id:this.node.config.allianceNodeId,address:this.node.config.allianceAwardAddress,host:this.node.config.host+":"+this.node.config.port};for(r of(t.voted=(await this.chain.db.voteMgr.checkVote(t.address)).result,s.push(t),this.node.config.alliances)){var n;(n={name:(n=r.split("|"))[0],id:n[1],address:n[4],host:n[5]}).voted=(await this.chain.db.voteMgr.checkVote(n.address)).result,s.push(n)}return s}async addPeer(e,t,i){if(t||e.length<2)throw new c(a.MISC_ERROR,"sys.alliance.addpeer host key: 添加授信信道 地址 信道公钥");return this._addPeer(e)}async _addPeer(e){var t=(e=new x([e])).str(0),i=e.str(1),r=e.str(2);e=e.uint(3);return t&&i?(i==d.publicKeyCreate(Buffer.from(this.node.config.identityKey,"hex"),!0).toString("hex")||this.node.pool.authdb.getKnown(t)||(await this.node.rpc.addNode([t,"add"]),this.node.pool.authdb.addKnown(t,Buffer.from(i,"hex"))),r==this.node.config.allianceName&&e==this.node.config.allianceNodeId&&(this.node.config.abandon=!1,this.node.config.saveAsync()),{host:t,key:i}):null}async getPeer(e,t,i){if(t)throw new c(a.MISC_ERROR,"sys.alliance.getpeer: 查看授信信道");return{peer:this.node.config.knownPeers}}async delPeer(e,t,i){if(t||e.length<1)throw new c(a.MISC_ERROR,"sys.alliance.delpeer hostname: 删除授信信道 信道地址");var r;t={host:new x([e]).str(0)};return(e=this.node.require("walletdb"))&&(e=await e.get("primary"))&&(r=v.signObj(t,e.notifyKey.privateKey),await e.commNotify({dst:e.notifyAddress,content:JSON.stringify({cmd:"peerdel",payload:t,sig:r,pub:e.notifyKey.publicKey.toString("hex")})})),t}async _delPeer(e){let t={host:(e=new x([e])).str(0),allianceName:e.str(1),allianceNodeId:e.uint(2)};var i=this.node.config.knownPeers.length;for(let e=0;e<i;e++)if(-1!=this.node.config.knownPeers[e].indexOf(t.host)){var r=this.node.config.knownPeers.splice(e,1);t.key=r[0].split(" ")[1].replace(" ",""),this.pool.authdb.delKnown(t.host),await this.node.rpc.addNode([t.host,"remove"]),setTimeout(()=>{var e,i;for(e of this.pool.peers.getbyhost(t.host))e.destroy();for(i of this.pool.peers.getInbound())i.destroy()},6e3);break}return t.allianceName==this.node.config.allianceName&&t.allianceNodeId==this.node.config.allianceNodeId&&(this.node.config.abandon=!0,this.node.config.saveAsync()),t}async getAllianceInfo(e,t,i){if(t)throw new c(a.MISC_ERROR,"sys.alliance.info: 获取联盟信息");t=this.node.config.identityKey;var r=(t=d.publicKeyCreate(Buffer.from(t,"hex"),!0)).toString("hex");t=R.fromWitnessPubkeyhash(l.hash160(t),this.network.type).toString();return{alliancePrivateKey:this.node.config.alliancePrivateKey,peerIdentity:r,awardAddress:t,allianceName:this.node.config.allianceName,allianceNodeId:this.node.config.allianceNodeId}}async voteShow(e,t){if(t)throw new c(a.MISC_ERROR,"vote.show [zoneId]: 查询选举结果 [指定区间]");return t=new x([e]).uint(0,0),this.chain.db.voteMgr.getVote(t)}async oracleCheck(e,t){if(t)throw new c(a.MISC_ERROR,"oracle.check key: 查询上链数据 数据标记");return{k:t=new x([e]).str(0,""),v:(e=await this.chain.db.voteMgr.checkOracle(t)).v,vote:e.vote}}async voteCheck(e,t){if(t)throw new c(a.MISC_ERROR,"vote.check address: 查询选举结果 指定地址");return t=new x([e]).str(0,""),this.chain.db.voteMgr.checkVote(t)}async changeSpecialCp(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'sys.changeSpecialCp action[0-view 1-add 2-remove 3-clear] "[cid]": 添加/删除/清空特约商户');e=(t=new x([e])).uint(0,0);var i=t.array(1);if(e){switch(e){case 1:for(var r of i)this.node.specialCp.add(r);break;case 2:for(var s of i)this.node.specialCp.del(s);break;case 3:this.node.specialCp.clear()}await this.node.config.saveAsync()}return this.node.specialCp.content()}async setDevMode(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,"sys.devMode remove[true,false]: 设置/取消开发模式");return t=new x([e]).bool(0,!1),this.node.config.devMode=t,(e=this.node.require("walletdb"))&&(e.options.devMode=t),(e=this.node.require("contractdb"))&&(e.options.devMode=t),await this.node.config.saveAsync(),t}async addGroupPrefix(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'sys.groupPrefix "[[prefix, cid]]" remove[true,false]: 添加/删除前缀成员');e=(t=new x([e])).array(0);var i,r=t.bool(1,!1);for(i of e)r?(this.node.acl.delGroupPrefix(i[0],i[1]),await this.logAudit({address:this.node.config.coinbaseAddress||"",oper:"usermanager",hash:"unforbid/"+i[1],index:0})):(this.node.acl.addGroupPrefix(i[0],i[1]),await this.logAudit({address:this.node.config.coinbaseAddress||"",oper:"usermanager",hash:"forbid/"+i[1],index:0}));return await this.node.config.saveAsync(),!0}async logAudit(e){var t=this.node.require("walletdb");t&&await t.logAudit(e)}async rescan(e,t){if(t)throw new c(a.MISC_ERROR,'sys.rescan ( "height" )');return t=new x([e]).u32(0),this.node.scan(t,null,async(e,t)=>{await this.node.fire("sys.rescan",e,t)}),!0}async addGroupSuffix(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'sys.groupSuffix "[[suffix, cid]]" remove[true,false]: 添加/删除后缀成员');e=(t=new x([e])).array(0);var i,r=t.bool(1,!1);for(i of e)r?this.node.acl.delGroupSuffix(i[0],i[1]):this.node.acl.addGroupSuffix(i[0],i[1]);return await this.node.config.saveAsync(),!0}async heapDump(e,t){return this.node.config.heapDump(),!0}async getInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.info");t=this.mempool?this.mempool.map.size:0,e=this.mempool?this.mempool.getSize():0;let i=this.pool.hosts.getLocal();return i=i||this.pool.hosts.address,{version:h.version,testnet:"main"!=this.network.type,paytxfee:g.btc(this.network.feeRate,!0),relayfee:g.btc(this.network.minRelay,!0),network:this.network.type,chain:{height:this.chain.height,tip:this.chain.tip.rhash(),progress:this.chain.getProgress(),difficulty:m.bits2Diff(this.chain.tip.bits)},mempool:{tx:t,size:e},time:{uptime:this.node.uptime(),system:w.now(),adjusted:this.network.now(),offset:this.network.time.offset},memory:w.memoryUsage(),pool:{host:i.host,port:i.port,agent:this.pool.options.agent,protocolversion:this.pool.options.version,services:this.pool.options.services.toString(2),outbound:this.pool.peers.outbound,inbound:this.pool.peers.inbound,connections:this.pool.peers.size()},walletversion:0,balance:0,proxy:"",keypoololdest:0,keypoolsize:0,unlocked_until:0,errors:""}}async help(e){if(0===e.length)throw new c(a.MISC_ERROR,"\n miner 记账相关\n block 区块相关\n cp 实体管理\n prop 道具相关\n contract 交易对相关\n tx 交易相关\n sys 系统管理和状态监控\n estimate 评估\n mempool 交易池\n wallet 钱包管理\n key 密钥管理\n account 账户管理\n address 地址管理\n coin 硬币管理\n vote 投票管理\n htlc 跨链操作\n ");return e={method:e[0],params:[]},this.execute(e,!0)}async broadcast(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"tx.broadcast tx-hex: 广播交易 交易HEX字符串");return t=new x([e]).buf(0),s(t,"tx.broadcast: tx-hex is required."),e=B.fromRaw(t),await this.node.sendTX(e),!0}async authtoken(e,t,i){if(t||1!==e.length)throw new c(a.TYPE_ERROR,"sys.createAuthToken tids: 制备令牌固定量 终端编码列表(逗分字符串)");if(t=new x([e]).array(0),!Array.isArray(t))throw new c(a.TYPE_ERROR,"sys.createAuthToken tids: 制备令牌固定量 终端编码列表(逗分字符串)");var r,{aeskey:s,aesiv:n}=S.fromKey(k.ONE_HASH,this.node.keys.hmacSalt,this.network.type).getAes(i.options.cid),o=[];for(r of t){if(!("string"==typeof r&&r.length<=40))throw new c(a.TYPE_ERROR,"各终端编码必须是最大长度40字节的字符串");var h=S.getHmac(r.toString(),this.node.keys.hmacSalt).token,u=this.node.require("walletdb");u&&await u.logAudit({address:this.node.config.coinbaseAddress||"",oper:"usermanager",hash:"create/"+r,index:0}),this.node.config.devMode?o.push({cid:r,encry:w.encrypt(s,n,h),token:h}):o.push({cid:r,encry:w.encrypt(s,n,h)})}return o}async querySCModel(e,t){return Object.keys(E.list).map(e=>E.list[e])}async querySCList(e,t){if(t)throw new c(a.MISC_ERROR,"sc.query (conditions): 查询合约 (查询条件)");t=new x([e]).array(0,[]),e=await this.chain.db.getSCList(t);var i,r=await this.node.cdb.get("primary");for(i of e.list){var s=await r.getBalance(i.options.addr);i.options.confirmed=s.toJSON().confirmed}return e}async scBalance(e,t){if(t)throw new c(a.MISC_ERROR,"sc.balance address: 查询合约库地址余额 指定地址");return t=new x([e]).str(0,""),(await(await this.node.cdb.get("primary")).getBalance(t)).toJSON()}async cpByClass(e,t){if(t||e.length<1||3<e.length)throw new c(a.MISC_ERROR,"cp.byClass cls: 查询CP编码集合 游戏类别 页码 页宽");e=(t=new x([e])).str(0,"");var i=t.uint(1,1),r=(t=t.uint(2,10),[]);return r.push(["size",t]),r.push(["page",i]),r.push(["cls",e]),this.chain.db.cpList.query(r)}async cpById(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'cp.byId "clientNo": 根据编码查询厂商记录');return(t=new x([e]).str(0))?this.chain.db.cpList.getRecord(t):null}async cpByName(e,t){if(t||e.length<1)throw new c(a.MISC_ERROR,'cp.byName "name": 根据名称查询厂商记录');return(t=new x([e]).str(0))?this.chain.db.cpList.getItemByName(decodeURIComponent(t)):null}async resetBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"block.reset.admin [hash | height]: 重置区块头 [区块哈希 | 区块高度]");let i=new x([e]).str(0);if(s(i,"Height is required."),1==this.node.config.mining)throw new c(a.MISC_ERROR,'Use "miner.set.admin false" stop miner first!');if(this.generating||this.node.miner&&this.node.miner.cpu.running)throw new c(a.MISC_ERROR,"Miner is running, stop it first!");return 64!==i.length&&(i=parseInt(i,10)),await this.chain.reset(i),this.logger.info("Chain has been reset: %s.",i),!0}async rollbackBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"block.rollback.admin [hash | height]: 回滚区块 [区块哈希| 区块高度]");if(t=new x([e]).str(0),s(t,"Height is required."),1==this.node.config.mining)throw new c(a.MISC_ERROR,'Use "miner.set.admin false" stop miner first!');if(this.generating||this.node.miner&&this.node.miner.cpu.running)throw new c(a.MISC_ERROR,"Miner is running, stop it first!");let i=null;if(i=64!==t.length?await this.chain.getEntry(parseInt(t,10)):await this.chain.getEntry(w.revHex(t)))return await this.chain.reorganize(i),this.logger.info("Chain has been reorganize: %s.",t),!0;throw new c(a.MISC_ERROR,"Block not found.")}async stop(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.stop.admin");return this.node.close().catch(e=>{setImmediate(()=>{throw e})}).finally(async()=>{await new Promise(e=>{setTimeout(e,1e4)}),process.exit(0)}),"Stopping."}async getNetworkInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.networkinfo");var i=[];for(const e of this.pool.hosts.local.values())i.push({address:e.addr.host,port:e.addr.port,score:e.score});return{version:h.version,subversion:this.pool.options.agent,protocolversion:this.pool.options.version,localservices:w.hex32(this.pool.options.services),localrelay:!this.pool.options.noRelay,timeoffset:this.network.time.offset,networkactive:this.pool.connected,connections:this.pool.peers.size(),networks:[],relayfee:g.btc(this.network.minRelay,!0),incrementalfee:0,localaddresses:i,warnings:""}}async addNode(e,t){if(t||2!==e.length)throw new c(a.MISC_ERROR,'sys.addnode "node" "add|remove|onetry"');var i=(e=new x([e])).str(0,"");switch(e.str(1,"")){case"add":if(-1!=this.node.config.nodes.indexOf(i))break;this.node.config.nodes.push(i),await this.node.config.saveAsync(),this.pool.hosts.addNode(i);case"onetry":var r=n.parseNetAddress(i,this.network);this.pool.peers.get(r.hostname)||(r=this.pool.createOutbound(r),this.pool.peers.add(r));break;case"remove":-1!=(r=this.node.config.nodes.indexOf(i))&&(this.node.config.nodes.splice(r,1),await this.node.config.saveAsync()),this.pool.hosts.removeNode(i)}return this.getAddedNodeInfo([],t)}async disconnectNode(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.disconnectnode "node"');return t=new x([e]).str(0,""),e=n.parseIP(t,this.network),(t=this.pool.peers.get(e.hostname))&&t.destroy(),null}async getAddedNodeInfo(e,t){if(t||1<e.length)throw new c(a.MISC_ERROR,'sys.addednodeinfo ( "node" )');t=this.pool.hosts;var i=new x([e]).str(0,"");let r;1===e.length&&(r=n.parseIP(i,this.network));var s=[];for(const e of t.nodes){if(r){if(e.host!==r.host)continue;if(e.port!==r.port)continue}var o=this.pool.peers.get(e.hostname);o&&o.connected?s.push({addednode:e.hostname,connected:o.connected,addresses:[{address:o.hostname(),connected:o.outbound?"outbound":"inbound"}]}):s.push({addednode:e.hostname,connected:!1,addresses:[]})}if(r&&0===s.length)throw new c(a.CLIENT_NODE_NOT_ADDED,"Node has not been added.");return s}async getConnectionCount(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.connectioncount");return this.pool.peers.size()}async getNetTotals(e,t){if(t||0<e.length)throw new c(a.MISC_ERROR,"sys.nettotals");let i=0,r=0;for(let e=this.pool.peers.head();e;e=e.next)i+=e.socket.bytesWritten,r+=e.socket.bytesRead;return{totalbytesrecv:r,totalbytessent:i,timemillis:w.ms()}}async getPeerInfo(e,t){if(t)throw new c(a.MISC_ERROR,"sys.peerinfo onlyOutbound");var i=new x([e]).bool(0,!1),r=[];for(let e=this.pool.peers.head();e;e=e.next)if(!i||e.outbound){let t=this.network.time.known.get(e.hostname());var s=[];null==t&&(t=0);for(const t in e.blockMap.keys()){var n=w.revHex(t);s.push(n)}r.push({id:e.id,addr:e.hostname(),addrlocal:e.local.isNull()?void 0:e.local.hostname,services:w.hex32(e.services),relaytxes:!e.noRelay,lastsend:e.lastSend/1e3|0,lastrecv:e.lastRecv/1e3|0,bytessent:e.socket.bytesWritten,bytesrecv:e.socket.bytesRead,conntime:0!==e.time?(w.ms()-e.time)/1e3|0:0,timeoffset:t,pingtime:-1!==e.lastPong?(e.lastPong-e.lastPing)/1e3:-1,minping:-1!==e.minPing?e.minPing/1e3:-1,version:e.version,subver:e.agent,inbound:!e.outbound,startingheight:e.height,besthash:null,bestheight:0,banscore:e.banScore,inflight:s,whitelisted:!1})}return r}async ping(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.ping");for(let e=this.pool.peers.head();e;e=e.next)e.sendPing();return null}async setBan(e,t){var i=(r=new x([e])).str(0,""),r=r.str(1,"");if(t||e.length<2||"add"!==r&&"remove"!==r)throw new c(a.MISC_ERROR,'sys.setban "ip(/netmask)" "add|remove" (bantime) (absolute)');var s=n.parseNetAddress(i,this.network);switch(r){case"add":this.pool.ban(s);break;case"remove":this.pool.unban(s)}return null}async listBanned(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.listbanned");var i,r,s=[];for([i,r]of this.pool.hosts.banned)s.push({address:i,banned_until:r+this.pool.options.banTime,ban_created:r,ban_reason:""});return s}async clearBanned(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.clearbanned");return this.pool.hosts.clearBanned(),null}async getBlockchainInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.blockinfo");return{chain:"testnet"!==this.network.type?this.network.type:"test",blocks:this.chain.height,headers:this.chain.height,orphan:this.chain.orphanMap.size,bestblockhash:this.chain.tip.rhash(),difficulty:m.bits2Diff(this.chain.tip.bits),mediantime:await this.chain.getMedianTime(this.chain.tip),verificationprogress:this.chain.getProgress(),chainwork:this.chain.tip.chainwork.toString("hex",64),pruned:this.chain.options.prune,softforks:this.getSoftforks(),bip9_softforks:await this.getBIP9Softforks(),pruneheight:this.chain.options.prune?Math.max(0,this.chain.height-this.network.block.keepBlocks):null}}async getBestBlockHash(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"block.best: 获取当前主链顶部区块哈希(小端)");return this.chain.tip.rhash()}async getBlockCount(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"block.count: 获取当前主链区块数量");return this.chain.tip.height}async getBlock(e,t){if(t||e.length<1||3<e.length)throw new c(a.MISC_ERROR,"block.info hash ( bool-verbose bool-details ): 查询区块内容 小端哈希 (展开为对象 更多细节)");e=(t=new x([e])).hash(0);var i=t.bool(1,!0);t=t.bool(2,!1);if(!e)throw new c(a.TYPE_ERROR,"Invalid block hash.");if(!(e=await this.chain.getEntry(e)))throw new c(a.MISC_ERROR,"Block not found");var r=await this.chain.getBlock(e.hash);if(r)return i?this.blockToJSON(e,r,t):r.toRaw().toString("hex");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Block not available (spv mode)");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Block not available (pruned data)");throw new c(a.MISC_ERROR,"Can't read block from disk")}async getBlockByHeight(e,t){if(t||e.length<1||3<e.length)throw new c(a.MISC_ERROR,'block.info.byheight "height" ( bool-verbose bool-details ): 根据高度查询区块 高度 (展开为对象 更多细节)');e=(t=new x([e])).u32(0,-1);var i=t.bool(1,!0);t=t.bool(2,!1);if(-1===e)throw new c(a.TYPE_ERROR,"Invalid block height.");if(!(e=await this.chain.getEntry(e)))throw new c(a.MISC_ERROR,"Block not found");var r=await this.chain.getBlock(e.hash);if(r)return i?this.blockToJSON(e,r,t):r.toRaw().toString("hex");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Block not available (spv mode)");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Block not available (pruned data)");throw new c(a.DATABASE_ERROR,"Can't read block from disk")}async getBlockHash(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"block.hash height: 根据高度查询区块哈希(小端)");if(null==(t=new x([e]).u32(0))||t>this.chain.height)throw new c(a.INVALID_PARAMETER,"Block height out of range.");if(e=await this.chain.getHash(t))return w.revHex(e);throw new c(a.MISC_ERROR,"Not found.")}async getCoinByOutpoint(e,t){if(t||2!=e.length)throw new c(a.MISC_ERROR,"tx.coins.byoutpoint txid index: 查询硬币列表 交易ID 交易内索引");return e=(t=new x([e])).hash(0),t=t.u32(1),s(e,"Hash is required."),s(null!=t,"Index is required."),s(!this.chain.options.spv,"Cannot get coins in SPV mode."),(e=await this.node.getCoin(e,t))?e.getJSON(this.network):null}async getSpender(e,t,i){var r=(e=new x([e])).hash(0);e=e.u32(1);return(r=(s(r,"Hash is required."),s(null!=e,"Index is required."),await this.chain.db.getSpender(r,e)))&&(r.txid=w.revHex(r.txid)),r}async getCoins(e,t){if(t||1!=e.length)throw new c(a.MISC_ERROR,"tx.coins addr: 查询硬币列表 地址");t=new x([e]).str(0,""),s(t,"Address is required."),s(!this.chain.options.spv,"Cannot get coins in SPV mode."),e=await this.node.getCoinsByAddress(t.split(","));var i=[];for(const t of e)i.push(t.getJSON(this.network));return i}async getCoinCache(e,t){return this.chain.db.coinCache.size}async getBlockHeader(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,'block.header "hash" ( verbose ): 查询区块头 哈希(小端) (展开为对象)');if(e=(t=new x([e])).hash(0),t=t.bool(1,!0),!e)throw new c(a.MISC_ERROR,"Invalid block hash.");if(e=await this.chain.getEntry(e))return t?this.headerToJSON(e):e.toRaw().toString("hex",0,80);throw new c(a.MISC_ERROR,"Block not found")}async getChainTips(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"block.tips: 列表所有分叉的头部信息");var i=[];for(const e of await this.chain.getTips()){var r=await this.chain.getEntry(e),n=(s(r),await this.findFork(r)),o=await this.chain.isMainChain(r);i.push({height:r.height,hash:r.rhash(),branchlen:r.height-n.height,status:o?"active":"valid-headers"})}return i}async getDifficulty(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"miner.difficulty: 查看当前挖矿难度");return m.bits2Diff(this.chain.tip.bits)}async resetMempool(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"mempool.reset");if(this.mempool)return this.mempool.reset();throw new c(a.MISC_ERROR,"No mempool available.")}async getMempoolInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.mempoolinfo");if(this.mempool)return{waiting:this.mempool.waiting.keys().length,orphans:this.mempool.orphans.size,size:this.mempool.map.size,bytes:this.mempool.getSize(),usage:this.mempool.getSize(),maxmempool:this.mempool.options.maxSize,mempoolminfee:g.btc(this.mempool.options.minRelay,!0)};throw new c(a.MISC_ERROR,"No mempool available.")}async getMempoolOrphans(e,t){if(!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");let i=[];return this.mempool.orphans.forEach((e,t)=>{i.push(w.revHex(t))}),i}async getMempoolAncestors(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,"mempool.ancestors txid (bool-verbose): 向前搠源 交易哈希小端 [展开为对象]");if(e=(t=new x([e])).hash(0),t=t.bool(1,!1),!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(!e)throw new c(a.TYPE_ERROR,"Invalid TXID.");const i=this.mempool.getEntry(e);if(!i)throw new c(a.MISC_ERROR,"Transaction not in mempool.");e=this.mempool.getAncestors(i);var r=[];if(t)for(const t of e)r.push(this.entryToJSON(t));else for(const t of e)r.push(t.txid());return r}async getMempoolDescendants(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,"mempool.descendants txid (bool-verbose): 向后搠源 交易哈希小端 [展开为对象]");if(e=(t=new x([e])).hash(0),t=t.bool(1,!1),!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(!e)throw new c(a.TYPE_ERROR,"Invalid TXID.");const i=this.mempool.getEntry(e);if(!i)throw new c(a.MISC_ERROR,"Transaction not in mempool.");e=this.mempool.getDescendants(i);var r=[];if(t)for(const t of e)r.push(this.entryToJSON(t));else for(const t of e)r.push(t.txid());return r}async getMempoolEntry(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"mempool.entry txid: 查询交易记录");if(t=new x([e]).hash(0),!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(!t)throw new c(a.TYPE_ERROR,"Invalid TXID.");if(e=this.mempool.getEntry(t))return this.entryToJSON(e);throw new c(a.MISC_ERROR,"Transaction not in mempool.")}async getMempool(e,t){if(t||0<e.length)throw new c(a.MISC_ERROR,"mempool.snap: 查询交易池原始记录");s(this.mempool,"No mempool available.");var i=[];for(const e of this.mempool.getSnapshot())i.push(w.revHex(e));return i}async getRawMempool(e,t){if(t||1<e.length)throw new c(a.MISC_ERROR,"mempool.raw ( bool-verbose ): 查询交易池原始记录 [展开为对象]");if(t=new x([e]).bool(0,!1),!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(t){var i={};for(const e of this.mempool.map.values())i[e.txid()]=this.entryToJSON(e);return i}return this.mempool.getSnapshot().map(w.revHex)}async getTXOut(e,t){if(t||e.length<2||3<e.length)throw new c(a.MISC_ERROR,'tx.utxo "txid" n ( includemempool )');e=(t=new x([e])).hash(0);var i=t.u32(1);t=t.bool(2,!0);if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Cannot get coins in SPV mode.");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Cannot get coins when pruned.");if(!e||null==i)throw new c(a.TYPE_ERROR,"Invalid outpoint.");let r;if(t){if(!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");r=this.mempool.getCoin(e,i)}return(r=r||await this.chain.getCoin(e,i))?{bestblock:this.chain.tip.rhash(),confirmations:r.getDepth(this.chain.height),value:g.btc(r.value,!0),scriptPubKey:this.scriptToJSON(r.script,!0),version:r.version,coinbase:r.coinbase}:null}async getTXOutProof(e,t){if(t||1!==e.length&&2!==e.length)throw new c(a.MISC_ERROR,'tx.txo.proof ["txid",...] ( blockhash )');var i=(t=new x([e])).array(0);const r=t.hash(1);if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Cannot get coins in SPV mode.");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Cannot get coins when pruned.");if(!i||0===i.length)throw new c(a.INVALID_PARAMETER,"Invalid TXIDs.");var s=new x([i]),n=new Set,o=[];let h=null;for(let e=0;e<i.length;e++){const t=s.hash(e);if(!t)throw new c(a.TYPE_ERROR,"Invalid TXID.");if(n.has(t))throw new c(a.INVALID_PARAMETER,"Duplicate txid.");n.add(t),o.push(t),h=t}let u=null;if(r?u=await this.chain.getBlock(r):this.chain.options.indexTX?(e=await this.chain.getMeta(h))&&(u=await this.chain.getBlock(e.block)):(t=await this.chain.getCoin(h,0))&&(u=await this.chain.getBlock(t.height)),!u)throw new c(a.MISC_ERROR,"Block not found.");for(const e of o)if(!u.hasTX(e))throw new c(a.VERIFY_ERROR,"Block does not contain all txids.");return(u=I.fromHashes(u,o)).toRaw().toString("hex")}async verifyTXOutProof(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'tx.txo.verifyproof "proof"');if(!(t=new x([e]).buf(0)))throw new c(a.TYPE_ERROR,"Invalid hex string.");if(!(e=I.fromRaw(t)).verify())return[];if(!await this.chain.getEntry(e.hash("hex")))throw new c(a.MISC_ERROR,"Block not found in chain.");var i=[];for(const t of e.getTree().matches)i.push(w.revHex(t.toString("hex")));return i}async getTXOutSetInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.txoinfo");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Chainstate not available (SPV mode).");return{height:this.chain.height,bestblock:this.chain.tip.rhash(),transactions:this.chain.db.state.tx,txouts:this.chain.db.state.coin,bytes_serialized:0,hash_serialized:0,total_amount:g.btc(this.chain.db.state.value,!0)}}async pruneBlockchain(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.prune: 修剪块链数据");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Cannot prune chain in SPV mode.");if(this.chain.options.prune)throw new c(a.MISC_ERROR,"Chain is already pruned.");if(this.chain.height<this.network.block.pruneAfterHeight)throw new c(a.MISC_ERROR,"Chain is too short for pruning.");try{await this.chain.prune()}catch(e){throw new c(a.DATABASE_ERROR,e.message)}}async submitWork(e){var t=await this.locker.lock();try{return await this._submitWork(e)}finally{t()}}async _submitWork(e){var t=this.attempt;if(!t)return!1;if(128!==e.length)throw new c(a.INVALID_PARAMETER,"Invalid work size.");if(M(e=e.slice(0,80)),(e=O.fromHead(e)).prevBlock!==t.prevBlock||e.bits!==t.bits)return!1;if(!e.verify())return!1;if(!(i=this.merkleMap.get(e.merkleRoot)))return!1;var i,[i,r]=i,s=e.nonce;e=e.time;if(!(i=t.getProof(i,r,e,s)).verify(t.target))return!1;let n;r=t.commit(i);try{n=await this.chain.add(r)}catch(e){if("VerifyError"===e.type)return this.logger.warning("RPC block rejected: %s (%s).",r.rhash(),e.reason),!1;throw e}return!!n||(this.logger.warning("RPC block rejected: %s (bad-prevblk).",r.rhash()),!1)}async createWork(e){var t=await this.locker.lock();try{return await this._createWork(e)}finally{t()}}async _createWork(){var e=await this.updateWork(),t=this.nonce1,i=this.nonce2,r=e.time,s=Buffer.allocUnsafe(128);s.fill(0),t=e.getRoot(t,i);return e.getHeader(t,r,0).copy(s,0),s[80]=128,s.writeUInt32BE(640,s.length-4,!0),M(s),{data:s.toString("hex"),target:e.target.toString("hex"),height:e.height}}async getWorkLongpoll(e,t){if(t||0!=e.length)throw new c(a.MISC_ERROR,"sys.worklp");return await this.longpoll(),this.createWork()}async getWork(e,t){if(t||1<e.length)throw new c(a.MISC_ERROR,'sys.work ( "data" )');if(1!==e.length)return this.createWork();if(t=new x([e]).buf(0))return this.submitWork(t);throw new c(a.TYPE_ERROR,"Invalid work data.")}async submitBlock(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,'block.submit.admin "hexdata" ( "jsonparametersobject" ): 提交区块数据 区块数据HEX串');return t=new x([e]).buf(0),e=A.fromRaw(t),this.addBlock(e)}async getBlockTemplate(e,t){if(t||1<e.length)throw new c(a.MISC_ERROR,"block.template.admin ( \"{'mode':'template | proposal', 'data': '{hex}', 'rules':['segwit']}\" ): 生成或校验区块数据模板");if(t=new x([e]).obj(0,{}),"template"!==(t=(e=new x([t])).str("mode","template"))&&"proposal"!==t)throw new c(a.INVALID_PARAMETER,"Invalid mode.");if("proposal"===t){if(!(t=e.buf("data")))throw new c(a.TYPE_ERROR,"Missing data parameter.");if((t=A.fromRaw(t)).prevBlock!==this.chain.tip.hash)return"inconclusive-not-best-prevblk";try{await this.chain.verifyBlock(t)}catch(e){if("VerifyError"===e.type)return e.reason;throw e}return null}let i=e.u32("maxversion",-1),r=e.array("rules");r&&(i=-1);let s=!1;if(t=e.array("capabilities")){let e=!1,i=!1;for(const r of t){if("string"!=typeof r)throw new c(a.TYPE_ERROR,"Invalid capability.");switch(r){case"coinbasetxn":e=!0;break;case"coinbasevalue":i=!0}}if(i=!0,e&&!i){if(0===this.miner.addresses.length)throw new c(a.MISC_ERROR,"No addresses available for coinbase.");s=!0}}return(t=e.str("longpollid"))&&await this.handleLongpoll(t),r=r||[],this.createTemplate(i,s,r)}async createTemplate(e,t,i){var r=await this.locker.lock();try{return await this._createTemplate(e,t,i)}finally{r()}}async _createTemplate(e,t,i){var r=await this.getTemplate(),n=r.witness?1:u.WITNESS_SCALE_FACTOR,o=["time","transactions","prevblock"],h=(2<=e&&o.push("version/force"),t&&(o.push("coinbase"),o.push("coinbase/append"),o.push("generation")),new Map);for(let e=0;e<r.items.length;e++){var l=r.items[e];h.set(l.hash,e+1)}var p=[];for(let e=0;e<r.items.length;e++){var d=r.items[e],m=d.tx,g=[];for(let t=0;t<m.inputs.length;t++){var y=m.inputs[t];null!=(y=h.get(y.prevout.hash))&&-1===g.indexOf(y)&&(s(y<e+1),g.push(y))}p.push({data:m.toRaw().toString("hex"),txid:m.txid(),hash:m.wtxid(),depends:g,fee:d.fee,sigops:d.sigops/n|0,weight:m.getWeight()})}let v=r.version;var b={},k=[];for(const e of this.network.deploys){var x=await this.chain.getState(this.chain.tip,e);let t=e.name;switch(x){case f.thresholdStates.DEFINED:case f.thresholdStates.FAILED:break;case f.thresholdStates.LOCKED_IN:v|=1<<e.bit;case f.thresholdStates.STARTED:e.force||(-1===i.indexOf(t)&&(v&=~(1<<e.bit)),e.required&&(t="!"+t)),b[t]=e.bit;break;case f.thresholdStates.ACTIVE:if(!e.force&&e.required){if(-1===i.indexOf(t))throw new c(a.INVALID_PARAMETER,`Client must support ${t}.`);t="!"+t}k.push(t);break;default:s(!1,"Bad state.")}}var S;e={capabilities:["proposal"],mutable:o,version:v>>>=0,rules:k,vbavailable:b,vbrequired:0,height:r.height,previousblockhash:w.revHex(r.prevBlock),target:w.revHex(r.target.toString("hex")),bits:w.hex32(r.bits),noncerange:"00000000ffffffff",curtime:r.time,mintime:r.mtp+1,maxtime:r.time+7200,expires:r.time+7200,sigoplimit:u.MAX_BLOCK_SIGOPS_COST/n|0,sizelimit:u.MAX_BLOCK_SIZE,weightlimit:void 0,longpollid:this.chain.tip.rhash()+w.pad32(this.totalTX()),submitold:!1,coinbaseaux:{flags:r.coinbaseFlags.toString("hex")},coinbasevalue:void 0,coinbasetxn:void 0,default_witness_commitment:void 0,transactions:p};return r.witness&&(e.sizelimit=u.MAX_RAW_BLOCK_SIZE,e.weightlimit=u.MAX_BLOCK_WEIGHT),t?((t=(o=r.toCoinbase()).inputs[0]).script.pop(),t.script.compile(),r.witness&&(S=o.outputs.pop(),s(S.script.isCommitment()),t.witness.clear()),o.refresh(),e.coinbasetxn={data:o.toRaw().toString("hex"),txid:o.txid(),hash:o.wtxid(),depends:[],fee:0,sigops:o.getSigopsCost()/n|0,weight:o.getWeight()}):e.coinbasevalue=r.getReward(),-1!==i.indexOf("segwit")&&(e.default_witness_commitment=r.getWitnessScript().toJSON()),e}async getMiningInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.mininginfo");let i=0,r=0,s=0,n=0;if(t=this.attempt){r=t.weight,s=t.items.length+1,n=t.getDifficulty(),i=1e3;for(const e of t.items)i+=e.tx.getBaseSize()}return{blocks:this.chain.height,currentblocksize:i,currentblockweight:r,currentblocktx:s,difficulty:n,errors:"",genproclimit:this.procLimit,networkhashps:await this.getHashRate(120),pooledtx:this.totalTX(),testnet:"main"!=this.network.type,chain:"testnet"!==this.network.type?this.network.type:"test",generate:this.node.config.mining}}async getNetworkHashPS(e,t){if(t||2<e.length)throw new c(a.MISC_ERROR,"getnetworkhashps ( blocks height )");return e=(t=new x([e])).u32(0,120),t=t.u32(1),this.getHashRate(e,t)}async prioritiseTransaction(e,t){if(t||3!==e.length)throw new c(a.MISC_ERROR,"tx.prioritise <txid> <priority delta> <fee delta>");e=(t=new x([e])).hash(0);var i=t.i64(1);t=t.i64(2);if(!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");if(!e)throw new c(a.TYPE_ERROR,"Invalid TXID");if(null==i||null==t)throw new c(a.TYPE_ERROR,"Invalid fee or priority.");if(e=this.mempool.getEntry(e))return this.mempool.prioritise(e,i,t),!0;throw new c(a.MISC_ERROR,"Transaction not in mempool.")}async verifyBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'block.verify "hexdata": 校验区块数据 区块数据HEX串');if(!(t=new x([e]).buf(0)))throw new c(a.TYPE_ERROR,"Invalid block hex.");if(this.chain.options.spv)throw new c(a.MISC_ERROR,"Cannot verify block in SPV mode.");e=A.fromRaw(t);try{await this.chain.verifyBlock(e)}catch(e){if("VerifyError"===e.type)return e.reason;throw e}return null}async getGenerate(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"miner.check: 检查矿机运行状态");return{mode:this.node.config.mining}}async setSync(e,t){this.chain.synced=!0,this.chain.emit("chain.full")}async getMinerAddr(e,t){if(t)throw new c(a.MISC_ERROR,"miner.getaddr.admin: 查询矿机奖励地址");return{address:this.node.config.coinbaseAddress}}async addMinerAddr(e,t){if(t)throw new c(a.MISC_ERROR,"miner.addaddr.admin address: 添加矿机奖励地址");(t=new x([e]).str(0,""))&&(this.miner.addresses.unshift(t),this.node.config.coinbaseAddress=this.miner.addresses.reduce((e,t)=>e+(e?","+t:t),""),await this.node.config.saveAsync())}async setMinerAddr(e,t){if(t)throw new c(a.MISC_ERROR,"miner.setaddr.admin addresses: 设置矿机奖励地址");let i=new x([e]).array(0,"");if(!i||0==i.length){if((t=await this.execute({method:"address.index",params:[1]})).error)throw new c(a.MISC_ERROR,"获取默认矿机奖励地址出错");i=[t.result]}this.miner.addresses=i.reduce((e,t)=>(e.push(new R(t)),e),[]),this.node.config.coinbaseAddress=i.reduce((e,t)=>e+(e?","+t:t),""),await this.node.config.saveAsync()}async remoteNotifySet(e,t){if(t)throw new c(a.MISC_ERROR,"remoteNotify.set url secret: 设置远程消息推送 远程地址 签名密钥");return e.length<1||(e=(t=new x([e])).str(0,""),t=t.str(1,""),this.node.config.remotenotify=e,this.node.config.remotesecret=t,this.node.config.saveAsync()),{url:this.node.config.remotenotify,secret:this.node.config.remotesecret}}async setGenerate(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,"miner.set.admin mine ( proclimit ): 设置矿机运行状态 [true|false] (进程数限制)");if(e=(t=new x([e])).bool(0,!1),t=t.u32(1,0),e&&0===this.miner.addresses.length)throw new c(a.MISC_ERROR,"No addresses available for coinbase.");return this.node.config.mining!=e&&(this.node.config.mining=e,this.node.config.saveAsync(),this.procLimit=t,e?this.miner.cpu.start():this.miner.cpu.stop()),{mode:this.node.config.mining}}async generate(e,t){if(this.node.spv)throw new c(a.INVALID_REQUEST,"spv node can not generate new block");if(this.node.config.mining)throw new c(a.INVALID_REQUEST,"Miner is auto-running.");if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,"miner.generate.admin numblocks ( passphrase tip ): 生产区块 生产数量 ( 解锁密码 区块头 )");e=(t=new x([e])).u32(0,1);var i=t.str(1);t=t.hash(2);if(0===this.miner.addresses.length)throw new c(a.MISC_ERROR,"No addresses available for coinbase.");return this.mineBlocks(e,null,i,t)}async generateToAddress(e,t){if(this.node.spv)throw new c(a.INVALID_REQUEST,"spv node can not generate new block");if(this.node.config.mining)throw new c(a.INVALID_REQUEST,"Miner is auto-running.");if(t||2!==e.length)throw new c(a.MISC_ERROR,"miner.generateto.admin numblocks address: 生产区块并发奖至 生产数量 奖励地址 ( 解锁密码 区块头 )");e=(t=new x([e])).u32(0,1);var i=t.str(1,""),r=t.str(2);t=t.str(3),i=n.parseAddress(i,this.network);return this.mineBlocks(e,i,r,t)}async createRawTransaction(e,t){if(t||e.length<2||3<e.length)throw new c(a.MISC_ERROR,'tx.raw.create [{"txid":"id","vout":n},...] {"address":amount,"data":"hex",...} ( locktime ): 创建交易,返回交易原始数据');const i=new x([e]);t=i.array(0),e=i.obj(1);var r=i.u32(2);if(!t||!e)throw new c(a.TYPE_ERROR,"Invalid parameters (inputs and sendTo).");var s=new j;null!=r&&(s.locktime=r);for(const e of t){const t=new x([e]);var o=t.hash("txid"),h=t.u32("vout");let i=t.u32("sequence",4294967295);if(s.locktime&&i--,!o||null==h)throw new c(a.TYPE_ERROR,"Invalid outpoint.");var u=new C;u.prevout.hash=o,u.prevout.index=h,u.sequence=i,s.inputs.push(u)}var l=new x([e]),p=new Set;for(const t of Object.keys(e))if("data"===t){var d=l.buf(t);if(!d)throw new c(a.TYPE_ERROR,"Invalid nulldata..");var f=new T;f.value=0,f.script.createScript(d,y.types.NULLDATA),s.outputs.push(f)}else{if(f=(d=n.parseAddress(t,this.network)).toString(this.network),p.has(f))throw new c(a.INVALID_PARAMETER,"Duplicate address");p.add(f);var m=l.ufixed(t,8);if(null==m)throw new c(a.TYPE_ERROR,"Invalid output value.");var g=new T;g.value=m,g.script.fromAddress(d),s.outputs.push(g)}return s.toRaw().toString("hex")}async decodeRawTransaction(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'tx.raw.decode "hexstring": 解码交易原始数据 交易原始数据');if(s(!this.chain.options.spv,"Cannot get TX in SPV mode."),!(t=new x([e]).buf(0)))throw new c(a.TYPE_ERROR,"Invalid hex string.");e=B.fromRaw(t);if((t=await this.node.getMeta(e.hash("hex")))&&t.block)return t=await this.chain.getEntry(t.block),this.txToJSON(e,t);throw new c(a.TYPE_ERROR,"TX Not Confirmed.")}async decodeScript(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.decodescript "hex"');t=new x([e]).buf(0);let i=new y;return t&&(i=y.fromRaw(t)),e=R.fromScripthash(i.hash160()),(t=this.scriptToJSON(i)).p2sh=e.toString(this.network),t}async getRawTransaction(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,'tx.raw.get "txid" ( verbose ): 获取交易原始数据 交易哈希小端 [展开为对象]');if(s(!this.chain.options.spv,"Cannot get TX in SPV mode."),e=(t=new x([e])).hash(0),t=t.bool(1,!1),!e)throw new c(a.TYPE_ERROR,"Invalid TXID.");if(!(e=await this.node.getMeta(e)))throw new c(a.MISC_ERROR,"Transaction not found.");var i=e.tx;if(!t)return i.toRaw().toString("hex");let r;return e.block&&(r=await this.chain.getEntry(e.block)),(t=this.txToJSON(i,r)).time=e.mtime,t.hex=i.toRaw().toString("hex"),t}async getTXByHash(e,t){if(t||1!=e.length)throw new c(a.MISC_ERROR,'tx.get "txid": 查询交易记录 交易哈希小端');t=new x([e]).hash(0);return(e=(s(t,"Hash is required."),s(!this.chain.options.spv,"Cannot get TX in SPV mode."),await this.node.getMeta(t)))?(t=await this.node.getMetaView(e),e.getJSON(this.network,t,this.chain.height)):null}async sendRawTransaction(e,t){if(t||e.length<1||2<e.length)throw new c(a.MISC_ERROR,'tx.raw.send "hexstring" ( allowhighfees ): 发送交易数据返回交易ID 交易原始数据 [允许高手续费]');if(t=new x([e]).buf(0))return e=B.fromRaw(t),await this.node.relay(e),e.txid();throw new c(a.TYPE_ERROR,"Invalid hex string.")}async signRawTransaction(e,t){if(t||e.length<1||4<e.length)throw new c(a.MISC_ERROR,'tx.raw.sign.admin "hexstring" ( [{"txid":"id","vout":n,"scriptPubKey":"hex",redeemScript":"hex"},...] ["privatekey1",...] sighashtype ): 签署交易');const i=new x([e]);t=i.buf(0),e=i.array(1);var r=i.array(2),s=i.str(3);if(!t)throw new c(a.TYPE_ERROR,"Invalid hex string.");if(!this.mempool)throw new c(a.MISC_ERROR,"No mempool available.");var o=j.fromRaw(t),h=(o.view=await this.mempool.getSpentView(o),new Map),u=[];if(r){const e=new x([r]);for(let t=0;t<r.length;t++){var l=e.str(t,"");l=n.parseSecret(l,this.network);h.set(l.getPublicKey("hex"),l),u.push(l)}}if(e)for(const t of e){const e=new x([t]);var p=e.hash("txid"),d=e.u32("vout"),f=e.buf("scriptPubKey"),m=e.ufixed("amount",8),g=e.buf("redeemScript");if(!p||null==d||!f||null==m)throw new c(a.INVALID_PARAMETER,"Invalid UTXO.");p=new P(p,d);var v=y.fromRaw(f);d=T.fromScript(v,m);if(o.view.addOutput(p,d),0!==u.length&&g&&(v.isScripthash()||v.isWitnessScripthash())){if(!g)throw new c(a.INVALID_PARAMETER,"P2SH requires redeem script.");var b=y.fromRaw(g);for(const e of b.code)if(e.data){var w=h.get(e.data.toString("hex"));if(w){w.script=b,w.witness=v.isWitnessScripthash(),w.refresh();break}}}}let k=y.hashType.ALL;if(s){if((t=s.split("|")).length<1||2<t.length)throw new c(a.INVALID_PARAMETER,"Invalid sighash type.");if(null==(k=y.hashType[t[0]]))throw new c(a.INVALID_PARAMETER,"Invalid sighash type.");if(2===t.length){if("ANYONECANPAY"!==t[1])throw new c(a.INVALID_PARAMETER,"Invalid sighash type.");k|=y.hashType.ANYONECANPAY}}return await o.signAsync(u,k,this.workers),{hex:o.toRaw().toString("hex"),complete:o.isSigned()}}async createMultisig(e,t){if(t||e.length<2||2<e.length)throw new c(a.MISC_ERROR,'sys.createmultisig nrequired ["key",...]');e=(t=new x([e])).u32(0,0);var i=t.array(1,[]);t=i.length;if(e<1||t<e||16<t)throw new c(a.INVALID_PARAMETER,"Invalid m and n values.");var r=new x([i]);for(let e=0;e<i.length;e++){var s=r.buf(e);if(!s)throw new c(a.TYPE_ERROR,"Invalid key.");if(!d.publicKeyVerify(s))throw new c(a.INVALID_ADDRESS_OR_KEY,"Invalid key.");i[e]=s}if((e=y.createScript([e,t,i],y.types.MULTISIG)).getSize()>u.MAX_SCRIPT_PUSH)throw new c(a.VERIFY_ERROR,"Redeem script exceeds size limit.");return{address:R.fromScript(e).toString(this.network),redeemScript:e.toJSON()}}async createWitnessAddress(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.createwitnessaddress "script"');if(t=new x([e]).buf(0))return e=y.fromRaw(t).forWitness(),{address:R.fromScript(e).toString(this.network),witnessScript:e.toJSON()};throw new c(a.TYPE_ERROR,"Invalid script hex.")}async validateAddress(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.validateaddress "address"');let i;t=new x([e]).str(0,"");try{i=R.fromString(t,this.network)}catch(e){return{isvalid:!1}}return e=y.fromAddress(i),{isvalid:!0,address:i.toString(this.network),scriptPubKey:e.toJSON(),ismine:!1,iswatchonly:!1}}async verifyMessage(e,t){if(t||3!==e.length)throw new c(a.MISC_ERROR,'sys.message.verify "bitcoinaddress" "signature" "message"');e=(t=new x([e])).str(0,"");var i,r,s,h=t.buf(1,null,"base64");t=t.str(2);if(h&&t)return e=n.parseAddress(e,this.network),t=Buffer.from(o+t,"utf8"),t=l.hash256(t),i=d.recover(t,h,0,!0),r=d.recover(t,h,1,!0),s=d.recover(t,h,2,!0),t=d.recover(t,h,3,!0),!!i&&p(l.hash160(i),e.hash)||!!r&&p(l.hash160(r),e.hash)||!!s&&p(l.hash160(s),e.hash)||!!t&&p(l.hash160(t),e.hash);throw new c(a.TYPE_ERROR,"Invalid parameters.")}async signMessageWithPrivkey(e,t){if(t||2!==e.length)throw new c(a.MISC_ERROR,'sys.message.signk "privkey" "message"');return e=(t=new x([e])).str(0,""),t=t.str(1,""),e=n.parseSecret(e,this.network),t=Buffer.from(o+t,"utf8"),t=l.hash256(t),e.sign(t).toString("base64")}async estimateFee(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"estimate.fee nblocks");if(t=new x([e]).u32(0,1),this.fees)return 0===(e=this.fees.estimateFee(t,!1))?-1:g.btc(e,!0);throw new c(a.MISC_ERROR,"Fee estimation not available.")}async estimatePriority(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"estimate.priority nblocks");if(t=new x([e]).u32(0,1),this.fees)return this.fees.estimatePriority(t,!1);throw new c(a.MISC_ERROR,"Priority estimation not available.")}async estimateSmartFee(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"estimate.smartfee nblocks");if(t=new x([e]).u32(0,1),!this.fees)throw new c(a.MISC_ERROR,"Fee estimation not available.");let i=this.fees.estimateFee(t,!0);return{fee:i=0===i?-1:g.btc(i,!0),blocks:t}}async estimateSmartPriority(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"estimate.smartpriority nblocks");if(t=new x([e]).u32(0,1),this.fees)return{priority:this.fees.estimatePriority(t,!0),blocks:t};throw new c(a.MISC_ERROR,"Priority estimation not available.")}async invalidateBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'block.invalidate.admin "hash": 标记区块为无效 区块哈希(小端)');if(t=new x([e]).hash(0))return await this.chain.invalidate(t),null;throw new c(a.TYPE_ERROR,"Invalid block hash.")}async reconsiderBlock(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'block.reconsider.admin "hash": 取消区块无效标记 区块哈希(小端)');if(t=new x([e]).hash(0))return this.chain.removeInvalid(t),null;throw new c(a.TYPE_ERROR,"Invalid block hash.")}async setMockTime(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"sys.setmocktime timestamp");if(null==(t=new x([e]).u32(0)))throw new c(a.TYPE_ERROR,"Invalid timestamp.");return this.network.time.offset=0,e=this.network.now()-t,this.network.time.offset=-e,null}async getMemoryInfo(e,t){if(t||0!==e.length)throw new c(a.MISC_ERROR,"sys.memoryinfo");return w.memoryUsage()}async setLogLevel(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,'sys.setloglevel "level"');return t=new x([e]).str(0,""),this.logger.setLevel(t),null}async handleLongpoll(e){if(74!==e.length)throw new c(a.INVALID_PARAMETER,"Invalid longpoll ID.");var t=e.slice(0,64);e=parseInt(e.slice(64,74),10);if(!w.isHex(t)||!w.isU32(e))throw new c(a.INVALID_PARAMETER,"Invalid longpoll ID.");e=w.revHex(t),this.chain.tip.hash===e&&await this.longpoll()}longpoll(){return new Promise((e,t)=>{this.pollers.push(b.job(e,t))})}refreshBlock(){var e=this.pollers;this.attempt=null,this.lastActivity=0,this.merkleMap.clear(),this.nonce1=0,this.nonce2=0,this.pollers=[];for(const t of e)t.resolve()}bindChain(){this.boundChain||(this.boundChain=!0,this.node.on("block.connect",()=>{this.attempt&&this.refreshBlock()}),this.mempool&&this.node.on("tx",()=>{this.attempt&&10<w.now()-this.lastActivity&&this.refreshBlock()}))}async getTemplate(){this.bindChain();let e=this.attempt;return e?this.miner.updateTime(e):(e=await this.miner.createBlock(),this.attempt=e,this.lastActivity=w.now()),e}async updateWork(){this.bindChain();let e=this.attempt;if(e){if(e.address.isNull())throw new c(a.MISC_ERROR,"No addresses available for coinbase.");this.miner.updateTime(e),4294967296==++this.nonce2&&(this.nonce2=0,this.nonce1++);const t=this.nonce1,i=this.nonce2,r=e.getRoot(t,i).toString("hex");this.merkleMap.set(r,[t,i])}else{if(0===this.miner.addresses.length)throw new c(a.MISC_ERROR,"No addresses available for coinbase.");e=await this.miner.createBlock();const t=this.nonce1,i=this.nonce2,r=e.getRoot(t,i).toString("hex");this.attempt=e,this.lastActivity=w.now(),this.merkleMap.set(r,[t,i])}return e}async addBlock(e){var t=await this.locker.lock(),i=await this.chain.locker.lock();try{return await this._addBlock(e)}finally{i(),t()}}async _addBlock(e){this.logger.info("Handling submitted block: %s.",e.rhash());var t,i=await this.chain.getEntry(e.prevBlock);let r;i&&(await this.chain.getDeployments(e.time,i)).hasWitness()&&e.getCommitmentHash()&&(t=(i=e.txs[0]).inputs[0],i.hasWitness()||(this.logger.warning("Submitted block had no witness nonce."),this.logger.debug(i),t.witness.push(k.ZERO_HASH),t.witness.compile(),i.refresh(),e.refresh()));try{r=await this.chain._add(e)}catch(t){if("VerifyError"===t.type)return this.logger.warning("RPC block rejected: %s (%s).",e.rhash(),t.reason),"rejected: "+t.reason;throw t}return r?null:(this.logger.warning("RPC block rejected: %s (bad-prevblk).",e.rhash()),"rejected: bad-prevblk")}totalTX(){return this.mempool?this.mempool.map.size:0}getSoftforks(){return[{id:"bip66",version:3,reject:{status:this.chain.state.hasBIP66()}}]}async getBIP9Softforks(){var e=this.chain.tip,t={};for(const r of this.network.deploys){var i=await this.chain.getState(e,r);i=f.thresholdStates.getName(i);t[r.name]={status:i,bit:r.bit,startTime:r.startTime,timeout:r.timeout}}return t}async getTXByAddress(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"tx.list.address address: 按地址查询交易列表");t=new x([e]).str(0);var i=(s(t,"Address is required."),s(!this.chain.options.spv,"Cannot get TX in SPV mode."),[]);for(const e of await this.node.getMetaByAddress(t)){var r=await this.node.getMetaView(e);i.push(e.getJSON(this.network,r,this.chain.height))}return i}async getVpByAddress(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"prop.byaddress address: 按地址查询道具列表");return t=new x([e]).str(0),s(t,"Address is required."),s(!this.chain.options.spv,"Cannot get TX in SPV mode."),this.chain.db.getVpByAddress(t)}async getVpByHashIndex(e,t){if(t||2!==e.length)throw new c(a.MISC_ERROR,"prop.byHashIndex hash index: 按输出查询道具");var i,r;e=(t=new x([e])).hash(0),t=t.int(1,0);return(e=(s(e,"Hash is required."),await this.node.getMeta(e)))&&(i=e.tx.outputs[t])?((r=i.getReturnData([N.OP_PROPCREATE,N.OP_PROPEXCHANGE]))&&(r.current={hash:e.tx.rhash("hex"),index:t,address:i.getAddress().toString()}),r):null}async getVpById(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"prop.byid pid: 按道具编码查询道具列表");t=new x([e]).str(0);var i=[];if(e=await this.chain.db.propList.getVp(t)){t=e.current.hash,e.oper="exchange",i.push({oper:"exchange",pid:e.pid,oid:e.oid,cid:e.cid,pst:e.pst,current:{hash:w.revHex(e.current.hash),index:e.current.index,address:e.current.address},height:e.height});let a=[t,e.current.index];for(;;){var r=await this.node.getMeta(a[0]),s=r.tx;if(!s)break;if(!(s=s.outputs[a[1]]))break;var n=s.getReturnData([N.OP_PROPCREATE,N.OP_PROPEXCHANGE]);if(!n)break;if("new"==n.oper){n.current={hash:w.revHex(a[0]),index:a[1],address:s.getAddress().toString()},n.height=r.height,i.push(n);break}if(!n.prev)break;a=[n.prev.hash,n.prev.index]}}return i}async getTXByAddresses(e,t){if(t||1!==e.length)throw new c(a.MISC_ERROR,"tx.list.addresses addresses: 按地址集合查询交易列表");t=new x([e]).array(0);var i=(s(t,"Address is required."),s(!this.chain.options.spv,"Cannot get TX in SPV mode."),[]);for(const e of await this.node.getMetaByAddress(t)){var r=await this.node.getMetaView(e);i.push(e.getJSON(this.network,r,this.chain.height))}return i}async getHashRate(e,t){let i=this.chain.tip;if(!(i=null!=t?await this.chain.getEntry(t):i))return 0;s("number"==typeof e),s(0<=e),(e=0===e?i.height%this.network.pow.retargetInterval+1:e)>i.height&&(e=i.height);let r=i.time,n=r,o=i;for(let t=0;t<e;t++){if(!(o=await this.chain.getPrevious(o)))throw new c(a.DATABASE_ERROR,"Not found.");r=Math.min(o.time,r),n=Math.max(o.time,n)}var h;return 0==(t=n-r)?0:(h=i.chainwork.sub(o.chainwork),Number(h.toString())/t)}async mineBlocks(e,t,i,r){var s=await this.locker.lock();try{return await this._mineBlocks(e,t,i,r)}finally{s()}}async _mineBlocks(e,t,i,r){var n=[];for(let o=0;o<e;o++){var a=await this.miner.mineBlock(r,t,i);a=await this.chain.add(a);s(a),n.push(a.rhash())}return n}async findFork(e){for(;e;){if(await this.chain.isMainChain(e))return e;e=await this.chain.getPrevious(e)}throw new Error("Fork not found.")}txToJSON(e,t){var i;let r=0,s=null,n=0;t&&(i=t.height,r=t.time,s=t.rhash(),n=this.chain.height-i+1);var a=[];for(const t of e.inputs){var o={coinbase:void 0,txid:void 0,scriptSig:void 0,txinwitness:void 0,sequence:t.sequence};e.isCoinbase()?o.coinbase=t.script.toJSON():(o.txid=t.prevout.txid(),o.vout=t.prevout.index,o.scriptSig={asm:t.script.toASM(),hex:t.script.toJSON()}),0<t.witness.items.length&&(o.txinwitness=t.witness.items.map(e=>e.toString("hex"))),a.push(o)}var c=[];for(let t=0;t<e.outputs.length;t++){var h=e.outputs[t];c.push({value:g.btc(h.value,!0),n:t,scriptPubKey:this.scriptToJSON(h.script,!0)})}return{txid:e.txid(),hash:e.wtxid(),size:e.getSize(),vsize:e.getVirtualSize(),version:e.version,locktime:e.locktime,vin:a,vout:c,blockhash:s,confirmations:n,time:r,blocktime:r,hex:void 0}}scriptToJSON(e,t){var i=e.getType(),[t]=(i={asm:e.toASM(),hex:void 0,type:y.typesByVal[i],reqSigs:1,addresses:[],p2sh:void 0},t&&(i.hex=e.toJSON()),e.getMultisig());return(t=(-1!==t&&(i.reqSigs=t),R.fromScript(e)))&&(e=t.toString(this.network),i.addresses.push(e)),i}async headerToJSON(e){var t=await this.chain.getMedianTime(e),i=await this.chain.getNextHash(e.hash);return{hash:e.rhash(),confirmations:this.chain.height-e.height+1,height:e.height,version:e.version,versionHex:w.hex32(e.version),merkleroot:w.revHex(e.merkleRoot),time:e.time,mediantime:t,bits:e.bits,difficulty:m.bits2Diff(e.bits),chainwork:e.chainwork.toString("hex",64),previousblockhash:e.prevBlock!==k.NULL_HASH?w.revHex(e.prevBlock):null,nextblockhash:i?w.revHex(i):null}}async blockToJSON(e,t,i){var r,s=await this.chain.getMedianTime(e),n=await this.chain.getNextHash(e.hash),a=[];for(const s of t.txs)i?(r=this.txToJSON(s,e),a.push(r)):a.push(s.txid());return{hash:e.rhash(),confirmations:this.chain.height-e.height+1,strippedsize:t.getBaseSize(),size:t.getSize(),weight:t.getWeight(),height:e.height,version:e.version,versionHex:w.hex32(e.version),merkleroot:w.revHex(e.merkleRoot),coinbase:t.txs[0].inputs[0].script.toJSON(),tx:a,time:e.time,mediantime:s,bits:e.bits,nonce:t.nonce,difficulty:m.bits2Diff(e.bits),chainwork:e.chainwork.toString("hex",64),previousblockhash:e.prevBlock!==k.NULL_HASH?w.revHex(e.prevBlock):null,nextblockhash:n?w.revHex(n):null}}entryToJSON(e){return{size:e.size,fee:g.btc(e.deltaFee,!0),modifiedfee:0,time:e.time,height:e.height,startingpriority:e.priority,currentpriority:e.getPriority(this.chain.height),descendantcount:this.mempool.countDescendants(e),descendantsize:e.descSize,descendantfees:e.descFee,ancestorcount:this.mempool.countAncestors(e),ancestorsize:0,ancestorfees:0,depends:this.mempool.getDepends(e.tx).map(w.revHex)}}}},function(e,t,i){"use strict";
|
|
940
940
|
/*!
|
|
941
941
|
* fees.js - fee estimation for vallnet
|
|
942
942
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|