This repository has been archived by the owner on May 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 346
/
rlp.go
334 lines (294 loc) · 7.63 KB
/
rlp.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
package rlp
import (
"bytes"
"encoding/binary"
"fmt"
"math/bits"
"reflect"
)
const (
EmptyString = 0x80
EmptySlice = 0xC0
)
type Code uint32
const (
ErrUnknown Code = iota
ErrNoInput
ErrInvalid
)
func (c Code) Error() string {
switch c {
case ErrNoInput:
return "no input"
case ErrInvalid:
return "input not valid RLP encoding"
default:
return "unknown error"
}
}
func encodeUint8(input uint8) ([]byte, error) {
if input == 0 {
return []byte{EmptyString}, nil
} else if input >= 0x00 && input <= 0x7f {
return []byte{input}, nil
} else if input >= 0x80 && input <= 0xff {
return []byte{0x81, input}, nil
}
return []byte{EmptyString}, nil
}
func encodeUint64(i uint64) ([]byte, error) {
size := bits.Len64(i)/8 + 1
if size == 1 {
return encodeUint8(uint8(i))
}
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(i))
return encodeString(b[8-size:])
}
func encodeLength(n, offset int) []byte {
if n <= 55 {
return []uint8{uint8(n + offset)}
}
i := uint64(n)
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, i)
size := bits.Len64(i)/8 + 1
return append([]byte{uint8(0xb7 + len(string(n)))}, b[8-size:]...)
}
func encodeString(input []byte) ([]byte, error) {
if len(input) == 0 {
return []byte{EmptyString}, nil
} else if len(input) == 1 {
return encodeUint8(input[0])
} else {
return append(encodeLength(len(input), EmptyString), []byte(input)...), nil
}
}
func encodeList(val reflect.Value) ([]byte, error) {
if val.Len() == 0 {
return []byte{EmptySlice}, nil
}
out := make([][]byte, 0)
for i := 0; i < val.Len(); i++ {
data, err := encode(val.Index(i).Interface())
if err != nil {
return nil, err
}
out = append(out, data)
}
sum := bytes.Join(out, []byte{})
return append(encodeLength(len(sum), EmptySlice), sum...), nil
}
func encodeStruct(val reflect.Value) ([]byte, error) {
out := make([][]byte, 0)
for i := 0; i < val.NumField(); i++ {
data, err := encode(val.Field(i).Interface())
if err != nil {
return nil, err
}
out = append(out, data)
}
sum := bytes.Join(out, []byte{})
return append(encodeLength(len(sum), EmptySlice), sum...), nil
}
func encode(input interface{}) ([]byte, error) {
val := reflect.ValueOf(input)
typ := reflect.TypeOf(input)
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i := val.Int()
if i < 0 {
return nil, fmt.Errorf("cannot rlp encode negative integer")
}
return encodeUint64(uint64(i))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return encodeUint64(val.Uint())
case reflect.Bool:
if val.Bool() {
return []byte{0x01}, nil
}
return []byte{EmptyString}, nil
case reflect.String:
return encodeString([]byte(reflect.ValueOf(input).String()))
case reflect.Slice:
switch typ.Elem().Kind() {
case reflect.Uint8:
return encodeString(reflect.ValueOf(input).Bytes())
default:
return encodeList(val)
}
case reflect.Struct:
return encodeStruct(val)
default:
return []byte{EmptyString}, nil
}
}
func Encode(input interface{}) ([]byte, error) {
return encode(input)
}
type fields struct {
fields [][]byte
}
func (f *fields) add(element []byte) {
f.fields = append(f.fields, element)
}
func decode(in []byte, out *fields) error {
if len(in) == 0 {
return nil
}
offset, length, typ, err := decodeLength(in)
if err != nil {
return err
}
switch typ {
case reflect.String:
out.add(in[offset:length])
case reflect.Slice:
err = decode(in[offset:length], out)
if err != nil {
return err
}
}
return decode(in[length:], out)
}
func decodeLength(input []byte) (uint8, uint8, reflect.Kind, error) {
length := len(input)
if length == 0 {
return 0, 0, reflect.Invalid, ErrNoInput
}
prefix := input[0]
if prefix <= 0x7f {
// single byte
return 0, 1, reflect.String, nil
} else if length > int(prefix-0x80) && prefix <= 0xb7 {
// short string
strLen := prefix - 0x80
if strLen == 1 && uint8(input[1]) <= 0x7f {
return 0, 0, reflect.Invalid, fmt.Errorf("single byte below 128 must be encoded as itself")
}
return 1, strLen + 1, reflect.String, nil
} else if length > int(prefix-0xb7) && prefix <= 0xbf {
// long string
next, err := getLength(input[1 : (prefix-0xb7)+1])
if err != nil {
return 0, 0, reflect.Invalid, err
} else if length > int(prefix-0xb7+next) {
lenOfStrLen := prefix - 0xb7
if input[1] == 0 {
return 0, 0, reflect.Invalid, fmt.Errorf("multi-byte length must have no leading zero")
}
strLen, err := getLength(input[1 : lenOfStrLen+1])
if err != nil {
return 0, 0, reflect.Invalid, err
} else if strLen < 56 {
return 0, 0, reflect.Invalid, fmt.Errorf("length below 56 must be encoded in one byte")
}
return lenOfStrLen + 1, lenOfStrLen + strLen, reflect.String, nil
}
} else if length > int(prefix-0xc0) && prefix <= 0xf7 {
// short list
lenOfList := prefix - 0xc0
return 1, lenOfList + 1, reflect.Slice, nil
} else if prefix <= 0xff && length > int(prefix-0xf7) {
// long list
lenOfListLen := (prefix - 0xf7) + 1
next, err := getLength(input[1:lenOfListLen])
if err != nil {
return 0, 0, reflect.Invalid, err
} else if length > int(prefix-0xf7+next) {
if input[1] == 0 {
return 0, 0, reflect.Invalid, fmt.Errorf("multi-byte length must have no leading zero")
}
listLen, err := getLength(input[1:lenOfListLen])
if err != nil {
return 0, 0, reflect.Invalid, err
} else if listLen < 56 {
return 0, 0, reflect.Invalid, fmt.Errorf("length below 56 must be encoded in one byte")
}
return lenOfListLen, lenOfListLen + listLen, reflect.Slice, nil
}
}
return 0, 0, reflect.Invalid, ErrInvalid
}
func getLength(data []byte) (uint8, error) {
length := len(data)
if length == 0 {
return 0, ErrNoInput
} else if length == 1 {
return uint8(data[0]), nil
} else {
next, err := getLength(data[0 : len(data)-1])
return uint8(data[len(data)-1]) + next, err
}
}
func decodeStruct(in reflect.Value, fields [][]byte) error {
if in.NumField() != len(fields) {
return fmt.Errorf("wrong number of fields; have %d, want %d", len(fields), in.NumField())
}
for i := 0; i < in.NumField(); i++ {
val := in.Field(i)
typ := in.Field(i).Type()
switch val.Kind() {
case reflect.String:
val.SetString(string(fields[i]))
case reflect.Uint64:
out := make([]byte, 8)
for j := range fields[i] {
out[len(out)-(len(fields[i])-j)] = fields[i][j]
}
val.SetUint(binary.BigEndian.Uint64(out))
case reflect.Slice:
if typ.Elem().Kind() != reflect.Uint8 {
continue
}
out := make([]byte, len(fields[i]))
for i, b := range fields[i] {
out[i] = b
}
val.SetBytes(out)
}
}
return nil
}
func Decode(src []byte, dst interface{}) error {
dec := new(fields)
err := decode(src, dec)
if err != nil {
return err
}
val := reflect.ValueOf(dst)
typ := reflect.TypeOf(dst)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
switch val.Kind() {
case reflect.Slice:
switch typ.Elem().Kind() {
case reflect.Uint8:
out, ok := dst.([]byte)
if !ok {
return fmt.Errorf("cannot decode into type %s", val.Type())
}
found := bytes.Join(dec.fields, []byte(""))
if len(out) < len(found) {
return fmt.Errorf("cannot decode %d bytes into slice of size %d", len(found), len(out))
}
for i, b := range found {
out[i] = b
}
return nil
case reflect.Slice:
out, ok := dst.([][]byte)
if !ok {
return fmt.Errorf("cannot decode into type %s", val.Type())
}
for i := range out {
out[i] = dec.fields[i]
}
return nil
}
case reflect.Struct:
return decodeStruct(val, dec.fields)
}
return fmt.Errorf("cannot decode into unsupported type %v", reflect.TypeOf(dst))
}