forked from DeathwingTheBoss/hivego
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserializer.go
383 lines (319 loc) · 8.68 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package hivego
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"math"
"strconv"
"strings"
"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 appendVAsset(asset string, b *bytes.Buffer) error {
parts := strings.Split(asset, " ")
if len(parts) != 2 {
return errors.New("invalid asset format: " + asset)
}
amountStr, symbol := parts[0], parts[1]
// all tokens have precision 3 except for VESTS
precision := 3
if symbol == "VESTS" {
precision = 6
}
// convert to their old names for compatibility
switch symbol {
case "HIVE":
symbol = "STEEM"
case "HBD":
symbol = "SBD"
}
// convert to float and multiply by 10^precision
amount, err := strconv.ParseFloat(amountStr, 64)
if err != nil {
return err
}
amount = amount * math.Pow10(precision)
// write the amount as int64
err = binary.Write(b, binary.LittleEndian, int64(amount))
if err != nil {
return err
}
// write the precision
b.WriteByte(byte(precision))
// write the symbol NUL padded to 8 bits
for i := 0; i < 7; i++ {
if i < len(symbol) {
b.WriteByte(symbol[i])
} else {
b.WriteByte(byte(0))
}
}
return nil
}
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.OpName())})
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.OpName())})
appendVStringArray(o.RequiredAuths, &jBuf)
appendVStringArray(o.RequiredPostingAuths, &jBuf)
appendVString(o.Id, &jBuf)
appendVString(o.Json, &jBuf)
return jBuf.Bytes(), nil
}
func (o ClaimRewardOperation) SerializeOp() ([]byte, error) {
var claimBuf bytes.Buffer
claimBuf.Write([]byte{opIdB(o.OpName())})
appendVString(o.Account, &claimBuf)
err := appendVAsset(o.RewardHIVE, &claimBuf)
if err != nil {
return nil, err
}
err = appendVAsset(o.RewardHBD, &claimBuf)
if err != nil {
return nil, err
}
err = appendVAsset(o.RewardVests, &claimBuf)
if err != nil {
return nil, err
}
return claimBuf.Bytes(), nil
}
func (o TransferOperation) SerializeOp() ([]byte, error) {
var transferBuf bytes.Buffer
transferBuf.Write([]byte{opIdB(o.OpName())})
appendVString(o.From, &transferBuf)
appendVString(o.To, &transferBuf)
appendVAsset(o.Amount, &transferBuf)
appendVString(o.Memo, &transferBuf)
return transferBuf.Bytes(), nil
}
func (a AccountUpdateOperation) SerializeOp() ([]byte, error) {
var buf bytes.Buffer
// operation ID
buf.WriteByte(opIdB(a.OpName()))
// account name
appendVString(a.Account, &buf)
// serialize optional authorities (owner, active, posting)
// TODO: THIS IS UNTESTED
appendOptionalAuthority(a.Owner, &buf)
appendOptionalAuthority(a.Active, &buf)
appendOptionalAuthority(a.Posting, &buf)
// memo key
//
// The memo key is kept as a string argument for the sake of simplicity and
// because it's intuative to the user. However, it must be serialized as a
// public key. We decode the public key and compressed to 33 bytes to actually
// be used.
pubKey, err := DecodePublicKey(a.MemoKey)
if err != nil {
return nil, err
}
buf.Write(pubKey.SerializeCompressed())
// JSON metadata
appendVString(a.JsonMetadata, &buf)
return buf.Bytes(), nil
}
func (o TransferToSavings) SerializeOp() ([]byte, error) {
// OperationSerializers.transfer_to_savings = OperationDataSerializer(32, [
// ['from', StringSerializer],
// ['to', StringSerializer],
// ['amount', AssetSerializer],
// ['memo', StringSerializer]
// ])
var buf bytes.Buffer
buf.WriteByte(opIdB(o.OpName()))
appendVString(o.From, &buf)
appendVString(o.To, &buf)
appendVAsset(o.Amount, &buf)
appendVString(o.Memo, &buf)
return buf.Bytes(), nil
}
func (o TransferFromSavings) SerializeOp() ([]byte, error) {
// OperationSerializers.transfer_from_savings = OperationDataSerializer(33, [
// ['from', StringSerializer],
// ['request_id', UInt32Serializer],
// ['to', StringSerializer],
// ['amount', AssetSerializer],
// ['memo', StringSerializer]
// ])
var buf bytes.Buffer
buf.WriteByte(opIdB(o.OpName()))
appendVString(o.From, &buf)
err := binary.Write(&buf, binary.LittleEndian, uint32(o.RequestId))
if err != nil {
return nil, err
}
appendVString(o.To, &buf)
appendVAsset(o.Amount, &buf)
appendVString(o.Memo, &buf)
return buf.Bytes(), nil
}
func (o CancelTransferFromSavings) SerializeOp() ([]byte, error) {
// OperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(
// 34,
// [
// ['from', StringSerializer],
// ['request_id', UInt32Serializer]
// ]
// )
var buf bytes.Buffer
buf.WriteByte(opIdB(o.OpName()))
appendVString(o.From, &buf)
err := binary.Write(&buf, binary.LittleEndian, uint32(o.RequestId))
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// todo: UNTESTED
func appendOptionalAuthority(auth *Auths, buf *bytes.Buffer) {
if auth != nil {
buf.WriteByte(1) // field is present, so we prepend a 1
serializeAuthority(*auth, buf)
} else {
buf.WriteByte(0) // field is absent, so we write a 0
}
}
// todo: UNTESTED
// encodes a uint64 into a variable-length byte slice and writes it to w
func WriteUvarint(w io.Writer, x uint64) error {
var buf [binary.MaxVarintLen64]byte
n := binary.PutUvarint(buf[:], x)
if _, err := w.Write(buf[:n]); err != nil {
return fmt.Errorf("failed to write Uvarint: %w", err)
}
return nil
}
// todo: UNTESTED
// encodes an int64 into a variable-length byte slice and writes it to w
func WriteVarint(w io.Writer, x int64) error {
var buf [binary.MaxVarintLen64]byte
n := binary.PutVarint(buf[:], x)
if _, err := w.Write(buf[:n]); err != nil {
return fmt.Errorf("failed to write Varint: %w", err)
}
return nil
}
// todo: UNTESTED
func serializeAuthority(auth Auths, buf *bytes.Buffer) {
// write weight_threshold
err := binary.Write(buf, binary.LittleEndian, uint32(auth.WeightThreshold))
if err != nil {
fmt.Printf("Error writing weight_threshold: %v\n", err)
return
}
// write account_auths
err = WriteUvarint(buf, uint64(len(auth.AccountAuths)))
if err != nil {
log.Printf("error writing account_auths length: %v\n", err)
return
}
for _, accountAuth := range auth.AccountAuths {
appendVString(accountAuth[0].(string), buf)
err = binary.Write(buf, binary.LittleEndian, uint16(accountAuth[1].(int)))
if err != nil {
log.Printf("error writing account_auth weight: %v\n", err)
return
}
}
// write key_auths
err = WriteUvarint(buf, uint64(len(auth.KeyAuths)))
if err != nil {
log.Printf("error writing key_auths length: %v\n", err)
return
}
for _, keyAuth := range auth.KeyAuths {
appendVString(keyAuth[0].(string), buf)
err = binary.Write(buf, binary.LittleEndian, uint16(keyAuth[1].(int)))
if err != nil {
log.Printf("error writing key_auth weight: %v\n", err)
return
}
}
}