-
Notifications
You must be signed in to change notification settings - Fork 8
/
serializer.go
118 lines (100 loc) · 2.5 KB
/
serializer.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
package hivego
import (
"bytes"
"encoding/binary"
"time"
)
func opIdB(opName string) byte {
id := getHiveOpId(opName)
return byte(id)
}
func refBlockNumB(refBlockNumber uint16) []byte {
buf := make([]byte, 2)
binary.LittleEndian.PutUint16(buf, refBlockNumber)
return buf
}
func refBlockPrefixB(refBlockPrefix uint32) []byte {
buf := make([]byte, 4)
binary.LittleEndian.PutUint32(buf, refBlockPrefix)
return buf
}
func expTimeB(expTime string) ([]byte, error) {
exp, err := time.Parse("2006-01-02T15:04:05", expTime)
if err != nil {
return nil, err
}
buf := make([]byte, 4)
binary.LittleEndian.PutUint32(buf, uint32(exp.Unix()))
return buf, nil
}
func countOpsB(ops []hiveOperation) []byte {
b := make([]byte, 5)
l := binary.PutUvarint(b, uint64(len(ops)))
return b[0:l]
}
func extensionsB() byte {
return byte(0x00)
}
func appendVString(s string, b *bytes.Buffer) *bytes.Buffer {
vBuf := make([]byte, 5)
vLen := binary.PutUvarint(vBuf, uint64(len(s)))
b.Write(vBuf[0:vLen])
b.WriteString(s)
return b
}
func appendVStringArray(a []string, b *bytes.Buffer) *bytes.Buffer {
b.Write([]byte{byte(len(a))})
for _, s := range a {
appendVString(s, b)
}
return b
}
func serializeTx(tx hiveTransaction) ([]byte, error) {
var buf bytes.Buffer
buf.Write(refBlockNumB(tx.RefBlockNum))
buf.Write(refBlockPrefixB(tx.RefBlockPrefix))
expTime, err := expTimeB(tx.Expiration)
if err != nil {
return nil, err
}
buf.Write(expTime)
opsB, err := serializeOps(tx.Operations)
if err != nil {
return nil, err
}
buf.Write(opsB)
buf.Write([]byte{extensionsB()})
return buf.Bytes(), nil
}
func serializeOps(ops []hiveOperation) ([]byte, error) {
var opsBuf bytes.Buffer
opsBuf.Write(countOpsB(ops))
for _, op := range ops {
b, err := op.serializeOp()
if err != nil {
return nil, err
}
opsBuf.Write(b)
}
return opsBuf.Bytes(), nil
}
func (o voteOperation) serializeOp() ([]byte, error) {
var voteBuf bytes.Buffer
voteBuf.Write([]byte{opIdB(o.opText)})
appendVString(o.Voter, &voteBuf)
appendVString(o.Author, &voteBuf)
appendVString(o.Permlink, &voteBuf)
weightBuf := make([]byte, 2)
binary.LittleEndian.PutUint16(weightBuf, uint16(o.Weight))
voteBuf.Write(weightBuf)
return voteBuf.Bytes(), nil
}
func (o customJsonOperation) serializeOp() ([]byte, error) {
var jBuf bytes.Buffer
jBuf.Write([]byte{opIdB(o.opText)})
appendVStringArray(o.RequiredAuths, &jBuf)
appendVStringArray(o.RequiredPostingAuths, &jBuf)
appendVString(o.Id, &jBuf)
appendVString(o.Json, &jBuf)
return jBuf.Bytes(), nil
}