eth-lightwallet
Version:
A lightweight ethereum javascript wallet.
1 lines • 1.41 MB
JavaScript
!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).lightwallet=f()}}(function(){var define,module,exports;return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){"use strict";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":3,"./lib/keystore.js":4,"./lib/signing.js":5,"./lib/txutils.js":6,"./lib/upgrade.js":7}],2:[function(require,module,exports){"use strict";module.exports={derivedKey:function(keystore,pwDerivedKey){if(!keystore.isDerivedKeyCorrect(pwDerivedKey))throw new Error("Incorrect derived key!")}}},{}],3:[function(require,module,exports){(function(Buffer){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);return Object.getOwnPropertySymbols&&keys.push.apply(keys,Object.getOwnPropertySymbols(object)),enumerableOnly&&(keys=keys.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _objectWithoutProperties(source,excluded){if(null==source)return{};var key,i,target=function(source,excluded){if(null==source)return{};var key,i,target={},sourceKeys=Object.keys(source);for(i=0;i<sourceKeys.length;i++)key=sourceKeys[i],0<=excluded.indexOf(key)||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++)key=sourceSymbolKeys[i],0<=excluded.indexOf(key)||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}var Nacl=require("tweetnacl"),NaclUtil=require("tweetnacl-util"),Assert=require("./assert");function encodeHex(msgUInt8Arr){var msgBase64=NaclUtil.encodeBase64(msgUInt8Arr);return new Buffer(msgBase64,"base64").toString("hex")}function decodeHex(msgHex){var msgBase64=new Buffer(msgHex,"hex").toString("base64");return NaclUtil.decodeBase64(msgBase64)}function asymEncryptRaw(keystore,pwDerivedKey,msgUint8Array,myAddress,theirPubKey){Assert.derivedKey(keystore,pwDerivedKey);var privateKeyUInt8Array=decodeHex(keystore.exportPrivateKey(myAddress,pwDerivedKey)),pubKeyUInt8Array=decodeHex(theirPubKey),nonce=Nacl.randomBytes(Nacl.box.nonceLength),encryptedMessage=Nacl.box(msgUint8Array,nonce,pubKeyUInt8Array,privateKeyUInt8Array);return{alg:"curve25519-xsalsa20-poly1305",nonce:NaclUtil.encodeBase64(nonce),ciphertext:NaclUtil.encodeBase64(encryptedMessage)}}function asymDecryptRaw(keystore,pwDerivedKey,encMsg,theirPubKey,myAddress){Assert.derivedKey(keystore,pwDerivedKey);var privateKeyUInt8Array=decodeHex(keystore.exportPrivateKey(myAddress,pwDerivedKey)),pubKeyUInt8Array=decodeHex(theirPubKey),nonce=NaclUtil.decodeBase64(encMsg.nonce),cipherText=NaclUtil.decodeBase64(encMsg.ciphertext);return Nacl.box.open(cipherText,nonce,pubKeyUInt8Array,privateKeyUInt8Array)}module.exports={encodeHex:encodeHex,decodeHex:decodeHex,asymEncryptString:function(keystore,pwDerivedKey,msg,myAddress,theirPubKey){return Assert.derivedKey(keystore,pwDerivedKey),asymEncryptRaw(keystore,pwDerivedKey,NaclUtil.decodeUTF8(msg),myAddress,theirPubKey)},asymDecryptString:function(keystore,pwDerivedKey,encMsg,theirPubKey,myAddress){Assert.derivedKey(keystore,pwDerivedKey);var clearText=asymDecryptRaw(keystore,pwDerivedKey,encMsg,theirPubKey,myAddress);return null!==clearText&&NaclUtil.encodeUTF8(clearText)},multiEncryptString:function(keystore,pwDerivedKey,msg,myAddress,theirPubKeyArray){Assert.derivedKey(keystore,pwDerivedKey);var messageUInt8Array=NaclUtil.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=theirPubKeyArray.map(function(theirPubKey){var _asymEncryptRaw=asymEncryptRaw(keystore,pwDerivedKey,symEncryptionKey,myAddress,theirPubKey);return _asymEncryptRaw.alg,function(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(source,!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(source).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target}({},_objectWithoutProperties(_asymEncryptRaw,["alg"]))});return{version:1,asymAlg:"curve25519-xsalsa20-poly1305",symAlg:"xsalsa20-poly1305",symNonce:NaclUtil.encodeBase64(symNonce),symEncMessage:NaclUtil.encodeBase64(symEncMessage),encryptedSymKey:encryptedSymKey}},multiDecryptString:function(keystore,pwDerivedKey,encMsg,theirPubKey,myAddress){Assert.derivedKey(keystore,pwDerivedKey);for(var symKey=null,i=0;i<encMsg.encryptedSymKey.length;i++){var result=asymDecryptRaw(keystore,pwDerivedKey,encMsg.encryptedSymKey[i],theirPubKey,myAddress);if(null!==result){symKey=result;break}}if(null===symKey)return!1;var symNonce=NaclUtil.decodeBase64(encMsg.symNonce),symEncMessage=NaclUtil.decodeBase64(encMsg.symEncMessage),msg=Nacl.secretbox.open(symEncMessage,symNonce,symKey);return null!==msg&&NaclUtil.encodeUTF8(msg)},addressToPublicEncKey:function(keystore,pwDerivedKey,address){Assert.derivedKey(keystore,pwDerivedKey);var privateKeyUInt8Array=decodeHex(keystore.exportPrivateKey(address,pwDerivedKey));return encodeHex(Nacl.box.keyPair.fromSecretKey(privateKeyUInt8Array).publicKey)}}}).call(this,require("buffer").Buffer)},{"./assert":2,buffer:138,tweetnacl:311,"tweetnacl-util":310}],4:[function(require,module,exports){(function(Buffer){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);return Object.getOwnPropertySymbols&&keys.push.apply(keys,Object.getOwnPropertySymbols(object)),enumerableOnly&&(keys=keys.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _objectWithoutProperties(source,excluded){if(null==source)return{};var key,i,target=function(source,excluded){if(null==source)return{};var key,i,target={},sourceKeys=Object.keys(source);for(i=0;i<sourceKeys.length;i++)key=sourceKeys[i],0<=excluded.indexOf(key)||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++)key=sourceSymbolKeys[i],0<=excluded.indexOf(key)||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}var CryptoJS=require("crypto-js"),Util=require("ethereumjs-util"),EC=require("elliptic").ec,BitCore=require("bitcore-lib"),Random=BitCore.crypto.Random,Hash=BitCore.crypto.Hash,Mnemonic=require("bitcore-mnemonic"),Nacl=require("tweetnacl"),NaclUtil=require("tweetnacl-util"),ScryptAsync=require("scrypt-async"),Assert=require("./assert"),Encryption=require("./encryption"),Signing=require("./signing"),TxUtils=require("./txutils"),ec=new EC("secp256k1");function leftPadString(stringToPad,padChar,length){for(var repeatedPadChar="",i=0;i<length;i++)repeatedPadChar+=padChar;return(repeatedPadChar+stringToPad).slice(-length)}var KeyStore=function(){};KeyStore.prototype.init=function(mnemonic,pwDerivedKey,hdPathString,salt){if(this.salt=salt,this.hdPathString=hdPathString,this.encSeed=void 0,this.encHdRootPriv=void 0,this.version=3,this.hdIndex=0,this.encPrivKeys={},this.addresses=[],void 0!==pwDerivedKey&&void 0!==mnemonic){var words=mnemonic.split(" ");if(!KeyStore.isSeedValid(mnemonic)||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,hdPathKey=new BitCore.HDPrivateKey(hdRoot).derive(hdPathString).xprivkey;this.encHdRootPriv=KeyStore._encryptString(hdPathKey,pwDerivedKey)}},KeyStore.prototype.isDerivedKeyCorrect=function(pwDerivedKey){var paddedSeed=KeyStore._decryptString(this.encSeed,pwDerivedKey);return paddedSeed&&0<paddedSeed.length},KeyStore.prototype.serialize=function(){return JSON.stringify({encSeed:this.encSeed,encHdRootPriv:this.encHdRootPriv,addresses:this.addresses,encPrivKeys:this.encPrivKeys,hdPathString:this.hdPathString,salt:this.salt,hdIndex:this.hdIndex,version:this.version})},KeyStore.prototype.getAddresses=function(){return this.addresses.map(function(addr){return Util.addHexPrefix(addr)})},KeyStore.prototype.getSeed=function(pwDerivedKey){Assert.derivedKey(this,pwDerivedKey);var paddedSeed=KeyStore._decryptString(this.encSeed,pwDerivedKey);if(!paddedSeed||0===paddedSeed.length)throw new Error("Provided password derived key is wrong");return paddedSeed.trim()},KeyStore.prototype.exportPrivateKey=function(address,pwDerivedKey){Assert.derivedKey(this,pwDerivedKey);var addr=Util.stripHexPrefix(address).toLowerCase();if(void 0===this.encPrivKeys[addr])throw new Error("KeyStore.exportPrivateKey: Address not found in KeyStore");var encPrivateKey=this.encPrivKeys[addr];return KeyStore._decryptKey(encPrivateKey,pwDerivedKey)},KeyStore.prototype.generateNewAddress=function(pwDerivedKey,n){if(Assert.derivedKey(this,pwDerivedKey),!this.encSeed)throw new Error("KeyStore.generateNewAddress: No seed set");n=n||1;for(var keys=this._generatePrivKeys(pwDerivedKey,n),i=0;i<n;i++){var keyObj=keys[i],address=KeyStore._computeAddressFromPrivKey(keyObj.privKey);this.encPrivKeys[address]=keyObj.encPrivKey,this.addresses.push(address)}},KeyStore.prototype.keyFromPassword=function(password,callback){KeyStore.deriveKeyFromPasswordAndSalt(password,this.salt,callback)},KeyStore.prototype.passwordProvider=function(callback){callback(null,prompt("Enter password to continue","Enter password"))},KeyStore.prototype.hasAddress=function(address,callback){var addrToCheck=Util.stripHexPrefix(address);void 0!==this.encPrivKeys[addrToCheck]?callback(null,!0):callback(new Error("Address not found!"),!1)},KeyStore.prototype.signTransaction=function(txParams,callback){var _this=this,gas=txParams.gas,txObj=function(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(source,!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(source).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target}({},_objectWithoutProperties(txParams,["gas"]),{gasLimit:gas}),tx=TxUtils.createTx(txObj),rawTx=TxUtils.txToHexString(tx),signingAddress=Util.stripHexPrefix(txParams.from);this.passwordProvider(function(err,password){err?callback(err):_this.keyFromPassword(password,function(err,pwDerivedKey){if(err)callback(err);else{var signedTx=Signing.signTx(_this,pwDerivedKey,rawTx,signingAddress);callback(null,Util.addHexPrefix(signedTx))}})})},KeyStore.prototype._generatePrivKeys=function(pwDerivedKey,n){Assert.derivedKey(this,pwDerivedKey);var hdRoot=KeyStore._decryptString(this.encHdRootPriv,pwDerivedKey);if(!hdRoot||0===hdRoot.length)throw new Error("Provided password derived key is wrong");for(var keys=[],i=0;i<n;i++){var privateKeyBuf=new BitCore.HDPrivateKey(hdRoot).derive(this.hdIndex++).privateKey.toBuffer(),privateKeyHex=privateKeyBuf.toString("hex");if(privateKeyBuf.length<16)throw new Error("Private key suspiciously small: < 16 bytes. Aborting!");if(32<privateKeyBuf.length)throw new Error("Private key larger than 32 bytes. Aborting!");privateKeyBuf.length<32&&(privateKeyHex=leftPadString(privateKeyBuf.toString("hex"),"0",64));var encPrivateKey=KeyStore._encryptKey(privateKeyHex,pwDerivedKey);keys[i]={privKey:privateKeyHex,encPrivKey:encPrivateKey}}return keys},KeyStore.createVault=function(opts,cb){var hdPathString=opts.hdPathString,seedPhrase=opts.seedPhrase,password=opts.password,salt=opts.salt;if(!hdPathString){var err=new Error("Keystore: Must include hdPathString in createVault inputs. Suggested alternatives are m/0'/0'/0' for previous lightwallet default, or m/44'/60'/0'/0 for BIP44 (used by Jaxx & MetaMask)");return cb(err)}if(!seedPhrase){var _err=new Error("Keystore: Must include seedPhrase in createVault inputs.");return cb(_err)}salt||(salt=KeyStore.generateSalt(32)),KeyStore.deriveKeyFromPasswordAndSalt(password,salt,function(err,pwDerivedKey){if(err)cb(err);else{var ks=new KeyStore;ks.init(seedPhrase,pwDerivedKey,hdPathString,salt),cb(null,ks)}})},KeyStore.generateSalt=function(byteCount){return BitCore.crypto.Random.getRandomBuffer(byteCount||32).toString("base64")},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.deserialize=function(keystore){var dataKS=JSON.parse(keystore),version=dataKS.version,salt=dataKS.salt,encSeed=dataKS.encSeed,encHdRootPriv=dataKS.encHdRootPriv,encPrivKeys=dataKS.encPrivKeys,hdIndex=dataKS.hdIndex,hdPathString=dataKS.hdPathString,addresses=dataKS.addresses;if(void 0===version||version<3)throw new Error("Old version of serialized keystore. Please use KeyStore.upgradeOldSerialized() to convert it to the latest version.");var ks=new KeyStore;return ks.salt=salt,ks.hdPathString=hdPathString,ks.encSeed=encSeed,ks.encHdRootPriv=encHdRootPriv,ks.version=version,ks.hdIndex=hdIndex,ks.encPrivKeys=encPrivKeys,ks.addresses=addresses,ks},KeyStore.deriveKeyFromPasswordAndSalt=function(password,salt,callback){callback||"function"!=typeof salt?salt||"function"!=typeof callback||(salt=KeyStore.DEFAULT_SALT):(callback=salt,salt=KeyStore.DEFAULT_SALT);ScryptAsync(password,salt,14,8,32,200,function(derKey){var err=null,ui8arr=null;try{ui8arr=new Uint8Array(derKey)}catch(e){err=e}callback(err,ui8arr)},null)},KeyStore._encryptString=function(string,pwDerivedKey){var nonce=Nacl.randomBytes(Nacl.secretbox.nonceLength),encStr=Nacl.secretbox(NaclUtil.decodeUTF8(string),nonce,pwDerivedKey);return{encStr:NaclUtil.encodeBase64(encStr),nonce:NaclUtil.encodeBase64(nonce)}},KeyStore._decryptString=function(encryptedStr,pwDerivedKey){var decStr=NaclUtil.decodeBase64(encryptedStr.encStr),nonce=NaclUtil.decodeBase64(encryptedStr.nonce),decryptedStr=Nacl.secretbox.open(decStr,nonce,pwDerivedKey);return null!==decryptedStr&&NaclUtil.encodeUTF8(decryptedStr)},KeyStore._encryptKey=function(privateKey,pwDerivedKey){var nonce=Nacl.randomBytes(Nacl.secretbox.nonceLength),privateKeyArray=Encryption.decodeHex(privateKey),encKey=Nacl.secretbox(privateKeyArray,nonce,pwDerivedKey);return{key:NaclUtil.encodeBase64(encKey),nonce:NaclUtil.encodeBase64(nonce)}},KeyStore._decryptKey=function(encryptedKey,pwDerivedKey){var decKey=NaclUtil.decodeBase64(encryptedKey.key),nonce=NaclUtil.decodeBase64(encryptedKey.nonce),decryptedKey=Nacl.secretbox.open(decKey,nonce,pwDerivedKey);if(null===decryptedKey)throw new Error("Decryption failed!");return Encryption.encodeHex(decryptedKey)},KeyStore._computeAddressFromPrivKey=function(privateKey){var keyPair=ec.genKeyPair();keyPair._importPrivate(privateKey,"hex");var pubKey=keyPair.getPublic(!1,"hex").slice(2),pubKeyWordArray=CryptoJS.enc.Hex.parse(pubKey);return CryptoJS.SHA3(pubKeyWordArray,{outputLength:256}).toString(CryptoJS.enc.Hex).slice(24)},KeyStore._computePubkeyFromPrivKey=function(privKey,curve){if("curve25519"!==curve)throw new Error('KeyStore._computePubkeyFromPrivKey: Only "curve25519" supported.');var privateKeyBase64=new Buffer(privKey,"hex").toString("base64"),privateKeyUInt8Array=NaclUtil.decodeBase64(privateKeyBase64),pubKey=Nacl.box.keyPair.fromSecretKey(privateKeyUInt8Array).publicKey,pubKeyBase64=NaclUtil.encodeBase64(pubKey);return new Buffer(pubKeyBase64,"base64").toString("hex")},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.");return Hash.sha256(totalEnt)},KeyStore.DEFAULT_SALT="lightwalletSalt",module.exports=KeyStore}).call(this,require("buffer").Buffer)},{"./assert":2,"./encryption":3,"./signing":5,"./txutils":6,"bitcore-lib":29,"bitcore-mnemonic":93,buffer:138,"crypto-js":155,elliptic:191,"ethereumjs-util":210,"scrypt-async":290,tweetnacl:311,"tweetnacl-util":310}],5:[function(require,module,exports){(function(Buffer){"use strict";var Transaction=require("ethereumjs-tx"),Util=require("ethereumjs-util"),Assert=require("./assert");function getPrivateKeyBuff(keystore,pwDerivedKey,address){var privateKey=keystore.exportPrivateKey(Util.stripHexPrefix(address),pwDerivedKey);return new Buffer(privateKey,"hex")}module.exports={signTx:function(keystore,pwDerivedKey,rawTx,signingAddress){Assert.derivedKey(keystore,pwDerivedKey);var tx=new Transaction(new Buffer(Util.stripHexPrefix(rawTx),"hex")),privateKeyBuff=getPrivateKeyBuff(keystore,pwDerivedKey,signingAddress);return tx.sign(privateKeyBuff),tx.serialize().toString("hex")},signMsg:function(keystore,pwDerivedKey,rawMsg,signingAddress){Assert.derivedKey(keystore,pwDerivedKey);var msgHash=Util.addHexPrefix(Util.keccak(rawMsg).toString("hex"));return this.signMsgHash(keystore,pwDerivedKey,msgHash,signingAddress)},signMsgHash:function(keystore,pwDerivedKey,msgHash,signingAddress){Assert.derivedKey(keystore,pwDerivedKey);var msgBuff=new Buffer(Util.stripHexPrefix(msgHash),"hex"),privateKeyBuff=getPrivateKeyBuff(keystore,pwDerivedKey,signingAddress);return Util.ecsign(msgBuff,privateKeyBuff)},concatSig:function(signature){var v=signature.v,r=signature.r,s=signature.s;return r=Util.fromSigned(r),s=Util.fromSigned(s),v=Util.bufferToInt(v),r=Util.setLengthLeft(Util.toUnsigned(r),32).toString("hex"),s=Util.setLengthLeft(Util.toUnsigned(s),32).toString("hex"),v=Util.stripHexPrefix(Util.intToHex(v)),Util.addHexPrefix(r.concat(s,v).toString("hex"))},recoverAddress:function(rawMsg,v,r,s){var msgHash=Util.keccak(rawMsg);return Util.pubToAddress(Util.ecrecover(msgHash,v,r,s))}}}).call(this,require("buffer").Buffer)},{"./assert":2,buffer:138,"ethereumjs-tx":208,"ethereumjs-util":210}],6:[function(require,module,exports){(function(Buffer){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);return Object.getOwnPropertySymbols&&keys.push.apply(keys,Object.getOwnPropertySymbols(object)),enumerableOnly&&(keys=keys.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(source,!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(source).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}var Transaction=require("ethereumjs-tx"),Util=require("ethereumjs-util"),Coder=require("web3/lib/solidity/coder"),Rlp=require("rlp"),CryptoJS=require("crypto-js");function createTx(txObject){return new Transaction(_objectSpread({},txObject.from&&{from:Util.addHexPrefix(txObject.from)},{},txObject.to&&{to:Util.addHexPrefix(txObject.to)},{},txObject.gasPrice&&{gasPrice:Util.addHexPrefix(txObject.gasPrice)},{},txObject.gasLimit&&{gasLimit:Util.addHexPrefix(txObject.gasLimit)},{},txObject.nonce&&{nonce:Util.addHexPrefix(txObject.nonce)},{},txObject.value&&{value:Util.addHexPrefix(txObject.value)},{},txObject.data&&{data:Util.addHexPrefix(txObject.data)}))}function txToHexString(tx){return Util.addHexPrefix(tx.serialize().toString("hex"))}function _getTypesFromAbi(abi,functionName){return abi.filter(function(json){return"function"===json.type&&json.name===functionName})[0].inputs.map(function(json){return json.type})}function _encodeFunctionTxData(functionName,types,args){var fullName="".concat(functionName,"(").concat(types.join(),")"),signature=CryptoJS.SHA3(fullName,{outputLength:256}).toString(CryptoJS.enc.Hex).slice(0,8),encodeParams=Coder.encodeParams(types,args);return Util.addHexPrefix("".concat(signature).concat(encodeParams))}function createdContractAddress(fromAddress,nonce){var addressBuf=new Buffer(Util.stripHexPrefix(fromAddress),"hex"),rlpEncodedHex=Rlp.encode([addressBuf,nonce]).toString("hex"),rlpEncodedWordArray=CryptoJS.enc.Hex.parse(rlpEncodedHex),hash=CryptoJS.SHA3(rlpEncodedWordArray,{outputLength:256}).toString(CryptoJS.enc.Hex);return Util.addHexPrefix(hash.slice(24))}module.exports={_encodeFunctionTxData:_encodeFunctionTxData,_getTypesFromAbi:_getTypesFromAbi,createTx:createTx,txToHexString:txToHexString,functionTx:function(abi,functionName,args,txObject){return txToHexString(createTx(_objectSpread({},txObject,{data:_encodeFunctionTxData(functionName,_getTypesFromAbi(abi,functionName),args)})))},createdContractAddress:createdContractAddress,createContractTx:function(fromAddress,txObject){var tx=createTx(txObject),contractAddress=createdContractAddress(fromAddress,txObject.nonce);return{tx:txToHexString(tx),addr:contractAddress}},valueTx:function(txObject){return txToHexString(createTx(txObject))}}}).call(this,require("buffer").Buffer)},{buffer:138,"crypto-js":155,"ethereumjs-tx":208,"ethereumjs-util":210,rlp:288,"web3/lib/solidity/coder":321}],7:[function(require,module,exports){"use strict";var CryptoJS=require("crypto-js"),Keystore=require("./keystore"),HD_PATH_STRING="m/0'/0'/0'";function upgradeVersion1(oldKS,password,callback){var salt=oldKS.salt,keyHash=oldKS.keyHash,encSeed=oldKS.encSeed,hdIndex=oldKS.hdIndex,derivedKey=function(password,salt){return CryptoJS.PBKDF2(password,salt,{keySize:16,iterations:150}).toString()}(password,salt);if(keyHash===CryptoJS.SHA3(derivedKey).toString()){var seedPhrase=function(encryptedStr,password){var encStr=encryptedStr.encStr,iv=encryptedStr.iv,salt=encryptedStr.salt;return CryptoJS.AES.decrypt(encStr,password,{iv:iv,salt:salt}).toString(CryptoJS.enc.Latin1)}(encSeed,derivedKey);Keystore.createVault({password:password,seedPhrase:seedPhrase,salt:Keystore.DEFAULT_SALT,hdPathString:HD_PATH_STRING},function(err,newKeyStore){err?callback(err):newKeyStore.keyFromPassword(password,function(err,pwDerivedKey){err?callback(err):(newKeyStore.generateNewAddress(pwDerivedKey,hdIndex),callback(null,newKeyStore.serialize()))})})}else callback(new Error("Keystore Upgrade: Invalid Password!"))}module.exports={upgradeOldSerialized:function(oldSerialized,password,callback){var oldKS=JSON.parse(oldSerialized),version=oldKS.version;if(void 0===version||1===version)upgradeVersion1(oldKS,password,callback);else if(2===version)!function(oldKS,password,callback){var _oldKS$salt=oldKS.salt,salt=void 0===_oldKS$salt?Keystore.DEFAULT_SALT:_oldKS$salt,encSeed=oldKS.encSeed,ksData=oldKS.ksData;Keystore.deriveKeyFromPasswordAndSalt(password,salt,function(err,pwKey){if(err)callback(err);else{var seedPhrase=Keystore._decryptString(encSeed,pwKey);if(seedPhrase&&(seedPhrase=seedPhrase.trim()),seedPhrase&&Keystore.isSeedValid(seedPhrase)){var hdPaths=Object.keys(ksData),hdPathString=HD_PATH_STRING;0<hdPaths.length&&(hdPathString=hdPaths[0]),Keystore.createVault({password:password,seedPhrase:seedPhrase,salt:salt,hdPathString:hdPathString},function(err,newKeyStore){err?callback(err):newKeyStore.keyFromPassword(password,function(err,pwDerivedKey){if(err)callback(err);else{var hdIndex=ksData[hdPathString].hdIndex;newKeyStore.generateNewAddress(pwDerivedKey,hdIndex),callback(null,newKeyStore.serialize())}})})}else callback(new Error("Keystore Upgrade: Invalid provided password."))}})}(oldKS,password,callback);else{if(3!==version)throw new Error("Keystore is not of correct version.");callback(null,oldSerialized)}}}},{"./keystore":4,"crypto-js":155}],8:[function(require,module,exports){"use strict";var asn1=exports;asn1.bignum=require("bn.js"),asn1.define=require("./asn1/api").define,asn1.base=require("./asn1/base"),asn1.constants=require("./asn1/constants"),asn1.decoders=require("./asn1/decoders"),asn1.encoders=require("./asn1/encoders")},{"./asn1/api":9,"./asn1/base":11,"./asn1/constants":15,"./asn1/decoders":17,"./asn1/encoders":20,"bn.js":105}],9:[function(require,module,exports){"use strict";var asn1=require("../asn1"),inherits=require("inherits");function Entity(name,body){this.name=name,this.body=body,this.decoders={},this.encoders={}}exports.define=function(name,body){return new Entity(name,body)},Entity.prototype._createNamed=function(base){var named;try{named=require("vm").runInThisContext("(function "+this.name+"(entity) {\n this._initNamed(entity);\n})")}catch(e){named=function(entity){this._initNamed(entity)}}return inherits(named,base),named.prototype._initNamed=function(entity){base.call(this,entity)},new named(this)},Entity.prototype._getDecoder=function(enc){return enc=enc||"der",this.decoders.hasOwnProperty(enc)||(this.decoders[enc]=this._createNamed(asn1.decoders[enc])),this.decoders[enc]},Entity.prototype.decode=function(data,enc,options){return this._getDecoder(enc).decode(data,options)},Entity.prototype._getEncoder=function(enc){return enc=enc||"der",this.encoders.hasOwnProperty(enc)||(this.encoders[enc]=this._createNamed(asn1.encoders[enc])),this.encoders[enc]},Entity.prototype.encode=function(data,enc,reporter){return this._getEncoder(enc).encode(data,reporter)}},{"../asn1":8,inherits:230,vm:317}],10:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}var inherits=require("inherits"),Reporter=require("../base").Reporter,Buffer=require("buffer").Buffer;function DecoderBuffer(base,options){Reporter.call(this,options),Buffer.isBuffer(base)?(this.base=base,this.offset=0,this.length=base.length):this.error("Input not Buffer")}function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map(function(item){return item instanceof EncoderBuffer||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item},this);else if("number"==typeof value){if(!(0<=value&&value<=255))return reporter.error("non-byte EncoderBuffer value");this.value=value,this.length=1}else if("string"==typeof value)this.value=value,this.length=Buffer.byteLength(value);else{if(!Buffer.isBuffer(value))return reporter.error("Unsupported type: "+_typeof(value));this.value=value,this.length=value.length}}inherits(DecoderBuffer,Reporter),(exports.DecoderBuffer=DecoderBuffer).prototype.save=function(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function(save){var res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function(fail){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(fail||"DecoderBuffer overrun")},DecoderBuffer.prototype.skip=function(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||"DecoderBuffer overrun");var res=new DecoderBuffer(this.base);return res._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res},DecoderBuffer.prototype.raw=function(save){return this.base.slice(save?save.offset:this.offset,this.length)},(exports.EncoderBuffer=EncoderBuffer).prototype.join=function(out,offset){return out||(out=new Buffer(this.length)),offset||(offset=0),0===this.length||(Array.isArray(this.value)?this.value.forEach(function(item){item.join(out,offset),offset+=item.length}):("number"==typeof this.value?out[offset]=this.value:"string"==typeof this.value?out.write(this.value,offset):Buffer.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length)),out}},{"../base":11,buffer:138,inherits:230}],11:[function(require,module,exports){"use strict";var base=exports;base.Reporter=require("./reporter").Reporter,base.DecoderBuffer=require("./buffer").DecoderBuffer,base.EncoderBuffer=require("./buffer").EncoderBuffer,base.Node=require("./node")},{"./buffer":10,"./node":12,"./reporter":13}],12:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}var Reporter=require("../base").Reporter,EncoderBuffer=require("../base").EncoderBuffer,DecoderBuffer=require("../base").DecoderBuffer,assert=require("minimalistic-assert"),tags=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],methods=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(tags);function Node(enc,parent){var state={};(this._baseState=state).enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state.default=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}module.exports=Node;var stateProps=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];Node.prototype.clone=function(){var state=this._baseState,cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});var res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function(){var state=this._baseState;methods.forEach(function(method){this[method]=function(){var clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}},this)},Node.prototype._init=function(body){var state=this._baseState;assert(null===state.parent),body.call(this),state.children=state.children.filter(function(child){return child._baseState.parent===this},this),assert.equal(state.children.length,1,"Root node can have only one child")},Node.prototype._useArgs=function(args){var state=this._baseState,children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this),0!==children.length&&(assert(null===state.children),(state.children=children).forEach(function(child){child._baseState.parent=this},this)),0!==args.length&&(assert(null===state.args),state.args=args,state.reverseArgs=args.map(function(arg){if("object"!==_typeof(arg)||arg.constructor!==Object)return arg;var res={};return Object.keys(arg).forEach(function(key){key==(0|key)&&(key|=0);var value=arg[key];res[value]=key}),res}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(method){Node.prototype[method]=function(){var state=this._baseState;throw new Error(method+" not implemented for encoding: "+state.enc)}}),tags.forEach(function(tag){Node.prototype[tag]=function(){var state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(null===state.tag),state.tag=tag,this._useArgs(args),this}}),Node.prototype.use=function(item){assert(item);var state=this._baseState;return assert(null===state.use),state.use=item,this},Node.prototype.optional=function(){return this._baseState.optional=!0,this},Node.prototype.def=function(val){var state=this._baseState;return assert(null===state.default),state.default=val,state.optional=!0,this},Node.prototype.explicit=function(num){var state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.explicit=num,this},Node.prototype.implicit=function(num){var state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.implicit=num,this},Node.prototype.obj=function(){var state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,0!==args.length&&this._useArgs(args),this},Node.prototype.key=function(newKey){var state=this._baseState;return assert(null===state.key),state.key=newKey,this},Node.prototype.any=function(){return this._baseState.any=!0,this},Node.prototype.choice=function(obj){var state=this._baseState;return assert(null===state.choice),state.choice=obj,this._useArgs(Object.keys(obj).map(function(key){return obj[key]})),this},Node.prototype.contains=function(item){var state=this._baseState;return assert(null===state.use),state.contains=item,this},Node.prototype._decode=function(input,options){var state=this._baseState;if(null===state.parent)return input.wrapResult(state.children[0]._decode(input,options));var prevObj,result=state.default,present=!0,prevKey=null;if(null!==state.key&&(prevKey=input.enterKey(state.key)),state.optional){var tag=null;if(null!==state.explicit?tag=state.explicit:null!==state.implicit?tag=state.implicit:null!==state.tag&&(tag=state.tag),null!==tag||state.any){if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}else{var save=input.save();try{null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch(e){present=!1}input.restore(save)}}if(state.obj&&present&&(prevObj=input.enterObject()),present){if(null!==state.explicit){var explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}var start=input.offset;if(null===state.use&&null===state.choice){if(state.any)save=input.save();var body=this._decodeTag(input,null!==state.implicit?state.implicit:state.tag,state.any);if(input.isError(body))return body;state.any?result=input.raw(save):input=body}if(options&&options.track&&null!==state.tag&&options.track(input.path(),start,input.length,"tagged"),options&&options.track&&null!==state.tag&&options.track(input.path(),input.offset,input.length,"content"),result=state.any?result:null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),input.isError(result))return result;if(state.any||null!==state.choice||null===state.children||state.children.forEach(function(child){child._decode(input,options)}),state.contains&&("octstr"===state.tag||"bitstr"===state.tag)){var data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}return state.obj&&present&&(result=input.leaveObject(prevObj)),null===state.key||null===result&&!0!==present?null!==prevKey&&input.exitKey(prevKey):input.leaveKey(prevKey,state.key,result),result},Node.prototype._decodeGeneric=function(tag,input,options){var state=this._baseState;return"seq"===tag||"set"===tag?null:"seqof"===tag||"setof"===tag?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)?this._decodeStr(input,tag,options):"objid"===tag&&state.args?this._decodeObjid(input,state.args[0],state.args[1],options):"objid"===tag?this._decodeObjid(input,null,null,options):"gentime"===tag||"utctime"===tag?this._decodeTime(input,tag,options):"null_"===tag?this._decodeNull(input,options):"bool"===tag?this._decodeBool(input,options):"objDesc"===tag?this._decodeStr(input,tag,options):"int"===tag||"enum"===tag?this._decodeInt(input,state.args&&state.args[0],options):null!==state.use?this._getUse(state.use,input._reporterState.obj)._decode(input,options):input.error("unknown tag: "+tag)},Node.prototype._getUse=function(entity,obj){var state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(null===state.useDecoder._baseState.parent),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function(input,options){var state=this._baseState,result=null,match=!1;return Object.keys(state.choice).some(function(key){var save=input.save(),node=state.choice[key];try{var value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value:value},match=!0}catch(e){return input.restore(save),!1}return!0},this),match?result:input.error("Choice not matched")},Node.prototype._createEncoderBuffer=function(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function(data,reporter,parent){var state=this._baseState;if(null===state.default||state.default!==data){var result=this._encodeValue(data,reporter,parent);if(void 0!==result&&!this._skipDefault(result,reporter,parent))return result}},Node.prototype._encodeValue=function(data,reporter,parent){var state=this._baseState;if(null===state.parent)return state.children[0]._encode(data,reporter||new Reporter);var result=null;if(this.reporter=reporter,state.optional&&void 0===data){if(null===state.default)return;data=state.default}var content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map(function(child){if("null_"===child._baseState.tag)return child._encode(null,reporter,data);if(null===child._baseState.key)return reporter.error("Child should have a key");var prevKey=reporter.enterKey(child._baseState.key);if("object"!==_typeof(data))return reporter.error("Child expected, but input is not object");var res=child._encode(data[child._baseState.key],reporter,data);return reporter.leaveKey(prevKey),res},this).filter(function(child){return child}),content=this._createEncoderBuffer(content);else if("seqof"===state.tag||"setof"===state.tag){if(!state.args||1!==state.args.length)return reporter.error("Too many args for : "+state.tag);if(!Array.isArray(data))return reporter.error("seqof/setof, but data is not Array");var child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map(function(item){var state=this._baseState;return this._getUse(state.args[0],data)._encode(item,reporter)},child))}else null!==state.use?result=this._getUse(state.use,parent)._encode(data,reporter):(content=this._encodePrimitive(state.tag,data),primitive=!0);if(!state.any&&null===state.choice){var tag=null!==state.implicit?state.implicit:state.tag,cls=null===state.implicit?"universal":"context";null===tag?null===state.use&&reporter.error("Tag could be omitted only for .use()"):null===state.use&&(result=this._encodeComposite(tag,primitive,cls,content))}return null!==state.explicit&&(result=this._encodeComposite(state.explicit,!1,"context",result)),result},Node.prototype._encodeChoice=function(data,reporter){var state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+" not found in "+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function(tag,data){var state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if("objid"===tag&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if("objid"===tag)return this._encodeObjid(data,null,null);if("gentime"===tag||"utctime"===tag)return this._encodeTime(data,tag);if("null_"===tag)return this._encodeNull();if("int"===tag||"enum"===tag)return this._encodeInt(data,state.args&&state.reverseArgs[0]);if("bool"===tag)return this._encodeBool(data);if("objDesc"===tag)return this._encodeStr(data,tag);throw new Error("Unsupported tag: "+tag)},Node.prototype._isNumstr=function(str){return/^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function(str){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str)}},{"../base":11,"minimalistic-assert":244}],13:[function(require,module,exports){"use strict";var inherits=require("inherits");function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}function ReporterError(path,msg){this.path=path,this.rethrow(msg)}(exports.Reporter=Reporter).prototype.isError=function(obj){return obj instanceof ReporterError},Reporter.prototype.save=function(){var state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function(data){var state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function(index){var state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function(index,key,value){var state=this._reporterState;this.exitKey(index),null!==state.obj&&(state.obj[key]=value)},Reporter.prototype.path=function(){return this._reporterState.path.join("/")},Reporter.prototype.enterObject=function(){var state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function(prev){var state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function(msg){var err,state=this._reporterState,inherited=msg instanceof ReporterError;if(err=inherited?msg:new ReporterError(state.path.map(function(elem){return"["+JSON.stringify(elem)+"]"}).join(""),msg.message||msg,msg.stack),!state.options.partial)throw err;return inherited||state.errors.push(err),err},Reporter.prototype.wrapResult=function(result){var state=this._reporterState;return state.options.partial?{result:this.isError(result)?null:result,errors:state.errors}:result},inherits(ReporterError,Error),ReporterError.prototype.rethrow=function(msg){if(this.message=msg+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:230}],14:[function(require,module,exports){"use strict";var constants=require("../constants");exports.tagClass={0:"universal",1:"application",2:"context",3:"private"},exports.tagClassByName=constants._reverse(exports.tagClass),exports.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},exports.tagByName=constants._reverse(exports.tag)},{"../constants":15}],15:[function(require,module,exports){"use strict";var constants=exports;constants._reverse=function(map){var res={};return Object.keys(map).forEach(function(key){(0|key)==key&&(key|=0);var value=map[key];res[value]=key}),res},constants.der=require("./der")},{"./der":14}],16:[function(require,module,exports){"use strict";var inherits=require("inherits"),asn1=require("../../asn1"),base=asn1.base,bignum=asn1.bignum,der=asn1.constants.der;function DERDecoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){base.Node.call(this,"der",parent)}function derDecodeTag(buf,fail){var tag=buf.readUInt8(fail);if(buf.isError(tag))return tag;var cls=der.tagClass[tag>>6],primitive=0==(32&tag);if(31==(31&tag)){var oct=tag;for(tag=0;128==(128&oct);){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag<<=7,tag|=127&oct}}else tag&=31;return{cls:cls,primitive:primitive,tag:tag,tagStr:der.tag[tag]}}function derDecodeLen(buf,primitive,fail){var len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&128===len)return null;if(0==(128&len))return len;var num=127&len;if(4<num)return buf.error("length octect is too long");for(var i=len=0;i<num;i++){len<<=8;var j=buf.readUInt8(fail);if(buf.isError(j))return j;len|=j}return len}(module.exports=DERDecoder).prototype.decode=function(data,options){return data instanceof base.DecoderBuffer||(data=new base.DecoderBuffer(data,options)),this.tree._decode(data,options)},inherits(DERNode,base.Node),DERNode.prototype._peekTag=function(buffer,tag,any){if(buffer.isEmpty())return!1;var state=buffer.save(),decodedTag=derDecodeTag(buffer,'Failed to peek tag: "'+tag+'"');return buffer.isError(decodedTag)?decodedTag:(buffer.restore(state),decodedTag.tag===tag||decodedTag.tagStr===tag||decodedTag.tagStr+"of"===tag||any)},DERNode.prototype._decodeTag=function(buffer,tag,any){var decodedTag=derDecodeTag(buffer,'Failed to decode tag of "'+tag+'"');if(buffer.isError(decodedTag))return decodedTag;var len=derDecodeLen(buffer,decodedTag.primitive,'Failed to get length of "'+tag+'"');if(buffer.isError(len))return len;if(!any&&decodedTag.tag!==tag&&decodedTag.tagStr!==tag&&decodedTag.tagStr+"of"!==tag)return buffer.error('Failed to match tag: "'+tag+'"');if(decodedTag.primitive||null!==len)return buffer.skip(len,'Failed to match body of: "'+tag+'"');var state=buffer.save(),res=this._skipUntilEnd(buffer,'Failed to skip indefinite length body: "'+this.tag+'"');return buffer.isError(res)?res:(len=buffer.offset-state.offset,buffer.restore(state),buffer.skip(len,'Failed to match body of: "'+tag+'"'))},DERNode.prototype._skipUntilEnd=function(buffer,fail){for(;;){var tag=derDecodeTag(buffer,fail);if(buffer.isError(tag))return tag;var res,len=derDecodeLen(buffer,tag.primitive,fail);if(buffer.isError(len))return len;if(res=tag.primitive||null!==len?buffer.skip(len):this._skipUntilEnd(buffer,fail),buffer.isError(res))return res;if("end"===tag.tagStr)break}},DERNode.prototype._decodeList=function(buffer,tag,decoder,options){for(var result=[];!buffer.isEmpty();){var possibleEnd=this._peekTag(buffer,"end");if(buffer.isError(possibleEnd))return possibleEnd;var res=decoder.decode(buffer,"der",options);if(buffer.isError(res)&&possibleEnd)break;result.push(res)}return result},DERNode.prototype._decodeStr=function(buffer,tag){if("bitstr"===tag){var unused=buffer.readUInt8();return buffer.isError(unused)?unused:{unused:unused,data:buffer.raw()}}if("bmpstr"===tag){var raw=buffer.raw();if(raw.length%2==1)return buffer.error("Decoding of string type: bmpstr length mismatch");for(var str="",i=0;i<raw.length/2;i++)str+=String.fromCharCode(raw.readUInt16BE(2*i));return str}if("numstr"===tag){var numstr=buffer.raw().toString("ascii");return this._isNumstr(numstr)?numstr:buffer.error("Decoding of string type: numstr unsupported characters")}if("octstr"===tag)return buffer.raw();if("objDesc"===tag)return buffer.raw();if("printstr"!==tag)return/str$/.test(tag)?buffer.raw().toString():buffer.error("Decoding of string type: "+tag+" unsupported");var printstr=buffer.raw().toString("ascii");return this._isPrintstr(printstr)?printstr:buffer.error("Decoding of string type: printstr unsupported characters")},DERNode.prototype._decodeObjid=function(buffer,values,relative){for(var result,identifiers=[],ident=0;!buffer.isEmpty();){var subident=buffer.readUInt8();ident<<=7,ident|=127&subident,0==(128&subident)&&(identifiers.push(ident),ident=0)}128&subident&&identifiers.push(ident);var first=identifiers[0]/40|0,second=identifiers[0]%40;if(result=relative?identifiers:[first,second].concat(identifiers.slice(1)),values){var tmp=values[result.join(" ")];void 0===tmp&&(tmp=values[result.join(".")]),void 0!==tmp&&(result=tmp)}return result},DERNode.prototype._decodeTime=function(buffer,tag){var str=buffer.raw().toString();if("gentime"===tag)var year=0|str.slice(0,4),mon=0|str.slice(4,6),day=0|str.slice(6,8),hour=0|str.slice(8,10),min=0|str.slice(10,12),sec=0|str.slice(12,14);else{if("utctime"!==tag)return buffer.error("Decoding "+tag+" time is not supported yet");year=0|str.slice(0,2),mon=0|str.slice(2,4),day=0|str.slice(4,6),hour=0|str.slice(6,8),min=0|str.slice(8,10),sec=0|str.slice(10,12);year=year<70?2e3+year:1900+year}return Date.UTC(year,mon-1,day,hour,min,sec,0)},DERNode.prototype._decodeNull=function(buffer){return null},DERNode.prototype._decodeBool=function(buffer){var res=buffer.readUInt8();return buffer.i