Giter Club home page Giter Club logo

eth-lightwallet's Introduction

LightWallet

A minimal ethereum javascript wallet.

About

LightWallet is a HD wallet that can store your private keys encrypted in the browser to allow you to run Ethereum dapps even if you're not running a local Ethereum node. It uses BIP32 and BIP39 to generate an HD tree of addresses from a randomly generated 12-word seed.

LightWallet is primarily intended to be a signing provider for the Hooked Web3 provider through the keystore module. This allows you to have full control over your private keys while still connecting to a remote node to relay signed transactions. Moreover, the txutils functions can be used to construct transactions when offline, for use in e.g. air-gapped coldwallet implementations.

The default BIP32 HD derivation path has been m/0'/0'/0'/i, but any HD path can be chosen.

Security

Please note that LightWallet has not been through a comprehensive security review at this point. It is still experimental software, intended for small amounts of Ether to be used for interacting with smart contracts on the Ethereum blockchain. Do not rely on it to store larger amounts of Ether yet.

Get Started

npm install eth-lightwallet

The eth-lightwallet package contains dist/lightwallet.min.js that can be included in an HTML page:

<html>
  <body>
    <script src="lightwallet.min.js"></script>
  </body>
</html>

The file lightwallet.min.js exposes the global object lightwallet to the browser which has the two main modules lightwallet.keystore and lightwallet.txutils.

Sample recommended usage with hooked web3 provider:

// the seed is stored encrypted by a user-defined password
var password = prompt('Enter password for encryption', 'password');

keyStore.createVault({
  password: password,
  // seedPhrase: seedPhrase, // Optionally provide a 12-word seed phrase
  // salt: fixture.salt,     // Optionally provide a salt.
                             // A unique salt will be generated otherwise.
  // hdPathString: hdPath    // Optional custom HD Path String
}, function (err, ks) {

  // Some methods will require providing the `pwDerivedKey`,
  // Allowing you to only decrypt private keys on an as-needed basis.
  // You can generate that value with this convenient method:
  ks.keyFromPassword(password, function (err, pwDerivedKey) {
    if (err) throw err;

    // generate five new address/private key pairs
    // the corresponding private keys are also encrypted
    ks.generateNewAddress(pwDerivedKey, 5);
    var addr = ks.getAddresses();

    ks.passwordProvider = function (callback) {
      var pw = prompt("Please enter password", "Password");
      callback(null, pw);
    };

    // Now set ks as transaction_signer in the hooked web3 provider
    // and you can start using web3 using the keys/addresses in ks!
  });
});

Sample old-style usage with hooked web3 provider (still works, but less secure because uses fixed salts).

// generate a new BIP32 12-word seed
var secretSeed = lightwallet.keystore.generateRandomSeed();

// the seed is stored encrypted by a user-defined password
var password = prompt('Enter password for encryption', 'password');
lightwallet.keystore.deriveKeyFromPassword(password, function (err, pwDerivedKey) {

var ks = new lightwallet.keystore(secretSeed, pwDerivedKey);

// generate five new address/private key pairs
// the corresponding private keys are also encrypted
ks.generateNewAddress(pwDerivedKey, 5);
var addr = ks.getAddresses();

// Create a custom passwordProvider to prompt the user to enter their
// password whenever the hooked web3 provider issues a sendTransaction
// call.
ks.passwordProvider = function (callback) {
  var pw = prompt("Please enter password", "Password");
  callback(null, pw);
};

// Now set ks as transaction_signer in the hooked web3 provider
// and you can start using web3 using the keys/addresses in ks!
});

keystore Function definitions

These are the interface functions for the keystore object. The keystore object holds a 12-word seed according to BIP39 spec. From this seed you can generate addresses and private keys, and use the private keys to sign transactions.

Note: Addresses and RLP encoded data are in the form of hex-strings. Hex-strings start with 0x.

keystore.createVault(options, callback)

This is the interface to create a new lightwallet keystore.

Options

  • password: (mandatory) A string used to encrypt the vault when serialized.
  • seedPhrase: (mandatory) A twelve-word mnemonic used to generate all accounts.
  • salt: (optional) The user may supply the salt used to encrypt & decrypt the vault, otherwise a random salt will be generated.
  • hdPathString (mandatory): The user must provide a BIP39 compliant HD Path String. Previously the default has been m/0'/0'/0', another popular one is the BIP44 path string m/44'/60'/0'/0.

keystore.keyFromPassword(password, callback)

This instance method uses any internally-configured salt to return the appropriate pwDerivedKey.

Takes the user's password as input and generates a symmetric key of type Uint8Array that is used to encrypt/decrypt the keystore.

keystore.isDerivedKeyCorrect(pwDerivedKey)

Returns true if the derived key can decrypt the seed, and returns false otherwise.

keystore.generateRandomSeed([extraEntropy])

Generates a string consisting of a random 12-word seed and returns it. If the optional argument string extraEntropy is present the random data from the Javascript RNG will be concatenated with extraEntropy and then hashed to produce the final seed. The string extraEntropy can be something like entropy from mouse movements or keyboard presses, or a string representing dice throws.

keystore.isSeedValid(seed)

Checks if seed is a valid 12-word seed according to the BIP39 specification.

keystore.generateNewAddress(pwDerivedKey, [num])

Allows the vault to generate additional internal address/private key pairs.

The simplest usage is ks.generateNewAddress(pwDerivedKey).

Generates num new address/private key pairs (defaults to 1) in the keystore from the seed phrase, which will be returned with calls to ks.getAddresses().

keystore.deserialize(serialized_keystore)

Takes a serialized keystore string serialized_keystore and returns a new keystore object.

keystore.serialize()

Serializes the current keystore object into a JSON-encoded string and returns that string.

keystore.getAddresses()

Returns a list of hex-string addresses currently stored in the keystore.

keystore.getSeed(pwDerivedKey)

Given the pwDerivedKey, decrypts and returns the users 12-word seed.

keystore.exportPrivateKey(address, pwDerivedKey)

Given the derived key, decrypts and returns the private key corresponding to address. This should be done sparingly as the recommended practice is for the keystore to sign transactions using signing.signTx, so there is normally no need to export private keys.

upgrade Function definitions

keystore.upgradeOldSerialized(oldSerialized, password, callback)

Takes a serialized keystore in an old format and a password. The callback takes the upgraded serialized keystore as its second argument.

signing Function definitions

signing.signTx(keystore, pwDerivedKey, rawTx, signingAddress, hdPathString)

Signs a transaction with the private key corresponding to signingAddress.

Inputs

  • keystore: An instance of the keystore with which to sign the TX with.
  • pwDerivedKey: the users password derived key (Uint8Array)
  • rawTx: Hex-string defining an RLP-encoded raw transaction.
  • signingAddress: hex-string defining the address to send the transaction from.
  • hdPathString: (Optional) A path at which to create the encryption keys.

Return value

Hex-string corresponding to the RLP-encoded raw transaction.

signing.signMsg(keystore, pwDerivedKey, rawMsg, signingAddress, hdPathString)

Creates and signs a sha3 hash of a message with the private key corresponding to signingAddress.

Inputs

  • keystore: An instance of the keystore with which to sign the TX with.
  • pwDerivedKey: the users password derived key (Uint8Array)
  • rawMsg: Message to be signed
  • signingAddress: hex-string defining the address corresponding to the signing private key.
  • hdPathString: (Optional) A path at which to create the encryption keys.

Return value

Signed hash as signature object with v, r and s values.

signing.signMsgHash(keystore, pwDerivedKey, msgHash, signingAddress, hdPathString)

Signs a sha3 message hash with the private key corresponding to signingAddress.

Inputs

  • keystore: An instance of the keystore with which to sign the TX with.
  • pwDerivedKey: the users password derived key (Uint8Array)
  • msgHash: SHA3 hash to be signed
  • signingAddress: hex-string defining the address corresponding to the signing private key.
  • hdPathString: (Optional) A path at which to create the encryption keys.

Return value

Signed hash as signature object with v, r and s values.

signing.concatSig(signature)

Concatenates signature object to return signature as hex-string in the same format as eth_sign does.

Inputs

  • signature: Signature object as returned from signMsg or ``signMsgHash`.

Return value

Concatenated signature object as hex-string.

signing.recoverAddress(rawMsg, v, r, s)

Recovers the signing address from the message rawMsg and the signature v, r, s.

encryption Function definitions

encryption.multiEncryptString(keystore, pwDerivedKey, msg, myAddress, theirPubKeyArray)

NOTE: The format of encrypted messages has not been finalized and may change at any time, so only use this for ephemeral messages that do not need to be stored encrypted for a long time.

Encrypts the string msg with a randomly generated symmetric key, then encrypts that symmetric key assymetrically to each of the pubkeys in theirPubKeyArray. The encrypted message can then be read only by sender and the holders of the private keys corresponding to the public keys in theirPubKeyArray. The returned object has the following form, where nonces and ciphertexts are encoded in base64:

{ version: 1,
  asymAlg: 'curve25519-xsalsa20-poly1305',
  symAlg: 'xsalsa20-poly1305',
  symNonce: 'SLmxcH3/CPMCCJ7orkI7iSjetRlMmzQH',
  symEncMessage: 'iN4+/b5InlsVo5Bc7GTmaBh8SgWV8OBMHKHMVf7aq5O9eqwnIzVXeX4yzUWbw2w=',
  encryptedSymKey:
   [ { nonce: 'qcNCtKqiooYLlRuIrNlNVtF8zftoT5Cb',
       ciphertext: 'L8c12EJsFYM1K7udgHDRrdHhQ7ng+VMkzOdVFTjWu0jmUzpehFeqyoEyg8cROBmm' },
     { nonce: 'puD2x3wmQKu3OIyxgJq2kG2Hz01+dxXs',
       ciphertext: 'gLYtYpJbeFKXL/WAK0hyyGEelaL5Ddq9BU3249+hdZZ7xgTAZVL8tw+fIVcvpgaZ' },
     { nonce: '1g8VbftPnjc+1NG3zCGwZS8KO73yjucu',
       ciphertext: 'pftERJOPDV2dfP+C2vOwPWT43Q89V74Nfu1arNQeTMphSHqVuUXItbyCMizISTxG' },
     { nonce: 'KAH+cCxbFGSDjHDOBzDhMboQdFWepvBw',
       ciphertext: 'XWmmBmxLEyLTUmUBiWy2wDqedubsa0KTcufhKM7YfJn/eHWhDDptMxYDvaKisFmn' } ] }

Note that no padding is applied to msg, so it's possible to deduce the length of the string msg from the ciphertext. If you don't want this information to be known, please apply padding to msg before calling this function.

encryption.multiDecryptString(keystore, pwDerivedKey, encMsg, theirPubKey, myAddress)

Decrypt a message encMsg created with the function multiEncryptString(). If successful, returns the original message string. If not successful, returns false.

encryption.addressToPublicEncKey(keystore, pwDerivedKey, address)

Gets the public encryption key corresponding to the private key of address in the keystore.

txutils Function definitions

These are the interface functions for the txutils module. These functions will create RLP encoded raw unsigned transactions which can be signed using the keystore.signTx() command.

txutils.createContractTx(fromAddress, txObject)

Using the data in txObject, creates an RLP-encoded transaction that will create the contract with compiled bytecode defined by txObject.data. Also computes the address of the created contract.

Inputs

  • fromAddress: Address to send the transaction from
  • txObject.gasLimit: Gas limit
  • txObject.gasPrice: Gas price
  • txObject.value: Endowment (optional)
  • txObject.nonce: Nonce of fromAddress
  • txObject.data: Compiled code of the contract

Output

Object obj with fields

  • obj.tx: RLP encoded transaction (hex string)
  • obj.addr: Address of the created contract

txutils.functionTx(abi, functionName, args, txObject)

Creates a transaction calling a function with name functionName, with arguments args conforming to abi. The function is defined in a contract with address txObject.to.

Inputs

  • abi: Json-formatted ABI as returned from the solc compiler
  • functionName: string with the function name
  • args: Array with the arguments to the function
  • txObject.to: Address of the contract
  • txObject.gasLimit: Gas limit
  • txObject.gasPrice: Gas price
  • txObject.value: Value to send
  • txObject.nonce: Nonce of sending address

Output

RLP-encoded hex string defining the transaction.

txutils.valueTx(txObject)

Creates a transaction sending value to txObject.to.

Inputs

  • txObject.to: Address to send to
  • txObject.gasLimit: Gas limit
  • txObject.gasPrice: Gas price
  • txObject.value: Value to send
  • txObject.nonce: Nonce of sending address

Output

RLP-encoded hex string defining the transaction.

Examples

See the file example_usage.js for usage of keystore and txutils in node.

See the file example_web.html for an example of how to use the LightWallet keystore together with the Hooked Web3 Provider in the browser.

Tests

Run all tests:

npm run test
npm run coverage

License

MIT License.

eth-lightwallet's People

Contributors

area avatar coder5876 avatar cubedro avatar dalexj avatar danfinlay avatar firescar96 avatar georgi87 avatar istoramandiri avatar jeffscottward avatar kejace avatar kevinjiao avatar miladmostavi avatar oed avatar pipermerriam avatar roderik avatar skmgoldin avatar zachferland avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eth-lightwallet's Issues

Astronomical issue with private keys to sign tx.

secret seed is "erupt consider beyond twist bike enroll you salute weasel emerge divert hundred"

with keystore password "password"
with hdPath = "m/44'/60'/0'"

the private key that is returned is a 62 character hex value.

example code:
(using lightwallet.keystore.deriveKeyFromPassword(password, function(err, pwDerivedKey))

var keystore = new lightwallet.keystore(secretSeed, pwDerivedKey);
var hdPath = "m/44'/60'/0'"; //as defined in SLIP44

keystore.addHdDerivationPath(hdPath, pwDerivedKey, {curve: 'secp256k1', purpose: 'sign'});
keystore.generateNewAddress(pwDerivedKey, 1, hdPath); //Generate a new address

var incompleteAddress = keystore.getAddresses(hdPath)[0];
keystore.setDefaultHdDerivationPath(hdPath);
var hexSeedETH = keystore.exportPrivateKey(incompleteAddress, pwDerivedKey);

..

hexSeedETH.length = 62.

something like a:

function pad(num, size) {
var s = num+"";
while (s.length < size) {
s = "0" + s;
}
return s;
}

with a:

hexSeedETH = pad(hexSeedETH, 64);

returns valid private keys that can sign for this address for the ethereumjs-tx module, and this library's signtx function.

txutil.functionTx & signTx producing invalid "to" address

I'm using txutil.functionTx and signTx to create a raw transaction and then sign it. It all works, but when I broadcast to geth, geth shows a valid tx hash but shows "to: &12345"

e.g. i set

txObject {
to: 0x12345
}

Then in geth it shows the tx is addressed to &12345.

Of course these txs never get confirmed.

Update: Looks like txutil.valueTx also has the same issue.

Not working when installed with NPM3

What error exactly do you get here?

This is bad practice and it should be resolved somehow. In NPM3 the node_modules directory structure is flat, so there is no such path when you install the module with NPM3.

Node >5.0.0 is bundled with NPM3 by default, so this might be a problem for a lot of people.

Support standardized Hex format(s)

There's 2 commons hex formats at the moment

  • prefixed hex strings 0x123456
  • Buffers new Buffer('123456', 'hex') ( ideal memory footprint )

Currently eth-lightwallet expects non-prefixed strings.
Maybe wrap all public fn inputs in a format normalizer fn

TypeError: undefined is not a function from lightwallet.keystore.deriveKeyFromPassword()

Getting the following error in lightwallet.keystore.deriveKeyFromPassword in nodejs

Version

    "eth-lightwallet": "^2.2.0",

Error

> TypeError: undefined is not a function
    at new KeyStore (/Users/aeufemio/projects/digixglobal/web/accountmanager/node_modules/eth-lightwallet/lib/keystore.js:80:27)
    at cb (/Users/aeufemio/projects/digixglobal/web/accountmanager/node_modules/eth-lightwallet/lib/keystore.js:433:5)
    at /Users/aeufemio/projects/digixglobal/web/accountmanager/node_modules/eth-lightwallet/node_modules/scrypt-async/scrypt-async.js:474:9
    at Immediate._onImmediate (/Users/aeufemio/projects/digixglobal/web/accountmanager/node_modules/eth-lightwallet/node_modules/scrypt-async/scrypt-async.js:433:11)
    at processImmediate [as _immediateCallback] (timers.js:367:17)

unable to pass input data with a value tx

in the valueTx method, we are unable to pass in some input data:
https://github.com/ConsenSys/eth-lightwallet/blob/master/lib/txutils.js#L92

is this by design?

the following code is commented to show the additional line:

function valueTx (txObject) {
  // txObject contains gasPrice, gasLimit, value, nonce

  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);
  //NB NB NB added this here - should we do a pull request?
  txObjectCopy.data = txObject.data;

  var tx = new Transaction(txObjectCopy);

  return tx.serialize().toString('hex');
}

BTW - thanks so much for your efforts, really great little library!

Webpack: Uncaught TypeError: EC is not a constructor

When importing with Webpack require("eth-lightwallet") Uncaught TypeError: EC is not a constructor is thrown.

Not sure if this is related to lightwallet it self. It seems that there is some dependency cycles in those crypo libs. Attached npm project with this issue
test-webpack.zip

npm start -> http://localhost:8080 -> open dev console

Currently workaround is to include full js file form dist require("node_modules/eth-lightwallet/dist/lightwallet.js");

deserialize function is not part of the API ?

Why is this function not part of the API ? I guess I should be able to deserialize a wallet that I have serialized before ?
Is this something that is missing in the code - or am I doing something wrong?

Thanks.
Stefaan

example webwallet.html does not work

I downloaded the latest release, unpacked and ran eth-lightwallet-2.2.3/example/webwallet.html from that on ubuntu 15.10 in the latest Chrome. I have issues with the retrieving address:

  1. When creating a new wallet it shows Retrieving addresses... in the Show Addresses section which remains and seems stuck. Clicking Show or Refresh does not change this.
  2. Importing the wallet from the seed and password shows an address in the From / Caller dropdowns (suggesting seed and PW are ok). Still I seem to be unable to get retrieving addresses.

hdpath String is not yet implemented ?

when going to generate index 1 address (1st address)

var lightwallet = require("eth-lightwallet");
var keythereum = require("keythereum");
var secretSeed = "police club trick jealous together tunnel clarify sustain enforce vast absurd matrix";
var password = "test";
var _getPrivAddressByIndex = function(indexNum) {
    if(indexNum <= 0) throw Error("address index should be starting from 1")
    lightwallet.keystore.deriveKeyFromPassword(password, function (err, pwDerivedKey) {
        console.time();
        var ks = new lightwallet.keystore(secretSeed, pwDerivedKey);
        // lightwallet module doesn't have the method to get the given index address and secret
        // ex) if indexNum is 1003, hdPathString is "m/0'/0'/1'"
        // And the generate is 3
        // 1- 999 is "m/0'/0'/0'"
        // 1000- 1999 is "m/0'/1'/0'"
        // 2000 -2999 is "m/0'/2'/0'"
        var hdPathString = "m/0'/" + (indexNum - indexNum % 1000) / 1000  + "'/" + 0 + "'"
        var generateAddressNum = (indexNum % 1000 == 0)? 1: indexNum % 1000;
        console.log("hdpath " + hdPathString)
        console.log("number of addresses to generate " +  generateAddressNum)
        ks.generateNewAddress(pwDerivedKey, generateAddressNum, hdPathString);
        var addresses = ks.getAddresses();
        var address = addresses[generateAddressNum - 1];
        var exportedPriv = ks.exportPrivateKey(address, pwDerivedKey)
        console.log("generated address and private key is " + JSON.stringify([address, exportedPriv]));
        return [address, exportedPriv]
    });
}
var addressAndPriv = _getPrivAddressByIndex(1);

Then the result is

$ node exampleEtherGenerateAddress.js 
hdpath m/0'/0'/0'
number of addresses to generate 1
{ 'm/0\'/0\'/0\'': 
   { info: { curve: 'secp256k1', purpose: 'sign' },
     encHdPathPriv: 
      { encStr: 'Qp3li7Cr6eFI8dybiziRX7/56R/EnKUZVgwh2022/caO4HXO5efSFaLGHXmQacAWVdowxerOYrME5ZHU870+MZ39/447YfkDIfI2UnwCf/dKRNQc8Rijvsp0y4cJBulhcbyWef/rDAUBcZON79BOR8ddMQ/szqhxhr1DFjK4Bw==',
        nonce: 'dpuxp5OVtokxIYCzsLdSJfFBCusnnvcN' },
     hdIndex: 0,
     encPrivKeys: {},
     addresses: [] } }
generated address and private key is ["14adb0788d887ec5d5bb71a7d37a8389a896558f","74b081765d2546a3831f0d4c23a20986cd2e6a6381479fe156dc32287dc5117b"]

and when going to generate 999th

var lightwallet = require("eth-lightwallet");
var keythereum = require("keythereum");
var secretSeed = "police club trick jealous together tunnel clarify sustain enforce vast absurd matrix";
var password = "test";
var _getPrivAddressByIndex = function(indexNum) {
    if(indexNum <= 0) throw Error("address index should be starting from 1")
    lightwallet.keystore.deriveKeyFromPassword(password, function (err, pwDerivedKey) {
        console.time();
        var ks = new lightwallet.keystore(secretSeed, pwDerivedKey);
        // lightwallet module doesn't have the method to get the given index address and secret
        // ex) if indexNum is 1003, hdPathString is "m/0'/0'/1'"
        // And the generate is 3
        // 1- 999 is "m/0'/0'/0'"
        // 1000- 1999 is "m/0'/1'/0'"
        // 2000 -2999 is "m/0'/2'/0'"
        var hdPathString = "m/0'/" + (indexNum - indexNum % 1000) / 1000  + "'/" + 0 + "'"
        var generateAddressNum = (indexNum % 1000 == 0)? 1: indexNum % 1000;
        console.log("hdpath " + hdPathString)
        console.log("number of addresses to generate " +  generateAddressNum)
        ks.generateNewAddress(pwDerivedKey, generateAddressNum, hdPathString);
        var addresses = ks.getAddresses();
        var address = addresses[generateAddressNum - 1];
        var exportedPriv = ks.exportPrivateKey(address, pwDerivedKey)
        console.log("generated address and private key is " + JSON.stringify([address, exportedPriv]));
        return [address, exportedPriv]
    });
}
var addressAndPriv = _getPrivAddressByIndex(999);

then the result is

$ node exampleEtherGenerateAddress.js 
hdpath m/0'/0'/0'
number of addresses to generate 999
{ 'm/0\'/0\'/0\'': 
   { info: { curve: 'secp256k1', purpose: 'sign' },
     encHdPathPriv: 
      { encStr: 'I2BD7emNYC9n8d5Uvw4ruGEfLY7Xdtn58tlnBbgRVdB09Uw4ttOnjx+atzX5QfnQb8nEn1v40iJIWLRXwuFQnghFh27AJuPxuVD/CBMqNNOm0Ukv3xcOey8g7XG5uwwXtd3XUQuDmBcvRFa22wDSo4kH0kRDw4ocfPqDU5xjYA==',
        nonce: 'R7rQ1hd0JjfJwfFHpfugrC/x+HvvDQq5' },
     hdIndex: 0,
     encPrivKeys: {},
     addresses: [] } }
generated address and private key is ["aa07af9bf584e64e355bd51101cb8f8e0e9bfc4b","9365b6dd26e705c9d6123c1f2790910bfbf21e3a033efe8dba2deb4938ee7cdf"]

but when 2001th

var lightwallet = require("eth-lightwallet");
var keythereum = require("keythereum");
var secretSeed = "police club trick jealous together tunnel clarify sustain enforce vast absurd matrix";
var password = "test";
var _getPrivAddressByIndex = function(indexNum) {
    if(indexNum <= 0) throw Error("address index should be starting from 1")
    lightwallet.keystore.deriveKeyFromPassword(password, function (err, pwDerivedKey) {
        console.time();
        var ks = new lightwallet.keystore(secretSeed, pwDerivedKey);
        // lightwallet module doesn't have the method to get the given index address and secret
        // ex) if indexNum is 1003, hdPathString is "m/0'/0'/1'"
        // And the generate is 3
        // 1- 999 is "m/0'/0'/0'"
        // 1000- 1999 is "m/0'/1'/0'"
        // 2000 -2999 is "m/0'/2'/0'"
        var hdPathString = "m/0'/" + (indexNum - indexNum % 1000) / 1000  + "'/" + 0 + "'"
        var generateAddressNum = (indexNum % 1000 == 0)? 1: indexNum % 1000;
        console.log("hdpath " + hdPathString)
        console.log("number of addresses to generate " +  generateAddressNum)
        ks.generateNewAddress(pwDerivedKey, generateAddressNum, hdPathString);
        var addresses = ks.getAddresses();
        var address = addresses[generateAddressNum - 1];
        var exportedPriv = ks.exportPrivateKey(address, pwDerivedKey)
        console.log("generated address and private key is " + JSON.stringify([address, exportedPriv]));
        return [address, exportedPriv]
    });
}
var addressAndPriv = _getPrivAddressByIndex(2011);

Then it fails

$ node testGenerateAddress.js 
hdpath m/0'/2'/0'
number of addresses to generate 11
hdpath m/0'/2'/0'
number of addresses to generate 11
/Users/tom/Documents/workspace_js/AsianPayPoloniexEtherwallet/node_modules/eth-lightwallet/lib/keystore.js:135
  var secretbox = nacl.util.decodeBase64(encryptedStr.encStr);
                                                     ^

TypeError: Cannot read property 'encStr' of undefined
    at Function.KeyStore._decryptString (/Users/tom/Documents/workspace_js/AsianPayPoloniexEtherwallet/node_modules/eth-lightwallet/lib/keystore.js:135:54)
    at KeyStore.isDerivedKeyCorrect (/Users/tom/Documents/workspace_js/AsianPayPoloniexEtherwallet/node_modules/eth-lightwallet/lib/keystore.js:115:29)
    at KeyStore.generateNewAddress (/Users/tom/Documents/workspace_js/AsianPayPoloniexEtherwallet/node_modules/eth-lightwallet/lib/keystore.js:444:12)
    at /Users/tom/Documents/workspace_js/AsianPayPoloniexEtherwallet/exampleEtherGenerateAddress.js:20:12
    at cb (/Users/tom/Documents/workspace_js/AsianPayPoloniexEtherwallet/node_modules/eth-lightwallet/lib/keystore.js:531:7)
    at /Users/tom/Documents/workspace_js/AsianPayPoloniexEtherwallet/node_modules/scrypt-async/scrypt-async.js:474:9
    at Immediate._onImmediate (/Users/tom/Documents/workspace_js/AsianPayPoloniexEtherwallet/node_modules/scrypt-async/scrypt-async.js:433:11)
    at tryOnImmediate (timers.js:543:15)
    at processImmediate [as _immediateCallback] (timers.js:523:5)

Meteor 1.3 Integration

hi i'm trying to use https://github.com/ConsenSys/eth-lightwallet w Meteor 1.3. Meteor install commands:

meteor create ethereum-app
cd ethereum-app
meteor npm install
meteor npm install --save eth-lightwallet

but when using eth-lightwallet from w/in meteor. Just copy the following line into main.js (for example):

import lightwallet from 'eth-lightwallet';

and starting the meteor app with:

meteor

i get:

Unable to resolve some modules:

  "build/Release/sha3" in
/home/reto/Development/ethereum-app/node_modules/eth-lightwallet/node_modules/ethereumjs-util/node_modules/keccakjs/node_modules/sha3/package.json
(web.browser)

does somebody have a idea on how to solve this?

Lightwallet on meteor

Please fix light wallet so it can be installed in a meteor project and used server side. You'll see the problem if you install the module in a meteor project.

Install error

Hi
I have this error trying to build in ubuntu:

npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the secp256k1 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls secp256k1

Any idea?
Need more data?

Keystore vs keystore

theres almost no distinction in wording/format of lightwallet.keystore vs the keystore obj.
its class-like, so i would capitalize it

var keystore = Keystore.deserialize(serialized_keystore)

Further explanation of not running node?

"LightWallet is a HD wallet that can store your private keys encrypted in the browser to allow you to run Ethereum dapps even if you're not running a local Ethereum node"

Can you explain the above sentence a bit? Currently, I would like to call a contract that exists on the Ethereum test node (the one accessible from Mist). Is this possible? Do I need their ip address? Are new accounts created with lightwallet able to receive ether? Any information on this would be useful.

Thanks

Minify process fails with this library

I noticed a week ago that including lightwallet.js would cause my minify build process to fail, but if I used the lightwallet.min.js it would build fine.

I just updated to lightwallet to 2.2.5 and now it seems both normal and min versions cause my minify to fail.

It also fails to compress here: http://jscompress.com/

Can't deploy a contract

TIA
Am I supposed to be able to deploy a contract over web3 using eth-lightwallet?
I have a valid Solidity contract. The js code is taken from Web3 deploy in Solidity Browser. When run from geth with loadScript() is works.

If I use the same code in the context of a js with the eth-wallet API I get an:
Error: Gas price too low for acceptance .

Code is as follows:

`var ethClient = "http://localhost:xxxx";
var web3 = new Web3();
var global_keystore;

// setting up a web3 provider but using a keystore to get access to account information
function setWeb3Provider(keystore) {
var web3Provider = new HookedWeb3Provider({
host: ethClient,
transaction_signer: keystore
});
web3.setProvider(web3Provider);
}

function setSeed() {
var password = prompt('Enter Password to encrypt your seed', 'Password');
var providedSeed = document.getElementById('seed').value;
lightwallet.keystore.deriveKeyFromPassword(password, function (err, pwDerivedKey) {
global_keystore = new lightwallet.keystore(
providedSeed,
pwDerivedKey);
global_keystore.generateNewAddress(pwDerivedKey, 2);
setWeb3Provider(global_keystore);
});
}

function create() {
var addresses = global_keystore.getAddresses();
var c = web3.eth.contract(myAbi);
var cInstance = c.new(
{
from: addresses[0],
data: '........',
gas: 3000000000000
}, function(e, contract){
console.log(e, contract);
if (typeof contract != 'undefined') {
console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
console.log(contract.address);
}
});
}
`

Keep a hash of the password

We should keep a hash of the password to validate against whenever one is submitted by a user. That way we never attempt to generate keys using an invalid seed decrypted by an incorrect password.

ripemd160 is not supported

Hi, when doing :
var randomSeed = lightwallet.keystore.generateRandomSeed(extraEntropy)

it throw :
Error: ripemd160 is not supported (we accept pull requests) Trace de la pile : module.exports@http://localhost:8080/app.js:151561:19 module.exports@http://localhost:8080/app.js:151550:11 Hash.ripemd160@http://localhost:8080/app.js:198294:11 Hash.sha256ripemd160@http://localhost:8080/app.js:198299:11 HDPrivateKey.prototype._buildFromBuffers@http://localhost:8080/app.js:207826:22 HDPrivateKey.prototype._buildFromObject@http://localhost:8080/app.js:207714:11 HDPrivateKey@http://localhost:8080/app.js:207469:6 HDPrivateKey.fromSeed@http://localhost:8080/app.js:207760:11 Mnemonic.prototype.toHDPrivateKey@http://localhost:8080/app.js:208956:11 KeyStore@http://localhost:8080/app.js:170272:19 newWallet/<@http://localhost:8080/app.js:143693:24 KeyStore.deriveKeyFromPassword/cb@http://localhost:8080/app.js:170628:8 scrypt/</<@http://localhost:8080/app.js:210140:10 scrypt/interruptedFor/<@http://localhost:8080/app.js:210099:12 onNextTick@http://localhost:8080/app.js:78599:10 Item.prototype.run@http://localhost:8080/app.js:2340:6 drainQueue@http://localhost:8080/app.js:2310:18

As it is no (longer ?) supported, does anyone use it or everyone has forked eth-lightwallet to use another hash ?

Thank you

AssertionError invalid chainCode size in Microsoft Edge

Hi,

I'm using eth-lightwallet to generate accounts in the browser. Everything works great in Firefox (45.0.2, Windows and Ubuntu) and Chrome (49.0.2623, Windows, Ubuntu and Android).

But in Microsoft Edge (25.10586.0.0) I get the following error and I traced it back to bitcore-lib (https://github.com/bitpay/bitcore-lib):

AssertionError: chainCode has not the expected size: found 64, expected 32

The assertion error is raised here:

https://github.com/bitpay/bitcore-lib/blob/b3b18d532ff86855a142688413f60364aec4048a/lib/hdprivatekey.js#L464

My first guess is this buffer is initialized/filled twice in Microsoft Edge for some reason.
Could it be eth-lightwallet misusing bitcore-lib?
Can anyone confirm this part of bitcore-lib works in an app in Microsoft Edge?

How can we fix this?

Thank you !

Broken in electron

Uncaught Exception:
Error: Module version mismatch. Expected 46, got 14.
at Error (native)
at Object.module.(anonymous function) (ATOM_SHELL_ASAR.js:137:20)
at Object.module.(anonymous function) as .node
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object. (/Users/aeufemio/projects/digixglobal/apps/wallet/app/node_modules/eth-lightwallet/node_modules/ethereumjs-tx/node_modules/ethereumjs-util/index.js:1:93)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)

[Question] How can I use eth-lightwallet to verify a signature?

I have the following message: '0xdeadbeefdeadbeefdeadbeef' and I'm using eth-lightwallet to sign it like this:

signedMsg = lightwallet.signing.signMsg(keystore, pwDerivedKey, '0xdeadbeefdeadbeefdeadbeef', '0xd5311ad626f09d0f9d1b1f7cdb84fdd600efbc1d');

It gives me this back: 0x348bdaeacdc93823b136f7d4f87a1c10be001de19a844c2d6751647a0c7fe5ee5451791e9696e08f815d851ad840c5a10a96cae9a5735d7c920bbfb39dfd30041c. How can I verify a signed msg later? Using recoverAddress? is there an example of how to do that?

How do I run html page?

Im trying to run the example. Do I need to host the html page locally using iis? I'm very confused. I open the webwallet.html but its like a dead page. I have the web3. hooked-web3-provider as folder besides the eth-lightwallet folder too. Im running windows 7 64-bit

please help. thanks

generateNewAddress bug with deserialized KeyStore

I create a new keyStore, and generate one new address and then serialize it to localStorage. When I deserialize that keyStore I can see the one address that was previously generated. However if I then issue another generateNewAddress(pwDerivedKey) and the keyStore stays at just the one address, and then if I generateNewAddress again I then see two.

Return the newly generated address in keystore.generateNewAddress()

Can the generateNewAddress(derivedPwKey, N) function be modified to return the newly generated address(es) as a convenience instead of returning undefined? The most likely thing a client does after generating new address(es) is to access them. This enhancement would save the client the extra step to call keystore.getAddresses() and obtain the last N addresses to gain access to those new addresses.
Of course, the return would be an array type of new addresses.

Global leaks

Hi,

As I was testing my application, my testing framework (lab) detected a bunch of global leaks:

The following leaks were detected:signTx, legacyDecryptString, multiEncryptString, _bitcore, legacyGenerateEncKey, asymEncryptString, asymDecryptString, recoverAddress, multiDecryptString, signMsg, upgradeOldSerialized, ethUtil, pathKsData, concatSig

Is there a reason why globals were necessary here? Can I safely ignore that?

Thanks!

import eth-lightwallet with es6

Hi,
I would like to import the lightwallet to my project (Truffle), when I do
import { lightwallet } from 'eth-lightwallet'
, I have an error :
_ethLightwallet.lightwallet is undefined

The README say lightwallet is exposed, how do I get it ?

Thank you

Transfer calls instead of Function calls

When i send ether to an account (using the blockapps api) it appears on http://blockapps.net/demo/ as a function call instead of an ether transfer.

Of course the money ends up in the right place which is what matters, but still, I think the call from helpers to the api is wrong for transfering ether.

txParams optionally instead of rawTx

i have to serialize my unsigned tx just so lightwallet can deserialize it. seems silly.

params hash is like

{
  to: '0x1234',
  from: '0x4321',
  value: 100,
  nonce: 0
}

ethereumjs-tx now also accepts web3 style tx params keys (gasLimit -> gas)

Question: How to provide password to signTransaction()

My implementation of sendEth() in the example webwallet.html always prompts for password with a dialog box even though the global_keystore is set. Is it possible to request password from a web form and pass it, and prevent the browser dialog box in KeyStore.prototype.signTransaction and passwordProvider?

('KeyStore.generateNewAddress: No seed set') when seed is set according to debug

 Hi, I am using eth-lightwallet on a NodeJS server. I am getting a stack trace when I try and get the private key from the keystore. It is flagging this line "keystore.generateNewAddress(pwDerivedKey);" I cannot see how it is related. When I comment out the line "account.prv_key = keystore.exportPrivateKey(sendingAddr, pwDerivedKey);" it appears to work flawlessly. Am I doing something wrong? I am new to Node and suspect it has something to do with the asynchronous nature of Node. I have included the code and the stacktrace below. Thank you


lightwallet.keystore.deriveKeyFromPassword('mypassword',
    function (err, pwDerivedKey) {
      var seed = lightwallet.keystore.generateRandomSeed();
      var keystore = new lightwallet.keystore(seed, pwDerivedKey);

      keystore.generateNewAddress(pwDerivedKey);
      account.address = keystore.getAddresses()[0];
      account.prv_key = keystore.exportPrivateKey(sendingAddr, pwDerivedKey);
    })


/Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/lib/keystore.js:389
    throw new Error('KeyStore.generateNewAddress: No seed set');
    ^

Error: KeyStore.generateNewAddress: No seed set
    at KeyStore.generateNewAddress (/Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/lib/keystore.js:389:11)
    at /Users/username/WebstormProjects/eth-project/nodejs-server/controllers/ActorService.js:39:20
    at cb (/Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/lib/keystore.js:459:7)
    at /Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/node_modules/scrypt-async/scrypt-async.js:474:9
    at Immediate._onImmediate (/Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/node_modules/scrypt-async/scrypt-async.js:433:11)
    at processImmediate [as _immediateCallback] (timers.js:383:17)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.