Skip to content

Instantly share code, notes, and snippets.

@paulbellamy
Created December 1, 2014 11:45
Show Gist options
  • Save paulbellamy/80954ea08e4450a35bb0 to your computer and use it in GitHub Desktop.
Save paulbellamy/80954ea08e4450a35bb0 to your computer and use it in GitHub Desktop.
Bitcoin Key Generator (broken)
//usr/bin/env go run $0 $@
package main
import (
"encoding/hex"
"flag"
"fmt"
"os"
"github.com/conformal/btcnet"
"github.com/conformal/btcutil"
"github.com/conformal/btcutil/hdkeychain"
)
var defaultBits = hdkeychain.RecommendedSeedLen * 8
var bits = flag.Int("bits", defaultBits, "Number of bits of seed to generate. Between 128-512")
var hexSeed = flag.String("seed", "", "Hex-encoded seed value to use. If none is provided, one will be generated")
var testnet = flag.Bool("testnet", false, "use the bitcoin testnet")
func netParams() *btcnet.Params {
if *testnet {
return &btcnet.TestNet3Params
} else {
return &btcnet.MainNetParams
}
}
func main() {
flag.Parse()
if *bits != defaultBits {
if *hexSeed != "" {
fmt.Fprintln(os.Stderr, "Cannot provide both --bits and --seed")
os.Exit(1)
}
if *bits > 512 || *bits < 128 {
fmt.Fprintln(os.Stderr, "--bits must be 128 <= bits <= 512")
os.Exit(1)
}
}
var seed []byte
var err error
if *hexSeed != "" {
seed, err = hex.DecodeString(*hexSeed)
} else {
seed, err = hdkeychain.GenerateSeed(uint8(*bits / 8))
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
key, err := hdkeychain.NewMaster(seed)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
key.SetNet(netParams())
address, err := key.Address(netParams())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
ecPrivKey, err := key.ECPrivKey()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
wif, err := btcutil.NewWIF(ecPrivKey, netParams(), false)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Fprintln(os.Stdout, "Key: ", key)
fmt.Fprintln(os.Stdout, "Address:", address)
fmt.Fprintln(os.Stdout, "WIF: ", wif)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment