tyler-smith / go-bip39

The BIP39 library for Go.
MIT License
549 stars 196 forks source link

Expand README example with reverse validation #43

Closed gandaldf closed 1 year ago

gandaldf commented 3 years ago

Hi! I just wanted to suggest to expand the main example with a validation test starting from a set of known keys:

package main

import (
    "fmt"

    "github.com/tyler-smith/go-bip32"
    "github.com/tyler-smith/go-bip39"
)

func main() {
    // Generate a mnemonic for memorization or user-friendly seeds
    entropy, _ := bip39.NewEntropy(256)
    mnemonic, _ := bip39.NewMnemonic(entropy)

    // Generate a Bip32 HD wallet for the mnemonic and a user supplied password
    seed := bip39.NewSeed(mnemonic, "Secret Passphrase")

    masterKey, _ := bip32.NewMasterKey(seed)
    publicKey := masterKey.PublicKey()

    // Display mnemonic and keys
    fmt.Println("Mnemonic: ", mnemonic)
    fmt.Println("Master private key: ", masterKey)
    fmt.Println("Master public key: ", publicKey)

    // Validate test
    testMnemonic := "drip hover remember layer torch father remind voyage fatigue skull mango business local lawsuit balance omit surprise silent peasant pull shrug promote holiday armor"
    testMasterKey := "xprv9s21ZrQH143K4ZyKb8QHCDbbWZ2qUkBRtQZ3y9bnGnmYzxumiJCJYvsLXfiBtkTdwJ9G6g213z8dxCFotenv4TyUNy3rr5nqvABZkzyBxm7"
    testPublicKey := "xpub661MyMwAqRbcH43nh9wHZMYL4asKtCuHFdUemY1Pq8JXsmEvFqWZ6jBpNxxZr2d2qErR5vKzU2vVecv7fLkNfma9yVmLe9JZrtCCz72MtWg"

    revSeed := bip39.NewSeed(testMnemonic, "Secret Passphrase")

    revMasterKey, _ := bip32.NewMasterKey(revSeed)
    revPublicKey := revMasterKey.PublicKey()

    validMnemonic := bip39.IsMnemonicValid(testMnemonic)

    validMaster := false
    if revMasterKey.String() == testMasterKey {
        validMaster = true
    }

    validPublic := false
    if revPublicKey.String() == testPublicKey {
        validPublic = true
    }

    fmt.Println("Valid mnemonic: ", validMnemonic)
    fmt.Println("Valid master private key: ", validMaster)
    fmt.Println("Valid master public key: ", validPublic)
}