Giter Site home page Giter Site logo

hatgit / bip39-mnemonic-tools Goto Github PK

View Code? Open in Web Editor NEW
14.0 3.0 14.0 161 KB

Simple Python and Javascript Tools for generating valid BIP39 mnemonics

License: MIT License

Python 48.68% HTML 51.32%
javascript html blockchain cryptography cryptocurrency

bip39-mnemonic-tools's Introduction

BIP39 Mnemonic Tools

Simple Python and Javascript-based programs for generating valid BIP39 mnemonics, including reversible 'palindromic' mnemonics (i.e. reversible recovery phrases) that are BIP-39 compliant in terms of security, wordlist, and checksum, and that can be used offline as standalone applications (internet-less) without the need of an internet connection or third-party libraries, as all code is contained inline within the singular file (either python file or html file).

This repository currently contains three separate tools, which consist of two Python (.py) files and one Javascript-based app that is wrapped in an .html file, each of which works on a standalone basis independently either from the command-line or within an application (browser or compiler):

Description:

Simplified Python and Javascript programs for generating valid bip39 mnemonics, using an initial random entropy via the secrets module in Python for cryptographically secure entropy (for the Python-related .py files), and the Web3 Cryptography API (for the Javascript-based .html files) then revealing the entropy in its various formats including hex, as a binary string, and as a bytearray before hashing with the SHA256 algorithm to obtain the leading required number of bits from the hash digest in order to compute the checksum and complete the final groups of words shown as 11 bit strings that correspond to an index value for a word as per the BIP39 specification.

The resulting words can be used as valid BIP39 mnemonic recovery phrases for related compatible crypto wallets, and because these apps are early stage and under experimental development, they should be checked against more established tools, in order to confirm that a given entropy maps correctly to its resulting mnemonic words.

The general formula followed in the creation of BIP39-compliant mnemonics is as follows:

  • Initial Entropy in bits /32 = checksum length in bits (this is equal to wordcount/3 == checksum length)

    Initial entropy mod 11 = remaining bits + checksum = last word

    Initial entropy + checksum = total bits /11 = total words. (total words can be either 12 or 24, depending on initial entropy length)

12-word mnemonic 24-word mnemonic
Initial Entropy (security) 128 bits 256 bits
Checksum 4 bits 8 bits
Total Bits 132 bits 264 bits
Total Words 132/11 = 12 words 264/11 = 24 words
---------------- ------------------------------- -----------------------------

Example usage: For a 12-word mnemonic, 128 bits of entropy is needed, and then a 4 bit checksum is calculated from those 128 bits, resulting in a total of 132 bits, which become broken into groups of 11 bits each, where each group corresponds to an index value that represents a word on a list of 2048 words (2^11). A user can choose that the tool generates the entropy for them, to create the 128 bits randomly, or manually enter the 128 bits in the form of a hexidecimal string (i.e. a 32 character hex string, left-padded with 0x making it 34 characters total). In all cases the tool always computes the required checksum which is determinisitc and derived from the initial entropy, therefore, for user-supplied entropy the checksum should not be included as it will be automatically computed by the tool and appended to the end of the string before the final word group is derived.

BIP39 HTML Tool

Note: The palindromic 'reversible' mnemonics are simply regular BIP39-compliant ones that happen to also have the ability to reverse the order of their words and still be BIP39-compliant, this is only possible for certain mnemonics that meet specific criteria, and the author does not believe that there is any security loss for these reversible ones, as one would still need to brute-force the range of valid mnemonics in order to find ones that are also reversible.

BIP39 HTML Tool Palindromic Mnemonic Phase

IMPORTANT: The above entropy values shown in the above example should never be used with any real funds even when testing.

bip39-mnemonic-tools's People

Contributors

hatgit avatar pumpkingwok avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

bip39-mnemonic-tools's Issues

Experiment: Randomly Create Palindromic Mnemonic in new Python File

Edit the .py file mentioned further below that will run if/then loop statements while generating random mnemonics until a valid palindromic one is found. Additional reference:
gitcoinambassadors/ideas#2

Required Steps:

  1. generate a valid mnemonic randomly using the tool (and note the values of bit position 8,9,10 & 11, which are the last four bits of the first word or first group of 11-bits from the left)
  2. put the words into reverse order, then translate them back into groups of 11 bits,
  3. SHA256 hash the first 128 bits (not 132) as a bytearray and compute the 4-bit checksum,
  4. check if the checksum matches the leftover 4 bits from prior step which should match the last four bits of the first group noted in step 1. If they match, a mnemonic is palindromic and should be valid both as a little endian and big endian format. If no match, the program should loop back and repeat steps 1-4.

The file to use as a basis for this experiment is: https://github.com/hatgit/BIP39_mnemonic_creation_light_python/blob/master/Palindromic_Mnemonic_experiment.py

Example of steps that didn't lead to a palindromic mnemonic and should loop over again:

Initial entropy plus checksum:
01101000111011011100101111010001001110011111011000101111101011011010111011011011011000111110000001011001100010000101110111110101 +0110
11-bit groups (note the last 4 bits of first group):

['01101000111', '01101110010', '11110100010', '01110011111', '01100010111', '11010110110', '10111011011', '01101100011', '11100000010', '11001100010', '00010111011', '11101010110']
Index values of words:
[839, 882, 1954, 927, 791, 1718, 1499, 867, 1794, 1634, 187, 1878]
happy hour violin initial glass strategy rocket hockey theory slush blast turn

Putting the above mnemonic into reverse:

turn blast slush theory hockey rocket strategy glass initial violin hour happy

Extract first 128 bits and compute checksum:

111010101100001011101111001100010111000000100110110001110111011011110101101100110001011101110011111111101000100110111001001101000111 +1100

checksum didn't match:

['11101010110', '00010111011', '11001100010', '11100000010', '01101100011', '10111011011', '11010110110', '01100010111', '01110011111', '11110100010', '01101110010', '01101001100'] <โ€” checksum here of 1100 would have had to been 0111, in order for the mnemonic to have been palindromic (not its entropy) where last word would have been "happy" and not "hat".

[1878, 187, 1634, 1794, 867, 1499, 1718, 791, 927, 1954, 882, 844]
turn blast slush theory hockey rocket strategy glass initial violin hour hat

Repeat all steps until a match is found.

"Total Bits" value in Palindromic Field Showing Incorrect values (Did Affect Both Mnemonic Fields)

In the Palindromic section, for the second reversed mnemonic, the field "Initial entropy + checksum = total bits", as well as "initial entropy" are both not displaying the correct number of bits for a 12-word and 24-word mnemonic, and appears to be padding with extra bits after each 11-bit group.

total-bits-error

Looks like the variable "b" is involved:

// final entropy + checksum bits const b = entropyBinary + checksum; addElementToOutput('Initial entropy:', entropyBinary, mode) addElementToOutput('Length of initial entropy:', entropyBinary.length, mode) addElementToOutput('Initial entropy as hex:', hexData, mode) addElementToOutput('Length of entropy as hex:', hexData.length, mode) addElementToOutput('gcc:', generatedCharCount, mode) addElementToOutput('Entropy length as hex without 0x pad:', hexDataNoPadding.length, mode) addElementToOutput('Initial entropy as hex without pad:', hexDataNoPadding, mode) addElementToOutput('Entropy as bytes:', entropyBytearray.join(' '), mode) addElementToOutput('Length of initial entropy as bytearray:', entropyBytearray.length, mode) addElementToOutput('SHA-256 hash digest of entropy bytes', hashHex, mode) addElementToOutput('Partial fragment of initial "byte" of hash', bit, mode) addElementToOutput('First n bits of hash to convert to hex', bit.slice(0,checksumCharCount), mode) addElementToOutput('Checksum (hex to bits)', checksum, mode) addElementToOutput('Initial entropy + checksum = total bits:', b, mode) addElementToOutput('Length of total bits:', b.length, mode) addElementToOutput('Optional backup hex:', hexData, mode) addElementToOutput('Optional backup hex with checksum:', hexData + parseInt(checksum, 2).toString(16),

Clean code & Add dynamic variables for user-supplied entropy and 24-word mnemonics

The current version of this simple Python program lets a user create a cryptographically secure 12-word mnemonic under BIP39. The issue posted here requires that the existing code is cleaned up (condensed, or otherwise improved for speed/performance) while adding the two options below:

  1. User chooses at the start of the app whether to supply their own entropy or for the tool to randomly create entropy.

  2. User selects whether to use a 12-word (as it current defaults to) or a 24-word mnemonic (note: when users choose for the tool to randomly create the entropy, the option for word length will still be shown, and in all cases, the tool will also compute the check, and only allow 128 bits (not 132) for the user to add, as the tool should calculate those last 4 bits, or for 24 word mnemonics 256 bits (not 264) as the last 8 bit checksum would be calculated as part of validating the mnemonic.

Prevent (!window.__cfRLUnblockHandlers) return false;" when page saved for offline use

When the Palindromic Mnemonic tool is served from a Cloudflare-hosted website and a user saves it as an .html file for offline use, the two buttons become disabled due to the following command which the browser inserts into the tag: (!window.__cfRLUnblockHandlers) return false;`

The fix will result the tag retaining its original structure so the button works when saved for offline use:<button onclick= generateBIP39Palindromic()"

This error is limited to the site that host the file through cloudflare, due to a recent change from cloudflare on January 30th: https://www.phplivesupport.com/help_desk.php?docid=284

Convert to HTML-friendly Javascript with dependencies inline

As python is not feasible for most users to run in day-to-day operations on the internet (i.e. online web browsing), it makes sense to translate both of the .py files in this repo to an HTML-friendly Javascript-based code and script(s) where all of the dependencies/libraries that would be needed are brought inline so that the page also works offline, not requiring an internet connection to import any dependencies. This also allows for all inline code to be analyzed from a single page, although subsequent updates to any of the dependency-related code would need to be manually reviewed/changed later on.

In lieu of the secrets library in Python that generates cryptographic randomness by sourcing entropy from the users computer processes, in Javascript the app should make use of the command getRandomValue which is cryptographically secure as per the W3C spec https://github.com/w3c/webcrypto/blob/master/spec/Overview-WebCryptoAPI.xml

The goal of the final result is that the app produces the same utility as the python versions but run from a web browser and not requiring that a user is connected (can be used for cold-storage generation), while keeping all entropy-related cryptographic randomness and random number generation data client-side, just as the Python files do.

Files to use: https://github.com/hatgit/BIP39_mnemonic_creation_light_python/blob/master/bip39appv1_8.py

and: https://github.com/hatgit/BIP39_mnemonic_creation_light_python/blob/master/Palindromic_Mnemonic_experiment.py

Add lookup to find matching word from index list from resulting total bits

While the light python program does create valid BIP39 mnemonics, in its current form it only shows the index values for each word as groups of 11 bits. There should be a lookup feature added so that each of those index values can be matched to the corresponding word from the word list (i.e. https://github.com/hatgit/BIP39-wordlist-printable-en) and printed so that the user doesn't have to manually lookup each index value to find the corresponding mnemonic word.

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.