UNPKG

moac-lightwallets

Version:
2 lines 1.36 MB
!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.lightwallet=f()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports={txutils:require("./lib/txutils.js"),encryption:require("./lib/encryption.js"),signing:require("./lib/signing.js"),keystore:require("./lib/keystore.js"),upgrade:require("./lib/upgrade.js")}},{"./lib/encryption.js":2,"./lib/keystore.js":3,"./lib/signing.js":4,"./lib/txutils.js":5,"./lib/upgrade.js":6}],2:[function(require,module,exports){(function(Buffer){function nacl_decodeHex(msgHex){var msgBase64=new Buffer(msgHex,"hex").toString("base64");return nacl.util.decodeBase64(msgBase64)}function _asymEncryptRaw(keystore,pwDerivedKey,msgUint8Array,myPubKey,theirPubKey,hdPathString){if(void 0===hdPathString&&(hdPathString=keystore.defaultHdPathString),"asymEncrypt"!==keystore.ksData[hdPathString].info.purpose)throw new Error('encryption._asymEncryptRaw: Function not defined when purpose is not "asymEncrypt"');if(void 0===keystore.ksData[hdPathString].encPrivKeys[myPubKey])throw new Error("encryption._asymEncryptRaw: public key not found in KeyStore");var privKey=keystore.exportPrivateKey(myPubKey,pwDerivedKey,hdPathString),privKeyUInt8Array=nacl_decodeHex(privKey),pubKeyUInt8Array=nacl_decodeHex(theirPubKey),nonce=nacl.randomBytes(nacl.box.nonceLength),encryptedMessage=nacl.box(msgUint8Array,nonce,pubKeyUInt8Array,privKeyUInt8Array),output={alg:"curve25519-xsalsa20-poly1305",nonce:nacl.util.encodeBase64(nonce),ciphertext:nacl.util.encodeBase64(encryptedMessage)};return output}function _asymDecryptRaw(keystore,pwDerivedKey,encMsg,theirPubKey,myPubKey,hdPathString){if(void 0===hdPathString&&(hdPathString=keystore.defaultHdPathString),"asymEncrypt"!==keystore.ksData[hdPathString].info.purpose)throw new Error('encryption._asymDecryptRaw: Function not defined when purpose is not "asymEncrypt"');if(void 0===keystore.ksData[hdPathString].encPrivKeys[myPubKey])throw new Error("encryption._asymDecryptRaw: public key not found in KeyStore");var privKey=keystore.exportPrivateKey(myPubKey,pwDerivedKey,hdPathString),privKeyUInt8Array=nacl_decodeHex(privKey),pubKeyUInt8Array=nacl_decodeHex(theirPubKey),nonce=nacl.util.decodeBase64(encMsg.nonce),ciphertext=nacl.util.decodeBase64(encMsg.ciphertext),cleartext=nacl.box.open(ciphertext,nonce,pubKeyUInt8Array,privKeyUInt8Array);return cleartext}var nacl=(require("ethereumjs-util"),require("tweetnacl"));asymEncryptString=function(keystore,pwDerivedKey,msg,myPubKey,theirPubKey,hdPathString){var messageUInt8Array=nacl.util.decodeUTF8(msg);return _asymEncryptRaw(keystore,pwDerivedKey,messageUInt8Array,myPubKey,theirPubKey,hdPathString)},asymDecryptString=function(keystore,pwDerivedKey,encMsg,theirPubKey,myPubKey,hdPathString){var cleartext=_asymDecryptRaw(keystore,pwDerivedKey,encMsg,theirPubKey,myPubKey,hdPathString);return cleartext===!1?!1:nacl.util.encodeUTF8(cleartext)},multiEncryptString=function(keystore,pwDerivedKey,msg,myPubKey,theirPubKeyArray,hdPathString){var messageUInt8Array=nacl.util.decodeUTF8(msg),symEncryptionKey=nacl.randomBytes(nacl.secretbox.keyLength),symNonce=nacl.randomBytes(nacl.secretbox.nonceLength),symEncMessage=nacl.secretbox(messageUInt8Array,symNonce,symEncryptionKey);if(theirPubKeyArray.length<1)throw new Error("Found no pubkeys to encrypt to.");var encryptedSymKey={};encryptedSymKey=[];for(var i=0;i<theirPubKeyArray.length;i++){var encSymKey=_asymEncryptRaw(keystore,pwDerivedKey,symEncryptionKey,myPubKey,theirPubKeyArray[i],hdPathString);delete encSymKey.alg,encryptedSymKey.push(encSymKey)}var output={};return output.version=1,output.asymAlg="curve25519-xsalsa20-poly1305",output.symAlg="xsalsa20-poly1305",output.symNonce=nacl.util.encodeBase64(symNonce),output.symEncMessage=nacl.util.encodeBase64(symEncMessage),output.encryptedSymKey=encryptedSymKey,output},multiDecryptString=function(keystore,pwDerivedKey,encMsg,theirPubKey,myPubKey,hdPathString){for(var symKey=!1,i=0;i<encMsg.encryptedSymKey.length;i++){var result=_asymDecryptRaw(keystore,pwDerivedKey,encMsg.encryptedSymKey[i],theirPubKey,myPubKey,hdPathString);if(result!==!1){symKey=result;break}}if(symKey===!1)return!1;var symNonce=nacl.util.decodeBase64(encMsg.symNonce),symEncMessage=nacl.util.decodeBase64(encMsg.symEncMessage),msg=nacl.secretbox.open(symEncMessage,symNonce,symKey);return msg===!1?!1:nacl.util.encodeUTF8(msg)},module.exports={asymEncryptString:asymEncryptString,asymDecryptString:asymDecryptString,multiEncryptString:multiEncryptString,multiDecryptString:multiDecryptString}}).call(this,require("buffer").Buffer)},{buffer:99,"ethereumjs-util":382,tweetnacl:419}],3:[function(require,module,exports){(function(Buffer){function strip0x(input){return"string"!=typeof input?input:input.length>=2&&"0x"===input.slice(0,2)?input.slice(2):input}function add0x(input){return"string"!=typeof input?input:input.length<2||"0x"!==input.slice(0,2)?"0x"+input:input}function leftPadString(stringToPad,padChar,length){for(var repreatedPadChar="",i=0;length>i;i++)repreatedPadChar+=padChar;return(repreatedPadChar+stringToPad).slice(-length)}function nacl_encodeHex(msgUInt8Arr){var msgBase64=nacl.util.encodeBase64(msgUInt8Arr);return new Buffer(msgBase64,"base64").toString("hex")}function nacl_decodeHex(msgHex){var msgBase64=new Buffer(msgHex,"hex").toString("base64");return nacl.util.decodeBase64(msgBase64)}var CryptoJS=require("crypto-js"),Transaction=require("ethereumjs-tx"),EC=require("elliptic").ec,ec=new EC("secp256k1"),bitcore=require("bitcore-lib"),Random=bitcore.crypto.Random,Hash=bitcore.crypto.Hash,Mnemonic=require("bitcore-mnemonic"),nacl=require("tweetnacl"),scrypt=require("scrypt-async"),signing=(require("./encryption"),require("./signing")),KeyStore=function(mnemonic,pwDerivedKey,hdPathString){if(this.defaultHdPathString="m/0'/0'/0'",void 0===hdPathString&&(hdPathString=this.defaultHdPathString),this.ksData={},this.ksData[hdPathString]={},pathKsData=this.ksData[hdPathString],pathKsData.info={curve:"secp256k1",purpose:"sign"},this.encSeed=void 0,this.encHdRootPriv=void 0,this.version=2,pathKsData.encHdPathPriv=void 0,pathKsData.hdIndex=0,pathKsData.encPrivKeys={},pathKsData.addresses=[],"undefined"!=typeof pwDerivedKey&&"undefined"!=typeof mnemonic){var words=mnemonic.split(" ");if(!Mnemonic.isValid(mnemonic,Mnemonic.Words.ENGLISH)||12!==words.length)throw new Error("KeyStore: Invalid mnemonic");var paddedSeed=leftPadString(mnemonic," ",120);this.encSeed=KeyStore._encryptString(paddedSeed,pwDerivedKey);var hdRoot=new Mnemonic(mnemonic).toHDPrivateKey().xprivkey;this.encHdRootPriv=KeyStore._encryptString(hdRoot,pwDerivedKey);var hdRootKey=new bitcore.HDPrivateKey(hdRoot),hdPath=hdRootKey.derive(hdPathString).xprivkey;pathKsData.encHdPathPriv=KeyStore._encryptString(hdPath,pwDerivedKey)}};KeyStore._encryptString=function(string,pwDerivedKey){var nonce=nacl.randomBytes(nacl.secretbox.nonceLength),encObj=nacl.secretbox(nacl.util.decodeUTF8(string),nonce,pwDerivedKey),encString={encStr:nacl.util.encodeBase64(encObj),nonce:nacl.util.encodeBase64(nonce)};return encString},KeyStore._decryptString=function(encryptedStr,pwDerivedKey){var secretbox=nacl.util.decodeBase64(encryptedStr.encStr),nonce=nacl.util.decodeBase64(encryptedStr.nonce),decryptedStr=nacl.secretbox.open(secretbox,nonce,pwDerivedKey);return nacl.util.encodeUTF8(decryptedStr)},KeyStore._encryptKey=function(privKey,pwDerivedKey){var privKeyArray=nacl_decodeHex(privKey),nonce=nacl.randomBytes(nacl.secretbox.nonceLength),encKey=nacl.secretbox(privKeyArray,nonce,pwDerivedKey);return encKey={key:nacl.util.encodeBase64(encKey),nonce:nacl.util.encodeBase64(nonce)}},KeyStore._decryptKey=function(encryptedKey,pwDerivedKey){var secretbox=nacl.util.decodeBase64(encryptedKey.key),nonce=nacl.util.decodeBase64(encryptedKey.nonce),decryptedKey=nacl.secretbox.open(secretbox,nonce,pwDerivedKey);return nacl_encodeHex(decryptedKey)},KeyStore._computeAddressFromPrivKey=function(privKey){var keyPair=ec.genKeyPair();keyPair._importPrivate(privKey,"hex");var compact=!1,pubKey=keyPair.getPublic(compact,"hex").slice(2),pubKeyWordArray=CryptoJS.enc.Hex.parse(pubKey),hash=CryptoJS.SHA3(pubKeyWordArray,{outputLength:256}),address=hash.toString(CryptoJS.enc.Hex).slice(24);return address},KeyStore._computePubkeyFromPrivKey=function(privKey,curve){if("curve25519"!==curve)throw new Error('KeyStore._computePubkeyFromPrivKey: Only "curve25519" supported.');var privKeyBase64=new Buffer(privKey,"hex").toString("base64"),privKeyUInt8Array=nacl.util.decodeBase64(privKeyBase64),pubKey=nacl.box.keyPair.fromSecretKey(privKeyUInt8Array).publicKey,pubKeyBase64=nacl.util.encodeBase64(pubKey),pubKeyHex=new Buffer(pubKeyBase64,"base64").toString("hex");return pubKeyHex},KeyStore.prototype.addHdDerivationPath=function(hdPathString,pwDerivedKey,info){if("sign"!==info.purpose&&"asymEncrypt"!==info.purpose)throw new Error("KeyStore.addHdDerivationPath: info.purpose is '"+info.purpose+"' but must be either 'sign' or 'asymEncrypt'.");if("secp256k1"!==info.curve&&"curve25519"!==info.curve)throw new Error("KeyStore.addHdDerivationPath: info.curve is '"+info.curve+"' but must be either 'secp256k1' or 'curve25519'.");var hdRoot=KeyStore._decryptString(this.encHdRootPriv,pwDerivedKey),hdRootKey=new bitcore.HDPrivateKey(hdRoot),hdPath=hdRootKey.derive(hdPathString).xprivkey;this.ksData[hdPathString]={},this.ksData[hdPathString].info=info,this.ksData[hdPathString].encHdPathPriv=KeyStore._encryptString(hdPath,pwDerivedKey),this.ksData[hdPathString].hdIndex=0,this.ksData[hdPathString].encPrivKeys={},"sign"===info.purpose?this.ksData[hdPathString].addresses=[]:"asymEncrypt"===info.purpose&&(this.ksData[hdPathString].pubKeys=[])},KeyStore.prototype.setDefaultHdDerivationPath=function(hdPathString){if(void 0===this.ksData[hdPathString])throw new Error("setDefaultHdDerivationPath: HD path does not exist. Cannot set default.");this.defaultHdPathString=hdPathString},KeyStore.prototype._generatePrivKeys=function(pwDerivedKey,n,hdPathString){void 0===hdPathString&&(hdPathString=this.defaultHdPathString);for(var hdRoot=KeyStore._decryptString(this.ksData[hdPathString].encHdPathPriv,pwDerivedKey),keys=[],i=0;n>i;i++){var hdprivkey=new bitcore.HDPrivateKey(hdRoot).derive(this.ksData[hdPathString].hdIndex++),privkeyBuf=hdprivkey.privateKey.toBuffer(),privkeyHex=privkeyBuf.toString("hex");if(privkeyBuf.length<16)throw new Error("Private key suspiciously small: < 16 bytes. Aborting!");if(privkeyBuf.length<32)privkeyHex=leftPadString(privkeyBuf.toString("hex"),"0",64);else if(privkeyBuf.length>32)throw new Error("Private key larger than 32 bytes. Aborting!");var encPrivKey=KeyStore._encryptKey(privkeyHex,pwDerivedKey);keys[i]={privKey:privkeyHex,encPrivKey:encPrivKey}}return keys},KeyStore._concatAndSha256=function(entropyBuf0,entropyBuf1){var totalEnt=Buffer.concat([entropyBuf0,entropyBuf1]);if(totalEnt.length!==entropyBuf0.length+entropyBuf1.length)throw new Error("generateRandomSeed: Logic error! Concatenation of entropy sources failed.");var hashedEnt=Hash.sha256(totalEnt);return hashedEnt},KeyStore.generateRandomSeed=function(extraEntropy){var seed="";if(void 0===extraEntropy)seed=new Mnemonic(Mnemonic.Words.ENGLISH);else{if("string"!=typeof extraEntropy)throw new Error("generateRandomSeed: extraEntropy is set but not a string.");var entBuf=new Buffer(extraEntropy),randBuf=Random.getRandomBuffer(32),hashedEnt=this._concatAndSha256(randBuf,entBuf).slice(0,16);seed=new Mnemonic(hashedEnt,Mnemonic.Words.ENGLISH)}return seed.toString()},KeyStore.isSeedValid=function(seed){return Mnemonic.isValid(seed,Mnemonic.Words.ENGLISH)},KeyStore.prototype.isDerivedKeyCorrect=function(pwDerivedKey){var paddedSeed=KeyStore._decryptString(this.encSeed,pwDerivedKey);return paddedSeed.length>0},KeyStore.deserialize=function(keystore){var jsonKS=JSON.parse(keystore);if(void 0===jsonKS.version||1===jsonKS.version)throw new Error("Old version of serialized keystore. Please use KeyStore.upgradeOldSerialized() to convert it to the latest version.");var keystoreX=new KeyStore;return keystoreX.encSeed=jsonKS.encSeed,keystoreX.encHdRootPriv=jsonKS.encHdRootPriv,keystoreX.ksData=jsonKS.ksData,keystoreX},KeyStore.prototype.serialize=function(){var jsonKS={encSeed:this.encSeed,ksData:this.ksData,encHdRootPriv:this.encHdRootPriv,version:this.version};return JSON.stringify(jsonKS)},KeyStore.prototype.getAddresses=function(hdPathString){if(void 0===hdPathString&&(hdPathString=this.defaultHdPathString),"sign"!==this.ksData[hdPathString].info.purpose)throw new Error('KeyStore.getAddresses: Addresses not defined when purpose is not "sign"');return this.ksData[hdPathString].addresses},KeyStore.prototype.getSeed=function(pwDerivedKey){var paddedSeed=KeyStore._decryptString(this.encSeed,pwDerivedKey);return paddedSeed.trim()},KeyStore.prototype.exportPrivateKey=function(address,pwDerivedKey,hdPathString){void 0===hdPathString&&(hdPathString=this.defaultHdPathString);var address=strip0x(address);if(void 0===this.ksData[hdPathString].encPrivKeys[address])throw new Error("KeyStore.exportPrivateKey: Address not found in KeyStore");var encPrivKey=this.ksData[hdPathString].encPrivKeys[address],privKey=KeyStore._decryptKey(encPrivKey,pwDerivedKey);return privKey},KeyStore.prototype.generateNewAddress=function(pwDerivedKey,n,hdPathString){if(void 0===hdPathString&&(hdPathString=this.defaultHdPathString),"sign"!==this.ksData[hdPathString].info.purpose)throw new Error('KeyStore.generateNewAddress: Address not defined when purpose is not "sign"');if(!this.encSeed)throw new Error("KeyStore.generateNewAddress: No seed set");n=n||1;for(var keys=this._generatePrivKeys(pwDerivedKey,n,hdPathString),i=0;n>i;i++){var keyObj=keys[i],address=KeyStore._computeAddressFromPrivKey(keyObj.privKey);this.ksData[hdPathString].encPrivKeys[address]=keyObj.encPrivKey,this.ksData[hdPathString].addresses.push(address)}},KeyStore.prototype.generateNewEncryptionKeys=function(pwDerivedKey,n,hdPathString){if(void 0===hdPathString&&(hdPathString=this.defaultHdPathString),"asymEncrypt"!==this.ksData[hdPathString].info.purpose)throw new Error('KeyStore.generateNewEncryptionKeys: Address not defined when purpose is not "asymEncrypt"');if(!this.encSeed)throw new Error("KeyStore.generateNewEncryptionKeys: No seed set");n=n||1;for(var keys=this._generatePrivKeys(pwDerivedKey,n,hdPathString),curve=this.ksData[hdPathString].info.curve,i=0;n>i;i++){var keyObj=keys[i],pubkey=KeyStore._computePubkeyFromPrivKey(keyObj.privKey,curve);this.ksData[hdPathString].encPrivKeys[pubkey]=keyObj.encPrivKey,this.ksData[hdPathString].pubKeys.push(pubkey)}},KeyStore.prototype.getPubKeys=function(hdPathString){if(void 0===hdPathString&&(hdPathString=this.defaultHdPathString),"asymEncrypt"!==this.ksData[hdPathString].info.purpose)throw new Error('KeyStore.getPubKeys: Not defined when purpose is not "asymEncrypt"');if(void 0===this.ksData[hdPathString].pubKeys)throw new Error("KeyStore.getPubKeys: No pubKeys data found!");return this.ksData[hdPathString].pubKeys},KeyStore.deriveKeyFromPassword=function(password,callback){var salt="lightwalletSalt",logN=14,r=8,dkLen=32,interruptStep=200,cb=function(derKey){var ui8arr=new Uint8Array(derKey);callback(null,ui8arr)};scrypt(password,salt,logN,r,dkLen,interruptStep,cb,null)},KeyStore.prototype.passwordProvider=function(callback){var password=prompt("Enter password to continue","Enter password");callback(null,password)},KeyStore.prototype.hasAddress=function(address,callback){var addrToCheck=strip0x(address);void 0===this.ksData[this.defaultHdPathString].encPrivKeys[addrToCheck]?callback("Address not found!",!1):callback(null,!0)},KeyStore.prototype.signTransaction=function(txParams,callback){var ethjsTxParams={};ethjsTxParams.from=add0x(txParams.from),ethjsTxParams.to=add0x(txParams.to),ethjsTxParams.gasLimit=add0x(txParams.gas),ethjsTxParams.gasPrice=add0x(txParams.gasPrice),ethjsTxParams.nonce=add0x(txParams.nonce),ethjsTxParams.value=add0x(txParams.value),ethjsTxParams.data=add0x(txParams.data);var txObj=new Transaction(ethjsTxParams),rawTx=txObj.serialize().toString("hex"),signingAddress=strip0x(txParams.from),self=this;this.passwordProvider(function(err,password){return err?callback(err):void KeyStore.deriveKeyFromPassword(password,function(err,pwDerivedKey){var signedTx=signing.signTx(self,pwDerivedKey,rawTx,signingAddress,self.defaultHdPathString);callback(null,"0x"+signedTx)})})},module.exports=KeyStore}).call(this,require("buffer").Buffer)},{"./encryption":2,"./signing":4,"bitcore-lib":7,"bitcore-mnemonic":86,buffer:99,"crypto-js":330,elliptic:356,"ethereumjs-tx":379,"scrypt-async":418,tweetnacl:419}],4:[function(require,module,exports){(function(Buffer){var Transaction=require("ethereumjs-tx"),util=require("ethereumjs-util");signTx=function(keystore,pwDerivedKey,rawTx,signingAddress,hdPathString){void 0===hdPathString&&(hdPathString=keystore.defaultHdPathString),rawTx=util.stripHexPrefix(rawTx),signingAddress=util.stripHexPrefix(signingAddress);var txCopy=new Transaction(new Buffer(rawTx,"hex")),privKey=keystore.exportPrivateKey(signingAddress,pwDerivedKey,hdPathString);return txCopy.sign(new Buffer(privKey,"hex")),privKey="",txCopy.serialize().toString("hex")},module.exports.signTx=signTx,signMsg=function(keystore,pwDerivedKey,rawMsg,signingAddress,hdPathString){void 0===hdPathString&&(hdPathString=keystore.defaultHdPathString),signingAddress=util.stripHexPrefix(signingAddress);var msgHash=util.sha3(rawMsg),privKey=keystore.exportPrivateKey(signingAddress,pwDerivedKey,hdPathString);return util.ecsign(msgHash,new Buffer(privKey,"hex"))},module.exports.signMsg=signMsg,recoverAddress=function(rawMsg,v,r,s){var msgHash=util.sha3(rawMsg);return util.pubToAddress(util.ecrecover(msgHash,v,r,s))},module.exports.recoverAddress=recoverAddress,concatSig=function(v,r,s){return r=util.fromSigned(r),s=util.fromSigned(s),v=util.bufferToInt(v),r=util.toUnsigned(r).toString("hex"),s=util.toUnsigned(s).toString("hex"),v=util.stripHexPrefix(util.intToHex(v)),util.addHexPrefix(r.concat(s,v).toString("hex"))},module.exports.concatSig=concatSig}).call(this,require("buffer").Buffer)},{buffer:99,"ethereumjs-tx":379,"ethereumjs-util":382}],5:[function(require,module,exports){(function(Buffer){function add0x(input){return"string"!=typeof input?input:input.length<2||"0x"!==input.slice(0,2)?"0x"+input:input}function _encodeFunctionTxData(functionName,types,args){var fullName=functionName+"("+types.join()+")",signature=CryptoJS.SHA3(fullName,{outputLength:256}).toString(CryptoJS.enc.Hex).slice(0,8),dataHex=signature+coder.encodeParams(types,args);return dataHex}function _getTypesFromAbi(abi,functionName){function matchesFunctionName(json){return json.name===functionName&&"function"===json.type}function getTypes(json){return json.type}var funcJson=abi.filter(matchesFunctionName)[0];return funcJson.inputs.map(getTypes)}function functionTx(abi,functionName,args,txObject){var types=_getTypesFromAbi(abi,functionName),txData=_encodeFunctionTxData(functionName,types,args),txObjectCopy={};return txObjectCopy.to=add0x(txObject.to),txObjectCopy.gasPrice=add0x(txObject.gasPrice),txObjectCopy.gasLimit=add0x(txObject.gasLimit),txObjectCopy.nonce=add0x(txObject.nonce),txObjectCopy.data=add0x(txData),txObjectCopy.value=add0x(txObject.value),new Transaction(txObjectCopy).serialize().toString("hex")}function createdContractAddress(fromAddress,nonce){var rlpEncodedHex=rlp.encode([new Buffer(fromAddress,"hex"),nonce]).toString("hex"),rlpEncodedWordArray=CryptoJS.enc.Hex.parse(rlpEncodedHex),hash=CryptoJS.SHA3(rlpEncodedWordArray,{outputLength:256}).toString(CryptoJS.enc.Hex);return hash.slice(24)}function createContractTx(fromAddress,txObject){var txObjectCopy={};txObjectCopy.to=add0x(txObject.to),txObjectCopy.gasPrice=add0x(txObject.gasPrice),txObjectCopy.gasLimit=add0x(txObject.gasLimit),txObjectCopy.nonce=add0x(txObject.nonce),txObjectCopy.data=add0x(txObject.data),txObjectCopy.value=add0x(txObject.value);var contractAddress=createdContractAddress(fromAddress,txObject.nonce),tx=new Transaction(txObjectCopy);return{tx:tx.serialize().toString("hex"),addr:contractAddress}}function valueTx(txObject){var txObjectCopy={};txObjectCopy.to=add0x(txObject.to),txObjectCopy.gasPrice=add0x(txObject.gasPrice),txObjectCopy.gasLimit=add0x(txObject.gasLimit),txObjectCopy.nonce=add0x(txObject.nonce),txObjectCopy.value=add0x(txObject.value);var tx=new Transaction(txObjectCopy);return tx.serialize().toString("hex")}var Transaction=require("ethereumjs-tx"),coder=require("web3/lib/solidity/coder"),rlp=require("rlp"),CryptoJS=require("crypto-js");module.exports={_encodeFunctionTxData:_encodeFunctionTxData,_getTypesFromAbi:_getTypesFromAbi,functionTx:functionTx,createdContractAddress:createdContractAddress,createContractTx:createContractTx,valueTx:valueTx}}).call(this,require("buffer").Buffer)},{buffer:99,"crypto-js":330,"ethereumjs-tx":379,rlp:417,"web3/lib/solidity/coder":423}],6:[function(require,module,exports){var CryptoJS=require("crypto-js"),keystore=require("./keystore"),EC=(require("ethereumjs-tx"),require("elliptic").ec),bitcore=(new EC("secp256k1"),require("bitcore-lib"));bitcore.crypto.Random,bitcore.crypto.Hash,require("bitcore-mnemonic"),require("tweetnacl"),require("scrypt-async");legacyDecryptString=function(encryptedStr,password){var decryptedStr=CryptoJS.AES.decrypt(encryptedStr.encStr,password,{iv:encryptedStr.iv,salt:encryptedStr.salt});return decryptedStr.toString(CryptoJS.enc.Latin1)},legacyGenerateEncKey=function(password,salt,keyHash){var encKey=CryptoJS.PBKDF2(password,salt,{keySize:16,iterations:150}).toString(),hash=CryptoJS.SHA3(encKey).toString();if(keyHash!==hash)throw new Error("Invalid Password");return encKey},upgradeOldSerialized=function(oldSerialized,password,callback){var oldKS=JSON.parse(oldSerialized);if(void 0!==oldKS.version&&1!==oldKS.version)throw new Error("Keystore is not of correct version.");var derivedKey=legacyGenerateEncKey(password,oldKS.salt,oldKS.keyHash),seed=legacyDecryptString(oldKS.encSeed,derivedKey);keystore.deriveKeyFromPassword(password,function(err,pwDerivedKey){var newKeyStore=new keystore(seed,pwDerivedKey),hdIndex=oldKS.hdIndex;newKeyStore.generateNewAddress(pwDerivedKey,hdIndex),callback(null,newKeyStore.serialize())})},module.exports.upgradeOldSerialized=upgradeOldSerialized},{"./keystore":3,"bitcore-lib":7,"bitcore-mnemonic":86,"crypto-js":330,elliptic:356,"ethereumjs-tx":379,"scrypt-async":418,tweetnacl:419}],7:[function(require,module,exports){(function(global,Buffer){"use strict";var bitcore=module.exports;bitcore.version="v"+require("./package.json").version,bitcore.versionGuard=function(version){if(void 0!==version){var message="More than one instance of bitcore-lib found. Please make sure to require bitcore-lib and check that submodules do not also include their own bitcore-lib dependency.";throw new Error(message)}},bitcore.versionGuard(global._bitcore),global._bitcore=bitcore.version,bitcore.crypto={},bitcore.crypto.BN=require("./lib/crypto/bn"),bitcore.crypto.ECDSA=require("./lib/crypto/ecdsa"),bitcore.crypto.Hash=require("./lib/crypto/hash"),bitcore.crypto.Random=require("./lib/crypto/random"),bitcore.crypto.Point=require("./lib/crypto/point"),bitcore.crypto.Signature=require("./lib/crypto/signature"),bitcore.encoding={},bitcore.encoding.Base58=require("./lib/encoding/base58"),bitcore.encoding.Base58Check=require("./lib/encoding/base58check"),bitcore.encoding.BufferReader=require("./lib/encoding/bufferreader"),bitcore.encoding.BufferWriter=require("./lib/encoding/bufferwriter"),bitcore.encoding.Varint=require("./lib/encoding/varint"),bitcore.util={},bitcore.util.buffer=require("./lib/util/buffer"),bitcore.util.js=require("./lib/util/js"),bitcore.util.preconditions=require("./lib/util/preconditions"),bitcore.errors=require("./lib/errors"),bitcore.Address=require("./lib/address"),bitcore.Block=require("./lib/block"),bitcore.MerkleBlock=require("./lib/block/merkleblock"),bitcore.BlockHeader=require("./lib/block/blockheader"),bitcore.HDPrivateKey=require("./lib/hdprivatekey.js"),bitcore.HDPublicKey=require("./lib/hdpublickey.js"),bitcore.Networks=require("./lib/networks"),bitcore.Opcode=require("./lib/opcode"),bitcore.PrivateKey=require("./lib/privatekey"),bitcore.PublicKey=require("./lib/publickey"),bitcore.Script=require("./lib/script"),bitcore.Transaction=require("./lib/transaction"),bitcore.URI=require("./lib/uri"),bitcore.Unit=require("./lib/unit"),bitcore.deps={},bitcore.deps.bnjs=require("bn.js"),bitcore.deps.bs58=require("bs58"),bitcore.deps.Buffer=Buffer,bitcore.deps.elliptic=require("elliptic"),bitcore.deps._=require("lodash"),bitcore._HDKeyCache=require("./lib/hdkeycache"),bitcore.Transaction.sighash=require("./lib/transaction/sighash")}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require("buffer").Buffer)},{"./lib/address":8,"./lib/block":11,"./lib/block/blockheader":10,"./lib/block/merkleblock":12,"./lib/crypto/bn":13,"./lib/crypto/ecdsa":14,"./lib/crypto/hash":15,"./lib/crypto/point":16,"./lib/crypto/random":17,"./lib/crypto/signature":18,"./lib/encoding/base58":19,"./lib/encoding/base58check":20,"./lib/encoding/bufferreader":21,"./lib/encoding/bufferwriter":22,"./lib/encoding/varint":23,"./lib/errors":24,"./lib/hdkeycache":26,"./lib/hdprivatekey.js":27,"./lib/hdpublickey.js":28,"./lib/networks":29,"./lib/opcode":30,"./lib/privatekey":31,"./lib/publickey":32,"./lib/script":33,"./lib/transaction":36,"./lib/transaction/sighash":44,"./lib/unit":48,"./lib/uri":49,"./lib/util/buffer":50,"./lib/util/js":51,"./lib/util/preconditions":52,"./package.json":85,"bn.js":53,bs58:54,buffer:99,elliptic:56,lodash:78}],8:[function(require,module,exports){(function(Buffer){"use strict";function Address(data,network,type){if(!(this instanceof Address))return new Address(data,network,type);if(_.isArray(data)&&_.isNumber(network))return Address.createMultisig(data,network,type);if(data instanceof Address)return data;if($.checkArgument(data,"First argument is required, please include address data.","guide/address.html"),network&&!Networks.get(network))throw new TypeError('Second argument must be "livenet" or "testnet".');if(type&&type!==Address.PayToPublicKeyHash&&type!==Address.PayToScriptHash)throw new TypeError('Third argument must be "pubkeyhash" or "scripthash".');var info=this._classifyArguments(data,network,type);return info.network=info.network||Networks.get(network)||Networks.defaultNetwork,info.type=info.type||type||Address.PayToPublicKeyHash,JSUtil.defineImmutable(this,{hashBuffer:info.hashBuffer,network:info.network,type:info.type}),this}var _=require("lodash"),$=require("./util/preconditions"),errors=require("./errors"),Base58Check=require("./encoding/base58check"),Networks=require("./networks"),Hash=require("./crypto/hash"),JSUtil=require("./util/js"),PublicKey=require("./publickey");Address.prototype._classifyArguments=function(data,network,type){if((data instanceof Buffer||data instanceof Uint8Array)&&20===data.length)return Address._transformHash(data);if((data instanceof Buffer||data instanceof Uint8Array)&&21===data.length)return Address._transformBuffer(data,network,type);if(data instanceof PublicKey)return Address._transformPublicKey(data);if(data instanceof Script)return Address._transformScript(data,network);if("string"==typeof data)return Address._transformString(data,network,type);if(_.isObject(data))return Address._transformObject(data);throw new TypeError("First argument is an unrecognized data format.")},Address.PayToPublicKeyHash="pubkeyhash",Address.PayToScriptHash="scripthash",Address._transformHash=function(hash){var info={};if(!(hash instanceof Buffer||hash instanceof Uint8Array))throw new TypeError("Address supplied is not a buffer.");if(20!==hash.length)throw new TypeError("Address hashbuffers must be exactly 20 bytes.");return info.hashBuffer=hash,info},Address._transformObject=function(data){return $.checkArgument(data.hash||data.hashBuffer,"Must provide a `hash` or `hashBuffer` property"),$.checkArgument(data.type,"Must provide a `type` property"),{hashBuffer:data.hash?new Buffer(data.hash,"hex"):data.hashBuffer,network:Networks.get(data.network)||Networks.defaultNetwork,type:data.type}},Address._classifyFromVersion=function(buffer){var version={},pubkeyhashNetwork=Networks.get(buffer[0],"pubkeyhash"),scripthashNetwork=Networks.get(buffer[0],"scripthash");return pubkeyhashNetwork?(version.network=pubkeyhashNetwork,version.type=Address.PayToPublicKeyHash):scripthashNetwork&&(version.network=scripthashNetwork,version.type=Address.PayToScriptHash),version},Address._transformBuffer=function(buffer,network,type){var info={};if(!(buffer instanceof Buffer||buffer instanceof Uint8Array))throw new TypeError("Address supplied is not a buffer.");if(21!==buffer.length)throw new TypeError("Address buffers must be exactly 21 bytes.");network=Networks.get(network);var bufferVersion=Address._classifyFromVersion(buffer);if(!bufferVersion.network||network&&network!==bufferVersion.network)throw new TypeError("Address has mismatched network type.");if(!bufferVersion.type||type&&type!==bufferVersion.type)throw new TypeError("Address has mismatched type.");return info.hashBuffer=buffer.slice(1),info.network=bufferVersion.network,info.type=bufferVersion.type,info},Address._transformPublicKey=function(pubkey){var info={};if(!(pubkey instanceof PublicKey))throw new TypeError("Address must be an instance of PublicKey.");return info.hashBuffer=Hash.sha256ripemd160(pubkey.toBuffer()),info.type=Address.PayToPublicKeyHash,info},Address._transformScript=function(script,network){$.checkArgument(script instanceof Script,"script must be a Script instance");var info=script.getAddressInfo(network);if(!info)throw new errors.Script.CantDeriveAddress(script);return info},Address.createMultisig=function(publicKeys,threshold,network){return network=network||publicKeys[0].network||Networks.defaultNetwork,Address.payingTo(Script.buildMultisigOut(publicKeys,threshold),network)},Address._transformString=function(data,network,type){if("string"!=typeof data)throw new TypeError("data parameter supplied is not a string.");data=data.trim();var addressBuffer=Base58Check.decode(data),info=Address._transformBuffer(addressBuffer,network,type);return info},Address.fromPublicKey=function(data,network){var info=Address._transformPublicKey(data);return network=network||Networks.defaultNetwork,new Address(info.hashBuffer,network,info.type)},Address.fromPublicKeyHash=function(hash,network){var info=Address._transformHash(hash);return new Address(info.hashBuffer,network,Address.PayToPublicKeyHash)},Address.fromScriptHash=function(hash,network){$.checkArgument(hash,"hash parameter is required");var info=Address._transformHash(hash);return new Address(info.hashBuffer,network,Address.PayToScriptHash)},Address.payingTo=function(script,network){return $.checkArgument(script,"script is required"),$.checkArgument(script instanceof Script,"script must be instance of Script"),Address.fromScriptHash(Hash.sha256ripemd160(script.toBuffer()),network)},Address.fromScript=function(script,network){$.checkArgument(script instanceof Script,"script must be a Script instance");var info=Address._transformScript(script,network);return new Address(info.hashBuffer,network,info.type)},Address.fromBuffer=function(buffer,network,type){ var info=Address._transformBuffer(buffer,network,type);return new Address(info.hashBuffer,info.network,info.type)},Address.fromString=function(str,network,type){var info=Address._transformString(str,network,type);return new Address(info.hashBuffer,info.network,info.type)},Address.fromObject=function(obj){$.checkState(JSUtil.isHexa(obj.hash),'Unexpected hash property, "'+obj.hash+'", expected to be hex.');var hashBuffer=new Buffer(obj.hash,"hex");return new Address(hashBuffer,obj.network,obj.type)},Address.getValidationError=function(data,network,type){var error;try{new Address(data,network,type)}catch(e){error=e}return error},Address.isValid=function(data,network,type){return!Address.getValidationError(data,network,type)},Address.prototype.isPayToPublicKeyHash=function(){return this.type===Address.PayToPublicKeyHash},Address.prototype.isPayToScriptHash=function(){return this.type===Address.PayToScriptHash},Address.prototype.toBuffer=function(){var version=new Buffer([this.network[this.type]]),buf=Buffer.concat([version,this.hashBuffer]);return buf},Address.prototype.toObject=Address.prototype.toJSON=function(){return{hash:this.hashBuffer.toString("hex"),type:this.type,network:this.network.toString()}},Address.prototype.toString=function(){return Base58Check.encode(this.toBuffer())},Address.prototype.inspect=function(){return"<Address: "+this.toString()+", type: "+this.type+", network: "+this.network+">"},module.exports=Address;var Script=require("./script")}).call(this,require("buffer").Buffer)},{"./crypto/hash":15,"./encoding/base58check":20,"./errors":24,"./networks":29,"./publickey":32,"./script":33,"./util/js":51,"./util/preconditions":52,buffer:99,lodash:78}],9:[function(require,module,exports){(function(Buffer){"use strict";function Block(arg){return this instanceof Block?(_.extend(this,Block._from(arg)),this):new Block(arg)}var _=require("lodash"),BlockHeader=require("./blockheader"),BN=require("../crypto/bn"),BufferUtil=require("../util/buffer"),BufferReader=require("../encoding/bufferreader"),BufferWriter=require("../encoding/bufferwriter"),Hash=require("../crypto/hash"),Transaction=require("../transaction"),$=require("../util/preconditions");Block.MAX_BLOCK_SIZE=1e6,Block._from=function(arg){var info={};if(BufferUtil.isBuffer(arg))info=Block._fromBufferReader(BufferReader(arg));else{if(!_.isObject(arg))throw new TypeError("Unrecognized argument for Block");info=Block._fromObject(arg)}return info},Block._fromObject=function(data){var transactions=[];data.transactions.forEach(function(tx){tx instanceof Transaction?transactions.push(tx):transactions.push(Transaction().fromObject(tx))});var info={header:BlockHeader.fromObject(data.header),transactions:transactions};return info},Block.fromObject=function(obj){var info=Block._fromObject(obj);return new Block(info)},Block._fromBufferReader=function(br){var info={};$.checkState(!br.finished(),"No block data received"),info.header=BlockHeader.fromBufferReader(br);var transactions=br.readVarintNum();info.transactions=[];for(var i=0;transactions>i;i++)info.transactions.push(Transaction().fromBufferReader(br));return info},Block.fromBufferReader=function(br){$.checkArgument(br,"br is required");var info=Block._fromBufferReader(br);return new Block(info)},Block.fromBuffer=function(buf){return Block.fromBufferReader(new BufferReader(buf))},Block.fromString=function(str){var buf=new Buffer(str,"hex");return Block.fromBuffer(buf)},Block.fromRawBlock=function(data){BufferUtil.isBuffer(data)||(data=new Buffer(data,"binary"));var br=BufferReader(data);br.pos=Block.Values.START_OF_BLOCK;var info=Block._fromBufferReader(br);return new Block(info)},Block.prototype.toObject=Block.prototype.toJSON=function(){var transactions=[];return this.transactions.forEach(function(tx){transactions.push(tx.toObject())}),{header:this.header.toObject(),transactions:transactions}},Block.prototype.toBuffer=function(){return this.toBufferWriter().concat()},Block.prototype.toString=function(){return this.toBuffer().toString("hex")},Block.prototype.toBufferWriter=function(bw){bw||(bw=new BufferWriter),bw.write(this.header.toBuffer()),bw.writeVarintNum(this.transactions.length);for(var i=0;i<this.transactions.length;i++)this.transactions[i].toBufferWriter(bw);return bw},Block.prototype.getTransactionHashes=function(){var hashes=[];if(0===this.transactions.length)return[Block.Values.NULL_HASH];for(var t=0;t<this.transactions.length;t++)hashes.push(this.transactions[t]._getHash());return hashes},Block.prototype.getMerkleTree=function(){for(var tree=this.getTransactionHashes(),j=0,size=this.transactions.length;size>1;size=Math.floor((size+1)/2)){for(var i=0;size>i;i+=2){var i2=Math.min(i+1,size-1),buf=Buffer.concat([tree[j+i],tree[j+i2]]);tree.push(Hash.sha256sha256(buf))}j+=size}return tree},Block.prototype.getMerkleRoot=function(){var tree=this.getMerkleTree();return tree[tree.length-1]},Block.prototype.validMerkleRoot=function(){var h=new BN(this.header.merkleRoot.toString("hex"),"hex"),c=new BN(this.getMerkleRoot().toString("hex"),"hex");return 0===h.cmp(c)},Block.prototype._getHash=function(){return this.header._getHash()};var idProperty={configurable:!1,enumerable:!0,get:function(){return this._id||(this._id=this.header.id),this._id},set:_.noop};Object.defineProperty(Block.prototype,"id",idProperty),Object.defineProperty(Block.prototype,"hash",idProperty),Block.prototype.inspect=function(){return"<Block "+this.id+">"},Block.Values={START_OF_BLOCK:8,NULL_HASH:new Buffer("0000000000000000000000000000000000000000000000000000000000000000","hex")},module.exports=Block}).call(this,require("buffer").Buffer)},{"../crypto/bn":13,"../crypto/hash":15,"../encoding/bufferreader":21,"../encoding/bufferwriter":22,"../transaction":36,"../util/buffer":50,"../util/preconditions":52,"./blockheader":10,buffer:99,lodash:78}],10:[function(require,module,exports){(function(Buffer){"use strict";var _=require("lodash"),BN=require("../crypto/bn"),BufferUtil=require("../util/buffer"),BufferReader=require("../encoding/bufferreader"),BufferWriter=require("../encoding/bufferwriter"),Hash=require("../crypto/hash"),$=(require("../util/js"),require("../util/preconditions")),GENESIS_BITS=486604799,BlockHeader=function BlockHeader(arg){if(!(this instanceof BlockHeader))return new BlockHeader(arg);var info=BlockHeader._from(arg);return this.version=info.version,this.prevHash=info.prevHash,this.merkleRoot=info.merkleRoot,this.time=info.time,this.timestamp=info.time,this.bits=info.bits,this.nonce=info.nonce,info.hash&&$.checkState(this.hash===info.hash,"Argument object hash property does not match block hash."),this};BlockHeader._from=function(arg){var info={};if(BufferUtil.isBuffer(arg))info=BlockHeader._fromBufferReader(BufferReader(arg));else{if(!_.isObject(arg))throw new TypeError("Unrecognized argument for BlockHeader");info=BlockHeader._fromObject(arg)}return info},BlockHeader._fromObject=function(data){$.checkArgument(data,"data is required");var prevHash=data.prevHash,merkleRoot=data.merkleRoot;_.isString(data.prevHash)&&(prevHash=BufferUtil.reverse(new Buffer(data.prevHash,"hex"))),_.isString(data.merkleRoot)&&(merkleRoot=BufferUtil.reverse(new Buffer(data.merkleRoot,"hex")));var info={hash:data.hash,version:data.version,prevHash:prevHash,merkleRoot:merkleRoot,time:data.time,timestamp:data.time,bits:data.bits,nonce:data.nonce};return info},BlockHeader.fromObject=function(obj){var info=BlockHeader._fromObject(obj);return new BlockHeader(info)},BlockHeader.fromRawBlock=function(data){BufferUtil.isBuffer(data)||(data=new Buffer(data,"binary"));var br=BufferReader(data);br.pos=BlockHeader.Constants.START_OF_HEADER;var info=BlockHeader._fromBufferReader(br);return new BlockHeader(info)},BlockHeader.fromBuffer=function(buf){var info=BlockHeader._fromBufferReader(BufferReader(buf));return new BlockHeader(info)},BlockHeader.fromString=function(str){var buf=new Buffer(str,"hex");return BlockHeader.fromBuffer(buf)},BlockHeader._fromBufferReader=function(br){var info={};return info.version=br.readUInt32LE(),info.prevHash=br.read(32),info.merkleRoot=br.read(32),info.time=br.readUInt32LE(),info.bits=br.readUInt32LE(),info.nonce=br.readUInt32LE(),info},BlockHeader.fromBufferReader=function(br){var info=BlockHeader._fromBufferReader(br);return new BlockHeader(info)},BlockHeader.prototype.toObject=BlockHeader.prototype.toJSON=function(){return{hash:this.hash,version:this.version,prevHash:BufferUtil.reverse(this.prevHash).toString("hex"),merkleRoot:BufferUtil.reverse(this.merkleRoot).toString("hex"),time:this.time,bits:this.bits,nonce:this.nonce}},BlockHeader.prototype.toBuffer=function(){return this.toBufferWriter().concat()},BlockHeader.prototype.toString=function(){return this.toBuffer().toString("hex")},BlockHeader.prototype.toBufferWriter=function(bw){return bw||(bw=new BufferWriter),bw.writeUInt32LE(this.version),bw.write(this.prevHash),bw.write(this.merkleRoot),bw.writeUInt32LE(this.time),bw.writeUInt32LE(this.bits),bw.writeUInt32LE(this.nonce),bw},BlockHeader.prototype.getTargetDifficulty=function(bits){bits=bits||this.bits;for(var target=new BN(16777215&bits),mov=8*((bits>>>24)-3);mov-- >0;)target=target.mul(new BN(2));return target},BlockHeader.prototype.getDifficulty=function(){var difficulty1TargetBN=this.getTargetDifficulty(GENESIS_BITS).mul(new BN(Math.pow(10,8))),currentTargetBN=this.getTargetDifficulty(),difficultyString=difficulty1TargetBN.div(currentTargetBN).toString(10),decimalPos=difficultyString.length-8;return difficultyString=difficultyString.slice(0,decimalPos)+"."+difficultyString.slice(decimalPos),parseFloat(difficultyString)},BlockHeader.prototype._getHash=function(){var buf=this.toBuffer();return Hash.sha256sha256(buf)};var idProperty={configurable:!1,enumerable:!0,get:function(){return this._id||(this._id=BufferReader(this._getHash()).readReverse().toString("hex")),this._id},set:_.noop};Object.defineProperty(BlockHeader.prototype,"id",idProperty),Object.defineProperty(BlockHeader.prototype,"hash",idProperty),BlockHeader.prototype.validTimestamp=function(){var currentTime=Math.round((new Date).getTime()/1e3);return!(this.time>currentTime+BlockHeader.Constants.MAX_TIME_OFFSET)},BlockHeader.prototype.validProofOfWork=function(){var pow=new BN(this.id,"hex"),target=this.getTargetDifficulty();return!(pow.cmp(target)>0)},BlockHeader.prototype.inspect=function(){return"<BlockHeader "+this.id+">"},BlockHeader.Constants={START_OF_HEADER:8,MAX_TIME_OFFSET:7200,LARGEST_HASH:new BN("10000000000000000000000000000000000000000000000000000000000000000","hex")},module.exports=BlockHeader}).call(this,require("buffer").Buffer)},{"../crypto/bn":13,"../crypto/hash":15,"../encoding/bufferreader":21,"../encoding/bufferwriter":22,"../util/buffer":50,"../util/js":51,"../util/preconditions":52,buffer:99,lodash:78}],11:[function(require,module,exports){module.exports=require("./block"),module.exports.BlockHeader=require("./blockheader"),module.exports.MerkleBlock=require("./merkleblock")},{"./block":9,"./blockheader":10,"./merkleblock":12}],12:[function(require,module,exports){(function(Buffer){"use strict";function MerkleBlock(arg){if(!(this instanceof MerkleBlock))return new MerkleBlock(arg);var info={};if(BufferUtil.isBuffer(arg))info=MerkleBlock._fromBufferReader(BufferReader(arg));else{if(!_.isObject(arg))throw new TypeError("Unrecognized argument for MerkleBlock");var header;header=arg.header instanceof BlockHeader?arg.header:BlockHeader.fromObject(arg.header),info={header:header,numTransactions:arg.numTransactions,hashes:arg.hashes,flags:arg.flags}}return _.extend(this,info),this._flagBitsUsed=0,this._hashesUsed=0,this}var _=require("lodash"),BlockHeader=require("./blockheader"),BufferUtil=require("../util/buffer"),BufferReader=require("../encoding/bufferreader"),BufferWriter=require("../encoding/bufferwriter"),Hash=require("../crypto/hash"),Transaction=(require("../util/js"),require("../transaction")),$=require("../util/preconditions");MerkleBlock.fromBuffer=function(buf){return MerkleBlock.fromBufferReader(BufferReader(buf))},MerkleBlock.fromBufferReader=function(br){return new MerkleBlock(MerkleBlock._fromBufferReader(br))},MerkleBlock.prototype.toBuffer=function(){return this.toBufferWriter().concat()},MerkleBlock.prototype.toBufferWriter=function(bw){bw||(bw=new BufferWriter),bw.write(this.header.toBuffer()),bw.writeUInt32LE(this.numTransactions),bw.writeVarintNum(this.hashes.length);for(var i=0;i<this.hashes.length;i++)bw.write(new Buffer(this.hashes[i],"hex"));for(bw.writeVarintNum(this.flags.length),i=0;i<this.flags.length;i++)bw.writeUInt8(this.flags[i]);return bw},MerkleBlock.prototype.toObject=MerkleBlock.prototype.toJSON=function(){return{header:this.header.toObject(),numTransactions:this.numTransactions,hashes:this.hashes,flags:this.flags}},MerkleBlock.prototype.validMerkleTree=function(){if($.checkState(_.isArray(this.flags),"MerkleBlock flags is not an array"),$.checkState(_.isArray(this.hashes),"MerkleBlock hashes is not an array"),this.hashes.length>this.numTransactions)return!1;if(8*this.flags.length<this.hashes.length)return!1;var height=this._calcTreeHeight(),opts={hashesUsed:0,flagBitsUsed:0},root=this._traverseMerkleTree(height,0,opts);return opts.hashesUsed!==this.hashes.length?!1:BufferUtil.equals(root,this.header.merkleRoot)},MerkleBlock.prototype._traverseMerkleTree=function(depth,pos,opts){if(opts=opts||{},opts.txs=opts.txs||[],opts.flagBitsUsed=opts.flagBitsUsed||0,opts.hashesUsed=opts.hashesUsed||0,opts.flagBitsUsed>8*this.flags.length)return null;var isParentOfMatch=this.flags[opts.flagBitsUsed>>3]>>>(7&opts.flagBitsUsed++)&1;if(0!==depth&&isParentOfMatch){var left=this._traverseMerkleTree(depth-1,2*pos,opts),right=left;return 2*pos+1<this._calcTreeWidth(depth-1)&&(right=this._traverseMerkleTree(depth-1,2*pos+1,opts)),Hash.sha256sha256(new Buffer.concat([left,right]))}if(opts.hashesUsed>=this.hashes.length)return null;var hash=this.hashes[opts.hashesUsed++];return 0===depth&&isParentOfMatch&&opts.txs.push(hash),new Buffer(hash,"hex")},MerkleBlock.prototype._calcTreeWidth=function(height){return this.numTransactions+(1<<height)-1>>height},MerkleBlock.prototype._calcTreeHeight=function(){for(var height=0;this._calcTreeWidth(height)>1;)height++;return height},MerkleBlock.prototype.hasTransaction=function(tx){$.checkArgument(!_.isUndefined(tx),"tx cannot be undefined"),$.checkArgument(tx instanceof Transaction||"string"==typeof tx,'Invalid tx given, tx must be a "string" or "Transaction"');var hash=tx;tx instanceof Transaction&&(hash=BufferUtil.reverse(new Buffer(tx.id,"hex")).toString("hex"));var txs=[],height=this._calcTreeHeight();return this._traverseMerkleTree(height,0,{txs:txs}),-1!==txs.indexOf(hash)},MerkleBlock._fromBufferReader=function(br){$.checkState(!br.finished(),"No merkleblock data received");var info={};info.header=BlockHeader.fromBufferReader(br),info.numTransactions=br.readUInt32LE();var numHashes=br.readVarintNum();info.hashes=[];for(var i=0;numHashes>i;i++)info.hashes.push(br.read(32).toString("hex"));var numFlags=br.readVarintNum();for(info.flags=[],i=0;numFlags>i;i++)info.flags.push(br.readUInt8());return info},MerkleBlock.fromObject=function(obj){return new MerkleBlock(obj)},module.exports=MerkleBlock}).call(this,require("buffer").Buffer)},{"../crypto/hash":15,"../encoding/bufferreader":21,"../encoding/bufferwriter":22,"../transaction":36,"../util/buffer":50,"../util/js":51,"../util/preconditions":52,"./blockheader":10,buffer:99,lodash:78}],13:[function(require,module,exports){(function(Buffer){"use strict";var BN=require("bn.js"),$=require("../util/preconditions"),_=require("lodash"),reversebuf=function(buf){for(var buf2=new Buffer(buf.length),i=0;i<buf.length;i++)buf2[i]=buf[buf.length-1-i];return buf2};BN.Zero=new BN(0),BN.One=new BN(1),BN.Minus1=new BN(-1),BN.fromNumber=function(n){return $.checkArgument(_.isNumber(n)),new BN(n)},BN.fromString=function(str,base){return $.checkArgument(_.isString(str)),new BN(str,base)},BN.fromBuffer=function(buf,opts){"undefined"!=typeof opts&&"little"===opts.endian&&(buf=reversebuf(buf));var hex=buf.toString("hex"),bn=new BN(hex,16);return bn},BN.fromSM=function(buf,opts){var ret;if(0===buf.length)return BN.fromBuffer(new Buffer([0]));var endian="big";return opts&&(endian=opts.endian),"little"===endian&&(buf=reversebuf(buf)),128&buf[0]?(buf[0]=127&buf[0],ret=BN.fromBuffer(buf),ret.neg().copy(ret)):ret=BN.fromBuffer(buf),ret},BN.prototype.toNumber=function(){return parseInt(this.toString(10),10)},BN.prototype.toBuffer=function(opts){var buf,hex;if(opts&&opts.size){hex=this.toString(16,2);var natlen=hex.length/2;buf=new Buffer(hex,"hex"),natlen===opts.size?buf=buf:natlen>opts.size?buf=BN.trim(buf,natlen):natlen<opts.size&&(buf=BN.pad(buf,natlen,opts.size))}else hex=this.toString(16,2),buf=new Buffer(hex,"hex");return"undefined"!=typeof opts&&"little"===opts.endian&&(buf=reversebuf(buf)),buf},BN.prototype.toSMBigEndian=function(){var buf;return-1===this.cmp(BN.Zero)?(buf=this.neg().toBuffer(),128&buf[0]?buf=Buffer.concat([new Buffer([128]),buf]):buf[0]=128|buf[0]):(buf=this.toBuffer(),128&buf[0]&&(buf=Buffer.concat([new Buffer([0]),buf]))),1===buf.length&0===buf[0]&&(buf=new Buffer([])),buf},BN.prototype.toSM=function(opts){var endian=opts?opts.endian:"big",buf=this.toSMBigEndian();return"little"===endian&&(buf=reversebuf(buf)),buf},BN.fromScriptNumBuffer=function(buf,fRequireMinimal,size){var nMaxNumSize=size||4;if($.checkArgument(buf.length<=nMaxNumSize,new Error("script number overflow")),fRequireMinimal&&buf.length>0&&0===(127&buf[buf.length-1])&&(buf.length<=1||0===(128&buf[buf.length-2])))throw new Error("non-minimally encoded script number");return BN.fromSM(buf,{endian:"little"})},BN.prototype.toScriptNumBuffer=function(){return this.toSM({endian:"little"})},BN.prototype.gt=function(b){return this.cmp(b)>0},BN.prototype.gte=function(b){return this.cmp(b)>=0},BN.prototype.lt=function(b){return this.cmp(b)<0},BN.trim=function(buf,natlen){return buf.slice(natlen-