-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy patheth_block.go
474 lines (414 loc) · 13.8 KB
/
eth_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
// Copyright 2024 The Erigon Authors
// This file is part of Erigon.
//
// Erigon 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.
//
// Erigon is 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 Erigon. If not, see <http://www.gnu.org/licenses/>.
package jsonrpc
import (
"context"
"fmt"
"math/big"
"time"
"github.com/erigontech/erigon-lib/common"
"github.com/erigontech/erigon-lib/common/hexutil"
"github.com/erigontech/erigon-lib/common/hexutility"
"github.com/erigontech/erigon-lib/common/math"
"github.com/erigontech/erigon-lib/crypto/cryptopool"
"github.com/erigontech/erigon-lib/kv"
"github.com/erigontech/erigon-lib/kv/rawdbv3"
"github.com/erigontech/erigon-lib/log/v3"
"github.com/erigontech/erigon/cl/clparams"
"github.com/erigontech/erigon/core"
"github.com/erigontech/erigon/core/rawdb"
"github.com/erigontech/erigon/core/state"
"github.com/erigontech/erigon/core/types"
"github.com/erigontech/erigon/core/vm"
"github.com/erigontech/erigon/polygon/bor/borcfg"
bortypes "github.com/erigontech/erigon/polygon/bor/types"
"github.com/erigontech/erigon/rpc"
"github.com/erigontech/erigon/turbo/adapter/ethapi"
"github.com/erigontech/erigon/turbo/rpchelper"
"github.com/erigontech/erigon/turbo/snapshotsync/freezeblocks"
"github.com/erigontech/erigon/turbo/transactions"
)
func (api *APIImpl) CallBundle(ctx context.Context, txHashes []common.Hash, stateBlockNumberOrHash rpc.BlockNumberOrHash, timeoutMilliSecondsPtr *int64) (map[string]interface{}, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
chainConfig, err := api.chainConfig(ctx, tx)
if err != nil {
return nil, err
}
engine := api.engine()
if len(txHashes) == 0 {
return nil, nil
}
var txs types.Transactions
for _, txHash := range txHashes {
blockNum, ok, err := api.txnLookup(ctx, tx, txHash)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
block, err := api.blockByNumberWithSenders(ctx, tx, blockNum)
if err != nil {
return nil, err
}
if block == nil {
return nil, nil
}
var txn types.Transaction
for _, transaction := range block.Transactions() {
if transaction.Hash() == txHash {
txn = transaction
break
}
}
if txn == nil {
return nil, nil // not error, see https://github.com/erigontech/erigon/issues/1645
}
txs = append(txs, txn)
}
defer func(start time.Time) { log.Trace("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
txNumsReader := rawdbv3.TxNums.WithCustomReadTxNumFunc(freezeblocks.ReadTxNumFuncFromBlockReader(ctx, api._blockReader))
stateBlockNumber, hash, latest, err := rpchelper.GetBlockNumber(ctx, stateBlockNumberOrHash, tx, api._blockReader, api.filters)
if err != nil {
return nil, err
}
var stateReader state.StateReader
if latest {
cacheView, err := api.stateCache.View(ctx, tx)
if err != nil {
return nil, err
}
stateReader = rpchelper.CreateLatestCachedStateReader(cacheView, tx)
} else {
stateReader, err = rpchelper.CreateHistoryStateReader(tx, txNumsReader, stateBlockNumber+1, 0, chainConfig.ChainName)
if err != nil {
return nil, err
}
}
ibs := state.New(stateReader)
parent, _ := api.headerByRPCNumber(ctx, rpc.BlockNumber(stateBlockNumber), tx)
if parent == nil {
return nil, fmt.Errorf("block %d(%x) not found", stateBlockNumber, hash)
}
blockNumber := stateBlockNumber + 1
timestamp := parent.Time + clparams.MainnetBeaconConfig.SecondsPerSlot
coinbase := parent.Coinbase
header := &types.Header{
ParentHash: parent.Hash(),
Number: new(big.Int).SetUint64(blockNumber),
GasLimit: parent.GasLimit,
Time: timestamp,
Difficulty: parent.Difficulty,
Coinbase: coinbase,
}
signer := types.MakeSigner(chainConfig, blockNumber, timestamp)
rules := chainConfig.Rules(blockNumber, timestamp)
firstMsg, err := txs[0].AsMessage(*signer, nil, rules)
if err != nil {
return nil, err
}
blockCtx := transactions.NewEVMBlockContext(engine, header, stateBlockNumberOrHash.RequireCanonical, tx, api._blockReader, chainConfig)
txCtx := core.NewEVMTxContext(firstMsg)
// Get a new instance of the EVM
evm := vm.NewEVM(blockCtx, txCtx, ibs, chainConfig, vm.Config{Debug: false})
timeoutMilliSeconds := int64(5000)
if timeoutMilliSecondsPtr != nil {
timeoutMilliSeconds = *timeoutMilliSecondsPtr
}
timeout := time.Millisecond * time.Duration(timeoutMilliSeconds)
// Setup context so it may be cancelled the call has completed
// or, in case of unmetered gas, setup a context with a timeout.
var cancel context.CancelFunc
if timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, timeout)
} else {
ctx, cancel = context.WithCancel(ctx)
}
// Make sure the context is cancelled when the call has completed
// this makes sure resources are cleaned up.
defer cancel()
// Wait for the context to be done and cancel the evm. Even if the
// EVM has finished, cancelling may be done (repeatedly)
go func() {
<-ctx.Done()
evm.Cancel()
}()
// Setup the gas pool (also for unmetered requests)
// and apply the message.
gp := new(core.GasPool).AddGas(math.MaxUint64).AddBlobGas(math.MaxUint64)
bundleHash := cryptopool.NewLegacyKeccak256()
defer cryptopool.ReturnToPoolKeccak256(bundleHash)
results := make([]map[string]interface{}, 0, len(txs))
for _, txn := range txs {
msg, err := txn.AsMessage(*signer, nil, rules)
msg.SetCheckNonce(false)
if err != nil {
return nil, err
}
// Execute the transaction message
result, err := core.ApplyMessage(evm, msg, gp, true /* refunds */, false /* gasBailout */)
if err != nil {
return nil, err
}
// If the timer caused an abort, return an appropriate error message
if evm.Cancelled() {
return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
}
txHash := txn.Hash().String()
jsonResult := map[string]interface{}{
"txHash": txHash,
"gasUsed": result.UsedGas,
}
bundleHash.Write(txn.Hash().Bytes())
if result.Err != nil {
jsonResult["error"] = result.Err.Error()
} else {
jsonResult["value"] = common.BytesToHash(result.Return())
}
results = append(results, jsonResult)
}
ret := map[string]interface{}{}
ret["results"] = results
ret["bundleHash"] = hexutility.Encode(bundleHash.Sum(nil))
return ret, nil
}
// GetBlockByNumber implements eth_getBlockByNumber. Returns information about a block given the block's number.
func (api *APIImpl) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
b, err := api.blockByNumber(ctx, number, tx)
if err != nil {
return nil, err
}
if b == nil {
return nil, nil
}
additionalFields := make(map[string]interface{})
// =============================
// TODO - remove this after https://github.com/ethereum/execution-apis/pull/570 is implemented by Hive and rest of the community
td, err := rawdb.ReadTd(tx, b.Hash(), b.NumberU64())
if err != nil {
return nil, err
}
if td != nil {
additionalFields["totalDifficulty"] = (*hexutil.Big)(td)
}
// =================================
chainConfig, err := api.chainConfig(ctx, tx)
if err != nil {
return nil, err
}
var borTx types.Transaction
var borTxHash common.Hash
if chainConfig.Bor != nil {
borTx = rawdb.ReadBorTransactionForBlock(tx, b.NumberU64())
if borTx != nil {
borTxHash = bortypes.ComputeBorTxHash(b.NumberU64(), b.Hash())
}
}
response, err := ethapi.RPCMarshalBlockEx(b, true, fullTx, borTx, borTxHash, additionalFields)
if err == nil && number == rpc.PendingBlockNumber {
// Pending blocks need to nil out a few fields
for _, field := range []string{"hash", "nonce", "miner"} {
response[field] = nil
}
}
return response, err
}
// GetBlockByHash implements eth_getBlockByHash. Returns information about a block given the block's hash.
func (api *APIImpl) GetBlockByHash(ctx context.Context, numberOrHash rpc.BlockNumberOrHash, fullTx bool) (map[string]interface{}, error) {
if numberOrHash.BlockHash == nil {
// some web3.js based apps (like ethstats client) for some reason call
// eth_getBlockByHash with a block number as a parameter
// so no matter how weird that is, we would love to support that.
if numberOrHash.BlockNumber == nil {
return nil, nil // not error, see https://github.com/erigontech/erigon/issues/1645
}
return api.GetBlockByNumber(ctx, *numberOrHash.BlockNumber, fullTx)
}
hash := *numberOrHash.BlockHash
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
additionalFields := make(map[string]interface{})
block, err := api.blockByHashWithSenders(ctx, tx, hash)
if err != nil {
return nil, err
}
if block == nil {
return nil, nil // not error, see https://github.com/erigontech/erigon/issues/1645
}
number := block.NumberU64()
// =============================
// TODO - remove this after https://github.com/ethereum/execution-apis/pull/570 is implemented by Hive and rest of the community
td, err := rawdb.ReadTd(tx, hash, number)
if err != nil {
return nil, err
}
if td != nil {
additionalFields["totalDifficulty"] = (*hexutil.Big)(td)
}
// ==============================
chainConfig, err := api.chainConfig(ctx, tx)
if err != nil {
return nil, err
}
var borTx types.Transaction
var borTxHash common.Hash
if chainConfig.Bor != nil {
borTx = rawdb.ReadBorTransactionForBlock(tx, number)
if borTx != nil {
borTxHash = bortypes.ComputeBorTxHash(number, block.Hash())
}
}
response, err := ethapi.RPCMarshalBlockEx(block, true, fullTx, borTx, borTxHash, additionalFields)
if chainConfig.Bor != nil {
borConfig := chainConfig.Bor.(*borcfg.BorConfig)
response["miner"], _ = ecrecover(block.Header(), borConfig)
}
if err == nil && int64(number) == rpc.PendingBlockNumber.Int64() {
// Pending blocks need to nil out a few fields
for _, field := range []string{"hash", "nonce", "miner"} {
response[field] = nil
}
}
return response, err
}
// GetBlockTransactionCountByNumber implements eth_getBlockTransactionCountByNumber. Returns the number of transactions in a block given the block's block number.
func (api *APIImpl) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*hexutil.Uint, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
if blockNr == rpc.PendingBlockNumber {
b, err := api.blockByRPCNumber(ctx, blockNr, tx)
if err != nil {
return nil, err
}
if b == nil {
return nil, nil
}
n := hexutil.Uint(len(b.Transactions()))
return &n, nil
}
blockNum, blockHash, _, err := rpchelper.GetBlockNumber(ctx, rpc.BlockNumberOrHashWithNumber(blockNr), tx, api._blockReader, api.filters)
if err != nil {
return nil, err
}
latestBlockNumber, err := rpchelper.GetLatestBlockNumber(tx)
if err != nil {
return nil, err
}
if blockNum > latestBlockNumber {
// (Compatibility) Every other node just returns `null` for when the block does not exist.
return nil, nil
}
body, txCount, err := api._blockReader.Body(ctx, tx, blockHash, blockNum)
if err != nil {
return nil, err
}
if body == nil {
return nil, nil
}
chainConfig, err := api.chainConfig(ctx, tx)
if err != nil {
return nil, err
}
if chainConfig.Bor != nil {
borStateSyncTxHash := bortypes.ComputeBorTxHash(blockNum, blockHash)
var ok bool
var err error
if api.useBridgeReader {
_, ok, err = api.bridgeReader.EventTxnLookup(ctx, borStateSyncTxHash)
} else {
_, ok, err = api._blockReader.EventLookup(ctx, tx, borStateSyncTxHash)
}
if err != nil {
return nil, err
}
if ok {
txCount++
}
}
numOfTx := hexutil.Uint(txCount)
return &numOfTx, nil
}
// GetBlockTransactionCountByHash implements eth_getBlockTransactionCountByHash. Returns the number of transactions in a block given the block's block hash.
func (api *APIImpl) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) (*hexutil.Uint, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
blockNum, _, _, err := rpchelper.GetBlockNumber(ctx, rpc.BlockNumberOrHash{BlockHash: &blockHash}, tx, api._blockReader, nil)
if err != nil {
// (Compatibility) Every other node just return `null` for when the block does not exist.
log.Debug("eth_getBlockTransactionCountByHash GetBlockNumber failed", "err", err)
return nil, nil
}
_, txCount, err := api._blockReader.Body(ctx, tx, blockHash, blockNum)
if err != nil {
return nil, err
}
chainConfig, err := api.chainConfig(ctx, tx)
if err != nil {
return nil, err
}
if chainConfig.Bor != nil {
borStateSyncTxHash := bortypes.ComputeBorTxHash(blockNum, blockHash)
var ok bool
var err error
if api.useBridgeReader {
_, ok, err = api.bridgeReader.EventTxnLookup(ctx, borStateSyncTxHash)
} else {
_, ok, err = api._blockReader.EventLookup(ctx, tx, borStateSyncTxHash)
}
if err != nil {
return nil, err
}
if ok {
txCount++
}
}
numOfTx := hexutil.Uint(txCount)
return &numOfTx, nil
}
func (api *APIImpl) blockByNumber(ctx context.Context, number rpc.BlockNumber, tx kv.Tx) (*types.Block, error) {
if number != rpc.PendingBlockNumber {
return api.blockByRPCNumber(ctx, number, tx)
}
if block := api.pendingBlock(); block != nil {
return block, nil
}
block, err := api.ethBackend.PendingBlock(ctx)
if err != nil {
return nil, err
}
if block != nil {
return block, nil
}
return api.blockByRPCNumber(ctx, number, tx)
}