gamegold 4.1.0 → 4.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/gamegold-worker.js +3 -3
- package/lib/gamegold.js +6 -6
- package/package.json +1 -1
package/lib/gamegold-worker.js
CHANGED
|
@@ -196,7 +196,7 @@ var i=r(128),s=i.Buffer;function n(e,t){for(var r in e)t[r]=e[r]}function a(e,t,
|
|
|
196
196
|
* pkg.js - package constants
|
|
197
197
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
198
198
|
* https://github.com/bookmansoft/gamegold
|
|
199
|
-
*/t.protocol="vallnet",t.version="v4.1.
|
|
199
|
+
*/t.protocol="vallnet",t.version="v4.1.1",t.url="https://github.com/bookmansoft/gamegold"},function(e,t,r){"use strict";
|
|
200
200
|
/*!
|
|
201
201
|
* common.js - p2p constants for vallnet
|
|
202
202
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -292,7 +292,7 @@ const i=r(21).opcodes;function s(e){let t=null;var r=s.list[e.type];return new(r
|
|
|
292
292
|
/*!
|
|
293
293
|
* wallet.js - wallet object for vallnet
|
|
294
294
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
295
|
-
*/const i=r(0);var s=r(16);const n=r(15),a=r(1),o=r(3),c=r(34),u=r(199),h=r(119).sortWithSeq,l=r(7),p=r(94),d=r(2),f=r(4),m=r(70),g=r(339);r(222);const y=r(110),v=r(73),b=r(12),w=r(60),x=r(17),k=r(223),S=r(124),E=r(26),_=r(159),A=r(340),R=r(65),I=r(28),j=r(27),C=r(6),P=r(311),O=r(39),T=S.Mnemonic,{opcodes:F,hashType:B}=r(21),N=r(167),D=r(77),L=r(78),z=r(143),H=r(46),M=r(19),U=r(43),q=r(53),{NotifyMsg:V,OrderData:K,ContractStatus:W,ContractType:$}=r(5),G=r(37).VerifyError,Y=r(85).stockItem,X=r(157).ErItem,J=r(158).ErAbolishItem,Z=r(237).EnchancementItem,Q=r(31),ee=r(69),te=r(59),re=r(82);class ie extends s{constructor(e,t){super(),i(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 R(1e4),this.accountCache=new R(1e4),this.pathCache=new R(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 A,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,r,s=e.master;return s?("string"==typeof s&&(s=S.PrivateKey.fromBase58(s,this.network)),i(S.isPrivate(s),"Must create wallet with hd private key.")):(r=new T(e.mnemonic),s=S.fromMnemonic(r,this.network)),i(s.network===this.network,"Network mismatch for master key."),this.master.fromKey(s,r),null!=e.wid&&(i(a.isU32(e.wid)),this.wid=e.wid),e.id&&(i(v.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(i("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(i("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(i(a.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(i(Buffer.isBuffer(e.token)),i(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new ie(e).fromOptions(t)}async init(e){var t=e.passphrase;i(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);i(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){i(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,r){var i={alliancename:e,nodeid:t};return e?(i.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),r?(i.prv=Buffer.alloc(0),i.pub=Buffer.from(r,"hex"),i.awardAddress=b.fromWitnessPubkeyhash(l.hash160(i.pub),this.network.type).toString(this.network.type),i.mnemonic=new T):(r=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),i.mnemonic=new T({entropy:r,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),i.prv=l.hash256(Buffer.from(i.mnemonic.toSeed().toString("hex"))),i.pub=I.publicKeyCreate(i.prv,!0),e=A.fromKey(S.fromMnemonic(i.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),i.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(t=await this.createReceive("default",1,this.master),i.prv=t.privateKey,i.pub=t.publicKey,i.awardAddress=b.fromWitnessPubkeyhash(l.hash160(i.pub),this.network.type).toString(this.network.type),i.mnemonic=new T),i.address=b.fromWitnessPubkeyhash(l.hash160(i.pub),this.network.type).toString(),i}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 r=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{r()}}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 r;this.start();try{r=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),r}async removeSharedKey(e,t){var r=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{r()}}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 r;this.start();try{r=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),r}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 r=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{r()}}async _renameAccount(e,t){if(!v.isName(t))throw new Error("Bad account name.");var r=await this.getAccount(e);if(!r)throw new Error("Account not found.");if(0===r.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=r.name,this.start(),this.db.renameAccount(r,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const i of e)i.account===r.accountIndex&&(i.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(){i(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 r=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{r()}}async _createAccount(e,t){let r,s,n=e.name,o=(n=n||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=a.hashInt(n)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(n))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(r=e.accountKey)&&(r=S.PublicKey.fromBase58(r,this.network)),!S.isPublic(r))throw new Error("Must add HD public keys to watch only wallet.");i(r.network===this.network,"Network mismatch for watch only key.")}else i(this.master.key),r=(r=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":n,witness:e.witness,watchOnly:this.watchOnly,accountKey:r,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(s=_.fromOptions(this.db,t)).wallet=this,await s.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",s.id,s.name,s.accountIndex),this.accountDepth++,this.save(),await this.commit(),s}async ensureAccount(e,t){var r=e.name;return(r=await this.getAccount(r))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,r=null){return this.createKey(e,0,t,r)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,r=0,i=null){var s=await this.writeLock.lock();try{return await this._createKey(e,t,r,i)}finally{s()}}async _createKey(e,t,r=0,i=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let s;this.start();try{s=await e.createKey(t,r,i)}catch(e){throw this.drop(),e}return await this.commit(),s}async deriveKey(e,t,r,i=null){let s=null;var n=await this.writeLock.lock();try{this.start(),s=await this._deriveKey(e,t,r,i),await this.commit()}catch(e){throw this.drop(),e}finally{n()}return s}async _deriveKey(e,t,r=0,i=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,r,i),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),i(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),i(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),r=await this.getAccountHashes(t),s=await this.getAccountName(e),n=(i(s),[]);for(const e of r){var a=await this.readPath(e);i(a),i(a.account===t),a.name=s,this.pathCache.set(a.hash,a),n.push(a)}return n}async importKey(e,t,r){var i=await this.writeLock.lock();try{return await this._importKey(e,t,r)}finally{i()}}async _importKey(e,t,r){if(e&&"object"==typeof e&&(r=t,t=e,e=null),null==e&&(e=0),i(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var s=t.getHash("hex");if(await this.getPath(s))throw new Error("Key already exists.");if(!(s=await this.getAccount(e)))throw new Error("Account not found.");if(s.type!==_.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(r),e=k.fromRing(s,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),i(e.data),e.encrypted=!0),this.start();try{await s.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var r=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{r()}}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!==_.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=y.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var r=await this.writeLock.lock();try{return await this._fund(e,t)}finally{r()}}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 r;if(null!=t.account){if(!(r=await this.getAccount(t.account)))throw new Error("Account not found.")}else r=this.account;if(!r.initialized)throw new Error("Account is not initialized.");let s,n=t.rate;return null==n&&(n=await this.db.estimateFee(t.blocks)),s=t.smart?await this.getSmartCoins(r.name):(s=await this.getCoins(r.name),this.txdb.filterConserved(s)),await e.fund(s,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:r.change.getAddress(),height:this.db.curHeight,rate:n,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&i(e.getFee()<=P.MAX_FEE,"TX exceeds MAX_FEE."),s}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=C.WITNESS_SCALE_FACTOR,r=b.fromScript(e);if(!r)return-1;var i=await this.getAccountByAddress(r);if(!i)return-1;let s=0;if(e.isScripthash()&&i.witness)switch(i.type){case _.types.PUBKEYHASH:s=4*(s+23);break;case _.types.MULTISIG:s=4*(s+35)}switch(i.type){case _.types.PUBKEYHASH:s=s+74+34;break;case _.types.MULTISIG:s=(s=(s=(s=(s+=1)+74*i.m)+3+1)+34*i.n)+1+1}return i.witness?s=((s+=1)+t-1)/t|0:s+=o.sizeVarint(s),s}async createTX(e){var t=e.outputs,r=new w;i(Array.isArray(t),"Outputs must be an array."),i(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),r.outputs.push(E.fromScript(x.createScript(Buffer.from(e.comment),x.types.NULLDATA),0)));for(const e of t){var s=new E(e),n=s.getAddress();if(s.isDust())throw new Error("Output is dust.");if(0<s.value){if(!n)throw new Error("Cannot send to unknown address.");if(n.isNull())throw new Error("Cannot send to null address.")}r.outputs.push(s)}let a=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(a=o.getAddress(),e.allowPreInput=!0,r.addCoin(o))}else await this.fund(r,e);if(a&&((t=new E).value=r.getFee()-P.MIN_FEE,t.script.fromAddress(a),r.outputs.push(t),r.changeIndex=r.outputs.length-1),!1!==e.sort&&r.sortMembers(),null!=e.locktime&&r.setLocktime(e.locktime),i(r.isSane(),"TX failed sanity check."),i(r.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(r))throw new Error("Templating failed.");return r}async send(e,t){var r=await this.sendLock.lock();try{return await this._send(e,t)}finally{r()}}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 r=e.toTX();if(r.getSigopsCost(e.view)>j.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(r.getWeight()>j.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,r.txid()),await this.db.addTX(r),await this.db.send(r)),r}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const r of e)t.push(r.tx);for(const e of await h(t,this.db))await this.db.send(e);return t}async deriveInputs(e){i(e.mutable);var t=[];for(const i of await this.getInputPaths(e)){var r=await this.getAccount(i.account);r&&(r=r.derivePath(i,this.master))&&t.push(r)}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(!te.unsupported){var t=await this.db.getTip(),r=a.date();let o=1,c="",u=[a.fmt("# Wallet Dump created by %s %s",re.protocol,re.version),a.fmt("# * Created on %s",r),a.fmt("# * Best block at time of backup was %d (%s).",t.height,a.revHex(t.hash)),a.fmt("# * File: %s",e.file),""];t=a.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),u.push(t),t=await this.getAccounts();for(const e of t){var i=await this.getAccount(e);i=a.fmt("C %s name= %s index= %d",i.toRaw().toString("base64"),i.name,i.accountIndex);u.push(i)}for(const t of await this.getAddressHashes()){var s,n=await this.getPrivateKey(t);n&&(s=n.getAddress("string"),n=a.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",n.toSecret(),r,n.account,n.branch,n.index,s),u.push(n),1e5<u.length)&&(c=u.join("\n"),await te.writeFile(`${e.file}-${o++}.txt`,c,"utf8"),u=[])}u.push(""),u.push("# End of dump"),u.push(""),c=u.join("\n"),await te.writeFile(`${e.file}-${o++}.txt`,c,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var r=await this.getAccount(e.account);return r?(await this.unlock(t),(t=r.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(i(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const i of e.getInputHashes("hex")){var r=await this.getPath(i);r&&t.push(r)}return t}async getOutputPaths(e){var t=[];for(const i of e.getOutputHashes("hex")){var r=await this.getPath(i);r&&t.push(r)}return t}async setLookahead(e,t){var r=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{r()}}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 i of e.outputs){var r=i.path;r&&-1!==r.index&&(t.has(r.account)||t.set(r.account,[]),t.get(r.account).push(r))}var s,n,a=[];for([s,n]of t){let e=-1,t=-1,r=-1;for(const i of n)switch(i.branch){case 0:i.index>e&&(e=i.index);break;case 1:i.index>t&&(t=i.index);break;case 2:i.index>r&&(r=i.index)}e+=2,t+=2,r+=2;var o=await this.getAccount(s);(o=(i(o),await o.syncDepth(e,t,r)))&&a.push(o)}return a}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async getOrderList(e,t){let r=[];var i=new Q;(await this.getHistory(t||"default")).reduce((e,t)=>{var{tx:t,hash:i,height:s}=t;if(t.outputs[0].getReturnType(F.OP_RETURN))try{var n,a=JSON.parse(t.outputs[0].script.code[1].toString());a&&a.oper==$.payOrder&&((n=K.fromJson(a)).hash=i,n.height=s,e.set(""+n.cid+n.sn,n),r.push(n.cid))}catch(e){}return e},i),t=i.query(e);return await this.db.flushCP(r),t.list.map(e=>{e.cp=this.db.cpList.getItem(e.cid)}),t}async propCreate(e,t){var r,s=new w;for(r of e){var n=await this.ensureCp(r.cid,!0);!n||r.cid==this.network.genesisId||(r.gold=(0|r.gold)>>>0,r.gold<C.MINPROPVALUE)||(r.pid||(r.pid=z()),s.propCreate(n.current.address,r),r.index=s.outputs.length-1)}if(0<s.outputs.length){t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s);var a,o=s.commit();for(a of(await this.db.addTX(o[0]),await this.db.send(o[0]),i(o[0].verify(o[1],x.flags.STANDARD_VERIFY_FLAGS)),e))a.hash=o[0].hash("hex"),a.txid=o[0].txid();return o}return[]}async stockAddress(e,t){return await this.ensureAccount({name:t,witness:!0}),(await this.createReceive(t,a.hashInt(e),this.master)).getAddress()}async stockOffer(e,t,r,s){i(!!e),i(!!t),i(!!r),t=(0|t)>>>0,r=(0|r)>>>0;var n=await this.ensureCp(e),a=await this.getKey(n.current.address);if(i(!!a),s&&s!==a.name)throw new D(L.errors.TYPE_ERROR,"illegal account");return a=a.signData({cid:e,type:Y.RecordType.Offer,sum:t,price:r}),(e=new w).outputs.push(E.fromScript(a.data.addr,.05*t*r)),t=new V($.stock,z(),this.db.curHeight,a),r=E.fromScript(x.createScript(t.toRaw(),x.types.NULLDATA),0),e.outputs.push(r),s?await this.fund(e,{account:s}):await this.fund(e),e.outputs.shift(),await this.sign(e),a=e.commit(),i(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(a[0]),await this.db.send(a[0]),t.hash=a[0].hash("hex"),t.height=-1,t.cp=n,t}async stockPurchase(e,t,r){if(i(!!e),i(!!t),(t=(0|t)>>>0)<C.STOCK_TRADE_SINGLE||t>C.STOCK_MAX_TRADE_SINGLE)throw new D(L.errors.TYPE_ERROR,"Invalid Stock Amount.");var s=await this.ensureCp(e),n=(e={type:Y.RecordType.Purchase,cid:e,uid:r,seq:0,to:s.current.address,sum:t},e=(await this.addStockAccountSeq(e),await this.tokenCreate(e,r)),new w),a=(e=new V($.stock,z(),this.db.curHeight,e),E.fromScript(x.createScript(e.toRaw(),x.types.NULLDATA),0));n.outputs.push(a),n.outputs.push(E.fromScript(s.current.address,t*s.stock.price)),r?await this.fund(n,{account:r}):await this.fund(n),await this.sign(n),a=n.commit();return i(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(a[0]),await this.db.send(a[0]),e.hash=a[0].hash("hex"),e.height=-1,e.cp=s,e}async stockPurchaseTo(e,t,r,s){if(i(!!e),i(!!t),(t=(0|t)>>>0)<C.STOCK_TRADE_SINGLE||t>C.STOCK_MAX_TRADE_SINGLE)throw new D(L.errors.TYPE_ERROR,"Invalid Stock Amount.");var n=await this.ensureCp(e),a=(e={type:Y.RecordType.Purchase,cid:e,uid:r,seq:0,to:n.current.address,sum:t},e=(await this.addStockAccountSeq(e),await this.tokenCreate(e,r)),r=new w,e=new V($.stock,z(),this.db.curHeight,e),E.fromScript(x.createScript(e.toRaw(),x.types.NULLDATA),0));r.outputs.push(a),r.outputs.push(E.fromScript(n.current.address,t*n.stock.price)),s?await this.fund(r,{account:s}):await this.fund(r),await this.sign(r),a=r.commit();return i(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(a[0]),await this.db.send(a[0]),e.hash=a[0].hash("hex"),e.height=-1,e.cp=n,e}async stockSend(e,t,r,s,n){i(!!e),i(!!t),t=(0|t)>>>0;var a=await this.ensureCp(e,!0);return a?(e={type:Y.RecordType.Send,cid:e,uid:s,seq:0,sum:t,to:r},await this.addStockAccountSeq(e),t=await this.tokenCreate(e,s,n),r=new w,e=new V($.stock,z(),this.db.curHeight,t),n=E.fromScript(x.createScript(e.toRaw(),x.types.NULLDATA),0),r.outputs.push(n),s?await this.fund(r,{account:s}):await this.fund(r),await this.sign(r),t=r.commit(),i(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(t[0]),await this.db.send(t[0]),e.hash=t[0].hash("hex"),e.height=-1,e.cp=a,e):null}async stockBid(e,t,r,s,n){i(!!e),i(!!t),i(!!r),t=(0|t)>>>0,r=(0|r)>>>0;var a=await this.ensureCp(e,!0);return a?(e={type:Y.RecordType.Bid,cid:e,uid:s,seq:0,sum:t,price:r},await this.addStockAccountSeq(e),e=await this.tokenCreate(e,s,n),(n=new w).outputs.push(E.fromScript(e.data.addr,.05*t*r)),t=new V($.stock,z(),this.db.curHeight,e),r=E.fromScript(x.createScript(t.toRaw(),x.types.NULLDATA),0),n.outputs.push(r),s?await this.fund(n,{account:s}):await this.fund(n),n.outputs.shift(),await this.sign(n),e=n.commit(),i(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(e[0]),await this.db.send(e[0]),t.hash=e[0].hash("hex"),t.height=-1,t.cp=a,t):null}async stockAuction(e,t,r,s,n,a){i(!!e),i(!!t),i(!!r);var o=await this.ensureCp(e,!0);if(!o)return null;r=(0|r)>>>0;e={type:Y.RecordType.Auction,cid:e,to:t,uid:n,seq:0,sum:r,price:s},await this.addStockAccountSeq(e),e=await this.tokenCreate(e,n,a),a=new w,e=new V($.stock,z(),this.db.curHeight,e);var c=E.fromScript(x.createScript(e.toRaw(),x.types.NULLDATA),0);a.outputs.push(c),a.outputs.push(E.fromScript(t,r*s)),n?await this.fund(a,{account:n}):await this.fund(a),await this.sign(a),c=a.commit();return i(c[0].verify(c[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(c[0]),await this.db.send(c[0]),e.hash=c[0].hash("hex"),e.height=-1,e.cp=o,e}async sendSecret(e,t,r){let i=this.db.$contacts.get(e);if(!i||!i.sender){var s=(await this.createReceive(r)).getAddress("string");if(e==s)throw new D(L.errors.TYPE_ERROR,"Forbid Sending to Self Address.");i=await this.db.ensureContact({contact:e,messenger:s,wallet:this,account:r})}if(i)return i.send(t);throw new D(L.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){i(!!e),i(!!e.dst),i(!!e.content);var t=new w,r=e.src||this.getReceive().toString(),s=(r=new V($.notify,z(),this.db.curHeight,{src:r,content:e.content}),E.fromScript(x.createScript(r.toRaw(),x.types.NULLDATA),0));t.outputs.push(s),s={address:e.dst,locktime:C.BLOCK_DAY,locktype:"csb",value:.1*C.COIN},t.outputs.push(new E(s)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),s=t.commit();return i(s[0].verify(s[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,s[0].txid()),await this.db.send(s[0]),r.hash=s[0].hash("hex"),r.height=-1,r}async payOrder(e,t,r,s,n){i(!!e),i(!!t),i(!!r),i(!!s);var o=(await this.tokenCreate({cid:e,uid:t},n)).data.addr,c=(r=a.sprintf("%0-36s",r),await this.getOrderList([["cid",e],["sn",r]],n));if(0<c.list.length)return c.list[0];if((s=(0|s)>>>0)<C.MINPROPVALUE)return null;if(!(c=await this.ensureCp(e,!0)))return null;e=new K(e,t,r,s,o,"");var u=new w;t=E.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0);for(u.outputs.push(t),u.outputs.push(E.fromScript(c.current.address,s)),n?await this.fund(u,{account:n}):await this.fund(u);2<u.outputs.length;)u.outputs.pop();return await this.sign(u,null,B.ZERO|B.ANYONECANPAY),r=u.commit(),i(r[0].verify(r[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(r[0]),await this.db.send(r[0]),e.hash=r[0].hash("hex"),e.height=-1,e.cp=c,e}async cpRegister(e,t,r,s){if(i(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:$.cpRegister}]))throw new D(L.errors.TYPE_ERROR,"Invalid CP Register Info.");const n=new w;e||(o=await this.createReceive(r),e=o.getAddress());var o=await this.getKey(e);if(!o)throw new D(L.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");t.pubAddress=e.toString(),t.pubKey=o.getPublicKey("hex"),t.signMethod="secp256k1",t.register=this.master.key.publicKey.toString("hex"),n.cpRegister(e,C.registerFee,t);for(let r=0;r<10;r++){var c=""+t.cid+this.network.stockFix+a.sprintf("%02d",r);c={oper:$.propCreate,pid:c,oid:t.cid,cid:t.cid,gold:C.MINPROPVALUE};n.propCreate(e,c)}if(o=async()=>{r?await this.fund(n,{account:r}):await this.fund(n),await this.sign(n);var s=n.commit();return i(s[0].verify(s[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),await this.db.send(s[0]),t.txid=s[0].txid(),t.addr=e.toString(),s},!s)return o();o()}getSCAddress(e){return e=ee.fromMnemonic(T.fromOptions(C.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var r=await this.ensureCp(e.cid);if(r.cid==this.network.genesisId||"ATHENA"==r.name)throw new D(L.errors.TYPE_ERROR,"Invalid cp name.");var s=await this.getTX(r.current.hash);if(!s)throw new D(L.errors.TYPE_ERROR,"Do not have permission to change this info.");if(s=s.tx,!await this.belongToAccount(t,s.outputs[0].getAddress()))throw new D(L.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:r.cid,name:e.newName,oper:$.cpChange}]))throw new D(L.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=r.name;return e.addr||(e.addr=b.fromString(r.current.address)),r=w.cpChange(s,e),t?await this.fund(r,{allowPreInput:!0,account:t}):await this.fund(r,{allowPreInput:!0}),await this.sign(r),s=r.commit(),await this.db.send(s[0]),i(s[0].verify(s[1],x.flags.STANDARD_VERIFY_FLAGS)),e.txid=s[0].txid(),s}async propExchangeList(e,t,r=!1){var s,n,a,o=new w,c=[];for([s,n,a]of e){var u,h=null,l=0;(h=await this.getTX(s.hash))?(h=h.tx,l=s.index,!h||!h.outputs||h.outputs.length<=l||(r||await this.belongToAccount(t,h.outputs[l].getAddress())?(u=h.outputs[l].getReturnData())&&(o.propExchange(h,l,n),u.index=o.outputs.length-1,u.addr=n.toString(),c.push(u)):this.logger.error("not owned prop:",s.hash,s.index))):this.logger.error("tx not find:",s.hash,a)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),i(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var r=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=r)throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[r].getAddress()))throw new D(L.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[r].getReturnData()))throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new G(e.tx,"invalid","Special props that can not to donate",100);var i=new w;return(e=(i.addInputFromTx(e.tx,r),i.addOutput(x.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[r].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),x.types.NULLDATA),0),await this.sign(i,null,B.NONE|B.ANYONECANPAY),i.commit())).push(t),e}async propReceive(e,t){var r=(e=w.fromTX(e,1)).inputs[0].prevout,i=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new E({value:i.value})),e.outputs.pop();let s=this.getAddress().toString(this.network);t&&(n={cid:i.cid,uid:t},s=(n=await this.tokenCreate(n,t)).data.addr),e.outputs.push(E.fromScript(s,i.value,{oper:$.propExchange,pid:i.pid,cid:i.cid,oid:i.oid,prev:{hash:r.hash,index:r.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,B.ALL,[0]);var n=e.commit();return await this.db.send(n[0]),i.simAddr=s,[n[0],null,i]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,r){let s=null,n=0;var a;return Array.isArray(e)?(s=e[0],n=e[1]):(a=await this.getTX(e.hash))&&(s=a.tx,n=e.index),!s||!s.outputs||s.outputs.length<=n?(this.logger.error("Invalid tx info."),null):await this.belongToAccount(r,s.outputs[n].getAddress())?(a=s.outputs[n].getReturnData())?(e=(new w).propExchange(s,n,t),a.index=e.outputs.length-1,r?await this.fund(e,{allowPreInput:!0,account:r}):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]),i(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(a),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t){if(e=await this.getTX(e),i(e),!(e=e.tx))throw new D(L.errors.TYPE_ERROR,"Invalid hex string.");let r=0;3<=e.outputs.length&&(r=2);var s=(a=e.outputs[r]).getReturnData();if(!s||s.oper!==$.propExchange&&s.oper!==$.propCreate)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new G(block,"invalid","prop found supertoken",100);var n=new w,a=(e=(n.addInputFromTx(e,r),E.fromScript(a.getAddress(),a.value)),n.outputs.push(e),t?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:t}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),n.commit());return await this.db.send(a[0]),i(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),a.push(s),a}async propSale(e,t,r,s){let n=await this.getTX(e);if(!n)throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");if(n.getDepth(this.db.curHeight)<=0)throw new D(L.errors.TYPE_ERROR,"No enough confirmations.");if(!(n=n.tx))throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");n.outputs[0].getReturnType(x.opcodes.OP_RETURN)&&(t=2);var a=n.outputs[t].getReturnData([x.opcodes.OP_PROPEXCHANGE,x.opcodes.OP_PROPCREATE]);if(!a)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.belongToAccount(s,n.outputs[t].getAddress()))throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");if(!(s=await this.getCoin(e,t))||-1===s.height||-2===s.height)throw new D(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new D(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(r<=n.outputs[t].value)throw new D(L.errors.TYPE_ERROR,"Invalid fixed price.");if(a.cid==this.network.genesisId)throw new G(n,"invalid","prop not for sale",100);return e=(s=new w).addInputFromTx(n,t),t={oper:$.propSale,pid:a.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:r,period:this.db.curHeight+C.BLOCK_DAY},a=E.fromScript(x.createScript(Buffer.from(JSON.stringify(t)),x.types.NULLDATA),0),s.outputs.push(a),await this.sign(s,null,B.SINGLE|B.ANYONECANPAY),e=s.commit(),i(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,r){if(!(e=this.db.propList.get(e))||!e.bid||!e.bid.raw)throw new D(L.errors.INVALID_PARAMS,"Invalid Tx Hash.");var i=M.fromRaw(Buffer.from(e.bid.raw,"hex")),s=(await this.createReceive(r)).getAddress(),n=e.gold,a=b.fromString(e.current.address,this.network).getHash();if(t<n)throw new Error("wrong price");if(1<i.outputs.length&&t<i.outputs[1].value)throw new Error("low bid price than before");var o=w.fromTX(i,1);if(!o.outputs[0].getReturnType(F.OP_RETURN))throw new Error("not a sale order");return await this.remove(i.hash("hex")),o.view.addOutput({hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index},new E({value:e.gold})),a=E.fromScript(x.createScript(a),t),o.outputs.push(a),t={oper:$.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index}},a=E.fromScript(s,n,t),o.outputs.push(a),r?await this.fund(o,{allowPreInput:!0,account:r}):await this.fund(o,{allowPreInput:!0}),await this.sign(o,null,B.ALL,[0]),s=o.commit(),e.owned||this.db.client.watchOutpoint((new H).fromOptions(i.inputs[0].prevout)),await this.db.send(s[0]),s}async getTXByAmount(e,t){let r=null;var i;for(i of await this.getCoins(t))if(!(i.height<=0)&&i.value==e){r=i;break}return r&&(t=await this.getTX(r.hash))?[t.tx,r.index,r.height]:[]}async contractCreate(e,t,r,s,n){if(this.db.transactionList.query(e,s)!=W.None)throw new D(L.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new D(L.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,s))throw new D(L.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let a=!1,[o,c,u]=await this.getTXByAmount(t,n);if(!o){a=!0;var h=new w;let e="";e=(n?await this.createReceive(n):this).getAddress(),h.outputs.push(E.fromScript(e,t)),n?await this.fund(h,{allowPreInput:!0,account:n}):await this.fund(h,{allowPreInput:!0}),await this.sign(h),h=h.commit(),i(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=(n?await this.createReceive(n):this).getAddress();var p=await this.getKey(l);e={oper:$.contractCreate,type:e,addr:s,src:t,dst:r,srcact:n,alice:p.getPublicKey("hex"),period:this.db.curHeight+C.TRANSACTION_PERIOD},s=E.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0),h.outputs.push(s),await this.sign(h,null,B.SINGLE|B.ANYONECANPAY),t=h.commit();return a&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=W.CreatedOnMem)throw new D(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=M.fromRaw(Buffer.from(e.raw,"hex"))))throw new D(L.errors.TYPE_ERROR,"Invalid Tx id.");var r=U.parseContract(e);if(!r||r.oper!==$.contractCreate)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");var i=w.fromTX(e,1);if(!i.outputs[0].getReturnType(F.OP_RETURN))throw new Error("not a valid contract");i.view.addOutput({hash:i.inputs[0].prevout.hash,index:i.inputs[0].prevout.index},new E({value:r.src}));let s="";s=(t?await this.createReceive(t):this).getAddress();var n=await this.getKey(s);e={oper:$.contractPromise,prevhash:e.hash("hex"),type:r.type,addr:r.addr,dst:r.dst,srcact:r.srcact,dstact:t,bob:n.getPublicKey("hex"),period:r.period},t=new x([N.fromSymbol("promise"),N.fromData(Buffer.from(JSON.stringify(e))),N.fromSymbol("drop"),N.fromSymbol("greaterthan"),N.fromSymbol("drop"),N.fromSymbol("if"),N.fromData(l.hash160(Buffer.from(e.bob,"hex"))),N.fromSymbol("else"),N.fromData(l.hash160(Buffer.from(r.alice,"hex"))),N.fromSymbol("endif"),N.fromSymbol("checksig")]),i.outputs.push(E.fromScript(t,r.src)),await this.remove(e.prevhash),await this.sign(i,null,B.ALL,[0]),n=i.commit();return await this.db.send(n[0]),e.current={hash:n[0].hash("hex"),index:0},e.raw=n[0].toRaw().toString("hex"),e.transStatus=W.Promised,this.db.transactionList.saveContract(e,!0),n}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=W.Confirmed&&e.transStatus!=W.Expired)throw new D(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=M.fromRaw(Buffer.from(e.raw,"hex"))))throw new D(L.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var r=U.parseContract(e);if(!r||r.oper!==$.contractPromise)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");var s=e.outputs[1].getReturnData();if(!s||s.oper!==$.contractPromise)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");i.strictEqual(r.addr,s.addr),i.strictEqual(r.type,s.type),i.strictEqual(r.dst,s.dst),i.strictEqual(r.period,s.period),i.strictEqual(r.srcact,s.srcact),i.strictEqual(r.dstact,s.dstact);var n=this.db.transactionList.query(r.type,r.addr);if(n!=W.Confirmed&&n!=W.Expired)throw new D(L.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(n==W.Expired&&1!=t||n==W.Confirmed&&2!=t)throw new D(L.errors.TYPE_ERROR,"Invalid Executor.");let a=r.srcact,o=(2==t&&(a=r.dstact),"");o=(a?await this.createReceive(a):this).getAddress();var c=new w,u=(c.addInputFromTx(e,1),{oper:$.contractExecute,type:r.type,addr:r.addr,master:t});u=E.fromScript(x.createScript(Buffer.from(JSON.stringify(u)),x.types.NULLDATA),0),c.outputs.push(u),u=E.fromScript(o,e.outputs[1].value),c.outputs.push(u),e=1==t?await O.fromPublic(Buffer.from(r.ori.alice,"hex")):await O.fromPublic(Buffer.from(s.bob,"hex")),u=await this.getKey(e.getAddress()),await c.signAsync(u,x.hashType.ALL,this.db.workers),t=c.commit();return i(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS,n)),await this.db.send(t[0]),t}async htlcDeal(e,t){var r=await this.getTX(e.hash);let i=null;if(t){if(!(t=await this.getAccount(t)))throw new D(L.errors.TYPE_ERROR,"Invalid Account.");i=t.getReceive().toString()}else i=this.getReceive().toString();t=new w;var s=(new x).pushOp(F.OP_1);e.suggest&&s.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:s}),t.addOutput(i,r.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new E(r.tx.outputs[e.index])),await this.sign(t,null,B.ALL),s=t.commit();return await this.db.send(s[0]),s}async htlcCancel(e,t){let r=null;var i=await this.getTX(e.hash);if(!(r=i?i.tx.outputs[e.index]:r))throw new D(L.errors.TYPE_ERROR,"Invalid Input.");let s=null;if(t){if(!(i=await this.getAccount(t)))throw new D(L.errors.TYPE_ERROR,"Invalid Account.");s=i.getReceive().toString()}else s=this.getReceive().toString();return t=new w,i=(new x).pushOp(F.OP_0),e.suggest&&i.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:i}),e.suggest?t.setSequence(0,2*C.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,C.HTLC_CANCEL_PERIOD,!1),t.addOutput(s,r.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new E(r)),i=await this.getKey(e.master),await t.signAsync(i,x.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,r){var i,s=new w;for(i of e)s.outputs.push(r.create(i));return t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s),e=s.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async addStockAccountSeq(e){i(e&&"object"==typeof e,"Token data should be a object"),i(e.cid,"Token data should has a cid property"),i(e.uid,"Token data should has a uid property");var t=await this.stockAddress(e.cid,e.uid);t=this.db.accountList.getOrCreateStockAccount(e.cid,t.toString());return e.seq=t.seq+1,e}async tokenCreate(e,t="",r){i(e&&"object"==typeof e,"Token data should be a object"),i(e.cid,"Token data should has a cid property"),i(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let s=null;if(r){if(!await this.belongToAccount(t,r))throw new D(L.errors.TYPE_ERROR,`stock.send address error: addr:${r} is not belongs to account:`+t);s=await this.getKey(r)}else s=await this.createReceive(t,a.hashInt(e.cid),this.master);return s.signData(e)}async sign(e,t,r=x.hashType.ALL,i){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,r,this.db.workers,i)}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 r=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{r()}}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,r){var i=await this.writeLock.lock();try{return await this._add(e,t,r)}finally{i()}}async _add(e,t,r){let i,s;this.txdb.start();try{(i=await this.txdb._add(e,t,r))&&(s=await this.syncOutputDepth(i)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return s&&0<s.length&&(this.db.emit("address",this.id,s),this.emit("address",s)),i}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb.resetBalance(),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}}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 r=await this.writeLock.lock();try{return await this._zap(e,t)}finally{r()}}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 i of await this.getCredits(e)){var r=i.coin;i.spent||this.txdb.isConserved(r)||(-1!==r.height&&-2!==r.height||i.own)&&t.push(r)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(e){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(e)).writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(e){e=new d(e);var t=n.fromMagic(e.readU32());return this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),i(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new ie(e).fromRaw(t)}static isWallet(e){return e instanceof ie}async issueCreate(e,t,r){var i=new X(e),s=((s=(i.source.subjectName||(i.source.subjectName=i.erid),O.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,i.sign(s,!0,this.network),i.toOptions(!0));return r?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 caAbolish(e,t,r){var i=O.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),s=(i.witness=!0,await this.db.$parent.chain.db.erList.getEr(e.erid));if(!s)throw new D(L.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(s.source.cid!=e.cid)throw new D(L.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(s.source.uid!=e.uid)throw new D(L.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var n=s.signature;if(s.sign(i,!0,this.network),s.witness!=e.witness||s.signature!=n)throw new D(L.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(s=new J(e)).sign(i),n=s.toOptions(!0),r?this.send({outputs:[{address:e.address,value:1e4}],comment:n},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:n},t),n}async enchanceCp(e,t){var r=((e=new Z(e)).oper="enchanceCp",await this.ensureCp(e.to)),i=await this.ensureCp(e.from);if(!(i=await this.getKey(i.pubAddress)))throw new D(L.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(i),i=e.toOptions(!0),[await this.send({outputs:[{address:r.pubAddress,value:1e4}],comment:i},t),i]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new D(L.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=ie},function(e,t,r){"use strict";
|
|
295
|
+
*/const i=r(0);var s=r(16);const n=r(15),a=r(1),o=r(3),c=r(34),u=r(199),h=r(119).sortWithSeq,l=r(7),p=r(94),d=r(2),f=r(4),m=r(70),g=r(339);r(222);const y=r(110),v=r(73),b=r(12),w=r(60),x=r(17),k=r(223),S=r(124),E=r(26),_=r(159),A=r(340),R=r(65),I=r(28),j=r(27),C=r(6),P=r(311),O=r(39),T=S.Mnemonic,{opcodes:F,hashType:B}=r(21),N=r(167),D=r(77),L=r(78),z=r(143),H=r(46),M=r(19),U=r(43),q=r(53),{NotifyMsg:V,OrderData:K,ContractStatus:W,ContractType:$}=r(5),G=r(37).VerifyError,Y=r(85).stockItem,X=r(157).ErItem,J=r(158).ErAbolishItem,Z=r(237).EnchancementItem,Q=r(31),ee=r(69),te=r(59),re=r(82);class ie extends s{constructor(e,t){super(),i(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 R(1e4),this.accountCache=new R(1e4),this.pathCache=new R(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 A,this.txdb=new g(this),this.account=null,t&&this.fromOptions(t)}fromOptions(e){let t,r,s=e.master;return s?("string"==typeof s&&(s=S.PrivateKey.fromBase58(s,this.network)),i(S.isPrivate(s),"Must create wallet with hd private key.")):(r=new T(e.mnemonic),s=S.fromMnemonic(r,this.network)),i(s.network===this.network,"Network mismatch for master key."),this.master.fromKey(s,r),null!=e.wid&&(i(a.isU32(e.wid)),this.wid=e.wid),e.id&&(i(v.isName(e.id),"Bad wallet ID."),t=e.id),null!=e.initialized&&(i("boolean"==typeof e.initialized),this.initialized=e.initialized),null!=e.watchOnly&&(i("boolean"==typeof e.watchOnly),this.watchOnly=e.watchOnly),null!=e.accountDepth&&(i(a.isU32(e.accountDepth)),this.accountDepth=e.accountDepth),e.token&&(i(Buffer.isBuffer(e.token)),i(32===e.token.length),this.token=e.token),t=t||this.getID(),this.id=t,this}static fromOptions(e,t){return new ie(e).fromOptions(t)}async init(e){var t=e.passphrase;i(!this.initialized),this.initialized=!0,t&&await this.master.encrypt(t),e=await this._createAccount(e,t);i(e),this.account=e,this.logger.info("Wallet initialized (%s).",this.id),await this.txdb.open()}async open(){i(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,r){var i={alliancename:e,nodeid:t};return e?(i.alliancePrivateKey=l.hash256(Buffer.concat([Buffer.from(e),this.master.key.privateKey])),r?(i.prv=Buffer.alloc(0),i.pub=Buffer.from(r,"hex"),i.awardAddress=b.fromWitnessPubkeyhash(l.hash160(i.pub),this.network.type).toString(this.network.type),i.mnemonic=new T):(r=l.hash256(Buffer.concat([Buffer.from(e+"-"+t),this.master.key.privateKey])),i.mnemonic=new T({entropy:r,language:this.master.mnemonic.language,passphrase:this.master.mnemonic.passphrase}),i.prv=l.hash256(Buffer.from(i.mnemonic.toSeed().toString("hex"))),i.pub=I.publicKeyCreate(i.prv,!0),e=A.fromKey(S.fromMnemonic(i.mnemonic),this.network.type).key.deriveAccount(44,0).derive(9).derive(1),i.awardAddress=b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network.type).toString(this.network.type))):(i.mnemonic=T.fromOptions(this.master.mnemonic),i.prv=l.hash256(Buffer.from(i.mnemonic.toSeed().toString("hex"))),i.pub=I.publicKeyCreate(i.prv,!0),i.awardAddress=b.fromWitnessPubkeyhash(l.hash160(i.pub),this.network.type).toString(this.network.type)),i.address=b.fromWitnessPubkeyhash(l.hash160(i.pub),this.network.type).toString(),i}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 r=await this.writeLock.lock();try{return await this._addSharedKey(e,t)}finally{r()}}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 r;this.start();try{r=await e.addSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),r}async removeSharedKey(e,t){var r=await this.writeLock.lock();try{return await this._removeSharedKey(e,t)}finally{r()}}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 r;this.start();try{r=await e.removeSharedKey(t)}catch(e){throw this.drop(),e}return await this.commit(),r}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 r=await this.writeLock.lock();try{return await this._renameAccount(e,t)}finally{r()}}async _renameAccount(e,t){if(!v.isName(t))throw new Error("Bad account name.");var r=await this.getAccount(e);if(!r)throw new Error("Account not found.");if(0===r.accountIndex)throw new Error("Cannot rename default account.");if(await this.hasAccount(t))throw new Error("Account name not available.");e=r.name,this.start(),this.db.renameAccount(r,t),await this.commit(),this.indexCache.remove(e),e=this.pathCache.values();for(const i of e)i.account===r.accountIndex&&(i.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(){i(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 r=await this.writeLock.lock();try{return await this._createAccount(e,t)}finally{r()}}async _createAccount(e,t){let r,s,n=e.name,o=(n=n||this.accountDepth.toString(10),0);if(0!=this.accountDepth&&(o=a.hashInt(n)),await this.hasAccountIndex(o))throw new Error("Account Index Conflict.");if(await this.hasAccount(n))throw new Error("Account already exists.");if(await this.unlock(t),this.watchOnly&&e.accountKey){if("string"==typeof(r=e.accountKey)&&(r=S.PublicKey.fromBase58(r,this.network)),!S.isPublic(r))throw new Error("Must add HD public keys to watch only wallet.");i(r.network===this.network,"Network mismatch for watch only key.")}else i(this.master.key),r=(r=this.master.key.deriveAccount(44,o)).toPublic();t={wid:this.wid,id:this.id,name:0===this.accountDepth?"default":n,witness:e.witness,watchOnly:this.watchOnly,accountKey:r,accountIndex:o,type:e.type,m:e.m,n:e.n,keys:e.keys},this.start();try{(s=_.fromOptions(this.db,t)).wallet=this,await s.init()}catch(e){throw this.drop(),e}return this.logger.info("Created account %s/%s/%d.",s.id,s.name,s.accountIndex),this.accountDepth++,this.save(),await this.commit(),s}async ensureAccount(e,t){var r=e.name;return(r=await this.getAccount(r))||this.createAccount(e,t)}getAccounts(){return this.db.getAccounts(this.wid)}getAddressHashes(e){return null!=e?this.getAccountHashes(e):this.db.getWalletHashes(this.wid)}async getAccountHashes(e){return e=await this.ensureIndex(e,!0),this.db.getAccountHashes(this.wid,e)}async getAccount(e){if(this.account&&(null==e||"default"===e||"number"==typeof e&&0===e||"string"==typeof e&&0===e.length))return this.account;if(-1===(e=await this.getAccountIndex(e)))return null;var t=await this.readLock.lock(e);try{return await this._getAccount(e)}finally{t()}}async _getAccount(e){var t=this.accountCache.get(e);return t||((t=await this.db.getAccount(this.wid,e))?(t.wallet=this,t.wid=this.wid,t.id=this.id,t.watchOnly=this.watchOnly,await t.open(),this.accountCache.set(e,t),t):null)}async getAccountIndex(e){var t;return null==e?-1:"number"==typeof e?e:null!=(t=this.indexCache.get(e))?t:-1===(t=await this.db.getAccountIndex(this.wid,e))?-1:(this.indexCache.set(e,t),t)}async getAccountName(e){var t;return"string"==typeof e?e:(t=this.accountCache.get(e))?t.name:this.db.getAccountName(this.wid,e)}async hasAccount(e){return-1!==(e=await this.getAccountIndex(e))&&(!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e))}async hasAccountIndex(e){return!!this.accountCache.has(e)||this.db.hasAccount(this.wid,e)}createReceive(e,t=0,r=null){return this.createKey(e,0,t,r)}createChange(e){return this.createKey(e,1)}createNested(e){return this.createKey(e,2)}async createKey(e,t,r=0,i=null){var s=await this.writeLock.lock();try{return await this._createKey(e,t,r,i)}finally{s()}}async _createKey(e,t,r=0,i=null){if(null==t&&(t=e,e=null),!(e=await this.getAccount(e=e||0)))throw new Error("Account not found.");let s;this.start();try{s=await e.createKey(t,r,i)}catch(e){throw this.drop(),e}return await this.commit(),s}async deriveKey(e,t,r,i=null){let s=null;var n=await this.writeLock.lock();try{this.start(),s=await this._deriveKey(e,t,r,i),await this.commit()}catch(e){throw this.drop(),e}finally{n()}return s}async _deriveKey(e,t,r=0,i=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,r,i),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),i(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),i(e.name),this.pathCache.set(e.hash,e),t.push(e);return t}async getAccountPaths(e){var t=await this.ensureIndex(e,!0),r=await this.getAccountHashes(t),s=await this.getAccountName(e),n=(i(s),[]);for(const e of r){var a=await this.readPath(e);i(a),i(a.account===t),a.name=s,this.pathCache.set(a.hash,a),n.push(a)}return n}async importKey(e,t,r){var i=await this.writeLock.lock();try{return await this._importKey(e,t,r)}finally{i()}}async _importKey(e,t,r){if(e&&"object"==typeof e&&(r=t,t=e,e=null),null==e&&(e=0),i(t.network===this.network,"Network mismatch for key."),this.watchOnly){if(t.privateKey)throw new Error("Cannot import privkey into watch-only wallet.")}else if(!t.privateKey)throw new Error("Cannot import pubkey into non watch-only wallet.");var s=t.getHash("hex");if(await this.getPath(s))throw new Error("Key already exists.");if(!(s=await this.getAccount(e)))throw new Error("Account not found.");if(s.type!==_.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");await this.unlock(r),e=k.fromRing(s,t).toPath(),this.master.encrypted&&(e.data=this.master.encipher(e.data,e.hash),i(e.data),e.encrypted=!0),this.start();try{await s.savePath(e)}catch(e){throw this.drop(),e}await this.commit()}async importAddress(e,t){var r=await this.writeLock.lock();try{return await this._importAddress(e,t)}finally{r()}}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!==_.types.PUBKEYHASH)throw new Error("Cannot import into non-pkh account.");t=y.fromAddress(e,t),this.start();try{await e.savePath(t)}catch(e){throw this.drop(),e}await this.commit()}async fund(e,t){var r=await this.writeLock.lock();try{return await this._fund(e,t)}finally{r()}}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 r;if(null!=t.account){if(!(r=await this.getAccount(t.account)))throw new Error("Account not found.")}else r=this.account;if(!r.initialized)throw new Error("Account is not initialized.");let s,n=t.rate;return null==n&&(n=await this.db.estimateFee(t.blocks)),s=t.smart?await this.getSmartCoins(r.name):(s=await this.getCoins(r.name),this.txdb.filterConserved(s)),await e.fund(s,{allowPreInput:t.allowPreInput,noChange:t.noChange,selection:t.selection,round:t.round,depth:t.depth,hardFee:t.hardFee,subtractFee:t.subtractFee,subtractIndex:t.subtractIndex,changeAddress:r.change.getAddress(),height:this.db.curHeight,rate:n,maxFee:t.maxFee,estimate:e=>this.estimateSize(e),network:this.network}),!t.allowInfiniteFee&&t.noChange&&i(e.getFee()<=P.MAX_FEE,"TX exceeds MAX_FEE."),s}async getAccountByAddress(e){return e=b.getHash(e,"hex"),(e=await this.getPath(e))?this.getAccount(e.account):null}async estimateSize(e){var t=C.WITNESS_SCALE_FACTOR,r=b.fromScript(e);if(!r)return-1;var i=await this.getAccountByAddress(r);if(!i)return-1;let s=0;if(e.isScripthash()&&i.witness)switch(i.type){case _.types.PUBKEYHASH:s=4*(s+23);break;case _.types.MULTISIG:s=4*(s+35)}switch(i.type){case _.types.PUBKEYHASH:s=s+74+34;break;case _.types.MULTISIG:s=(s=(s=(s=(s+=1)+74*i.m)+3+1)+34*i.n)+1+1}return i.witness?s=((s+=1)+t-1)/t|0:s+=o.sizeVarint(s),s}async createTX(e){var t=e.outputs,r=new w;i(Array.isArray(t),"Outputs must be an array."),i(0<t.length,"No outputs available."),e.comment&&("object"==typeof e.comment&&(e.comment=JSON.stringify(e.comment)),r.outputs.push(E.fromScript(x.createScript(Buffer.from(e.comment),x.types.NULLDATA),0)));for(const e of t){var s=new E(e),n=s.getAddress();if(s.isDust())throw new Error("Output is dust.");if(0<s.value){if(!n)throw new Error("Cannot send to unknown address.");if(n.isNull())throw new Error("Cannot send to null address.")}r.outputs.push(s)}let a=null;if(e.inputs)for(const t of e.inputs){var o=await this.getTX(t.hash);o&&(o=q.fromTX(o.tx,t.index,-1,0))&&(a=o.getAddress(),e.allowPreInput=!0,r.addCoin(o))}else await this.fund(r,e);if(a&&((t=new E).value=r.getFee()-P.MIN_FEE,t.script.fromAddress(a),r.outputs.push(t),r.changeIndex=r.outputs.length-1),!1!==e.sort&&r.sortMembers(),null!=e.locktime&&r.setLocktime(e.locktime),i(r.isSane(),"TX failed sanity check."),i(r.verifyInputs(this.db.curHeight+1),"TX failed context check."),0===await this.template(r))throw new Error("Templating failed.");return r}async send(e,t){var r=await this.sendLock.lock();try{return await this._send(e,t)}finally{r()}}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 r=e.toTX();if(r.getSigopsCost(e.view)>j.MAX_TX_SIGOPS_COST)throw new Error("TX exceeds policy sigops.");if(r.getWeight()>j.MAX_TX_WEIGHT)throw new Error("TX exceeds policy weight.");return t.sendafter||(this.logger.debug("Sending wallet tx (%s): %s",this.id,r.txid()),await this.db.addTX(r),await this.db.send(r)),r}async resend(){var e=await this.getPending(),t=(0<e.length&&this.logger.info("Rebroadcasting %d transactions.",e.length),[]);for(const r of e)t.push(r.tx);for(const e of await h(t,this.db))await this.db.send(e);return t}async deriveInputs(e){i(e.mutable);var t=[];for(const i of await this.getInputPaths(e)){var r=await this.getAccount(i.account);r&&(r=r.derivePath(i,this.master))&&t.push(r)}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(!te.unsupported){var t=await this.db.getTip(),r=a.date();let o=1,c="",u=[a.fmt("# Wallet Dump created by %s %s",re.protocol,re.version),a.fmt("# * Created on %s",r),a.fmt("# * Best block at time of backup was %d (%s).",t.height,a.revHex(t.hash)),a.fmt("# * File: %s",e.file),""];t=a.fmt("W %s wid= %s",this.toRaw().toString("base64"),this.wid),u.push(t),t=await this.getAccounts();for(const e of t){var i=await this.getAccount(e);i=a.fmt("C %s name= %s index= %d",i.toRaw().toString("base64"),i.name,i.accountIndex);u.push(i)}for(const t of await this.getAddressHashes()){var s,n=await this.getPrivateKey(t);n&&(s=n.getAddress("string"),n=a.fmt("A %s %s label= account= %s branch= %s index= %s addr= %s",n.toSecret(),r,n.account,n.branch,n.index,s),u.push(n),1e5<u.length)&&(c=u.join("\n"),await te.writeFile(`${e.file}-${o++}.txt`,c,"utf8"),u=[])}u.push(""),u.push("# End of dump"),u.push(""),c=u.join("\n"),await te.writeFile(`${e.file}-${o++}.txt`,c,"utf8")}}async getPrivateKey(e,t){if(e=b.getHash(e,"hex"),!(e=await this.getPath(e)))return null;var r=await this.getAccount(e.account);return r?(await this.unlock(t),(t=r.derivePath(e,this.master)).privateKey?t:null):null}async getInputPaths(e){if(i(e.mutable),!e.hasCoins())throw new Error("Not all coins available.");var t=[];for(const i of e.getInputHashes("hex")){var r=await this.getPath(i);r&&t.push(r)}return t}async getOutputPaths(e){var t=[];for(const i of e.getOutputHashes("hex")){var r=await this.getPath(i);r&&t.push(r)}return t}async setLookahead(e,t){var r=await this.writeLock.lock();try{return this._setLookahead(e,t)}finally{r()}}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 i of e.outputs){var r=i.path;r&&-1!==r.index&&(t.has(r.account)||t.set(r.account,[]),t.get(r.account).push(r))}var s,n,a=[];for([s,n]of t){let e=-1,t=-1,r=-1;for(const i of n)switch(i.branch){case 0:i.index>e&&(e=i.index);break;case 1:i.index>t&&(t=i.index);break;case 2:i.index>r&&(r=i.index)}e+=2,t+=2,r+=2;var o=await this.getAccount(s);(o=(i(o),await o.syncDepth(e,t,r)))&&a.push(o)}return a}async getRedeem(e){"string"==typeof e&&(e=Buffer.from(e,"hex"));var t=await this.getKey(e.toString("hex"));return t?t.getRedeem(e):null}async template(e){var t=await this.deriveInputs(e);return e.sign(t)}async getOrderList(e,t){let r=[];var i=new Q;(await this.getHistory(t||"default")).reduce((e,t)=>{var{tx:t,hash:i,height:s}=t;if(t.outputs[0].getReturnType(F.OP_RETURN))try{var n,a=JSON.parse(t.outputs[0].script.code[1].toString());a&&a.oper==$.payOrder&&((n=K.fromJson(a)).hash=i,n.height=s,e.set(""+n.cid+n.sn,n),r.push(n.cid))}catch(e){}return e},i),t=i.query(e);return await this.db.flushCP(r),t.list.map(e=>{e.cp=this.db.cpList.getItem(e.cid)}),t}async propCreate(e,t){var r,s=new w;for(r of e){var n=await this.ensureCp(r.cid,!0);!n||r.cid==this.network.genesisId||(r.gold=(0|r.gold)>>>0,r.gold<C.MINPROPVALUE)||(r.pid||(r.pid=z()),s.propCreate(n.current.address,r),r.index=s.outputs.length-1)}if(0<s.outputs.length){t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s);var a,o=s.commit();for(a of(await this.db.addTX(o[0]),await this.db.send(o[0]),i(o[0].verify(o[1],x.flags.STANDARD_VERIFY_FLAGS)),e))a.hash=o[0].hash("hex"),a.txid=o[0].txid();return o}return[]}async stockAddress(e,t){return await this.ensureAccount({name:t,witness:!0}),(await this.createReceive(t,a.hashInt(e),this.master)).getAddress()}async stockOffer(e,t,r,s){i(!!e),i(!!t),i(!!r),t=(0|t)>>>0,r=(0|r)>>>0;var n=await this.ensureCp(e),a=await this.getKey(n.current.address);if(i(!!a),s&&s!==a.name)throw new D(L.errors.TYPE_ERROR,"illegal account");return a=a.signData({cid:e,type:Y.RecordType.Offer,sum:t,price:r}),(e=new w).outputs.push(E.fromScript(a.data.addr,.05*t*r)),t=new V($.stock,z(),this.db.curHeight,a),r=E.fromScript(x.createScript(t.toRaw(),x.types.NULLDATA),0),e.outputs.push(r),s?await this.fund(e,{account:s}):await this.fund(e),e.outputs.shift(),await this.sign(e),a=e.commit(),i(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(a[0]),await this.db.send(a[0]),t.hash=a[0].hash("hex"),t.height=-1,t.cp=n,t}async stockPurchase(e,t,r){if(i(!!e),i(!!t),(t=(0|t)>>>0)<C.STOCK_TRADE_SINGLE||t>C.STOCK_MAX_TRADE_SINGLE)throw new D(L.errors.TYPE_ERROR,"Invalid Stock Amount.");var s=await this.ensureCp(e),n=(e={type:Y.RecordType.Purchase,cid:e,uid:r,seq:0,to:s.current.address,sum:t},e=(await this.addStockAccountSeq(e),await this.tokenCreate(e,r)),new w),a=(e=new V($.stock,z(),this.db.curHeight,e),E.fromScript(x.createScript(e.toRaw(),x.types.NULLDATA),0));n.outputs.push(a),n.outputs.push(E.fromScript(s.current.address,t*s.stock.price)),r?await this.fund(n,{account:r}):await this.fund(n),await this.sign(n),a=n.commit();return i(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(a[0]),await this.db.send(a[0]),e.hash=a[0].hash("hex"),e.height=-1,e.cp=s,e}async stockPurchaseTo(e,t,r,s){if(i(!!e),i(!!t),(t=(0|t)>>>0)<C.STOCK_TRADE_SINGLE||t>C.STOCK_MAX_TRADE_SINGLE)throw new D(L.errors.TYPE_ERROR,"Invalid Stock Amount.");var n=await this.ensureCp(e),a=(e={type:Y.RecordType.Purchase,cid:e,uid:r,seq:0,to:n.current.address,sum:t},e=(await this.addStockAccountSeq(e),await this.tokenCreate(e,r)),r=new w,e=new V($.stock,z(),this.db.curHeight,e),E.fromScript(x.createScript(e.toRaw(),x.types.NULLDATA),0));r.outputs.push(a),r.outputs.push(E.fromScript(n.current.address,t*n.stock.price)),s?await this.fund(r,{account:s}):await this.fund(r),await this.sign(r),a=r.commit();return i(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(a[0]),await this.db.send(a[0]),e.hash=a[0].hash("hex"),e.height=-1,e.cp=n,e}async stockSend(e,t,r,s,n){i(!!e),i(!!t),t=(0|t)>>>0;var a=await this.ensureCp(e,!0);return a?(e={type:Y.RecordType.Send,cid:e,uid:s,seq:0,sum:t,to:r},await this.addStockAccountSeq(e),t=await this.tokenCreate(e,s,n),r=new w,e=new V($.stock,z(),this.db.curHeight,t),n=E.fromScript(x.createScript(e.toRaw(),x.types.NULLDATA),0),r.outputs.push(n),s?await this.fund(r,{account:s}):await this.fund(r),await this.sign(r),t=r.commit(),i(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(t[0]),await this.db.send(t[0]),e.hash=t[0].hash("hex"),e.height=-1,e.cp=a,e):null}async stockBid(e,t,r,s,n){i(!!e),i(!!t),i(!!r),t=(0|t)>>>0,r=(0|r)>>>0;var a=await this.ensureCp(e,!0);return a?(e={type:Y.RecordType.Bid,cid:e,uid:s,seq:0,sum:t,price:r},await this.addStockAccountSeq(e),e=await this.tokenCreate(e,s,n),(n=new w).outputs.push(E.fromScript(e.data.addr,.05*t*r)),t=new V($.stock,z(),this.db.curHeight,e),r=E.fromScript(x.createScript(t.toRaw(),x.types.NULLDATA),0),n.outputs.push(r),s?await this.fund(n,{account:s}):await this.fund(n),n.outputs.shift(),await this.sign(n),e=n.commit(),i(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(e[0]),await this.db.send(e[0]),t.hash=e[0].hash("hex"),t.height=-1,t.cp=a,t):null}async stockAuction(e,t,r,s,n,a){i(!!e),i(!!t),i(!!r);var o=await this.ensureCp(e,!0);if(!o)return null;r=(0|r)>>>0;e={type:Y.RecordType.Auction,cid:e,to:t,uid:n,seq:0,sum:r,price:s},await this.addStockAccountSeq(e),e=await this.tokenCreate(e,n,a),a=new w,e=new V($.stock,z(),this.db.curHeight,e);var c=E.fromScript(x.createScript(e.toRaw(),x.types.NULLDATA),0);a.outputs.push(c),a.outputs.push(E.fromScript(t,r*s)),n?await this.fund(a,{account:n}):await this.fund(a),await this.sign(a),c=a.commit();return i(c[0].verify(c[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.verifyClsTx(c[0]),await this.db.send(c[0]),e.hash=c[0].hash("hex"),e.height=-1,e.cp=o,e}async sendSecret(e,t,r){let i=this.db.$contacts.get(e);if(!i||!i.sender){var s=(await this.createReceive(r)).getAddress("string");if(e==s)throw new D(L.errors.TYPE_ERROR,"Forbid Sending to Self Address.");i=await this.db.ensureContact({contact:e,messenger:s,wallet:this,account:r})}if(i)return i.send(t);throw new D(L.errors.TYPE_ERROR,"Invalid Address.")}async commNotify(e){i(!!e),i(!!e.dst),i(!!e.content);var t=new w,r=e.src||this.getReceive().toString(),s=(r=new V($.notify,z(),this.db.curHeight,{src:r,content:e.content}),E.fromScript(x.createScript(r.toRaw(),x.types.NULLDATA),0));t.outputs.push(s),s={address:e.dst,locktime:C.BLOCK_DAY,locktype:"csb",value:.1*C.COIN},t.outputs.push(new E(s)),e.account?await this.fund(t,{account:e.account,noChange:!0,allowInfiniteFee:!0}):await this.fund(t,{noChange:!0,allowInfiniteFee:!0}),await this.sign(t),s=t.commit();return i(s[0].verify(s[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),this.logger.debug("Sending tx on wallet(%s): %s",this.id,s[0].txid()),await this.db.send(s[0]),r.hash=s[0].hash("hex"),r.height=-1,r}async payOrder(e,t,r,s,n){i(!!e),i(!!t),i(!!r),i(!!s);var o=(await this.tokenCreate({cid:e,uid:t},n)).data.addr,c=(r=a.sprintf("%0-36s",r),await this.getOrderList([["cid",e],["sn",r]],n));if(0<c.list.length)return c.list[0];if((s=(0|s)>>>0)<C.MINPROPVALUE)return null;if(!(c=await this.ensureCp(e,!0)))return null;e=new K(e,t,r,s,o,"");var u=new w;t=E.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0);for(u.outputs.push(t),u.outputs.push(E.fromScript(c.current.address,s)),n?await this.fund(u,{account:n}):await this.fund(u);2<u.outputs.length;)u.outputs.pop();return await this.sign(u,null,B.ZERO|B.ANYONECANPAY),r=u.commit(),i(r[0].verify(r[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(r[0]),await this.db.send(r[0]),e.hash=r[0].hash("hex"),e.height=-1,e.cp=c,e}async cpRegister(e,t,r,s){if(i(!!t&&"object"==typeof t),!await this.db.client.execute("canExecute",[{confirm:!1,cid:t.cid,name:t.name,oper:$.cpRegister}]))throw new D(L.errors.TYPE_ERROR,"Invalid CP Register Info.");const n=new w;e||(o=await this.createReceive(r),e=o.getAddress());var o=await this.getKey(e);if(!o)throw new D(L.errors.TYPE_ERROR,"Invalid CP Register Address, Not along to this wallet.");t.pubAddress=e.toString(),t.pubKey=o.getPublicKey("hex"),t.signMethod="secp256k1",o=await this.createAllianceInfo(),t.register=o.pub.toString("hex"),n.cpRegister(e,C.registerFee,t);for(let r=0;r<10;r++){var c=""+t.cid+this.network.stockFix+a.sprintf("%02d",r);c={oper:$.propCreate,pid:c,oid:t.cid,cid:t.cid,gold:C.MINPROPVALUE};n.propCreate(e,c)}if(o=async()=>{r?await this.fund(n,{account:r}):await this.fund(n),await this.sign(n);var s=n.commit();return i(s[0].verify(s[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.addTX(s[0]),await this.db.send(s[0]),t.txid=s[0].txid(),t.addr=e.toString(),s},!s)return o();o()}getSCAddress(e){return e=ee.fromMnemonic(T.fromOptions(C.SmartContractMnemonic),this.network).deriveAccount(44,e).derive(9).derive(1),b.fromWitnessPubkeyhash(l.hash160(e.publicKey),this.network)}async cpChange(e,t){var r=await this.ensureCp(e.cid);if(r.cid==this.network.genesisId||"ATHENA"==r.name)throw new D(L.errors.TYPE_ERROR,"Invalid cp name.");var s=await this.getTX(r.current.hash);if(!s)throw new D(L.errors.TYPE_ERROR,"Do not have permission to change this info.");if(s=s.tx,!await this.belongToAccount(t,s.outputs[0].getAddress()))throw new D(L.errors.TYPE_ERROR,"Invalid account info.");if(e.newName){if(!await this.db.client.execute("canExecute",[{confirm:!1,cid:r.cid,name:e.newName,oper:$.cpChange}]))throw new D(L.errors.TYPE_ERROR,"Invalid CP Change Info.")}else e.newName=r.name;return e.addr||(e.addr=b.fromString(r.current.address)),r=w.cpChange(s,e),t?await this.fund(r,{allowPreInput:!0,account:t}):await this.fund(r,{allowPreInput:!0}),await this.sign(r),s=r.commit(),await this.db.send(s[0]),i(s[0].verify(s[1],x.flags.STANDARD_VERIFY_FLAGS)),e.txid=s[0].txid(),s}async propExchangeList(e,t,r=!1){var s,n,a,o=new w,c=[];for([s,n,a]of e){var u,h=null,l=0;(h=await this.getTX(s.hash))?(h=h.tx,l=s.index,!h||!h.outputs||h.outputs.length<=l||(r||await this.belongToAccount(t,h.outputs[l].getAddress())?(u=h.outputs[l].getReturnData())&&(o.propExchange(h,l,n),u.index=o.outputs.length-1,u.addr=n.toString(),c.push(u)):this.logger.error("not owned prop:",s.hash,s.index))):this.logger.error("tx not find:",s.hash,a)}return t?await this.fund(o,{allowPreInput:!0,account:t}):await this.fund(o,{allowPreInput:!0}),await this.sign(o),e=o.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),i(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),e.push(c),e}async propDonate(e,t){var r=e.index;if(!(e=await this.getTX(e.hash))||!e.tx||!e.tx.outputs||e.tx.outputs.length<=r)throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");if(!await this.belongToAccount(t,e.tx.outputs[r].getAddress()))throw new D(L.errors.TYPE_ERROR,"Props that do not belong to you.");if(!(t=e.tx.outputs[r].getReturnData()))throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");if(t.cid&&t.cid==this.network.genesisId)throw new G(e.tx,"invalid","Special props that can not to donate",100);var i=new w;return(e=(i.addInputFromTx(e.tx,r),i.addOutput(x.createScript(Buffer.from(JSON.stringify({value:e.tx.outputs[r].value,cid:t.cid,pid:t.pid,oid:t.oid,gaddr:this.getAddress().toString(this.network)})),x.types.NULLDATA),0),await this.sign(i,null,B.NONE|B.ANYONECANPAY),i.commit())).push(t),e}async propReceive(e,t){var r=(e=w.fromTX(e,1)).inputs[0].prevout,i=e.outputs[0].getReturnData();e.view.addOutput({hash:e.inputs[0].prevout.hash,index:e.inputs[0].prevout.index},new E({value:i.value})),e.outputs.pop();let s=this.getAddress().toString(this.network);t&&(n={cid:i.cid,uid:t},s=(n=await this.tokenCreate(n,t)).data.addr),e.outputs.push(E.fromScript(s,i.value,{oper:$.propExchange,pid:i.pid,cid:i.cid,oid:i.oid,prev:{hash:r.hash,index:r.index}})),t?await this.fund(e,{allowPreInput:!0,account:t}):await this.fund(e,{allowPreInput:!0}),await this.sign(e,null,B.ALL,[0]);var n=e.commit();return await this.db.send(n[0]),i.simAddr=s,[n[0],null,i]}async belongToAccount(e,t){return!!t&&!(!(t=await this.getAccountByAddress(t))||e&&t.name!==e)}async propExchange(e,t,r){let s=null,n=0;var a;return Array.isArray(e)?(s=e[0],n=e[1]):(a=await this.getTX(e.hash))&&(s=a.tx,n=e.index),!s||!s.outputs||s.outputs.length<=n?(this.logger.error("Invalid tx info."),null):await this.belongToAccount(r,s.outputs[n].getAddress())?(a=s.outputs[n].getReturnData())?(e=(new w).propExchange(s,n,t),a.index=e.outputs.length-1,r?await this.fund(e,{allowPreInput:!0,account:r}):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]),i(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS)),t.push(a),t):(this.logger.error("Invalid tx info."),null):(this.logger.error("Invalid user."),null)}async propFound(e,t){if(e=await this.getTX(e),i(e),!(e=e.tx))throw new D(L.errors.TYPE_ERROR,"Invalid hex string.");let r=0;3<=e.outputs.length&&(r=2);var s=(a=e.outputs[r]).getReturnData();if(!s||s.oper!==$.propExchange&&s.oper!==$.propCreate)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");if(s.cid==this.network.genesisId)throw new G(block,"invalid","prop found supertoken",100);var n=new w,a=(e=(n.addInputFromTx(e,r),E.fromScript(a.getAddress(),a.value)),n.outputs.push(e),t?await this.fund(n,{allowPreInput:!0,subtractFee:!0,account:t}):await this.fund(n,{allowPreInput:!0,subtractFee:!0}),await this.sign(n),n.commit());return await this.db.send(a[0]),i(a[0].verify(a[1],x.flags.STANDARD_VERIFY_FLAGS)),a.push(s),a}async propSale(e,t,r,s){let n=await this.getTX(e);if(!n)throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");if(n.getDepth(this.db.curHeight)<=0)throw new D(L.errors.TYPE_ERROR,"No enough confirmations.");if(!(n=n.tx))throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");n.outputs[0].getReturnType(x.opcodes.OP_RETURN)&&(t=2);var a=n.outputs[t].getReturnData([x.opcodes.OP_PROPEXCHANGE,x.opcodes.OP_PROPCREATE]);if(!a)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");if(!await this.belongToAccount(s,n.outputs[t].getAddress()))throw new D(L.errors.TYPE_ERROR,"Invalid tx info.");if(!(s=await this.getCoin(e,t))||-1===s.height||-2===s.height)throw new D(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(await this.txdb.isSpent(e,t))throw new D(L.errors.WALLET_INSUFFICIENT_FUNDS,"Invalid coin.");if(r<=n.outputs[t].value)throw new D(L.errors.TYPE_ERROR,"Invalid fixed price.");if(a.cid==this.network.genesisId)throw new G(n,"invalid","prop not for sale",100);return e=(s=new w).addInputFromTx(n,t),t={oper:$.propSale,pid:a.pid,prev:{hash:e.prevout.hash,index:e.prevout.index},fixed:r,period:this.db.curHeight+C.BLOCK_DAY},a=E.fromScript(x.createScript(Buffer.from(JSON.stringify(t)),x.types.NULLDATA),0),s.outputs.push(a),await this.sign(s,null,B.SINGLE|B.ANYONECANPAY),e=s.commit(),i(e[0].verify(e[1],x.flags.STANDARD_VERIFY_FLAGS)),await this.db.send(e[0]),e}async propBuy(e,t,r){if(!(e=this.db.propList.get(e))||!e.bid||!e.bid.raw)throw new D(L.errors.INVALID_PARAMS,"Invalid Tx Hash.");var i=M.fromRaw(Buffer.from(e.bid.raw,"hex")),s=(await this.createReceive(r)).getAddress(),n=e.gold,a=b.fromString(e.current.address,this.network).getHash();if(t<n)throw new Error("wrong price");if(1<i.outputs.length&&t<i.outputs[1].value)throw new Error("low bid price than before");var o=w.fromTX(i,1);if(!o.outputs[0].getReturnType(F.OP_RETURN))throw new Error("not a sale order");return await this.remove(i.hash("hex")),o.view.addOutput({hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index},new E({value:e.gold})),a=E.fromScript(x.createScript(a),t),o.outputs.push(a),t={oper:$.propExchange,pid:e.pid,cid:e.cid,oid:e.oid,prev:{hash:o.inputs[0].prevout.hash,index:o.inputs[0].prevout.index}},a=E.fromScript(s,n,t),o.outputs.push(a),r?await this.fund(o,{allowPreInput:!0,account:r}):await this.fund(o,{allowPreInput:!0}),await this.sign(o,null,B.ALL,[0]),s=o.commit(),e.owned||this.db.client.watchOutpoint((new H).fromOptions(i.inputs[0].prevout)),await this.db.send(s[0]),s}async getTXByAmount(e,t){let r=null;var i;for(i of await this.getCoins(t))if(!(i.height<=0)&&i.value==e){r=i;break}return r&&(t=await this.getTX(r.hash))?[t.tx,r.index,r.height]:[]}async contractCreate(e,t,r,s,n){if(this.db.transactionList.query(e,s)!=W.None)throw new D(L.errors.TYPE_ERROR,"Contract with the same address finded.");if(0!=parseInt(t%1e3,10))throw new D(L.errors.TYPE_ERROR,"Contract source should an integer multiple of 1000.");if(!await U.checkSum(this.network,e,s))throw new D(L.errors.TYPE_ERROR,"Create contract with an invalid Address or a Address with old transations.");let a=!1,[o,c,u]=await this.getTXByAmount(t,n);if(!o){a=!0;var h=new w;let e="";e=(n?await this.createReceive(n):this).getAddress(),h.outputs.push(E.fromScript(e,t)),n?await this.fund(h,{allowPreInput:!0,account:n}):await this.fund(h,{allowPreInput:!0}),await this.sign(h),h=h.commit(),i(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=(n?await this.createReceive(n):this).getAddress();var p=await this.getKey(l);e={oper:$.contractCreate,type:e,addr:s,src:t,dst:r,srcact:n,alice:p.getPublicKey("hex"),period:this.db.curHeight+C.TRANSACTION_PERIOD},s=E.fromScript(x.createScript(Buffer.from(JSON.stringify(e)),x.types.NULLDATA),0),h.outputs.push(s),await this.sign(h,null,B.SINGLE|B.ANYONECANPAY),t=h.commit();return a&&await this.db.send(o),await this.db.send(t[0]),t}async contractPromise(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=W.CreatedOnMem)throw new D(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=M.fromRaw(Buffer.from(e.raw,"hex"))))throw new D(L.errors.TYPE_ERROR,"Invalid Tx id.");var r=U.parseContract(e);if(!r||r.oper!==$.contractCreate)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");var i=w.fromTX(e,1);if(!i.outputs[0].getReturnType(F.OP_RETURN))throw new Error("not a valid contract");i.view.addOutput({hash:i.inputs[0].prevout.hash,index:i.inputs[0].prevout.index},new E({value:r.src}));let s="";s=(t?await this.createReceive(t):this).getAddress();var n=await this.getKey(s);e={oper:$.contractPromise,prevhash:e.hash("hex"),type:r.type,addr:r.addr,dst:r.dst,srcact:r.srcact,dstact:t,bob:n.getPublicKey("hex"),period:r.period},t=new x([N.fromSymbol("promise"),N.fromData(Buffer.from(JSON.stringify(e))),N.fromSymbol("drop"),N.fromSymbol("greaterthan"),N.fromSymbol("drop"),N.fromSymbol("if"),N.fromData(l.hash160(Buffer.from(e.bob,"hex"))),N.fromSymbol("else"),N.fromData(l.hash160(Buffer.from(r.alice,"hex"))),N.fromSymbol("endif"),N.fromSymbol("checksig")]),i.outputs.push(E.fromScript(t,r.src)),await this.remove(e.prevhash),await this.sign(i,null,B.ALL,[0]),n=i.commit();return await this.db.send(n[0]),e.current={hash:n[0].hash("hex"),index:0},e.raw=n[0].toRaw().toString("hex"),e.transStatus=W.Promised,this.db.transactionList.saveContract(e,!0),n}async contractExecute(e,t){if(!(e=this.db.transactionList.get(e))||e.transStatus!=W.Confirmed&&e.transStatus!=W.Expired)throw new D(L.errors.INVALID_PARAMS,"Invalid Tx id.");if(!(e=M.fromRaw(Buffer.from(e.raw,"hex"))))throw new D(L.errors.TYPE_ERROR,"Invalid Tx id.");t=t||1;var r=U.parseContract(e);if(!r||r.oper!==$.contractPromise)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");var s=e.outputs[1].getReturnData();if(!s||s.oper!==$.contractPromise)throw new D(L.errors.TYPE_ERROR,"Invalid tx type.");i.strictEqual(r.addr,s.addr),i.strictEqual(r.type,s.type),i.strictEqual(r.dst,s.dst),i.strictEqual(r.period,s.period),i.strictEqual(r.srcact,s.srcact),i.strictEqual(r.dstact,s.dstact);var n=this.db.transactionList.query(r.type,r.addr);if(n!=W.Confirmed&&n!=W.Expired)throw new D(L.errors.TYPE_ERROR,"Contract Promise not Check yet.");if(n==W.Expired&&1!=t||n==W.Confirmed&&2!=t)throw new D(L.errors.TYPE_ERROR,"Invalid Executor.");let a=r.srcact,o=(2==t&&(a=r.dstact),"");o=(a?await this.createReceive(a):this).getAddress();var c=new w,u=(c.addInputFromTx(e,1),{oper:$.contractExecute,type:r.type,addr:r.addr,master:t});u=E.fromScript(x.createScript(Buffer.from(JSON.stringify(u)),x.types.NULLDATA),0),c.outputs.push(u),u=E.fromScript(o,e.outputs[1].value),c.outputs.push(u),e=1==t?await O.fromPublic(Buffer.from(r.ori.alice,"hex")):await O.fromPublic(Buffer.from(s.bob,"hex")),u=await this.getKey(e.getAddress()),await c.signAsync(u,x.hashType.ALL,this.db.workers),t=c.commit();return i(t[0].verify(t[1],x.flags.STANDARD_VERIFY_FLAGS,n)),await this.db.send(t[0]),t}async htlcDeal(e,t){var r=await this.getTX(e.hash);let i=null;if(t){if(!(t=await this.getAccount(t)))throw new D(L.errors.TYPE_ERROR,"Invalid Account.");i=t.getReceive().toString()}else i=this.getReceive().toString();t=new w;var s=(new x).pushOp(F.OP_1);e.suggest&&s.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:s}),t.addOutput(i,r.tx.outputs[e.index].value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new E(r.tx.outputs[e.index])),await this.sign(t,null,B.ALL),s=t.commit();return await this.db.send(s[0]),s}async htlcCancel(e,t){let r=null;var i=await this.getTX(e.hash);if(!(r=i?i.tx.outputs[e.index]:r))throw new D(L.errors.TYPE_ERROR,"Invalid Input.");let s=null;if(t){if(!(i=await this.getAccount(t)))throw new D(L.errors.TYPE_ERROR,"Invalid Account.");s=i.getReceive().toString()}else s=this.getReceive().toString();return t=new w,i=(new x).pushOp(F.OP_0),e.suggest&&i.pushData(Buffer.from(e.sa,"hex")),t.addInput({prevout:{hash:e.hash,index:e.index},script:i}),e.suggest?t.setSequence(0,2*C.HTLC_CANCEL_PERIOD,!1):t.setSequence(0,C.HTLC_CANCEL_PERIOD,!1),t.addOutput(s,r.value-1e4),t.view.addOutput({hash:e.hash,index:e.index},new E(r)),i=await this.getKey(e.master),await t.signAsync(i,x.hashType.ALL,this.db.workers),e=t.commit(),await this.db.send(e[0]),e}async sendContracts(e,t,r){var i,s=new w;for(i of e)s.outputs.push(r.create(i));return t?await this.fund(s,{account:t}):await this.fund(s),await this.sign(s),e=s.commit(),await this.db.addTX(e[0]),await this.db.send(e[0]),e}async addStockAccountSeq(e){i(e&&"object"==typeof e,"Token data should be a object"),i(e.cid,"Token data should has a cid property"),i(e.uid,"Token data should has a uid property");var t=await this.stockAddress(e.cid,e.uid);t=this.db.accountList.getOrCreateStockAccount(e.cid,t.toString());return e.seq=t.seq+1,e}async tokenCreate(e,t="",r){i(e&&"object"==typeof e,"Token data should be a object"),i(e.cid,"Token data should has a cid property"),i(e.uid,"Token data should has a uid property"),e.time=!0,await this.ensureAccount({name:t,witness:!0});let s=null;if(r){if(!await this.belongToAccount(t,r))throw new D(L.errors.TYPE_ERROR,`stock.send address error: addr:${r} is not belongs to account:`+t);s=await this.getKey(r)}else s=await this.createReceive(t,a.hashInt(e.cid),this.master);return s.signData(e)}async sign(e,t,r=x.hashType.ALL,i){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,r,this.db.workers,i)}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 r=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{r()}}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,r){var i=await this.writeLock.lock();try{return await this._add(e,t,r)}finally{i()}}async _add(e,t,r){let i,s;this.txdb.start();try{(i=await this.txdb._add(e,t,r))&&(s=await this.syncOutputDepth(i)),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}return s&&0<s.length&&(this.db.emit("address",this.id,s),this.emit("address",s)),i}async resetBalance(){var e=await this.writeLock.lock();try{this.txdb.start();try{await this.txdb.resetBalance(),await this.txdb.commit()}catch(e){throw this.txdb.drop(),e}}finally{e()}}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 r=await this.writeLock.lock();try{return await this._zap(e,t)}finally{r()}}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 i of await this.getCredits(e)){var r=i.coin;i.spent||this.txdb.isConserved(r)||(-1!==r.height&&-2!==r.height||i.own)&&t.push(r)}return t}async getPending(e){return e=await this.ensureIndex(e),this.txdb.getPending(e)}async getBalance(e){return e=await this.ensureIndex(e),this.txdb.getBalance(e)}async queryBalanceLog(e,t=0){return(e=await this.ensureIndex(e))?this.db.queryBalanceLog(this.wid,e,t):[]}async getRange(e,t){return e&&"object"==typeof e&&(t=e,e=null),e=await this.ensureIndex(e),this.txdb.getRange(e,t)}async getLast(e,t){return e=await this.ensureIndex(e),this.txdb.getLast(e,t)}async ensureIndex(e,t){if(null==e){if(t)throw new Error("No account provided.");return null}if(-1===(t=await this.getAccountIndex(e)))throw new Error("Account not found.");return t}getAddress(e){return this.account.getAddress(e)}getReceive(e){return this.account.getReceive(e)}getChange(e){return this.account.getChange(e)}getNested(e){return this.account.getNested(e)}inspect(){return{wid:this.wid,id:this.id,network:this.network.type,initialized:this.initialized,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,state:this.txdb.state?this.txdb.state.toJSON(!0):null,master:this.master,account:this.account}}toJSON(e){return{network:this.network.type,wid:this.wid,id:this.id,initialized:this.initialized,watchOnly:this.watchOnly,accountDepth:this.accountDepth,token:this.token.toString("hex"),tokenDepth:this.tokenDepth,height:this.db.curHeight,state:this.txdb.state.toJSON(!0),master:this.master.toJSON(e),account:this.account.toJSON(!0)}}getSize(){var e=0;return(e+=50)+o.sizeVarString(this.id,"ascii")+o.sizeVarlen(this.master.getSize())}toRaw(){var e=this.getSize();return(e=new f(e)).writeU32(this.network.magic),e.writeU32(this.wid),e.writeVarString(this.id,"ascii"),e.writeU8(this.initialized?1:0),e.writeU8(this.watchOnly?1:0),e.writeU32(this.accountDepth),e.writeBytes(this.token),e.writeU32(this.tokenDepth),e.writeVarBytes(this.master.toRaw()),e.render()}fromRaw(e){e=new d(e);var t=n.fromMagic(e.readU32());return this.wid=e.readU32(),this.id=e.readVarString("ascii"),this.initialized=1===e.readU8(),this.watchOnly=1===e.readU8(),this.accountDepth=e.readU32(),this.token=e.readBytes(32),this.tokenDepth=e.readU32(),this.master.fromRaw(e.readVarBytes()),i(t===this.db.network,"Wallet network mismatch."),this}static fromRaw(e,t){return new ie(e).fromRaw(t)}static isWallet(e){return e instanceof ie}async issueCreate(e,t,r){var i=new X(e),s=((s=(i.source.subjectName||(i.source.subjectName=i.erid),O.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network))).witness=!0,i.sign(s,!0,this.network),i.toOptions(!0));return r?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 caAbolish(e,t,r){var i=O.fromPrivate(Buffer.from(e.key,"hex"),!0,this.network),s=(i.witness=!0,await this.db.$parent.chain.db.erList.getEr(e.erid));if(!s)throw new D(L.errors.TYPE_ERROR,"ca.abolish: Invalid erid.");if(s.source.cid!=e.cid)throw new D(L.errors.TYPE_ERROR,"ca.abolish: Invalid cid.");if(s.source.uid!=e.uid)throw new D(L.errors.TYPE_ERROR,"ca.abolish: Invalid uid.");var n=s.signature;if(s.sign(i,!0,this.network),s.witness!=e.witness||s.signature!=n)throw new D(L.errors.TYPE_ERROR,"ca.abolish: You have no permission to abolish this witness.");return(s=new J(e)).sign(i),n=s.toOptions(!0),r?this.send({outputs:[{address:e.address,value:1e4}],comment:n},t):await this.send({outputs:[{address:e.address,value:1e4}],comment:n},t),n}async enchanceCp(e,t){var r=((e=new Z(e)).oper="enchanceCp",await this.ensureCp(e.to)),i=await this.ensureCp(e.from);if(!(i=await this.getKey(i.pubAddress)))throw new D(L.errors.TYPE_ERROR,"Invalid cid, Not along to this wallet.");return e.sign(i),i=e.toOptions(!0),[await this.send({outputs:[{address:r.pubAddress,value:1e4}],comment:i},t),i]}async ensureCp(e,t=!1){if(await this.db.flushCP([e]),(e=this.db.cpList.getItem(e))||t)return e;throw new D(L.errors.TYPE_ERROR,"Invalid cid, cannot find cp.")}}e.exports=ie},function(e,t,r){"use strict";
|
|
296
296
|
/*!
|
|
297
297
|
* BlockMeta.js - walletdb records
|
|
298
298
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
@@ -432,7 +432,7 @@ const i=r(5).ContractType;e.exports=function(e){if(!e)return r(190);switch(e.ope
|
|
|
432
432
|
/*!
|
|
433
433
|
* cpHelper.js
|
|
434
434
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|
|
435
|
-
*/const i=r(54);e.exports=class{static verifyDataFormat(e){return e.name&&!/^(?![_.-])(?!.*?[_.-]$)[.a-zA-Z0-9_-]{4,
|
|
435
|
+
*/const i=r(54);e.exports=class{static verifyDataFormat(e){return e.name&&!/^(?![_.-])(?!.*?[_.-]$)[.a-zA-Z0-9_-]{4,64}$/.test(e.name)?"error name format, length 4~64":e.grate&&(e.grate<0||50<=e.grate)?"error grate value: 0~49":e.cls&&!/^(?![_.-])(?!.*?[_.-]$)[.a-zA-Z0-9_-]{2,20}$/.test(e.cls)?"error class format, length 2~20":!e.ip||i.isIPv4(i.toBuffer(e.ip))||i.isIPv6(i.toBuffer(e.ip))?null:"error ip format"}}},function(e,t,r){const i=r(0);var s=r(11);const n=r(5).ContractEnvType,a=r(37).VerifyError,o=r(21).opcodes,c=r(194);e.exports=class extends s{async insert(){var e=this.options.env,t=(i=this.options.tx).hash("hex");let r=i.outputs[0];var i;(t=((i=this.data).current={hash:t,index:0,address:r.getAddress().toString()},i.height=-1,e.cpMemList.addItem(i),await e.finder(i.prev.hash)))&&t.outputs[i.prev.index]&&(t=(r=t.outputs[i.prev.index]).getReturnData([o.OP_CPCHANGE,o.OP_CPREGISTER]))&&t.name!=i.name&&e.cpMemList.removeNameIndex(t.name)}async erase(){var e,t,r=this.options.env,i=this.data,s=(i=(r.cpMemList.delItem(i),i.prev),await r.getExtendTX(i.hash));s&&(t=(e=s.tx.outputs[i.index]).getReturnData([o.OP_CPCHANGE,o.OP_CPREGISTER]))&&(t.current={hash:i.hash,index:i.index,address:e.getAddress().toString()},t.height=s.height,r.cpMemList.addItem(t))}async confirm(){var e=this.options.env,t=(i=this.options.tx).hash("hex");let r=i.outputs[0];var i;(t=((i=this.data).current={hash:t,index:0,address:r.getAddress().toString()},i.height=this.options.coinbaseHeight,e.cpList.addItem(i),await e.finder(i.prev.hash)))&&t.outputs[i.prev.index]&&(t=(r=t.outputs[i.prev.index]).getReturnData([o.OP_CPCHANGE,o.OP_CPREGISTER]))&&t.name!=i.name&&e.cpList.removeNameIndex(t.name)}async unconfirm(){var e,t,r=this.options.env,i=this.data,s=(i=(r.cpList.delItem(i),i.prev),await r.getExtendTX(i.hash));s&&(t=(e=s.tx.outputs[i.index]).getReturnData([o.OP_CPCHANGE,o.OP_CPREGISTER]))&&(t.current={hash:i.hash,index:i.index,address:e.getAddress().toString()},t.height=s.height,r.cpList.addItem(t))}async verify(){var e=this.options.env,t=this.options.tx,r=this.data;if(!r)throw new a(t,"invalid","null cpChange data",100);var s=c.verifyDataFormat(this.data);if(s)throw new a(t,"invalid",s,100);if(i.strictEqual(r.prev.hash,t.inputs[0].prevout.hash),i.strictEqual(r.prev.index,t.inputs[0].prevout.index),s=await e.finder(r.prev.hash),i(s),s=s.outputs[r.prev.index],i(s),s=s.getReturnData([o.OP_CPREGISTER,o.OP_CPCHANGE]),i(s),i(s.cid===r.cid),this.mode!=n.Block||"spv"!=e.node.nodeType){var u=this.mode!=n.Mempool;if(!await e.rpcExecute({method:"canExecute",params:[{confirm:u,cid:r.cid,name:s.name,oper:r.oper}]}))throw new a(t,"invalid info on "+r.oper,"cp manager",0)}return!0}}},function(e,t,r){const i=r(0),s=r(37).VerifyError;var n=r(11);const{BlockFinalType:a,ContractEnvType:o}=r(5),c=r(63).verifyData;e.exports=class extends n{async confirm(){this.mode==o.Block&&await this.options.env.voteMgr.calcBlock(this.data.data.addr,!0)}async unconfirm(){this.mode==o.Block&&await this.options.env.voteMgr.calcBlock(this.data.data.addr,!1)}async verify(){if(this.mode!=o.Block)return null;var e=this.options.env;if(i.strictEqual(!0,c(this.data)),i(this.data.data.addr,this.options.block.txs[0].outputs[0].getAddress().toString()),(await e.voteMgr.checkVote(this.data.data.addr)).result)return!0;throw new s(this.options.block,"invalid","bad-coinbase address invalid",100)}isBlockFinal(){return a.Final}}},function(e,t,r){const i=r(573),s=r(77),n=r(78);var a=r(11);const{BlockFinalType:o,ContractType:c,ContractStatus:u,ContractEnvType:h}=r(5),l=r(109),p=r(21).opcodes;e.exports=class extends a{async confirm(){var e=this.options.env;return this.data.current={hash:this.options.hash,index:0},this.data.raw=this.options.raw,await e.transactionList.promiseContract(this.data,!0),0<e.network.txcheckpoint.getCheck(this.data.type).length&&e.network.txchecktime[this.data.type]&&e.autoTaskMgr.addTask(new l(e.network.txcheckpoint,this.data),e.network.txchecktime[this.data.type]),!0}async unconfirm(){await this.options.env.transactionList.delTransContract(this.data)}async verify(){var e=this.options.env,t=this.options.facade,r=(i(1<this.options.tx.outputs.length),this.options.tx.outputs[1].script.code);if(i.strictEqual(r[0].value,p.OP_PROMISE),i.strictEqual(r[2].value,p.OP_DROP),i.strictEqual(r[3].value,p.OP_GREATERTHAN),i.strictEqual(r[4].value,p.OP_IF),i.bufferEqual(r[5].data,Buffer.from(this.data.bob,"hex")),i.strictEqual(r[6].value,p.OP_ELSE),i.bufferEqual(r[7].data,Buffer.from(this.data.ori.alice,"hex")),i.strictEqual(r[8].value,p.OP_ENDIF),i.strictEqual(r[9].value,p.OP_CHECKSIG),i.strictEqual(this.data.addr,this.data.ori.addr),i.strictEqual(this.data.type,this.data.ori.type),i.strictEqual(this.data.dst,this.data.ori.dst),i.strictEqual(this.data.period,this.data.ori.period),this.mode==h.Mempool&&(r=await e.finder(this.data.prevhash))){if(!(t=await t.FactoryOfContract({tx:r,env:e})).data||t.data.oper!==c.contractCreate)throw new s(n.errors.TYPE_ERROR,"Contract promise: Invalid ori tx type");await e.removeDoubleSpenders(r)}if(this.mode==h.Block){t=this.data;let i=this.options.env.transactionList.query(t.type,t.addr);if(i!==u.Expired&&i!==u.Confirmed&&(r=new l(e.network.txcheckpoint,this.data),[,i]=await r.execute(e)),(this.data.transStatus=i)!==u.Expired&&i!==u.Confirmed)return!1}return!0}isBlockFinal(){var e=this.options.env;return this.data.transStatus===u.Confirmed?o.Final:this.data.period<e.curHeight||this.data.transStatus===u.Expired?(this.data.transStatus=u.Expired,o.Final):o.Waiting}async checkFees(){return!0}}},function(e,t,r){"use strict";
|
|
436
436
|
/*!
|
|
437
437
|
* mnemonic.js - hd mnemonics for vallnet
|
|
438
438
|
* Copyright (c) 2019-2022, Bookman Software (MIT License).
|