-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
102 lines (90 loc) · 2.18 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"encoding/hex"
"flag"
"fmt"
"unsafe"
"github.com/cosmos/go-bip39"
"github.com/tmthrgd/go-memset"
)
var (
argHdPath string
argCurve string
argMnemonic string
argPassword string
)
const defaultMnemonicBitSize = 256
func init() {
flag.StringVar(&argHdPath, "hdpath", "", "HD derivation path.")
flag.StringVar(&argCurve, "curve", "ed25519", "Elliptic curve to use.")
flag.StringVar(&argMnemonic, "mnemonic", "", "Mnemonic to derive a seed from. If empty, generate a new mnemonic.")
flag.StringVar(&argPassword, "password", "", "Password to use with BIP-39.")
flag.Parse()
}
func main() {
mnemonic := getMnemonic()
defer clearString(mnemonic)
seed := getSeed(mnemonic)
defer memset.Memset(seed, 0)
path := getHdPath()
key := DeriveKey(path, argCurve, seed)
defer memset.Memset(key.Private, 0)
pkHash := DerivePkHash(key)
addr := DeriveAddress(pkHash)
pk := DerivePublicKey(key)
fmt.Printf("mnemonic: %s\n", mnemonic)
fmt.Printf("public key: %s\n", pk)
fmt.Printf("private key: %s\n", hex.EncodeToString(key.Private))
fmt.Printf("public key hash: %s\n", hex.EncodeToString(pkHash[:20]))
fmt.Printf("address: %s\n", addr)
}
func getHdPath() []HdIndex {
if argHdPath == "" {
switch argCurve {
case "ed25519":
path, err := ParseHdPath(DefaultHdIndexEd25519)
if err != nil {
panic(err)
}
return path
case "secp256k1":
path, err := ParseHdPath(DefaultHdIndexSecp256k1)
if err != nil {
panic(err)
}
return path
default:
panic("invalid curve: " + argCurve)
}
}
path, err := ParseHdPath(argHdPath)
if err != nil {
panic(err)
}
return path
}
func getMnemonic() string {
if argMnemonic == "" {
entropy, err := bip39.NewEntropy(defaultMnemonicBitSize)
if err != nil {
panic(err)
}
mnemonic, err := bip39.NewMnemonic(entropy)
memset.Memset(entropy, 0)
if err != nil {
panic(err)
}
return mnemonic
} else {
if !bip39.IsMnemonicValid(argMnemonic) {
panic("invalid mnemonic: " + argMnemonic)
}
return argMnemonic
}
}
func getSeed(mnemonic string) []byte {
return bip39.NewSeed(mnemonic, argPassword)
}
func clearString(s string) {
memset.Memset(unsafe.Slice(unsafe.StringData(s), len(s)), 0)
}