-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
537 lines (442 loc) · 13.8 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package main
import (
"flag"
"fmt"
"log"
"strings"
"sync"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcutil"
"github.com/tyler-smith/go-bip32"
"github.com/tyler-smith/go-bip39"
crypto "github.com/ethereum/go-ethereum/crypto"
)
// Purpose BIP43 - Purpose Field for Deterministic Wallets
// https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
//
// Purpose is a constant set to 44' (or 0x8000002C) following the BIP43 recommendation.
// It indicates that the subtree of this node is used according to this specification.
//
// What does 44' mean in BIP44?
// https://bitcoin.stackexchange.com/questions/74368/what-does-44-mean-in-bip44
//
// 44' means that hardened keys should be used. The distinguisher for whether
// a key a given index is hardened is that the index is greater than 2^31,
// which is 2147483648. In hex, that is 0x80000000. That is what the apostrophe (') means.
// The 44 comes from adding it to 2^31 to get the final hardened key index.
// In hex, 44 is 2C, so 0x80000000 + 0x2C = 0x8000002C.
type Purpose = uint32
const (
PurposeBIP44 Purpose = 0x8000002C // 44' BIP44
PurposeBIP49 Purpose = 0x80000031 // 49' BIP49
PurposeBIP84 Purpose = 0x80000054 // 84' BIP84
)
// CoinType SLIP-0044 : Registered coin types for BIP-0044
// https://github.com/satoshilabs/slips/blob/master/slip-0044.md
type CoinType = uint32
const (
CoinTypeBTC CoinType = 0x80000000
CoinTypeLTC CoinType = 0x80000002
CoinTypeETH CoinType = 0x8000003c
CoinTypeEOS CoinType = 0x800000c2
)
const (
Apostrophe uint32 = 0x80000000 // 0'
)
type Key struct {
path string
bip32Key *bip32.Key
}
func (k *Key) Encode(compress bool) (wif, address, segwitBech32, segwitNested string, privateKey string, err error) {
prvKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), k.bip32Key.Key)
return GenerateFromBytes(prvKey, compress)
}
func (k *Key) EncodeEth() (address string, publicKey string, privateKey string) {
prvKey, pubKey := btcec.PrivKeyFromBytes(btcec.S256(), k.bip32Key.Key)
pub := pubKey.ToECDSA()
address = crypto.PubkeyToAddress(*pub).Hex()
publicKey = string(crypto.FromECDSAPub(pub))
privateKey = fmt.Sprintf("%x", prvKey.D)
return address, publicKey, privateKey
}
// https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
// bip44 define the following 5 levels in BIP32 path:
// m / purpose' / coin_type' / account' / change / address_index
func (k *Key) GetPath() string {
return k.path
}
type KeyManager struct {
mnemonic string
passphrase string
keys map[string]*bip32.Key
mux sync.Mutex
}
// NewKeyManager return new key manager
// bitSize has to be a multiple 32 and be within the inclusive range of {128, 256}
// 128: 12 phrases
// 256: 24 phrases
func NewKeyManager(bitSize int, passphrase string) (*KeyManager, error) {
entropy, err := bip39.NewEntropy(bitSize)
if err != nil {
return nil, err
}
mnemonic, err := bip39.NewMnemonic(entropy)
if err != nil {
return nil, err
}
km := &KeyManager{
mnemonic: mnemonic,
passphrase: passphrase,
keys: make(map[string]*bip32.Key, 0),
}
return km, nil
}
// NewKeyManager return new key manager
// bitSize has to be a multiple 32 and be within the inclusive range of {128, 256}
// 128: 12 phrases
// 256: 24 phrases
func NewKeyManagerWithMnemonic(bitSize int, passphrase string, keyphrase string) (*KeyManager, error) {
entropy, err := bip39.EntropyFromMnemonic(keyphrase)
if err != nil {
return nil, err
}
/*
valid := bip39.IsMnemonicValid(keyphrase)
if valid == false {
err := errors.New("mnemonic not valid")
return nil, err
}
*/
mnemonic, err := bip39.NewMnemonic(entropy)
if err != nil {
return nil, err
}
km := &KeyManager{
mnemonic: mnemonic,
passphrase: passphrase,
keys: make(map[string]*bip32.Key, 0),
}
return km, nil
}
func (km *KeyManager) GetMnemonic() string {
return km.mnemonic
}
func (km *KeyManager) GetPassphrase() string {
return km.passphrase
}
func (km *KeyManager) GetSeed() []byte {
return bip39.NewSeed(km.GetMnemonic(), km.GetPassphrase())
}
func (km *KeyManager) getKey(path string) (*bip32.Key, bool) {
km.mux.Lock()
defer km.mux.Unlock()
key, ok := km.keys[path]
return key, ok
}
func (km *KeyManager) setKey(path string, key *bip32.Key) {
km.mux.Lock()
defer km.mux.Unlock()
km.keys[path] = key
}
func (km *KeyManager) GetMasterKey() (*bip32.Key, error) {
path := "m"
key, ok := km.getKey(path)
if ok {
return key, nil
}
key, err := bip32.NewMasterKey(km.GetSeed())
if err != nil {
return nil, err
}
km.setKey(path, key)
return key, nil
}
func (km *KeyManager) GetPurposeKey(purpose uint32) (*bip32.Key, error) {
path := fmt.Sprintf(`m/%d'`, purpose-Apostrophe)
key, ok := km.getKey(path)
if ok {
return key, nil
}
parent, err := km.GetMasterKey()
if err != nil {
return nil, err
}
key, err = parent.NewChildKey(purpose)
if err != nil {
return nil, err
}
km.setKey(path, key)
return key, nil
}
func (km *KeyManager) GetCoinTypeKey(purpose, coinType uint32) (*bip32.Key, error) {
path := fmt.Sprintf(`m/%d'/%d'`, purpose-Apostrophe, coinType-Apostrophe)
key, ok := km.getKey(path)
if ok {
return key, nil
}
parent, err := km.GetPurposeKey(purpose)
if err != nil {
return nil, err
}
key, err = parent.NewChildKey(coinType)
if err != nil {
return nil, err
}
km.setKey(path, key)
return key, nil
}
func (km *KeyManager) GetAccountKey(purpose, coinType, account uint32) (*bip32.Key, error) {
path := fmt.Sprintf(`m/%d'/%d'/%d'`, purpose-Apostrophe, coinType-Apostrophe, account)
key, ok := km.getKey(path)
if ok {
return key, nil
}
parent, err := km.GetCoinTypeKey(purpose, coinType)
if err != nil {
return nil, err
}
key, err = parent.NewChildKey(account + Apostrophe)
if err != nil {
return nil, err
}
km.setKey(path, key)
return key, nil
}
// GetChangeKey ...
// https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#change
// change constant 0 is used for external chain
// change constant 1 is used for internal chain (also known as change addresses)
func (km *KeyManager) GetChangeKey(purpose, coinType, account, change uint32) (*bip32.Key, error) {
path := fmt.Sprintf(`m/%d'/%d'/%d'/%d`, purpose-Apostrophe, coinType-Apostrophe, account, change)
key, ok := km.getKey(path)
if ok {
return key, nil
}
parent, err := km.GetAccountKey(purpose, coinType, account)
if err != nil {
return nil, err
}
key, err = parent.NewChildKey(change)
if err != nil {
return nil, err
}
km.setKey(path, key)
return key, nil
}
func (km *KeyManager) GetShortAccountKey(purpose uint32, coinType uint32, account uint32) (*bip32.Key, error) {
path := fmt.Sprintf(`m/%d'/%d'/%d`, purpose-Apostrophe, coinType-Apostrophe, account)
key, ok := km.getKey(path)
if ok {
return key, nil
}
key, err := km.GetAccountKey(purpose, coinType, account)
if err != nil {
return nil, err
}
km.setKey(path, key)
return key, nil
}
func (km *KeyManager) GetShortKey(purpose uint32, coinType uint32, account uint32, index uint32) (*Key, error) {
path := fmt.Sprintf(`m/%d'/%d'/%d'/%d`, purpose-Apostrophe, coinType-Apostrophe, account, index)
key, ok := km.getKey(path)
if ok {
return &Key{path: path, bip32Key: key}, nil
}
parent, err := km.GetShortAccountKey(purpose, coinType, account)
if err != nil {
return nil, err
}
key, err = parent.NewChildKey(index)
if err != nil {
return nil, err
}
km.setKey(path, key)
return &Key{path: path, bip32Key: key}, nil
}
func (km *KeyManager) GetKey(purpose, coinType, account, change, index uint32) (*Key, error) {
path := fmt.Sprintf(`m/%d'/%d'/%d'/%d/%d`, purpose-Apostrophe, coinType-Apostrophe, account, change, index)
key, ok := km.getKey(path)
if ok {
return &Key{path: path, bip32Key: key}, nil
}
parent, err := km.GetChangeKey(purpose, coinType, account, change)
if err != nil {
return nil, err
}
key, err = parent.NewChildKey(index)
if err != nil {
return nil, err
}
km.setKey(path, key)
return &Key{path: path, bip32Key: key}, nil
}
func Generate(compress bool) (wif, address, segwitBech32, segwitNested string, privateKey string, err error) {
prvKey, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return "", "", "", "", "", err
}
return GenerateFromBytes(prvKey, compress)
}
func GenerateFromBytes(prvKey *btcec.PrivateKey, compress bool) (wif, address, segwitBech32, segwitNested string, privateKey string, err error) {
// generate the wif(wallet import format) string
btcwif, err := btcutil.NewWIF(prvKey, &chaincfg.MainNetParams, compress)
if err != nil {
return "", "", "", "", "", err
}
wif = btcwif.String()
// generate a normal p2pkh address
serializedPubKey := btcwif.SerializePubKey()
addressPubKey, err := btcutil.NewAddressPubKey(serializedPubKey, &chaincfg.MainNetParams)
if err != nil {
return "", "", "", "", "", err
}
address = addressPubKey.EncodeAddress()
// generate a normal p2wkh address from the pubkey hash
witnessProg := btcutil.Hash160(serializedPubKey)
addressWitnessPubKeyHash, err := btcutil.NewAddressWitnessPubKeyHash(witnessProg, &chaincfg.MainNetParams)
if err != nil {
return "", "", "", "", "", err
}
segwitBech32 = addressWitnessPubKeyHash.EncodeAddress()
// generate an address which is
// backwards compatible to Bitcoin nodes running 0.6.0 onwards, but
// allows us to take advantage of segwit's scripting improvments,
// and malleability fixes.
serializedScript, err := txscript.PayToAddrScript(addressWitnessPubKeyHash)
if err != nil {
return "", "", "", "", "", err
}
addressScriptHash, err := btcutil.NewAddressScriptHash(serializedScript, &chaincfg.MainNetParams)
if err != nil {
return "", "", "", "", "", err
}
segwitNested = addressScriptHash.EncodeAddress()
privateKey = fmt.Sprintf("%x", prvKey.D)
return wif, address, segwitBech32, segwitNested, privateKey, nil
}
func main() {
compress := true // generate a compressed public key
bip39 := flag.Bool("bip39", false, "mnemonic code for generating deterministic keys")
pass := flag.String("pass", "", "protect bip39 mnemonic with a passphrase")
number := flag.Int("n", 10, "set number of keys to generate")
mnemonic := flag.String("phrase", "", "set the key phase mnemonic")
size := flag.Int("size", 24, "Key phase size, valid values are 12 or 24")
short := flag.Bool("s", false, "Use short derivation paths, as used with Ledger devices (ie. m/44'/60'/0'/0)")
flag.Parse()
var bitsize int
if *size == 24 {
bitsize = 256
} else if *size == 12 {
bitsize = 128
} else {
log.Fatal("Invalid size, value must be 12 or 24")
return
}
if !*bip39 {
fmt.Printf("\n%-34s %-34s %-52s %-42s %s\n", "Bitcoin Address", "Private Key", "WIF(Wallet Import Format)", "SegWit(bech32)", "SegWit(nested)")
fmt.Println(strings.Repeat("-", 165))
for i := 0; i < *number; i++ {
wif, address, segwitBech32, segwitNested, pk, err := Generate(compress)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-34s %s %s %s %s\n", address, pk, wif, segwitBech32, segwitNested)
}
fmt.Println()
return
}
var err error
var km *KeyManager
if *mnemonic != "" {
km, err = NewKeyManagerWithMnemonic(bitsize, *pass, *mnemonic)
} else {
km, err = NewKeyManager(bitsize, *pass)
}
if err != nil {
log.Fatal(err)
}
masterKey, err := km.GetMasterKey()
if err != nil {
log.Fatal(err)
}
passphrase := km.GetPassphrase()
if passphrase == "" {
passphrase = "<none>"
}
fmt.Printf("\n%-18s %s\n", "BIP39 Mnemonic:", km.GetMnemonic())
fmt.Printf("%-18s %s\n", "BIP39 Passphrase:", passphrase)
fmt.Printf("%-18s %x\n", "BIP39 Seed:", km.GetSeed())
fmt.Printf("%-18s %s\n", "BIP32 Root Key:", masterKey.B58Serialize())
fmt.Printf("\n%-18s %-42s %-44s\n", "Path(BIP44)", "Ethereum Address", "Private Key")
fmt.Println(strings.Repeat("-", 126))
for i := 0; i < *number; i++ {
var key *Key
if *short {
key, err = km.GetShortKey(PurposeBIP44, CoinTypeETH, 0, uint32(i))
} else {
key, err = km.GetKey(PurposeBIP44, CoinTypeETH, 0, 0, uint32(i))
}
if err != nil {
log.Fatal(err)
}
address, _, privateKey := key.EncodeEth()
fmt.Printf("%-18s %-34s %s\n", key.GetPath(), address, privateKey)
}
fmt.Printf("\n%s %22s %44s %38s\n", "Path(BIP44)", "Bitcoin Address", "WIF(Wallet Import Format)", "Private Key")
fmt.Println(strings.Repeat("-", 171))
for i := 0; i < *number; i++ {
var key *Key
if *short {
key, err = km.GetShortKey(PurposeBIP44, CoinTypeBTC, 0, uint32(i))
} else {
key, err = km.GetKey(PurposeBIP44, CoinTypeBTC, 0, 0, uint32(i))
}
if err != nil {
log.Fatal(err)
}
wif, address, _, _, pk, err := key.Encode(compress)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-18s %-34s %44s %s\n", key.GetPath(), address, wif, pk)
}
fmt.Printf("\n%-18s %-34s %24s %38s\n", "Path(BIP49)", "SegWit(nested)", "WIF(Wallet Import Format)", "Private key")
fmt.Println(strings.Repeat("-", 171))
for i := 0; i < *number; i++ {
var key *Key
if *short {
key, err = km.GetShortKey(PurposeBIP49, CoinTypeBTC, 0, uint32(i))
} else {
key, err = km.GetKey(PurposeBIP49, CoinTypeBTC, 0, 0, uint32(i))
}
if err != nil {
log.Fatal(err)
}
wif, _, _, segwitNested, pk, err := key.Encode(compress)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-18s %s %s %s\n", key.GetPath(), segwitNested, wif, pk)
}
fmt.Printf("\n%-18s %-42s %s %38s\n", "Path(BIP84)", "SegWit(bech32)", "WIF(Wallet Import Format)", "Private key")
fmt.Println(strings.Repeat("-", 179))
for i := 0; i < *number; i++ {
var key *Key
if *short {
key, err = km.GetShortKey(PurposeBIP84, CoinTypeBTC, 0, uint32(i))
} else {
key, err = km.GetKey(PurposeBIP84, CoinTypeBTC, 0, 0, uint32(i))
}
if err != nil {
log.Fatal(err)
}
wif, _, segwitBech32, _, pk, err := key.Encode(compress)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-18s %s %s %s\n", key.GetPath(), segwitBech32, wif, pk)
}
fmt.Println()
}