This repository has been archived by the owner on Oct 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
keys.go
70 lines (56 loc) · 1.69 KB
/
keys.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
package keys
import (
"encoding/json"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcutil"
"github.com/pkg/errors"
)
// Keys represents a simple wrapper for generated keys
type Keys struct {
PrivateKey *btcec.PrivateKey
PublicKey *btcec.PublicKey
AddressPKH *btcutil.AddressPubKeyHash
}
// New creates new keys object
func New() (*Keys, error) {
privateKey, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return nil, errors.Wrap(err, "failed to create private key")
}
pubKey := privateKey.PubKey().SerializeCompressed()
addressPKH, err := btcutil.NewAddressPubKeyHash(btcutil.Hash160(pubKey), &chaincfg.Params{})
if err != nil {
return nil, errors.Wrap(err, "failed to create address public key hash")
}
return &Keys{
PrivateKey: privateKey,
PublicKey: privateKey.PubKey(),
AddressPKH: addressPKH,
}, nil
}
// MarshalJSON returns marshaled keys
// This is not the best way to serialize, but this is a prototype :)
func (k *Keys) MarshalJSON() ([]byte, error) {
key := struct {
PrivateKey []byte `json:"private_key"`
}{k.PrivateKey.Serialize()}
return json.Marshal(&key)
}
// UnmarshalJSON does unmarshal keys
func (k *Keys) UnmarshalJSON(d []byte) error {
var key struct {
PrivateKey []byte `json:"private_key"`
}
err := json.Unmarshal(d, &key)
if err != nil {
return err
}
k.PrivateKey, k.PublicKey = btcec.PrivKeyFromBytes(btcec.S256(), key.PrivateKey)
pubKey := k.PublicKey.SerializeCompressed()
k.AddressPKH, err = btcutil.NewAddressPubKeyHash(btcutil.Hash160(pubKey), &chaincfg.Params{})
if err != nil {
return errors.Wrap(err, "failed to create address public key hash during unmarshal")
}
return err
}