forked from coinbase/mesh-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
asserter.go
455 lines (398 loc) · 13.2 KB
/
asserter.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Copyright 2024 Coinbase, 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 asserter
import (
"encoding/json"
"fmt"
"io/ioutil"
"path"
"strings"
"github.com/coinbase/rosetta-sdk-go/types"
)
// Asserter contains all logic to perform static
// validation on Rosetta Server responses.
type Asserter struct {
// These variables are used for response assertion.
network *types.NetworkIdentifier
operationTypes []string
operationStatusMap map[string]bool
errorTypeMap map[int32]*types.Error
genesisBlock *types.BlockIdentifier
timestampStartIndex int64
// These variables are used for request assertion.
historicalBalanceLookup bool
supportedNetworks []*types.NetworkIdentifier
callMethods map[string]struct{}
mempoolCoins bool
validations *Validations
ignoreRosettaSpecValidation bool
}
// Validations is used to define stricter validations
// on the transaction. Fore more details please refer to
// https://github.com/coinbase/rosetta-sdk-go/tree/master/asserter#readme
type Validations struct {
Enabled bool `json:"enabled"`
RelatedOpsExists bool `json:"related_ops_exists"`
ChainType ChainType `json:"chain_type"`
Payment *ValidationOperation `json:"payment"`
Fee *ValidationOperation `json:"fee"`
}
type ValidationOperation struct {
Name string `json:"name"`
Operation *Operation `json:"operation"`
}
type Operation struct {
Count int `json:"count"`
ShouldBalance bool `json:"should_balance"`
}
type ChainType string
const (
Account ChainType = "account"
UTXO ChainType = "utxo"
)
// NewServer constructs a new Asserter for use in the
// server package.
func NewServer(
supportedOperationTypes []string,
historicalBalanceLookup bool,
supportedNetworks []*types.NetworkIdentifier,
callMethods []string,
mempoolCoins bool,
validationFilePath string,
) (*Asserter, error) {
if err := OperationTypes(supportedOperationTypes); err != nil {
return nil, fmt.Errorf("operation types %v are invalid: %w", supportedOperationTypes, err)
}
if err := SupportedNetworks(supportedNetworks); err != nil {
return nil, fmt.Errorf(
"network identifiers %s are invalid: %w",
types.PrintStruct(supportedNetworks),
err,
)
}
validationConfig, err := getValidationConfig(validationFilePath)
if err != nil {
return nil, fmt.Errorf("config %s is invalid: %w", validationFilePath, err)
}
callMap := map[string]struct{}{}
for _, method := range callMethods {
if len(method) == 0 {
return nil, ErrCallMethodEmpty
}
if _, ok := callMap[method]; ok {
return nil, fmt.Errorf("failed to call method %s: %w", method, ErrCallMethodDuplicate)
}
callMap[method] = struct{}{}
}
return &Asserter{
operationTypes: supportedOperationTypes,
historicalBalanceLookup: historicalBalanceLookup,
supportedNetworks: supportedNetworks,
callMethods: callMap,
mempoolCoins: mempoolCoins,
validations: validationConfig,
}, nil
}
// NewGenericAsserter constructs a new Asserter for generic usage
func NewGenericAsserter(
supportedOperationTypes []string,
historicalBalanceLookup bool,
supportedNetworks []*types.NetworkIdentifier,
operationStatuses []*types.OperationStatus,
errors []*types.Error,
genesisBlockIdentifier *types.BlockIdentifier,
timestampStartIndex int64,
validationFilePath string,
) (*Asserter, error) {
if err := OperationTypes(supportedOperationTypes); err != nil {
return nil, fmt.Errorf("operation types %v are invalid: %w", supportedOperationTypes, err)
}
if err := SupportedNetworks(supportedNetworks); err != nil {
return nil, fmt.Errorf(
"network identifiers %s are invalid: %w",
types.PrintStruct(supportedNetworks),
err,
)
}
validationConfig, err := getValidationConfig(validationFilePath)
if err != nil {
return nil, fmt.Errorf("config %s is invalid: %w", validationFilePath, err)
}
asserter := &Asserter{
operationTypes: supportedOperationTypes,
historicalBalanceLookup: historicalBalanceLookup,
supportedNetworks: supportedNetworks,
validations: validationConfig,
genesisBlock: genesisBlockIdentifier,
timestampStartIndex: timestampStartIndex,
}
asserter.errorTypeMap = map[int32]*types.Error{}
for _, err := range errors {
asserter.errorTypeMap[err.Code] = err
}
asserter.operationStatusMap = map[string]bool{}
for _, status := range operationStatuses {
asserter.operationStatusMap[status.Status] = status.Successful
}
return asserter, nil
}
// NewClientWithResponses constructs a new Asserter
// from a NetworkStatusResponse and
// NetworkOptionsResponse.
func NewClientWithResponses(
network *types.NetworkIdentifier,
networkStatus *types.NetworkStatusResponse,
networkOptions *types.NetworkOptionsResponse,
validationFilePath string,
) (*Asserter, error) {
if err := NetworkIdentifier(network); err != nil {
return nil, fmt.Errorf(
"network identifier %s is invalid: %w",
types.PrintStruct(network),
err,
)
}
if err := NetworkStatusResponse(networkStatus); err != nil {
return nil, fmt.Errorf(
"network status response %s is invalid: %w",
types.PrintStruct(networkStatus),
err,
)
}
if err := NetworkOptionsResponse(networkOptions); err != nil {
return nil, fmt.Errorf(
"network options response %s is invalid: %w",
types.PrintStruct(networkOptions),
err,
)
}
validationConfig, err := getValidationConfig(validationFilePath)
if err != nil {
return nil, fmt.Errorf("config %s is invalid: %w", validationFilePath, err)
}
return NewClientWithOptions(
network,
networkStatus.GenesisBlockIdentifier,
networkOptions.Allow.OperationTypes,
networkOptions.Allow.OperationStatuses,
networkOptions.Allow.Errors,
networkOptions.Allow.TimestampStartIndex,
validationConfig,
)
}
// Configuration is the static configuration of an Asserter. This
// configuration can be exported by the Asserter and used to instantiate an
// Asserter.
type Configuration struct {
NetworkIdentifier *types.NetworkIdentifier `json:"network_identifier"`
GenesisBlockIdentifier *types.BlockIdentifier `json:"genesis_block_identifier"`
AllowedOperationTypes []string `json:"allowed_operation_types"`
AllowedOperationStatuses []*types.OperationStatus `json:"allowed_operation_statuses"`
AllowedErrors []*types.Error `json:"allowed_errors"`
AllowedTimestampStartIndex int64 `json:"allowed_timestamp_start_index"`
}
// NewClientWithFile constructs a new Asserter using a specification
// file instead of responses. This can be useful for running reliable
// systems that error when updates to the server (more error types,
// more operations, etc.) significantly change how to parse the chain.
// The filePath provided is parsed relative to the current directory.
func NewClientWithFile(
filePath string,
) (*Asserter, error) {
content, err := ioutil.ReadFile(path.Clean(filePath))
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %w", filePath, err)
}
config := &Configuration{}
if err := json.Unmarshal(content, config); err != nil {
return nil, fmt.Errorf("failed to unmarshal content of file %s: %w", filePath, err)
}
return NewClientWithOptions(
config.NetworkIdentifier,
config.GenesisBlockIdentifier,
config.AllowedOperationTypes,
config.AllowedOperationStatuses,
config.AllowedErrors,
&config.AllowedTimestampStartIndex,
&Validations{
Enabled: false,
},
)
}
// NewClientWithOptions constructs a new Asserter using the provided
// arguments instead of using a NetworkStatusResponse and a
// NetworkOptionsResponse.
func NewClientWithOptions(
network *types.NetworkIdentifier,
genesisBlockIdentifier *types.BlockIdentifier,
operationTypes []string,
operationStatuses []*types.OperationStatus,
errors []*types.Error,
timestampStartIndex *int64,
validationConfig *Validations,
) (*Asserter, error) {
if err := NetworkIdentifier(network); err != nil {
return nil, fmt.Errorf(
"network identifier %s is invalid: %w",
types.PrintStruct(network),
err,
)
}
if err := BlockIdentifier(genesisBlockIdentifier); err != nil {
return nil, fmt.Errorf(
"genesis block identifier %s is invalid: %w",
types.PrintStruct(genesisBlockIdentifier),
err,
)
}
if err := OperationStatuses(operationStatuses); err != nil {
return nil, fmt.Errorf(
"operation statuses %s are invalid: %w",
types.PrintStruct(operationStatuses),
err,
)
}
if err := OperationTypes(operationTypes); err != nil {
return nil, fmt.Errorf(
"operation types %s are invalid: %w",
types.PrintStruct(operationTypes),
err,
)
}
// TimestampStartIndex defaults to genesisIndex + 1 (this
// avoid breaking existing clients using < v1.4.6).
parsedTimestampStartIndex := genesisBlockIdentifier.Index + 1
if timestampStartIndex != nil {
if *timestampStartIndex < 0 {
return nil, fmt.Errorf(
"failed to validate index %d: %w",
*timestampStartIndex,
ErrTimestampStartIndexInvalid,
)
}
parsedTimestampStartIndex = *timestampStartIndex
}
asserter := &Asserter{
network: network,
operationTypes: operationTypes,
genesisBlock: genesisBlockIdentifier,
timestampStartIndex: parsedTimestampStartIndex,
validations: validationConfig,
}
asserter.operationStatusMap = map[string]bool{}
for _, status := range operationStatuses {
asserter.operationStatusMap[status.Status] = status.Successful
}
asserter.errorTypeMap = map[int32]*types.Error{}
for _, err := range errors {
asserter.errorTypeMap[err.Code] = err
}
return asserter, nil
}
// NewGenericRosettaClient constructs a new Asserter using the provided
// arguments and without a Rosetta Spec validation. This is used to ignore rosetta spec validation
func NewGenericRosettaClient(
network *types.NetworkIdentifier,
genesisBlockIdentifier *types.BlockIdentifier,
) (*Asserter, error) {
if err := NetworkIdentifier(network); err != nil {
return nil, fmt.Errorf(
"network identifier %s is invalid: %w",
types.PrintStruct(network),
err,
)
}
if err := BlockIdentifier(genesisBlockIdentifier); err != nil {
return nil, fmt.Errorf(
"genesis block identifier %s is invalid: %w",
types.PrintStruct(genesisBlockIdentifier),
err,
)
}
asserter := &Asserter{
network: network,
genesisBlock: genesisBlockIdentifier,
validations: &Validations{
Enabled: false,
},
ignoreRosettaSpecValidation: true,
}
//init default operation statuses for generic rosetta client
InitOperationStatus(asserter)
return asserter, nil
}
// ClientConfiguration returns all variables currently set in an Asserter.
// This function will error if it is called on an uninitialized asserter.
func (a *Asserter) ClientConfiguration() (*Configuration, error) {
if a == nil {
return nil, ErrAsserterNotInitialized
}
operationStatuses := []*types.OperationStatus{}
for k, v := range a.operationStatusMap {
operationStatuses = append(operationStatuses, &types.OperationStatus{
Status: k,
Successful: v,
})
}
errors := []*types.Error{}
for _, v := range a.errorTypeMap {
errors = append(errors, v)
}
return &Configuration{
NetworkIdentifier: a.network,
GenesisBlockIdentifier: a.genesisBlock,
AllowedOperationTypes: a.operationTypes,
AllowedOperationStatuses: operationStatuses,
AllowedErrors: errors,
AllowedTimestampStartIndex: a.timestampStartIndex,
}, nil
}
// OperationSuccessful returns a boolean indicating if a types.Operation is
// successful and should be applied in a transaction. This should only be called
// AFTER an operation has been validated.
func (a *Asserter) OperationSuccessful(operation *types.Operation) (bool, error) {
if a == nil {
return false, ErrAsserterNotInitialized
}
if operation.Status == nil || len(*operation.Status) == 0 {
return false, ErrOperationStatusMissing
}
val, ok := a.operationStatusMap[*operation.Status]
if !ok {
val, ok = a.operationStatusMap[strings.ToUpper(*operation.Status)]
if !ok {
return false, fmt.Errorf("operation status %s is not found", *operation.Status)
}
}
return val, nil
}
func getValidationConfig(validationFilePath string) (*Validations, error) {
validationConfig := &Validations{
Enabled: false,
}
if validationFilePath != "" {
content, err := ioutil.ReadFile(path.Clean(validationFilePath))
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %w", validationFilePath, err)
}
if err := json.Unmarshal(content, validationConfig); err != nil {
return nil, fmt.Errorf(
"failed to unmarshal content of file %s: %w",
validationFilePath,
err,
)
}
}
return validationConfig, nil
}