-
Notifications
You must be signed in to change notification settings - Fork 5
/
pub_key.go
91 lines (77 loc) · 1.59 KB
/
pub_key.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
package crypto
import (
"encoding/hex"
"github.com/dipdup-net/go-lib/tools/encoding"
"github.com/pkg/errors"
)
// PubKey -
type PubKey struct {
address string
curve Curve
bytes []byte
}
// NewPubKey -
func NewPubKey(bytes []byte, curveKind ECKind) (PubKey, error) {
curve, err := NewCurve(curveKind)
if err != nil {
return PubKey{}, err
}
return PubKey{
bytes: bytes,
curve: curve,
}, nil
}
// NewPubKeyFromBase58 -
func NewPubKeyFromBase58(data string) (PubKey, error) {
if len(data) < 4 {
return PubKey{}, errors.Errorf("invalid public key string: %s", data)
}
curve, err := NewCurveFromPrefix(data[:4])
if err != nil {
return PubKey{}, err
}
bytes, err := encoding.DecodeBase58(data)
if err != nil {
return PubKey{}, err
}
return PubKey{
curve: curve,
bytes: bytes,
}, nil
}
// Address -
func (pk PubKey) Address() (string, error) {
if pk.address != "" {
return pk.address, nil
}
data, err := Blake2b160(pk.bytes)
if err != nil {
return "", err
}
result, err := encoding.EncodeBase58(data, pk.curve.AddressPrefix())
if err != nil {
return "", err
}
pk.address = result
return pk.address, nil
}
// Bytes -
func (pk PubKey) Bytes() []byte {
return pk.bytes
}
// Base58 -
func (pk PubKey) Base58() (string, error) {
return encoding.EncodeBase58(pk.bytes, pk.curve.PublicKeyPrefix())
}
// Hex -
func (pk PubKey) Hex() string {
return hex.EncodeToString(pk.bytes)
}
// String -
func (pk PubKey) String() string {
return pk.Hex()
}
// Verify -
func (pk PubKey) Verify(data, signature []byte) bool {
return pk.curve.Verify(data, signature, pk.bytes)
}