• Stars
    star
    1,466
  • Rank 32,080 (Top 0.7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Lightweight JS Wallet for Node and the browser

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.

More Repositories

1

smart-contract-best-practices

A guide to smart contract security best practices
HTML
7,473
star
2

ethereum-developer-tools-list

A guide to available tools and platforms for developing on Ethereum.
5,321
star
3

quorum

A permissioned implementation of Ethereum supporting data privacy
Go
4,581
star
4

mythril

Security analysis tool for EVM bytecode. Supports smart contracts built for Ethereum, Hedera, Quorum, Vechain, Rootstock, Tron and other EVM-compatible blockchains.
Python
3,817
star
5

Tokens

Ethereum Token Contracts
JavaScript
2,059
star
6

gnark

gnark is a fast zk-SNARK library that offers a high-level API to design circuits. The library is open source and developed under the Apache 2.0 license
Go
1,383
star
7

surya

A set of utilities for exploring Solidity contracts
JavaScript
1,076
star
8

ethql

A GraphQL interface to Ethereum 🔥
TypeScript
623
star
9

abi-decoder

Nodejs and Javascript library for decoding data params and events from ethereum transactions
JavaScript
605
star
10

vscode-solidity-auditor

Solidity language support and visual security auditor for Visual Studio Code
JavaScript
568
star
11

teku

Java Implementation of the Ethereum 2.0 Beacon Chain
Java
557
star
12

cakeshop

An integrated development environment and SDK for Ethereum-like ledgers
JavaScript
507
star
13

gnark-crypto

gnark-crypto provides elliptic curve and pairing-based cryptography on BN, BLS12, BLS24 and BW6 curves. It also provides various algorithms (algebra, crypto) of particular interest to zero knowledge proof systems.
Go
487
star
14

Token-Factory

Basic Token Factory dapp.
JavaScript
479
star
15

constellation

Peer-to-peer encrypted message exchange
Haskell
379
star
16

UniversalToken

Implementation of Universal Token for Assets and Payments
JavaScript
346
star
17

doc.linea

Linea documentation
JavaScript
338
star
18

quorum-examples

Examples for Quorum
Shell
317
star
19

scribble

Scribble instrumentation tool
TypeScript
315
star
20

anonymous-zether

A private payment system for Ethereum-based blockchains, with no trusted setup.
Solidity
295
star
21

defi-score

DeFi Score: An open framework for evaluating DeFi protocols
Python
280
star
22

EthOn

EthOn - The Ethereum Ontology
HTML
245
star
23

solidity-metrics

Solidity Code Metrics
JavaScript
235
star
24

Mahuta

IPFS Storage service with search capability
Java
230
star
25

tessera

Tessera - Enterprise Implementation of Quorum's transaction manager
Java
169
star
26

PLCRVoting

Partial Lock Commit Reveal Voting System that utilizes ERC20 Tokens
JavaScript
169
star
27

ethjsonrpc

Python JSON-RPC client for the Ethereum blockchain
Python
156
star
28

linea-attestation-registry

Verax is a shared registry for storing attestations of public interest on EVM chains, designed to enhance data discoverability and consumption for dApps across the network.
TypeScript
129
star
29

zero-knowledge-proofs

Zero Knowledge Proofs and how they can be implemented in Quorum
C++
128
star
30

evm-dafny

An EVM interpreter in Dafny
Dafny
125
star
31

python-solidity-parser

An experimental Solidity parser for Python built on top of a robust ANTLR4 grammar 📚
Python
125
star
32

truffle-security

MythX smart contract security verification plugin for Truffle Framework
JavaScript
124
star
33

solc-typed-ast

A TypeScript package providing a normalized typed Solidity AST along with the utilities necessary to generate the AST (from Solc) and traverse/manipulate it.
TypeScript
123
star
34

web3signer

Web3Signer is an open-source signing service capable of signing on multiple platforms (Ethereum1 and 2, Filecoin) using private keys stored in an external vault, or encrypted on a disk.
Java
122
star
35

daedaluzz

Benchmark Generator for Smart-Contract Fuzzers
Solidity
120
star
36

btcrelay-fetchd

Just the fetchd script of btcrelay
Python
116
star
37

ethsigner

DEPRECATED. A transaction signing application to be used with a web3 provider.
Java
112
star
38

ethereum-dissectors

🔍Wireshark dissectors for Ethereum devp2p protocols
C
109
star
39

quorum-dev-quickstart

The Quorum Developer Quickstart utility can be used to rapidly generate local Quorum blockchain networks for development and demo purposes using Besu, GoQuorum, and Codefi Orchestrate.
Solidity
108
star
40

truffle-webpack-demo

A demo Webpack + React App using truffle-solidity-loader
JavaScript
95
star
41

orion

Orion is a PegaSys component for doing private transactions
Java
92
star
42

blockchainSecurityDB

JavaScript
90
star
43

quorum-kubernetes

Helm charts for Hyperledger Besu and GoQuorum
Mustache
85
star
44

quorum-docs

Documentation assets for Quorum
84
star
45

mythx-cli

A command line interface for the MythX smart contract security analysis API
Python
83
star
46

gpact

General Purpose Atomic Crosschain Transaction Protocol
Java
81
star
47

bytecode-verifier

Compile Solidity source code and verify its bytecode matches the blockchain
JavaScript
80
star
48

goff

goff (go finite field) is a unix-like tool that generates fast field arithmetic in Go.
Go
76
star
49

starknet-snap

The MetaMask Snap for Starknet
TypeScript
74
star
50

linea-contracts

Linea smart-contracts
Solidity
73
star
51

eth2.0-dafny

Eth2.0 spec in Dafny
Dafny
72
star
52

zsl-q

ZSL on Quorum
C++
71
star
53

security-workshop-for-devs

Secure smart contract development workshop hosted by ConsenSys Diligence and MythX.
70
star
54

Legions

Ethereum/EVM Node Security Toolkit
Python
69
star
55

support-metamask-io

Public-facing repository of content live on support.metamask.io. Open for contributions and suggestions.
MDX
66
star
56

quorum-docker-Nnodes

Run a bunch of Quorum nodes, each in a separate Docker container.
Shell
65
star
57

Project-Alchemy

Ethereum-Zcash Integration effort
63
star
58

handel

Multi-Signature Aggregation in a Large Byzantine Committees
Go
53
star
59

qubernetes

Quorum on Kubernetes.
Go
52
star
60

Uniswap-audit-report-2018-12

51
star
61

quorum-tools

Tools for running Quorum clusters and integration tests
Haskell
51
star
62

doc.teku

ConsenSys Ethereum 2.0 client
CSS
47
star
63

vscode-solidity-metrics

Generate Solidity Source Code Metrics, Complexity and Risk profile reports for your project.
JavaScript
46
star
64

private-networks-deployment-scripts

This repository contains out-of-the-box deployment scripts for private PoA networks
Shell
45
star
65

awesome-quorum

A curated list of awesome softwares, libraries, tools, articles, educational resources, discussion channels and more to build on ConsenSys Quorum.
45
star
66

wittgenstein

Simulator for some PoS or consensus algorithms. Includes dfinity, casper IMD and others
Java
45
star
67

linea-tutorials

An EVM-equivalent zk-rollup for scaling Ethereum dapps
Shell
43
star
68

vscode-ethover

Ethereum Account Address Hover Info and Actions
JavaScript
42
star
69

permissioning-smart-contracts

Smart contracts for the Besu permissioning system
TypeScript
41
star
70

besu-sample-networks

Hyperledger Besu Ethereum client quick-start makes you able to simply test all Besu features.
40
star
71

linea-token-list

Linea Token List
TypeScript
39
star
72

0x-review

Security review of 0x smart contracts
HTML
39
star
73

quorum-key-manager

A universal Key & Account Management solution for blockchain applications.
Go
39
star
74

mythx-playground

Exercises to go along with smart contract security workshops by MythX and ConsenSys Diligence
Solidity
39
star
75

kubernetes-action

GitHub Action to run kubectl
Dockerfile
38
star
76

evm-analyzer-benchmark-suite

A benchmark suite for evaluating the precision of EVM code analysis tools.
HTML
38
star
77

quorum-cloud

Deploy Quorum network in a cloud provider of choice
HCL
36
star
78

quorum.js

Quorum.js is an extension to web3.js providing support for JP Morgan's Quorum API
JavaScript
36
star
79

web3js-eea

EEA JavaScript libraries.
JavaScript
35
star
80

truffle-solidity-loader

A Webpack loader that will parse and provision Solidity files to Javascript using Truffle for compilation
JavaScript
35
star
81

secureum-diligence-bootcamp

Solidity
35
star
82

rimble-app-demo

React Ethereum dApp demonstrating onboarding and transaction UX
JavaScript
35
star
83

linea-monorepo

The principal Linea repository. This mainly includes the smart contracts covering Linea's core functions, the prover in charge of generating ZK proofs, the coordinator responsible for multiple orchestrations, and the postman to execute bridge messages.
Go
35
star
84

linea-tracer

Part of the Linea stack responsible for extracting data from the execution of an EVM client in order to construct large matrices called execution traces.
Java
34
star
85

infura-sdk

Infura NFT SDK
TypeScript
34
star
86

web3studio-soy

Static Websites on the Distributed Web
JavaScript
33
star
87

pythx

A Python library for the MythX smart contract security analysis platform
Python
33
star
88

quorum-aws

Tools for deploying Quorum clusters to AWS
HCL
33
star
89

react-metamask

JavaScript
32
star
90

diligence-fuzzing

Python
32
star
91

boilerplate-react

React app boilerplate by ConsenSys France
JavaScript
29
star
92

hellhound

HellHound is a decentralized blind computation platform.
Go
29
star
93

aragraph

Visualize your Aragon DAO Templates
JavaScript
29
star
94

quorum-wizard

Quorum Wizard is a command line tool that allow users to set up a development Quorum network on their local machine in less than 2 minutes.
JavaScript
28
star
95

doc.goquorum

Documentation site for GoQuorum, the ConsenSys Enterprise Ethereum client
CSS
27
star
96

quorum-explorer

A light-weight front-end explorer for Besu and GoQuorum to visualise private networks and deploy smart contracts
TypeScript
27
star
97

mythxjs

TypeScript
26
star
98

hackathon-2021-dapp-workshop

JavaScript
25
star
99

0x_audit_report_2018-07-23

0x Protocol v2 Audit
HTML
24
star
100

web3js-quorum

JavaScript
24
star