-
Notifications
You must be signed in to change notification settings - Fork 14
/
variant.go
353 lines (306 loc) · 11.3 KB
/
variant.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
// Copyright 2021 github.com/gagliardetto
// This file has been modified by github.com/gagliardetto
//
// Copyright 2020 dfuse Platform Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bin
import (
"bytes"
"encoding/binary"
"fmt"
"reflect"
"strings"
)
//
/// Variant (emulates `fc::static_variant` type)
//
type Variant interface {
Assign(typeID TypeID, impl interface{})
Obtain(*VariantDefinition) (typeID TypeID, typeName string, impl interface{})
}
type VariantType struct {
Name string
Type interface{}
}
type VariantDefinition struct {
typeIDToType map[TypeID]reflect.Type
typeIDToName map[TypeID]string
typeNameToID map[string]TypeID
typeIDEncoding TypeIDEncoding
}
// TypeID defines the internal representation of an instruction type ID
// (or account type, etc. in anchor programs)
// and it's used to associate instructions to decoders in the variant tracker.
type TypeID [8]byte
func (vid TypeID) Bytes() []byte {
return vid[:]
}
// Uvarint32 parses the TypeID to a uint32.
func (vid TypeID) Uvarint32() uint32 {
return Uvarint32FromTypeID(vid)
}
// Uint32 parses the TypeID to a uint32.
func (vid TypeID) Uint32() uint32 {
return Uint32FromTypeID(vid, binary.LittleEndian)
}
// Uint8 parses the TypeID to a Uint8.
func (vid TypeID) Uint8() uint8 {
return Uint8FromTypeID(vid)
}
// Equal returns true if the provided bytes are equal to
// the bytes of the TypeID.
func (vid TypeID) Equal(b []byte) bool {
return bytes.Equal(vid.Bytes(), b)
}
// TypeIDFromBytes converts a []byte to a TypeID.
// The provided slice must be 8 bytes long or less.
func TypeIDFromBytes(slice []byte) (id TypeID) {
// TODO: panic if len(slice) > 8 ???
copy(id[:], slice)
return id
}
// TypeIDFromSighash converts a sighash bytes to a TypeID.
func TypeIDFromSighash(sh []byte) TypeID {
return TypeIDFromBytes(sh)
}
// TypeIDFromUvarint32 converts a Uvarint to a TypeID.
func TypeIDFromUvarint32(v uint32) TypeID {
buf := make([]byte, 8)
l := binary.PutUvarint(buf, uint64(v))
return TypeIDFromBytes(buf[:l])
}
// TypeIDFromUint32 converts a uint32 to a TypeID.
func TypeIDFromUint32(v uint32, bo binary.ByteOrder) TypeID {
out := make([]byte, TypeSize.Uint32)
bo.PutUint32(out, v)
return TypeIDFromBytes(out)
}
// TypeIDFromUint32 converts a uint8 to a TypeID.
func TypeIDFromUint8(v uint8) TypeID {
return TypeIDFromBytes([]byte{v})
}
// Uvarint32FromTypeID parses a TypeID bytes to a uvarint 32.
func Uvarint32FromTypeID(vid TypeID) (out uint32) {
l, _ := binary.Uvarint(vid[:])
out = uint32(l)
return out
}
// Uint32FromTypeID parses a TypeID bytes to a uint32.
func Uint32FromTypeID(vid TypeID, order binary.ByteOrder) (out uint32) {
out = order.Uint32(vid[:])
return out
}
// Uint32FromTypeID parses a TypeID bytes to a uint8.
func Uint8FromTypeID(vid TypeID) (out uint8) {
return vid[0]
}
type TypeIDEncoding uint32
const (
Uvarint32TypeIDEncoding TypeIDEncoding = iota
Uint32TypeIDEncoding
Uint8TypeIDEncoding
// AnchorTypeIDEncoding is the instruction ID encoding used by programs
// written using the anchor SDK.
// The typeID is the sighash of the instruction.
AnchorTypeIDEncoding
// No type ID; ONLY ONE VARIANT PER PROGRAM.
NoTypeIDEncoding
)
var NoTypeIDDefaultID = TypeIDFromUint8(0)
// NewVariantDefinition creates a variant definition based on the *ordered* provided types.
//
// - For anchor instructions, it's the name that defines the binary variant value.
// - For all other types, it's the ordering that defines the binary variant value just like in native `nodeos` C++
// and in Smart Contract via the `std::variant` type. It's important to pass the entries
// in the right order!
//
// This variant definition can now be passed to functions of `BaseVariant` to implement
// marshal/unmarshaling functionalities for binary & JSON.
func NewVariantDefinition(typeIDEncoding TypeIDEncoding, types []VariantType) (out *VariantDefinition) {
if len(types) < 0 {
panic("it's not valid to create a variant definition without any types")
}
typeCount := len(types)
out = &VariantDefinition{
typeIDEncoding: typeIDEncoding,
typeIDToType: make(map[TypeID]reflect.Type, typeCount),
typeIDToName: make(map[TypeID]string, typeCount),
typeNameToID: make(map[string]TypeID, typeCount),
}
switch typeIDEncoding {
case Uvarint32TypeIDEncoding:
for i, typeDef := range types {
typeID := TypeIDFromUvarint32(uint32(i))
// FIXME: Check how the reflect.Type is used and cache all its usage in the definition.
// Right now, on each Unmarshal, we re-compute some expensive stuff that can be
// re-used like the `typeGo.Elem()` which is always the same. It would be preferable
// to have those already pre-defined here so we can actually speed up the
// Unmarshal code.
out.typeIDToType[typeID] = reflect.TypeOf(typeDef.Type)
out.typeIDToName[typeID] = typeDef.Name
out.typeNameToID[typeDef.Name] = typeID
}
case Uint32TypeIDEncoding:
for i, typeDef := range types {
typeID := TypeIDFromUint32(uint32(i), binary.LittleEndian)
// FIXME: Check how the reflect.Type is used and cache all its usage in the definition.
// Right now, on each Unmarshal, we re-compute some expensive stuff that can be
// re-used like the `typeGo.Elem()` which is always the same. It would be preferable
// to have those already pre-defined here so we can actually speed up the
// Unmarshal code.
out.typeIDToType[typeID] = reflect.TypeOf(typeDef.Type)
out.typeIDToName[typeID] = typeDef.Name
out.typeNameToID[typeDef.Name] = typeID
}
case Uint8TypeIDEncoding:
for i, typeDef := range types {
typeID := TypeIDFromUint8(uint8(i))
// FIXME: Check how the reflect.Type is used and cache all its usage in the definition.
// Right now, on each Unmarshal, we re-compute some expensive stuff that can be
// re-used like the `typeGo.Elem()` which is always the same. It would be preferable
// to have those already pre-defined here so we can actually speed up the
// Unmarshal code.
out.typeIDToType[typeID] = reflect.TypeOf(typeDef.Type)
out.typeIDToName[typeID] = typeDef.Name
out.typeNameToID[typeDef.Name] = typeID
}
case AnchorTypeIDEncoding:
for _, typeDef := range types {
typeID := TypeIDFromSighash(Sighash(SIGHASH_GLOBAL_NAMESPACE, typeDef.Name))
// FIXME: Check how the reflect.Type is used and cache all its usage in the definition.
// Right now, on each Unmarshal, we re-compute some expensive stuff that can be
// re-used like the `typeGo.Elem()` which is always the same. It would be preferable
// to have those already pre-defined here so we can actually speed up the
// Unmarshal code.
out.typeIDToType[typeID] = reflect.TypeOf(typeDef.Type)
out.typeIDToName[typeID] = typeDef.Name
out.typeNameToID[typeDef.Name] = typeID
}
case NoTypeIDEncoding:
if len(types) != 1 {
panic(fmt.Sprintf("NoTypeIDEncoding can only have one variant type definition, got %v", len(types)))
}
typeDef := types[0]
typeID := NoTypeIDDefaultID
// FIXME: Check how the reflect.Type is used and cache all its usage in the definition.
// Right now, on each Unmarshal, we re-compute some expensive stuff that can be
// re-used like the `typeGo.Elem()` which is always the same. It would be preferable
// to have those already pre-defined here so we can actually speed up the
// Unmarshal code.
out.typeIDToType[typeID] = reflect.TypeOf(typeDef.Type)
out.typeIDToName[typeID] = typeDef.Name
out.typeNameToID[typeDef.Name] = typeID
default:
panic(fmt.Errorf("unsupported TypeIDEncoding: %v", typeIDEncoding))
}
return out
}
func (d *VariantDefinition) TypeID(name string) TypeID {
id, found := d.typeNameToID[name]
if !found {
knownNames := make([]string, len(d.typeNameToID))
i := 0
for name := range d.typeNameToID {
knownNames[i] = name
i++
}
panic(fmt.Errorf("trying to use an unknown type name %q, known names are %q", name, strings.Join(knownNames, ", ")))
}
return id
}
type (
VariantImplFactory = func() interface{}
OnVariant = func(impl interface{}) error
)
type BaseVariant struct {
TypeID TypeID
Impl interface{}
}
var _ Variant = &BaseVariant{}
func (a *BaseVariant) Assign(typeID TypeID, impl interface{}) {
a.TypeID = typeID
a.Impl = impl
}
func (a *BaseVariant) Obtain(def *VariantDefinition) (typeID TypeID, typeName string, impl interface{}) {
return a.TypeID, def.typeIDToName[a.TypeID], a.Impl
}
func (a *BaseVariant) UnmarshalBinaryVariant(decoder *Decoder, def *VariantDefinition) (err error) {
var typeID TypeID
switch def.typeIDEncoding {
case Uvarint32TypeIDEncoding:
val, err := decoder.ReadUvarint32()
if err != nil {
return fmt.Errorf("uvarint32: unable to read variant type id: %s", err)
}
typeID = TypeIDFromUvarint32(val)
case Uint32TypeIDEncoding:
val, err := decoder.ReadUint32(binary.LittleEndian)
if err != nil {
return fmt.Errorf("uint32: unable to read variant type id: %s", err)
}
typeID = TypeIDFromUint32(val, binary.LittleEndian)
case Uint8TypeIDEncoding:
id, err := decoder.ReadUint8()
if err != nil {
return fmt.Errorf("uint8: unable to read variant type id: %s", err)
}
typeID = TypeIDFromBytes([]byte{id})
case AnchorTypeIDEncoding:
typeID, err = decoder.ReadTypeID()
if err != nil {
return fmt.Errorf("anchor: unable to read variant type id: %s", err)
}
case NoTypeIDEncoding:
typeID = NoTypeIDDefaultID
}
a.TypeID = typeID
typeGo := def.typeIDToType[typeID]
if typeGo == nil {
return fmt.Errorf("no known type for type %d", typeID)
}
if typeGo.Kind() == reflect.Ptr {
a.Impl = reflect.New(typeGo.Elem()).Interface()
if err = decoder.Decode(a.Impl); err != nil {
return fmt.Errorf("unable to decode variant type %d: %s", typeID, err)
}
} else {
// This is not the most optimal way of doing things for "value"
// types (over "pointer" types) as we always allocate a new pointer
// element, unmarshal it and then either keep the pointer type or turn
// it into a value type.
//
// However, in non-reflection based code, one would do like this and
// avoid an `new` memory allocation:
//
// ```
// name := eos.Name("")
// json.Unmarshal(data, &name)
// ```
//
// This would work without a problem. In reflection code however, I
// did not find how one can go from `reflect.Zero(typeGo)` (which is
// the equivalence of doing `name := eos.Name("")`) and take the
// pointer to it so it can be unmarshalled correctly.
//
// A played with various iteration, and nothing got it working. Maybe
// the next step would be to explore the `unsafe` package and obtain
// an unsafe pointer and play with it.
value := reflect.New(typeGo)
if err = decoder.Decode(value.Interface()); err != nil {
return fmt.Errorf("unable to decode variant type %d: %s", typeID, err)
}
a.Impl = value.Elem().Interface()
}
return nil
}