Coder Social home page Coder Social logo

bitcoinjs / bip39 Goto Github PK

View Code? Open in Web Editor NEW
1.0K 33.0 429.0 498 KB

JavaScript implementation of Bitcoin BIP39: Mnemonic code for generating deterministic keys

License: ISC License

JavaScript 73.60% TypeScript 26.40%
bitcoin mnemonic bip39 bip bitcoinjs javascript

bip39's People

Contributors

d-yokoi avatar dabura667 avatar daolou avatar dcousens avatar dependabot[bot] avatar fanatid avatar gastonponti avatar hankhero avatar hladik-dan avatar junderw avatar kumavis avatar lukechilds avatar nop33 avatar paulmillr avatar rubensayshi avatar sebastiengllmt avatar weilu 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

bip39's Issues

9 word mnemonic being broken by latest patch

[akegalj@notebook npm]$ npm i [email protected] --save
npm WARN saveError ENOENT: no such file or directory, open '/home/akegalj/projects/iohk/npm/package.json'
/home/akegalj/projects/iohk/npm
└─┬ [email protected] 
  ├─┬ [email protected] 
  │ ├─┬ [email protected] 
  │ │ └── [email protected]  deduped
  │ ├── [email protected] 
  │ ├─┬ [email protected] 
  │ │ ├─┬ [email protected] 
  │ │ │ └── [email protected]  deduped
  │ │ └── [email protected]  deduped
  │ └─┬ [email protected] 
  │   └── [email protected]  deduped
  ├─┬ [email protected] 
  │ ├── [email protected]  deduped
  │ ├─┬ [email protected] 
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ └── [email protected]  deduped
  │ ├── [email protected]  deduped
  │ ├── [email protected] 
  │ └── [email protected]  deduped
  ├── [email protected] 
  └── [email protected] 

npm WARN enoent ENOENT: no such file or directory, open '/home/akegalj/projects/iohk/npm/package.json'
npm WARN npm No description
npm WARN npm No repository field.
npm WARN npm No README data
npm WARN npm No license field.
[akegalj@notebook npm]$ ls
node_modules
[akegalj@notebook npm]$ node
> var bip = require('bip39')
undefined
> bip.generateMnemonic()
'hair skate prison broken park great twin gauge cool jewel pear shy'
> bip.generateMnemonic(96)
'renew milk guide erode accuse opinion soda bus fold'
[akegalj@notebook npm]$ rm -rf node_modules/
[akegalj@notebook npm]$ npm i [email protected] --save
npm WARN saveError ENOENT: no such file or directory, open '/home/akegalj/projects/iohk/npm/package.json'
/home/akegalj/projects/iohk/npm
└─┬ [email protected] 
  ├─┬ [email protected] 
  │ ├─┬ [email protected] 
  │ │ └── [email protected]  deduped
  │ ├── [email protected] 
  │ ├─┬ [email protected] 
  │ │ ├─┬ [email protected] 
  │ │ │ └── [email protected]  deduped
  │ │ └── [email protected]  deduped
  │ └─┬ [email protected] 
  │   └── [email protected]  deduped
  ├─┬ [email protected] 
  │ ├── [email protected]  deduped
  │ ├─┬ [email protected] 
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ └── [email protected]  deduped
  │ ├── [email protected]  deduped
  │ ├── [email protected] 
  │ └── [email protected]  deduped
  ├── [email protected] 
  └── [email protected] 

npm WARN enoent ENOENT: no such file or directory, open '/home/akegalj/projects/iohk/npm/package.json'
npm WARN npm No description
npm WARN npm No repository field.
npm WARN npm No README data
npm WARN npm No license field.
[akegalj@notebook npm]$ node
> var bip = require('bip39')
undefined
> bip.generateMnemonic()
'bracket what scene civil soldier master crop peace hub paddle cross comic'
> bip.generateMnemonic(96)
'oven need prosper kitten vessel offer stable wasp ready'

[akegalj@notebook npm]$ rm -rf node_modules/
[akegalj@notebook npm]$ npm i [email protected] --save
npm WARN saveError ENOENT: no such file or directory, open '/home/akegalj/projects/iohk/npm/package.json'
/home/akegalj/projects/iohk/npm
└─┬ [email protected] 
  ├─┬ [email protected] 
  │ ├─┬ [email protected] 
  │ │ └── [email protected]  deduped
  │ ├── [email protected] 
  │ ├─┬ [email protected] 
  │ │ ├─┬ [email protected] 
  │ │ │ └── [email protected]  deduped
  │ │ └── [email protected]  deduped
  │ └─┬ [email protected] 
  │   └── [email protected]  deduped
  ├─┬ [email protected] 
  │ ├── [email protected]  deduped
  │ ├─┬ [email protected] 
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ ├── [email protected]  deduped
  │ │ └── [email protected]  deduped
  │ ├── [email protected]  deduped
  │ ├── [email protected]  deduped
  │ └── [email protected]  deduped
  ├── [email protected] 
  ├── [email protected] 
  └── [email protected] 

npm WARN enoent ENOENT: no such file or directory, open '/home/akegalj/projects/iohk/npm/package.json'
npm WARN npm No description
npm WARN npm No repository field.
npm WARN npm No README data
npm WARN npm No license field.
[akegalj@notebook npm]$ node
> var bip = require('bip39')
undefined
> bip.generateMnemonic()
'churn purse awful tent grid teach super target flash glance indoor warm'
> bip.generateMnemonic(96)
TypeError: Invalid entropy
    at entropyToMnemonic (/home/akegalj/projects/iohk/npm/node_modules/bip39/index.js:94:37)
    at Object.generateMnemonic (/home/akegalj/projects/iohk/npm/node_modules/bip39/index.js:120:10)
    at repl:1:5
    at ContextifyScript.Script.runInThisContext (vm.js:23:33)
    at REPLServer.defaultEval (repl.js:339:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.onLine (repl.js:536:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:191:7)
> 

Hm, it looks to me its a breaking change. At least it broke our package :)

Don't you think this should be major change bump at least. I would even call this a breaking change and maybe bump to 3.0.0

[proposal] Add Installation to the README.md

I am creating a btc wallet in javascript with this this library to generate the seed.

In order to get a little more safe, and to avoid the typing soemthing like
npm install bip-39
add the command to add the bip 39 to the README.md.

Just as bitcoinlib-js:

screenshot from 2018-10-31 16-06-05

(I didn't do the PR myself to not come as imposing, if everyone agrees, I will gladly do it).

mnemonicToSeed should throw on non-string input

It should probably additionally throw on empty string? But maybe someone has a use case there...

Additionally:

  • enforce no duplicate whitespace
  • enforce non-zero length
  • enforce only printable characters

feat: ESM bundling (or export functions in separate files)

would you consider a smaller PR that adds ESM bundling and/or exports all functions in separate files to allow cherry picking imports?

@timhwang21 see #81 - maybe source is still too small to make bundling a reasonably important issue. Or maybe you meant about dependencies? By only importing, say, the encoding part, you would be able to skip all the generator-related stuff.

unmet dependencies when installing via npm

$ npm -g install bip39
+ [email protected]
added 13 packages in 2.184s
$ npm list
[email protected] bitcoinjs/bip39
├── UNMET DEPENDENCY create-hash@^1.1.0
├── UNMET DEPENDENCY pbkdf2@^3.0.9
├── UNMET DEPENDENCY randombytes@^2.0.1
├── UNMET DEPENDENCY safe-buffer@^5.0.1
└── UNMET DEPENDENCY unorm@^1.3.3

npm ERR! missing: create-hash@^1.1.0, required by [email protected]
npm ERR! missing: pbkdf2@^3.0.9, required by [email protected]
npm ERR! missing: randombytes@^2.0.1, required by [email protected]
npm ERR! missing: safe-buffer@^5.0.1, required by [email protected]
npm ERR! missing: unorm@^1.3.3, required by [email protected]
$ npm --version
5.6.0

Using bip39 with React Native

I've Browserified the library using npm run compile and many other ways, but every time I do I get the same error of Buffer is not defined from the create-hash module (helpers.js, line 3). Have you gotten this issue before in the browser?

Branch protection added

To prevent accidental merging before tests pass, like in #33, branch protection has been enabled for all contributors and administrators.

Restructure source so that individual functions can be imported w/o importing the entire source

Right now, if you want to import just one function in bip39 you must import the entire bundle. This can add unnecessary code to already large apps, making them larger. I propose that each function be written in their own files so that they can be imported independently of one another.

My specific concerns here are the the unorm dependency and words list files, which are quite large and not required for all of these utility functions.

Note: I plan to PR this repo with this change, but am open to thoughts in the meantime :)

`mnemonicToEntropy` not returning correct entropy

I found a call to mnemonicToEntropy which isn't returning the correct entropy. To reproduce:

let entropy = "ea9d80e70b08bbfb6b7f2bca56c88ddb2c2d003e675a855779d81e11f3009346a";
let mnemonic = bip39.entropyToMnemonic(entropy);
// 'tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe'

let rand = bip39.mnemonicToEntropy(mnemonic);
// 'ea9d80e70b08bbfb6b7f2bca56c88ddb2c2d003e675a855779d81e11f3009346'

The returned entropy is missing an a at the end. This is the only case where I've found that mnemonicToEntropy doesn't return the correct entropy.

Thanks for a great library!

Can't get mnemonic

I called this function btw I received

{“_40”:0,”_65”:0,”_55”:null,”_72”:null}
generateMnemonic = async () => {
  try {
    return await bip39.generateMnemonic(256) // default to 128
  } catch(e) {
    return false
  }
}

//=>  {“_40”:0,”_65”:0,”_55”:null,”_72”:null}

Could you help me? Looking forward to your reply. Thanks.

How do I use a non-English wordlist?

How can I call generateMnemonic with non-english wordlist? I can't get it to work.

choosing "strength" works fine: bip39.generateMnemonic(256) .
But I can't seem to choose a specific wordlist, e.g. french.

Help appreciated.

browser support?

I'm interested in using this in a browser-context. Is that possible?
currently, I have issues with safe-buffer not existing when I try to use this library.

thanks!

Not working in React-Native

I tried to install bip39 to my react-native app, but when I try to generateMnemonic. I get this error.
simulator screen shot - iphone 6 - 2018-07-10 at 16 13 47

Here is what I did :

  1. npm install bip39
  2. Code: import bip39 from 'bip39'; generateMnemonic() { const mnemonic = bip39.generateMnemonic(); console.log(mnemonic); }.

Please help me out on this

Entropy?

Hi
In this line

var mnemonic = bip39.entropyToMnemonic('133755ff') // hex input, defaults to BIP39 English word list

what is the 133755ff? is this a random string we enter inorder to create entropy? more entropy?

String.prototype.normalize support

Doesn't String.prototype.normalize is supported now by most of the browsers?
May be unorm dependency should be removed and polyfills should be set by builders script of projects using this library?

Error if module imported

`import bip39 from 'react-native-bip39';

var mnemonic = bip39.generateMnemonic();`

I get an error "Unable to resolve module 'assert' from '----/node_modules/react-native-bip39/index.js':
Module 'assert' does not exist in the Haste module map .

Anyone please help me out!

nodejs dependence undocumented

It appears that this code is nodejs dependent - using "require" as far as I'm aware is specific to Nodejs.

If nodejs dependence is intended then maybe documenting that in README.md would be good. (I'd do a pull request, but I'm not sure if that dependence is intended/fixable).

It might be good also to point at non-nodejs versions. I see https://github.com/ggozad/mnemonic.js/blob/master/mnemonic.js on GIT but there might be others.

TypeError: Invalid entropy

I'm try to get mnemonic with privateKey, get error: TypeError: Invalid entropy

privateKey like this: 0xbe03b2771ad49bac7dda1980687fdb1b5b4fce6a5ec7597923c3e3460687a576

my code like this:

const bip39 = require('bip39')
let mnemonic = bip39.entropyToMnemonic(String(privateKey))

is there any mistake i make?

"Invalid Entropy" when using Mnemonic password derived seed as entropy for new Mnemonic

It seems that mnemonicToSeed() returns a Buffer that contains "too much" entropy? https://github.com/bitcoinjs/bip39/blob/v2.5.0/index.js#L99 will then throw an Exception when I try to feed that entropy seed back into entropyToMnemonic()

Below I share the code with which I tried to create a password derived mnemonic with a passphrase based on the optional BIP39 spec with the bip39.js library. I also add a code snippet of how to achieve the encryption using bitcore-mnemonic

// bip39.js
var mnemonic = bip39.generateMnemonic(256);
var seedFromFirstMnemonic = bip39.mnemonicToSeed(mnemonic, "password");
// next line throws
var encryptedSecondMnemonic = bip39.entropyToMnemonic(seedFromFirstMnemonic);
// bitcore-mnemonic
var mnemonic = new Mnemonic(256, Mnemonic.Words.ENGLISH);
var seed = mnemonic.toSeed("password");
var encryptedMnemonic = Mnemonic.fromSeed(seed, Mnemonic.Words.ENGLISH);

The Exception thrown is

lacksfish@computer:~/tmp/path$ node mnemonic-crypt.js
/tmp/path/bip39/index.js:99
  if (entropy.length > 32) throw new TypeError(INVALID_ENTROPY)
                           ^

TypeError: Invalid entropy
    at Object.entropyToMnemonic (/tmp/path/bip39/index.js:99:34)
    at Object.<anonymous> (/tmp/path/mnemonic-crypt.js:7:37)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

Most likely I'm doing something wrong. Although what is confusing is that bitcore-mnemonic seems to be using the seed/entropy Buffer the way I'd have expected... ( see https://github.com/bitpay/bitcore-mnemonic/blob/master/lib/mnemonic.js#L71)

Environment: Ubuntu 18.04 , Node v8.12.0

exclude unused wordlists

hello, I am using this lib in a react & webpack app, and when importing this lib, i've noticed it brings all wordlists into the bundle.

is there a way to exclude the non-english wordlists? or is a version without the non-english wordlists?

I tried to use Webpack IgnorePlugin, to ignore them, but when running the app there is an error

Uncaught Error: Cannot find module "./wordlists/chinese_simplified.json"
at vendors_a853dca288e8f1c5a51a.js:1
at Object. (vendors_a853dca288e8f1c5a51a.js:1)
at e (vendors_a853dca288e8f1c5a51a.js:1)
at Object. (main_17b4f38a6590aae27c42.js:1)
at e (vendors_a853dca288e8f1c5a51a.js:1)
at Object. (main_17b4f38a6590aae27c42.js:1)
at e (vendors_a853dca288e8f1c5a51a.js:1)
at Object. (main_17b4f38a6590aae27c42.js:1)
at e (vendors_a853dca288e8f1c5a51a.js:1)
at Object. (main_17b4f38a6590aae27c42.js:1)

Error: Private key must be less than the curve order

I'm attempting to use the library with MeteorJs instead of browserify. Everything works fine on the server side, on the client I'm running into an Exception with message

Error: Private key must be less than the curve order

On the client the following works fine
var key = bitcoin.ECPair.makeRandom();
console.log(key.getAddress());

But if I want to generate keys through mnuemonic phrases instead I get the above exception. See code below.

this.mnemonic = bip39.generateMnemonic();
let mnemonicSeedHex = bip39.mnemonicToSeedHex(this.mnemonic);
let node = bitcoin.HDNode.fromSeedHex(mnemonicSeedHex, bitcoin.networks.testnet);
console.log(node.getAddress());

I assume its something down to Buffer in the browser?

Wrong master key derived.

I am trying to use this library to generate keys. I have:

let seed        = bip39.mnemonicToSeed(mnemonic);
let master      = bitcoin.HDNode.fromSeedBuffer(seed, bitcoin.networks['testnet']);
let derived     = master.deriveHardened(0).toBase58();

But the result is not consistent with: http://bip32.org/

is mnemonicToEntropy() possible?

Dude would like to go both directions from hex -> wordlist. wordlist -> original hex.

Not a crypto Dude, so I'm just asking. Is mnemonicToEntropy() possible?

Can you implement it please?

Passphrase Usage Support

I was wondering if this library supported passphrase protecting mnemonic phrases. It is described in the "From mnemonic to seed" section of the bip39 white paper. I am looking for the type of functionality found in Ian Coleman Web Wallet , BIP39 Passphrase (optional) section. Thank you for the help.

Release 2.3.0

  • Add a script to download/verify the word lists against BIP39

Contributing to development

Hello, is there a way to contribute to the development of bip39 ? I've created a 2048 brazilian portuguese wordlist and I'd like to open a pull request, or at least send it to the developers in some way...

Performance of bip39.mnemonicToSeed

In my JavaScript app (browser) bip39.mnemonicToSeed(seedPhrase) takes about 1500ms.

Is there anyway to improve the speed of this function?

pbkdf2 performance vs sjcl

I was trying to figure out how to optimize bip39 a bit for mobile (cordova), the sjcl package is about 10x faster for me than the pbkdf package, could be interesting to switch?

  • note you have to ./configure --with-sha512 --with-hmac --with-pbkdf2 --with-bitArray && make the sjcl, the default npm package does not contain sha512.... *
var sjcl = require('sjcl');
var pbkdf = require('pbkdf');

var mnemonic = "later arrest fit foil goat excess online question trumpet grape license term bounce job nominee nuclear credit artefact measure record buyer service husband april tower average athlete pole alpha law picnic tail prepare satisfy dizzy hire illness legal forum rain sniff ask asthma pond present beach either minimum";
var salt = "roooooooobs";
var mnemonicBuffer = new Buffer(mnemonic, 'utf8');
var saltBuffer = new Buffer(password, 'utf8');

t = (new Date).getTime();

console.log(typeof sjcl.hash.sha512);

var hmacSHA512 = function (key) {
    var hasher = new sjcl.misc.hmac( key, sjcl.hash.sha512 );
    this.encrypt = function () {
        return hasher.encrypt.apply( hasher, arguments );
    };
};

var sjclResult = sjcl.misc.pbkdf2(sjcl.codec.utf8String.toBits(mnemonic), sjcl.codec.utf8String.toBits(salt), 2048, 64 * 8, hmacSHA512);
console.log("sjcl.misc.pbkdf2 " + ((new Date).getTime() - t));
console.log(sjcl.codec.hex.fromBits(sjclResult));

t = (new Date).getTime();

var pbkdf2Result = pbkdf2.pbkdf2Sync(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512');
console.log("pbkdf2.pbkdf2Sync " + ((new Date).getTime() - t));
console.log(pbkdf2Result.toString('hex'));

Is the seed the same as the private key?

I'm attempting to generate the private key (not the extended private key, although if the path to generating the private key is through that then that'd be interesting). However I'm having a lot of difficulty.

Is the seed generated from mneumonicToSeed or mneumonicToSeedHex considered a private key or master private key? Does this definition differ between different currencies? i.e. Bitcoin and Ethereum?

feat: defer/lazy load word lists

currently word lists are loaded all at start-up, while realistically the user only ever needs to use one at a time. The suggestion is to make word-lists initialize lazily, and only after the language choice has been made. This abstraction could be hidden in a separate js file to make the main file less verbose. (Imho 154 lines is verbose. You might have taller screens / bigger heads than me, YMMW :-p)

Version 3

  • Isolation of wordlists from primary export (#71)
  • Remove mnemonicToSeedHex, remove implicit hex support, Buffer only
  • safe-buffer
  • Removal of mnemonicToEntropy and entropyToMnemonic from the public API
  • Change to async pbkdf2, aka, an async API (#72)

Thoughts any/everyone?

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.