-
Notifications
You must be signed in to change notification settings - Fork 191
/
capdata.go
298 lines (284 loc) · 8.69 KB
/
capdata.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
package capdata
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
)
// JsonMarshal returns JSON text representing its input,
// without special replacement of "<", ">", "&", U+2028, or U+2029.
func JsonMarshal(val any) ([]byte, error) {
buf := &bytes.Buffer{}
encoder := json.NewEncoder(buf)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(val); err != nil {
return nil, err
}
// Return without a trailing line feed.
lineTerminatedJson := buf.Bytes()
return bytes.TrimSuffix(lineTerminatedJson, []byte("\n")), nil
}
// cf. https://github.com/endojs/endo/tree/master/packages/marshal
type Capdata struct {
Body string `json:"body"`
Slots []interface{} `json:"slots"`
}
var validBigint = regexp.MustCompile(`^-?(?:0|[1-9][0-9]*)$`)
type CapdataBigint struct {
Normalized string
}
type CapdataRemotable struct {
Id interface{}
Iface *string
Representation interface{}
}
func NewCapdataBigint(str string) *CapdataBigint {
if !validBigint.MatchString(str) {
return nil
}
bigint := CapdataBigint{str}
return &bigint
}
func (r *CapdataRemotable) MarshalJSON() ([]byte, error) {
return JsonMarshal(r.Representation)
}
type CapdataValueTransformations struct {
Bigint func(*CapdataBigint) interface{}
Remotable func(*CapdataRemotable) interface{}
}
// upsertCapdataRemotable either adds a new CapdataRemotable to `remotables` at the specified
// slot index or updates the iface of the value that is already there, ensuring lack of iface name
// inconsistency (iteration order is not guaranteed to correspond with JSON text like it does in
// JavaScript, so we must accept encountering the "first" reference to a slot late
// and must therefore also defer transformations).
func upsertCapdataRemotable(remotables map[uint64]*CapdataRemotable, slotIndex uint64, id interface{}, iface *string) (*CapdataRemotable, error) {
r := remotables[slotIndex]
if r == nil {
r = new(CapdataRemotable)
r.Id = id
r.Iface = iface
remotables[slotIndex] = r
} else if iface != nil {
if r.Iface != nil && *iface != *r.Iface {
return nil, fmt.Errorf("slot iface mismatch: %q", *iface)
}
r.Iface = iface
}
return r, nil
}
// decodeCapdataLegacyValue decodes the non-smallcaps encoding of
// https://github.com/endojs/endo/blob/master/packages/marshal/src/encodeToCapData.js
func decodeCapdataLegacyValue(
encoded interface{},
slots []interface{},
remotables map[uint64]*CapdataRemotable,
transformations CapdataValueTransformations,
) (interface{}, error) {
if arr, ok := encoded.([]interface{}); ok {
for i, v := range arr {
decoded, err := decodeCapdataLegacyValue(v, slots, remotables, transformations)
if err != nil {
return nil, err
}
arr[i] = decoded
}
return arr, nil
} else if obj, ok := encoded.(map[string]interface{}); ok {
if qclassVal, ok := obj["@qclass"]; ok {
qclass, ok := qclassVal.(string)
if !ok {
return nil, fmt.Errorf("invalid @qclass: %q", qclassVal)
}
switch qclass {
case "bigint":
var bigint *CapdataBigint
digitsVal := obj["digits"]
if digitsStr, ok := digitsVal.(string); ok {
bigint = NewCapdataBigint(digitsStr)
}
if bigint == nil {
return nil, fmt.Errorf("invalid bigint: %q", digitsVal)
}
if transformations.Bigint == nil {
return nil, fmt.Errorf("untransformed bigint")
}
return transformations.Bigint(bigint), nil
case "slot":
var iface *string
slotIndexVal, ifaceVal := obj["index"], obj["iface"]
slotIndexNum, ok := slotIndexVal.(float64)
slotIndex := uint64(slotIndexNum)
if !ok || float64(slotIndex) != slotIndexNum || slotIndex >= uint64(len(slots)) {
return nil, fmt.Errorf("invalid slot index: %q", slotIndexVal)
}
if ifaceStr, ok := ifaceVal.(string); ok {
iface = &ifaceStr
} else if ifaceVal != nil {
return nil, fmt.Errorf("invalid slot iface: %q", ifaceVal)
}
return upsertCapdataRemotable(remotables, slotIndex, slots[slotIndex], iface)
case "hilbert":
fallthrough
case "undefined":
fallthrough
case "NaN":
fallthrough
case "Infinity":
fallthrough
case "symbol":
fallthrough
case "tagged":
fallthrough
case "error":
fallthrough
case "-Infinity":
return nil, fmt.Errorf("not implemented: @qclass %q", qclass)
default:
return nil, fmt.Errorf("unrecognized @qclass: %q", qclass)
}
}
for k, v := range obj {
decoded, err := decodeCapdataLegacyValue(v, slots, remotables, transformations)
if err != nil {
return nil, err
}
obj[k] = decoded
}
return obj, nil
} else {
return encoded, nil
}
}
// decodeCapdataSmallcapsValue decodes the "smallcaps" encoding from
// https://github.com/endojs/endo/blob/master/packages/marshal/src/encodeToSmallcaps.js
func decodeCapdataSmallcapsValue(
encoded interface{},
slots []interface{},
remotables map[uint64]*CapdataRemotable,
transformations CapdataValueTransformations,
) (interface{}, error) {
if arr, ok := encoded.([]interface{}); ok {
for i, v := range arr {
decoded, err := decodeCapdataSmallcapsValue(v, slots, remotables, transformations)
if err != nil {
return nil, err
}
arr[i] = decoded
}
return arr, nil
} else if encodedObj, ok := encoded.(map[string]interface{}); ok {
if _, ok := encodedObj["#tag"]; ok {
return nil, fmt.Errorf("not implemented: #tag")
}
if _, ok := encodedObj["#error"]; ok {
return nil, fmt.Errorf("not implemented: #error")
}
// We need a distinct output map to avoid reprocessing already-decoded keys.
decodedObj := make(map[string]interface{}, len(encodedObj))
for encodedK, v := range encodedObj {
if strings.HasPrefix(encodedK, "#") {
return nil, fmt.Errorf("unrecognized record type: %q", encodedK)
}
decodedK, err := decodeCapdataSmallcapsValue(encodedK, slots, remotables, CapdataValueTransformations{})
k, ok := decodedK.(string)
if err != nil || !ok {
return nil, fmt.Errorf("invalid copyRecord key: %q", encodedK)
}
decoded, err := decodeCapdataSmallcapsValue(v, slots, remotables, transformations)
if err != nil {
return nil, err
}
decodedObj[k] = decoded
}
return decodedObj, nil
} else if str, ok := encoded.(string); ok {
if len(str) == 0 {
return str, nil
}
switch str[0] {
case '!':
return str[1:], nil
case '+':
// Normalize to no leading "+".
str = str[1:]
fallthrough
case '-':
bigint := NewCapdataBigint(str)
if bigint == nil {
return nil, fmt.Errorf("invalid bigint: %q", encoded.(string))
}
if transformations.Bigint == nil {
return nil, fmt.Errorf("untransformed bigint")
}
return transformations.Bigint(bigint), nil
case '$':
var slotIndexStr string
var iface *string
if dotIndex := strings.IndexByte(str, '.'); dotIndex >= 0 {
slotIndexStr = str[1:dotIndex]
ifaceStr := str[dotIndex+1:]
iface = &ifaceStr
} else {
slotIndexStr = str[1:]
}
slotIndex, err := strconv.ParseUint(slotIndexStr, 10, 0)
if err != nil || slotIndex >= uint64(len(slots)) {
return nil, fmt.Errorf("invalid slot index: %q", str)
}
r, err := upsertCapdataRemotable(remotables, slotIndex, slots[slotIndex], iface)
if err != nil {
return nil, fmt.Errorf("slot iface mismatch: %q", str)
}
return r, nil
case '#':
fallthrough
case '%':
fallthrough
case '&':
return nil, fmt.Errorf("not implemented: %q", str)
default:
if str[0] >= '!' && str[0] <= '-' {
return nil, fmt.Errorf("invalid smallcaps encoding prefix: %q", str[:1])
}
}
return str, nil
} else {
return encoded, nil
}
}
// DecodeSerializedCapdata accepts JSON text representing encoded CapData and
// decodes it, applying specified transformations for values that otherwise
// hinder interchange.
func DecodeSerializedCapdata(
serializedCapdata string,
transformations CapdataValueTransformations,
) (interface{}, error) {
var capdata Capdata
if err := json.Unmarshal([]byte(serializedCapdata), &capdata); err != nil {
return nil, err
}
if capdata.Body == "" || capdata.Slots == nil {
return nil, fmt.Errorf("invalid CapData")
}
serializedBody, decodeValue := capdata.Body, decodeCapdataLegacyValue
if strings.HasPrefix(serializedBody, "#") {
serializedBody, decodeValue = serializedBody[1:], decodeCapdataSmallcapsValue
}
var encoded interface{}
if err := json.Unmarshal([]byte(serializedBody), &encoded); err != nil {
return nil, err
}
remotables := map[uint64]*CapdataRemotable{}
decoded, err := decodeValue(encoded, capdata.Slots, remotables, transformations)
if err == nil && len(remotables) > 0 {
if transformations.Remotable == nil {
return nil, fmt.Errorf("untransformed remotable")
}
for _, r := range remotables {
r.Representation = transformations.Remotable(r)
}
}
return decoded, err
}