/
types-metadata.go
322 lines (294 loc) · 9.19 KB
/
types-metadata.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
package wallet
import (
"encoding/hex"
"fmt"
"strconv"
)
const (
MetadataTypeInt = "int"
MetadataTypeString = "string"
MetadataTypeBytes = "bytes"
MetadataTypeList = "list"
MetadataTypeMap = "map"
MetadataMapKey = "k"
MetadataMapVal = "v"
)
// Metadata represents transaction metadata, as it is stored on the ledger.
// This type is manually added here, because oapi-codegen fails to generate it.
// The doc-comment below is copied from the Swagger definition.
//
// **⚠️ WARNING ⚠️**
//
// _Please note that metadata provided in a transaction will be
// stored on the blockchain forever. Make sure not to include any sensitive data,
// in particular personally identifiable information (PII)._
//
// Extra application data attached to the transaction.
//
// Cardano allows users and developers to embed their own
// authenticated metadata when submitting transactions. Metadata can
// be expressed as a JSON object with some restrictions:
//
// 1. All top-level keys must be integers between `0` and `2^64 - 1`.
//
// 2. Each metadata value is tagged with its type.
//
// 3. Strings must be at most 64 bytes when UTF-8 encoded.
//
// 4. Bytestrings are hex-encoded, with a maximum length of 64 bytes.
//
// Metadata aren't stored as JSON on the Cardano blockchain but are
// instead stored using a compact binary encoding (CBOR).
//
// The binary encoding of metadata values supports three simple types:
//
// * Integers in the range `-(2^64 - 1)` to `2^64 - 1`
// * Strings (UTF-8 encoded)
// * Bytestrings
//
// And two compound types:
//
// * Lists of metadata values
// * Mappings from metadata values to metadata values
//
// It is possible to transform any JSON object into this schema.
//
// However, if your application uses floating point values, they will
// need to be converted somehow, according to your
// requirements. Likewise for `null` or `bool` values. When reading
// metadata from chain, be aware that integers may exceed the
// javascript numeric range, and may need special "bigint" parsing.
type Metadata map[uint]interface{}
// TODO add Metadata.ParseInto by re-encoding the result of Parse() as clean json,
// and parsing it into an arbitrary interface{}
// TODO add EncodeMetadataFrom(interface{}) by dumping to json, re-parsing to a map[...]...
// and passing the result to EncodeMetadata()
// TODO how to handle bools, floats, and nil values?
// TODO Is it necessary to handle all primitive types in EncodeMetadata? Or better error out?
func (meta *Metadata) Parse() (map[uint]interface{}, error) {
if meta == nil || len(*meta) == 0 {
return nil, nil
}
result := make(map[uint]interface{})
for key, val := range *meta {
parsedVal, err := parseMetaValue(strconv.Itoa(int(key)), val)
if err != nil {
return nil, err
}
result[key] = parsedVal
}
return result, nil
}
func str(val interface{}) string {
// Limit length of error messages
s := fmt.Sprintf("%T: %v", val, val)
return fmt.Sprintf("%.25s", s)
}
func parseMetaValue(path string, rawVal interface{}) (interface{}, error) {
val, ok := rawVal.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("%v: unexpected type for metadata object: %s", path, str(rawVal))
}
if len(val) != 1 {
return nil, fmt.Errorf("%v: unexpected length of metadata object (%v): %s", path, len(val), str(val))
}
for valType, actualVal := range val {
// This loop will be entered only once
switch valType {
case MetadataTypeInt:
intVal, ok := actualVal.(int) // TODO this does not match int64 when encoding
if !ok {
return nil, fmt.Errorf("%v: expected type int, but got: %s", path, str(actualVal))
}
return intVal, nil
case MetadataTypeString:
strVal, ok := actualVal.(string)
if !ok {
return nil, fmt.Errorf("%v: expected type string, but got: %s", path, str(actualVal))
}
return strVal, nil
case MetadataTypeBytes:
strVal, ok := actualVal.(string)
if !ok {
return nil, fmt.Errorf("%v: expected type string, but got: %s", path, str(actualVal))
}
return parseByteString(path, strVal)
case MetadataTypeList:
listVal, ok := actualVal.([]interface{})
if !ok {
return nil, fmt.Errorf("%v: expected type []interface{} for list, but got: %s", path, str(actualVal))
}
return parseList(path, listVal)
case MetadataTypeMap:
listVal, ok := actualVal.([]interface{})
if !ok {
return nil, fmt.Errorf("%v: expected type []interface{} for map, but got: %s", path, str(actualVal))
}
return parseMap(path, listVal)
default:
return nil, fmt.Errorf("%v: unknown metadata type '%v' for %s", path, valType, str(actualVal))
}
}
return val, nil
}
func parseByteString(path string, rawStr string) ([]byte, error) {
result := make([]byte, hex.DecodedLen(len(rawStr)))
length, err := hex.Decode(result, []byte(rawStr))
if err != nil {
return nil, fmt.Errorf("%v: failed to decode hex-bytestring (%v): %v", path, err, rawStr)
}
return result[:length], err
}
func parseList(path string, rawList []interface{}) ([]interface{}, error) {
result := make([]interface{}, len(rawList))
for i, rawVal := range rawList {
parsedVal, err := parseMetaValue(path+"/"+strconv.Itoa(i), rawVal)
if err != nil {
return nil, err
}
result[i] = parsedVal
}
return result, nil
}
func parseMap(path string, rawList []interface{}) (map[interface{}]interface{}, error) {
result := make(map[interface{}]interface{}, len(rawList))
for i, rawPair := range rawList {
itemPath := path + "/" + strconv.Itoa(i)
rawPairObj, ok := rawPair.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("%v: expected map[string]interface{}, but got %s", itemPath, str(rawPair))
}
if len(rawPairObj) != 2 {
return nil, fmt.Errorf("%v: expected length 2, but got %v: %s", itemPath, len(rawPairObj), str(rawPairObj))
}
rawKey, keyOk := rawPairObj[MetadataMapKey]
if !keyOk {
return nil, fmt.Errorf("%v: missing key '%v' in map-pair: %s", itemPath, MetadataMapKey, str(rawPairObj))
}
rawVal, valOk := rawPairObj[MetadataMapVal]
if !valOk {
return nil, fmt.Errorf("%v: missing key '%v' in map-pair: %s", itemPath, MetadataMapVal, str(rawPairObj))
}
parsedKey, err := parseMetaValue(itemPath+"["+MetadataMapKey+"]", rawKey)
if err != nil {
return nil, err
}
parsedVal, err := parseMetaValue(itemPath+"["+MetadataMapVal+"]", rawVal)
if err != nil {
return nil, err
}
_, collision := result[parsedKey]
if collision {
// TODO any better error handling?
return nil, fmt.Errorf("%v: duplicate map key %s", itemPath, str(parsedKey))
}
result[parsedKey] = parsedVal
}
return result, nil
}
func EncodeMetadata(input map[uint]interface{}) (Metadata, error) {
result := make(Metadata, len(input))
for key, val := range input {
encodedVal, err := encodeMetaValue(strconv.Itoa(int(key)), val)
if err != nil {
return nil, err
}
result[key] = encodedVal
}
return result, nil
}
func encodeMetaValue(path string, val interface{}) (interface{}, error) {
var encodedType string
var encodedVal interface{}
switch typedVal := val.(type) {
case string:
encodedType = MetadataTypeString
encodedVal = typedVal
break
case []byte:
encodedType = MetadataTypeBytes
encodedVal = typedVal
break
case int:
case int8: // covers byte
case int16:
case int32: // covers rune
case int64:
case uint:
case uint8:
case uint16:
case uint32:
case uint64:
encodedType = MetadataTypeInt
encodedVal = int64(typedVal)
break
case bool: // TODO bool is not covered when parsing
encodedType = MetadataTypeInt
if typedVal {
encodedVal = 1
} else {
encodedVal = 0
}
// Avoid unexpected behavior due to rounding
case float32:
case float64:
case complex64:
case complex128:
return nil, fmt.Errorf("%v: encoding floating point and complex values unsupported (value: %v)", path, val)
case []interface{}:
encodedType = MetadataTypeList
var err error
encodedVal, err = encodeMetaList(path, typedVal)
if err != nil {
return nil, err
}
break
case map[interface{}]interface{}:
encodedType = MetadataTypeList
var err error
encodedVal, err = encodeMetaMap(path, typedVal)
if err != nil {
return nil, err
}
break
default:
return nil, fmt.Errorf("%v: cannot encode value of unexpected type: %s", path, str(val))
}
return map[string]interface{}{
encodedType: encodedVal,
}, nil
}
func encodeMetaList(path string, listVal []interface{}) (interface{}, error) {
encodedList := make([]interface{}, len(listVal))
for i, val := range listVal {
encodedVal, err := encodeMetaValue(path+"/"+strconv.Itoa(i), val)
if err != nil {
return nil, err
}
encodedList[i] = encodedVal
}
return map[string]interface{}{
MetadataTypeList: encodedList,
}, nil
}
func encodeMetaMap(path string, mapVal map[interface{}]interface{}) (interface{}, error) {
encodedMap := make([]interface{}, 0, len(mapVal))
for key, val := range mapVal {
itemPath := path + "/" + fmt.Sprintf("%v", key)
encodedKey, err := encodeMetaValue(itemPath+"[key]", key)
if err != nil {
return nil, err
}
encodedVal, err := encodeMetaValue(itemPath+"[value]", val)
if err != nil {
return nil, err
}
encodedMap = append(encodedMap, map[string]interface{}{
MetadataMapKey: encodedKey,
MetadataMapVal: encodedVal,
})
}
return map[string]interface{}{
MetadataTypeMap: encodedMap,
}, nil
}