/
order_validator.go
815 lines (752 loc) · 28.8 KB
/
order_validator.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
package zeroex
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"strings"
"sync"
"time"
"github.com/0xProject/0x-mesh/ethereum"
"github.com/0xProject/0x-mesh/ethereum/wrappers"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/jpillora/backoff"
log "github.com/sirupsen/logrus"
)
// MainnetOrderValidatorAddress is the mainnet OrderValidator contract address
var MainnetOrderValidatorAddress = common.HexToAddress("0x9463e518dea6810309563c81d5266c1b1d149138")
// GanacheOrderValidatorAddress is the ganache snapshot OrderValidator contract address
var GanacheOrderValidatorAddress = common.HexToAddress("0x32eecaf51dfea9618e9bc94e9fbfddb1bbdcba15")
// The context timeout length to use for requests to getOrdersAndTradersInfoTimeout
const getOrdersAndTradersInfoTimeout = 15 * time.Second
// The context timeout length to use for requests to getCoordinatorEndpoint
const getCoordinatorEndpointTimeout = 10 * time.Second
// Specifies the max number of eth_call requests we want to make concurrently.
// Additional requests will block until an ongoing request has completed.
const concurrencyLimit = 5
// OrderInfo represents the order information emitted from Mesh
type OrderInfo struct {
OrderHash common.Hash
SignedOrder *SignedOrder
FillableTakerAssetAmount *big.Int
OrderStatus OrderStatus
// The hash of the Ethereum transaction that caused the order status to change
TxHash common.Hash
}
// RejectedOrderInfo encapsulates all the needed information to understand _why_ a 0x order
// was rejected (i.e. did not pass) order validation. Since there are many potential reasons, some
// Mesh-specific, others 0x-specific and others due to external factors (i.e., network
// disruptions, etc...), we categorize them into `Kind`s and uniquely identify the reasons for
// machines with a `Code`
type RejectedOrderInfo struct {
OrderHash common.Hash `json:"orderHash"`
SignedOrder *SignedOrder `json:"signedOrder"`
Kind RejectedOrderKind `json:"kind"`
Status RejectedOrderStatus `json:"status"`
}
// AcceptedOrderInfo represents an fillable order and how much it could be filled for
type AcceptedOrderInfo struct {
OrderHash common.Hash `json:"orderHash"`
SignedOrder *SignedOrder `json:"signedOrder"`
FillableTakerAssetAmount *big.Int `json:"fillableTakerAssetAmount"`
IsNew bool `json:"isNew"`
}
type acceptedOrderInfoJSON struct {
OrderHash string `json:"orderHash"`
SignedOrder *SignedOrder `json:"signedOrder"`
FillableTakerAssetAmount string `json:"fillableTakerAssetAmount"`
IsNew bool `json:"isNew"`
}
// MarshalJSON is a custom Marshaler for AcceptedOrderInfo
func (a AcceptedOrderInfo) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"orderHash": a.OrderHash.Hex(),
"signedOrder": a.SignedOrder,
"fillableTakerAssetAmount": a.FillableTakerAssetAmount.String(),
"isNew": a.IsNew,
})
}
// UnmarshalJSON implements a custom JSON unmarshaller for the OrderEvent type
func (a *AcceptedOrderInfo) UnmarshalJSON(data []byte) error {
var acceptedOrderInfoJSON acceptedOrderInfoJSON
err := json.Unmarshal(data, &acceptedOrderInfoJSON)
if err != nil {
return err
}
a.OrderHash = common.HexToHash(acceptedOrderInfoJSON.OrderHash)
a.SignedOrder = acceptedOrderInfoJSON.SignedOrder
a.IsNew = acceptedOrderInfoJSON.IsNew
var ok bool
a.FillableTakerAssetAmount, ok = math.ParseBig256(acceptedOrderInfoJSON.FillableTakerAssetAmount)
if !ok {
return errors.New("Invalid uint256 number encountered for FillableTakerAssetAmount")
}
return nil
}
// RejectedOrderStatus enumerates all the unique reasons for an orders rejection
type RejectedOrderStatus struct {
Code string `json:"code"`
Message string `json:"message"`
}
// RejectedOrderStatus values
var (
ROEthRPCRequestFailed = RejectedOrderStatus{
Code: "EthRPCRequestFailed",
Message: "network request to Ethereum RPC endpoint failed",
}
ROCoordinatorRequestFailed = RejectedOrderStatus{
Code: "CoordinatorRequestFailed",
Message: "network request to coordinator server endpoint failed",
}
ROCoordinatorSoftCancelled = RejectedOrderStatus{
Code: "CoordinatorSoftCancelled",
Message: "order was soft-cancelled via the coordinator server",
}
ROCoordinatorEndpointNotFound = RejectedOrderStatus{
Code: "CoordinatorEndpointNotFound",
Message: "corresponding coordinator endpoint not found in CoordinatorRegistry contract",
}
ROInvalidMakerAssetAmount = RejectedOrderStatus{
Code: "OrderHasInvalidMakerAssetAmount",
Message: "order makerAssetAmount cannot be 0",
}
ROInvalidTakerAssetAmount = RejectedOrderStatus{
Code: "OrderHasInvalidTakerAssetAmount",
Message: "order takerAssetAmount cannot be 0",
}
ROExpired = RejectedOrderStatus{
Code: "OrderExpired",
Message: "order already expired",
}
ROFullyFilled = RejectedOrderStatus{
Code: "OrderFullyFilled",
Message: "order already fully filled",
}
ROCancelled = RejectedOrderStatus{
Code: "OrderCancelled",
Message: "order cancelled",
}
ROUnfunded = RejectedOrderStatus{
Code: "OrderUnfunded",
Message: "maker has insufficient balance or allowance for this order to be filled",
}
ROInvalidMakerAssetData = RejectedOrderStatus{
Code: "OrderHasInvalidMakerAssetData",
Message: "order makerAssetData must encode a supported assetData type",
}
ROInvalidTakerAssetData = RejectedOrderStatus{
Code: "OrderHasInvalidTakerAssetData",
Message: "order takerAssetData must encode a supported assetData type",
}
ROInvalidSignature = RejectedOrderStatus{
Code: "OrderHasInvalidSignature",
Message: "order signature must be valid",
}
)
// ConvertRejectOrderCodeToOrderEventKind converts an RejectOrderCode to an OrderEventKind type
func ConvertRejectOrderCodeToOrderEventKind(rejectedOrderStatus RejectedOrderStatus) (OrderEventKind, bool) {
switch rejectedOrderStatus {
case ROExpired:
return EKOrderExpired, true
case ROFullyFilled:
return EKOrderFullyFilled, true
case ROCancelled:
return EKOrderCancelled, true
case ROUnfunded:
return EKOrderBecameUnfunded, true
default:
// Catch-all returns Invalid OrderEventKind
return EKInvalid, false
}
}
// RejectedOrderKind enumerates all kinds of reasons an order could be rejected by Mesh
type RejectedOrderKind string
// RejectedOrderKind values
const (
ZeroExValidation = RejectedOrderKind("ZEROEX_VALIDATION")
MeshError = RejectedOrderKind("MESH_ERROR")
CoordinatorError = RejectedOrderKind("COORDINATOR_ERROR")
)
// ValidationResults defines the validation results returned from BatchValidate
// Within this context, an order is `Accepted` if it passes all the 0x schema tests
// and is fillable for a non-zero amount. An order is `Rejected` if it does not
// satisfy these conditions OR if we were unable to complete the validation process
// for whatever reason
type ValidationResults struct {
Accepted []*AcceptedOrderInfo `json:"accepted"`
Rejected []*RejectedOrderInfo `json:"rejected"`
}
// OrderValidator validates 0x orders
type OrderValidator struct {
maxRequestContentLength int
orderValidationUtilsABI abi.ABI
orderValidationUtils *wrappers.OrderValidationUtils
coordinatorRegistry *wrappers.CoordinatorRegistry
assetDataDecoder *AssetDataDecoder
networkID int
cachedFeeRecipientToEndpoint map[common.Address]string
contractAddresses ethereum.ContractAddresses
}
// NewOrderValidator instantiates a new order validator
func NewOrderValidator(ethClient *ethclient.Client, networkID int, maxRequestContentLength int) (*OrderValidator, error) {
contractAddresses, err := ethereum.GetContractAddressesForNetworkID(networkID)
if err != nil {
return nil, err
}
orderValidationUtilsABI, err := abi.JSON(strings.NewReader(wrappers.OrderValidationUtilsABI))
if err != nil {
return nil, err
}
orderValidationUtils, err := wrappers.NewOrderValidationUtils(contractAddresses.OrderValidationUtils, ethClient)
if err != nil {
return nil, err
}
coordinatorRegistry, err := wrappers.NewCoordinatorRegistry(contractAddresses.CoordinatorRegistry, ethClient)
if err != nil {
return nil, err
}
assetDataDecoder := NewAssetDataDecoder()
return &OrderValidator{
maxRequestContentLength: maxRequestContentLength,
orderValidationUtilsABI: orderValidationUtilsABI,
orderValidationUtils: orderValidationUtils,
coordinatorRegistry: coordinatorRegistry,
assetDataDecoder: assetDataDecoder,
networkID: networkID,
cachedFeeRecipientToEndpoint: map[common.Address]string{},
contractAddresses: contractAddresses,
}, nil
}
// BatchValidate retrieves all the information needed to validate the supplied orders.
// It splits the orders into chunks of `chunkSize`, and makes no more then `concurrencyLimit`
// requests concurrently. If a request fails, re-attempt it up to four times before giving up.
// If it some requests fail, this method still returns whatever order information it was able to
// retrieve.
func (o *OrderValidator) BatchValidate(rawSignedOrders []*SignedOrder, areNewOrders bool) *ValidationResults {
if len(rawSignedOrders) == 0 {
return &ValidationResults{}
}
offchainValidSignedOrders, rejectedOrderInfos := o.BatchOffchainValidation(rawSignedOrders)
validationResults := &ValidationResults{
Accepted: []*AcceptedOrderInfo{},
Rejected: rejectedOrderInfos,
}
// Validate Coordinator orders for soft-cancels
signedOrders, coordinatorRejectedOrderInfos := o.batchValidateSoftCancelled(offchainValidSignedOrders)
for _, rejectedOrderInfo := range coordinatorRejectedOrderInfos {
validationResults.Rejected = append(validationResults.Rejected, rejectedOrderInfo)
}
signedOrderChunks := [][]*SignedOrder{}
chunkSizes := o.computeOptimalChunkSizes(signedOrders)
for _, chunkSize := range chunkSizes {
signedOrderChunks = append(signedOrderChunks, signedOrders[:chunkSize])
signedOrders = signedOrders[chunkSize:]
}
semaphoreChan := make(chan struct{}, concurrencyLimit)
defer close(semaphoreChan)
wg := &sync.WaitGroup{}
for i, signedOrders := range signedOrderChunks {
wg.Add(1)
go func(signedOrders []*SignedOrder, i int) {
orders := []wrappers.OrderWithoutExchangeAddress{}
for _, signedOrder := range signedOrders {
orders = append(orders, signedOrder.ConvertToOrderWithoutExchangeAddress())
}
signatures := [][]byte{}
for _, signedOrder := range signedOrders {
signatures = append(signatures, signedOrder.Signature)
}
defer wg.Done()
// Add one to the semaphore chan. If it already has concurrencyLimit values,
// the request blocks here until one frees up.
semaphoreChan <- struct{}{}
// Attempt to make the eth_call request 4 times with an exponential back-off.
maxDuration := 4 * time.Second
b := &backoff.Backoff{
Min: 250 * time.Millisecond, // First back-off length
Max: maxDuration, // Longest back-off length
Factor: 2, // Factor to multiple each successive back-off
}
for {
// Pass a context with a 15 second timeout to `GetOrderRelevantStates` in order to avoid
// any one request from taking longer then 15 seconds
ctx, cancel := context.WithTimeout(context.Background(), getOrdersAndTradersInfoTimeout)
defer cancel()
opts := &bind.CallOpts{
Pending: false,
Context: ctx,
}
results, err := o.orderValidationUtils.GetOrderRelevantStates(opts, orders, signatures)
if err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
"attempt": b.Attempt(),
"numOrders": len(orders),
}).Info("GetOrderRelevantStates request failed")
d := b.Duration()
if d == maxDuration {
<-semaphoreChan
log.WithFields(log.Fields{
"error": err.Error(),
"numOrders": len(orders),
}).Warning("Gave up on GetOrderRelevantStates request after backoff limit reached")
for _, signedOrder := range signedOrders {
orderHash, err := signedOrder.ComputeOrderHash()
if err != nil {
log.WithField("error", err).Error("Unexpectedly failed to generate orderHash")
continue
}
validationResults.Rejected = append(validationResults.Rejected, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: MeshError,
Status: ROEthRPCRequestFailed,
})
}
return // Give up after 4 attempts
}
time.Sleep(d)
continue
}
for j, orderInfo := range results.OrdersInfo {
isValidSignature := results.IsValidSignature[j]
fillableTakerAssetAmount := results.FillableTakerAssetAmounts[j]
orderHash := common.Hash(orderInfo.OrderHash)
signedOrder := signedOrders[j]
orderStatus := OrderStatus(orderInfo.OrderStatus)
if !isValidSignature {
orderStatus = OSSignatureInvalid
}
switch orderStatus {
case OSExpired, OSFullyFilled, OSCancelled, OSSignatureInvalid:
var status RejectedOrderStatus
switch orderStatus {
case OSExpired:
status = ROExpired
case OSFullyFilled:
status = ROFullyFilled
case OSCancelled:
status = ROCancelled
case OSSignatureInvalid:
status = ROInvalidSignature
}
validationResults.Rejected = append(validationResults.Rejected, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: ZeroExValidation,
Status: status,
})
continue
case OSFillable:
if fillableTakerAssetAmount.Cmp(big.NewInt(0)) == 0 {
validationResults.Rejected = append(validationResults.Rejected, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: ZeroExValidation,
Status: ROUnfunded,
})
} else {
validationResults.Accepted = append(validationResults.Accepted, &AcceptedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
FillableTakerAssetAmount: fillableTakerAssetAmount,
IsNew: areNewOrders,
})
}
continue
}
}
<-semaphoreChan
return
}
}(signedOrders, i)
}
wg.Wait()
return validationResults
}
type softCancelResponse struct {
OrderHashes []common.Hash `json:"orderHashes"`
}
// batchValidateSoftCancelled validates any order specifying the Coordinator contract as the `senderAddress` to ensure
// that it hasn't been cancelled off-chain (soft cancellation). It does this by looking up the Coordinator server endpoint
// given the `feeRecipientAddress` specified in the order, and then hitting that endpoint to query whether the orders have
// been soft cancelled.
func (o *OrderValidator) batchValidateSoftCancelled(signedOrders []*SignedOrder) ([]*SignedOrder, []*RejectedOrderInfo) {
rejectedOrderInfos := []*RejectedOrderInfo{}
validSignedOrders := []*SignedOrder{}
endpointToSignedOrders := map[string][]*SignedOrder{}
for _, signedOrder := range signedOrders {
if signedOrder.SenderAddress != o.contractAddresses.Coordinator {
validSignedOrders = append(validSignedOrders, signedOrder)
continue
}
orderHash, err := signedOrder.ComputeOrderHash()
if err != nil {
log.WithError(err).WithField("signedOrder", signedOrder).Error("Computing the orderHash failed unexpectedly")
}
endpoint, ok := o.cachedFeeRecipientToEndpoint[signedOrder.FeeRecipientAddress]
if !ok {
ctx, cancel := context.WithTimeout(context.Background(), getCoordinatorEndpointTimeout)
defer cancel()
opts := &bind.CallOpts{
Pending: false,
Context: ctx,
}
var err error
// Look-up the coordinator endpoint in the CoordinatorRegistry by the order's `feeRecipientAddress`
endpoint, err = o.coordinatorRegistry.GetCoordinatorEndpoint(opts, signedOrder.FeeRecipientAddress)
if err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
"feeRecipientAddress": signedOrder.FeeRecipientAddress,
}).Info("GetCoordinatorEndpoint request failed")
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: MeshError,
Status: ROEthRPCRequestFailed,
})
continue
}
// CoordinatorRegistry lookup returns empty string if endpoint not found for the feeRecipientAddress
if endpoint == "" {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: CoordinatorError,
Status: ROCoordinatorEndpointNotFound,
})
continue
}
}
existingOrders, ok := endpointToSignedOrders[endpoint]
if !ok {
endpointToSignedOrders[endpoint] = []*SignedOrder{signedOrder}
} else {
endpointToSignedOrders[endpoint] = append(existingOrders, signedOrder)
}
}
for endpoint, signedOrders := range endpointToSignedOrders {
orderHashToSignedOrder := map[common.Hash]*SignedOrder{}
orderHashes := []common.Hash{}
for _, signedOrder := range signedOrders {
orderHash, err := signedOrder.ComputeOrderHash()
if err != nil {
log.WithError(err).WithField("signedOrder", signedOrder).Error("Computing the orderHash failed unexpectedly")
}
orderHashToSignedOrder[orderHash] = signedOrder
orderHashes = append(orderHashes, orderHash)
}
payload := &bytes.Buffer{}
err := json.NewEncoder(payload).Encode(orderHashes)
if err != nil {
log.WithError(err).WithField("orderHashes", orderHashes).Error("Unable to marshal `orderHashes` into JSON")
}
// Check if the orders have been soft-cancelled by querying the Coordinator server
requestURL := fmt.Sprintf("%s/v1/soft_cancels?networkId=%d", endpoint, o.networkID)
resp, err := http.Post(requestURL, "application/json", payload)
if err != nil {
log.WithFields(map[string]interface{}{
"endpoint": endpoint,
"requstURL": requestURL,
"payload": orderHashes,
}).Warn("failed to send request to Coordinator server")
for orderHash, signedOrder := range orderHashToSignedOrder {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: MeshError,
Status: ROCoordinatorRequestFailed,
})
}
continue
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.WithFields(map[string]interface{}{
"endpoint": endpoint,
"statusCode": resp.StatusCode,
"requstURL": requestURL,
}).Warn("Failed to read body received from Coordinator server")
for orderHash, signedOrder := range orderHashToSignedOrder {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: MeshError,
Status: ROCoordinatorRequestFailed,
})
}
continue
}
if resp.StatusCode != 200 {
log.WithFields(map[string]interface{}{
"endpoint": endpoint,
"statusCode": resp.StatusCode,
"requstURL": requestURL,
"body": string(body),
}).Warn("Got non-200 status code from Coordinator server")
for orderHash, signedOrder := range orderHashToSignedOrder {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: MeshError,
Status: ROCoordinatorRequestFailed,
})
}
continue
}
var response softCancelResponse
err = json.Unmarshal(body, &response)
if err != nil {
log.WithFields(map[string]interface{}{
"endpoint": endpoint,
"statusCode": resp.StatusCode,
"requstURL": requestURL,
"body": string(body),
}).Warn("Unable to unmarshal body returned from Coordinator server")
for orderHash, signedOrder := range orderHashToSignedOrder {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: MeshError,
Status: ROCoordinatorRequestFailed,
})
}
continue
}
softCancelledOrderHashes := response.OrderHashes
softCancelledOrderHashMap := map[common.Hash]interface{}{}
for _, orderHash := range softCancelledOrderHashes {
softCancelledOrderHashMap[orderHash] = struct{}{}
signedOrder := orderHashToSignedOrder[orderHash]
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: MeshError,
Status: ROCoordinatorSoftCancelled,
})
}
for orderHash, signedOrder := range orderHashToSignedOrder {
// If order hasn't been soft-cancelled
if _, ok := softCancelledOrderHashMap[orderHash]; !ok {
validSignedOrders = append(validSignedOrders, signedOrder)
}
}
}
return validSignedOrders, rejectedOrderInfos
}
// BatchOffchainValidation performs all off-chain validation checks on a batch of 0x orders.
// These checks include:
// - `MakerAssetAmount` and `TakerAssetAmount` cannot be 0
// - `AssetData` fields contain properly encoded, and currently supported assetData (ERC20 & ERC721 for now)
// - `Signature` contains a properly encoded 0x signature
// - Validate that order isn't expired
// Returns an orderHashToInfo mapping with all invalid orders added to it, and an array of the valid signedOrders
func (o *OrderValidator) BatchOffchainValidation(signedOrders []*SignedOrder) ([]*SignedOrder, []*RejectedOrderInfo) {
rejectedOrderInfos := []*RejectedOrderInfo{}
offchainValidSignedOrders := []*SignedOrder{}
for _, signedOrder := range signedOrders {
orderHash, err := signedOrder.ComputeOrderHash()
if err != nil {
log.WithError(err).WithField("signedOrder", signedOrder).Error("Computing the orderHash failed unexpectedly")
}
now := big.NewInt(time.Now().Unix())
if signedOrder.ExpirationTimeSeconds.Cmp(now) == -1 {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: ZeroExValidation,
Status: ROExpired,
})
continue
}
if signedOrder.MakerAssetAmount.Cmp(big.NewInt(0)) == 0 {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: ZeroExValidation,
Status: ROInvalidMakerAssetAmount,
})
continue
}
if signedOrder.TakerAssetAmount.Cmp(big.NewInt(0)) == 0 {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: ZeroExValidation,
Status: ROInvalidTakerAssetAmount,
})
continue
}
isMakerAssetDataSupported := o.isSupportedAssetData(signedOrder.MakerAssetData)
if !isMakerAssetDataSupported {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: ZeroExValidation,
Status: ROInvalidMakerAssetData,
})
continue
}
isTakerAssetDataSupported := o.isSupportedAssetData(signedOrder.TakerAssetData)
if !isTakerAssetDataSupported {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: ZeroExValidation,
Status: ROInvalidTakerAssetData,
})
continue
}
isSupportedSignature := isSupportedSignature(signedOrder.Signature, orderHash)
if !isSupportedSignature {
rejectedOrderInfos = append(rejectedOrderInfos, &RejectedOrderInfo{
OrderHash: orderHash,
SignedOrder: signedOrder,
Kind: ZeroExValidation,
Status: ROInvalidSignature,
})
continue
}
offchainValidSignedOrders = append(offchainValidSignedOrders, signedOrder)
}
return offchainValidSignedOrders, rejectedOrderInfos
}
func (o *OrderValidator) isSupportedAssetData(assetData []byte) bool {
assetDataName, err := o.assetDataDecoder.GetName(assetData)
if err != nil {
return false
}
switch assetDataName {
case "ERC20Token":
var decodedAssetData ERC20AssetData
err := o.assetDataDecoder.Decode(assetData, &decodedAssetData)
if err != nil {
return false
}
case "ERC721Token":
var decodedAssetData ERC721AssetData
err := o.assetDataDecoder.Decode(assetData, &decodedAssetData)
if err != nil {
return false
}
case "MultiAsset":
var decodedAssetData MultiAssetData
err := o.assetDataDecoder.Decode(assetData, &decodedAssetData)
if err != nil {
return false
}
default:
return false
}
return true
}
// emptyGetOrderRelevantStatesCallDataByteLength is all the boilerplate ABI encoding required when calling
// `getOrderRelevantStates` that does not include the encoded SignedOrder. By subtracting this amount from the
// calldata length returned from encoding a call to `getOrderRelevantStates` involving a single SignedOrder, we
// get the number of bytes taken up by the SignedOrder alone.
// i.e.: len(`"0x7f46448d0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"`)
const emptyGetOrderRelevantStatesCallDataByteLength = 268
// jsonRPCPayloadByteLength is the number of bytes occupied by the default call to `getOrderRelevantStates` with 0 signedOrders
// passed in. The `data` includes the empty `getOrderRelevantStates` calldata.
/*
{
"id": 2,
"jsonrpc": "2.0",
"method": "eth_call",
"params": [
{
"data": "0x7f46448d0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"from": "0x0000000000000000000000000000000000000000",
"to": "0x0000000000000000000000000000000000000000"
},
"latest"
]
}
*/
const jsonRPCPayloadByteLength = 444
func (o *OrderValidator) computeABIEncodedSignedOrderByteLength(signedOrder *SignedOrder) (int, error) {
orderWithExchangeAddress := signedOrder.ConvertToOrderWithoutExchangeAddress()
data, err := o.orderValidationUtilsABI.Pack(
"getOrderRelevantStates",
[]wrappers.OrderWithoutExchangeAddress{orderWithExchangeAddress},
[][]byte{signedOrder.Signature},
)
if err != nil {
return 0, err
}
dataBytes := hexutil.Bytes(data)
encodedData, err := json.Marshal(dataBytes)
if err != nil {
return 0, err
}
encodedSignedOrderByteLength := len(encodedData) - emptyGetOrderRelevantStatesCallDataByteLength
return encodedSignedOrderByteLength, nil
}
// computeOptimalChunkSizes splits the signedOrders into chunks where the payload size of each chunk
// is beneath the maxRequestContentLength. It does this by implementing a greedy algorithm which ABI
// encodes signedOrders one at a time until the computed payload size is as close to the
// maxRequestContentLength as possible.
func (o *OrderValidator) computeOptimalChunkSizes(signedOrders []*SignedOrder) []int {
chunkSizes := []int{}
payloadLength := jsonRPCPayloadByteLength
nextChunkSize := 0
for _, signedOrder := range signedOrders {
encodedSignedOrderByteLength, _ := o.computeABIEncodedSignedOrderByteLength(signedOrder)
if payloadLength+encodedSignedOrderByteLength < o.maxRequestContentLength {
payloadLength += encodedSignedOrderByteLength
nextChunkSize++
} else {
if nextChunkSize == 0 {
// This case should never be hit since we enforce that EthereumRPCMaxContentLength >= maxOrderSizeInBytes
log.WithField("signedOrder", signedOrder).Panic("EthereumRPCMaxContentLength is set so low, a single 0x order cannot fit beneath the payload limit")
}
chunkSizes = append(chunkSizes, nextChunkSize)
nextChunkSize = 1
payloadLength = jsonRPCPayloadByteLength + encodedSignedOrderByteLength
}
}
if nextChunkSize != 0 {
chunkSizes = append(chunkSizes, nextChunkSize)
}
return chunkSizes
}
func isSupportedSignature(signature []byte, orderHash common.Hash) bool {
signatureType := SignatureType(signature[len(signature)-1])
switch signatureType {
case IllegalSignature:
case InvalidSignature:
return false
case EIP712Signature:
if len(signature) != 66 {
return false
}
// TODO(fabio): Do further validation by splitting into r,s,v and do ECRecover
case EthSignSignature:
if len(signature) != 66 {
return false
}
// TODO(fabio): Do further validation by splitting into r,s,v, add prefix to hash
// and do ECRecover
case ValidatorSignature:
if len(signature) < 21 {
return false
}
case WalletSignature:
case PreSignedSignature:
return true
default:
return false
}
return true
}