forked from casper-ecosystem/casper-golang-sdk
/
types.go
96 lines (77 loc) · 1.62 KB
/
types.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
package keypair
import (
"bytes"
"encoding/hex"
"encoding/json"
"io"
)
type KeyTag byte
const (
KeyTagEd25519 KeyTag = iota + 1
KeyTagSecp256k1
)
const (
StrKeyTagEd25519 = "ed25519"
StrKeyTagSecp256k1 = "secp256k1"
Separator byte = 0
)
type PublicKey struct {
Tag KeyTag
PubKeyData []byte
}
func (key PublicKey) Marshal(w io.Writer) (int, error) {
n, err := w.Write([]byte{byte(key.Tag)})
if err != nil {
return n, err
}
n2, err := w.Write(key.PubKeyData)
n += n2
return n, err
}
func (key PublicKey) MarshalJSON() ([]byte, error) {
var w bytes.Buffer
_, err := key.Marshal(&w)
if err != nil {
return nil, nil
}
return json.Marshal(hex.EncodeToString(w.Bytes()))
}
func (key *PublicKey) UnmarshalJSON(data []byte) error {
var result string
if err := json.Unmarshal(data, &result); err != nil {
return err
}
resultHex, err := hex.DecodeString(result)
if err != nil {
return err
}
key.Tag = KeyTag(resultHex[0])
key.PubKeyData = resultHex[1:]
return nil
}
func (key PublicKey) ToBytes() ([]byte, error) {
var w bytes.Buffer
_, err := key.Marshal(&w)
return w.Bytes(), err
}
type Signature struct {
Tag KeyTag
SignatureData []byte
}
func (signature Signature) Marshal(w io.Writer) (int, error) {
n, err := w.Write([]byte{byte(signature.Tag)})
if err != nil {
return n, err
}
n2, err := w.Write(signature.SignatureData)
n += n2
return n, err
}
func (signature Signature) MarshalJSON() ([]byte, error) {
var w bytes.Buffer
_, err := signature.Marshal(&w)
if err != nil {
return nil, nil
}
return json.Marshal(hex.EncodeToString(w.Bytes()))
}