-
Notifications
You must be signed in to change notification settings - Fork 0
/
btc.go
82 lines (68 loc) · 1.64 KB
/
btc.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
package keystore
import (
"crypto/ecdsa"
"fmt"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcutil"
)
type bitcoinKey key
func (key *bitcoinKey) GetAddress() ([]byte, error) {
chainParams, err := getChainParams(key.Network)
if err != nil {
return nil, err
}
wif, err := btcutil.DecodeWIF(key.PrivateKey)
if err != nil {
return nil, err
}
serializedPubKey := wif.SerializePubKey()
pubKey, err := btcutil.NewAddressPubKey(serializedPubKey, chainParams)
if err != nil {
return nil, err
}
return []byte(pubKey.EncodeAddress()), nil
}
func (key *bitcoinKey) GetKeyString() string {
return key.PrivateKey
}
func (key *bitcoinKey) GetKey() (*ecdsa.PrivateKey, error) {
wif, err := btcutil.DecodeWIF(key.PrivateKey)
if err != nil {
return nil, err
}
privKey := ecdsa.PrivateKey(*wif.PrivKey)
return &privKey, nil
}
func (key *bitcoinKey) PriorityCode() uint32 {
return key.Code
}
func (key *bitcoinKey) Chain() string {
return key.Network
}
func RandomBitcoinKeyString(chain string) (string, error) {
priv, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return "", err
}
chainParams, err := getChainParams(chain)
if err != nil {
return "", err
}
wif, err := btcutil.NewWIF(priv, chainParams, false)
if err != nil {
return "", err
}
return wif.String(), nil
}
func getChainParams(chain string) (*chaincfg.Params, error) {
switch chain {
case "regtest":
return &chaincfg.RegressionNetParams, nil
case "testnet":
return &chaincfg.TestNet3Params, nil
case "mainnet":
return &chaincfg.MainNetParams, nil
}
return nil, fmt.Errorf(ErrPrefix, "Unknown chain")
}