-
Notifications
You must be signed in to change notification settings - Fork 246
/
transaction_validator.go
328 lines (275 loc) · 9.65 KB
/
transaction_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
package protocol
import (
"context"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"time"
"math/big"
"strings"
"github.com/pkg/errors"
"go.uber.org/zap"
coretypes "github.com/status-im/status-go/eth-node/core/types"
"github.com/status-im/status-go/eth-node/crypto"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/protocol/common"
)
const (
transferFunction = "a9059cbb"
tokenTransferDataLength = 68
transactionHashLength = 66
)
type TransactionValidator struct {
persistence *sqlitePersistence
addresses map[string]bool
client EthClient
logger *zap.Logger
}
var invalidResponse = &VerifyTransactionResponse{Valid: false}
type TransactionToValidate struct {
TransactionHash string
CommandID string
MessageID string
RetryCount int
// First seen indicates the whisper timestamp of the first time we seen this
FirstSeen uint64
// Validate indicates whether we should be validating this transaction
Validate bool
Signature []byte
From *ecdsa.PublicKey
}
func NewTransactionValidator(addresses []types.Address, persistence *sqlitePersistence, client EthClient, logger *zap.Logger) *TransactionValidator {
addressesMap := make(map[string]bool)
for _, a := range addresses {
addressesMap[strings.ToLower(a.Hex())] = true
}
logger.Debug("Checking addresses", zap.Any("addrse", addressesMap))
return &TransactionValidator{
persistence: persistence,
addresses: addressesMap,
logger: logger,
client: client,
}
}
type EthClient interface {
TransactionByHash(context.Context, types.Hash) (coretypes.Message, coretypes.TransactionStatus, error)
}
func (t *TransactionValidator) verifyTransactionSignature(ctx context.Context, from *ecdsa.PublicKey, address types.Address, transactionHash string, signature []byte) error {
publicKeyBytes := crypto.FromECDSAPub(from)
if len(transactionHash) != transactionHashLength {
return errors.New("wrong transaction hash length")
}
hashBytes, err := hex.DecodeString(transactionHash[2:])
if err != nil {
return err
}
signatureMaterial := append(publicKeyBytes, hashBytes...)
// We take a copy as EcRecover modifies the byte slice
signatureCopy := make([]byte, len(signature))
copy(signatureCopy, signature)
extractedAddress, err := crypto.EcRecover(ctx, signatureMaterial, signatureCopy)
if err != nil {
return err
}
if extractedAddress != address {
return errors.New("failed to verify signature")
}
return nil
}
func (t *TransactionValidator) validateTokenTransfer(parameters *common.CommandParameters, transaction coretypes.Message) (*VerifyTransactionResponse, error) {
data := transaction.Data()
if len(data) != tokenTransferDataLength {
return nil, errors.New(fmt.Sprintf("wrong data length: %d", len(data)))
}
functionCalled := hex.EncodeToString(data[:4])
if functionCalled != transferFunction {
return invalidResponse, nil
}
actualContractAddress := strings.ToLower(transaction.To().Hex())
if parameters.Contract != "" && actualContractAddress != parameters.Contract {
return invalidResponse, nil
}
to := types.EncodeHex(data[16:36])
if !t.validateToAddress(parameters.Address, to) {
return invalidResponse, nil
}
value := data[36:]
amount := new(big.Int).SetBytes(value)
if parameters.Value != "" {
advertisedAmount, ok := new(big.Int).SetString(parameters.Value, 10)
if !ok {
return nil, errors.New("can't parse amount")
}
return &VerifyTransactionResponse{
Value: parameters.Value,
Contract: actualContractAddress,
Address: to,
AccordingToSpec: amount.Cmp(advertisedAmount) == 0,
Valid: true,
}, nil
}
return &VerifyTransactionResponse{
Value: amount.String(),
Address: to,
Contract: actualContractAddress,
AccordingToSpec: false,
Valid: true,
}, nil
}
func (t *TransactionValidator) validateToAddress(specifiedTo, actualTo string) bool {
if len(specifiedTo) != 0 && (!strings.EqualFold(specifiedTo, actualTo) || !t.addresses[strings.ToLower(actualTo)]) {
return false
}
return t.addresses[actualTo]
}
func (t *TransactionValidator) validateEthereumTransfer(parameters *common.CommandParameters, transaction coretypes.Message) (*VerifyTransactionResponse, error) {
toAddress := strings.ToLower(transaction.To().Hex())
if !t.validateToAddress(parameters.Address, toAddress) {
return invalidResponse, nil
}
amount := transaction.Value()
if parameters.Value != "" {
advertisedAmount, ok := new(big.Int).SetString(parameters.Value, 10)
if !ok {
return nil, errors.New("can't parse amount")
}
return &VerifyTransactionResponse{
AccordingToSpec: amount.Cmp(advertisedAmount) == 0,
Valid: true,
Value: amount.String(),
Address: toAddress,
}, nil
}
return &VerifyTransactionResponse{
AccordingToSpec: false,
Valid: true,
Value: amount.String(),
Address: toAddress,
}, nil
}
type VerifyTransactionResponse struct {
Pending bool
// AccordingToSpec means that the transaction is valid,
// the user should be notified, but is not the same as
// what was requested, for example because the value is different
AccordingToSpec bool
// Valid means that the transaction is valid
Valid bool
// The actual value received
Value string
// The contract used in case of tokens
Contract string
// The address the transaction was actually sent
Address string
Message *common.Message
Transaction *TransactionToValidate
}
// validateTransaction validates a transaction and returns a response.
// If a negative response is returned, i.e `Valid` is false, it should
// not be retried.
// If an error is returned, validation can be retried.
func (t *TransactionValidator) validateTransaction(ctx context.Context, message coretypes.Message, parameters *common.CommandParameters, from *ecdsa.PublicKey) (*VerifyTransactionResponse, error) {
fromAddress := types.BytesToAddress(message.From().Bytes())
err := t.verifyTransactionSignature(ctx, from, fromAddress, parameters.TransactionHash, parameters.Signature)
if err != nil {
t.logger.Error("failed validating signature", zap.Error(err))
return invalidResponse, nil
}
if len(message.Data()) != 0 {
t.logger.Debug("Validating token")
return t.validateTokenTransfer(parameters, message)
}
t.logger.Debug("Validating eth")
return t.validateEthereumTransfer(parameters, message)
}
func (t *TransactionValidator) ValidateTransactions(ctx context.Context) ([]*VerifyTransactionResponse, error) {
if t.client == nil {
return nil, nil
}
var response []*VerifyTransactionResponse
t.logger.Debug("Started validating transactions")
transactions, err := t.persistence.TransactionsToValidate()
if err != nil {
return nil, err
}
t.logger.Debug("Transactions to validated", zap.Any("transactions", transactions))
for _, transaction := range transactions {
var validationResult *VerifyTransactionResponse
t.logger.Debug("Validating transaction", zap.Any("transaction", transaction))
if transaction.CommandID != "" {
chatID := contactIDFromPublicKey(transaction.From)
message, err := t.persistence.MessageByCommandID(chatID, transaction.CommandID)
if err != nil {
t.logger.Error("error pulling message", zap.Error(err))
return nil, err
}
if message == nil {
t.logger.Info("No message found, ignoring transaction")
// This is not a valid case, ignore transaction
transaction.Validate = false
transaction.RetryCount++
err = t.persistence.UpdateTransactionToValidate(transaction)
if err != nil {
return nil, err
}
continue
}
commandParameters := message.CommandParameters
commandParameters.TransactionHash = transaction.TransactionHash
commandParameters.Signature = transaction.Signature
validationResult, err = t.ValidateTransaction(ctx, message.CommandParameters, transaction.From)
if err != nil {
t.logger.Error("Error validating transaction", zap.Error(err))
continue
}
validationResult.Message = message
} else {
commandParameters := &common.CommandParameters{}
commandParameters.TransactionHash = transaction.TransactionHash
commandParameters.Signature = transaction.Signature
validationResult, err = t.ValidateTransaction(ctx, commandParameters, transaction.From)
if err != nil {
t.logger.Error("Error validating transaction", zap.Error(err))
continue
}
}
if validationResult.Pending {
t.logger.Debug("Pending transaction skipping")
// Check if we should stop updating
continue
}
// Mark transaction as valid
transaction.Validate = false
transaction.RetryCount++
err = t.persistence.UpdateTransactionToValidate(transaction)
if err != nil {
return nil, err
}
if !validationResult.Valid {
t.logger.Debug("Transaction not valid")
continue
}
t.logger.Debug("Transaction valid")
validationResult.Transaction = transaction
response = append(response, validationResult)
}
return response, nil
}
func (t *TransactionValidator) ValidateTransaction(ctx context.Context, parameters *common.CommandParameters, from *ecdsa.PublicKey) (*VerifyTransactionResponse, error) {
t.logger.Debug("validating transaction", zap.Any("transaction", parameters), zap.Any("from", from))
hash := parameters.TransactionHash
c, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
message, status, err := t.client.TransactionByHash(c, types.HexToHash(hash))
if err != nil {
return nil, err
}
switch status {
case coretypes.TransactionStatusPending:
t.logger.Debug("Transaction pending")
return &VerifyTransactionResponse{Pending: true}, nil
case coretypes.TransactionStatusFailed:
return invalidResponse, nil
}
return t.validateTransaction(ctx, message, parameters, from)
}