Created
July 18, 2019 10:56
-
-
Save leogr/7f19f9d10fccd476e9074aa6bb917d9f to your computer and use it in GitHub Desktop.
Golang BIP32 private key to Web3 Secret Storage conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"github.com/ethereum/go-ethereum/accounts/keystore" | |
"github.com/ethereum/go-ethereum/crypto" | |
"github.com/jbenet/go-base58" | |
"github.com/tyler-smith/go-bip32" | |
"github.com/tyler-smith/go-bip39" | |
) | |
func generateSeed(passphrase string) []byte { | |
// Generate a mnemonic for memorization or user-friendly seeds | |
entropy, _ := bip39.NewEntropy(256) | |
mnemonic, _ := bip39.NewMnemonic(entropy) | |
fmt.Println("Mnemonic: ", mnemonic) | |
return bip39.NewSeed(mnemonic, passphrase) | |
} | |
func newKs(keydir string) *keystore.KeyStore { | |
return keystore.NewKeyStore(keydir, keystore.StandardScryptN, keystore.StandardScryptP) | |
} | |
func main() { | |
// Generate a new seed | |
seed := generateSeed("") // or seed := bip39.NewSeed(mnemonic, "") to recover from a mnemonic | |
// Get the master key | |
masterKey, _ := bip32.NewMasterKey(seed) | |
publicKey := masterKey.PublicKey() | |
fmt.Println("BIP32 Master private key: ", masterKey) | |
fmt.Println("BIP32 Master public key: ", publicKey) | |
// To use derivate child keys instead, see: | |
// https://gist.github.com/miguelmota/f56fa0b01e8c6c649a6c4f0ee7337aab#file-bip32_ecdsa-go-L24 | |
// Extract the private key | |
decoded := base58.Decode(masterKey.B58Serialize()) | |
privateKey := decoded[46:78] | |
// Hex private key to ECDSA private key | |
privateKeyECDSA, err := crypto.ToECDSA(privateKey) | |
if err != nil { | |
panic(err) | |
} | |
// Import ECDSA key into the keystore | |
ks := newKs(".") | |
account, err := ks.ImportECDSA(privateKeyECDSA, "") | |
if err != nil { | |
panic(err) | |
} | |
// A Web3 Secret Storage JSON file is now stored in account.URL.Path, just print it out | |
b, err := ioutil.ReadFile(account.URL.Path) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("Web3 Secret Storage:") | |
fmt.Print(string(b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment