Mnemonic Code(HD Wallet)

단단한어린이·2022년 6월 9일
2

Blockchain

목록 보기
2/3
post-thumbnail

What is a seed phrase or mnemonic code?

In cryptocurrency wallets, the all-important private encryption key is a long string of hexadecimal characters (a mix of letters A through F and numbers zero through nine) that is not possible to memorize, and is tricky to transcribe in any form. For example, "A5CD7462F..." is part of a private key. Instead of having to deal with that long string of characters, the wallet seed phrase, also known as a mnemonic phrase, is made up of 12, 18, or 24 words that the wallet originally relies on to initially generate your private key. The order of the words is critical: if your seed phrase is made up of "State, Tiger, Collect, License...," for instance, they must remain in exactly that order. This seed phrase can be used to back up and later regenerate your private key in case you ever need to restore your wallet.

Seed phrases are part of the BIP39 standard. This is a set of rules that simplify managing private keys via seed phrases. In the BIP39 word dictionary, each word represents a number. When creating a seed phrase, it's important to use a random word generator rather than choosing your own words. A random number generator will ensure that your numbers (and associated words) are chosen more randomly than you could choose, making your seed phrase as secure as possible.


How do I use the seed phrase in my digital wallet?

Most digital wallets will have a "Restore from Backup" option, which will ask you to type in your 12, 18, or 24-word seed phrase. Type the words in order, and your assets should be recovered.

You could also add a "passphrase" to your seed phrase. That way, if someone gains access to your seed phrase, your assets have another layer of protection. For wallets that support the addition of passphrases, like the Trezor hardware wallet, passphrases can be long strings and can even include spaces. However, forgetting this passphrase would mean you lose access to your cryptocurrency forever, even if you have the seed phrase. (See section on passphrases in the BIP39 article.) Given the added risk of loss, experts do not agree that use of a passphrase is helpful, especially if you are confident in your method for securely storing your seed phrase. Wallet vendors counsel that passphrases should only be used by advanced users. Additionally, not all wallets support passphrases in the same way, so not only do passphrases come with added risks of loss and error in transcription, but they can complicate wallet migration or restoral.


source : https://vault12.com/securemycrypto/crypto-security-basics/mnemonic-seed-recovery-phrase/how-does-a-seed-phrase-protect-my-crypto-assets



Mnemonic Code and Seed Generation Step 9

Generating Mnemonic Words

  1. Generate a random sequence (entropy) of 128 to 256 bits.

  2. Create a checksum of the random sequence by taking the first (entropy-length/32) bits of its SHA256 hash.

  3. Add the checksum to the end of the random sequence.

  4. Split the result into 11-bit length segments.

  5. Map each 11-bit value to a word from the predefined dictionary of 2048 words.

  6. The mnemonic code is the sequence of words. (12 words)

Mnemonic to Seed

  1. The first parameter to the PBKDF2 key-stretching function is the mnemonic produced from step 6.

  2. The second parameter to the PBKDF2 key-stretching function is a salt. The salt is composed of the string constant mnemonic concatenated with an optional user-supplied passphrase string.

  3. PBKDF2 stretches the mnemonic and salt parameters using 2048 rounds of hashing with the HMAC-SHA512 algorithm, producing a 512-bit value as its final output. That 512-bit value is the seed.


Practice

https://github.com/Binest/MnemonicWallet

IDE

+ Postman for API test


Goal

1. Create newMnemonic API

  • Creates an mnemonic variable.
  • In the mnemonic variable, put lightwallet.keystore.generateRandomSeed() and send the mnemonic as a response.
  • Respond to an error.

Reference Code

router.post('/newMnemonic', async(req,res) => {
  let mnemonic;
  try {
      mnemonic = lightwallet.keystore.generateRandomSeed();
      res.json({mnemonic});
  } catch(err) {
      console.log(err);
  }
});

2. Test with Postman to obtain Mnemonic code

  • Run the local server, and enter the exact endpoint.
  • If Postman has entered the correct method POST, press send to send the request to the server.
  • Check the mnemonic code that the server responds to.


3. Create newWallet API using Mnemonic code and password

  • Send a request to the server with password and mnemonic as input values.
    • Create password and mnemonic variables.
    • Assign the password and mnemonic contained in the request to each variable.
  • Create a keystore using lightwallet.keystore.createVault.
    • The first factors include password, seedPhrase, and hdPathString.
    • For the second factor (callback), create a function that uses the keystore as a factor.
    • Use the keystore.keyFromPassword (password, callback) built-in function of the eth-lightwallet module.
    • Create a function that uses password for the first factor and pwDerivedKey for the second factor.
    • When the second callback function is executed, the new address generation function is executed using the keystore.generateNewAddress (pwDerivedKey, [num]) in the eth-lightwallet module.
    • Create an address variable and assign keystore.getAddresses() to a string.
    • Create a keystore variable and assign keystore.serialize().
    • Send the variable you created above as a response.
  • Respond to an error.

Reference Code

router.post('/newWallet', async(req, res) => {
    let password = req.body.password
    let mnemonic = req.body.mnemonic;

    try {
      lightwallet.keystore.createVault(
        {
          password: password, 
          seedPhrase: mnemonic,
          hdPathString: "m/0'/0'/0'"
        },
        function (err, ks) {
          ks.keyFromPassword(password, function (err, pwDerivedKey) {
            ks.generateNewAddress(pwDerivedKey, 1);
            
            let address = (ks.getAddresses()).toString();
            let keystore = ks.serialize();

            res.json({ keystore: keystore, address: address });
          });
        }
      );
    } catch (exception) { 
      console.log("NewWallet ==>>>> " + exception);
    }
});

4. Test the Response API of the keystore and address by Postman

  • Run the local server, and enter the exact endpoint.
  • If Postman has entered the correct method POST, press send to send the request to the server.
  • In this case, the mnemonic code obtained in Goal 2. is the value of the key called mnemonic, and in password, enter the desired password and press the send button.

5. Make the generated keystore a json file and save it on a local server

  • Import the fs module into the wallet.js file. (The fs module is a Node.js built-in module.)
  • In the function keyFromPassword's callback function of Goal 3, use fs.writeFile or fs.writeFileSync.
    • Enter the file name in .json format for the first factor and keystore for the second factor.
    • For the third factor, enter the callback function for the response.
    • Because the file is stored on the local server, the response sends only success or failure messages.

Reference Code

router.post('/newWallet', async(req, res) => {
  let password = req.body.password
  let mnemonic = req.body.mnemonic;

  try {
    lightwallet.keystore.createVault({
      password: password, 
      seedPhrase: mnemonic,
      hdPathString: "m/0'/0'/0'"
      },
      function (err, ks) {
        ks.keyFromPassword(password, function (err, pwDerivedKey) {
          ks.generateNewAddress(pwDerivedKey, 1);

          let address = (ks.getAddresses()).toString();
          let keystore = ks.serialize();

          fs.writeFile('wallet.json',keystore,function(err,data){
            if(err) {
                res.json({code:999,message:"실패"});
            } else {
                res.json({code:1,message:"성공"});
            }
          });
        });
      }
    );
  } catch (exception) { 
    console.log("NewWallet ==>>>> " + exception);
  }
});

6. Run Postman to see if a keystore file is created in local

  • Do the same as in Goal 4.
  • Verify that a file is created in the path of the local server.


Review

The advantage of mnemonic code is clear, but it feels like it uses a certain old method rather than a higher encryption system.
I just have to follow the order, but it wasn't that easy. I'm satisfied with understanding the principle, but not good enough to develop it alone. I have to work harder.

profile
Footprints in Coding

1개의 댓글

comment-user-thumbnail
2023년 7월 28일

This is really important, I have a couple of friends who have lost their code, but it seems to me that it is not so difficult to remember it, especially since now we do not need to remember a lot of other information, it is on the net. I found the perfect cold wallet for myself using this link and I feel like I don't remember my date of birth better than the code.

답글 달기