forked from coinbase/mesh-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
575 lines (477 loc) · 14 KB
/
block.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// 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 (
"fmt"
"math/big"
"github.com/coinbase/rosetta-sdk-go/types"
)
const (
// MinUnixEpoch is the unix epoch time in milliseconds of
// 01/01/2000 at 12:00:00 AM.
MinUnixEpoch = 946713600000
// MaxUnixEpoch is the unix epoch time in milliseconds of
// 01/01/2040 at 12:00:00 AM.
MaxUnixEpoch = 2209017600000
)
// Currency ensures a *types.Currency is valid.
func Currency(currency *types.Currency) error {
if currency == nil {
return ErrAmountCurrencyIsNil
}
if currency.Symbol == "" {
return ErrAmountCurrencySymbolEmpty
}
if currency.Decimals < 0 {
return ErrAmountCurrencyHasNegDecimals
}
return nil
}
// Amount ensures a types.Amount has an
// integer value, specified precision, and symbol.
func Amount(amount *types.Amount) error {
if amount == nil || amount.Value == "" {
return ErrAmountValueMissing
}
_, ok := new(big.Int).SetString(amount.Value, 10)
if !ok {
return fmt.Errorf("%w: %s", ErrAmountIsNotInt, amount.Value)
}
return Currency(amount.Currency)
}
// OperationIdentifier returns an error if index of the
// types.Operation is out-of-order or if the NetworkIndex is
// invalid.
func OperationIdentifier(
identifier *types.OperationIdentifier,
index int64,
) error {
if identifier == nil {
return ErrOperationIdentifierIndexIsNil
}
if identifier.Index != index {
return fmt.Errorf(
"%w: expected %d but got %d",
ErrOperationIdentifierIndexOutOfOrder,
index,
identifier.Index,
)
}
if identifier.NetworkIndex != nil && *identifier.NetworkIndex < 0 {
return ErrOperationIdentifierNetworkIndexInvalid
}
return nil
}
// AccountIdentifier returns an error if a types.AccountIdentifier
// is missing an address or a provided SubAccount is missing an identifier.
func AccountIdentifier(account *types.AccountIdentifier) error {
if account == nil {
return ErrAccountIsNil
}
if account.Address == "" {
return ErrAccountAddrMissing
}
if account.SubAccount == nil {
return nil
}
if account.SubAccount.Address == "" {
return ErrAccountSubAccountAddrMissing
}
return nil
}
// containsString checks if an string is contained in a slice
// of strings.
func containsString(valid []string, value string) bool {
for _, v := range valid {
if v == value {
return true
}
}
return false
}
// containsInt64 checks if an int64 is contained in a slice
// of Int64.
func containsInt64(valid []int64, value int64) bool {
for _, v := range valid {
if v == value {
return true
}
}
return false
}
// OperationStatus returns an error if an operation.Status
// is not valid.
func (a *Asserter) OperationStatus(status *string, construction bool) error {
if a == nil {
return ErrAsserterNotInitialized
}
// As of [email protected], populating
// the Operation.Status field is deprecated for construction,
// however, many implementations may still do this. Therefore,
// we need to handle a populated but empty Operation.Status
// field gracefully.
if status == nil || len(*status) == 0 {
if construction {
return nil
}
return ErrOperationStatusMissing
}
if construction {
return ErrOperationStatusNotEmptyForConstruction
}
if _, ok := a.operationStatusMap[*status]; !ok {
return fmt.Errorf("%w: %s", ErrOperationStatusInvalid, *status)
}
return nil
}
// OperationType returns an error if an operation.Type
// is not valid.
func (a *Asserter) OperationType(t string) error {
if a == nil {
return ErrAsserterNotInitialized
}
if t == "" || !containsString(a.operationTypes, t) {
return fmt.Errorf("%w: %s", ErrOperationTypeInvalid, t)
}
return nil
}
// Operation ensures a types.Operation has a valid
// type, status, and amount.
func (a *Asserter) Operation(
operation *types.Operation,
index int64,
construction bool,
) error {
if a == nil {
return ErrAsserterNotInitialized
}
if operation == nil {
return ErrOperationIsNil
}
if err := OperationIdentifier(operation.OperationIdentifier, index); err != nil {
return fmt.Errorf("%w: Operation identifier is invalid in operation %d", err, index)
}
if err := a.OperationType(operation.Type); err != nil {
return fmt.Errorf("%w: operation type is invalid in operation %d", err, index)
}
if err := a.OperationStatus(operation.Status, construction); err != nil {
return fmt.Errorf("%w: operation status is invalid in operation %d", err, index)
}
if operation.Amount == nil {
return nil
}
if err := AccountIdentifier(operation.Account); err != nil {
return fmt.Errorf("%w: account identifier is invalid in operation %d", err, index)
}
if err := Amount(operation.Amount); err != nil {
return fmt.Errorf("%w: amount is invalid in operation %d", err, index)
}
if operation.CoinChange == nil {
return nil
}
if err := CoinChange(operation.CoinChange); err != nil {
return fmt.Errorf("%w: coin change is invalid in operation %d", err, index)
}
return nil
}
// BlockIdentifier ensures a types.BlockIdentifier
// is well-formatted.
func BlockIdentifier(blockIdentifier *types.BlockIdentifier) error {
if blockIdentifier == nil {
return ErrBlockIdentifierIsNil
}
if blockIdentifier.Hash == "" {
return ErrBlockIdentifierHashMissing
}
if blockIdentifier.Index < 0 {
return ErrBlockIdentifierIndexIsNeg
}
return nil
}
// PartialBlockIdentifier ensures a types.PartialBlockIdentifier
// is well-formatted.
func PartialBlockIdentifier(blockIdentifier *types.PartialBlockIdentifier) error {
if blockIdentifier == nil {
return ErrPartialBlockIdentifierIsNil
}
if blockIdentifier.Hash != nil && *blockIdentifier.Hash != "" {
return nil
}
if blockIdentifier.Index != nil && *blockIdentifier.Index >= 0 {
return nil
}
return ErrPartialBlockIdentifierFieldsNotSet
}
// TransactionIdentifier returns an error if a
// types.TransactionIdentifier has an invalid hash.
func TransactionIdentifier(
transactionIdentifier *types.TransactionIdentifier,
) error {
if transactionIdentifier == nil {
return ErrTxIdentifierIsNil
}
if transactionIdentifier.Hash == "" {
return ErrTxIdentifierHashMissing
}
return nil
}
// Operations returns an error if any *types.Operation
// in a []*types.Operation is invalid.
func (a *Asserter) Operations( // nolint:gocognit
operations []*types.Operation,
construction bool,
) error {
if len(operations) == 0 && construction {
return ErrNoOperationsForConstruction
}
paymentTotal := big.NewInt(0)
feeTotal := big.NewInt(0)
paymentCount := 0
feeCount := 0
relatedOpsExists := false
for i, op := range operations {
// Ensure operations are sorted
if err := a.Operation(op, int64(i), construction); err != nil {
return err
}
if a.validations.Enabled {
if op.Type == a.validations.Payment.Name {
val, _ := new(big.Int).SetString(op.Amount.Value, 10)
paymentTotal.Add(paymentTotal, val)
paymentCount++
}
if op.Type == a.validations.Fee.Name {
if op.RelatedOperations != nil {
return fmt.Errorf(
"%w: operation index %d",
ErrRelatedOperationInFeeNotAllowed,
op.OperationIdentifier.Index,
)
}
val, err := types.BigInt(op.Amount.Value)
if err != nil {
return err
}
// Validate that fee operation amount is negative
if val.Sign() != -1 {
return fmt.Errorf(
"%w: operation index %d",
ErrFeeAmountNotNegative,
op.OperationIdentifier.Index,
)
}
feeTotal.Add(feeTotal, val)
feeCount++
}
}
// Ensure an operation's related_operations are only
// operations with an index less than the operation
// and that there are no duplicates.
relatedIndexes := []int64{}
for _, relatedOp := range op.RelatedOperations {
relatedOpsExists = true
if relatedOp.Index >= op.OperationIdentifier.Index {
return fmt.Errorf(
"%w: related operation index %d >= operation index %d",
ErrRelatedOperationIndexOutOfOrder,
relatedOp.Index,
op.OperationIdentifier.Index,
)
}
if containsInt64(relatedIndexes, relatedOp.Index) {
return fmt.Errorf(
"%w: related operation index %d found for operation index %d",
ErrRelatedOperationIndexDuplicate,
relatedOp.Index,
op.OperationIdentifier.Index,
)
}
relatedIndexes = append(relatedIndexes, relatedOp.Index)
}
}
// throw an error if relatedOps is not implemented and relatedOps is supported
if !relatedOpsExists {
if a.validations.Enabled && a.validations.RelatedOpsExists {
return ErrRelatedOperationMissing
}
}
// only account based validation
if a.validations.Enabled && a.validations.ChainType == Account {
return a.ValidatePaymentAndFee(paymentTotal, paymentCount, feeTotal, feeCount)
}
return nil
}
func (a *Asserter) ValidatePaymentAndFee(
paymentTotal *big.Int,
paymentCount int,
feeTotal *big.Int,
feeCount int,
) error {
zero := big.NewInt(0)
if a.validations.Payment.Operation.Count != -1 &&
a.validations.Payment.Operation.Count != paymentCount {
return ErrPaymentCountMismatch
}
if a.validations.Payment.Operation.ShouldBalance && paymentTotal.Cmp(zero) != 0 {
return ErrPaymentAmountNotBalancing
}
if a.validations.Fee.Operation.Count != -1 && a.validations.Fee.Operation.Count != feeCount {
return ErrFeeCountMismatch
}
if a.validations.Fee.Operation.ShouldBalance && feeTotal.Cmp(zero) != 0 {
return ErrPaymentAmountNotBalancing
}
return nil
}
// Transaction returns an error if the types.TransactionIdentifier
// is invalid, if any types.Operation within the types.Transaction
// is invalid, or if any operation index is reused within a transaction.
func (a *Asserter) Transaction(
transaction *types.Transaction,
) error {
if a == nil {
return ErrAsserterNotInitialized
}
if transaction == nil {
return ErrTxIsNil
}
if err := TransactionIdentifier(transaction.TransactionIdentifier); err != nil {
return err
}
if err := a.Operations(transaction.Operations, false); err != nil {
return fmt.Errorf(
"%w invalid operation in transaction %s",
err,
transaction.TransactionIdentifier.Hash,
)
}
if err := a.RelatedTransactions(transaction.RelatedTransactions); err != nil {
return fmt.Errorf(
"%w invalid related transaction in transaction %s",
err,
transaction.TransactionIdentifier.Hash,
)
}
return nil
}
// RelatedTransactions returns an error if the related transactions array is non-null and non-empty
// and
// any of the related transactions contain invalid types, invalid network identifiers,
// invalid transaction identifiers, or a direction not defined by the enum.
func (a *Asserter) RelatedTransactions(relatedTransactions []*types.RelatedTransaction) error {
if dup := DuplicateRelatedTransaction(relatedTransactions); dup != nil {
return fmt.Errorf("%w: %v", ErrDuplicateRelatedTransaction, dup)
}
for i, relatedTransaction := range relatedTransactions {
if relatedTransaction.NetworkIdentifier != nil {
if err := NetworkIdentifier(relatedTransaction.NetworkIdentifier); err != nil {
return fmt.Errorf(
"%w invalid network identifier in related transaction at index %d",
err,
i,
)
}
}
if err := TransactionIdentifier(relatedTransaction.TransactionIdentifier); err != nil {
return fmt.Errorf(
"%w invalid transaction identifier in related transaction at index %d",
err,
i,
)
}
if err := a.Direction(relatedTransaction.Direction); err != nil {
return fmt.Errorf(
"%w invalid direction in related transaction at index %d",
err,
i,
)
}
}
return nil
}
// DuplicateRelatedTransaction returns nil if no duplicates are found in the array and
// returns the first duplicated item found otherwise.
func DuplicateRelatedTransaction(
items []*types.RelatedTransaction,
) *types.RelatedTransaction {
seen := map[string]struct{}{}
for _, item := range items {
key := types.Hash(item)
if _, ok := seen[key]; ok {
return item
}
seen[key] = struct{}{}
}
return nil
}
// Direction returns an error if the value passed is not types.Forward or types.Backward
func (a *Asserter) Direction(direction types.Direction) error {
if direction != types.Forward &&
direction != types.Backward {
return ErrInvalidDirection
}
return nil
}
// Timestamp returns an error if the timestamp
// on a block is less than or equal to 0.
func Timestamp(timestamp int64) error {
switch {
case timestamp < MinUnixEpoch:
return fmt.Errorf("%w: %d", ErrTimestampBeforeMin, timestamp)
case timestamp > MaxUnixEpoch:
return fmt.Errorf("%w: %d", ErrTimestampAfterMax, timestamp)
default:
return nil
}
}
// Block runs a basic set of assertions for each returned block.
func (a *Asserter) Block(
block *types.Block,
) error {
if a == nil {
return ErrAsserterNotInitialized
}
if block == nil {
return ErrBlockIsNil
}
if err := BlockIdentifier(block.BlockIdentifier); err != nil {
return err
}
if err := BlockIdentifier(block.ParentBlockIdentifier); err != nil {
return err
}
// Only apply duplicate hash and index checks if the block index is not the
// genesis index.
if a.genesisBlock.Index != block.BlockIdentifier.Index {
if block.BlockIdentifier.Hash == block.ParentBlockIdentifier.Hash {
return ErrBlockHashEqualsParentBlockHash
}
if block.BlockIdentifier.Index <= block.ParentBlockIdentifier.Index {
return ErrBlockIndexPrecedesParentBlockIndex
}
}
// Only check for timestamp validity if timestamp start index is <=
// the current block index.
if a.timestampStartIndex <= block.BlockIdentifier.Index {
if err := Timestamp(block.Timestamp); err != nil {
return err
}
}
for _, transaction := range block.Transactions {
if err := a.Transaction(transaction); err != nil {
return err
}
}
return nil
}