/
private_key.go
119 lines (102 loc) · 2.45 KB
/
private_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
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
package mint
import (
"encoding/json"
"fmt"
"github.com/void616/gm.mint/internal/ed25519"
)
// PrivateKeySize is private key length in bytes
const PrivateKeySize = 64
// PrivateKey bytes
type PrivateKey [PrivateKeySize]byte
// NewPrivateKey generates a new random private key
func NewPrivateKey() (p PrivateKey, err error) {
_, epk, err := ed25519.GenerateKey(nil)
if err != nil {
return
}
// pk contains seed+public, prehash it
b := epk.Prehash()
copy(p[:], b[:64])
return
}
// MustNewPrivateKey generates a new random private key or panics on error
func MustNewPrivateKey() PrivateKey {
p, err := NewPrivateKey()
if err != nil {
panic(err)
}
return p
}
// PublicKey of the private key
func (p PrivateKey) PublicKey() PublicKey {
pub, err := BytesToPublicKey(ed25519.PublicKeyFromPrehashedPK(p[:]))
if err != nil {
panic(err)
}
return pub
}
// Bytes of the instance
func (p PrivateKey) Bytes() []byte {
b := make([]byte, len(p[:]))
copy(b, p[:])
return b
}
// String packs the instance into a Base58 string
func (p PrivateKey) String() string {
return Pack58(p[:])
}
// StringMask packs the instance into 6+4 a masked Base58 string
func (p PrivateKey) StringMask() string {
return MaskString6P4(p.String())
}
// MarshalJSON impl
func (p PrivateKey) MarshalJSON() ([]byte, error) {
return json.Marshal(p.String())
}
// UnmarshalJSON impl
func (p *PrivateKey) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
x, err := ParsePrivateKey(s)
if err != nil {
return err
}
copy(p[:], x[:])
return nil
}
// ParsePrivateKey parses an instance from Base58 string
func ParsePrivateKey(s string) (PrivateKey, error) {
var v PrivateKey
b, err := Unpack58(s)
if err != nil {
return v, err
}
return BytesToPrivateKey(b)
}
// MustParsePrivateKey parses an instance from Base58 string or panics
func MustParsePrivateKey(s string) PrivateKey {
v, err := ParsePrivateKey(s)
if err != nil {
panic(err)
}
return v
}
// BytesToPrivateKey creates an instance from a bytes slice
func BytesToPrivateKey(b []byte) (PrivateKey, error) {
var v PrivateKey
if len(b) != PrivateKeySize {
return v, fmt.Errorf("invalid length, got %v expected %v", len(b), PrivateKeySize)
}
copy(v[:], b)
return v, nil
}
// MustBytesToPrivateKey creates an instance from bytes slice or panics
func MustBytesToPrivateKey(b []byte) PrivateKey {
v, err := BytesToPrivateKey(b)
if err != nil {
panic(err)
}
return v
}