-
Notifications
You must be signed in to change notification settings - Fork 179
/
backend.go
360 lines (302 loc) · 10.7 KB
/
backend.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
package backend
import (
"context"
"fmt"
"github.com/okex/exchain/x/evm/watcher"
"github.com/tendermint/tendermint/libs/log"
rpctypes "github.com/okex/exchain/app/rpc/types"
evmtypes "github.com/okex/exchain/x/evm/types"
clientcontext "github.com/cosmos/cosmos-sdk/client/context"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/bitutil"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/bloombits"
ethtypes "github.com/ethereum/go-ethereum/core/types"
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
)
// Backend implements the functionality needed to filter changes.
// Implemented by EthermintBackend.
type Backend interface {
// Used by block filter; also used for polling
BlockNumber() (hexutil.Uint64, error)
LatestBlockNumber() (int64, error)
HeaderByNumber(blockNum rpctypes.BlockNumber) (*ethtypes.Header, error)
HeaderByHash(blockHash common.Hash) (*ethtypes.Header, error)
GetBlockByNumber(blockNum rpctypes.BlockNumber, fullTx bool) (interface{}, error)
GetBlockByHash(hash common.Hash, fullTx bool) (interface{}, error)
// returns the logs of a given block
GetLogs(blockHash common.Hash) ([][]*ethtypes.Log, error)
// Used by pending transaction filter
PendingTransactions() ([]*rpctypes.Transaction, error)
// Used by log filter
GetTransactionLogs(txHash common.Hash) ([]*ethtypes.Log, error)
BloomStatus() (uint64, uint64)
ServiceFilter(ctx context.Context, session *bloombits.MatcherSession)
}
var _ Backend = (*EthermintBackend)(nil)
// EthermintBackend implements the Backend interface
type EthermintBackend struct {
ctx context.Context
clientCtx clientcontext.CLIContext
logger log.Logger
gasLimit int64
bloomRequests chan chan *bloombits.Retrieval
closeBloomHandler chan struct{}
wrappedBackend *watcher.Querier
}
// New creates a new EthermintBackend instance
func New(clientCtx clientcontext.CLIContext, log log.Logger) *EthermintBackend {
return &EthermintBackend{
ctx: context.Background(),
clientCtx: clientCtx,
logger: log.With("module", "json-rpc"),
gasLimit: int64(^uint32(0)),
bloomRequests: make(chan chan *bloombits.Retrieval),
closeBloomHandler: make(chan struct{}),
wrappedBackend: watcher.NewQuerier(),
}
}
// BlockNumber returns the current block number.
func (b *EthermintBackend) BlockNumber() (hexutil.Uint64, error) {
ublockNumber, err := b.wrappedBackend.GetLatestBlockNumber()
if err == nil {
if ublockNumber > 0 {
//decrease blockNumber to make sure every block has been executed in local
ublockNumber--
}
return hexutil.Uint64(ublockNumber), err
}
blockNumber, err := b.LatestBlockNumber()
if err != nil {
return hexutil.Uint64(0), err
}
if blockNumber > 0 {
//decrease blockNumber to make sure every block has been executed in local
blockNumber--
}
return hexutil.Uint64(blockNumber), nil
}
// GetBlockByNumber returns the block identified by number.
func (b *EthermintBackend) GetBlockByNumber(blockNum rpctypes.BlockNumber, fullTx bool) (interface{}, error) {
ethBlock, err := b.wrappedBackend.GetBlockByNumber(uint64(blockNum), fullTx)
if err == nil {
return ethBlock, nil
}
height := blockNum.Int64()
if height <= 0 {
// get latest block height
num, err := b.BlockNumber()
if err != nil {
return nil, err
}
height = int64(num)
}
resBlock, err := b.clientCtx.Client.Block(&height)
if err != nil {
return nil, nil
}
return rpctypes.EthBlockFromTendermint(b.clientCtx, resBlock.Block, fullTx)
}
// GetBlockByHash returns the block identified by hash.
func (b *EthermintBackend) GetBlockByHash(hash common.Hash, fullTx bool) (interface{}, error) {
ethBlock, err := b.wrappedBackend.GetBlockByHash(hash, fullTx)
if err == nil {
return ethBlock, nil
}
res, _, err := b.clientCtx.Query(fmt.Sprintf("custom/%s/%s/%s", evmtypes.ModuleName, evmtypes.QueryHashToHeight, hash.Hex()))
if err != nil {
return nil, err
}
var out evmtypes.QueryResBlockNumber
if err := b.clientCtx.Codec.UnmarshalJSON(res, &out); err != nil {
return nil, err
}
resBlock, err := b.clientCtx.Client.Block(&out.Number)
if err != nil {
return nil, nil
}
return rpctypes.EthBlockFromTendermint(b.clientCtx, resBlock.Block, fullTx)
}
// HeaderByNumber returns the block header identified by height.
func (b *EthermintBackend) HeaderByNumber(blockNum rpctypes.BlockNumber) (*ethtypes.Header, error) {
height := blockNum.Int64()
if height <= 0 {
// get latest block height
num, err := b.BlockNumber()
if err != nil {
return nil, err
}
height = int64(num)
}
resBlock, err := b.clientCtx.Client.Block(&height)
if err != nil {
return nil, err
}
res, _, err := b.clientCtx.Query(fmt.Sprintf("custom/%s/%s/%d", evmtypes.ModuleName, evmtypes.QueryBloom, resBlock.Block.Height))
if err != nil {
return nil, err
}
var bloomRes evmtypes.QueryBloomFilter
b.clientCtx.Codec.MustUnmarshalJSON(res, &bloomRes)
ethHeader := rpctypes.EthHeaderFromTendermint(resBlock.Block.Header)
ethHeader.Bloom = bloomRes.Bloom
return ethHeader, nil
}
// HeaderByHash returns the block header identified by hash.
func (b *EthermintBackend) HeaderByHash(blockHash common.Hash) (*ethtypes.Header, error) {
res, _, err := b.clientCtx.Query(fmt.Sprintf("custom/%s/%s/%s", evmtypes.ModuleName, evmtypes.QueryHashToHeight, blockHash.Hex()))
if err != nil {
return nil, err
}
var out evmtypes.QueryResBlockNumber
if err := b.clientCtx.Codec.UnmarshalJSON(res, &out); err != nil {
return nil, err
}
resBlock, err := b.clientCtx.Client.Block(&out.Number)
if err != nil {
return nil, err
}
res, _, err = b.clientCtx.Query(fmt.Sprintf("custom/%s/%s/%d", evmtypes.ModuleName, evmtypes.QueryBloom, resBlock.Block.Height))
if err != nil {
return nil, err
}
var bloomRes evmtypes.QueryBloomFilter
b.clientCtx.Codec.MustUnmarshalJSON(res, &bloomRes)
ethHeader := rpctypes.EthHeaderFromTendermint(resBlock.Block.Header)
ethHeader.Bloom = bloomRes.Bloom
return ethHeader, nil
}
// GetTransactionLogs returns the logs given a transaction hash.
// It returns an error if there's an encoding error.
// If no logs are found for the tx hash, the error is nil.
func (b *EthermintBackend) GetTransactionLogs(txHash common.Hash) ([]*ethtypes.Log, error) {
txRes, err := b.clientCtx.Client.Tx(txHash.Bytes(), !b.clientCtx.TrustNode)
if err != nil {
return nil, err
}
execRes, err := evmtypes.DecodeResultData(txRes.TxResult.Data)
if err != nil {
return nil, err
}
return execRes.Logs, nil
}
// PendingTransactions returns the transactions that are in the transaction pool
// and have a from address that is one of the accounts this node manages.
func (b *EthermintBackend) PendingTransactions() ([]*rpctypes.Transaction, error) {
pendingTxs, err := b.clientCtx.Client.UnconfirmedTxs(-1)
if err != nil {
return nil, err
}
transactions := make([]*rpctypes.Transaction, 0)
for _, tx := range pendingTxs.Txs {
ethTx, err := rpctypes.RawTxToEthTx(b.clientCtx, tx)
if err != nil {
// ignore non Ethermint EVM transactions
continue
}
// TODO: check signer and reference against accounts the node manages
rpcTx, err := rpctypes.NewTransaction(ethTx, common.BytesToHash(tx.Hash()), common.Hash{}, 0, 0)
if err != nil {
return nil, err
}
transactions = append(transactions, rpcTx)
}
return transactions, nil
}
// GetLogs returns all the logs from all the ethereum transactions in a block.
func (b *EthermintBackend) GetLogs(blockHash common.Hash) ([][]*ethtypes.Log, error) {
res, _, err := b.clientCtx.Query(fmt.Sprintf("custom/%s/%s/%s", evmtypes.ModuleName, evmtypes.QueryHashToHeight, blockHash.Hex()))
if err != nil {
return nil, err
}
var out evmtypes.QueryResBlockNumber
if err := b.clientCtx.Codec.UnmarshalJSON(res, &out); err != nil {
return nil, err
}
block, err := b.clientCtx.Client.Block(&out.Number)
if err != nil {
return nil, err
}
var blockLogs = [][]*ethtypes.Log{}
for _, tx := range block.Block.Txs {
// NOTE: we query the state in case the tx result logs are not persisted after an upgrade.
txRes, err := b.clientCtx.Client.Tx(tx.Hash(), !b.clientCtx.TrustNode)
if err != nil {
continue
}
execRes, err := evmtypes.DecodeResultData(txRes.TxResult.Data)
if err != nil {
continue
}
blockLogs = append(blockLogs, execRes.Logs)
}
return blockLogs, nil
}
// BloomStatus returns the BloomBitsBlocks and the number of processed sections maintained
// by the chain indexer.
func (b *EthermintBackend) BloomStatus() (uint64, uint64) {
sections := evmtypes.GetIndexer().StoredSection()
return evmtypes.BloomBitsBlocks, sections
}
// LatestBlockNumber gets the latest block height in int64 format.
func (b *EthermintBackend) LatestBlockNumber() (int64, error) {
// NOTE: using 0 as min and max height returns the blockchain info up to the latest block.
info, err := b.clientCtx.Client.BlockchainInfo(0, 0)
if err != nil {
return 0, err
}
return info.LastHeight, nil
}
func (b *EthermintBackend) ServiceFilter(ctx context.Context, session *bloombits.MatcherSession) {
for i := 0; i < evmtypes.BloomFilterThreads; i++ {
go session.Multiplex(evmtypes.BloomRetrievalBatch, evmtypes.BloomRetrievalWait, b.bloomRequests)
}
}
// startBloomHandlers starts a batch of goroutines to accept bloom bit database
// retrievals from possibly a range of filters and serving the data to satisfy.
func (b *EthermintBackend) StartBloomHandlers(sectionSize uint64, db dbm.DB) {
for i := 0; i < evmtypes.BloomServiceThreads; i++ {
go func() {
for {
select {
case <-b.closeBloomHandler:
return
case request := <-b.bloomRequests:
task := <-request
task.Bitsets = make([][]byte, len(task.Sections))
for i, section := range task.Sections {
height := int64((section+1)*sectionSize-1) + tmtypes.GetStartBlockHeight()
hash, err := b.GetBlockHashByHeight(rpctypes.BlockNumber(height))
if err != nil {
task.Error = err
}
if compVector, err := evmtypes.ReadBloomBits(db, task.Bit, section, hash); err == nil {
if blob, err := bitutil.DecompressBytes(compVector, int(sectionSize/8)); err == nil {
task.Bitsets[i] = blob
} else {
task.Error = err
}
} else {
task.Error = err
}
}
request <- task
}
}
}()
}
}
// GetBlockHashByHeight returns the block hash by height.
func (b *EthermintBackend) GetBlockHashByHeight(height rpctypes.BlockNumber) (common.Hash, error) {
res, _, err := b.clientCtx.Query(fmt.Sprintf("custom/%s/%s/%d", evmtypes.ModuleName, evmtypes.QueryHeightToHash, height))
if err != nil {
return common.Hash{}, err
}
hash := common.BytesToHash(res)
return hash, nil
}
// Close
func (b *EthermintBackend) Close() {
close(b.closeBloomHandler)
}