/
blocks.go
514 lines (439 loc) · 16.7 KB
/
blocks.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
// Copyright 2022 Match Foundation
// This file is part of the Match Network packages.
//
// Match is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Match packages are distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Match packages. If not, see https://github.com/matchain/match/blob/main/LICENSE
package backend
import (
"bytes"
"fmt"
"math"
"math/big"
"strconv"
sdk "github.com/cosmos/cosmos-sdk/types"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/trie"
rpctypes "github.com/matchain/match/rpc/types"
evmtypes "github.com/matchain/match/x/evm/types"
"github.com/pkg/errors"
tmrpctypes "github.com/tendermint/tendermint/rpc/core/types"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
// BlockNumber returns the current block number in abci app state. Because abci
// app state could lag behind from tendermint latest block, it's more stable for
// the client to use the latest block number in abci app state than tendermint
// rpc.
func (b *Backend) BlockNumber() (hexutil.Uint64, error) {
// do any grpc query, ignore the response and use the returned block height
var header metadata.MD
_, err := b.queryClient.Params(b.ctx, &evmtypes.QueryParamsRequest{}, grpc.Header(&header))
if err != nil {
return hexutil.Uint64(0), err
}
blockHeightHeader := header.Get(grpctypes.GRPCBlockHeightHeader)
if headerLen := len(blockHeightHeader); headerLen != 1 {
return 0, fmt.Errorf("unexpected '%s' gRPC header length; got %d, expected: %d", grpctypes.GRPCBlockHeightHeader, headerLen, 1)
}
height, err := strconv.ParseUint(blockHeightHeader[0], 10, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse block height: %w", err)
}
if height > math.MaxInt64 {
return 0, fmt.Errorf("block height %d is greater than max uint64", height)
}
return hexutil.Uint64(height), nil
}
// GetBlockByNumber returns the JSON-RPC compatible Ethereum block identified by
// block number. Depending on fullTx it either returns the full transaction
// objects or if false only the hashes of the transactions.
func (b *Backend) GetBlockByNumber(blockNum rpctypes.BlockNumber, fullTx bool) (map[string]interface{}, error) {
resBlock, err := b.TendermintBlockByNumber(blockNum)
if err != nil {
return nil, nil
}
// return if requested block height is greater than the current one
if resBlock == nil || resBlock.Block == nil {
return nil, nil
}
blockRes, err := b.TendermintBlockResultByNumber(&resBlock.Block.Height)
if err != nil {
b.logger.Debug("failed to fetch block result from Tendermint", "height", blockNum, "error", err.Error())
return nil, nil
}
res, err := b.RPCBlockFromTendermintBlock(resBlock, blockRes, fullTx)
if err != nil {
b.logger.Debug("GetEthBlockFromTendermint failed", "height", blockNum, "error", err.Error())
return nil, err
}
return res, nil
}
// GetBlockByHash returns the JSON-RPC compatible Ethereum block identified by
// hash.
func (b *Backend) GetBlockByHash(hash common.Hash, fullTx bool) (map[string]interface{}, error) {
resBlock, err := b.TendermintBlockByHash(hash)
if err != nil {
return nil, err
}
if resBlock == nil {
// block not found
return nil, nil
}
blockRes, err := b.TendermintBlockResultByNumber(&resBlock.Block.Height)
if err != nil {
b.logger.Debug("failed to fetch block result from Tendermint", "block-hash", hash.String(), "error", err.Error())
return nil, nil
}
res, err := b.RPCBlockFromTendermintBlock(resBlock, blockRes, fullTx)
if err != nil {
b.logger.Debug("GetEthBlockFromTendermint failed", "hash", hash, "error", err.Error())
return nil, err
}
return res, nil
}
// GetBlockTransactionCountByHash returns the number of Ethereum transactions in
// the block identified by hash.
func (b *Backend) GetBlockTransactionCountByHash(hash common.Hash) *hexutil.Uint {
block, err := b.clientCtx.Client.BlockByHash(b.ctx, hash.Bytes())
if err != nil {
b.logger.Debug("block not found", "hash", hash.Hex(), "error", err.Error())
return nil
}
if block.Block == nil {
b.logger.Debug("block not found", "hash", hash.Hex())
return nil
}
return b.GetBlockTransactionCount(block)
}
// GetBlockTransactionCountByNumber returns the number of Ethereum transactions
// in the block identified by number.
func (b *Backend) GetBlockTransactionCountByNumber(blockNum rpctypes.BlockNumber) *hexutil.Uint {
block, err := b.TendermintBlockByNumber(blockNum)
if err != nil {
b.logger.Debug("block not found", "height", blockNum.Int64(), "error", err.Error())
return nil
}
if block.Block == nil {
b.logger.Debug("block not found", "height", blockNum.Int64())
return nil
}
return b.GetBlockTransactionCount(block)
}
// GetBlockTransactionCount returns the number of Ethereum transactions in a
// given block.
func (b *Backend) GetBlockTransactionCount(block *tmrpctypes.ResultBlock) *hexutil.Uint {
blockRes, err := b.TendermintBlockResultByNumber(&block.Block.Height)
if err != nil {
return nil
}
ethMsgs := b.EthMsgsFromTendermintBlock(block, blockRes)
n := hexutil.Uint(len(ethMsgs))
return &n
}
// TendermintBlockByNumber returns a Tendermint-formatted block for a given
// block number
func (b *Backend) TendermintBlockByNumber(blockNum rpctypes.BlockNumber) (*tmrpctypes.ResultBlock, error) {
height := blockNum.Int64()
if height <= 0 {
// fetch the latest block number from the app state, more accurate than the tendermint block store state.
n, err := b.BlockNumber()
if err != nil {
return nil, err
}
height = int64(n) //#nosec G701 -- checked for int overflow already
}
resBlock, err := b.clientCtx.Client.Block(b.ctx, &height)
if err != nil {
b.logger.Debug("tendermint client failed to get block", "height", height, "error", err.Error())
return nil, err
}
if resBlock.Block == nil {
b.logger.Debug("TendermintBlockByNumber block not found", "height", height)
return nil, nil
}
return resBlock, nil
}
// TendermintBlockResultByNumber returns a Tendermint-formatted block result
// by block number
func (b *Backend) TendermintBlockResultByNumber(height *int64) (*tmrpctypes.ResultBlockResults, error) {
return b.clientCtx.Client.BlockResults(b.ctx, height)
}
// TendermintBlockByHash returns a Tendermint-formatted block by block number
func (b *Backend) TendermintBlockByHash(blockHash common.Hash) (*tmrpctypes.ResultBlock, error) {
resBlock, err := b.clientCtx.Client.BlockByHash(b.ctx, blockHash.Bytes())
if err != nil {
b.logger.Debug("tendermint client failed to get block", "blockHash", blockHash.Hex(), "error", err.Error())
return nil, err
}
if resBlock == nil || resBlock.Block == nil {
b.logger.Debug("TendermintBlockByHash block not found", "blockHash", blockHash.Hex())
return nil, nil
}
return resBlock, nil
}
// BlockNumberFromTendermint returns the BlockNumber from BlockNumberOrHash
func (b *Backend) BlockNumberFromTendermint(blockNrOrHash rpctypes.BlockNumberOrHash) (rpctypes.BlockNumber, error) {
switch {
case blockNrOrHash.BlockHash == nil && blockNrOrHash.BlockNumber == nil:
return rpctypes.EthEarliestBlockNumber, fmt.Errorf("types BlockHash and BlockNumber cannot be both nil")
case blockNrOrHash.BlockHash != nil:
blockNumber, err := b.BlockNumberFromTendermintByHash(*blockNrOrHash.BlockHash)
if err != nil {
return rpctypes.EthEarliestBlockNumber, err
}
return rpctypes.NewBlockNumber(blockNumber), nil
case blockNrOrHash.BlockNumber != nil:
return *blockNrOrHash.BlockNumber, nil
default:
return rpctypes.EthEarliestBlockNumber, nil
}
}
// BlockNumberFromTendermintByHash returns the block height of given block hash
func (b *Backend) BlockNumberFromTendermintByHash(blockHash common.Hash) (*big.Int, error) {
resBlock, err := b.TendermintBlockByHash(blockHash)
if err != nil {
return nil, err
}
if resBlock == nil {
return nil, errors.Errorf("block not found for hash %s", blockHash.Hex())
}
return big.NewInt(resBlock.Block.Height), nil
}
// EthMsgsFromTendermintBlock returns all real MsgEthereumTxs from a
// Tendermint block. It also ensures consistency over the correct txs indexes
// across RPC endpoints
func (b *Backend) EthMsgsFromTendermintBlock(
resBlock *tmrpctypes.ResultBlock,
blockRes *tmrpctypes.ResultBlockResults,
) []*evmtypes.MsgEthereumTx {
var result []*evmtypes.MsgEthereumTx
block := resBlock.Block
txResults := blockRes.TxsResults
for i, tx := range block.Txs {
// Check if tx exists on EVM by cross checking with blockResults:
// - Include unsuccessful tx that exceeds block gas limit
// - Exclude unsuccessful tx with any other error but ExceedBlockGasLimit
if !rpctypes.TxSuccessOrExceedsBlockGasLimit(txResults[i]) {
b.logger.Debug("invalid tx result code", "cosmos-hash", hexutil.Encode(tx.Hash()))
continue
}
tx, err := b.clientCtx.TxConfig.TxDecoder()(tx)
if err != nil {
b.logger.Debug("failed to decode transaction in block", "height", block.Height, "error", err.Error())
continue
}
for _, msg := range tx.GetMsgs() {
ethMsg, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok {
continue
}
ethMsg.Hash = ethMsg.AsTransaction().Hash().Hex()
result = append(result, ethMsg)
}
}
return result
}
// HeaderByNumber returns the block header identified by height.
func (b *Backend) HeaderByNumber(blockNum rpctypes.BlockNumber) (*ethtypes.Header, error) {
resBlock, err := b.TendermintBlockByNumber(blockNum)
if err != nil {
return nil, err
}
if resBlock == nil {
return nil, errors.Errorf("block not found for height %d", blockNum)
}
blockRes, err := b.TendermintBlockResultByNumber(&resBlock.Block.Height)
if err != nil {
return nil, fmt.Errorf("block result not found for height %d", resBlock.Block.Height)
}
bloom, err := b.BlockBloom(blockRes)
if err != nil {
b.logger.Debug("HeaderByNumber BlockBloom failed", "height", resBlock.Block.Height)
}
baseFee, err := b.BaseFee(blockRes)
if err != nil {
// handle the error for pruned node.
b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", resBlock.Block.Height, "error", err)
}
ethHeader := rpctypes.EthHeaderFromTendermint(resBlock.Block.Header, bloom, baseFee)
return ethHeader, nil
}
// HeaderByHash returns the block header identified by hash.
func (b *Backend) HeaderByHash(blockHash common.Hash) (*ethtypes.Header, error) {
resBlock, err := b.TendermintBlockByHash(blockHash)
if err != nil {
return nil, err
}
if resBlock == nil {
return nil, errors.Errorf("block not found for hash %s", blockHash.Hex())
}
blockRes, err := b.TendermintBlockResultByNumber(&resBlock.Block.Height)
if err != nil {
return nil, errors.Errorf("block result not found for height %d", resBlock.Block.Height)
}
bloom, err := b.BlockBloom(blockRes)
if err != nil {
b.logger.Debug("HeaderByHash BlockBloom failed", "height", resBlock.Block.Height)
}
baseFee, err := b.BaseFee(blockRes)
if err != nil {
// handle the error for pruned node.
b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", resBlock.Block.Height, "error", err)
}
ethHeader := rpctypes.EthHeaderFromTendermint(resBlock.Block.Header, bloom, baseFee)
return ethHeader, nil
}
// BlockBloom query block bloom filter from block results
func (b *Backend) BlockBloom(blockRes *tmrpctypes.ResultBlockResults) (ethtypes.Bloom, error) {
for _, event := range blockRes.EndBlockEvents {
if event.Type != evmtypes.EventTypeBlockBloom {
continue
}
for _, attr := range event.Attributes {
if bytes.Equal(attr.Key, bAttributeKeyEthereumBloom) {
return ethtypes.BytesToBloom(attr.Value), nil
}
}
}
return ethtypes.Bloom{}, errors.New("block bloom event is not found")
}
// RPCBlockFromTendermintBlock returns a JSON-RPC compatible Ethereum block from a
// given Tendermint block and its block result.
func (b *Backend) RPCBlockFromTendermintBlock(
resBlock *tmrpctypes.ResultBlock,
blockRes *tmrpctypes.ResultBlockResults,
fullTx bool,
) (map[string]interface{}, error) {
ethRPCTxs := []interface{}{}
block := resBlock.Block
baseFee, err := b.BaseFee(blockRes)
if err != nil {
// handle the error for pruned node.
b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", block.Height, "error", err)
}
msgs := b.EthMsgsFromTendermintBlock(resBlock, blockRes)
for txIndex, ethMsg := range msgs {
if !fullTx {
hash := common.HexToHash(ethMsg.Hash)
ethRPCTxs = append(ethRPCTxs, hash)
continue
}
tx := ethMsg.AsTransaction()
height := uint64(block.Height) //#nosec G701 -- checked for int overflow already
index := uint64(txIndex) //#nosec G701 -- checked for int overflow already
rpcTx, err := rpctypes.NewRPCTransaction(
tx,
common.BytesToHash(block.Hash()),
height,
index,
baseFee,
b.chainID,
)
if err != nil {
b.logger.Debug("NewTransactionFromData for receipt failed", "hash", tx.Hash().Hex(), "error", err.Error())
continue
}
ethRPCTxs = append(ethRPCTxs, rpcTx)
}
bloom, err := b.BlockBloom(blockRes)
if err != nil {
b.logger.Debug("failed to query BlockBloom", "height", block.Height, "error", err.Error())
}
req := &evmtypes.QueryValidatorAccountRequest{
ConsAddress: sdk.ConsAddress(block.Header.ProposerAddress).String(),
}
var validatorAccAddr sdk.AccAddress
ctx := rpctypes.ContextWithHeight(block.Height)
res, err := b.queryClient.ValidatorAccount(ctx, req)
if err != nil {
b.logger.Debug(
"failed to query validator operator address",
"height", block.Height,
"cons-address", req.ConsAddress,
"error", err.Error(),
)
// use zero address as the validator operator address
validatorAccAddr = sdk.AccAddress(common.Address{}.Bytes())
} else {
validatorAccAddr, err = sdk.AccAddressFromBech32(res.AccountAddress)
if err != nil {
return nil, err
}
}
validatorAddr := common.BytesToAddress(validatorAccAddr)
gasLimit, err := rpctypes.BlockMaxGasFromConsensusParams(ctx, b.clientCtx, block.Height)
if err != nil {
b.logger.Error("failed to query consensus params", "error", err.Error())
}
gasUsed := uint64(0)
for _, txsResult := range blockRes.TxsResults {
// workaround for cosmos-sdk bug. https://github.com/cosmos/cosmos-sdk/issues/10832
if ShouldIgnoreGasUsed(txsResult) {
// block gas limit has exceeded, other txs must have failed with same reason.
break
}
gasUsed += uint64(txsResult.GetGasUsed()) // #nosec G701 -- checked for int overflow already
}
formattedBlock := rpctypes.FormatBlock(
block.Header, block.Size(),
gasLimit, new(big.Int).SetUint64(gasUsed),
ethRPCTxs, bloom, validatorAddr, baseFee,
)
return formattedBlock, nil
}
// EthBlockByNumber returns the Ethereum Block identified by number.
func (b *Backend) EthBlockByNumber(blockNum rpctypes.BlockNumber) (*ethtypes.Block, error) {
resBlock, err := b.TendermintBlockByNumber(blockNum)
if err != nil {
return nil, err
}
if resBlock == nil {
// block not found
return nil, fmt.Errorf("block not found for height %d", blockNum)
}
blockRes, err := b.TendermintBlockResultByNumber(&resBlock.Block.Height)
if err != nil {
return nil, fmt.Errorf("block result not found for height %d", resBlock.Block.Height)
}
return b.EthBlockFromTendermintBlock(resBlock, blockRes)
}
// EthBlockFromTendermintBlock returns an Ethereum Block type from Tendermint block
// EthBlockFromTendermintBlock
func (b *Backend) EthBlockFromTendermintBlock(
resBlock *tmrpctypes.ResultBlock,
blockRes *tmrpctypes.ResultBlockResults,
) (*ethtypes.Block, error) {
block := resBlock.Block
height := block.Height
bloom, err := b.BlockBloom(blockRes)
if err != nil {
b.logger.Debug("HeaderByNumber BlockBloom failed", "height", height)
}
baseFee, err := b.BaseFee(blockRes)
if err != nil {
// handle error for pruned node and log
b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", height, "error", err)
}
ethHeader := rpctypes.EthHeaderFromTendermint(block.Header, bloom, baseFee)
msgs := b.EthMsgsFromTendermintBlock(resBlock, blockRes)
txs := make([]*ethtypes.Transaction, len(msgs))
for i, ethMsg := range msgs {
txs[i] = ethMsg.AsTransaction()
}
// TODO: add tx receipts
ethBlock := ethtypes.NewBlock(ethHeader, txs, nil, nil, trie.NewStackTrie(nil))
return ethBlock, nil
}