gamegold 5.6.2 → 5.6.5
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 +5 -5
- package/lib/gamegold.js +5 -5
- package/package.json +1 -1
package/lib/gamegold-worker.js
CHANGED
|
@@ -75,7 +75,7 @@ const path = require('path');var gpath = path.join(__dirname, '../../../', 'node
|
|
|
75
75
|
* policy.js - bitcoin constants for vallnet
|
|
76
76
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
77
77
|
* https://github.com/bookmansoft/gamegold
|
|
78
|
-
*/const r=i(0);i=i(7),t.BASE_PORT=2e3,t.setPort=function(e,i=0){e.port=i+100*e.typeId+t.BASE_PORT,e.httpPort=i+100*e.typeId+t.BASE_PORT+2,e.publicPort=i+100*e.typeId+t.BASE_PORT+3,e.wsport=i+100*e.typeId+t.BASE_PORT+4,e.stratumPort=i+100*e.typeId+t.BASE_PORT+5},t.MAX_TX_VERSION=2,t.MAX_TX_SIZE=i.MAX_BLOCK_SIZE/10,t.MAX_TX_WEIGHT=i.MAX_BLOCK_WEIGHT/10,t.MAX_TX_SIGOPS=i.MAX_BLOCK_SIGOPS/5,t.MAX_TX_SIGOPS_COST=i.MAX_BLOCK_SIGOPS_COST/5,t.BYTES_PER_SIGOP=20,t.MIN_RELAY=1e3,t.BARE_MULTISIG=!0,t.FREE_THRESHOLD
|
|
78
|
+
*/const r=i(0);i=i(7),t.BASE_PORT=2e3,t.setPort=function(e,i=0){e.port=i+100*e.typeId+t.BASE_PORT,e.httpPort=i+100*e.typeId+t.BASE_PORT+2,e.publicPort=i+100*e.typeId+t.BASE_PORT+3,e.wsport=i+100*e.typeId+t.BASE_PORT+4,e.stratumPort=i+100*e.typeId+t.BASE_PORT+5},t.MAX_TX_VERSION=2,t.MAX_TX_SIZE=i.MAX_BLOCK_SIZE/10,t.MAX_TX_WEIGHT=i.MAX_BLOCK_WEIGHT/10,t.MAX_TX_SIGOPS=i.MAX_BLOCK_SIGOPS/5,t.MAX_TX_SIGOPS_COST=i.MAX_BLOCK_SIGOPS_COST/5,t.BYTES_PER_SIGOP=20,t.MIN_RELAY=1e3,t.BARE_MULTISIG=!0,t.FREE_THRESHOLD=144*i.COIN/250,t.MAX_P2SH_SIGOPS=15,t.MAX_OP_RETURN=262144,t.MAX_OP_INFO=2048,t.MAX_OP_RETURN_BYTES=t.MAX_OP_RETURN+3,t.MAX_P2WSH_STACK=100,t.MAX_P2WSH_PUSH=80,t.MAX_P2WSH_SIZE=3600,t.MEMPOOL_MAX_ANCESTORS=2e4,t.MEMPOOL_MAX_SIZE=1e3,t.MEMPOOL_EXPIRY_TIME=259200,t.MEMPOOL_MAX_ORPHANS=5e4,t.MIN_BLOCK_WEIGHT=8192,t.MAX_BLOCK_WEIGHT=1e7*i.WITNESS_SCALE_FACTOR,t.BLOCK_PRIORITY_WEIGHT=0,t.BLOCK_PRIORITY_THRESHOLD=t.FREE_THRESHOLD,t.getMinFee=function(e,i){if(null==i&&(i=t.MIN_RELAY),r(0<=e),r(0<=i),0===e)return 0;let a=Math.floor(i*e/1e3);return 0===a&&0<i?i:a},t.getRoundFee=function(e,i){if(null==i&&(i=t.MIN_RELAY),r(0<=e),r(0<=i),0===e)return 0;let a=i*Math.ceil(e/1e3);return 0===a&&0<i?i:a},t.getRate=function(e,t){return r(0<=e),r(0<=t),0===e?0:Math.floor(1e3*t/e)}},function(e,t,i){i=i(12).Buffer;var r={dsa:{parts:["p","q","g","y"],sizePart:"p"},rsa:{parts:["e","n"],sizePart:"n"},ecdsa:{parts:["curve","Q"],sizePart:"Q"},ed25519:{parts:["A"],sizePart:"A"}},a=(r.curve25519=r.ed25519,{dsa:{parts:["p","q","g","y","x"]},rsa:{parts:["n","e","d","iqmp","p","q"]},ecdsa:{parts:["curve","Q","d"]},ed25519:{parts:["A","k"]}});a.curve25519=a.ed25519,i={nistp256:{size:256,pkcs8oid:"1.2.840.10045.3.1.7",p:i.from("00ffffffff 00000001 00000000 0000000000000000 ffffffff ffffffff ffffffff".replace(/ /g,""),"hex"),a:i.from("00FFFFFFFF 00000001 00000000 0000000000000000 FFFFFFFF FFFFFFFF FFFFFFFC".replace(/ /g,""),"hex"),b:i.from("5ac635d8 aa3a93e7 b3ebbd55 769886bc651d06b0 cc53b0f6 3bce3c3e 27d2604b".replace(/ /g,""),"hex"),s:i.from("00c49d3608 86e70493 6a6678e1 139d26b7819f7e90".replace(/ /g,""),"hex"),n:i.from("00ffffffff 00000000 ffffffff ffffffffbce6faad a7179e84 f3b9cac2 fc632551".replace(/ /g,""),"hex"),G:i.from("046b17d1f2 e12c4247 f8bce6e5 63a440f277037d81 2deb33a0 f4a13945 d898c2964fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e162bce3357 6b315ece cbb64068 37bf51f5".replace(/ /g,""),"hex")},nistp384:{size:384,pkcs8oid:"1.3.132.0.34",p:i.from("00ffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff fffffffeffffffff 00000000 00000000 ffffffff".replace(/ /g,""),"hex"),a:i.from("00FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFEFFFFFFFF 00000000 00000000 FFFFFFFC".replace(/ /g,""),"hex"),b:i.from("b3312fa7 e23ee7e4 988e056b e3f82d19181d9c6e fe814112 0314088f 5013875ac656398d 8a2ed19d 2a85c8ed d3ec2aef".replace(/ /g,""),"hex"),s:i.from("00a335926a a319a27a 1d00896a 6773a4827acdac73".replace(/ /g,""),"hex"),n:i.from("00ffffffff ffffffff ffffffff ffffffffffffffff ffffffff c7634d81 f4372ddf581a0db2 48b0a77a ecec196a ccc52973".replace(/ /g,""),"hex"),G:i.from("04aa87ca22 be8b0537 8eb1c71e f320ad746e1d3b62 8ba79b98 59f741e0 82542a385502f25d bf55296c 3a545e38 72760ab73617de4a 96262c6f 5d9e98bf 9292dc29f8f41dbd 289a147c e9da3113 b5f0b8c00a60b1ce 1d7e819d 7a431d7c 90ea0e5f".replace(/ /g,""),"hex")},nistp521:{size:521,pkcs8oid:"1.3.132.0.35",p:i.from("01ffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff ffffffffffff".replace(/ /g,""),"hex"),a:i.from("01FFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFFFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC".replace(/ /g,""),"hex"),b:i.from("51953eb961 8e1c9a1f 929a21a0 b68540eea2da725b 99b315f3 b8b48991 8ef109e156193951 ec7e937b 1652c0bd 3bb1bf073573df88 3d2c34f1 ef451fd4 6b503f00".replace(/ /g,""),"hex"),s:i.from("00d09e8800 291cb853 96cc6717 393284aaa0da64ba".replace(/ /g,""),"hex"),n:i.from("01ffffffffff ffffffff ffffffff ffffffffffffffff ffffffff ffffffff fffffffa51868783 bf2f966b 7fcc0148 f709a5d03bb5c9b8 899c47ae bb6fb71e 91386409".replace(/ /g,""),"hex"),G:i.from("0400c6 858e06b7 0404e9cd 9e3ecb66 2395b4429c648139 053fb521 f828af60 6b4d3dbaa14b5e77 efe75928 fe1dc127 a2ffa8de3348b3c1 856a429b f97e7e31 c2e5bd660118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd998f54449 579b4468 17afbd17 273e662c97ee7299 5ef42640 c550b901 3fad0761353c7086 a272c240 88be9476 9fd16650".replace(/ /g,""),"hex")}};e.exports={info:r,privInfo:a,hashAlgs:{md5:!0,sha1:!0,sha256:!0,sha384:!0,sha512:!0},curves:i}},function(e,t){Array.prototype.array_diff=function(...e){return this.reduce((t,i)=>{let r=!1;for(let t=0;t<e.length;t++)-1!=e[t].indexOf(i)&&(r=!0);return r||t.push(i),t},[])},e.exports=class e{constructor(e){this.$dirty=!0,this.items=null,this.data=new Map,this.account=new Map,e&&this.load(e)}merge(e){for(var t of(this.$dirty=!0,this.items=null,e.data.keys()))this.data.set(t,e.data.get(t));for(var i of e.account.keys())this.account.set(i,e.account.get(i));return this}query(t,i,r){t=t||[];let a,s,n=10,o=1;var c=[];for(let e=0;e<t.length;e++){var u=t[e];u&&Array.isArray(u)?"size"==u[0]?(n=u[1],delete t[e]):"page"==u[0]?(o=u[1],delete t[e]):"@total"==u[0]||"@sum"==u[0]?(c.push(["sum",u[1]]),n=4294967295,delete t[e]):"@max"==u[0]?(c.push(["max",u[1]]),n=4294967295,delete t[e]):"@min"==u[0]?(c.push(["min",u[1]]),n=4294967295,delete t[e]):"@average"==u[0]?(c.push(["average",u[1]]),n=4294967295,delete t[e]):"wid"==u[0]?(a=u[1],delete t[e]):"account"==u[0]&&(s=u[1],delete t[e],a=a||1):delete t[e]}let h=this;if(a&&void 0!==s&&null!=s){var l=this.account.get(a+"."+s);if(!l)return{list:[],count:0,page:0,cur:0};h=new e(l.entries())}let p=h.where(t);return(p=Array.isArray(i)&&2<i.length?p.orderby(i[0],i[1]):p).paginate(n,o,c).result(r)}get dirty(){return this.$dirty}set dirty(e){this.$dirty=e}orderby(e,t){switch(this.items||(this.items=this.ToArray()),t){case"desc":this.items=this.items.sort((t,i)=>i[e]-t[e]);break;case"asc":this.items=this.items.sort((t,i)=>t[e]-i[e])}return this}paginate(e,t,i){return this.items||(this.items=this.ToArray()),t=t||1,this.pageSize=e||10,0<this.pageSize?this.items.length%this.pageSize==0?this.pageNum=this.items.length/this.pageSize|0:this.pageNum=1+(this.items.length/this.pageSize|0):(this.pageNum=1,this.pageSize=this.items.length),this.count=this.items.length,this.pageCur=t,this.statistic=i,this}result(e){let t={list:this.records(e||null),count:this.count,page:this.pageNum,cur:this.pageCur,countCur:this.countCur};return Array.isArray(this.statistic)&&this.statistic.map(e=>{t[e[1]]=this[e[1]]}),t}records(e){if(this.items||(this.items=this.ToArray()),0==this.items.length)return[];this.pageSize||(this.pageSize=this.items.length,this.pageNum=1,this.pageCur=1);var t=[];let i=this;if(!(this.pageCur>this.pageNum)){this.countCur=0;for(let r=this.pageSize*(this.pageCur-1);r<this.pageSize*this.pageCur&&this.items[r];r++){this.countCur++;let a=null;a=Array.isArray(e)?e.reduce((e,t)=>(e[t]=i.items[r][t],e),{}):this.items[r],Array.isArray(this.statistic)&&0<this.statistic.length?this.statistic.map(e=>{i[e[1]]=i[e[1]]||null;let t=null;var a;for(a of e[1].split("."))if(void 0===(t=(t||i.items[r])[a]))break;if(t)switch(e[0]){case"sum":i[e[1]]||(i[e[1]]=0),i[e[1]]+=t;break;case"max":(!i[e[1]]||i[e[1]]<t)&&(i[e[1]]=t);break;case"min":(!i[e[1]]||i[e[1]]>t)&&(i[e[1]]=t)}}):t.push(a)}}return t}async predict(t){var i,r,a=[];for([i,r]of[...this.data])await t(i,r)&&a.push([i,r]);return new e(a)}where(t){let i=[...this.data];for(var r of t)if(r&&Array.isArray(r)&&!(r.length<2)){let e={k:r[0],sign:2==r.length?"==":r[1],v:2==r.length?r[1]:r[2]};e.k&&void 0!==e.v&&(i=i.filter(([,t])=>{let i=null;var r;for(r of e.k.split("."))if(void 0===(i=(i||t)[r]))return!1;switch(e.sign){case"==":return i==e.v;case">":return i>e.v;case"<":return i<e.v;case"!=":return i!=e.v;case">=":return i>=e.v;case"<=":return i<=e.v;case"like":return"string"==typeof e.v&&"string"==typeof i&&(-1!=i.indexOf(e.v)||-1!=e.v.indexOf(i));case"notlike":return"string"!=typeof e.v||"string"!=typeof i||-1==i.indexOf(e.v)&&-1==e.v.indexOf(i);case"include":return!("string"!=typeof e.v&&!Array.isArray(e.v)||!i||-1==e.v.indexOf(i));case"exclude":return"string"!=typeof e.v&&!Array.isArray(e.v)||!i||-1==e.v.indexOf(i);default:return!1}}))}return new e(i)}excludeCids(e){return e=e||[],Array.isArray(e)?(e=Array.from(new Set(e))).reduce((e,t)=>(this.has(t)||e.push(t),e),[]):[]}diff(...e){return[...this.data.keys()].array_diff(...e.map(e=>[...e.data.keys()]))}has(e){return"object"==typeof e&&Buffer.isBuffer(e)&&(e=e.toString("hex")),this.data.has(e)}set(e,t){var i;t&&("object"==typeof e&&Buffer.isBuffer(e)&&(e=e.toString("hex")),t.wid&&void 0!==t.account&&null!=t.account&&(i=t.wid+"."+t.account,this.account.get(i)||this.account.set(i,new Map),this.account.get(i).set(e,t)),this.data.set(e,t),this.items=null)}get(e,t){return"object"==typeof e&&Buffer.isBuffer(e)&&(e=e.toString("hex")),t&&(e+=t),this.data.get(e)}getAccount(e,t){return(e=this.account.get(e+"."+t))?[...e.values()]:[]}remove(e){return this.delete(e)}delete(e){"object"==typeof e&&Buffer.isBuffer(e)&&(e=e.toString("hex")),(t=this.get(e))&&t.wid&&void 0!==t.account&&null!=t.account&&(t=this.account.get(t.wid+"."+t.account))&&t.delete(e);var t=this.data.delete(e);return this.items=null,t}deletes(e){var t;for(t of this.where(e).getKeys())this.data.delete(t);this.items=null}load(e,t=!0){for(var i of(t&&(this.data.clear(),this.items=null),e))this.set(i[0],i[1])}clear(){this.data.clear(),this.items=null}forEach(e,t){this.data.forEach(e,t||this)}ToArray(){return[...this.data.values()]}getKeys(){return[...this.data.keys()]}getSize(){return this.data.size}}},,function(e,t,i){"use strict";
|
|
79
79
|
/*!
|
|
80
80
|
* amount.js - amount object for vallnet
|
|
81
81
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -201,7 +201,7 @@ let r=[];[i(558),i(559),i(560),i(561),i(562),i(563),i(564),i(565),i(566),i(567),
|
|
|
201
201
|
* pkg.js - package constants
|
|
202
202
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
203
203
|
* https://github.com/bookmansoft/gamegold
|
|
204
|
-
*/t.protocol="vallnet",t.version="5.6.
|
|
204
|
+
*/t.protocol="vallnet",t.version="5.6.5",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,i){"use strict";
|
|
205
205
|
/*!
|
|
206
206
|
* common.js - p2p constants for vallnet
|
|
207
207
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -282,7 +282,7 @@ const r=i(19).opcodes;function a(e){let t=null;return new(0,(a.list[e.type]||a.l
|
|
|
282
282
|
/*!
|
|
283
283
|
* wallet.js - wallet object for vallnet
|
|
284
284
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
285
|
-
*/const r=i(0);var a=i(16);const s=i(15),n=i(2),o=i(3),c=i(35),u=i(198),h=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(69),g=i(334);i(218);const v=i(109),y=i(73),b=i(13),w=i(68),x=i(17),k=i(219),S=i(156),_=i(28),E=i(157),j=i(337),A=i(63),R=i(26),I=i(29),O=i(7),C=i(310),P=i(38),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),z=i(165),F=i(77),L=i(78),M=i(142),D=i(46),H=i(20),U=i(42),q=i(54),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),Y=i(37).VerifyError,G=i(153).ErItem,X=i(154).ErAbolishItem,J=i(228).EnchancementItem,Q=i(67),Z=i(59),ee=i(83),te=i(85).txdb,ie=i(31);class re extends a{constructor(e,t){super(),r(e,"DB required."),this.db=e,this.network=e.network,this.logger=e.logger,this.readLock=new u,this.writeLock=new c,this.sendLock=new c,this.indexCache=new A(1e4),this.accountCache=new A(1e4),this.pathCache=new A(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=o.ZERO_HASH,this.tokenDepth=0,this.master=new j,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,i,a=e.master;return a?("string"==typeof a&&(a=S.PrivateKey.fromBase58(a,this.network)),r(S.isPrivate(a),"Must create wallet with hd private key.")):(i=new T(e.mnemonic),a=S.fromMnemonic(i,this.network)),r(a.network===this.network,"Network mismatch for master key."),this.master.fromKey(a,i),null!=e.wid&&(r(n.isU32(e.wid)),this.wid=e.wid),e.id&&(r(y.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(r("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(r("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(r(n.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(r(Buffer.isBuffer(e.token)),r(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new re(e).fromOptions(t)}async init(e){var t=e.passphrase;r(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);r(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){r(this.initialized);var e=await this.getAccount(0);if(!e)throw new Error("Default account not found.");this.account=e,this.logger.info("Wallet opened (%s).",this.id),await this.txdb.open()}async ensureNotifyKey(){this.notifyKey||(await this.ensureAccount({name:"alliance",witness:!0}),this.notifyKey=await this.createReceive("alliance",1,this.master),this.notifyAddress=this.notifyKey.getAddress("string"))}async createAllianceInfo(e,t,i){var r={alliancename:e,nodeid:t};return e?(r.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),i?(r.prv=Buffer.alloc(0),r.pub=Buffer.from(i,"hex"),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type),r.mnemonic=new T):(i=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),r.mnemonic=new T({entropy:i,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),e=j.fromKey(S.fromMnemonic(r.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(r.mnemonic=T.fromOptions(this.master.mnemonic),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type)),r.address=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(),r}async destroy(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{t(),e()}}async addSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{i()}}async _addSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async removeSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{i()}}async _removeSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async setPassphrase(e,t){e&&await this.decrypt(e),t&&await this.encrypt(t)}async encrypt(e){var t=await this.writeLock.lock();try{return await this._encrypt(e)}finally{t()}}async _encrypt(e){e=await this.master.encrypt(e,!0),this.start();try{await this.db.encryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async decrypt(e){var t=await this.writeLock.lock();try{return await this._decrypt(e)}finally{t()}}async _decrypt(e){e=await this.master.decrypt(e,!0),this.start();try{await this.db.decryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async rename(e){var t=await this.writeLock.lock();try{return await this.db.rename(this,e)}finally{t()}}async writeBalanceLog(e){var t=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,e)}finally{t()}}async renameAccount(e,t){var i=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{i()}}async _renameAccount(e,t){if(!y.isName(t))throw new Error("Bad account name.");var i=await this.getAccount(e);if(!i)throw new Error("Account not found.");if(0===i.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=i.name,this.start(),this.db.renameAccount(i,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const r of e)r.account===i.accountIndex&&(r.name=t)}async lock(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{await this.master.lock()}finally{t(),e()}}unlock(e,t){return this.master.unlock(e,t)}getID(){r(this.master.key,"Cannot derive id.");var e,t=this.master.key.derive(44);(e=new f(37)).writeBytes(t.publicKey),e.writeU32(this.network.magic),t=l.hash160(e.render());return(e=new f(27)).writeU8(3),e.writeU8(190),e.writeU8(4),e.writeBytes(t),e.writeChecksum(),m.encode(e.render())}async createAccount(e,t){var i=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{i()}}async _createAccount(e,t){let i,a,s=e.name,o=(s=s||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=n.hashInt(s)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(s))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(i=e.accountKey)&&(i=S.PublicKey.fromBase58(i,this.network)),!S.isPublic(i))throw new Error("Must add HD public keys to watch only wallet.");r(i.network===this.network,"Network mismatch for watch only key.")}else r(this.master.key),i=(i=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":s,witness:e.witness,watchOnly:this.watchOnly,accountKey:i,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(a=E.fromOptions(this.db,t)).wallet=this,await a.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",a.id,a.name,a.accountIndex),this.accountDepth++,this.save(),await this.commit(),a}async ensureAccount(e,t){var i=e.name;return(i=await this.getAccount(i))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAccountMap(){return this.db.getAccountMap(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,i=null){return this.createKey(e,0,t,i)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,i=0,r=null){var a=await this.writeLock.lock();try{return await this._createKey(e,t,i,r)}finally{a()}}async _createKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let a;this.start();try{a=await e.createKey(t,i,r)}catch(e){throw this.drop(),e}return await this.commit(),a}async deriveKey(e,t,i,r=null){let a=null;var s=await this.writeLock.lock();try{this.start(),a=await this._deriveKey(e,t,i,r),await this.commit()}catch(e){throw this.drop(),e}finally{s()}return a}async _deriveKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),e=e||0,e=parseInt(e),e=await this.getAccount(e))return t=await e.deriveKey(t,i,r),await e.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(e){var t=await this.writeLock.lock();try{this.start(),e._save(),await this.commit(),0==e.accountIndex&&(this.account=e)}finally{t()}}start(){return this.db.start(this)}drop(){return this.db.drop(this)}clear(){return this.db.clear(this)}commit(){return this.db.commit(this)}async hasAddress(e){return e=b.getHash(e,"hex"),null!=await this.getPath(e)}async getPath(e){return(e=await this.readPath(e))?(e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(e){e=b.getHash(e,"hex");var t=this.pathCache.get(e);return t||((t=await this.db.getPath(this.wid,e))?(t.id=this.id,t):null)}async hasPath(e){return e=b.getHash(e,"hex"),!!this.pathCache.has(e)||this.db.hasPath(this.wid,e)}async getPaths(e){if(null!=e)return this.getAccountPaths(e);var t=[];for(const e of await this.db.getWalletPaths(this.wid))e.id=this.id,e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),i=await this.getAccountHashes(t),a=await this.getAccountName(e),s=(r(a),[]);for(const e of i){var n=await this.readPath(e);r(n),r(n.account===t),n.name=a,this.pathCache.set(n.hash,n),s.push(n)}return s}async importKey(e,t,i){var r=await this.writeLock.lock();try{return await this._importKey(e,t,i)}finally{r()}}async _importKey(e,t,i){if(e&&"object"==typeof e&&(i=t,t=e,e=null),null==e&&(e=0),r(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var a=t.getHash("hex");if(await this.getPath(a))throw new Error("Key already exists.");if(!(a=await this.getAccount(e)))throw new Error("Account not found.");if(a.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(i),e=k.fromRing(a,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),r(e.data),e.encrypted=!0),this.start();try{await a.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var i=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{i()}}async _importAddress(e,t){if(t||(t=e,e=null),null==e&&(e=0),t.network!==this.network)throw new Error("Network mismatch for address.");if(!this.watchOnly)throw new Error("Cannot import address into non watch-only wallet.");if(await this.getPath(t))throw new Error("Address already exists.");if(!(e=await this.getAccount(e)))throw new Error("Account not found.");if(e.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=v.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var i=await this.writeLock.lock();try{return await this._fund(e,t)}finally{i()}}async _fund(e,t){if(t=t||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let i;if(null!=t.account){if(!(i=await this.getAccount(t.account)))throw new Error("Account not found.")}else i=this.account;if(!i.initialized)throw new Error("Account is not initialized.");let a,s=t.rate;return null==s&&(s=await this.db.estimateFee(t.blocks)),a=t.smart?await this.getSmartCoins(i.name):(a=await this.getCoins(i.name),this.txdb.filterConserved(a)),await e.fund(a,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:i.change.getAddress(),height:this.db.curHeight,rate:s,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&r(e.getFee()<=C.MAX_FEE,"TX exceeds MAX_FEE."),a}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=O.WITNESS_SCALE_FACTOR,i=b.fromScript(e);if(!i)return-1;var r=await this.getAccountByAddress(i);if(!r)return-1;let a=0;if(e.isScripthash()&&r.witness)switch(r.type){case E.types.PUBKEYHASH:a=4*(a+23);break;case E.types.MULTISIG:a=4*(a+35)}switch(r.type){case E.types.PUBKEYHASH:a=a+74+34;break;case E.types.MULTISIG:a=(a=(a=(a=(a+=1)+74*r.m)+3+1)+34*r.n)+1+1}return r.witness?a=((a+=1)+t-1)/t|0:a+=o.sizeVarint(a),a}async createTX(e){var t=e.outputs,i=new w;r(Array.isArray(t),"Outputs must be an array."),r(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),i.outputs.push(_.fromScript(x.createScript(Buffer.from(e.comment),x.types.NULLDATA),0)));for(const e of t){var a=new _(e),s=a.getAddress();if(a.isDust())throw new Error("Output is dust.");if(0<a.value){if(!s)throw new Error("Cannot send to unknown address.");if(s.isNull())throw new Error("Cannot send to null address.")}i.outputs.push(a)}let n=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(n=o.getAddress(),e.allowPreInput=!0,i.addCoin(o))}else await this.fund(i,e);if(n&&((t=new _).value=i.getFee()-C.MIN_FEE,t.script.fromAddress(n),i.outputs.push(t),i.changeIndex=i.outputs.length-1),!1!==e.sort&&i.sortMembers(),null!=e.locktime&&i.setLocktime(e.locktime),r(i.isSane(),"TX failed sanity check."),r(i.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(i))throw new Error("Templating failed.");return i}async send(e,t){var i=await this.sendLock.lock();try{return await this._send(e,t)}finally{i()}}async _send(e,t){return t&&(e.account=t),t=await this.createTX(e,!0),await this.sign(t),this.sendMTX(t,{sendafter:e.sendafter})}async sendMTX(e,t={}){if(!e.isSigned())throw new Error("TX could not be fully signed.");var i=e.toTX();if(i.getSigopsCost(e.view)>I.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(i.getWeight()>I.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,i.txid()),await this.db.addTX(i),await this.db.send(i)),i}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const i of e)t.push(i.tx);for(const e of h(t))await this.db.send(e);return t}async deriveInputs(e){r(e.mutable);var t=[];for(const r of await this.getInputPaths(e)){var i=await this.getAccount(r.account);i&&(i=i.derivePath(r,this.master))&&t.push(i)}return t}async getKey(e){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(!Z.unsupported){var t=await this.db.getTip(),i=n.date();let o="",c=[n.fmt("# Wallet Dump created by %s %s",ee.protocol,ee.version),n.fmt("# * Created on %s",i),n.fmt("# * Best block at time of backup was %d (%s).",t.height,n.revHex(t.hash)),n.fmt("# * File: %s",e.file),""];var r,a;t=n.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),t=(c.push(t),await this.getAccounts());for(const e of t){var s=await this.getAccount(e);s=n.fmt("C %s name= %s index= %d",s.toRaw().toString("base64"),s.name,s.accountIndex);c.push(s)}for(const t of await this.getAddressHashes())this.watchOnly?(r=b.fromWitnessPubkeyhash(Buffer.from(t,"hex"),this.network.type).toString(),r=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s","S",i,0,-1,-1,r),c.push(r)):(r=await this.getPrivateKey(t))&&(a=r.getAddress("string"),a=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",r.toSecret(),i,r.account,r.branch,r.index,a),c.push(a),e.fragment)&&1e5<c.length&&(o=c.join("\n"),await Z.writeFile(e.file.split(".").reduce((e,t)=>(e?e+="."+t:e=t+"-1",e),""),o,"utf8"),c=[]);c.push(""),c.push("# End of dump"),c.push(""),o=c.join("\n"),await Z.writeFile(e.file,o,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var i=await this.getAccount(e.account);return i?(await this.unlock(t),(t=i.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(r(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const r of e.getInputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async getOutputPaths(e){var t=[];for(const r of e.getOutputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async setLookahead(e,t){var i=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{i()}}async _setLookahead(e,t){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");this.start();try{await e.setLookahead(t)}catch(e){throw this.drop(),e}await this.commit()}async syncOutputDepth(e){var t=new Map;for(const r of e.outputs){var i=r.path;i&&-1!==i.index&&(t.has(i.account)||t.set(i.account,[]),t.get(i.account).push(i))}var a,s,n=[];for([a,s]of t){let e=-1,t=-1,i=-1;for(const r of s)switch(r.branch){case 0:r.index>e&&(e=r.index);break;case 1:r.index>t&&(t=r.index);break;case 2:r.index>i&&(i=r.index)}e+=2,t+=2,i+=2;var o=await this.getAccount(a);(o=(r(o),await o.syncDepth(e,t,i)))&&n.push(o)}return n}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async onSaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>!!i.bid&&await this.belongToAccount(t,i.bid.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async mySaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>this.belongToAccount(t,i.current.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async getPropList(){const e=await this.db.loadVpList();var t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push((async()=>{await this.getPrivateKey(r.current.address)&&(e[i]=[r.pid,r])})())}return await Promise.all(t),new ie(e)}async propCreate(e,t){var i,a=new w;for(i of e){var s=await this.ensureCp(i.cid,!0);!s||i.cid==this.network.genesisId||(i.gold=(0|i.gold)>>>0,i.gold<O.MINPROPVALUE)||(i.pid||(i.pid=M()),i.oid||(i.oid=i.pid),a.propCreate(s.current.address,i),i.index=a.outputs.length-1)}if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var n,o=a.commit();for(n of(await this.db.addTX(o[0]),await this.db.send(o[0]),r(o[0].verify(o[1],x.flags.STANDARD_VERIFY_FLAGS)),e))n.hash=o[0].hash("hex"),n.txid=o[0].txid();return o}return[]}async attach(e,t){var i,a=new w;for(i of e)a.attach(i.address,i.value,i.data);if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var s,n=a.commit();for(s of(await this.db.addTX(n[0]),await this.db.send(n[0]),r(n[0].verify(n[1],x.flags.STANDARD_VERIFY_FLAGS)),e))s.hash=n[0].hash("hex"),s.txid=n[0].txid();return n}return[]}async sendSecret(e,t,i){let r=this.db.$contacts.get(e);if(!r||!r.sender){var a=(await this.createReceive(i)).getAddress("string");if(e==a)throw new F(L.errors.TYPE_ERROR,"Forbid Sending to Self Address.");r=await this.db.ensureContact({contact:e,messenger:a,wallet:this,account:i})}if(r)return r.send(t);throw new F(L.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){r(!!e),r(!!e.dst),r(!!e.content);var t=new w,i=e.src||this.getReceive().toString(),a=(i=new V(W.notify,M(),this.db.curHeight,{src:i,content:e.content}),_.fromScript(x.createScript(i.toRaw(),x.types.NULLDATA),0));t.outputs.push(a),a={address:e.dst,locktime:O.BLOCK_DAY,locktype:"csb",value:.1*O.COIN},t.outputs.push(new _(a)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),a=t.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,a[0].txid()),await this.db.send(a[0]),i.hash=a[0].hash("hex"),i.height=-1,i}async cpRegister(e,t,i,a){if(r(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:W.cpRegister}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Info.");const s=new w;e||(n=await this.createReceive(i),e=n.getAddress());var n=await this.getKey(e);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");if(t.pubAddress=e.toString(),t.pubKey=n.getPublicKey("hex"),t.signMethod="secp256k1",n=await this.createAllianceInfo(),t.register=n.pub.toString("hex"),s.cpRegister(e,O.registerFee,t),n=async()=>{i?await this.fund(s,{account:i}):await this.fund(s),await this.sign(s);var a=s.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),await this.db.send(a[0]),t.txid=a[0].txid(),t.addr=e.toString(),a},!a)return n();n()}getSCAddress(e){return e=Q.fromMnemonic(T.fromOptions(O.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var i=await this.ensureCp(e.cid);if(i.cid==this.network.genesisId||"ATHENA"==i.name)throw new F(L.errors.TYPE_ERROR,"Invalid cp name.");var a=await this.getTX(i.current.hash);if(!a)throw new F(L.errors.TYPE_ERROR,"Do not have permission to change this info.");if(a=a.tx,!await this.belongToAccount(t,a.outputs[0].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:i.cid,name:e.newName,oper:W.cpChange}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=i.name;return e.addr||(e.addr=b.fromString(i.current.address)),i=w.cpChange(a,e),t?await this.fund(i,{allowPreInput:!0,account:t}):await this.fund(i,{allowPreInput:!0}),await this.sign(i),a=i.commit(),await this.db.send(a[0]),r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),e.txid=a[0].txid(),a}async propExchangeList(e,t,i=!1){var a,s,n,o=new w,c=[];for([a,s,n]of e){var u,h=null;if(h=await this.getTX(a.hash)){if(h=h.tx,u=a.index,h&&h.outputs&&!(h.outputs.length<=u)){if(i){if(!await this.hasAddress(h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}}else if(!await this.belongToAccount(t,h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}var l=h.outputs[u].getReturnData();l&&(o.propExchange(h,u,s),l.index=o.outputs.length-1,l.addr=s.toString(),c.push(l))}}else this.logger.error("tx not find:",a.hash,n)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var i=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=i)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[i].getAddress()))throw new F(L.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[i].getReturnData()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new Y(e.tx,"invalid","Special props that can not to donate",100);var r=new w;return(e=(r.addInputFromTx(e.tx,i),r.addOutput(x.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[i].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),x.types.NULLDATA),0),await this.sign(r,null,N.NONE|N.ANYONECANPAY),r.commit())).push(t),e}async propReceive(e,t){var i=(e=w.fromTX(e,1)).inputs[0].prevout,r=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new _({value:r.value})),e.outputs.pop();let a=this.getAddress().toString(this.network);t&&(s={cid:r.cid,uid:t},a=(s=await this.tokenCreate(s,t)).data.addr),e.outputs.push(_.fromScript(a,r.value,{oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:i.hash,index:i.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,N.ALL,[0]);var s=e.commit();return await this.db.send(s[0]),r.simAddr=a,[s[0],null,r]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,i){let a=null,s=0;var n;return Array.isArray(e)?(a=e[0],s=e[1]):(n=await this.getTX(e.hash))&&(a=n.tx,s=e.index),!a||!a.outputs||a.outputs.length<=s?(this.logger.error("Invalid tx info."),null):await this.belongToAccount(i,a.outputs[s].getAddress())?(n=a.outputs[s].getReturnData())?(e=(new w).propExchange(a,s,t),n.index=e.outputs.length-1,i?await this.fund(e,{allowPreInput:!0,account:i}):await this.fund(e,{allowPreInput:!0}),await this.sign(e),t=e.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(n),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t,i){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new F(L.errors.TYPE_ERROR,"Invalid hex string.");var a=e.outputs[t],s=a.getReturnData();if(!s||s.oper!==W.propExchange&&s.oper!==W.propCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new Y(block,"invalid","prop found supertoken",100);var n=new w;n.addInputFromTx(e,t),e=_.fromScript(a.getAddress(),a.value),n.outputs.push(e),i?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:i}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),t=n.commit();return await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(s),t}async propSale(e,t,i,a){let s=await this.getTX(e);if(!s)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(s.getDepth(this.db.curHeight)<=0)throw new F(L.errors.TYPE_ERROR,"No enough confirmations.");if(!(s=s.tx))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var n=s.outputs[t].getReturnData([x.opcodes.OP_PROPEXCHANGE,x.opcodes.OP_PROPCREATE]);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.belongToAccount(a,s.outputs[t].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(!(a=await this.getCoin(e,t))||-1===a.height)throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(i<=s.outputs[t].value)throw new F(L.errors.TYPE_ERROR,"Invalid fixed price.");if(n.cid==this.network.genesisId)throw new Y(s,"invalid","prop not for sale",100);return e=(a=new w).addInputFromTx(s,t),t={oper:W.propSale,pid:n.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:i,period:this.db.curHeight+O.BLOCK_DAY},n=_.fromScript(x.createScript(Buffer.from(JSON.stringify(t)),x.types.NULLDATA),0),a.outputs.push(n),await this.sign(a,null,N.SINGLE|N.ANYONECANPAY),e=a.commit(),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,i){if(!(e=this.db.propList.get(e))||e.pst!=$.Sale||!e.bid||!e.bid.raw)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx Hash.");var r=H.fromRaw(Buffer.from(e.bid.raw,"hex")),a=(await this.createReceive(i)).getAddress(),s=e.gold,n=b.fromString(e.current.address,this.network).getHash();if(t<s)throw new Error("wrong price");if(1<r.outputs.length&&t<r.outputs[1].value)throw new Error("low bid price than before");var o=w.fromTX(r,1);if(!o.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(r.hash("hex")),o.view.addOutput({hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index},new _({value:e.gold})),n=_.fromScript(x.createScript(n),t),o.outputs.push(n),t={oper:W.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index}},n=_.fromScript(a,s,t),o.outputs.push(n),i?await this.fund(o,{allowPreInput:!0,account:i}):await this.fund(o,{allowPreInput:!0}),await this.sign(o,null,N.ALL,[0]),a=o.commit(),e.owned||this.db.client.watchOutpoint((new D).fromOptions(r.inputs[0].prevout)),await this.db.send(a[0]),a}async getTXByAmount(e,t){let i=null;var r;for(r of await this.getCoins(t))if(!(r.height<=0)&&r.value==e){i=r;break}return i&&(t=await this.getTX(i.hash))?[t.tx,i.index,i.height]:[]}async contractCreate(e,t,i,a,s){if(this.db.transactionList.query(e,a)!=K.None)throw new F(L.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new F(L.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,a))throw new F(L.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let n=!1,[o,c,u]=await this.getTXByAmount(t,s);if(!o){n=!0;var h=new w;let e="";e=(s?await this.createReceive(s):this).getAddress(),h.outputs.push(_.fromScript(e,t)),s?await this.fund(h,{allowPreInput:!0,account:s}):await this.fund(h,{allowPreInput:!0}),await this.sign(h),h=h.commit(),r(h[0].verify(h[1],x.flags.STANDARD_VERIFY_FLAGS)),o=h[0],c=0,u=-1}(h=new w).addInputFromTx(o,c,u);let l="";l=(s?await this.createReceive(s):this).getAddress();var p=await this.getKey(l);e={oper:W.contractCreate,type:e,addr:a,src:t,dst:i,srcact:s,alice:p.getPublicKey("hex"),period:this.db.curHeight+O.TRANSACTION_PERIOD},a=_.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0),h.outputs.push(a),await this.sign(h,null,N.SINGLE|N.ANYONECANPAY),t=h.commit();return n&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.CreatedOnMem)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");var i=U.parseContract(e);if(!i||i.oper!==W.contractCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var r=w.fromTX(e,1);if(!r.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.src}));let a="";a=(t?await this.createReceive(t):this).getAddress();var s=await this.getKey(a);e={oper:W.contractPromise,prevhash:e.hash("hex"),type:i.type,addr:i.addr,dst:i.dst,srcact:i.srcact,dstact:t,bob:s.getPublicKey("hex"),period:i.period},t=new x([z.fromSymbol("promise"),z.fromData(Buffer.from(JSON.stringify(e))),z.fromSymbol("drop"),z.fromSymbol("greaterthan"),z.fromSymbol("drop"),z.fromSymbol("if"),z.fromData(l.hash160(Buffer.from(e.bob,"hex"))),z.fromSymbol("else"),z.fromData(l.hash160(Buffer.from(i.alice,"hex"))),z.fromSymbol("endif"),z.fromSymbol("checksig")]),r.outputs.push(_.fromScript(t,i.src)),await this.remove(e.prevhash),await this.sign(r,null,N.ALL,[0]),s=r.commit();return await this.db.send(s[0]),e.current={hash:s[0].hash("hex"),index:0},e.raw=s[0].toRaw().toString("hex"),e.transStatus=K.Promised,this.db.transactionList.saveContract(e,!0),s}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.Confirmed&&e.transStatus!=K.Expired)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var i=U.parseContract(e);if(!i||i.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var a=e.outputs[1].getReturnData();if(!a||a.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");r.strictEqual(i.addr,a.addr),r.strictEqual(i.type,a.type),r.strictEqual(i.dst,a.dst),r.strictEqual(i.period,a.period),r.strictEqual(i.srcact,a.srcact),r.strictEqual(i.dstact,a.dstact);var s=this.db.transactionList.query(i.type,i.addr);if(s!=K.Confirmed&&s!=K.Expired)throw new F(L.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(s==K.Expired&&1!=t||s==K.Confirmed&&2!=t)throw new F(L.errors.TYPE_ERROR,"Invalid Executor.");let n=i.srcact,o=(2==t&&(n=i.dstact),"");o=(n?await this.createReceive(n):this).getAddress();var c=new w,u=(c.addInputFromTx(e,1),{oper:W.contractExecute,type:i.type,addr:i.addr,master:t});u=_.fromScript(x.createScript(Buffer.from(JSON.stringify(u)),x.types.NULLDATA),0),c.outputs.push(u),u=_.fromScript(o,e.outputs[1].value),c.outputs.push(u),e=1==t?await P.fromPublic(Buffer.from(i.ori.alice,"hex")):await P.fromPublic(Buffer.from(a.bob,"hex")),u=await this.getKey(e.getAddress()),await c.signAsync(u,x.hashType.ALL,this.db.workers),t=c.commit();return r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS,s)),await this.db.send(t[0]),t}async htlcDeal(e,t){var i=await this.getTX(e.hash);let r=null;if(t){if(!(t=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");r=t.getReceive().toString()}else r=this.getReceive().toString();t=new w;var a=(new x).pushOp(B.OP_1);e.suggest&&a.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:a}),t.addOutput(r,i.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i.tx.outputs[e.index])),await this.sign(t,null,N.ALL),a=t.commit();return await this.db.send(a[0]),a}async htlcCancel(e,t){let i=null;var r=await this.getTX(e.hash);if(!(i=r?r.tx.outputs[e.index]:i))throw new F(L.errors.TYPE_ERROR,"Invalid Input.");let a=null;if(t){if(!(r=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");a=r.getReceive().toString()}else a=this.getReceive().toString();return t=new w,r=(new x).pushOp(B.OP_0),e.suggest&&r.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:r}),e.suggest?t.setSequence(0,2*O.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,O.HTLC_CANCEL_PERIOD,!1),t.addOutput(a,i.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i)),r=await this.getKey(e.master),await t.signAsync(r,x.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,i){var r,a=new w;for(r of e)a.outputs.push(i.create(r));return t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a),e=a.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async tokenCreate(e,t="",i){r(e&&"object"==typeof e,"Token data should be a object"),r(e.cid,"Token data should has a cid property"),r(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let a=null;if(i){if(!await this.belongToAccount(t,i))throw new F(L.errors.TYPE_ERROR,`tokenCreate address error: addr:${i} is not belongs to account:`+t);a=await this.getKey(i)}else a=await this.createReceive(t,n.hashInt(e.cid),this.master);return a.signData(e)}async sign(e,t,i=x.hashType.ALL,r){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(t),t=await this.deriveInputs(e),e.signAsync(t,i,this.db.workers,r)}getCoinView(e){return this.txdb.getCoinView(e)}getSpentView(e){return this.txdb.getSpentView(e)}toDetails(e){return this.txdb.toDetails(e)}getDetails(e){return this.txdb.getDetails(e)}async getCoin(e,t){return this.txdb.getCoin(e,t)}async getCredit(e,t){return this.txdb.getCredit(e,t)}async getStatusOfSC(e){return this.txdb.getStatusOfSC(e)}async setStatusOfSC(e,t){var i=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(e,t),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{i()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(e){return this.txdb.getTX(e)}getBlocks(){return this.txdb.getBlocks()}getBlock(e){return this.txdb.getBlock(e)}async add(e,t,i){var r=await this.writeLock.lock();try{return await this._add(e,t,i)}finally{r()}}async _add(e,t,i){let r,a;this.txdb.start();try{(r=await this.txdb._add(e,t,i))&&(a=await this.syncOutputDepth(r)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return a&&0<a.length&&(this.db.emit("address",this.id,a),this.emit("address",a)),r}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{this.txdb.pending.unconfirmed=0,this.txdb.pending.confirmed=0;for(const e of await this.getAccounts()){var t=await this.getBalance(e);this.txdb.pending.unconfirmed+=t.unconfirmed,this.txdb.pending.confirmed+=t.confirmed}this.txdb.put(te.R,this.txdb.pending.commit()),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}return this.txdb.state.toBalance()}async unconfirm(e){var t=await this.writeLock.lock();try{return await this.txdb.unconfirm(e)}finally{t()}}async remove(e){var t=await this.writeLock.lock();try{return await this.txdb.remove(e)}finally{t()}}async zap(e,t){var i=await this.writeLock.lock();try{return await this._zap(e,t)}finally{i()}}async _zap(e,t){return e=await this.ensureIndex(e),this.txdb.zap(e,t)}async abandon(e){var t=await this.writeLock.lock();try{return await this._abandon(e)}finally{t()}}_abandon(e){return this.txdb.abandon(e)}conserveCoin(e){return this.txdb.conserveCoin(e)}unConserveCoin(e){return this.txdb.unConserveCoin(e)}isConserved(e){return this.txdb.isConserved(e)}getConserved(){return this.txdb.getConserved()}async getHistory(e){return e=await this.ensureIndex(e),this.txdb.getHistory(e)}async getCoins(e){return e=await this.ensureIndex(e),this.txdb.getCoins(e)}async getCredits(e){return e=await this.ensureIndex(e),this.txdb.getCredits(e)}async getSmartCoins(e){var t=[];for(const r of await this.getCredits(e)){var i=r.coin;r.spent||this.txdb.isConserved(i)||-1===i.height&&!r.own||t.push(i)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(e){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(e)).writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(e){e=new d(e);var t=s.fromMagic(e.readU32());return this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),r(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new re(e).fromRaw(t)}static isWallet(e){return e instanceof re}async issueCreate(e,t,i){var r=new G(e),a=((a=(r.source.subjectName||(r.source.subjectName=r.erid),P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,r.sign(a,!0,this.network),r.toOptions(!0));return i?this.send({outputs:[{address:e.address,value:1e4}],comment:a},t):(r=await this.send({outputs:[{address:e.address,value:1e4}],comment:a},t),a.txid=r.txid()),a}async caAbolish(e,t,i){var r=P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),a=(r.witness=!0,await this.db.client.execute("ca.byId",[e.erid]));if(!a)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(a.source.cid!=e.cid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(a.source.uid!=e.uid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var s=a.signature;if(a.sign(r,!0,this.network),a.witness!=e.witness||a.signature!=s)throw new F(L.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(a=new X(e)).sign(r),s=a.toOptions(!0),i?this.send({outputs:[{address:e.address,value:1e4}],comment:s},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:s},t),s}async enchanceCp(e,t){var i=((e=new J(e)).oper="enchanceCp",await this.ensureCp(e.to)),r=await this.ensureCp(e.from);if(!(r=await this.getKey(r.pubAddress)))throw new F(L.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(r),r=e.toOptions(!0),[await this.send({outputs:[{address:i.pubAddress,value:1e4}],comment:r},t),r]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new F(L.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=re},function(e,t,i){"use strict";
|
|
285
|
+
*/const r=i(0);var a=i(16);const s=i(15),n=i(2),o=i(3),c=i(35),u=i(198),h=i(141).sortWithSeq,l=i(6),p=i(94),d=i(1),f=i(4),m=i(69),g=i(334);i(218);const v=i(109),y=i(73),b=i(13),w=i(68),x=i(17),k=i(219),S=i(156),_=i(28),E=i(157),j=i(337),A=i(63),R=i(26),I=i(29),O=i(7),C=i(310),P=i(38),T=S.Mnemonic,{opcodes:B,hashType:N}=i(19),z=i(165),F=i(77),L=i(78),M=i(142),D=i(46),H=i(20),U=i(42),q=i(54),{NotifyMsg:V,ContractStatus:K,ContractType:W,PropStatus:$}=i(5),Y=i(37).VerifyError,G=i(153).ErItem,X=i(154).ErAbolishItem,J=i(228).EnchancementItem,Q=i(67),Z=i(59),ee=i(83),te=i(85).txdb,ie=i(31);class re extends a{constructor(e,t){super(),r(e,"DB required."),this.db=e,this.network=e.network,this.logger=e.logger,this.readLock=new u,this.writeLock=new c,this.sendLock=new c,this.indexCache=new A(1e4),this.accountCache=new A(1e4),this.pathCache=new A(1e5),this.current=null,this.wid=0,this.id=null,this.initialized=!1,this.watchOnly=!1,this.accountDepth=0,this.token=o.ZERO_HASH,this.tokenDepth=0,this.master=new j,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,i,a=e.master;return a?("string"==typeof a&&(a=S.PrivateKey.fromBase58(a,this.network)),r(S.isPrivate(a),"Must create wallet with hd private key.")):(i=new T(e.mnemonic),a=S.fromMnemonic(i,this.network)),r(a.network===this.network,"Network mismatch for master key."),this.master.fromKey(a,i),null!=e.wid&&(r(n.isU32(e.wid)),this.wid=e.wid),e.id&&(r(y.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(r("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(r("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(r(n.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(r(Buffer.isBuffer(e.token)),r(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new re(e).fromOptions(t)}async init(e){var t=e.passphrase;r(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);r(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){r(this.initialized);var e=await this.getAccount(0);if(!e)throw new Error("Default account not found.");this.account=e,this.logger.info("Wallet opened (%s).",this.id),await this.txdb.open()}async ensureNotifyKey(){this.notifyKey||(await this.ensureAccount({name:"alliance",witness:!0}),this.notifyKey=await this.createReceive("alliance",1,this.master),this.notifyAddress=this.notifyKey.getAddress("string"))}async createAllianceInfo(e,t,i){var r={alliancename:e,nodeid:t};return e?(r.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),i?(r.prv=Buffer.alloc(0),r.pub=Buffer.from(i,"hex"),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type),r.mnemonic=new T):(i=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),r.mnemonic=new T({entropy:i,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),e=j.fromKey(S.fromMnemonic(r.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(r.mnemonic=T.fromOptions(this.master.mnemonic),r.prv=l.hash256(Buffer.from(r.mnemonic.toSeed().toString("hex"))),r.pub=R.publicKeyCreate(r.prv,!0),r.awardAddress=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(this.network.type)),r.address=b.fromWitnessPubkeyhash(l.hash160(r.pub),this.network.type).toString(),r}async destroy(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{this.db.unregister(this),await this.master.destroy(),this.readLock.destroy(),this.writeLock.destroy(),this.sendLock.destroy()}finally{t(),e()}}async addSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{i()}}async _addSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async removeSharedKey(e,t){var i=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{i()}}async _removeSharedKey(e,t){if(t||(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");let i;this.start();try{i=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),i}async setPassphrase(e,t){e&&await this.decrypt(e),t&&await this.encrypt(t)}async encrypt(e){var t=await this.writeLock.lock();try{return await this._encrypt(e)}finally{t()}}async _encrypt(e){e=await this.master.encrypt(e,!0),this.start();try{await this.db.encryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async decrypt(e){var t=await this.writeLock.lock();try{return await this._decrypt(e)}finally{t()}}async _decrypt(e){e=await this.master.decrypt(e,!0),this.start();try{await this.db.decryptKeys(this,e)}catch(t){throw p(e),this.drop(),t}p(e),this.save(),await this.commit()}async rename(e){var t=await this.writeLock.lock();try{return await this.db.rename(this,e)}finally{t()}}async writeBalanceLog(e){var t=await this.writeLock.lock();try{return await this.db.writeBalanceLog(this,e)}finally{t()}}async renameAccount(e,t){var i=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{i()}}async _renameAccount(e,t){if(!y.isName(t))throw new Error("Bad account name.");var i=await this.getAccount(e);if(!i)throw new Error("Account not found.");if(0===i.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=i.name,this.start(),this.db.renameAccount(i,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const r of e)r.account===i.accountIndex&&(r.name=t)}async lock(){var e=await this.writeLock.lock(),t=await this.sendLock.lock();try{await this.master.lock()}finally{t(),e()}}unlock(e,t){return this.master.unlock(e,t)}getID(){r(this.master.key,"Cannot derive id.");var e,t=this.master.key.derive(44);(e=new f(37)).writeBytes(t.publicKey),e.writeU32(this.network.magic),t=l.hash160(e.render());return(e=new f(27)).writeU8(3),e.writeU8(190),e.writeU8(4),e.writeBytes(t),e.writeChecksum(),m.encode(e.render())}async createAccount(e,t){var i=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{i()}}async _createAccount(e,t){let i,a,s=e.name,o=(s=s||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=n.hashInt(s)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(s))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(i=e.accountKey)&&(i=S.PublicKey.fromBase58(i,this.network)),!S.isPublic(i))throw new Error("Must add HD public keys to watch only wallet.");r(i.network===this.network,"Network mismatch for watch only key.")}else r(this.master.key),i=(i=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":s,witness:e.witness,watchOnly:this.watchOnly,accountKey:i,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(a=E.fromOptions(this.db,t)).wallet=this,await a.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",a.id,a.name,a.accountIndex),this.accountDepth++,this.save(),await this.commit(),a}async ensureAccount(e,t){var i=e.name;return(i=await this.getAccount(i))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAccountMap(){return this.db.getAccountMap(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,i=null){return this.createKey(e,0,t,i)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,i=0,r=null){var a=await this.writeLock.lock();try{return await this._createKey(e,t,i,r)}finally{a()}}async _createKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let a;this.start();try{a=await e.createKey(t,i,r)}catch(e){throw this.drop(),e}return await this.commit(),a}async deriveKey(e,t,i,r=null){let a=null;var s=await this.writeLock.lock();try{this.start(),a=await this._deriveKey(e,t,i,r),await this.commit()}catch(e){throw this.drop(),e}finally{s()}return a}async _deriveKey(e,t,i=0,r=null){if(null==t&&(t=e,e=null),e=e||0,e=parseInt(e),e=await this.getAccount(e))return t=await e.deriveKey(t,i,r),await e.saveKey(t),t;throw new Error("Account not found.")}save(){return this.db.save(this)}async saveAccount(e){var t=await this.writeLock.lock();try{this.start(),e._save(),await this.commit(),0==e.accountIndex&&(this.account=e)}finally{t()}}start(){return this.db.start(this)}drop(){return this.db.drop(this)}clear(){return this.db.clear(this)}commit(){return this.db.commit(this)}async hasAddress(e){return e=b.getHash(e,"hex"),null!=await this.getPath(e)}async getPath(e){return(e=await this.readPath(e))?(e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),e):null}async readPath(e){e=b.getHash(e,"hex");var t=this.pathCache.get(e);return t||((t=await this.db.getPath(this.wid,e))?(t.id=this.id,t):null)}async hasPath(e){return e=b.getHash(e,"hex"),!!this.pathCache.has(e)||this.db.hasPath(this.wid,e)}async getPaths(e){if(null!=e)return this.getAccountPaths(e);var t=[];for(const e of await this.db.getWalletPaths(this.wid))e.id=this.id,e.name=await this.getAccountName(e.account),r(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),i=await this.getAccountHashes(t),a=await this.getAccountName(e),s=(r(a),[]);for(const e of i){var n=await this.readPath(e);r(n),r(n.account===t),n.name=a,this.pathCache.set(n.hash,n),s.push(n)}return s}async importKey(e,t,i){var r=await this.writeLock.lock();try{return await this._importKey(e,t,i)}finally{r()}}async _importKey(e,t,i){if(e&&"object"==typeof e&&(i=t,t=e,e=null),null==e&&(e=0),r(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var a=t.getHash("hex");if(await this.getPath(a))throw new Error("Key already exists.");if(!(a=await this.getAccount(e)))throw new Error("Account not found.");if(a.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(i),e=k.fromRing(a,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),r(e.data),e.encrypted=!0),this.start();try{await a.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var i=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{i()}}async _importAddress(e,t){if(t||(t=e,e=null),null==e&&(e=0),t.network!==this.network)throw new Error("Network mismatch for address.");if(!this.watchOnly)throw new Error("Cannot import address into non watch-only wallet.");if(await this.getPath(t))throw new Error("Address already exists.");if(!(e=await this.getAccount(e)))throw new Error("Account not found.");if(e.type!==E.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=v.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var i=await this.writeLock.lock();try{return await this._fund(e,t)}finally{i()}}async _fund(e,t){if(t=t||{},!this.initialized)throw new Error("Wallet is not initialized.");if(this.watchOnly)throw new Error("Cannot fund from watch-only wallet.");let i;if(null!=t.account){if(!(i=await this.getAccount(t.account)))throw new Error("Account not found.")}else i=this.account;if(!i.initialized)throw new Error("Account is not initialized.");let a,s=t.rate;return null==s&&(s=await this.db.estimateFee(t.blocks)),a=t.smart?await this.getSmartCoins(i.name):(a=await this.getCoins(i.name),this.txdb.filterConserved(a)),await e.fund(a,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:i.change.getAddress(),height:this.db.curHeight,rate:s,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&r(e.getFee()<=C.MAX_FEE,"TX exceeds MAX_FEE."),a}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=O.WITNESS_SCALE_FACTOR,i=b.fromScript(e);if(!i)return-1;var r=await this.getAccountByAddress(i);if(!r)return-1;let a=0;if(e.isScripthash()&&r.witness)switch(r.type){case E.types.PUBKEYHASH:a=4*(a+23);break;case E.types.MULTISIG:a=4*(a+35)}switch(r.type){case E.types.PUBKEYHASH:a=a+74+34;break;case E.types.MULTISIG:a=(a=(a=(a=(a+=1)+74*r.m)+3+1)+34*r.n)+1+1}return r.witness?a=((a+=1)+t-1)/t|0:a+=o.sizeVarint(a),a}async createTX(e){var t=e.outputs,i=new w;r(Array.isArray(t),"Outputs must be an array."),r(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),i.outputs.push(_.fromScript(x.createScript(Buffer.from(e.comment),x.types.NULLDATA),0)));for(const e of t){var a=new _(e),s=a.getAddress();if(a.isDust())throw new Error("Output is dust.");if(0<a.value){if(!s)throw new Error("Cannot send to unknown address.");if(s.isNull())throw new Error("Cannot send to null address.")}i.outputs.push(a)}let n=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(n=o.getAddress(),e.allowPreInput=!0,i.addCoin(o))}else await this.fund(i,e);if(n&&((t=new _).value=i.getFee()-C.MIN_FEE,t.script.fromAddress(n),i.outputs.push(t),i.changeIndex=i.outputs.length-1),!1!==e.sort&&i.sortMembers(),null!=e.locktime&&i.setLocktime(e.locktime),r(i.isSane(),"TX failed sanity check."),r(i.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(i))throw new Error("Templating failed.");return i}async send(e,t){var i=await this.sendLock.lock();try{return await this._send(e,t)}finally{i()}}async _send(e,t){return t&&(e.account=t),t=await this.createTX(e,!0),await this.sign(t),this.sendMTX(t,{sendafter:e.sendafter})}async sendMTX(e,t={}){if(!e.isSigned())throw new Error("TX could not be fully signed.");var i=e.toTX();if(i.getSigopsCost(e.view)>I.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(i.getWeight()>I.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,i.txid()),await this.db.addTX(i),await this.db.send(i)),i}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const i of e)t.push(i.tx);for(const e of h(t))await this.db.send(e);return t}async deriveInputs(e){r(e.mutable);var t=[];for(const r of await this.getInputPaths(e)){var i=await this.getAccount(r.account);i&&(i=i.derivePath(r,this.master))&&t.push(i)}return t}async getKey(e){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(!Z.unsupported){var t=await this.db.getTip(),i=n.date();let o="",c=[n.fmt("# Wallet Dump created by %s %s",ee.protocol,ee.version),n.fmt("# * Created on %s",i),n.fmt("# * Best block at time of backup was %d (%s).",t.height,n.revHex(t.hash)),n.fmt("# * File: %s",e.file),""];var r,a;t=n.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),t=(c.push(t),await this.getAccounts());for(const e of t){var s=await this.getAccount(e);s=n.fmt("C %s name= %s index= %d",s.toRaw().toString("base64"),s.name,s.accountIndex);c.push(s)}for(const t of await this.getAddressHashes())this.watchOnly?(r=b.fromWitnessPubkeyhash(Buffer.from(t,"hex"),this.network.type).toString(),r=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s","S",i,0,-1,-1,r),c.push(r)):(r=await this.getPrivateKey(t))&&(a=r.getAddress("string"),a=n.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",r.toSecret(),i,r.account,r.branch,r.index,a),c.push(a),e.fragment)&&1e5<c.length&&(o=c.join("\n"),await Z.writeFile(e.file.split(".").reduce((e,t)=>(e?e+="."+t:e=t+"-1",e),""),o,"utf8"),c=[]);c.push(""),c.push("# End of dump"),c.push(""),o=c.join("\n"),await Z.writeFile(e.file,o,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var i=await this.getAccount(e.account);return i?(await this.unlock(t),(t=i.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(r(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const r of e.getInputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async getOutputPaths(e){var t=[];for(const r of e.getOutputHashes("hex")){var i=await this.getPath(r);i&&t.push(i)}return t}async setLookahead(e,t){var i=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{i()}}async _setLookahead(e,t){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=null==e?0:e)))throw new Error("Account not found.");this.start();try{await e.setLookahead(t)}catch(e){throw this.drop(),e}await this.commit()}async syncOutputDepth(e){var t=new Map;for(const r of e.outputs){var i=r.path;i&&-1!==i.index&&(t.has(i.account)||t.set(i.account,[]),t.get(i.account).push(i))}var a,s,n=[];for([a,s]of t){let e=-1,t=-1,i=-1;for(const r of s)switch(r.branch){case 0:r.index>e&&(e=r.index);break;case 1:r.index>t&&(t=r.index);break;case 2:r.index>i&&(i=r.index)}e+=2,t+=2,i+=2;var o=await this.getAccount(a);(o=(r(o),await o.syncDepth(e,t,i)))&&n.push(o)}return n}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async onSaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>!!i.bid&&await this.belongToAccount(t,i.bid.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async mySaleList(e,t){return(await(await this.getPropList()).predict(async(e,i)=>this.belongToAccount(t,i.current.address))).where([["pst",$.Sale]]).paginate(10,e).records()}async getPropList(){const e=await this.db.loadVpList();var t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push((async()=>{await this.getPrivateKey(r.current.address)&&(e[i]=[r.pid,r])})())}return await Promise.all(t),new ie(e)}async propCreate(e,t){var i,a=new w;for(i of e){var s=await this.ensureCp(i.cid,!0);!s||i.cid==this.network.genesisId||(i.gold=(0|i.gold)>>>0,i.gold<O.MINPROPVALUE)||(i.pid||(i.pid=M()),i.oid||(i.oid=i.pid),a.propCreate(s.current.address,i),i.index=a.outputs.length-1)}if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var n,o=a.commit();for(n of(await this.db.addTX(o[0]),await this.db.send(o[0]),r(o[0].verify(o[1],x.flags.STANDARD_VERIFY_FLAGS)),e))n.hash=o[0].hash("hex"),n.txid=o[0].txid();return o}return[]}async attach(e,t){var i,a=new w;for(i of e)a.attach(i.address,i.value,i.data);if(0<a.outputs.length){t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a);var s,n=a.commit();for(s of(await this.db.addTX(n[0]),await this.db.send(n[0]),r(n[0].verify(n[1],x.flags.STANDARD_VERIFY_FLAGS)),e))s.hash=n[0].hash("hex"),s.txid=n[0].txid();return n}return[]}async sendSecret(e,t,i){let r=this.db.$contacts.get(e);if(!r||!r.sender){var a=(await this.createReceive(i)).getAddress("string");if(e==a)throw new F(L.errors.TYPE_ERROR,"Forbid Sending to Self Address.");r=await this.db.ensureContact({contact:e,messenger:a,wallet:this,account:i})}if(r)return r.send(t);throw new F(L.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){r(!!e),r(!!e.dst),r(!!e.content);var t=new w,i=e.src||this.getReceive().toString(),a=(i=new V(W.notify,M(),this.db.curHeight,{src:i,content:e.content}),_.fromScript(x.createScript(i.toRaw(),x.types.NULLDATA),0));t.outputs.push(a),a={address:e.dst,locktime:O.BLOCK_DAY,locktype:"csb",value:.1*O.COIN},t.outputs.push(new _(a)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),a=t.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,a[0].txid()),await this.db.send(a[0]),i.hash=a[0].hash("hex"),i.height=-1,i}async cpRegister(e,t,i,a){if(r(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:W.cpRegister}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Info.");const s=new w;e||(n=await this.createReceive(i),e=n.getAddress());var n=await this.getKey(e);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");if(t.pubAddress=e.toString(),t.pubKey=n.getPublicKey("hex"),t.signMethod="secp256k1",n=await this.createAllianceInfo(),t.register=n.pub.toString("hex"),s.cpRegister(e,O.registerFee,t),n=async()=>{i?await this.fund(s,{account:i}):await this.fund(s),await this.sign(s);var a=s.commit();return r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(a[0]),await this.db.send(a[0]),t.txid=a[0].txid(),t.addr=e.toString(),a},!a)return n();n()}getSCAddress(e){return e=Q.fromMnemonic(T.fromOptions(O.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var i=await this.ensureCp(e.cid);if(i.cid==this.network.genesisId||"ATHENA"==i.name)throw new F(L.errors.TYPE_ERROR,"Invalid cp name.");var a=await this.getTX(i.current.hash);if(!a)throw new F(L.errors.TYPE_ERROR,"Do not have permission to change this info.");if(a=a.tx,!await this.belongToAccount(t,a.outputs[0].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:i.cid,name:e.newName,oper:W.cpChange}]))throw new F(L.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=i.name;return e.addr||(e.addr=b.fromString(i.current.address)),i=w.cpChange(a,e),t?await this.fund(i,{allowPreInput:!0,account:t}):await this.fund(i,{allowPreInput:!0}),await this.sign(i),a=i.commit(),await this.db.send(a[0]),r(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),e.txid=a[0].txid(),a}async propExchangeList(e,t,i=!1){var a,s,n,o=new w,c=[];for([a,s,n]of e){var u,h=null;if(h=await this.getTX(a.hash)){if(h=h.tx,u=a.index,h&&h.outputs&&!(h.outputs.length<=u)){if(i){if(!await this.hasAddress(h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}}else if(!await this.belongToAccount(t,h.outputs[u].getAddress())){this.logger.error("not owned prop:",a.hash,a.index);continue}var l=h.outputs[u].getReturnData();l&&(o.propExchange(h,u,s),l.index=o.outputs.length-1,l.addr=s.toString(),c.push(l))}}else this.logger.error("tx not find:",a.hash,n)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var i=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=i)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[i].getAddress()))throw new F(L.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[i].getReturnData()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new Y(e.tx,"invalid","Special props that can not to donate",100);var r=new w;return(e=(r.addInputFromTx(e.tx,i),r.addOutput(x.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[i].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),x.types.NULLDATA),0),await this.sign(r,null,N.NONE|N.ANYONECANPAY),r.commit())).push(t),e}async propReceive(e,t){var i=(e=w.fromTX(e,1)).inputs[0].prevout,r=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new _({value:r.value})),e.outputs.pop();let a=this.getAddress().toString(this.network);t&&(s={cid:r.cid,uid:t},a=(s=await this.tokenCreate(s,t)).data.addr),e.outputs.push(_.fromScript(a,r.value,{oper:W.propExchange,pid:r.pid,cid:r.cid,oid:r.oid,prev:{hash:i.hash,index:i.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,N.ALL,[0]);var s=e.commit();return await this.db.send(s[0]),r.simAddr=a,[s[0],null,r]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,i){let a=null,s=0;var n;return Array.isArray(e)?(a=e[0],s=e[1]):(n=await this.getTX(e.hash))&&(a=n.tx,s=e.index),!a||!a.outputs||a.outputs.length<=s?(this.logger.error("Invalid tx info."),null):await this.hasAddress(a.outputs[s].getAddress())?(n=a.outputs[s].getReturnData())?(e=(new w).propExchange(a,s,t),n.index=e.outputs.length-1,i?await this.fund(e,{allowPreInput:!0,account:i}):await this.fund(e,{allowPreInput:!0}),await this.sign(e),t=e.commit(),await this.db.addTX(t[0]),await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(n),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t,i){if(e=await this.getTX(e),r(e),!(e=e.tx))throw new F(L.errors.TYPE_ERROR,"Invalid hex string.");var a=e.outputs[t],s=a.getReturnData();if(!s||s.oper!==W.propExchange&&s.oper!==W.propCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new Y(block,"invalid","prop found supertoken",100);var n=new w;n.addInputFromTx(e,t),e=_.fromScript(a.getAddress(),a.value),n.outputs.push(e),i?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:i}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),t=n.commit();return await this.db.send(t[0]),r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(s),t}async propSale(e,t,i,a){let s=await this.getTX(e);if(!s)throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");if(s.getDepth(this.db.curHeight)<=0)throw new F(L.errors.TYPE_ERROR,"No enough confirmations.");if(!(s=s.tx))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var n=s.outputs[t].getReturnData([x.opcodes.OP_PROPEXCHANGE,x.opcodes.OP_PROPCREATE]);if(!n)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.hasAddress(s.outputs[t].getAddress()))throw new F(L.errors.TYPE_ERROR,"Invalid tx info.");var o=await this.getCoin(e,t);if(!o||-1===o.height)throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new F(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(i<=s.outputs[t].value)throw new F(L.errors.TYPE_ERROR,"Invalid fixed price.");if(n.cid==this.network.genesisId)throw new Y(s,"invalid","prop not for sale",100);return e=(o=new w).addInputFromTx(s,t),t={oper:W.propSale,pid:n.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:i,period:this.db.curHeight+O.BLOCK_DAY},n=_.fromScript(x.createScript(Buffer.from(JSON.stringify(t)),x.types.NULLDATA),0),o.outputs.push(n),await this.sign(o,null,N.SINGLE|N.ANYONECANPAY),e=o.commit(),r(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,i){if(!(e=this.db.propList.get(e))||e.pst!=$.Sale||!e.bid||!e.bid.raw)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx Hash.");var r=H.fromRaw(Buffer.from(e.bid.raw,"hex")),a=(await this.createReceive(i)).getAddress(),s=e.gold,n=b.fromString(e.current.address,this.network).getHash();if(t<s)throw new Error("wrong price");if(1<r.outputs.length&&t<r.outputs[1].value)throw new Error("low bid price than before");var o=w.fromTX(r,1);if(!o.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a sale order");return await this.remove(r.hash("hex")),o.view.addOutput({hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index},new _({value:e.gold})),n=_.fromScript(x.createScript(n),t),o.outputs.push(n),t={oper:W.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index}},n=_.fromScript(a,s,t),o.outputs.push(n),i?await this.fund(o,{allowPreInput:!0,account:i}):await this.fund(o,{allowPreInput:!0}),await this.sign(o,null,N.ALL,[0]),a=o.commit(),e.owned||this.db.client.watchOutpoint((new D).fromOptions(r.inputs[0].prevout)),await this.db.send(a[0]),a}async getTXByAmount(e,t){let i=null;var r;for(r of await this.getCoins(t))if(!(r.height<=0)&&r.value==e){i=r;break}return i&&(t=await this.getTX(i.hash))?[t.tx,i.index,i.height]:[]}async contractCreate(e,t,i,a,s){if(this.db.transactionList.query(e,a)!=K.None)throw new F(L.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new F(L.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,a))throw new F(L.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let n=!1,[o,c,u]=await this.getTXByAmount(t,s);if(!o){n=!0;var h=new w;let e="";e=(s?await this.createReceive(s):this).getAddress(),h.outputs.push(_.fromScript(e,t)),s?await this.fund(h,{allowPreInput:!0,account:s}):await this.fund(h,{allowPreInput:!0}),await this.sign(h),h=h.commit(),r(h[0].verify(h[1],x.flags.STANDARD_VERIFY_FLAGS)),o=h[0],c=0,u=-1}(h=new w).addInputFromTx(o,c,u);let l="";l=(s?await this.createReceive(s):this).getAddress();var p=await this.getKey(l);e={oper:W.contractCreate,type:e,addr:a,src:t,dst:i,srcact:s,alice:p.getPublicKey("hex"),period:this.db.curHeight+O.TRANSACTION_PERIOD},a=_.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0),h.outputs.push(a),await this.sign(h,null,N.SINGLE|N.ANYONECANPAY),t=h.commit();return n&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.CreatedOnMem)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");var i=U.parseContract(e);if(!i||i.oper!==W.contractCreate)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var r=w.fromTX(e,1);if(!r.outputs[0].getReturnType(B.OP_RETURN))throw new Error("not a valid contract");r.view.addOutput({hash:r.inputs[0].prevout.hash,index:r.inputs[0].prevout.index},new _({value:i.src}));let a="";a=(t?await this.createReceive(t):this).getAddress();var s=await this.getKey(a);e={oper:W.contractPromise,prevhash:e.hash("hex"),type:i.type,addr:i.addr,dst:i.dst,srcact:i.srcact,dstact:t,bob:s.getPublicKey("hex"),period:i.period},t=new x([z.fromSymbol("promise"),z.fromData(Buffer.from(JSON.stringify(e))),z.fromSymbol("drop"),z.fromSymbol("greaterthan"),z.fromSymbol("drop"),z.fromSymbol("if"),z.fromData(l.hash160(Buffer.from(e.bob,"hex"))),z.fromSymbol("else"),z.fromData(l.hash160(Buffer.from(i.alice,"hex"))),z.fromSymbol("endif"),z.fromSymbol("checksig")]),r.outputs.push(_.fromScript(t,i.src)),await this.remove(e.prevhash),await this.sign(r,null,N.ALL,[0]),s=r.commit();return await this.db.send(s[0]),e.current={hash:s[0].hash("hex"),index:0},e.raw=s[0].toRaw().toString("hex"),e.transStatus=K.Promised,this.db.transactionList.saveContract(e,!0),s}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=K.Confirmed&&e.transStatus!=K.Expired)throw new F(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=H.fromRaw(Buffer.from(e.raw,"hex"))))throw new F(L.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var i=U.parseContract(e);if(!i||i.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");var a=e.outputs[1].getReturnData();if(!a||a.oper!==W.contractPromise)throw new F(L.errors.TYPE_ERROR,"Invalid tx type.");r.strictEqual(i.addr,a.addr),r.strictEqual(i.type,a.type),r.strictEqual(i.dst,a.dst),r.strictEqual(i.period,a.period),r.strictEqual(i.srcact,a.srcact),r.strictEqual(i.dstact,a.dstact);var s=this.db.transactionList.query(i.type,i.addr);if(s!=K.Confirmed&&s!=K.Expired)throw new F(L.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(s==K.Expired&&1!=t||s==K.Confirmed&&2!=t)throw new F(L.errors.TYPE_ERROR,"Invalid Executor.");let n=i.srcact,o=(2==t&&(n=i.dstact),"");o=(n?await this.createReceive(n):this).getAddress();var c=new w,u=(c.addInputFromTx(e,1),{oper:W.contractExecute,type:i.type,addr:i.addr,master:t});u=_.fromScript(x.createScript(Buffer.from(JSON.stringify(u)),x.types.NULLDATA),0),c.outputs.push(u),u=_.fromScript(o,e.outputs[1].value),c.outputs.push(u),e=1==t?await P.fromPublic(Buffer.from(i.ori.alice,"hex")):await P.fromPublic(Buffer.from(a.bob,"hex")),u=await this.getKey(e.getAddress()),await c.signAsync(u,x.hashType.ALL,this.db.workers),t=c.commit();return r(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS,s)),await this.db.send(t[0]),t}async htlcDeal(e,t){var i=await this.getTX(e.hash);let r=null;if(t){if(!(t=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");r=t.getReceive().toString()}else r=this.getReceive().toString();t=new w;var a=(new x).pushOp(B.OP_1);e.suggest&&a.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:a}),t.addOutput(r,i.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i.tx.outputs[e.index])),await this.sign(t,null,N.ALL),a=t.commit();return await this.db.send(a[0]),a}async htlcCancel(e,t){let i=null;var r=await this.getTX(e.hash);if(!(i=r?r.tx.outputs[e.index]:i))throw new F(L.errors.TYPE_ERROR,"Invalid Input.");let a=null;if(t){if(!(r=await this.getAccount(t)))throw new F(L.errors.TYPE_ERROR,"Invalid Account.");a=r.getReceive().toString()}else a=this.getReceive().toString();return t=new w,r=(new x).pushOp(B.OP_0),e.suggest&&r.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:r}),e.suggest?t.setSequence(0,2*O.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,O.HTLC_CANCEL_PERIOD,!1),t.addOutput(a,i.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new _(i)),r=await this.getKey(e.master),await t.signAsync(r,x.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,i){var r,a=new w;for(r of e)a.outputs.push(i.create(r));return t?await this.fund(a,{account:t}):await this.fund(a),await this.sign(a),e=a.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async tokenCreate(e,t="",i){r(e&&"object"==typeof e,"Token data should be a object"),r(e.cid,"Token data should has a cid property"),r(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let a=null;if(i){if(!await this.belongToAccount(t,i))throw new F(L.errors.TYPE_ERROR,`tokenCreate address error: addr:${i} is not belongs to account:`+t);a=await this.getKey(i)}else a=await this.createReceive(t,n.hashInt(e.cid),this.master);return a.signData(e)}async sign(e,t,i=x.hashType.ALL,r){if(this.watchOnly)throw new Error("Cannot sign from a watch-only wallet.");return await this.unlock(t),t=await this.deriveInputs(e),e.signAsync(t,i,this.db.workers,r)}getCoinView(e){return this.txdb.getCoinView(e)}getSpentView(e){return this.txdb.getSpentView(e)}toDetails(e){return this.txdb.toDetails(e)}getDetails(e){return this.txdb.getDetails(e)}async getCoin(e,t){return this.txdb.getCoin(e,t)}async getCredit(e,t){return this.txdb.getCredit(e,t)}async getStatusOfSC(e){return this.txdb.getStatusOfSC(e)}async setStatusOfSC(e,t){var i=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb._setStatusOfSC(e,t),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{i()}}getLockedCoins(){return this.txdb.lockedCoins.values}getTX(e){return this.txdb.getTX(e)}getBlocks(){return this.txdb.getBlocks()}getBlock(e){return this.txdb.getBlock(e)}async add(e,t,i){var r=await this.writeLock.lock();try{return await this._add(e,t,i)}finally{r()}}async _add(e,t,i){let r,a;this.txdb.start();try{(r=await this.txdb._add(e,t,i))&&(a=await this.syncOutputDepth(r)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return a&&0<a.length&&(this.db.emit("address",this.id,a),this.emit("address",a)),r}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{this.txdb.pending.unconfirmed=0,this.txdb.pending.confirmed=0;for(const e of await this.getAccounts()){var t=await this.getBalance(e);this.txdb.pending.unconfirmed+=t.unconfirmed,this.txdb.pending.confirmed+=t.confirmed}this.txdb.put(te.R,this.txdb.pending.commit()),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}return this.txdb.state.toBalance()}async unconfirm(e){var t=await this.writeLock.lock();try{return await this.txdb.unconfirm(e)}finally{t()}}async remove(e){var t=await this.writeLock.lock();try{return await this.txdb.remove(e)}finally{t()}}async zap(e,t){var i=await this.writeLock.lock();try{return await this._zap(e,t)}finally{i()}}async _zap(e,t){return e=await this.ensureIndex(e),this.txdb.zap(e,t)}async abandon(e){var t=await this.writeLock.lock();try{return await this._abandon(e)}finally{t()}}_abandon(e){return this.txdb.abandon(e)}conserveCoin(e){return this.txdb.conserveCoin(e)}unConserveCoin(e){return this.txdb.unConserveCoin(e)}isConserved(e){return this.txdb.isConserved(e)}getConserved(){return this.txdb.getConserved()}async getHistory(e){return e=await this.ensureIndex(e),this.txdb.getHistory(e)}async getCoins(e){return e=await this.ensureIndex(e),this.txdb.getCoins(e)}async getCredits(e){return e=await this.ensureIndex(e),this.txdb.getCredits(e)}async getSmartCoins(e){var t=[];for(const r of await this.getCredits(e)){var i=r.coin;r.spent||this.txdb.isConserved(i)||-1===i.height&&!r.own||t.push(i)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(e){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(e)).writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(e){e=new d(e);var t=s.fromMagic(e.readU32());return this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),r(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new re(e).fromRaw(t)}static isWallet(e){return e instanceof re}async issueCreate(e,t,i){var r=new G(e),a=((a=(r.source.subjectName||(r.source.subjectName=r.erid),P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,r.sign(a,!0,this.network),r.toOptions(!0));return i?this.send({outputs:[{address:e.address,value:1e4}],comment:a},t):(r=await this.send({outputs:[{address:e.address,value:1e4}],comment:a},t),a.txid=r.txid()),a}async caAbolish(e,t,i){var r=P.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),a=(r.witness=!0,await this.db.client.execute("ca.byId",[e.erid]));if(!a)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(a.source.cid!=e.cid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(a.source.uid!=e.uid)throw new F(L.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var s=a.signature;if(a.sign(r,!0,this.network),a.witness!=e.witness||a.signature!=s)throw new F(L.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(a=new X(e)).sign(r),s=a.toOptions(!0),i?this.send({outputs:[{address:e.address,value:1e4}],comment:s},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:s},t),s}async enchanceCp(e,t){var i=((e=new J(e)).oper="enchanceCp",await this.ensureCp(e.to)),r=await this.ensureCp(e.from);if(!(r=await this.getKey(r.pubAddress)))throw new F(L.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(r),r=e.toOptions(!0),[await this.send({outputs:[{address:i.pubAddress,value:1e4}],comment:r},t),r]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new F(L.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=re},function(e,t,i){"use strict";
|
|
286
286
|
/*!
|
|
287
287
|
* BlockMeta.js - walletdb records
|
|
288
288
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -369,7 +369,7 @@ const r=i(19).opcodes;function a(e){let t=null;return new(0,(a.list[e.type]||a.l
|
|
|
369
369
|
* mempoolentry.js - mempool entry object for vallnet
|
|
370
370
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
371
371
|
* https://github.com/bookmansoft/gamegold
|
|
372
|
-
*/const r=i(29),a=i(2),s=i(17),n=i(1),o=i(4),c=i(20);i(60),e.exports=class e{constructor(e){this.tx=null,this.height=-1,this.size=0,this.sigops=0,this.priority=0,this.fee=0,this.deltaFee=0,this.time=0,this.value=0,this.coinbase=!1,this.dependencies=!1,this.descFee=0,this.descSize=0,e&&this.fromOptions(e)}fromOptions(e){return this.tx=e.tx,this.height=e.height,this.size=e.size,this.sigops=e.sigops,this.priority=e.priority,this.fee=e.fee,this.deltaFee=e.deltaFee,this.time=e.time,this.value=e.value,this.coinbase=e.coinbase,this.dependencies=e.dependencies,this.descFee=e.descFee,this.descSize=e.descSize,this}static fromOptions(t){return(new e).fromOptions(t)}fromTX(e,t,i){var r=s.flags.STANDARD_VERIFY_FLAGS,n=e.getChainValue(t),o=(r=e.getSigopsCost(t,r),e.getSigopsSize(r)),c=e.getPriority(t,i,o),u=e.getFee(t);let h=!1;var l,p=e.isCoinbase();for({prevout:l}of e.inputs)if(-1===t.getHeight(l)){h=!0;break}return this.tx=e,this.height=i,this.size=o,this.sigops=r,this.priority=c,this.fee=u,this.deltaFee=u,this.time=a.now(),this.value=n,this.coinbase=p,this.dependencies=h,this.descFee=u,this.descSize=o,this}static fromTX(t,i,r){return(new e).fromTX(t,i,r)}hash(e){return this.tx.hash(e)}txid(){return this.tx.txid()}getPriority(e){return e=(e-this.height)*this.value/this.size,Math.max(0,this.priority+Math.floor(e))}getFee(){return this.fee}getDeltaFee(){return this.deltaFee}getRate(){return r.getRate(this.size,this.fee)}getDeltaRate(){return r.getRate(this.size,this.deltaFee)}getDescRate(){return r.getRate(this.descSize,this.descFee)}memUsage(){var e=this.tx;let t=0;t=(t=(t=(t=(t=t+176+48)+48+208)+80+88)+80+80)+48+32;for(const i of e.inputs){t=(t=(t=(t=t+120+104)+88+40)+80+32)+40*i.script.code.length;for(const e of i.script.code)e.data&&(t+=80);t=(t=t+96+32)+80*i.witness.items.length}t+=32;for(const i of e.outputs){t=(t=(t=t+104+40)+80+32)+40*i.script.code.length;for(const e of i.script.code)e.data&&(t+=80)}return t}isFree(e){return
|
|
372
|
+
*/const r=i(29),a=i(2),s=i(17),n=i(1),o=i(4),c=i(20);i(60),e.exports=class e{constructor(e){this.tx=null,this.height=-1,this.size=0,this.sigops=0,this.priority=0,this.fee=0,this.deltaFee=0,this.time=0,this.value=0,this.coinbase=!1,this.dependencies=!1,this.descFee=0,this.descSize=0,e&&this.fromOptions(e)}fromOptions(e){return this.tx=e.tx,this.height=e.height,this.size=e.size,this.sigops=e.sigops,this.priority=e.priority,this.fee=e.fee,this.deltaFee=e.deltaFee,this.time=e.time,this.value=e.value,this.coinbase=e.coinbase,this.dependencies=e.dependencies,this.descFee=e.descFee,this.descSize=e.descSize,this}static fromOptions(t){return(new e).fromOptions(t)}fromTX(e,t,i){var r=s.flags.STANDARD_VERIFY_FLAGS,n=e.getChainValue(t),o=(r=e.getSigopsCost(t,r),e.getSigopsSize(r)),c=e.getPriority(t,i,o),u=e.getFee(t);let h=!1;var l,p=e.isCoinbase();for({prevout:l}of e.inputs)if(-1===t.getHeight(l)){h=!0;break}return this.tx=e,this.height=i,this.size=o,this.sigops=r,this.priority=c,this.fee=u,this.deltaFee=u,this.time=a.now(),this.value=n,this.coinbase=p,this.dependencies=h,this.descFee=u,this.descSize=o,this}static fromTX(t,i,r){return(new e).fromTX(t,i,r)}hash(e){return this.tx.hash(e)}txid(){return this.tx.txid()}getPriority(e){return e=(e-this.height)*this.value/this.size,Math.max(0,this.priority+Math.floor(e))}getFee(){return this.fee}getDeltaFee(){return this.deltaFee}getRate(){return r.getRate(this.size,this.fee)}getDeltaRate(){return r.getRate(this.size,this.deltaFee)}getDescRate(){return r.getRate(this.descSize,this.descFee)}memUsage(){var e=this.tx;let t=0;t=(t=(t=(t=(t=t+176+48)+48+208)+80+88)+80+80)+48+32;for(const i of e.inputs){t=(t=(t=(t=t+120+104)+88+40)+80+32)+40*i.script.code.length;for(const e of i.script.code)e.data&&(t+=80);t=(t=t+96+32)+80*i.witness.items.length}t+=32;for(const i of e.outputs){t=(t=(t=t+104+40)+80+32)+40*i.script.code.length;for(const e of i.script.code)e.data&&(t+=80)}return t}isFree(e){return this.getPriority(e)>r.FREE_THRESHOLD}getSize(){return this.tx.getSize()+42}toRaw(){var e=new o(this.getSize());return e.writeBytes(this.tx.toRaw()),e.writeU32(this.height),e.writeU32(this.size),e.writeU32(this.sigops),e.writeDouble(this.priority),e.writeU64(this.fee),e.writeU32(this.time),e.writeU64(this.value),e.writeU8(this.coinbase?1:0),e.writeU8(this.dependencies?1:0),e.render()}fromRaw(e){return e=new n(e),this.tx=c.fromReader(e),this.height=e.readU32(),this.size=e.readU32(),this.sigops=e.readU32(),this.priority=e.readDouble(),this.fee=e.readU64(),this.time=e.readU32(),this.value=e.readU64(),this.coinbase=1===e.readU8(),this.dependencies=1===e.readU8(),this.deltaFee=this.fee,this.descFee=this.fee,this.descSize=this.size,this}static fromRaw(t){return(new e).fromRaw(t)}}},function(e,t,i){var r=i(31);const a=i(4),s=i(1),n=i(3);i(22);const o=i(2);class c extends r{constructor(e){super(),this.env=e}async loadHistory(){var e;for(e of await this.env.getScs())this.set(e.id,e)}async addItem(e){this.set(e.id,e),await this.env.setSc(e)}async delItem(e){await this.env.delSc(e.id),this.delete(e.id)}getItem(e){return this.has(e)?this.get(e):null}}class u{constructor(e){this.options=e||{},this.history=[]}do(){var e=JSON.stringify(this.options);this.history.push(o.parseJson(e)),144<this.history.length&&this.history.shift()}undo(){var e;1<this.history.length&&(this.history.pop(),e=JSON.stringify(this.history[0]),this.options=o.parseJson(e))}get id(){return this.options.addr}getSize(){return 0+n.sizeVarString(JSON.stringify(this.history),"utf8")}toWriter(e){return e.writeVarString(JSON.stringify(this.history),"utf8"),e}toRaw(){var e=this.getSize();return this.toWriter(new a(e)).render()}fromReader(e){return e=e.readVarString("utf8"),this.history=o.parseJson(e),e=JSON.stringify(this.history[0]),this.options=o.parseJson(e),this}fromRaw(e){return this.fromReader(new s(e))}clone(){return u.fromRaw(this.toRaw())}static fromReader(e){return(new u).fromReader(e)}static fromRaw(e){return(new u).fromRaw(e)}}c.scItem=u,e.exports=c},function(e,t,i){
|
|
373
373
|
/*!
|
|
374
374
|
* selector.js
|
|
375
375
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -848,7 +848,7 @@ const r=i(5).ContractType;e.exports=function(e){if(!e)return i(188);switch(e.ope
|
|
|
848
848
|
* rpc.js - bitcoind-compatible json rpc for vallnet.
|
|
849
849
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
850
850
|
* https://github.com/bookmansoft/gamegold
|
|
851
|
-
*/const r=i(0),a=i(73);i(119);const s=i(85).walletdb,n=i(157),o=i(78),c=o.errors,u=o.MAGIC_STRING,h=i(77),l=i(59),p=i(107),d=i(2),f=i(193),m=i(3),g=i(80),v=i(33),y=i(17),b=i(7),w=i(6),x=i(26),k=i(13),S=i(38),_=i(131),E=i(68),j=i(46),A=i(20),R=i(136),I=i(137),{ContractType:O,ContractState:C,PropStatus:P,HtlcStatus:T}=i(5),B=i(138),N=i(123),z=i(142),F=i(19).opcodes,L=i(34),M=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.map",this.mapAccounts),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("prop.sale",this.propSale),this.add("prop.buy",this.propBuy),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.attach",this.attach),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 h(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 h(c.MISC_ERROR,"\n contract.create 发布交易对合约\n contract.promise 签署交易对合约\n contract.execute 执行交易对合约\n contract.mine 获取已签署交易对合约列表\n contract.list 查询并返回交易对\n ")}async routerOfHTLC(e){throw new h(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 h(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 h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"\n sc.model 查询托管合约模板列表\n sc.register 指定托管合约模板,创建新的实例\n sc.query 查询托管合约实例列表\n sc.run 调用托管合约实例\n ")}async routerOfCa(e){throw new h(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 h(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 h(c.MISC_ERROR,"sys.alliance.create password nodeid alliancename (host): 创建联盟节点证书 备份密码 节点编号 盟友名称 (节点地址)");e=(t=new g([e])).str(0);var r=t.uint(1,0),a=t.str(2,"").trim();t=t.str(3,"");if(!r||!e)throw new h(c.MISC_ERROR,"节点编号、备份密码都不能为空");if(a==this.wdb.$parent.config.allianceName)throw new h(c.MISC_ERROR,`子网名称不能和当前网络名称[${this.wdb.$parent.config.allianceName}]相同`);if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new h(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");var[i,s]=await this.accessControl(i,""),n={body:{language:(n=await i.createAllianceInfo(a,r)).mnemonic.language,phrase:n.mnemonic.getPhrase(),passphrase:n.mnemonic.passphrase,alliancePrivateKey:n.alliancePrivateKey.toString("hex"),allianceName:a,allianceNodeId:r,awardAddress:n.awardAddress,allianceNodeToken:{network:this.network.type,alliancename:a,sn:r,prv:n.prv.toString("hex"),pub:n.pub.toString("hex"),address:n.address},notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${a}-${r}.keystore`};let o=N.encrypt(n);if(this.wdb.$parent){let i=!1;for(var u of this.wdb.$parent.config.alliances)if((u=u.split("|"))[0]==a&&u[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(n.body.allianceNodeToken.pub,"hex")),o=N.encrypt(n),this.wdb.$parent.config.alliances.push(`${a}|${r}|${o}|${e}|${n.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}e={host:t,an:n.body.allianceNodeToken.alliancename,ai:n.body.allianceNodeToken.sn,key:n.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(n.file,o,"utf8"),e=(await i.getAccount(s)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.create",hash:a+"."+r,index:0}),{nodeid:r,alliancename:a,host:t,peerPubkey:n.body.allianceNodeToken.pub,awardAddress:n.body.awardAddress,file:n.file,notifyAddress:i.notifyAddress}}async allianceImport(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"sys.alliance.import password nodeid alliancename key (host): 导入联盟节点 备份密码 节点编号 盟友名称 节点公钥 (节点地址)");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new h(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),a=t.str(2,""),s=t.str(3,"");t=t.str(4,"");if(!r||!e||!s)throw new h(c.MISC_ERROR,"节点编号、备份密码、节点公钥都不能为空");var[i,n]=await this.accessControl(i,""),o={body:{alliancePrivateKey:(o=await i.createAllianceInfo(a,r,s)).alliancePrivateKey.toString("hex"),allianceName:a,allianceNodeId:r,allianceNodeToken:{network:this.network.type,alliancename:a,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+`-${a}-${r}.keystore`};let u;if(this.wdb.$parent){let i=!1;for(var d of this.wdb.$parent.config.alliances)if((d=d.split("|"))[0]==a&&d[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(s,"hex")),u=N.encrypt(o),this.wdb.$parent.config.alliances.push(`${a}|${r}|${u}|${e}|${o.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}else u=N.encrypt(o);return l.unsupported||await l.writeFile(o.file,u,"utf8"),s={host:t,key:o.body.allianceNodeToken.pub,an:o.body.allianceNodeToken.alliancename,ai:o.body.allianceNodeToken.sn},e=p.signObj(s,i.notifyKey.privateKey),await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:s,sig:e,pub:i.notifyKey.publicKey.toString("hex")})}),s=(await i.getAccount(n)).getReceive().toString(),await this.wdb.logAudit({address:s,oper:"node.create",hash:a+"."+r,index:0}),{nodeid:r,alliancename:a,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 h(c.MISC_ERROR,"sys.alliance.refresh amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new h(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[a,s]=await this.accessControl(i);if(this.wdb.$parent)for(var n of this.wdb.$parent.config.alliances){n=n.split("|");var o=(k.fromString(n[4],this.network.type).isWitnessPubkeyhash()&&await a.send({outputs:[{address:n[4],value:r}]},s),N.decrypt({network:this.network.type,password:n[3],body:n[2]}));n=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([n[5],o.allianceNodeToken.pub]),{host:n[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(n,a.notifyKey.privateKey);await a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:o,pub:a.notifyKey.publicKey.toString("hex")})})}}async refreshAllianceAsync(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.refresh.async amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new h(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[a,s]=await this.accessControl(i);if(this.wdb.$parent)for(var n of this.wdb.$parent.config.alliances){n=n.split("|");var o=(k.fromString(n[4],this.network.type).isWitnessPubkeyhash()&&a.send({outputs:[{address:n[4],value:r}]},s),N.decrypt({network:this.network.type,password:n[3],body:n[2]}));n=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([n[5],o.allianceNodeToken.pub]),{host:n[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(n,a.notifyKey.privateKey);a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:o,pub:a.notifyKey.publicKey.toString("hex")})})}}async allianceDelete(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"sys.alliance.delete nodeid alliancename: 删除联盟节点证书 节点编号 盟友名称");var r=(t=new g([e])).uint(0,0),a=t.str(1,""),[s,e]=await this.accessControl(i,"");if(!r||!a)throw new h(c.MISC_ERROR,"节点编号、节点名称都不能为空");if(this.wdb.$parent)for(let e=0;e<this.wdb.$parent.config.alliances.length;e++){var n,o=this.wdb.$parent.config.alliances[e].split("|");o[0]==a&&o[1]==r&&(this.wdb.$parent.config.alliances.splice(e,1),await this.wdb.$parent.config.saveAsync(),o[5])&&(o={host:o[5],an:a,ai:r},n=p.signObj(o,s.notifyKey.privateKey),await s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peerdel",payload:o,sig:n,pub:s.notifyKey.publicKey.toString("hex")})}))}return t=(await s.getAccount(e)).getReceive().toString(),await this.wdb.logAudit({address:t,oper:"node.delete",hash:a+"."+r,index:0}),!0}async getAllianceNodeToken(e,t,i){if(t)throw new h(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=x.publicKeyCreate(i.prv,!0),i.address=k.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 h(c.MISC_ERROR,"this cmd can only run on fullnode.")}async allianceUserCreate(e,t,i){if(t)throw new h(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),a=e.uint(1);let s=null,n=null;return n=(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(n,!0,this.network),(t=S.fromPrivate(w.hash256(Buffer.concat([Buffer.from(r+"-"+a),e.privateKey]),!0,this.network))).witness=!0,s=t.signData({cid:r,uid:a}),i&&(s.prvkey=t.privateKey.toString("hex")),s}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 h(c.MISC_ERROR,"sys.walletdb.stop");return this.wdb.close(),"Stopping walletdb..."}async destroyWalletDb(e,t,i){if(t||0!==e.length)throw new h(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 h(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 h(c.MISC_ERROR,'tx.fund.admin "hexstring" ( options openid )');const r=new g([e]);var[t,e]=await this.accessControl(i,r.str(2,"")),a=(i=r.buf(0),r.obj(1));if(!i)throw new h(c.TYPE_ERROR,"Invalid hex string.");if(0===(i=E.fromRaw(i)).outputs.length)throw new h(c.INVALID_PARAMETER,"TX must have at least one output.");let s=null,n=null;if(a){const e=new g([a]);s=e.ufixed("feeRate",8),n=(n=e.str("changeAddress"))&&o.parseAddress(n,this.network)}return await t.fund(i,{rate:s,changeAddress:n,account:e}),{hex:i.toRaw().toString("hex"),changepos:i.changeIndex,fee:v.btc(i.getFee(),!0)}}async dumpPrivKey(e,t,i){if(t||e.length<1)throw new h(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 h(c.MISC_ERROR,"Invald Account.");if(i=o.parseHash(t,this.network),t=await e.getPrivateKey(i))return t.toSecret();throw new h(c.MISC_ERROR,"Key not found.")}async exportMnemonic(e,t,i){if(t||1!==e.length)throw new h(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 h(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid password");if("primary"==e.id&&"default"!=i)throw new h(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 h(c.MISC_ERROR,"wallet.importmnemonic.admin encrypt password: 导入钱包助记符 备份文本 备份密码");var r;t=new g([e]);let a=N.decrypt({body:t.str(0),password:t.str(1),network:this.network});for(r of("string"==typeof a&&(a=JSON.parse(a)),this.wdb.$parent&&(a.awardAddress=this.wdb.$parent.config.coinbaseAddress),await this.wdb.getWallets()))if((await this.wdb.get(r)).master.mnemonic.getPhrase()===a.phrase)throw new h(c.MISC_ERROR,"wallet.importmnemonic.admin: 相同助记词已被使用");return(e=await this.wdb.ensure({id:z(),type:"pubkeyhash",m:1,n:1,mnemonic:a,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 h(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 h(c.TYPE_ERROR,"Invalid filename.")}async dumpWallets(e,t,i){if(t)throw new h(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 h(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 h(c.MISC_ERROR,"Invalid Account");if(e.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Already running with an encrypted wallet.");if(t.length<1)throw new h(c.MISC_ERROR,'wallet.encrypt "passphrase"');try{await e.setPassphrase(null,t)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}return"wallet encrypted"}async getAccount(e,t,i){if(t||1!==e.length)throw new h(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 h(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 a=t.toAddress();if(0==t.branch&&t.index==r)return a.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 h(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 h(c.MISC_ERROR,'address.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[],a=[],s=[];for(const t of await e.getPaths(i)){var n=t.toAddress();(0==t.branch?r:1==t.branch?a:s).push(n.toString(this.network))}return[r,a,s]}async getAccountAddress(e,t,i){if(t)throw new h(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 h(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 h(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 h(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 a;return t=await e.getBalance(i),a=0<r?t.confirmed:t.unconfirmed,v.btc(a,!0)}async getBalanceLog(e,t,i){if(t||e.length<1)throw new h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"tx.history (page acct):查询交易历史记录 (页码 账号)");var r=(t=new g([e])).uint(0,1);if(r<1)throw new h(c.MISC_ERROR,"页面必须是大于0的数字");var[e,i]=await this.accessControl(i,t.str(1));t=await e.getHistory(i);a.sortTX(t);let s=0;var n,o=[];for(n of t){if(s<10*(r-1));else{if(s>=10*r)break;o.push(n)}s++}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 h(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 h(c.TYPE_ERROR,"Invalid Destination Address.")}async calcHash(e,t,i){if(t||e.length<1)throw new h(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 h(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 h(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 h(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(i))return this.wdb.scanContact(e.tx,t);throw new h(c.WALLET_ERROR,"TX not found.")}async listContact(e,t,i){if(t)throw new h(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 h(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 h(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),a=this.wdb.curHeight,s=(t=await e.getPaths(i),new Set);for(const e of t)s.add(e.hash);let n=0,o=-1;for(const t of await e.getHistory(i)){var u=t.getDepth(a);if(!(u<r)){(-1===o||u<o)&&(o=u);for(const e of t.tx.outputs){var l=e.getHash("hex");l&&s.has(l)&&(n+=e.value)}}}return v.btc(n,!0)}async getReceivedByAddress(e,t,i){if(t||e.length<1||2<e.length)throw new h(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)),a=this.wdb.curHeight,s=o.parseHash(i,this.network);let n=0;for(const t of await e.getHistory())if(!(t.getDepth(a)<r))for(const e of t.tx.outputs)e.getHash("hex")===s&&(n+=e.value);return v.btc(n,!0)}async _toWalletTX(e,t){var[e,,]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new h(c.WALLET_ERROR,"TX not found.");let r=!0;for(const e of i.inputs)if(e.path){r=!1;break}var a=[];let s=0,n=0;for(let e=0;e<i.outputs.length;e++){var o=i.outputs[e];o.path?1!==o.path.branch&&(a.push({account:o.path.name,address:o.address.toString(this.network),category:"receive",amount:v.btc(o.value,!0),label:o.path.name,vout:e}),n+=o.value):r||(a.push({account:"",address:o.address?o.address.toString(this.network):null,category:"send",amount:-v.btc(o.value,!0),fee:-v.btc(i.getFee(),!0),vout:e}),s+=o.value)}return{amount:v.btc(r?n:-s,!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:a,hex:i.tx.toRaw().toString("hex")}}async getTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'tx.get.wallet "txid" ( includeWatchonly )');t=new g([e]);var[e,,]=await this.accessControl(i),a=t.hash(0);r(a,"Hash is required."),t=t.bool(1,!1);if(!a)throw new h(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(a))return this._toWalletTX(i,e,t);throw new h(c.WALLET_ERROR,"TX not found.")}async abandonPending(e,t,i){if(t)throw new h(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 h(c.MISC_ERROR,'tx.abandon.admin "txid"');t=new g([e]);var[e,,]=await this.accessControl(i);if(!(i=t.hash(0)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(await e.abandon(i))return null;throw new h(c.WALLET_ERROR,"Transaction not in wallet.")}async getUnconfirmedBalance(e,t,i){if(t||1<e.length)throw new h(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 v.btc(t.unconfirmed,!0)}async importPrivKey(e,t,i){if(t||e.length<1||4<e.length)throw new h(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),a=t.str(2);t=t.bool(3,!1);return(r=o.parseSecret(r,this.network)).witness=!0,await e.importKey(i,r,a),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 h(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 h(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 a=t.bool(2,!1);if(t.bool(3,!1)){let e=t.buf(0);if(!e)throw new h(c.TYPE_ERROR,"Invalid parameters.");e=y.fromRaw(e),e=y.createScript(e.hash160(),y.types.SCRIPTHASH),r=k.fromScript(e)}else r=o.parseAddress(r,this.network);return await e.importAddress(i,r),a&&await this.wdb.rescan(0),!0}async importPubkey(e,t,i){if(t||e.length<1||4<e.length)throw new h(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 h(c.TYPE_ERROR,"Invalid parameter.")}async listAccounts(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[r]=await this.accessControl(i),a=t.u32(0,0),s=t.bool(1,!1),n={};for(const e of await r.getAccounts()){var o=await r.getBalance(e);let t=o.unconfirmed;0<a&&(t=o.confirmed),r.watchOnly!==s&&(t=0),n[e]=v.btc(t,!0)}return n}async mapAccounts(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[e]=await this.accessControl(i);return t.u32(0,0),t.bool(1,!1),e.getAccountMap()}async listConservedUnspent(e,t,i){if(t||0<e.length)throw new h(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 h(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 h(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 h(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 h(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,a){var[s]=await this.accessControl(e),n=(e=await s.getPaths(),this.wdb.curHeight);const o=new Map;for(const t of e){var c=t.toAddress();o.set(t.hash,{involvesWatchonly:s.watchOnly,address:c.toString(this.network),account:t.name,amount:0,confirmations:-1,label:""})}for(const e of await s.getHistory()){var u=e.getDepth(n);if(!(u<t))for(const t of e.tx.outputs){var h,l=t.getAddress();l&&(h=l.getHash("hex"),h=o.get(h))&&((-1===h.confirmations||u<h.confirmations)&&(h.confirmations=u),h.address=l.toString(this.network),h.amount+=t.value)}}let p=[];for(const e of o.values())p.push(e);if(a){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=v.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 h(c.MISC_ERROR,'tx.history.since ( "blockhash" target-confirmations includeWatchonly account)');var r=this.wdb.curHeight,[e,a]=(t=new g([e]),await this.accessControl(i,t.str(3,""))),s=t.hash(0),n=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return[];let o=-1;-1===(o=s&&(t=await this.client.getEntry(s))?t.height:o)&&(o=r);var u,l=[];let p;for(const t of await e.getHistory(a))t.height<o||t.getDepth(r)<n||((!p||t.height>p)&&(p=t),u=await this._toListTX(i,t),l.push(u));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 h(c.WALLET_ERROR,"TX not found.");let a=!0;for(const e of i.inputs)if(e.path){a=!1;break}let s,n,o,u,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,n=t,u=e):(f+=t.value,s=t,o=e)}return p=a?(l=n,u):(l=s,o),l||(r(!a),a=!0,l=n,p=u),{account:l.path?l.path.name:"",address:l.address?l.address.toString(this.network):null,category:a?"receive":"send",amount:v.btc(a?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 h(c.MISC_ERROR,'tx.list ( "account" count from includeWatchonly)');t=new g([e]);var[e,r]=await this.accessControl(i,t.str(0,"")),s=t.u32(1,10),n=t.u32(2,0);t=t.bool(3,!1);if(e.watchOnly!==t)return[];var o=await e.getHistory(r),u=(t=(a.sortTX(o),n+s),Math.min(t,o.length)),l=[];for(let e=n;e<u;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 h(c.MISC_ERROR,"coin.selectone options (account)");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),a=t.obj(0,{}),s=[];for(const t of await r.getCoins(e)){var n=t.getDepth(this.wdb.curHeight),o=t.getAddress();if(o){var u=t.getHash("hex");if(u&&!t.isColored&&!(a.value&&t.value<a.value||t.coinbase&&0<t.height&&this.wdb.curHeight<t.height+b.COINBASE_MATURITY)&&(u=await r.getKey(u),s.push({txid:t.txid(),vout:t.index,address:o?o.toString(this.network):null,account:u?u.name:void 0,redeemScript:u&&u.script?u.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:n,spendable:!r.isConserved(t),solvable:!0}),a.len&&s.length>=a.len))break}}return s}async listUnspent(e,t,i){if(t||4<e.length)throw new h(c.MISC_ERROR,'coin.list ( minconf maxconf ["address", account] )');const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(3,"")),n=r.u32(0,1),u=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 h(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await s.getCoins(t);var m,y,b,w=(a.sortCoins(e),[]);for(const t of e)t.isColored||(m=t.getDepth(p))<n||u<m||((y=t.getAddress())?(b=t.getHash("hex"),l&&0<l.length&&(!b||!d.has(b))||(b=await s.getKey(b),w.push({txid:t.txid(),vout:t.index,address:y?y.toString(this.network):null,account:b?b.name:void 0,redeemScript:b&&b.script?b.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:m,spendable:!s.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 h(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 h(c.MISC_ERROR,"prop.wallet.byaddress ( minconf maxconf [address, account] )");const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(3,"")),n=r.u32(0,1),u=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 h(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await s.getCoins(t);var m=(a.sortCoins(e),[]);for(const t of e){var y,b,w,x=t.getDepth(p);x<n||u<x||(y=t.getAddress())&&(b=t.getHash("hex"),!l||b&&d.has(b))&&(b=await s.getKey(b),w=t.getReturnData([F.OP_PROPCREATE,F.OP_PROPCREATE]))&&m.push({txid:t.txid(),vout:t.index,address:y?y.toString(this.network):null,account:b?b.name:void 0,amount:v.btc(t.value,!0),confirmations:x,spendable:!s.isConserved(t),solvable:!0,nd:w})}return m}async listPropByOid(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.wallet.byoid oid");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),s=t.str(0),n=this.wdb.curHeight,o=(i=await r.getCoins(e),a.sortCoins(i),[]);for(const e of i){var u,l,p,d=e.getDepth(n);d<0||9999999<d||(u=e.getAddress())&&(l=e.getHash("hex"),l=await r.getKey(l),p=e.getReturnData([F.OP_PROPCREATE,F.OP_PROPEXCHANGE]))&&p.oid==s&&o.push({txid:e.txid(),vout:e.index,address:u?u.toString(this.network):null,account:l?l.name:void 0,amount:v.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 h(c.MISC_ERROR,'coin.list.locked ["address", account]');const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(1,"")),n=r.array(0),u=this.wdb.curHeight,l=d.now(),p=new Set;if(n){const e=new g([n]);for(let t=0;t<n.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(p.has(f))throw new h(c.INVALID_PARAMETER,"Duplicate address.");p.add(f)}}let m;m=account?await s.getCoins(t):s.getLockedCoins(),a.sortCoins(m);var y,b,w,x,k,S,_=[];for(const e of m)(e.lockedByLocktime(u,l)||e.lockedBySequence(u,l))&&(y=e.getAddress())&&(b=e.getDepth(u),S=e.getHash("hex"),!n||S&&p.has(S))&&([w,x,k]=e.getLockStatus(),S=await s.getKey(S),_.push({txid:e.txid(),vout:e.index,address:y?y.toString(this.network):null,account:S?S.name:void 0,redeemScript:S&&S.script?S.script.toJSON():void 0,scriptPubKey:e.script.toJSON(),amount:v.btc(e.value,!0),confirmations:b,spendable:!1,solvable:!0,locktype:w,lockheight:x,locktime:k}));return _}async listOperUnspent(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'coin.conserved.oper.list unlock ([{"txid":"txid","vout":n},...]) 保持/解除保持一组UTXO: true/false [{"txid": "交易id","vout": "输出序号"}]');const r=new g([e]);var[a]=await this.accessControl(i),s=r.bool(0,!1);if(!(t=r.array(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(const e of t){const t=new g([e]);var n=t.hash("txid"),o=t.u32("vout");if(null==n||null==o)throw new h(c.INVALID_PARAMETER,"Invalid parameter.");n=new j(n,o),s?a.unConserveCoin(n):a.conserveCoin(n)}return!0}async setTXFee(e,t,i){if(t||e.length<1||1<e.length)throw new h(c.MISC_ERROR,"sys.setfee rate");if(null==(t=new g([e]).ufixed(0,8)))throw new h(c.TYPE_ERROR,"Invalid parameter.");return this.wdb.feeRate=t,!0}async signMessage(e,t,i){if(t||2!==e.length)throw new h(c.MISC_ERROR,'sys.message.sign "address" "message"');t=new g([e]);var[e]=await this.accessControl(i);if(!e.master.key)throw new h(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(u+i,"utf8"))).toString("base64");throw new h(c.WALLET_ERROR,"Address not found.")}async changePassphrase(e,t,i){if(t||e.length<2)throw new h(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 h(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(i.length<1||t.length<1)throw new h(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),a=r.str(0);r=r.u32(1,60);if(t||i.master.encrypted&&0==e.length)throw new h(c.MISC_ERROR,'wallet.unlock "passphrase" timeout');if(!i.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(a.length<1)throw new h(c.INVALID_PARAMETER,"Invalid parameter");if(null==r)throw new h(c.TYPE_ERROR,"Invalid parameter");return await i.unlock(a,r),null}async decryptWallet(e,t,i){if(t||1!==e.length)throw new h(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 h(c.WALLET_WRONG_ENC_STATE,"Running with an decrypted wallet.");if(i.length<1)throw new h(c.MISC_ERROR,'wallet.decrypt "passphrase"');try{await e.setPassphrase(i)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Decryption failed.")}return"wallet decrypted"}async importPrunedFunds(e,t,i){if(t||e.length<2||3<e.length)throw new h(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 h(c.TYPE_ERROR,"Invalid parameter.");e=A.fromRaw(e);var r=(t=_.fromRaw(t)).hash("hex");if(!t.verify())throw new h(c.VERIFY_ERROR,"Invalid proof.");if(!t.hasTX(e.hash("hex")))throw new h(c.VERIFY_ERROR,"Invalid proof.");var a=await this.client.getEntry(r);if(-1===a)throw new h(c.VERIFY_ERROR,"Invalid proof.");if(r={hash:r,time:t.time,mtp:t.mtp,height:a},await this.wdb.addTX(e,r))return null;throw new h(c.WALLET_ERROR,"No tracked address for TX.")}async removePrunedFunds(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'tx.removeprunedfunds.admin "txid"');t=new g([e]);var[e]=await this.accessControl(i);if(!(i=t.hash(0)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(await e.remove(i))return null;throw new h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"sc.register options (account): 发布合约 合约参数列表 (子账户)");t=new g([e]);var[r,a]=await this.accessControl(i,t.str(1,""));let s=t.obj(0);if(!s)throw new h(c.MISC_ERROR,"sc.register: options is null");let n=1e5;switch(s.oper){case"change":if(s.oper=O.scState,!s.dst||!s.state)throw new h(c.TYPE_ERROR,"sc.register: dst or state is null.");if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.register: not support this operation.");var o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]);if(!o||0==o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract not exist.");switch(o.list[0].options.state){case C.Normal:if(s.state!=C.Frozen&&s.state!=C.Destroy)throw new h(c.TYPE_ERROR,"Contract State Error");break;case C.Frozen:if(s.state!=C.Normal&&s.state!=C.Destroy)throw new h(c.TYPE_ERROR,"Contract State Error");break;default:throw new h(c.TYPE_ERROR,"Contract State Error")}if(s.addr=o.list[0].options.addr,await r.belongToAccount(a,s.addr))break;throw new h(c.MISC_ERROR,"sc.register: Invald Account.");case"update":if(s.oper=O.scUpdate,!s.dst)throw new h(c.TYPE_ERROR,"sc.register: dst is null.");if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.register: not support this operation.");if(!(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]))||0==o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract not exist.");if(o.list[0].options.state!=C.Normal)throw new h(c.TYPE_ERROR,"sc.register: contract state error.");if(s.addr=o.list[0].options.addr,await r.belongToAccount(a,s.addr))break;throw new h(c.MISC_ERROR,"sc.register: Invald Account.");default:if(n=1e8,s.oper=O.scRegister,s.addr=(await r.createReceive(a)).getAddress("string"),s.dst=r.getSCAddress(d.hashInt(s.addr)).toString(),this.wdb.$parent&&(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]))&&0<o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract address conflict.")}return(e=(await r.getPrivateKey(s.addr)).signData(s)).data.sig=e.sig,s=e.data,i=await r.send({subtractFee:!1,sort:!1,outputs:[{address:s.dst,value:n}],comment:JSON.stringify(s)},a),await this.wdb.logAudit({address:s.addr,oper:s.oper,hash:i.hash("hex"),index:0}),s.txid=i.rhash(),s}async scRun(e,t,i){if(t||e.length<1)throw new h(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(","),a=(t=t.obj(1,{}),r.shift());if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.run: not support this operation.");var s=await this.wdb.$parent.chain.db.getSCList([["options.dst",a]]);if(!s||0==s.list.length)throw new h(c.TYPE_ERROR,"sc.run: contract not exist.");if(1!=s.list[0].options.state)throw new h(c.TYPE_ERROR,`sc.run: contract execute disabled(state ${s.list[0].options.state}).`);if(t.ver&&t.ver!=s.list[0].options.ver)throw new h(c.TYPE_ERROR,"sc.run: contract version inconsistency.");return s=(0|parseInt(r.shift()))>>>0,o.parseAddress(a,this.network),r=await e.send({subtractFee:!1,sort:!1,outputs:[{address:a,value:s}],comment:JSON.stringify({oper:"scrun",params:t})},i),a=await e.getAccount(i),await this.wdb.logAudit({address:a.receive.getAddress("string"),oper:O.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 h(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 h(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)),a=(o=e.str(1,"").split(","))[0],s=o[1],n=o[2],o=o[3]?parseInt(o[3]):15,[t,e]=await this.accessControl(t,e.str(2,"")),u=f.verifyDataFormat({name:r,ip:a,grate:o,cls:n});if(u)throw new h(c.MISC_ERROR,u);return u={cid:z(),oper:O.cpRegister,name:r,ip:a,grate:o,cls:n},await t.cpRegister(d.isBech32(s)?s:null,u,e,i),u}async cpChange(e,t,i){if(t||e.length<2)throw new h(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,"")),a=t.str(0),s=(t=decodeURIComponent(t.str(1,"")).split(","))[0],n=t[1];let o=t[2];var u=t[3];t=parseInt(t[4])||null;if(l=f.verifyDataFormat({name:s,ip:n,grate:t,cls:u}))throw new h(c.MISC_ERROR,l);o&&(o=k.fromString(o),r(o instanceof k,"Not an address."));var l={cid:a,newName:s,ip:n,addr:o,grate:t,cls:u},[,,]=await e.cpChange(l,i);return l.addr=l.addr.toString(),l}async cpQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.query (conditions account): 查询钱包中的厂商列表 (复合条件 子帐号)");t=new g([e]);var r,[a,s]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=a.db.cpList.query(e);for(r of i.list)r.owned=await a.belongToAccount(s,r.current.address);return i}async cpQueryRemote(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.query.remote conditions: 查询厂商列表 (复合条件)");t=new g([e]);var r,[a,s]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=await a.db.client.execute("cp.remoteQuery",[e]);for(r of i.list)r.owned=await a.belongToAccount(s,r.current.address);return i}async cpMine(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.mine (conditions account): 查询钱包中归属当前操作员/指定账户的厂商列表 (复合条件 子帐号)");t=new g([e]);let[r,a]=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(a,t.current.address))).query(e)}async htlcSuggest(e,t,i){if(t||e.length<1||2<e.length)throw new h(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 h(c.MISC_ERROR,"htlc.suggest: params.ab(alice bchain address) is null");if(!Number.isInteger(e.amount))throw new h(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.amount=parseInt(e.amount),e.amount<0||e.amount>1e4*b.COIN)throw new h(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 h(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:k.fromString(r).hash,ab:k.fromString(e.ab).hash,ba:k.fromString(e.ba).hash},[i]=await i.sendContracts([e],t,R),i?{txid:i.rhash(),aa:r}:null;throw new h(c.MISC_ERROR,"htlc.suggest: params.target is null")}async htlcAssent(e,t,i){if(t||e.length<1||2<e.length)throw new h(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 h(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new h(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 h(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:k.fromString(r).hash,amount:t.amount*t.rate},await e.sendContracts([r],i,I));return t?{txid:t.rhash()}:null}async htlcSuggestDeal(e,t,i){if(t||e.length<1||2<e.length)throw new h(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 h(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 h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"comm.comment: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new h(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&&(a=await e.createReceive(i),t.alice=a.getAddress()));var a=(await e.getPrivateKey(t.alice)).signData(r),[t]=(a.data.sig=a.sig,await e.sendContracts([a.data],i,B));return t?{txid:t.rhash()}:null}async commentQuery(e,t,i){if(t)throw new h(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 h(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 h(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 h(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 h(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),a=t.u64(1),s=t.u64(2),[e,,]=(t=t.str(3),await e.contractCreate(r,a,s,t,i));return e.toJSON()}async propGet(e,t,i){if(t)throw new h(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 h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"prop.found prop not exist");if(!await e.belongToAccount(i,t.current.address))throw new h(c.MISC_ERROR,"prop.found: current account not owned prop.");if(t.pst!=P.Ready)throw new h(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 h(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 h(c.MISC_ERROR,"prop.sale prop not exist");if(r.pst!=P.Ready)throw new h(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 h(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,"")),a=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var s of t){var n,o;3<=(s=s.split("|")).length&&(n=s[0],o=new j(d.revHex(s[1]),parseInt(s[2])),4<=s.length?a.push([o,k.fromString(n),s[3]]):a.push([o,k.fromString(n)]))}var[t,,e]=await e.propExchangeList(a,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 h(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 h(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 h(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 h(c.MISC_ERROR,"prop not exist");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop cannt be sent on current status");t=new j(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 h(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 h(c.MISC_ERROR,"prop.send prop not exist");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop.send prop cannt be sent on current status");var[e,,t]=await e.propExchange(new j(t.current.hash,t.current.index),k.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 h(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 a of t)if(3<=(a=a.split("|")).length){var s=a[0],n=a[1],o=parseInt(a[2]);let e=null;4<=a.length&&(e=a[3]),o<b.MINPROPVALUE||r.push([s,n,o,e])}r=r.map(e=>{var[e,t,i,r]=e;return{oper:O.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=M.getType(L.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,"")),a=t.str(0);let u=t.str(1);if((t=t.u64(2,b.MINPROPVALUE))<b.MINPROPVALUE)throw new h(c.PROP_MINVALUE,"prop.create: not a valid value");if(0<=u.indexOf("file:")){const e=u.replace("file:","")||"docs/eth.jpg";u=await new Promise(t=>{this.readImageAsBlob(e,(e,i)=>{e?console.error("Error reading inscription:",e):t(i)})})}else{if(!(0<=u.indexOf("data:")))throw new h(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]");u=JSON.parse(u.replace("data:",""))}var s,n=await e.createReceive(r),o=w.sha256(Buffer.from(JSON.stringify(u))).toString("hex");if(o=await this.caIssuePublic([JSON.stringify({blob:u,hash:o,height:0}),n.getAddress("string"),"",r],null,i))return n={oper:O.propCreate,cid:a,gold:t,type:"inscription",oid:o.erid},[i,s]=await e.propCreate([n],r),i?n:null}throw new h(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 h(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),a=t.str(1),s=t.u64(2,b.MINPROPVALUE);t=t.str(3,null);if(s<b.MINPROPVALUE)throw new h(c.PROP_MINVALUE,"prop.create: not a valid value");r={oper:O.propCreate,cid:r,oid:a,gold:s,pid:t};var[a,,]=await e.propCreate([r],i);return a?r:null}async attach(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"tx.attach addr amount data (openid): 发送附言交易 地址 金额 附言结构 [账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0),a=t.u64(1),[a,,]=(r=((t=t.obj(2,{})).oper=O.attach,{address:r,value:a,data:t}),await e.attach([r],i));return a?r:null}async walletLock(e,t,i){if(t)throw new h(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 h(c.MISC_ERROR,"Wallet is not encrypted, please run wallet.lock passphrase");try{await t.setPassphrase(null,i)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}}return await t.lock(),null}async listMSTrans(e,t,i){if(t)throw new h(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 h(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(s.ms(k.getHash(e,"hex"),r))))throw new h(c.MISC_ERROR,"tx.mstrans.sign txid");if(e=JSON.parse(e.toString()),!await i.belongToAccount(t,e.addr))throw new h(c.MISC_ERROR,"tx.mstrans.sign invalid account");var a,o=await this.wdb.get(e.addr);o&&o.account.type==n.types.MULTISIG&&((a=E.fromRaw(e.data,"hex")).view=await o.getCoinView(a),await o.sign(a),a.isSigned()?await o.sendMTX(a):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:a.toRaw().toString("hex")}})},t),await this.wdb.delMSTrans(e.addr,r))}async resendWalletTransactions(e,t,i){if(t||0!==e.length)throw new h(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 h(c.MISC_ERROR,"tx.resendall.admin: 重发挂起交易");var r=await this.wdb.resend();if(r)for(var a of Object.keys(r))if(a)for(const e of r[a])await this.wdb.send(e);return!0}async rescan(e,t,i){if(t)throw new h(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 h(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 h(c.MISC_ERROR,"address.calc account(must be typeof number) branch index");t=new g([e]);let[a,s]=await this.accessControl(i,t.int(0,0));return e=t.u32(1,0),i=t.u32(2,0),"default"==s&&(s=0),t=(await a.deriveKey(s,e,i,a.master)).toJSON(),i=(e=await a.deriveKey(s,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 h(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 h(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 h(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 a of await this.wdb.getWallets())if((await this.wdb.get(a)).master.mnemonic.getPhrase()===body.phrase)throw new h(c.MISC_ERROR,"wallet.create: 相同助记词已被使用");return(r=await this.wdb.ensure({id:z(),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 h(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 h(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),a.sortTX(t),[]);for(const i of await e.toDetails(t))r.push(i.toJSON());return r}async getPendingItem(e,t,i){var r,a=(e=new g([e])).hash(0,""),[s,i]=await this.accessControl(i,e.str(1,""));for(r of await s.getPending(i))if(r.hash==a)return(r=await s.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),a.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 h(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),a=e.obj(0);e=e.str(1),a={name:(a=new g([a])).str("name"),witness:a.bool("witness",!0),type:a.str("type","pubkeyhash"),m:a.u32("m",1),n:a.u32("n",1),watchOnly:a.bool("watch",!1),accountKey:a.str("key",null),lookahead:a.u32("lookahead",10)};try{let t=await i.getAccount(a.name);return t?t.toJSON():((r=(t=await i.createAccount(a,e)).toJSON()).isNew=!0,r)}catch(t){return null}}async getblocks(e,t,i){if(t)throw new h(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 h(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 h(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 h(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 h(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),a=e.hash(0);e=e.u32(1);return(i=(r(a,"Hash is required."),r(null!=e,"Index is required."),await i.getCoin(a,e)))?i.getJSON(this.network):null}async getSpender(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),a=e.hash(0);e=e.u32(1);return(i=(r(a,"Hash is required."),r(null!=e,"Index is required."),await i.txdb.getSpender(a,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),a=e.hash(0);e=e.u32(1),r(a,"Hash is required."),r(null!=e,"Index is required."),i=await i.txdb.getSpentCoin({hash:a,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 h(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 j(i,t);return e.conserveCoin(i),!0}async getConservedCoins(e,t,i){if(t||0<e.length)throw new h(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 h(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 j(i,t);return e.unConserveCoin(i),!0}async addShared(e,t,i){if(t||e.length<1)throw new h(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 h(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 h(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),a=t.str(1,null);if(null==(t=t.u64(2)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(r&&a)return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:JSON.stringify({oper:O.vote,type:"oracle",k:r,v:a})},r=await e.send(t,i),(await e.getDetails(r.hash("hex"))).toJSON()}throw new h(c.MISC_ERROR,"oracle.send k v amount [openid]")}async sendVote(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,"vote.send addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0);if(null==(t=t.u64(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(r of a.split(","))if(!o.parseAddress(r,this.network))throw new h(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": "${O.vote}", "type": "mine", "ca": "${a}"}`},a=await e.send(t,i),(await e.getDetails(a.hash("hex"))).toJSON()}async sendVoteAsync(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,"vote.send.async addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0);if(null==(t=t.u64(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(r of a.split(","))if(!o.parseAddress(r,this.network))throw new h(c.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${O.vote}", "type": "mine", "ca": "${a}"}`},e.send(t,i)}async sendTX(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.send addr amount [openid]:发送交易 地址 金额 [发起账户]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new h(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 h(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 h(c.MISC_ERROR,"tx.sign.admin txdata [sendnow passphrase]: 对交易签名/发送 交易原始数据 [立即发送 解锁密码]");t=new g([e]);var[e]=await this.accessControl(i),a=(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 s=null;return s=(a&&i.isSigned()?await e.sendMTX(i):i).getJSON(this.network),e.account.type==n.types.MULTISIG&&(t=i.getMultisig(this.network),s.ms={m:t.m,n:t.n,c:t.c}),s}async createTX(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.create options outputs [openid]: 创建交易 参数对象 输出数组 [子账号]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new h(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 a of i.in)a.hash=d.revHex(a.hash);var s={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]),u={value:o.u64("value")};if(u.address=o.str("address"),!u.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 h(c.MISC_ERROR,`tx.create: account ${l} not exist`);u.address=p.getAddress("string")}}if((l=o.buf("script"))&&(u.script=y.fromRaw(l)),(p=o.str("locktype"))&&(o=o.u64("locktime",0))){if("no"!=p&&"clb"!=p&&"clt"!=p&&"csb"!=p&&"cst"!=p)throw new h(c.MISC_ERROR,'locktype should be "no"-不锁定 or "clb"-绝对高度锁定 or clt(绝对时间锁定) or "csb"-相对高度锁定 or "cst"-相对时间锁定 !');if(p==y.outputLockType.CHECKABSOLUTETIME&&o<=b.LOCKTIME_THRESHOLD)throw new h(c.MISC_ERROR,"lock absolute time should not less than 500000000!");if(p==y.outputLockType.CHECKABSOLUTEBLOCK&&o>b.LOCKTIME_THRESHOLD)throw new h(c.MISC_ERROR,"lock absolute block should not more than 500000000!");if((p==y.outputLockType.CHECKRELATIVEBLOCK||p==y.outputLockType.CHECKRELATIVETIME)&&65535<o)throw new h(c.MISC_ERROR,"lock relative block/time should not more than 65535!");u.locktype=p,u.locktime=o}s.outputs.push(u)}e&&(s.account=e);let f=null;return s.sendnow?(i=await r.send(s),f=(t=await r.getDetails(i.hash("hex"))).toJSON()):(e=await r.createTX(s),await r.sign(e),f=e.getJSON(this.network),r.account.type==n.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 h(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 h(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 h(c.MISC_ERROR,"ca.user.status cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),a=t.array(2,[]);let s=null;for(let e=0;e<a.length;e++){var n=a[e];n&&Array.isArray(n)?"alliancename"==n[0]&&(s=n[1],delete a[e]):delete a[e]}var[t]=await this.accessControl(i);e=await this.$allianceUserCreate([e,r,s],i);return a.push(["pubkey",e.data.pubkey]),a.push(["merge",!0]),t.db.client.execute("ca.list",[a])}async caUserLog(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"ca.user.log cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),a=t.array(2,[]);let s=null;for(let e=0;e<a.length;e++){var n=a[e];n&&Array.isArray(n)?"alliancename"==n[0]&&(s=n[1],delete a[e]):delete a[e]}var[t,,]=await this.accessControl(i,e);e=await this.$allianceUserCreate([e,r,s],i);return a.push(["pubkey",e.data.pubkey]),t.db.client.execute("ca.list",[a])}async sysLog(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.log (query openid)");e=(t=new g([e])).array(0,[]);var r,[a,,]=await this.accessControl(i,t.str(1,"")),s=[];for(r of(await this.wdb.auditList.query(e)).list){var n=Object.assign({},r),u=o.parseHash(r.address,this.network);(u=await a.getPath(u))&&(n.account=u.name),n.time=new Date(1e3*r.time).toLocaleString(),s.push(n)}return s}async caIssuePublic(e,t,i){if(t||e.length<2||4<e.length)throw new h(c.MISC_ERROR,"ca.issue.public cert witness [pubkey openid]: 签发证书 证书对象 见证地址 [原始存证签名公钥 支付账户]");e=(t=new g([e])).obj(0,{});var r=t.str(1,""),a=t.str(2,""),[i,t]=await this.accessControl(i,t.str(3,""));if(64!=e.hash.length)throw new h(c.TYPE_ERROR,"err hash length");var s=await i.db.client.execute("ca.byId",[e.hash]);if(s)return s;if(s=await i.getPrivateKey(r))return e.height||(e.height=b.retargetInterval),await i.issueCreate({erid:e.hash,key:s.privateKey.toString("hex"),address:s.getAddress().toString(),witness:s.publicKey.toString("hex"),validHeight:this.wdb.curHeight+e.height,source:{subjectName:e.name||"",pubkey:a,subjectHash:e.hash,cluster:e.cluster,blob:e.blob}},t);throw new h(c.TYPE_ERROR,"Invalid witness.")}async caAbolishPublic(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"ca.abolish.public array[[erid height [openid]]]: 废止授信交易 废止交易信息数组");var r,a=[];for(r of new g([e]).array(0,[])){var[s,n]=await this.accessControl(i,r[3]),o=r[0],u=parseInt(r[1]),l=await this.wdb.erList.query([["erid",o]]),p=(l=k.fromWitnessPubkeyhash(w.hash160(Buffer.from(l.list[0].witness,"hex")),this.network.type).toString(),await s.getKey(l));if(!p)throw new h(c.TYPE_ERROR,"Invalid witness.");(s=await s.caAbolish({key:p.privateKey.toString("hex"),witness:p.publicKey.toString("hex"),address:l,erid:o,abolishHeight:u,cid:"",uid:0},n))&&a.push(s)}return a}async caIssue(e,t,i){if(t||e.length<3||4<e.length)throw new h(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 h(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,{}),a=e.uint(1,0),s=e.str(2,""),[e,n]=await this.accessControl(t,e.str(3,""));if(!(o=await e.ensureCp(s))||"forbidden"==o.cls)throw new h(c.MISC_ERROR,"Invalid Account");if(64!=r.hash.length)throw new h(c.TYPE_ERROR,"err hash length");var o=await this.$allianceUserCreate([s,a],t),u=[];if(u.push(["pubkey",o.data.pubkey]),u.push(["source.subjectHash",r.hash]),0<(await e.db.client.execute("ca.list",[u])).count)throw new h(c.TYPE_ERROR,"cert.hash conflicted");if(await e.db.client.execute("ca.byId",[r.hash]))throw new h(c.TYPE_ERROR,"cert.hash conflicted");return r.height||(r.height=b.retargetInterval),o=await this.$allianceUserCreate([s,a],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:s,uid:a}},n,i)}async caAbolish(e,t,i){if(t||e.length<1)throw new h(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 h(c.MISC_ERROR,"ca.abolish.async [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!0)}async $caAbolish(e,t,i){var r,a=[];for(r of new g([e]).array(0,[])){var s,n=r[0],o=r[1],c=r[2],u=parseInt(r[3]),[s,h]=await this.accessControl(t,r[4]),l=await this.$allianceUserCreate([o,n],t,!0);(s=await s.caAbolish({cid:o,uid:n,key:l.prvkey,witness:l.data.pubkey,address:l.data.addr,erid:c,abolishHeight:u},h,i))&&a.push(s)}return a}async enchanceCp(e,t,i){if(t||e.length<2||4<e.length)throw new h(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),a=t.str(1,0);let s=t.uint(2,0);(!s||s<this.wdb.curHeight)&&(s=this.wdb.curHeight+b.retargetInterval);var[t,e]=await e.enchanceCp({to:r,from:a,enchanceHeight:s},i);return t&&e?e:null}async queryErList(e,t,i){if(t)throw new h(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 h(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(31);const{ContractEnvType:a,ContractStatus:s}=i(5),n=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==s.CreatedOnMem?await this.delTransContract(e,!0):(e.id=e.type+"."+e.addr,await this.saveContract(e),e.transStatus==s.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:s.None}async addTransContract(e,t,i=!1){t.id=t.type+"."+t.addr;var r=this.get(t.id);e===a.Mempool&&((t=r||t).transStatus||(t.transStatus=s.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=n.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 a=this.get(r);return a&&a.oper==e.oper||(i=!0,a=e),(!a.transStatus||a.transStatus<s.Promised)&&(i=!0,a.transStatus=s.Promised),i&&await this.saveContract(a,t),i}async confirmContract(e,t,i){e=e.type+"."+e.addr,!(e=this.get(e))||e.transStatus!=s.Promised||t!=s.Confirmed&&t!=s.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=n.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(31);class a 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)}}a.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=a},,,,,,,,,,,,,,,function(e,t,i){"use strict";
|
|
851
|
+
*/const r=i(0),a=i(73);i(119);const s=i(85).walletdb,n=i(157),o=i(78),c=o.errors,u=o.MAGIC_STRING,h=i(77),l=i(59),p=i(107),d=i(2),f=i(193),m=i(3),g=i(80),v=i(33),y=i(17),b=i(7),w=i(6),x=i(26),k=i(13),S=i(38),_=i(131),E=i(68),j=i(46),A=i(20),R=i(136),I=i(137),{ContractType:O,ContractState:C,PropStatus:P,HtlcStatus:T}=i(5),B=i(138),N=i(123),z=i(142),F=i(19).opcodes,L=i(34),M=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.map",this.mapAccounts),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("prop.sale",this.propSale),this.add("prop.buy",this.propBuy),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.attach",this.attach),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 h(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 h(c.MISC_ERROR,"\n contract.create 发布交易对合约\n contract.promise 签署交易对合约\n contract.execute 执行交易对合约\n contract.mine 获取已签署交易对合约列表\n contract.list 查询并返回交易对\n ")}async routerOfHTLC(e){throw new h(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 h(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 h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"\n sc.model 查询托管合约模板列表\n sc.register 指定托管合约模板,创建新的实例\n sc.query 查询托管合约实例列表\n sc.run 调用托管合约实例\n ")}async routerOfCa(e){throw new h(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 h(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 h(c.MISC_ERROR,"sys.alliance.create password nodeid alliancename (host): 创建联盟节点证书 备份密码 节点编号 盟友名称 (节点地址)");e=(t=new g([e])).str(0);var r=t.uint(1,0),a=t.str(2,"").trim();t=t.str(3,"");if(!r||!e)throw new h(c.MISC_ERROR,"节点编号、备份密码都不能为空");if(a==this.wdb.$parent.config.allianceName)throw new h(c.MISC_ERROR,`子网名称不能和当前网络名称[${this.wdb.$parent.config.allianceName}]相同`);if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new h(c.MISC_ERROR,"identityKey not set yet, please run sys.alliance.gettoken without params first");var[i,s]=await this.accessControl(i,""),n={body:{language:(n=await i.createAllianceInfo(a,r)).mnemonic.language,phrase:n.mnemonic.getPhrase(),passphrase:n.mnemonic.passphrase,alliancePrivateKey:n.alliancePrivateKey.toString("hex"),allianceName:a,allianceNodeId:r,awardAddress:n.awardAddress,allianceNodeToken:{network:this.network.type,alliancename:a,sn:r,prv:n.prv.toString("hex"),pub:n.pub.toString("hex"),address:n.address},notifyAddress:i.notifyAddress,authorized:""},password:e,network:this.network.type,file:this.network.type+`-${a}-${r}.keystore`};let o=N.encrypt(n);if(this.wdb.$parent){let i=!1;for(var u of this.wdb.$parent.config.alliances)if((u=u.split("|"))[0]==a&&u[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(n.body.allianceNodeToken.pub,"hex")),o=N.encrypt(n),this.wdb.$parent.config.alliances.push(`${a}|${r}|${o}|${e}|${n.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}e={host:t,an:n.body.allianceNodeToken.alliancename,ai:n.body.allianceNodeToken.sn,key:n.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(n.file,o,"utf8"),e=(await i.getAccount(s)).getReceive().toString(),await this.wdb.logAudit({address:e,oper:"node.create",hash:a+"."+r,index:0}),{nodeid:r,alliancename:a,host:t,peerPubkey:n.body.allianceNodeToken.pub,awardAddress:n.body.awardAddress,file:n.file,notifyAddress:i.notifyAddress}}async allianceImport(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"sys.alliance.import password nodeid alliancename key (host): 导入联盟节点 备份密码 节点编号 盟友名称 节点公钥 (节点地址)");if(!this.wdb.$parent||!this.wdb.$parent.config.identityKey)throw new h(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),a=t.str(2,""),s=t.str(3,"");t=t.str(4,"");if(!r||!e||!s)throw new h(c.MISC_ERROR,"节点编号、备份密码、节点公钥都不能为空");var[i,n]=await this.accessControl(i,""),o={body:{alliancePrivateKey:(o=await i.createAllianceInfo(a,r,s)).alliancePrivateKey.toString("hex"),allianceName:a,allianceNodeId:r,allianceNodeToken:{network:this.network.type,alliancename:a,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+`-${a}-${r}.keystore`};let u;if(this.wdb.$parent){let i=!1;for(var d of this.wdb.$parent.config.alliances)if((d=d.split("|"))[0]==a&&d[1]==r){i=!0;break}i||(this.wdb.$parent.pool.authdb.addKnown(t,Buffer.from(s,"hex")),u=N.encrypt(o),this.wdb.$parent.config.alliances.push(`${a}|${r}|${u}|${e}|${o.body.awardAddress}|`+t),await this.wdb.$parent.saveConfigAsync())}else u=N.encrypt(o);return l.unsupported||await l.writeFile(o.file,u,"utf8"),s={host:t,key:o.body.allianceNodeToken.pub,an:o.body.allianceNodeToken.alliancename,ai:o.body.allianceNodeToken.sn},e=p.signObj(s,i.notifyKey.privateKey),await i.commNotify({dst:i.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:s,sig:e,pub:i.notifyKey.publicKey.toString("hex")})}),s=(await i.getAccount(n)).getReceive().toString(),await this.wdb.logAudit({address:s,oper:"node.create",hash:a+"."+r,index:0}),{nodeid:r,alliancename:a,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 h(c.MISC_ERROR,"sys.alliance.refresh amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new h(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[a,s]=await this.accessControl(i);if(this.wdb.$parent)for(var n of this.wdb.$parent.config.alliances){n=n.split("|");var o=(k.fromString(n[4],this.network.type).isWitnessPubkeyhash()&&await a.send({outputs:[{address:n[4],value:r}]},s),N.decrypt({network:this.network.type,password:n[3],body:n[2]}));n=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([n[5],o.allianceNodeToken.pub]),{host:n[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(n,a.notifyKey.privateKey);await a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:o,pub:a.notifyKey.publicKey.toString("hex")})})}}async refreshAllianceAsync(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.alliance.refresh.async amount: 为联盟成员批量充值 充值金额");var r=new g([e]).uint(0,0);if(r<1e4||5e9<r)throw new h(c.MISC_ERROR,"无效的充值金额(10000~5000000000)");var[a,s]=await this.accessControl(i);if(this.wdb.$parent)for(var n of this.wdb.$parent.config.alliances){n=n.split("|");var o=(k.fromString(n[4],this.network.type).isWitnessPubkeyhash()&&a.send({outputs:[{address:n[4],value:r}]},s),N.decrypt({network:this.network.type,password:n[3],body:n[2]}));n=(this.wdb.$parent.rpc.addPeer&&await this.wdb.$parent.rpc.addPeer([n[5],o.allianceNodeToken.pub]),{host:n[5],key:o.allianceNodeToken.pub,an:o.allianceNodeToken.alliancename,ai:o.allianceNodeToken.sn}),o=p.signObj(n,a.notifyKey.privateKey);a.commNotify({dst:a.notifyAddress,content:JSON.stringify({cmd:"peeradd",payload:n,sig:o,pub:a.notifyKey.publicKey.toString("hex")})})}}async allianceDelete(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"sys.alliance.delete nodeid alliancename: 删除联盟节点证书 节点编号 盟友名称");var r=(t=new g([e])).uint(0,0),a=t.str(1,""),[s,e]=await this.accessControl(i,"");if(!r||!a)throw new h(c.MISC_ERROR,"节点编号、节点名称都不能为空");if(this.wdb.$parent)for(let e=0;e<this.wdb.$parent.config.alliances.length;e++){var n,o=this.wdb.$parent.config.alliances[e].split("|");o[0]==a&&o[1]==r&&(this.wdb.$parent.config.alliances.splice(e,1),await this.wdb.$parent.config.saveAsync(),o[5])&&(o={host:o[5],an:a,ai:r},n=p.signObj(o,s.notifyKey.privateKey),await s.commNotify({dst:s.notifyAddress,content:JSON.stringify({cmd:"peerdel",payload:o,sig:n,pub:s.notifyKey.publicKey.toString("hex")})}))}return t=(await s.getAccount(e)).getReceive().toString(),await this.wdb.logAudit({address:t,oper:"node.delete",hash:a+"."+r,index:0}),!0}async getAllianceNodeToken(e,t,i){if(t)throw new h(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=x.publicKeyCreate(i.prv,!0),i.address=k.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 h(c.MISC_ERROR,"this cmd can only run on fullnode.")}async allianceUserCreate(e,t,i){if(t)throw new h(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),a=e.uint(1);let s=null,n=null;return n=(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(n,!0,this.network),(t=S.fromPrivate(w.hash256(Buffer.concat([Buffer.from(r+"-"+a),e.privateKey]),!0,this.network))).witness=!0,s=t.signData({cid:r,uid:a}),i&&(s.prvkey=t.privateKey.toString("hex")),s}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 h(c.MISC_ERROR,"sys.walletdb.stop");return this.wdb.close(),"Stopping walletdb..."}async destroyWalletDb(e,t,i){if(t||0!==e.length)throw new h(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 h(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 h(c.MISC_ERROR,'tx.fund.admin "hexstring" ( options openid )');const r=new g([e]);var[t,e]=await this.accessControl(i,r.str(2,"")),a=(i=r.buf(0),r.obj(1));if(!i)throw new h(c.TYPE_ERROR,"Invalid hex string.");if(0===(i=E.fromRaw(i)).outputs.length)throw new h(c.INVALID_PARAMETER,"TX must have at least one output.");let s=null,n=null;if(a){const e=new g([a]);s=e.ufixed("feeRate",8),n=(n=e.str("changeAddress"))&&o.parseAddress(n,this.network)}return await t.fund(i,{rate:s,changeAddress:n,account:e}),{hex:i.toRaw().toString("hex"),changepos:i.changeIndex,fee:v.btc(i.getFee(),!0)}}async dumpPrivKey(e,t,i){if(t||e.length<1)throw new h(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 h(c.MISC_ERROR,"Invald Account.");if(i=o.parseHash(t,this.network),t=await e.getPrivateKey(i))return t.toSecret();throw new h(c.MISC_ERROR,"Key not found.")}async exportMnemonic(e,t,i){if(t||1!==e.length)throw new h(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 h(c.MISC_ERROR,"wallet.exportmnemonic.admin: Invalid password");if("primary"==e.id&&"default"!=i)throw new h(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 h(c.MISC_ERROR,"wallet.importmnemonic.admin encrypt password: 导入钱包助记符 备份文本 备份密码");var r;t=new g([e]);let a=N.decrypt({body:t.str(0),password:t.str(1),network:this.network});for(r of("string"==typeof a&&(a=JSON.parse(a)),this.wdb.$parent&&(a.awardAddress=this.wdb.$parent.config.coinbaseAddress),await this.wdb.getWallets()))if((await this.wdb.get(r)).master.mnemonic.getPhrase()===a.phrase)throw new h(c.MISC_ERROR,"wallet.importmnemonic.admin: 相同助记词已被使用");return(e=await this.wdb.ensure({id:z(),type:"pubkeyhash",m:1,n:1,mnemonic:a,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 h(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 h(c.TYPE_ERROR,"Invalid filename.")}async dumpWallets(e,t,i){if(t)throw new h(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 h(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 h(c.MISC_ERROR,"Invalid Account");if(e.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Already running with an encrypted wallet.");if(t.length<1)throw new h(c.MISC_ERROR,'wallet.encrypt "passphrase"');try{await e.setPassphrase(null,t)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}return"wallet encrypted"}async getAccount(e,t,i){if(t||1!==e.length)throw new h(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 h(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 a=t.toAddress();if(0==t.branch&&t.index==r)return a.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 h(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 h(c.MISC_ERROR,'address.list "account"');t=new g([e]);var[e,i]=await this.accessControl(i,t.str(0,"")),r=[],a=[],s=[];for(const t of await e.getPaths(i)){var n=t.toAddress();(0==t.branch?r:1==t.branch?a:s).push(n.toString(this.network))}return[r,a,s]}async getAccountAddress(e,t,i){if(t)throw new h(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 h(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 h(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 h(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 a;return t=await e.getBalance(i),a=0<r?t.confirmed:t.unconfirmed,v.btc(a,!0)}async getBalanceLog(e,t,i){if(t||e.length<1)throw new h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"tx.history (page acct):查询交易历史记录 (页码 账号)");var r=(t=new g([e])).uint(0,1);if(r<1)throw new h(c.MISC_ERROR,"页面必须是大于0的数字");var[e,i]=await this.accessControl(i,t.str(1));t=await e.getHistory(i);a.sortTX(t);let s=0;var n,o=[];for(n of t){if(s<10*(r-1));else{if(s>=10*r)break;o.push(n)}s++}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 h(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 h(c.TYPE_ERROR,"Invalid Destination Address.")}async calcHash(e,t,i){if(t||e.length<1)throw new h(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 h(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 h(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 h(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(i))return this.wdb.scanContact(e.tx,t);throw new h(c.WALLET_ERROR,"TX not found.")}async listContact(e,t,i){if(t)throw new h(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 h(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 h(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),a=this.wdb.curHeight,s=(t=await e.getPaths(i),new Set);for(const e of t)s.add(e.hash);let n=0,o=-1;for(const t of await e.getHistory(i)){var u=t.getDepth(a);if(!(u<r)){(-1===o||u<o)&&(o=u);for(const e of t.tx.outputs){var l=e.getHash("hex");l&&s.has(l)&&(n+=e.value)}}}return v.btc(n,!0)}async getReceivedByAddress(e,t,i){if(t||e.length<1||2<e.length)throw new h(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)),a=this.wdb.curHeight,s=o.parseHash(i,this.network);let n=0;for(const t of await e.getHistory())if(!(t.getDepth(a)<r))for(const e of t.tx.outputs)e.getHash("hex")===s&&(n+=e.value);return v.btc(n,!0)}async _toWalletTX(e,t){var[e,,]=await this.accessControl(e),i=await e.toDetails(t);if(!i)throw new h(c.WALLET_ERROR,"TX not found.");let r=!0;for(const e of i.inputs)if(e.path){r=!1;break}var a=[];let s=0,n=0;for(let e=0;e<i.outputs.length;e++){var o=i.outputs[e];o.path?1!==o.path.branch&&(a.push({account:o.path.name,address:o.address.toString(this.network),category:"receive",amount:v.btc(o.value,!0),label:o.path.name,vout:e}),n+=o.value):r||(a.push({account:"",address:o.address?o.address.toString(this.network):null,category:"send",amount:-v.btc(o.value,!0),fee:-v.btc(i.getFee(),!0),vout:e}),s+=o.value)}return{amount:v.btc(r?n:-s,!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:a,hex:i.tx.toRaw().toString("hex")}}async getTransaction(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'tx.get.wallet "txid" ( includeWatchonly )');t=new g([e]);var[e,,]=await this.accessControl(i),a=t.hash(0);r(a,"Hash is required."),t=t.bool(1,!1);if(!a)throw new h(c.TYPE_ERROR,"Invalid parameter");if(e=await e.getTX(a))return this._toWalletTX(i,e,t);throw new h(c.WALLET_ERROR,"TX not found.")}async abandonPending(e,t,i){if(t)throw new h(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 h(c.MISC_ERROR,'tx.abandon.admin "txid"');t=new g([e]);var[e,,]=await this.accessControl(i);if(!(i=t.hash(0)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(await e.abandon(i))return null;throw new h(c.WALLET_ERROR,"Transaction not in wallet.")}async getUnconfirmedBalance(e,t,i){if(t||1<e.length)throw new h(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 v.btc(t.unconfirmed,!0)}async importPrivKey(e,t,i){if(t||e.length<1||4<e.length)throw new h(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),a=t.str(2);t=t.bool(3,!1);return(r=o.parseSecret(r,this.network)).witness=!0,await e.importKey(i,r,a),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 h(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 h(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 a=t.bool(2,!1);if(t.bool(3,!1)){let e=t.buf(0);if(!e)throw new h(c.TYPE_ERROR,"Invalid parameters.");e=y.fromRaw(e),e=y.createScript(e.hash160(),y.types.SCRIPTHASH),r=k.fromScript(e)}else r=o.parseAddress(r,this.network);return await e.importAddress(i,r),a&&await this.wdb.rescan(0),!0}async importPubkey(e,t,i){if(t||e.length<1||4<e.length)throw new h(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 h(c.TYPE_ERROR,"Invalid parameter.")}async listAccounts(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[r]=await this.accessControl(i),a=t.u32(0,0),s=t.bool(1,!1),n={};for(const e of await r.getAccounts()){var o=await r.getBalance(e);let t=o.unconfirmed;0<a&&(t=o.confirmed),r.watchOnly!==s&&(t=0),n[e]=v.btc(t,!0)}return n}async mapAccounts(e,t,i){if(t||2<e.length)throw new h(c.MISC_ERROR,"account.list ( minconf includeWatchonly)");t=new g([e]);var[e]=await this.accessControl(i);return t.u32(0,0),t.bool(1,!1),e.getAccountMap()}async listConservedUnspent(e,t,i){if(t||0<e.length)throw new h(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 h(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 h(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 h(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 h(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,a){var[s]=await this.accessControl(e),n=(e=await s.getPaths(),this.wdb.curHeight);const o=new Map;for(const t of e){var c=t.toAddress();o.set(t.hash,{involvesWatchonly:s.watchOnly,address:c.toString(this.network),account:t.name,amount:0,confirmations:-1,label:""})}for(const e of await s.getHistory()){var u=e.getDepth(n);if(!(u<t))for(const t of e.tx.outputs){var h,l=t.getAddress();l&&(h=l.getHash("hex"),h=o.get(h))&&((-1===h.confirmations||u<h.confirmations)&&(h.confirmations=u),h.address=l.toString(this.network),h.amount+=t.value)}}let p=[];for(const e of o.values())p.push(e);if(a){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=v.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 h(c.MISC_ERROR,'tx.history.since ( "blockhash" target-confirmations includeWatchonly account)');var r=this.wdb.curHeight,[e,a]=(t=new g([e]),await this.accessControl(i,t.str(3,""))),s=t.hash(0),n=t.u32(1,0);t=t.bool(2,!1);if(e.watchOnly!==t)return[];let o=-1;-1===(o=s&&(t=await this.client.getEntry(s))?t.height:o)&&(o=r);var u,l=[];let p;for(const t of await e.getHistory(a))t.height<o||t.getDepth(r)<n||((!p||t.height>p)&&(p=t),u=await this._toListTX(i,t),l.push(u));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 h(c.WALLET_ERROR,"TX not found.");let a=!0;for(const e of i.inputs)if(e.path){a=!1;break}let s,n,o,u,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,n=t,u=e):(f+=t.value,s=t,o=e)}return p=a?(l=n,u):(l=s,o),l||(r(!a),a=!0,l=n,p=u),{account:l.path?l.path.name:"",address:l.address?l.address.toString(this.network):null,category:a?"receive":"send",amount:v.btc(a?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 h(c.MISC_ERROR,'tx.list ( "account" count from includeWatchonly)');t=new g([e]);var[e,r]=await this.accessControl(i,t.str(0,"")),s=t.u32(1,10),n=t.u32(2,0);t=t.bool(3,!1);if(e.watchOnly!==t)return[];var o=await e.getHistory(r),u=(t=(a.sortTX(o),n+s),Math.min(t,o.length)),l=[];for(let e=n;e<u;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 h(c.MISC_ERROR,"coin.selectone options (account)");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),a=t.obj(0,{}),s=[];for(const t of await r.getCoins(e)){var n=t.getDepth(this.wdb.curHeight),o=t.getAddress();if(o){var u=t.getHash("hex");if(u&&!t.isColored&&!(a.value&&t.value<a.value||t.coinbase&&0<t.height&&this.wdb.curHeight<t.height+b.COINBASE_MATURITY)&&(u=await r.getKey(u),s.push({txid:t.txid(),vout:t.index,address:o?o.toString(this.network):null,account:u?u.name:void 0,redeemScript:u&&u.script?u.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:n,spendable:!r.isConserved(t),solvable:!0}),a.len&&s.length>=a.len))break}}return s}async listUnspent(e,t,i){if(t||4<e.length)throw new h(c.MISC_ERROR,'coin.list ( minconf maxconf ["address", account] )');const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(3,"")),n=r.u32(0,1),u=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 h(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await s.getCoins(t);var m,y,b,w=(a.sortCoins(e),[]);for(const t of e)t.isColored||(m=t.getDepth(p))<n||u<m||((y=t.getAddress())?(b=t.getHash("hex"),l&&0<l.length&&(!b||!d.has(b))||(b=await s.getKey(b),w.push({txid:t.txid(),vout:t.index,address:y?y.toString(this.network):null,account:b?b.name:void 0,redeemScript:b&&b.script?b.script.toJSON():void 0,scriptPubKey:t.script.toJSON(),amount:v.btc(t.value,!0),confirmations:m,spendable:!s.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 h(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 h(c.MISC_ERROR,"prop.wallet.byaddress ( minconf maxconf [address, account] )");const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(3,"")),n=r.u32(0,1),u=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 h(c.INVALID_PARAMETER,"Duplicate address.");d.add(f)}}e=await s.getCoins(t);var m=(a.sortCoins(e),[]);for(const t of e){var y,b,w,x=t.getDepth(p);x<n||u<x||(y=t.getAddress())&&(b=t.getHash("hex"),!l||b&&d.has(b))&&(b=await s.getKey(b),w=t.getReturnData([F.OP_PROPCREATE,F.OP_PROPCREATE]))&&m.push({txid:t.txid(),vout:t.index,address:y?y.toString(this.network):null,account:b?b.name:void 0,amount:v.btc(t.value,!0),confirmations:x,spendable:!s.isConserved(t),solvable:!0,nd:w})}return m}async listPropByOid(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"prop.wallet.byoid oid");t=new g([e]);var[r,e]=await this.accessControl(i,t.str(1,"")),s=t.str(0),n=this.wdb.curHeight,o=(i=await r.getCoins(e),a.sortCoins(i),[]);for(const e of i){var u,l,p,d=e.getDepth(n);d<0||9999999<d||(u=e.getAddress())&&(l=e.getHash("hex"),l=await r.getKey(l),p=e.getReturnData([F.OP_PROPCREATE,F.OP_PROPEXCHANGE]))&&p.oid==s&&o.push({txid:e.txid(),vout:e.index,address:u?u.toString(this.network):null,account:l?l.name:void 0,amount:v.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 h(c.MISC_ERROR,'coin.list.locked ["address", account]');const r=new g([e]);var[s,t]=await this.accessControl(i,r.str(1,"")),n=r.array(0),u=this.wdb.curHeight,l=d.now(),p=new Set;if(n){const e=new g([n]);for(let t=0;t<n.length;t++){var f=e.str(t,"");f=o.parseHash(f,this.network);if(p.has(f))throw new h(c.INVALID_PARAMETER,"Duplicate address.");p.add(f)}}let m;m=account?await s.getCoins(t):s.getLockedCoins(),a.sortCoins(m);var y,b,w,x,k,S,_=[];for(const e of m)(e.lockedByLocktime(u,l)||e.lockedBySequence(u,l))&&(y=e.getAddress())&&(b=e.getDepth(u),S=e.getHash("hex"),!n||S&&p.has(S))&&([w,x,k]=e.getLockStatus(),S=await s.getKey(S),_.push({txid:e.txid(),vout:e.index,address:y?y.toString(this.network):null,account:S?S.name:void 0,redeemScript:S&&S.script?S.script.toJSON():void 0,scriptPubKey:e.script.toJSON(),amount:v.btc(e.value,!0),confirmations:b,spendable:!1,solvable:!0,locktype:w,lockheight:x,locktime:k}));return _}async listOperUnspent(e,t,i){if(t||e.length<1||2<e.length)throw new h(c.MISC_ERROR,'coin.conserved.oper.list unlock ([{"txid":"txid","vout":n},...]) 保持/解除保持一组UTXO: true/false [{"txid": "交易id","vout": "输出序号"}]');const r=new g([e]);var[a]=await this.accessControl(i),s=r.bool(0,!1);if(!(t=r.array(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(const e of t){const t=new g([e]);var n=t.hash("txid"),o=t.u32("vout");if(null==n||null==o)throw new h(c.INVALID_PARAMETER,"Invalid parameter.");n=new j(n,o),s?a.unConserveCoin(n):a.conserveCoin(n)}return!0}async setTXFee(e,t,i){if(t||e.length<1||1<e.length)throw new h(c.MISC_ERROR,"sys.setfee rate");if(null==(t=new g([e]).ufixed(0,8)))throw new h(c.TYPE_ERROR,"Invalid parameter.");return this.wdb.feeRate=t,!0}async signMessage(e,t,i){if(t||2!==e.length)throw new h(c.MISC_ERROR,'sys.message.sign "address" "message"');t=new g([e]);var[e]=await this.accessControl(i);if(!e.master.key)throw new h(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(u+i,"utf8"))).toString("base64");throw new h(c.WALLET_ERROR,"Address not found.")}async changePassphrase(e,t,i){if(t||e.length<2)throw new h(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 h(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(i.length<1||t.length<1)throw new h(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),a=r.str(0);r=r.u32(1,60);if(t||i.master.encrypted&&0==e.length)throw new h(c.MISC_ERROR,'wallet.unlock "passphrase" timeout');if(!i.master.encrypted)throw new h(c.WALLET_WRONG_ENC_STATE,"Wallet is not encrypted.");if(a.length<1)throw new h(c.INVALID_PARAMETER,"Invalid parameter");if(null==r)throw new h(c.TYPE_ERROR,"Invalid parameter");return await i.unlock(a,r),null}async decryptWallet(e,t,i){if(t||1!==e.length)throw new h(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 h(c.WALLET_WRONG_ENC_STATE,"Running with an decrypted wallet.");if(i.length<1)throw new h(c.MISC_ERROR,'wallet.decrypt "passphrase"');try{await e.setPassphrase(i)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Decryption failed.")}return"wallet decrypted"}async importPrunedFunds(e,t,i){if(t||e.length<2||3<e.length)throw new h(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 h(c.TYPE_ERROR,"Invalid parameter.");e=A.fromRaw(e);var r=(t=_.fromRaw(t)).hash("hex");if(!t.verify())throw new h(c.VERIFY_ERROR,"Invalid proof.");if(!t.hasTX(e.hash("hex")))throw new h(c.VERIFY_ERROR,"Invalid proof.");var a=await this.client.getEntry(r);if(-1===a)throw new h(c.VERIFY_ERROR,"Invalid proof.");if(r={hash:r,time:t.time,mtp:t.mtp,height:a},await this.wdb.addTX(e,r))return null;throw new h(c.WALLET_ERROR,"No tracked address for TX.")}async removePrunedFunds(e,t,i){if(t||1!==e.length)throw new h(c.MISC_ERROR,'tx.removeprunedfunds.admin "txid"');t=new g([e]);var[e]=await this.accessControl(i);if(!(i=t.hash(0)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(await e.remove(i))return null;throw new h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"sc.register options (account): 发布合约 合约参数列表 (子账户)");t=new g([e]);var[r,a]=await this.accessControl(i,t.str(1,""));let s=t.obj(0);if(!s)throw new h(c.MISC_ERROR,"sc.register: options is null");let n=1e5;switch(s.oper){case"change":if(s.oper=O.scState,!s.dst||!s.state)throw new h(c.TYPE_ERROR,"sc.register: dst or state is null.");if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.register: not support this operation.");var o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]);if(!o||0==o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract not exist.");switch(o.list[0].options.state){case C.Normal:if(s.state!=C.Frozen&&s.state!=C.Destroy)throw new h(c.TYPE_ERROR,"Contract State Error");break;case C.Frozen:if(s.state!=C.Normal&&s.state!=C.Destroy)throw new h(c.TYPE_ERROR,"Contract State Error");break;default:throw new h(c.TYPE_ERROR,"Contract State Error")}if(s.addr=o.list[0].options.addr,await r.belongToAccount(a,s.addr))break;throw new h(c.MISC_ERROR,"sc.register: Invald Account.");case"update":if(s.oper=O.scUpdate,!s.dst)throw new h(c.TYPE_ERROR,"sc.register: dst is null.");if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.register: not support this operation.");if(!(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]))||0==o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract not exist.");if(o.list[0].options.state!=C.Normal)throw new h(c.TYPE_ERROR,"sc.register: contract state error.");if(s.addr=o.list[0].options.addr,await r.belongToAccount(a,s.addr))break;throw new h(c.MISC_ERROR,"sc.register: Invald Account.");default:if(n=1e8,s.oper=O.scRegister,s.addr=(await r.createReceive(a)).getAddress("string"),s.dst=r.getSCAddress(d.hashInt(s.addr)).toString(),this.wdb.$parent&&(o=await this.wdb.$parent.chain.db.getSCList([["options.dst",s.dst]]))&&0<o.list.length)throw new h(c.TYPE_ERROR,"sc.register: contract address conflict.")}return(e=(await r.getPrivateKey(s.addr)).signData(s)).data.sig=e.sig,s=e.data,i=await r.send({subtractFee:!1,sort:!1,outputs:[{address:s.dst,value:n}],comment:JSON.stringify(s)},a),await this.wdb.logAudit({address:s.addr,oper:s.oper,hash:i.hash("hex"),index:0}),s.txid=i.rhash(),s}async scRun(e,t,i){if(t||e.length<1)throw new h(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(","),a=(t=t.obj(1,{}),r.shift());if(!this.wdb.$parent)throw new h(c.TYPE_ERROR,"sc.run: not support this operation.");var s=await this.wdb.$parent.chain.db.getSCList([["options.dst",a]]);if(!s||0==s.list.length)throw new h(c.TYPE_ERROR,"sc.run: contract not exist.");if(1!=s.list[0].options.state)throw new h(c.TYPE_ERROR,`sc.run: contract execute disabled(state ${s.list[0].options.state}).`);if(t.ver&&t.ver!=s.list[0].options.ver)throw new h(c.TYPE_ERROR,"sc.run: contract version inconsistency.");return s=(0|parseInt(r.shift()))>>>0,o.parseAddress(a,this.network),r=await e.send({subtractFee:!1,sort:!1,outputs:[{address:a,value:s}],comment:JSON.stringify({oper:"scrun",params:t})},i),a=await e.getAccount(i),await this.wdb.logAudit({address:a.receive.getAddress("string"),oper:O.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 h(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 h(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)),a=(o=e.str(1,"").split(","))[0],s=o[1],n=o[2],o=o[3]?parseInt(o[3]):15,[t,e]=await this.accessControl(t,e.str(2,"")),u=f.verifyDataFormat({name:r,ip:a,grate:o,cls:n});if(u)throw new h(c.MISC_ERROR,u);return u={cid:z(),oper:O.cpRegister,name:r,ip:a,grate:o,cls:n},await t.cpRegister(d.isBech32(s)?s:null,u,e,i),u}async cpChange(e,t,i){if(t||e.length<2)throw new h(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,"")),a=t.str(0),s=(t=decodeURIComponent(t.str(1,"")).split(","))[0],n=t[1];let o=t[2];var u=t[3];t=parseInt(t[4])||null;if(l=f.verifyDataFormat({name:s,ip:n,grate:t,cls:u}))throw new h(c.MISC_ERROR,l);o&&(o=k.fromString(o),r(o instanceof k,"Not an address."));var l={cid:a,newName:s,ip:n,addr:o,grate:t,cls:u},[,,]=await e.cpChange(l,i);return l.addr=l.addr.toString(),l}async cpQuery(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.query (conditions account): 查询钱包中的厂商列表 (复合条件 子帐号)");t=new g([e]);var r,[a,s]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=a.db.cpList.query(e);for(r of i.list)r.owned=await a.belongToAccount(s,r.current.address);return i}async cpQueryRemote(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.query.remote conditions: 查询厂商列表 (复合条件)");t=new g([e]);var r,[a,s]=await this.accessControl(i,t.str(1,""));e=t.array(0,[]),i=await a.db.client.execute("cp.remoteQuery",[e]);for(r of i.list)r.owned=await a.belongToAccount(s,r.current.address);return i}async cpMine(e,t,i){if(t)throw new h(c.MISC_ERROR,"cp.mine (conditions account): 查询钱包中归属当前操作员/指定账户的厂商列表 (复合条件 子帐号)");t=new g([e]);let[r,a]=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(a,t.current.address))).query(e)}async htlcSuggest(e,t,i){if(t||e.length<1||2<e.length)throw new h(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 h(c.MISC_ERROR,"htlc.suggest: params.ab(alice bchain address) is null");if(!Number.isInteger(e.amount))throw new h(c.MISC_ERROR,"htlc.suggest: illegal params.amount");if(e.amount=parseInt(e.amount),e.amount<0||e.amount>1e4*b.COIN)throw new h(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 h(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:k.fromString(r).hash,ab:k.fromString(e.ab).hash,ba:k.fromString(e.ba).hash},[i]=await i.sendContracts([e],t,R),i?{txid:i.rhash(),aa:r}:null;throw new h(c.MISC_ERROR,"htlc.suggest: params.target is null")}async htlcAssent(e,t,i){if(t||e.length<1||2<e.length)throw new h(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 h(c.MISC_ERROR,"htlc.assent: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new h(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 h(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:k.fromString(r).hash,amount:t.amount*t.rate},await e.sendContracts([r],i,I));return t?{txid:t.rhash()}:null}async htlcSuggestDeal(e,t,i){if(t||e.length<1||2<e.length)throw new h(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 h(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 h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"comm.comment: illegal params.amount");if(t.amount=parseInt(t.amount),t.amount<0||t.amount>1e4*b.COIN)throw new h(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&&(a=await e.createReceive(i),t.alice=a.getAddress()));var a=(await e.getPrivateKey(t.alice)).signData(r),[t]=(a.data.sig=a.sig,await e.sendContracts([a.data],i,B));return t?{txid:t.rhash()}:null}async commentQuery(e,t,i){if(t)throw new h(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 h(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 h(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 h(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 h(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),a=t.u64(1),s=t.u64(2),[e,,]=(t=t.str(3),await e.contractCreate(r,a,s,t,i));return e.toJSON()}async propGet(e,t,i){if(t)throw new h(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 h(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 h(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 h(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 h(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 h(c.MISC_ERROR,"prop.found prop not exist");if(!await e.hasAddress(t.current.address))throw new h(c.MISC_ERROR,"prop.found: current account not owned prop.");if(t.pst!=P.Ready)throw new h(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 h(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 h(c.MISC_ERROR,"prop.sale prop not exist");if(r.pst!=P.Ready)throw new h(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 h(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,"")),a=[];if((t=t.str(0).split(","))&&Array.isArray(t))for(var s of t){var n,o;3<=(s=s.split("|")).length&&(n=s[0],o=new j(d.revHex(s[1]),parseInt(s[2])),4<=s.length?a.push([o,k.fromString(n),s[3]]):a.push([o,k.fromString(n)]))}var[t,,e]=await e.propExchangeList(a,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 h(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 h(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 h(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 h(c.MISC_ERROR,"prop not exist");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop cannt be sent on current status");t=new j(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 h(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 h(c.MISC_ERROR,"prop.send prop not exist");if(t.pst!=P.Ready)throw new h(c.MISC_ERROR,"prop.send prop cannt be sent on current status");var[e,,t]=await e.propExchange(new j(t.current.hash,t.current.index),k.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 h(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 a of t)if(3<=(a=a.split("|")).length){var s=a[0],n=a[1],o=parseInt(a[2]);let e=null;4<=a.length&&(e=a[3]),o<b.MINPROPVALUE||r.push([s,n,o,e])}r=r.map(e=>{var[e,t,i,r]=e;return{oper:O.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=M.getType(L.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,"")),a=t.str(0);let u=t.str(1);if((t=t.u64(2,b.MINPROPVALUE))<b.MINPROPVALUE)throw new h(c.PROP_MINVALUE,"prop.create: not a valid value");if(0<=u.indexOf("file:")){const e=u.replace("file:","")||"docs/eth.jpg";u=await new Promise(t=>{this.readImageAsBlob(e,(e,i)=>{e?console.error("Error reading inscription:",e):t(i)})})}else{if(!(0<=u.indexOf("data:")))throw new h(c.MISC_ERROR,"inscription.create cid content gold (openid): 创建道具 厂商编码 素材(file:filename or data:{hex,type}) 含金量 [账户]");u=JSON.parse(u.replace("data:",""))}var s,n=await e.createReceive(r),o=w.sha256(Buffer.from(JSON.stringify(u))).toString("hex");if(o=await this.caIssuePublic([JSON.stringify({blob:u,hash:o,height:0}),n.getAddress("string"),"",r],null,i))return n={oper:O.propCreate,cid:a,gold:t,type:"inscription",oid:o.erid},[i,s]=await e.propCreate([n],r),i?n:null}throw new h(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 h(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),a=t.str(1),s=t.u64(2,b.MINPROPVALUE);t=t.str(3,null);if(s<b.MINPROPVALUE)throw new h(c.PROP_MINVALUE,"prop.create: not a valid value");r={oper:O.propCreate,cid:r,oid:a,gold:s,pid:t};var[a,,]=await e.propCreate([r],i);return a?r:null}async attach(e,t,i){if(t||e.length<3)throw new h(c.MISC_ERROR,"tx.attach addr amount data (openid): 发送附言交易 地址 金额 附言结构 [账户]");t=new g([e]);var[e,i]=await this.accessControl(i,t.str(3,"")),r=t.str(0),a=t.u64(1),[a,,]=(r=((t=t.obj(2,{})).oper=O.attach,{address:r,value:a,data:t}),await e.attach([r],i));return a?r:null}async walletLock(e,t,i){if(t)throw new h(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 h(c.MISC_ERROR,"Wallet is not encrypted, please run wallet.lock passphrase");try{await t.setPassphrase(null,i)}catch(e){throw new h(c.WALLET_ENCRYPTION_FAILED,"Encryption failed.")}}return await t.lock(),null}async listMSTrans(e,t,i){if(t)throw new h(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 h(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(s.ms(k.getHash(e,"hex"),r))))throw new h(c.MISC_ERROR,"tx.mstrans.sign txid");if(e=JSON.parse(e.toString()),!await i.belongToAccount(t,e.addr))throw new h(c.MISC_ERROR,"tx.mstrans.sign invalid account");var a,o=await this.wdb.get(e.addr);o&&o.account.type==n.types.MULTISIG&&((a=E.fromRaw(e.data,"hex")).view=await o.getCoinView(a),await o.sign(a),a.isSigned()?await o.sendMTX(a):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:a.toRaw().toString("hex")}})},t),await this.wdb.delMSTrans(e.addr,r))}async resendWalletTransactions(e,t,i){if(t||0!==e.length)throw new h(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 h(c.MISC_ERROR,"tx.resendall.admin: 重发挂起交易");var r=await this.wdb.resend();if(r)for(var a of Object.keys(r))if(a)for(const e of r[a])await this.wdb.send(e);return!0}async rescan(e,t,i){if(t)throw new h(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 h(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 h(c.MISC_ERROR,"address.calc account(must be typeof number) branch index");t=new g([e]);let[a,s]=await this.accessControl(i,t.int(0,0));return e=t.u32(1,0),i=t.u32(2,0),"default"==s&&(s=0),t=(await a.deriveKey(s,e,i,a.master)).toJSON(),i=(e=await a.deriveKey(s,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 h(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 h(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 h(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 a of await this.wdb.getWallets())if((await this.wdb.get(a)).master.mnemonic.getPhrase()===body.phrase)throw new h(c.MISC_ERROR,"wallet.create: 相同助记词已被使用");return(r=await this.wdb.ensure({id:z(),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 h(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 h(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),a.sortTX(t),[]);for(const i of await e.toDetails(t))r.push(i.toJSON());return r}async getPendingItem(e,t,i){var r,a=(e=new g([e])).hash(0,""),[s,i]=await this.accessControl(i,e.str(1,""));for(r of await s.getPending(i))if(r.hash==a)return(r=await s.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),a.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 h(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),a=e.obj(0);e=e.str(1),a={name:(a=new g([a])).str("name"),witness:a.bool("witness",!0),type:a.str("type","pubkeyhash"),m:a.u32("m",1),n:a.u32("n",1),watchOnly:a.bool("watch",!1),accountKey:a.str("key",null),lookahead:a.u32("lookahead",10)};try{let t=await i.getAccount(a.name);return t?t.toJSON():((r=(t=await i.createAccount(a,e)).toJSON()).isNew=!0,r)}catch(t){return null}}async getblocks(e,t,i){if(t)throw new h(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 h(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 h(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 h(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 h(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),a=e.hash(0);e=e.u32(1);return(i=(r(a,"Hash is required."),r(null!=e,"Index is required."),await i.getCoin(a,e)))?i.getJSON(this.network):null}async getSpender(e,t,i){e=new g([e]);var[i]=await this.accessControl(i),a=e.hash(0);e=e.u32(1);return(i=(r(a,"Hash is required."),r(null!=e,"Index is required."),await i.txdb.getSpender(a,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),a=e.hash(0);e=e.u32(1),r(a,"Hash is required."),r(null!=e,"Index is required."),i=await i.txdb.getSpentCoin({hash:a,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 h(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 j(i,t);return e.conserveCoin(i),!0}async getConservedCoins(e,t,i){if(t||0<e.length)throw new h(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 h(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 j(i,t);return e.unConserveCoin(i),!0}async addShared(e,t,i){if(t||e.length<1)throw new h(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 h(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 h(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),a=t.str(1,null);if(null==(t=t.u64(2)))throw new h(c.TYPE_ERROR,"Invalid parameter.");if(r&&a)return t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:JSON.stringify({oper:O.vote,type:"oracle",k:r,v:a})},r=await e.send(t,i),(await e.getDetails(r.hash("hex"))).toJSON()}throw new h(c.MISC_ERROR,"oracle.send k v amount [openid]")}async sendVote(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,"vote.send addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0);if(null==(t=t.u64(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(r of a.split(","))if(!o.parseAddress(r,this.network))throw new h(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": "${O.vote}", "type": "mine", "ca": "${a}"}`},a=await e.send(t,i),(await e.getDetails(a.hash("hex"))).toJSON()}async sendVoteAsync(e,t,i){if(t||e.length<2||3<e.length)throw new h(c.MISC_ERROR,"vote.send.async addresses amount [openid]");t=new g([e]);var r,[e,i]=await this.accessControl(i,t.str(2,"")),a=t.str(0);if(null==(t=t.u64(1)))throw new h(c.TYPE_ERROR,"Invalid parameter.");for(r of a.split(","))if(!o.parseAddress(r,this.network))throw new h(c.TYPE_ERROR,"Invalid address.");t={subtractFee:!1,selection:"age",sort:!1,outputs:[{address:(await e.createReceive(i)).getAddress("string"),value:t}],comment:`{"oper": "${O.vote}", "type": "mine", "ca": "${a}"}`},e.send(t,i)}async sendTX(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.send addr amount [openid]:发送交易 地址 金额 [发起账户]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new h(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 h(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 h(c.MISC_ERROR,"tx.sign.admin txdata [sendnow passphrase]: 对交易签名/发送 交易原始数据 [立即发送 解锁密码]");t=new g([e]);var[e]=await this.accessControl(i),a=(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 s=null;return s=(a&&i.isSigned()?await e.sendMTX(i):i).getJSON(this.network),e.account.type==n.types.MULTISIG&&(t=i.getMultisig(this.network),s.ms={m:t.m,n:t.n,c:t.c}),s}async createTX(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"tx.create options outputs [openid]: 创建交易 参数对象 输出数组 [子账号]");if(this.wdb.$parent&&this.wdb.$parent.config.abandon)throw new h(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 a of i.in)a.hash=d.revHex(a.hash);var s={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]),u={value:o.u64("value")};if(u.address=o.str("address"),!u.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 h(c.MISC_ERROR,`tx.create: account ${l} not exist`);u.address=p.getAddress("string")}}if((l=o.buf("script"))&&(u.script=y.fromRaw(l)),(p=o.str("locktype"))&&(o=o.u64("locktime",0))){if("no"!=p&&"clb"!=p&&"clt"!=p&&"csb"!=p&&"cst"!=p)throw new h(c.MISC_ERROR,'locktype should be "no"-不锁定 or "clb"-绝对高度锁定 or clt(绝对时间锁定) or "csb"-相对高度锁定 or "cst"-相对时间锁定 !');if(p==y.outputLockType.CHECKABSOLUTETIME&&o<=b.LOCKTIME_THRESHOLD)throw new h(c.MISC_ERROR,"lock absolute time should not less than 500000000!");if(p==y.outputLockType.CHECKABSOLUTEBLOCK&&o>b.LOCKTIME_THRESHOLD)throw new h(c.MISC_ERROR,"lock absolute block should not more than 500000000!");if((p==y.outputLockType.CHECKRELATIVEBLOCK||p==y.outputLockType.CHECKRELATIVETIME)&&65535<o)throw new h(c.MISC_ERROR,"lock relative block/time should not more than 65535!");u.locktype=p,u.locktime=o}s.outputs.push(u)}e&&(s.account=e);let f=null;return s.sendnow?(i=await r.send(s),f=(t=await r.getDetails(i.hash("hex"))).toJSON()):(e=await r.createTX(s),await r.sign(e),f=e.getJSON(this.network),r.account.type==n.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 h(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 h(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 h(c.MISC_ERROR,"ca.user.status cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),a=t.array(2,[]);let s=null;for(let e=0;e<a.length;e++){var n=a[e];n&&Array.isArray(n)?"alliancename"==n[0]&&(s=n[1],delete a[e]):delete a[e]}var[t]=await this.accessControl(i);e=await this.$allianceUserCreate([e,r,s],i);return a.push(["pubkey",e.data.pubkey]),a.push(["merge",!0]),t.db.client.execute("ca.list",[a])}async caUserLog(e,t,i){if(t||e.length<2)throw new h(c.MISC_ERROR,"ca.user.log cid uid (query)");e=(t=new g([e])).str(0,"");var r=t.uint(1,0),a=t.array(2,[]);let s=null;for(let e=0;e<a.length;e++){var n=a[e];n&&Array.isArray(n)?"alliancename"==n[0]&&(s=n[1],delete a[e]):delete a[e]}var[t,,]=await this.accessControl(i,e);e=await this.$allianceUserCreate([e,r,s],i);return a.push(["pubkey",e.data.pubkey]),t.db.client.execute("ca.list",[a])}async sysLog(e,t,i){if(t)throw new h(c.MISC_ERROR,"sys.log (query openid)");e=(t=new g([e])).array(0,[]);var r,[a,,]=await this.accessControl(i,t.str(1,"")),s=[];for(r of(await this.wdb.auditList.query(e)).list){var n=Object.assign({},r),u=o.parseHash(r.address,this.network);(u=await a.getPath(u))&&(n.account=u.name),n.time=new Date(1e3*r.time).toLocaleString(),s.push(n)}return s}async caIssuePublic(e,t,i){if(t||e.length<2||4<e.length)throw new h(c.MISC_ERROR,"ca.issue.public cert witness [pubkey openid]: 签发证书 证书对象 见证地址 [原始存证签名公钥 支付账户]");e=(t=new g([e])).obj(0,{});var r=t.str(1,""),a=t.str(2,""),[i,t]=await this.accessControl(i,t.str(3,""));if(64!=e.hash.length)throw new h(c.TYPE_ERROR,"err hash length");var s=await i.db.client.execute("ca.byId",[e.hash]);if(s)return s;if(s=await i.getPrivateKey(r))return e.height||(e.height=b.retargetInterval),await i.issueCreate({erid:e.hash,key:s.privateKey.toString("hex"),address:s.getAddress().toString(),witness:s.publicKey.toString("hex"),validHeight:this.wdb.curHeight+e.height,source:{subjectName:e.name||"",pubkey:a,subjectHash:e.hash,cluster:e.cluster,blob:e.blob}},t);throw new h(c.TYPE_ERROR,"Invalid witness.")}async caAbolishPublic(e,t,i){if(t||e.length<1)throw new h(c.MISC_ERROR,"ca.abolish.public array[[erid height [openid]]]: 废止授信交易 废止交易信息数组");var r,a=[];for(r of new g([e]).array(0,[])){var[s,n]=await this.accessControl(i,r[3]),o=r[0],u=parseInt(r[1]),l=await this.wdb.erList.query([["erid",o]]),p=(l=k.fromWitnessPubkeyhash(w.hash160(Buffer.from(l.list[0].witness,"hex")),this.network.type).toString(),await s.getKey(l));if(!p)throw new h(c.TYPE_ERROR,"Invalid witness.");(s=await s.caAbolish({key:p.privateKey.toString("hex"),witness:p.publicKey.toString("hex"),address:l,erid:o,abolishHeight:u,cid:"",uid:0},n))&&a.push(s)}return a}async caIssue(e,t,i){if(t||e.length<3||4<e.length)throw new h(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 h(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,{}),a=e.uint(1,0),s=e.str(2,""),[e,n]=await this.accessControl(t,e.str(3,""));if(!(o=await e.ensureCp(s))||"forbidden"==o.cls)throw new h(c.MISC_ERROR,"Invalid Account");if(64!=r.hash.length)throw new h(c.TYPE_ERROR,"err hash length");var o=await this.$allianceUserCreate([s,a],t),u=[];if(u.push(["pubkey",o.data.pubkey]),u.push(["source.subjectHash",r.hash]),0<(await e.db.client.execute("ca.list",[u])).count)throw new h(c.TYPE_ERROR,"cert.hash conflicted");if(await e.db.client.execute("ca.byId",[r.hash]))throw new h(c.TYPE_ERROR,"cert.hash conflicted");return r.height||(r.height=b.retargetInterval),o=await this.$allianceUserCreate([s,a],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:s,uid:a}},n,i)}async caAbolish(e,t,i){if(t||e.length<1)throw new h(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 h(c.MISC_ERROR,"ca.abolish.async [[uid cid erid height [openid]]]: 废止授信交易 废止交易信息数组");return this.$caAbolish(e,i,!0)}async $caAbolish(e,t,i){var r,a=[];for(r of new g([e]).array(0,[])){var s,n=r[0],o=r[1],c=r[2],u=parseInt(r[3]),[s,h]=await this.accessControl(t,r[4]),l=await this.$allianceUserCreate([o,n],t,!0);(s=await s.caAbolish({cid:o,uid:n,key:l.prvkey,witness:l.data.pubkey,address:l.data.addr,erid:c,abolishHeight:u},h,i))&&a.push(s)}return a}async enchanceCp(e,t,i){if(t||e.length<2||4<e.length)throw new h(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),a=t.str(1,0);let s=t.uint(2,0);(!s||s<this.wdb.curHeight)&&(s=this.wdb.curHeight+b.retargetInterval);var[t,e]=await e.enchanceCp({to:r,from:a,enchanceHeight:s},i);return t&&e?e:null}async queryErList(e,t,i){if(t)throw new h(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 h(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(31);const{ContractEnvType:a,ContractStatus:s}=i(5),n=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==s.CreatedOnMem?await this.delTransContract(e,!0):(e.id=e.type+"."+e.addr,await this.saveContract(e),e.transStatus==s.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:s.None}async addTransContract(e,t,i=!1){t.id=t.type+"."+t.addr;var r=this.get(t.id);e===a.Mempool&&((t=r||t).transStatus||(t.transStatus=s.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=n.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 a=this.get(r);return a&&a.oper==e.oper||(i=!0,a=e),(!a.transStatus||a.transStatus<s.Promised)&&(i=!0,a.transStatus=s.Promised),i&&await this.saveContract(a,t),i}async confirmContract(e,t,i){e=e.type+"."+e.addr,!(e=this.get(e))||e.transStatus!=s.Promised||t!=s.Confirmed&&t!=s.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=n.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(31);class a 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)}}a.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=a},,,,,,,,,,,,,,,function(e,t,i){"use strict";
|
|
852
852
|
/*!
|
|
853
853
|
* int64.js - int64 object for javascript.
|
|
854
854
|
* Copyright (c) 2017, Christopher Jeffrey (MIT License).
|