forked from coinbase/mesh-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asserter.go
328 lines (282 loc) · 9.23 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
// Copyright 2020 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"
"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
}
// 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, err
}
if err := SupportedNetworks(supportedNetworks); err != nil {
return nil, err
}
validationConfig, err := getValidationConfig(validationFilePath)
if err != nil {
return nil, 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("%w: %s", ErrCallMethodDuplicate, method)
}
callMap[method] = struct{}{}
}
return &Asserter{
operationTypes: supportedOperationTypes,
historicalBalanceLookup: historicalBalanceLookup,
supportedNetworks: supportedNetworks,
callMethods: callMap,
mempoolCoins: mempoolCoins,
validations: validationConfig,
}, 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, err
}
if err := NetworkStatusResponse(networkStatus); err != nil {
return nil, err
}
if err := NetworkOptionsResponse(networkOptions); err != nil {
return nil, err
}
validationConfig, err := getValidationConfig(validationFilePath)
if err != nil {
return nil, 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, err
}
config := &Configuration{}
if err := json.Unmarshal(content, config); err != nil {
return nil, 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, err
}
if err := BlockIdentifier(genesisBlockIdentifier); err != nil {
return nil, err
}
if err := OperationStatuses(operationStatuses); err != nil {
return nil, err
}
if err := OperationTypes(operationTypes); err != nil {
return nil, 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(
"%w: %d",
ErrTimestampStartIndexInvalid,
*timestampStartIndex,
)
}
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
}
// 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 {
return false, fmt.Errorf("%s 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, err
}
if err := json.Unmarshal(content, validationConfig); err != nil {
return nil, err
}
}
return validationConfig, nil
}