github.com/ethereum/go-ethereum@v1.16.1/internal/ethapi/api.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package ethapi 18 19 import ( 20 "context" 21 "encoding/hex" 22 "errors" 23 "fmt" 24 gomath "math" 25 "math/big" 26 "strings" 27 "time" 28 29 "github.com/davecgh/go-spew/spew" 30 "github.com/ethereum/go-ethereum/accounts" 31 "github.com/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/common/hexutil" 33 "github.com/ethereum/go-ethereum/common/math" 34 "github.com/ethereum/go-ethereum/consensus" 35 "github.com/ethereum/go-ethereum/consensus/misc/eip1559" 36 "github.com/ethereum/go-ethereum/core" 37 "github.com/ethereum/go-ethereum/core/state" 38 "github.com/ethereum/go-ethereum/core/types" 39 "github.com/ethereum/go-ethereum/core/vm" 40 "github.com/ethereum/go-ethereum/crypto" 41 "github.com/ethereum/go-ethereum/eth/gasestimator" 42 "github.com/ethereum/go-ethereum/eth/tracers/logger" 43 "github.com/ethereum/go-ethereum/internal/ethapi/override" 44 "github.com/ethereum/go-ethereum/log" 45 "github.com/ethereum/go-ethereum/p2p" 46 "github.com/ethereum/go-ethereum/params" 47 "github.com/ethereum/go-ethereum/rlp" 48 "github.com/ethereum/go-ethereum/rpc" 49 "github.com/ethereum/go-ethereum/trie" 50 ) 51 52 // estimateGasErrorRatio is the amount of overestimation eth_estimateGas is 53 // allowed to produce in order to speed up calculations. 54 const estimateGasErrorRatio = 0.015 55 56 var errBlobTxNotSupported = errors.New("signing blob transactions not supported") 57 58 // EthereumAPI provides an API to access Ethereum related information. 59 type EthereumAPI struct { 60 b Backend 61 } 62 63 // NewEthereumAPI creates a new Ethereum protocol API. 64 func NewEthereumAPI(b Backend) *EthereumAPI { 65 return &EthereumAPI{b} 66 } 67 68 // GasPrice returns a suggestion for a gas price for legacy transactions. 69 func (api *EthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) { 70 tipcap, err := api.b.SuggestGasTipCap(ctx) 71 if err != nil { 72 return nil, err 73 } 74 if head := api.b.CurrentHeader(); head.BaseFee != nil { 75 tipcap.Add(tipcap, head.BaseFee) 76 } 77 return (*hexutil.Big)(tipcap), err 78 } 79 80 // MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee transactions. 81 func (api *EthereumAPI) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) { 82 tipcap, err := api.b.SuggestGasTipCap(ctx) 83 if err != nil { 84 return nil, err 85 } 86 return (*hexutil.Big)(tipcap), err 87 } 88 89 type feeHistoryResult struct { 90 OldestBlock *hexutil.Big `json:"oldestBlock"` 91 Reward [][]*hexutil.Big `json:"reward,omitempty"` 92 BaseFee []*hexutil.Big `json:"baseFeePerGas,omitempty"` 93 GasUsedRatio []float64 `json:"gasUsedRatio"` 94 BlobBaseFee []*hexutil.Big `json:"baseFeePerBlobGas,omitempty"` 95 BlobGasUsedRatio []float64 `json:"blobGasUsedRatio,omitempty"` 96 } 97 98 // FeeHistory returns the fee market history. 99 func (api *EthereumAPI) FeeHistory(ctx context.Context, blockCount math.HexOrDecimal64, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) { 100 oldest, reward, baseFee, gasUsed, blobBaseFee, blobGasUsed, err := api.b.FeeHistory(ctx, uint64(blockCount), lastBlock, rewardPercentiles) 101 if err != nil { 102 return nil, err 103 } 104 results := &feeHistoryResult{ 105 OldestBlock: (*hexutil.Big)(oldest), 106 GasUsedRatio: gasUsed, 107 } 108 if reward != nil { 109 results.Reward = make([][]*hexutil.Big, len(reward)) 110 for i, w := range reward { 111 results.Reward[i] = make([]*hexutil.Big, len(w)) 112 for j, v := range w { 113 results.Reward[i][j] = (*hexutil.Big)(v) 114 } 115 } 116 } 117 if baseFee != nil { 118 results.BaseFee = make([]*hexutil.Big, len(baseFee)) 119 for i, v := range baseFee { 120 results.BaseFee[i] = (*hexutil.Big)(v) 121 } 122 } 123 if blobBaseFee != nil { 124 results.BlobBaseFee = make([]*hexutil.Big, len(blobBaseFee)) 125 for i, v := range blobBaseFee { 126 results.BlobBaseFee[i] = (*hexutil.Big)(v) 127 } 128 } 129 if blobGasUsed != nil { 130 results.BlobGasUsedRatio = blobGasUsed 131 } 132 return results, nil 133 } 134 135 // BlobBaseFee returns the base fee for blob gas at the current head. 136 func (api *EthereumAPI) BlobBaseFee(ctx context.Context) *hexutil.Big { 137 return (*hexutil.Big)(api.b.BlobBaseFee(ctx)) 138 } 139 140 // Syncing returns false in case the node is currently not syncing with the network. It can be up-to-date or has not 141 // yet received the latest block headers from its peers. In case it is synchronizing: 142 // - startingBlock: block number this node started to synchronize from 143 // - currentBlock: block number this node is currently importing 144 // - highestBlock: block number of the highest block header this node has received from peers 145 // - pulledStates: number of state entries processed until now 146 // - knownStates: number of known state entries that still need to be pulled 147 func (api *EthereumAPI) Syncing(ctx context.Context) (interface{}, error) { 148 progress := api.b.SyncProgress(ctx) 149 150 // Return not syncing if the synchronisation already completed 151 if progress.Done() { 152 return false, nil 153 } 154 // Otherwise gather the block sync stats 155 return map[string]interface{}{ 156 "startingBlock": hexutil.Uint64(progress.StartingBlock), 157 "currentBlock": hexutil.Uint64(progress.CurrentBlock), 158 "highestBlock": hexutil.Uint64(progress.HighestBlock), 159 "syncedAccounts": hexutil.Uint64(progress.SyncedAccounts), 160 "syncedAccountBytes": hexutil.Uint64(progress.SyncedAccountBytes), 161 "syncedBytecodes": hexutil.Uint64(progress.SyncedBytecodes), 162 "syncedBytecodeBytes": hexutil.Uint64(progress.SyncedBytecodeBytes), 163 "syncedStorage": hexutil.Uint64(progress.SyncedStorage), 164 "syncedStorageBytes": hexutil.Uint64(progress.SyncedStorageBytes), 165 "healedTrienodes": hexutil.Uint64(progress.HealedTrienodes), 166 "healedTrienodeBytes": hexutil.Uint64(progress.HealedTrienodeBytes), 167 "healedBytecodes": hexutil.Uint64(progress.HealedBytecodes), 168 "healedBytecodeBytes": hexutil.Uint64(progress.HealedBytecodeBytes), 169 "healingTrienodes": hexutil.Uint64(progress.HealingTrienodes), 170 "healingBytecode": hexutil.Uint64(progress.HealingBytecode), 171 "txIndexFinishedBlocks": hexutil.Uint64(progress.TxIndexFinishedBlocks), 172 "txIndexRemainingBlocks": hexutil.Uint64(progress.TxIndexRemainingBlocks), 173 "stateIndexRemaining": hexutil.Uint64(progress.StateIndexRemaining), 174 }, nil 175 } 176 177 // TxPoolAPI offers and API for the transaction pool. It only operates on data that is non-confidential. 178 type TxPoolAPI struct { 179 b Backend 180 } 181 182 // NewTxPoolAPI creates a new tx pool service that gives information about the transaction pool. 183 func NewTxPoolAPI(b Backend) *TxPoolAPI { 184 return &TxPoolAPI{b} 185 } 186 187 // Content returns the transactions contained within the transaction pool. 188 func (api *TxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction { 189 pending, queue := api.b.TxPoolContent() 190 content := map[string]map[string]map[string]*RPCTransaction{ 191 "pending": make(map[string]map[string]*RPCTransaction, len(pending)), 192 "queued": make(map[string]map[string]*RPCTransaction, len(queue)), 193 } 194 curHeader := api.b.CurrentHeader() 195 // Flatten the pending transactions 196 for account, txs := range pending { 197 dump := make(map[string]*RPCTransaction, len(txs)) 198 for _, tx := range txs { 199 dump[fmt.Sprintf("%d", tx.Nonce())] = NewRPCPendingTransaction(tx, curHeader, api.b.ChainConfig()) 200 } 201 content["pending"][account.Hex()] = dump 202 } 203 // Flatten the queued transactions 204 for account, txs := range queue { 205 dump := make(map[string]*RPCTransaction, len(txs)) 206 for _, tx := range txs { 207 dump[fmt.Sprintf("%d", tx.Nonce())] = NewRPCPendingTransaction(tx, curHeader, api.b.ChainConfig()) 208 } 209 content["queued"][account.Hex()] = dump 210 } 211 return content 212 } 213 214 // ContentFrom returns the transactions contained within the transaction pool. 215 func (api *TxPoolAPI) ContentFrom(addr common.Address) map[string]map[string]*RPCTransaction { 216 content := make(map[string]map[string]*RPCTransaction, 2) 217 pending, queue := api.b.TxPoolContentFrom(addr) 218 curHeader := api.b.CurrentHeader() 219 220 // Build the pending transactions 221 dump := make(map[string]*RPCTransaction, len(pending)) 222 for _, tx := range pending { 223 dump[fmt.Sprintf("%d", tx.Nonce())] = NewRPCPendingTransaction(tx, curHeader, api.b.ChainConfig()) 224 } 225 content["pending"] = dump 226 227 // Build the queued transactions 228 dump = make(map[string]*RPCTransaction, len(queue)) 229 for _, tx := range queue { 230 dump[fmt.Sprintf("%d", tx.Nonce())] = NewRPCPendingTransaction(tx, curHeader, api.b.ChainConfig()) 231 } 232 content["queued"] = dump 233 234 return content 235 } 236 237 // Status returns the number of pending and queued transaction in the pool. 238 func (api *TxPoolAPI) Status() map[string]hexutil.Uint { 239 pending, queue := api.b.Stats() 240 return map[string]hexutil.Uint{ 241 "pending": hexutil.Uint(pending), 242 "queued": hexutil.Uint(queue), 243 } 244 } 245 246 // Inspect retrieves the content of the transaction pool and flattens it into an 247 // easily inspectable list. 248 func (api *TxPoolAPI) Inspect() map[string]map[string]map[string]string { 249 pending, queue := api.b.TxPoolContent() 250 content := map[string]map[string]map[string]string{ 251 "pending": make(map[string]map[string]string, len(pending)), 252 "queued": make(map[string]map[string]string, len(queue)), 253 } 254 255 // Define a formatter to flatten a transaction into a string 256 format := func(tx *types.Transaction) string { 257 if to := tx.To(); to != nil { 258 return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice()) 259 } 260 return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice()) 261 } 262 // Flatten the pending transactions 263 for account, txs := range pending { 264 dump := make(map[string]string, len(txs)) 265 for _, tx := range txs { 266 dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx) 267 } 268 content["pending"][account.Hex()] = dump 269 } 270 // Flatten the queued transactions 271 for account, txs := range queue { 272 dump := make(map[string]string, len(txs)) 273 for _, tx := range txs { 274 dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx) 275 } 276 content["queued"][account.Hex()] = dump 277 } 278 return content 279 } 280 281 // EthereumAccountAPI provides an API to access accounts managed by this node. 282 // It offers only methods that can retrieve accounts. 283 type EthereumAccountAPI struct { 284 am *accounts.Manager 285 } 286 287 // NewEthereumAccountAPI creates a new EthereumAccountAPI. 288 func NewEthereumAccountAPI(am *accounts.Manager) *EthereumAccountAPI { 289 return &EthereumAccountAPI{am: am} 290 } 291 292 // Accounts returns the collection of accounts this node manages. 293 func (api *EthereumAccountAPI) Accounts() []common.Address { 294 return api.am.Accounts() 295 } 296 297 // BlockChainAPI provides an API to access Ethereum blockchain data. 298 type BlockChainAPI struct { 299 b Backend 300 } 301 302 // NewBlockChainAPI creates a new Ethereum blockchain API. 303 func NewBlockChainAPI(b Backend) *BlockChainAPI { 304 return &BlockChainAPI{b} 305 } 306 307 // ChainId is the EIP-155 replay-protection chain id for the current Ethereum chain config. 308 // 309 // Note, this method does not conform to EIP-695 because the configured chain ID is always 310 // returned, regardless of the current head block. We used to return an error when the chain 311 // wasn't synced up to a block where EIP-155 is enabled, but this behavior caused issues 312 // in CL clients. 313 func (api *BlockChainAPI) ChainId() *hexutil.Big { 314 return (*hexutil.Big)(api.b.ChainConfig().ChainID) 315 } 316 317 // BlockNumber returns the block number of the chain head. 318 func (api *BlockChainAPI) BlockNumber() hexutil.Uint64 { 319 header, _ := api.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available 320 return hexutil.Uint64(header.Number.Uint64()) 321 } 322 323 // GetBalance returns the amount of wei for the given address in the state of the 324 // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta 325 // block numbers are also allowed. 326 func (api *BlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) { 327 state, _, err := api.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 328 if state == nil || err != nil { 329 return nil, err 330 } 331 b := state.GetBalance(address).ToBig() 332 return (*hexutil.Big)(b), state.Error() 333 } 334 335 // AccountResult structs for GetProof 336 type AccountResult struct { 337 Address common.Address `json:"address"` 338 AccountProof []string `json:"accountProof"` 339 Balance *hexutil.Big `json:"balance"` 340 CodeHash common.Hash `json:"codeHash"` 341 Nonce hexutil.Uint64 `json:"nonce"` 342 StorageHash common.Hash `json:"storageHash"` 343 StorageProof []StorageResult `json:"storageProof"` 344 } 345 346 type StorageResult struct { 347 Key string `json:"key"` 348 Value *hexutil.Big `json:"value"` 349 Proof []string `json:"proof"` 350 } 351 352 // proofList implements ethdb.KeyValueWriter and collects the proofs as 353 // hex-strings for delivery to rpc-caller. 354 type proofList []string 355 356 func (n *proofList) Put(key []byte, value []byte) error { 357 *n = append(*n, hexutil.Encode(value)) 358 return nil 359 } 360 361 func (n *proofList) Delete(key []byte) error { 362 panic("not supported") 363 } 364 365 // GetProof returns the Merkle-proof for a given account and optionally some storage keys. 366 func (api *BlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) { 367 var ( 368 keys = make([]common.Hash, len(storageKeys)) 369 keyLengths = make([]int, len(storageKeys)) 370 storageProof = make([]StorageResult, len(storageKeys)) 371 ) 372 // Deserialize all keys. This prevents state access on invalid input. 373 for i, hexKey := range storageKeys { 374 var err error 375 keys[i], keyLengths[i], err = decodeHash(hexKey) 376 if err != nil { 377 return nil, err 378 } 379 } 380 statedb, header, err := api.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 381 if statedb == nil || err != nil { 382 return nil, err 383 } 384 codeHash := statedb.GetCodeHash(address) 385 storageRoot := statedb.GetStorageRoot(address) 386 387 if len(keys) > 0 { 388 var storageTrie state.Trie 389 if storageRoot != types.EmptyRootHash && storageRoot != (common.Hash{}) { 390 id := trie.StorageTrieID(header.Root, crypto.Keccak256Hash(address.Bytes()), storageRoot) 391 st, err := trie.NewStateTrie(id, statedb.Database().TrieDB()) 392 if err != nil { 393 return nil, err 394 } 395 storageTrie = st 396 } 397 // Create the proofs for the storageKeys. 398 for i, key := range keys { 399 // Output key encoding is a bit special: if the input was a 32-byte hash, it is 400 // returned as such. Otherwise, we apply the QUANTITY encoding mandated by the 401 // JSON-RPC spec for getProof. This behavior exists to preserve backwards 402 // compatibility with older client versions. 403 var outputKey string 404 if keyLengths[i] != 32 { 405 outputKey = hexutil.EncodeBig(key.Big()) 406 } else { 407 outputKey = hexutil.Encode(key[:]) 408 } 409 if storageTrie == nil { 410 storageProof[i] = StorageResult{outputKey, &hexutil.Big{}, []string{}} 411 continue 412 } 413 var proof proofList 414 if err := storageTrie.Prove(crypto.Keccak256(key.Bytes()), &proof); err != nil { 415 return nil, err 416 } 417 value := (*hexutil.Big)(statedb.GetState(address, key).Big()) 418 storageProof[i] = StorageResult{outputKey, value, proof} 419 } 420 } 421 // Create the accountProof. 422 tr, err := trie.NewStateTrie(trie.StateTrieID(header.Root), statedb.Database().TrieDB()) 423 if err != nil { 424 return nil, err 425 } 426 var accountProof proofList 427 if err := tr.Prove(crypto.Keccak256(address.Bytes()), &accountProof); err != nil { 428 return nil, err 429 } 430 balance := statedb.GetBalance(address).ToBig() 431 return &AccountResult{ 432 Address: address, 433 AccountProof: accountProof, 434 Balance: (*hexutil.Big)(balance), 435 CodeHash: codeHash, 436 Nonce: hexutil.Uint64(statedb.GetNonce(address)), 437 StorageHash: storageRoot, 438 StorageProof: storageProof, 439 }, statedb.Error() 440 } 441 442 // decodeHash parses a hex-encoded 32-byte hash. The input may optionally 443 // be prefixed by 0x and can have a byte length up to 32. 444 func decodeHash(s string) (h common.Hash, inputLength int, err error) { 445 if strings.HasPrefix(s, "0x") || strings.HasPrefix(s, "0X") { 446 s = s[2:] 447 } 448 if (len(s) & 1) > 0 { 449 s = "0" + s 450 } 451 b, err := hex.DecodeString(s) 452 if err != nil { 453 return common.Hash{}, 0, errors.New("hex string invalid") 454 } 455 if len(b) > 32 { 456 return common.Hash{}, len(b), errors.New("hex string too long, want at most 32 bytes") 457 } 458 return common.BytesToHash(b), len(b), nil 459 } 460 461 // GetHeaderByNumber returns the requested canonical block header. 462 // - When blockNr is -1 the chain pending header is returned. 463 // - When blockNr is -2 the chain latest header is returned. 464 // - When blockNr is -3 the chain finalized header is returned. 465 // - When blockNr is -4 the chain safe header is returned. 466 func (api *BlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) { 467 header, err := api.b.HeaderByNumber(ctx, number) 468 if header != nil && err == nil { 469 response := RPCMarshalHeader(header) 470 if number == rpc.PendingBlockNumber { 471 // Pending header need to nil out a few fields 472 for _, field := range []string{"hash", "nonce", "miner"} { 473 response[field] = nil 474 } 475 } 476 return response, err 477 } 478 return nil, err 479 } 480 481 // GetHeaderByHash returns the requested header by hash. 482 func (api *BlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} { 483 header, _ := api.b.HeaderByHash(ctx, hash) 484 if header != nil { 485 return RPCMarshalHeader(header) 486 } 487 return nil 488 } 489 490 // GetBlockByNumber returns the requested canonical block. 491 // - When blockNr is -1 the chain pending block is returned. 492 // - When blockNr is -2 the chain latest block is returned. 493 // - When blockNr is -3 the chain finalized block is returned. 494 // - When blockNr is -4 the chain safe block is returned. 495 // - When fullTx is true all transactions in the block are returned, otherwise 496 // only the transaction hash is returned. 497 func (api *BlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { 498 block, err := api.b.BlockByNumber(ctx, number) 499 if block != nil && err == nil { 500 response := RPCMarshalBlock(block, true, fullTx, api.b.ChainConfig()) 501 if number == rpc.PendingBlockNumber { 502 // Pending blocks need to nil out a few fields 503 for _, field := range []string{"hash", "nonce", "miner"} { 504 response[field] = nil 505 } 506 } 507 return response, nil 508 } 509 return nil, err 510 } 511 512 // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full 513 // detail, otherwise only the transaction hash is returned. 514 func (api *BlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) { 515 block, err := api.b.BlockByHash(ctx, hash) 516 if block != nil { 517 return RPCMarshalBlock(block, true, fullTx, api.b.ChainConfig()), nil 518 } 519 return nil, err 520 } 521 522 // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. 523 func (api *BlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) { 524 block, err := api.b.BlockByNumber(ctx, blockNr) 525 if block != nil { 526 uncles := block.Uncles() 527 if index >= hexutil.Uint(len(uncles)) { 528 log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index) 529 return nil, nil 530 } 531 block = types.NewBlockWithHeader(uncles[index]) 532 return RPCMarshalBlock(block, false, false, api.b.ChainConfig()), nil 533 } 534 return nil, err 535 } 536 537 // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. 538 func (api *BlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) { 539 block, err := api.b.BlockByHash(ctx, blockHash) 540 if block != nil { 541 uncles := block.Uncles() 542 if index >= hexutil.Uint(len(uncles)) { 543 log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index) 544 return nil, nil 545 } 546 block = types.NewBlockWithHeader(uncles[index]) 547 return RPCMarshalBlock(block, false, false, api.b.ChainConfig()), nil 548 } 549 return nil, err 550 } 551 552 // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number 553 func (api *BlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) (*hexutil.Uint, error) { 554 block, err := api.b.BlockByNumber(ctx, blockNr) 555 if block != nil { 556 n := hexutil.Uint(len(block.Uncles())) 557 return &n, nil 558 } 559 return nil, err 560 } 561 562 // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash 563 func (api *BlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) (*hexutil.Uint, error) { 564 block, err := api.b.BlockByHash(ctx, blockHash) 565 if block != nil { 566 n := hexutil.Uint(len(block.Uncles())) 567 return &n, nil 568 } 569 return nil, err 570 } 571 572 // GetCode returns the code stored at the given address in the state for the given block number. 573 func (api *BlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { 574 state, _, err := api.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 575 if state == nil || err != nil { 576 return nil, err 577 } 578 code := state.GetCode(address) 579 return code, state.Error() 580 } 581 582 // GetStorageAt returns the storage from the state at the given address, key and 583 // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block 584 // numbers are also allowed. 585 func (api *BlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, hexKey string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { 586 state, _, err := api.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 587 if state == nil || err != nil { 588 return nil, err 589 } 590 key, _, err := decodeHash(hexKey) 591 if err != nil { 592 return nil, fmt.Errorf("unable to decode storage key: %s", err) 593 } 594 res := state.GetState(address, key) 595 return res[:], state.Error() 596 } 597 598 // GetBlockReceipts returns the block receipts for the given block hash or number or tag. 599 func (api *BlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]map[string]interface{}, error) { 600 block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash) 601 if block == nil || err != nil { 602 return nil, err 603 } 604 receipts, err := api.b.GetReceipts(ctx, block.Hash()) 605 if err != nil { 606 return nil, err 607 } 608 txs := block.Transactions() 609 if len(txs) != len(receipts) { 610 return nil, fmt.Errorf("receipts length mismatch: %d vs %d", len(txs), len(receipts)) 611 } 612 613 // Derive the sender. 614 signer := types.MakeSigner(api.b.ChainConfig(), block.Number(), block.Time()) 615 616 result := make([]map[string]interface{}, len(receipts)) 617 for i, receipt := range receipts { 618 result[i] = marshalReceipt(receipt, block.Hash(), block.NumberU64(), signer, txs[i], i) 619 } 620 621 return result, nil 622 } 623 624 // ChainContextBackend provides methods required to implement ChainContext. 625 type ChainContextBackend interface { 626 Engine() consensus.Engine 627 HeaderByNumber(context.Context, rpc.BlockNumber) (*types.Header, error) 628 ChainConfig() *params.ChainConfig 629 } 630 631 // ChainContext is an implementation of core.ChainContext. It's main use-case 632 // is instantiating a vm.BlockContext without having access to the BlockChain object. 633 type ChainContext struct { 634 b ChainContextBackend 635 ctx context.Context 636 } 637 638 // NewChainContext creates a new ChainContext object. 639 func NewChainContext(ctx context.Context, backend ChainContextBackend) *ChainContext { 640 return &ChainContext{ctx: ctx, b: backend} 641 } 642 643 func (context *ChainContext) Engine() consensus.Engine { 644 return context.b.Engine() 645 } 646 647 func (context *ChainContext) GetHeader(hash common.Hash, number uint64) *types.Header { 648 // This method is called to get the hash for a block number when executing the BLOCKHASH 649 // opcode. Hence no need to search for non-canonical blocks. 650 header, err := context.b.HeaderByNumber(context.ctx, rpc.BlockNumber(number)) 651 if err != nil || header.Hash() != hash { 652 return nil 653 } 654 return header 655 } 656 657 func (context *ChainContext) Config() *params.ChainConfig { 658 return context.b.ChainConfig() 659 } 660 661 func doCall(ctx context.Context, b Backend, args TransactionArgs, state *state.StateDB, header *types.Header, overrides *override.StateOverride, blockOverrides *override.BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) { 662 blockCtx := core.NewEVMBlockContext(header, NewChainContext(ctx, b), nil) 663 if blockOverrides != nil { 664 if err := blockOverrides.Apply(&blockCtx); err != nil { 665 return nil, err 666 } 667 } 668 rules := b.ChainConfig().Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time) 669 precompiles := vm.ActivePrecompiledContracts(rules) 670 if err := overrides.Apply(state, precompiles); err != nil { 671 return nil, err 672 } 673 674 // Setup context so it may be cancelled the call has completed 675 // or, in case of unmetered gas, setup a context with a timeout. 676 var cancel context.CancelFunc 677 if timeout > 0 { 678 ctx, cancel = context.WithTimeout(ctx, timeout) 679 } else { 680 ctx, cancel = context.WithCancel(ctx) 681 } 682 // Make sure the context is cancelled when the call has completed 683 // this makes sure resources are cleaned up. 684 defer cancel() 685 gp := new(core.GasPool) 686 if globalGasCap == 0 { 687 gp.AddGas(gomath.MaxUint64) 688 } else { 689 gp.AddGas(globalGasCap) 690 } 691 return applyMessage(ctx, b, args, state, header, timeout, gp, &blockCtx, &vm.Config{NoBaseFee: true}, precompiles, true) 692 } 693 694 func applyMessage(ctx context.Context, b Backend, args TransactionArgs, state *state.StateDB, header *types.Header, timeout time.Duration, gp *core.GasPool, blockContext *vm.BlockContext, vmConfig *vm.Config, precompiles vm.PrecompiledContracts, skipChecks bool) (*core.ExecutionResult, error) { 695 // Get a new instance of the EVM. 696 if err := args.CallDefaults(gp.Gas(), blockContext.BaseFee, b.ChainConfig().ChainID); err != nil { 697 return nil, err 698 } 699 msg := args.ToMessage(header.BaseFee, skipChecks, skipChecks) 700 // Lower the basefee to 0 to avoid breaking EVM 701 // invariants (basefee < feecap). 702 if msg.GasPrice.Sign() == 0 { 703 blockContext.BaseFee = new(big.Int) 704 } 705 if msg.BlobGasFeeCap != nil && msg.BlobGasFeeCap.BitLen() == 0 { 706 blockContext.BlobBaseFee = new(big.Int) 707 } 708 evm := b.GetEVM(ctx, state, header, vmConfig, blockContext) 709 if precompiles != nil { 710 evm.SetPrecompiles(precompiles) 711 } 712 res, err := applyMessageWithEVM(ctx, evm, msg, timeout, gp) 713 // If an internal state error occurred, let that have precedence. Otherwise, 714 // a "trie root missing" type of error will masquerade as e.g. "insufficient gas" 715 if err := state.Error(); err != nil { 716 return nil, err 717 } 718 return res, err 719 } 720 721 func applyMessageWithEVM(ctx context.Context, evm *vm.EVM, msg *core.Message, timeout time.Duration, gp *core.GasPool) (*core.ExecutionResult, error) { 722 // Wait for the context to be done and cancel the evm. Even if the 723 // EVM has finished, cancelling may be done (repeatedly) 724 go func() { 725 <-ctx.Done() 726 evm.Cancel() 727 }() 728 729 // Execute the message. 730 result, err := core.ApplyMessage(evm, msg, gp) 731 732 // If the timer caused an abort, return an appropriate error message 733 if evm.Cancelled() { 734 return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout) 735 } 736 if err != nil { 737 return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.GasLimit) 738 } 739 return result, nil 740 } 741 742 func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *override.StateOverride, blockOverrides *override.BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) { 743 defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now()) 744 745 state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 746 if state == nil || err != nil { 747 return nil, err 748 } 749 return doCall(ctx, b, args, state, header, overrides, blockOverrides, timeout, globalGasCap) 750 } 751 752 // Call executes the given transaction on the state for the given block number. 753 // 754 // Additionally, the caller can specify a batch of contract for fields overriding. 755 // 756 // Note, this function doesn't make and changes in the state/blockchain and is 757 // useful to execute and retrieve values. 758 func (api *BlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *override.StateOverride, blockOverrides *override.BlockOverrides) (hexutil.Bytes, error) { 759 if blockNrOrHash == nil { 760 latest := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) 761 blockNrOrHash = &latest 762 } 763 result, err := DoCall(ctx, api.b, args, *blockNrOrHash, overrides, blockOverrides, api.b.RPCEVMTimeout(), api.b.RPCGasCap()) 764 if err != nil { 765 return nil, err 766 } 767 if errors.Is(result.Err, vm.ErrExecutionReverted) { 768 return nil, newRevertError(result.Revert()) 769 } 770 return result.Return(), result.Err 771 } 772 773 // SimulateV1 executes series of transactions on top of a base state. 774 // The transactions are packed into blocks. For each block, block header 775 // fields can be overridden. The state can also be overridden prior to 776 // execution of each block. 777 // 778 // Note, this function doesn't make any changes in the state/blockchain and is 779 // useful to execute and retrieve values. 780 func (api *BlockChainAPI) SimulateV1(ctx context.Context, opts simOpts, blockNrOrHash *rpc.BlockNumberOrHash) ([]*simBlockResult, error) { 781 if len(opts.BlockStateCalls) == 0 { 782 return nil, &invalidParamsError{message: "empty input"} 783 } else if len(opts.BlockStateCalls) > maxSimulateBlocks { 784 return nil, &clientLimitExceededError{message: "too many blocks"} 785 } 786 if blockNrOrHash == nil { 787 n := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) 788 blockNrOrHash = &n 789 } 790 state, base, err := api.b.StateAndHeaderByNumberOrHash(ctx, *blockNrOrHash) 791 if state == nil || err != nil { 792 return nil, err 793 } 794 gasCap := api.b.RPCGasCap() 795 if gasCap == 0 { 796 gasCap = gomath.MaxUint64 797 } 798 sim := &simulator{ 799 b: api.b, 800 state: state, 801 base: base, 802 chainConfig: api.b.ChainConfig(), 803 // Each tx and all the series of txes shouldn't consume more gas than cap 804 gp: new(core.GasPool).AddGas(gasCap), 805 traceTransfers: opts.TraceTransfers, 806 validate: opts.Validation, 807 fullTx: opts.ReturnFullTransactions, 808 } 809 return sim.execute(ctx, opts.BlockStateCalls) 810 } 811 812 // DoEstimateGas returns the lowest possible gas limit that allows the transaction to run 813 // successfully at block `blockNrOrHash`. It returns error if the transaction would revert, or if 814 // there are unexpected failures. The gas limit is capped by both `args.Gas` (if non-nil & 815 // non-zero) and `gasCap` (if non-zero). 816 func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *override.StateOverride, blockOverrides *override.BlockOverrides, gasCap uint64) (hexutil.Uint64, error) { 817 // Retrieve the base state and mutate it with any overrides 818 state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 819 if state == nil || err != nil { 820 return 0, err 821 } 822 if err := overrides.Apply(state, nil); err != nil { 823 return 0, err 824 } 825 // Construct the gas estimator option from the user input 826 opts := &gasestimator.Options{ 827 Config: b.ChainConfig(), 828 Chain: NewChainContext(ctx, b), 829 Header: header, 830 BlockOverrides: blockOverrides, 831 State: state, 832 ErrorRatio: estimateGasErrorRatio, 833 } 834 // Set any required transaction default, but make sure the gas cap itself is not messed with 835 // if it was not specified in the original argument list. 836 if args.Gas == nil { 837 args.Gas = new(hexutil.Uint64) 838 } 839 if err := args.CallDefaults(gasCap, header.BaseFee, b.ChainConfig().ChainID); err != nil { 840 return 0, err 841 } 842 call := args.ToMessage(header.BaseFee, true, true) 843 844 // Run the gas estimation and wrap any revertals into a custom return 845 estimate, revert, err := gasestimator.Estimate(ctx, call, opts, gasCap) 846 if err != nil { 847 if errors.Is(err, vm.ErrExecutionReverted) { 848 return 0, newRevertError(revert) 849 } 850 return 0, err 851 } 852 return hexutil.Uint64(estimate), nil 853 } 854 855 // EstimateGas returns the lowest possible gas limit that allows the transaction to run 856 // successfully at block `blockNrOrHash`, or the latest block if `blockNrOrHash` is unspecified. It 857 // returns error if the transaction would revert or if there are unexpected failures. The returned 858 // value is capped by both `args.Gas` (if non-nil & non-zero) and the backend's RPCGasCap 859 // configuration (if non-zero). 860 // Note: Required blob gas is not computed in this method. 861 func (api *BlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *override.StateOverride, blockOverrides *override.BlockOverrides) (hexutil.Uint64, error) { 862 bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) 863 if blockNrOrHash != nil { 864 bNrOrHash = *blockNrOrHash 865 } 866 return DoEstimateGas(ctx, api.b, args, bNrOrHash, overrides, blockOverrides, api.b.RPCGasCap()) 867 } 868 869 // RPCMarshalHeader converts the given header to the RPC output . 870 func RPCMarshalHeader(head *types.Header) map[string]interface{} { 871 result := map[string]interface{}{ 872 "number": (*hexutil.Big)(head.Number), 873 "hash": head.Hash(), 874 "parentHash": head.ParentHash, 875 "nonce": head.Nonce, 876 "mixHash": head.MixDigest, 877 "sha3Uncles": head.UncleHash, 878 "logsBloom": head.Bloom, 879 "stateRoot": head.Root, 880 "miner": head.Coinbase, 881 "difficulty": (*hexutil.Big)(head.Difficulty), 882 "extraData": hexutil.Bytes(head.Extra), 883 "gasLimit": hexutil.Uint64(head.GasLimit), 884 "gasUsed": hexutil.Uint64(head.GasUsed), 885 "timestamp": hexutil.Uint64(head.Time), 886 "transactionsRoot": head.TxHash, 887 "receiptsRoot": head.ReceiptHash, 888 } 889 if head.BaseFee != nil { 890 result["baseFeePerGas"] = (*hexutil.Big)(head.BaseFee) 891 } 892 if head.WithdrawalsHash != nil { 893 result["withdrawalsRoot"] = head.WithdrawalsHash 894 } 895 if head.BlobGasUsed != nil { 896 result["blobGasUsed"] = hexutil.Uint64(*head.BlobGasUsed) 897 } 898 if head.ExcessBlobGas != nil { 899 result["excessBlobGas"] = hexutil.Uint64(*head.ExcessBlobGas) 900 } 901 if head.ParentBeaconRoot != nil { 902 result["parentBeaconBlockRoot"] = head.ParentBeaconRoot 903 } 904 if head.RequestsHash != nil { 905 result["requestsHash"] = head.RequestsHash 906 } 907 return result 908 } 909 910 // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are 911 // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain 912 // transaction hashes. 913 func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *params.ChainConfig) map[string]interface{} { 914 fields := RPCMarshalHeader(block.Header()) 915 fields["size"] = hexutil.Uint64(block.Size()) 916 917 if inclTx { 918 formatTx := func(idx int, tx *types.Transaction) interface{} { 919 return tx.Hash() 920 } 921 if fullTx { 922 formatTx = func(idx int, tx *types.Transaction) interface{} { 923 return newRPCTransactionFromBlockIndex(block, uint64(idx), config) 924 } 925 } 926 txs := block.Transactions() 927 transactions := make([]interface{}, len(txs)) 928 for i, tx := range txs { 929 transactions[i] = formatTx(i, tx) 930 } 931 fields["transactions"] = transactions 932 } 933 uncles := block.Uncles() 934 uncleHashes := make([]common.Hash, len(uncles)) 935 for i, uncle := range uncles { 936 uncleHashes[i] = uncle.Hash() 937 } 938 fields["uncles"] = uncleHashes 939 if block.Withdrawals() != nil { 940 fields["withdrawals"] = block.Withdrawals() 941 } 942 return fields 943 } 944 945 // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction 946 type RPCTransaction struct { 947 BlockHash *common.Hash `json:"blockHash"` 948 BlockNumber *hexutil.Big `json:"blockNumber"` 949 From common.Address `json:"from"` 950 Gas hexutil.Uint64 `json:"gas"` 951 GasPrice *hexutil.Big `json:"gasPrice"` 952 GasFeeCap *hexutil.Big `json:"maxFeePerGas,omitempty"` 953 GasTipCap *hexutil.Big `json:"maxPriorityFeePerGas,omitempty"` 954 MaxFeePerBlobGas *hexutil.Big `json:"maxFeePerBlobGas,omitempty"` 955 Hash common.Hash `json:"hash"` 956 Input hexutil.Bytes `json:"input"` 957 Nonce hexutil.Uint64 `json:"nonce"` 958 To *common.Address `json:"to"` 959 TransactionIndex *hexutil.Uint64 `json:"transactionIndex"` 960 Value *hexutil.Big `json:"value"` 961 Type hexutil.Uint64 `json:"type"` 962 Accesses *types.AccessList `json:"accessList,omitempty"` 963 ChainID *hexutil.Big `json:"chainId,omitempty"` 964 BlobVersionedHashes []common.Hash `json:"blobVersionedHashes,omitempty"` 965 AuthorizationList []types.SetCodeAuthorization `json:"authorizationList,omitempty"` 966 V *hexutil.Big `json:"v"` 967 R *hexutil.Big `json:"r"` 968 S *hexutil.Big `json:"s"` 969 YParity *hexutil.Uint64 `json:"yParity,omitempty"` 970 } 971 972 // newRPCTransaction returns a transaction that will serialize to the RPC 973 // representation, with the given location metadata set (if available). 974 func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, blockTime uint64, index uint64, baseFee *big.Int, config *params.ChainConfig) *RPCTransaction { 975 signer := types.MakeSigner(config, new(big.Int).SetUint64(blockNumber), blockTime) 976 from, _ := types.Sender(signer, tx) 977 v, r, s := tx.RawSignatureValues() 978 result := &RPCTransaction{ 979 Type: hexutil.Uint64(tx.Type()), 980 From: from, 981 Gas: hexutil.Uint64(tx.Gas()), 982 GasPrice: (*hexutil.Big)(tx.GasPrice()), 983 Hash: tx.Hash(), 984 Input: hexutil.Bytes(tx.Data()), 985 Nonce: hexutil.Uint64(tx.Nonce()), 986 To: tx.To(), 987 Value: (*hexutil.Big)(tx.Value()), 988 V: (*hexutil.Big)(v), 989 R: (*hexutil.Big)(r), 990 S: (*hexutil.Big)(s), 991 } 992 if blockHash != (common.Hash{}) { 993 result.BlockHash = &blockHash 994 result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber)) 995 result.TransactionIndex = (*hexutil.Uint64)(&index) 996 } 997 998 switch tx.Type() { 999 case types.LegacyTxType: 1000 // if a legacy transaction has an EIP-155 chain id, include it explicitly 1001 if id := tx.ChainId(); id.Sign() != 0 { 1002 result.ChainID = (*hexutil.Big)(id) 1003 } 1004 1005 case types.AccessListTxType: 1006 al := tx.AccessList() 1007 yparity := hexutil.Uint64(v.Sign()) 1008 result.Accesses = &al 1009 result.ChainID = (*hexutil.Big)(tx.ChainId()) 1010 result.YParity = &yparity 1011 1012 case types.DynamicFeeTxType: 1013 al := tx.AccessList() 1014 yparity := hexutil.Uint64(v.Sign()) 1015 result.Accesses = &al 1016 result.ChainID = (*hexutil.Big)(tx.ChainId()) 1017 result.YParity = &yparity 1018 result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap()) 1019 result.GasTipCap = (*hexutil.Big)(tx.GasTipCap()) 1020 // if the transaction has been mined, compute the effective gas price 1021 if baseFee != nil && blockHash != (common.Hash{}) { 1022 // price = min(gasTipCap + baseFee, gasFeeCap) 1023 result.GasPrice = (*hexutil.Big)(effectiveGasPrice(tx, baseFee)) 1024 } else { 1025 result.GasPrice = (*hexutil.Big)(tx.GasFeeCap()) 1026 } 1027 1028 case types.BlobTxType: 1029 al := tx.AccessList() 1030 yparity := hexutil.Uint64(v.Sign()) 1031 result.Accesses = &al 1032 result.ChainID = (*hexutil.Big)(tx.ChainId()) 1033 result.YParity = &yparity 1034 result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap()) 1035 result.GasTipCap = (*hexutil.Big)(tx.GasTipCap()) 1036 // if the transaction has been mined, compute the effective gas price 1037 if baseFee != nil && blockHash != (common.Hash{}) { 1038 result.GasPrice = (*hexutil.Big)(effectiveGasPrice(tx, baseFee)) 1039 } else { 1040 result.GasPrice = (*hexutil.Big)(tx.GasFeeCap()) 1041 } 1042 result.MaxFeePerBlobGas = (*hexutil.Big)(tx.BlobGasFeeCap()) 1043 result.BlobVersionedHashes = tx.BlobHashes() 1044 1045 case types.SetCodeTxType: 1046 al := tx.AccessList() 1047 yparity := hexutil.Uint64(v.Sign()) 1048 result.Accesses = &al 1049 result.ChainID = (*hexutil.Big)(tx.ChainId()) 1050 result.YParity = &yparity 1051 result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap()) 1052 result.GasTipCap = (*hexutil.Big)(tx.GasTipCap()) 1053 // if the transaction has been mined, compute the effective gas price 1054 if baseFee != nil && blockHash != (common.Hash{}) { 1055 result.GasPrice = (*hexutil.Big)(effectiveGasPrice(tx, baseFee)) 1056 } else { 1057 result.GasPrice = (*hexutil.Big)(tx.GasFeeCap()) 1058 } 1059 result.AuthorizationList = tx.SetCodeAuthorizations() 1060 } 1061 return result 1062 } 1063 1064 // effectiveGasPrice computes the transaction gas fee, based on the given basefee value. 1065 // 1066 // price = min(gasTipCap + baseFee, gasFeeCap) 1067 func effectiveGasPrice(tx *types.Transaction, baseFee *big.Int) *big.Int { 1068 fee := tx.GasTipCap() 1069 fee = fee.Add(fee, baseFee) 1070 if tx.GasFeeCapIntCmp(fee) < 0 { 1071 return tx.GasFeeCap() 1072 } 1073 return fee 1074 } 1075 1076 // NewRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation 1077 func NewRPCPendingTransaction(tx *types.Transaction, current *types.Header, config *params.ChainConfig) *RPCTransaction { 1078 var ( 1079 baseFee *big.Int 1080 blockNumber = uint64(0) 1081 blockTime = uint64(0) 1082 ) 1083 if current != nil { 1084 baseFee = eip1559.CalcBaseFee(config, current) 1085 blockNumber = current.Number.Uint64() 1086 blockTime = current.Time 1087 } 1088 return newRPCTransaction(tx, common.Hash{}, blockNumber, blockTime, 0, baseFee, config) 1089 } 1090 1091 // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation. 1092 func newRPCTransactionFromBlockIndex(b *types.Block, index uint64, config *params.ChainConfig) *RPCTransaction { 1093 txs := b.Transactions() 1094 if index >= uint64(len(txs)) { 1095 return nil 1096 } 1097 return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), b.Time(), index, b.BaseFee(), config) 1098 } 1099 1100 // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index. 1101 func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes { 1102 txs := b.Transactions() 1103 if index >= uint64(len(txs)) { 1104 return nil 1105 } 1106 blob, _ := txs[index].MarshalBinary() 1107 return blob 1108 } 1109 1110 // accessListResult returns an optional accesslist 1111 // It's the result of the `debug_createAccessList` RPC call. 1112 // It contains an error if the transaction itself failed. 1113 type accessListResult struct { 1114 Accesslist *types.AccessList `json:"accessList"` 1115 Error string `json:"error,omitempty"` 1116 GasUsed hexutil.Uint64 `json:"gasUsed"` 1117 } 1118 1119 // CreateAccessList creates an EIP-2930 type AccessList for the given transaction. 1120 // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state. 1121 // StateOverrides can be used to create the accessList while taking into account state changes from previous transactions. 1122 func (api *BlockChainAPI) CreateAccessList(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash, stateOverrides *override.StateOverride) (*accessListResult, error) { 1123 bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) 1124 if blockNrOrHash != nil { 1125 bNrOrHash = *blockNrOrHash 1126 } 1127 acl, gasUsed, vmerr, err := AccessList(ctx, api.b, bNrOrHash, args, stateOverrides) 1128 if err != nil { 1129 return nil, err 1130 } 1131 result := &accessListResult{Accesslist: &acl, GasUsed: hexutil.Uint64(gasUsed)} 1132 if vmerr != nil { 1133 result.Error = vmerr.Error() 1134 } 1135 return result, nil 1136 } 1137 1138 // AccessList creates an access list for the given transaction. 1139 // If the accesslist creation fails an error is returned. 1140 // If the transaction itself fails, an vmErr is returned. 1141 func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrHash, args TransactionArgs, stateOverrides *override.StateOverride) (acl types.AccessList, gasUsed uint64, vmErr error, err error) { 1142 // Retrieve the execution context 1143 db, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 1144 if db == nil || err != nil { 1145 return nil, 0, nil, err 1146 } 1147 1148 // Apply state overrides immediately after StateAndHeaderByNumberOrHash. 1149 // If not applied here, there could be cases where user-specified overrides (e.g., nonce) 1150 // may conflict with default values from the database, leading to inconsistencies. 1151 if stateOverrides != nil { 1152 if err := stateOverrides.Apply(db, nil); err != nil { 1153 return nil, 0, nil, err 1154 } 1155 } 1156 1157 // Ensure any missing fields are filled, extract the recipient and input data 1158 if err = args.setFeeDefaults(ctx, b, header); err != nil { 1159 return nil, 0, nil, err 1160 } 1161 if args.Nonce == nil { 1162 nonce := hexutil.Uint64(db.GetNonce(args.from())) 1163 args.Nonce = &nonce 1164 } 1165 blockCtx := core.NewEVMBlockContext(header, NewChainContext(ctx, b), nil) 1166 if err = args.CallDefaults(b.RPCGasCap(), blockCtx.BaseFee, b.ChainConfig().ChainID); err != nil { 1167 return nil, 0, nil, err 1168 } 1169 1170 var to common.Address 1171 if args.To != nil { 1172 to = *args.To 1173 } else { 1174 to = crypto.CreateAddress(args.from(), uint64(*args.Nonce)) 1175 } 1176 isPostMerge := header.Difficulty.Sign() == 0 1177 // Retrieve the precompiles since they don't need to be added to the access list 1178 precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number, isPostMerge, header.Time)) 1179 1180 // addressesToExclude contains sender, receiver, precompiles and valid authorizations 1181 addressesToExclude := map[common.Address]struct{}{args.from(): {}, to: {}} 1182 for _, addr := range precompiles { 1183 addressesToExclude[addr] = struct{}{} 1184 } 1185 1186 // Prevent redundant operations if args contain more authorizations than EVM may handle 1187 maxAuthorizations := uint64(*args.Gas) / params.CallNewAccountGas 1188 if uint64(len(args.AuthorizationList)) > maxAuthorizations { 1189 return nil, 0, nil, errors.New("insufficient gas to process all authorizations") 1190 } 1191 1192 for _, auth := range args.AuthorizationList { 1193 // Duplicating stateTransition.validateAuthorization() logic 1194 if (!auth.ChainID.IsZero() && auth.ChainID.CmpBig(b.ChainConfig().ChainID) != 0) || auth.Nonce+1 < auth.Nonce { 1195 continue 1196 } 1197 1198 if authority, err := auth.Authority(); err == nil { 1199 addressesToExclude[authority] = struct{}{} 1200 } 1201 } 1202 1203 // Create an initial tracer 1204 prevTracer := logger.NewAccessListTracer(nil, addressesToExclude) 1205 if args.AccessList != nil { 1206 prevTracer = logger.NewAccessListTracer(*args.AccessList, addressesToExclude) 1207 } 1208 for { 1209 if err := ctx.Err(); err != nil { 1210 return nil, 0, nil, err 1211 } 1212 // Retrieve the current access list to expand 1213 accessList := prevTracer.AccessList() 1214 log.Trace("Creating access list", "input", accessList) 1215 1216 // Copy the original db so we don't modify it 1217 statedb := db.Copy() 1218 // Set the accesslist to the last al 1219 args.AccessList = &accessList 1220 msg := args.ToMessage(header.BaseFee, true, true) 1221 1222 // Apply the transaction with the access list tracer 1223 tracer := logger.NewAccessListTracer(accessList, addressesToExclude) 1224 config := vm.Config{Tracer: tracer.Hooks(), NoBaseFee: true} 1225 evm := b.GetEVM(ctx, statedb, header, &config, nil) 1226 1227 // Lower the basefee to 0 to avoid breaking EVM 1228 // invariants (basefee < feecap). 1229 if msg.GasPrice.Sign() == 0 { 1230 evm.Context.BaseFee = new(big.Int) 1231 } 1232 if msg.BlobGasFeeCap != nil && msg.BlobGasFeeCap.BitLen() == 0 { 1233 evm.Context.BlobBaseFee = new(big.Int) 1234 } 1235 res, err := core.ApplyMessage(evm, msg, new(core.GasPool).AddGas(msg.GasLimit)) 1236 if err != nil { 1237 return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.ToTransaction(types.LegacyTxType).Hash(), err) 1238 } 1239 if tracer.Equal(prevTracer) { 1240 return accessList, res.UsedGas, res.Err, nil 1241 } 1242 prevTracer = tracer 1243 } 1244 } 1245 1246 // TransactionAPI exposes methods for reading and creating transaction data. 1247 type TransactionAPI struct { 1248 b Backend 1249 nonceLock *AddrLocker 1250 signer types.Signer 1251 } 1252 1253 // NewTransactionAPI creates a new RPC service with methods for interacting with transactions. 1254 func NewTransactionAPI(b Backend, nonceLock *AddrLocker) *TransactionAPI { 1255 // The signer used by the API should always be the 'latest' known one because we expect 1256 // signers to be backwards-compatible with old transactions. 1257 signer := types.LatestSigner(b.ChainConfig()) 1258 return &TransactionAPI{b, nonceLock, signer} 1259 } 1260 1261 // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number. 1262 func (api *TransactionAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*hexutil.Uint, error) { 1263 block, err := api.b.BlockByNumber(ctx, blockNr) 1264 if block != nil { 1265 n := hexutil.Uint(len(block.Transactions())) 1266 return &n, nil 1267 } 1268 return nil, err 1269 } 1270 1271 // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash. 1272 func (api *TransactionAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) (*hexutil.Uint, error) { 1273 block, err := api.b.BlockByHash(ctx, blockHash) 1274 if block != nil { 1275 n := hexutil.Uint(len(block.Transactions())) 1276 return &n, nil 1277 } 1278 return nil, err 1279 } 1280 1281 // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index. 1282 func (api *TransactionAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (*RPCTransaction, error) { 1283 block, err := api.b.BlockByNumber(ctx, blockNr) 1284 if block != nil { 1285 return newRPCTransactionFromBlockIndex(block, uint64(index), api.b.ChainConfig()), nil 1286 } 1287 return nil, err 1288 } 1289 1290 // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index. 1291 func (api *TransactionAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (*RPCTransaction, error) { 1292 block, err := api.b.BlockByHash(ctx, blockHash) 1293 if block != nil { 1294 return newRPCTransactionFromBlockIndex(block, uint64(index), api.b.ChainConfig()), nil 1295 } 1296 return nil, err 1297 } 1298 1299 // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index. 1300 func (api *TransactionAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes { 1301 if block, _ := api.b.BlockByNumber(ctx, blockNr); block != nil { 1302 return newRPCRawTransactionFromBlockIndex(block, uint64(index)) 1303 } 1304 return nil 1305 } 1306 1307 // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index. 1308 func (api *TransactionAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes { 1309 if block, _ := api.b.BlockByHash(ctx, blockHash); block != nil { 1310 return newRPCRawTransactionFromBlockIndex(block, uint64(index)) 1311 } 1312 return nil 1313 } 1314 1315 // GetTransactionCount returns the number of transactions the given address has sent for the given block number 1316 func (api *TransactionAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) { 1317 // Ask transaction pool for the nonce which includes pending transactions 1318 if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber { 1319 nonce, err := api.b.GetPoolNonce(ctx, address) 1320 if err != nil { 1321 return nil, err 1322 } 1323 return (*hexutil.Uint64)(&nonce), nil 1324 } 1325 // Resolve block number and use its state to ask for the nonce 1326 state, _, err := api.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 1327 if state == nil || err != nil { 1328 return nil, err 1329 } 1330 nonce := state.GetNonce(address) 1331 return (*hexutil.Uint64)(&nonce), state.Error() 1332 } 1333 1334 // GetTransactionByHash returns the transaction for the given hash 1335 func (api *TransactionAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) { 1336 // Try to return an already finalized transaction 1337 found, tx, blockHash, blockNumber, index := api.b.GetCanonicalTransaction(hash) 1338 if !found { 1339 // No finalized transaction, try to retrieve it from the pool 1340 if tx := api.b.GetPoolTransaction(hash); tx != nil { 1341 return NewRPCPendingTransaction(tx, api.b.CurrentHeader(), api.b.ChainConfig()), nil 1342 } 1343 // If also not in the pool there is a chance the tx indexer is still in progress. 1344 if !api.b.TxIndexDone() { 1345 return nil, NewTxIndexingError() 1346 } 1347 // If the transaction is not found in the pool and the indexer is done, return nil 1348 return nil, nil 1349 } 1350 header, err := api.b.HeaderByHash(ctx, blockHash) 1351 if err != nil { 1352 return nil, err 1353 } 1354 return newRPCTransaction(tx, blockHash, blockNumber, header.Time, index, header.BaseFee, api.b.ChainConfig()), nil 1355 } 1356 1357 // GetRawTransactionByHash returns the bytes of the transaction for the given hash. 1358 func (api *TransactionAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 1359 // Retrieve a finalized transaction, or a pooled otherwise 1360 found, tx, _, _, _ := api.b.GetCanonicalTransaction(hash) 1361 if !found { 1362 if tx = api.b.GetPoolTransaction(hash); tx != nil { 1363 return tx.MarshalBinary() 1364 } 1365 // If also not in the pool there is a chance the tx indexer is still in progress. 1366 if !api.b.TxIndexDone() { 1367 return nil, NewTxIndexingError() 1368 } 1369 // If the transaction is not found in the pool and the indexer is done, return nil 1370 return nil, nil 1371 } 1372 return tx.MarshalBinary() 1373 } 1374 1375 // GetTransactionReceipt returns the transaction receipt for the given transaction hash. 1376 func (api *TransactionAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) { 1377 found, tx, blockHash, blockNumber, index := api.b.GetCanonicalTransaction(hash) 1378 if !found { 1379 // Make sure indexer is done. 1380 if !api.b.TxIndexDone() { 1381 return nil, NewTxIndexingError() 1382 } 1383 // No such tx. 1384 return nil, nil 1385 } 1386 receipt, err := api.b.GetCanonicalReceipt(tx, blockHash, blockNumber, index) 1387 if err != nil { 1388 return nil, err 1389 } 1390 // Derive the sender. 1391 return marshalReceipt(receipt, blockHash, blockNumber, api.signer, tx, int(index)), nil 1392 } 1393 1394 // marshalReceipt marshals a transaction receipt into a JSON object. 1395 func marshalReceipt(receipt *types.Receipt, blockHash common.Hash, blockNumber uint64, signer types.Signer, tx *types.Transaction, txIndex int) map[string]interface{} { 1396 from, _ := types.Sender(signer, tx) 1397 1398 fields := map[string]interface{}{ 1399 "blockHash": blockHash, 1400 "blockNumber": hexutil.Uint64(blockNumber), 1401 "transactionHash": tx.Hash(), 1402 "transactionIndex": hexutil.Uint64(txIndex), 1403 "from": from, 1404 "to": tx.To(), 1405 "gasUsed": hexutil.Uint64(receipt.GasUsed), 1406 "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed), 1407 "contractAddress": nil, 1408 "logs": receipt.Logs, 1409 "logsBloom": receipt.Bloom, 1410 "type": hexutil.Uint(tx.Type()), 1411 "effectiveGasPrice": (*hexutil.Big)(receipt.EffectiveGasPrice), 1412 } 1413 1414 // Assign receipt status or post state. 1415 if len(receipt.PostState) > 0 { 1416 fields["root"] = hexutil.Bytes(receipt.PostState) 1417 } else { 1418 fields["status"] = hexutil.Uint(receipt.Status) 1419 } 1420 if receipt.Logs == nil { 1421 fields["logs"] = []*types.Log{} 1422 } 1423 1424 if tx.Type() == types.BlobTxType { 1425 fields["blobGasUsed"] = hexutil.Uint64(receipt.BlobGasUsed) 1426 fields["blobGasPrice"] = (*hexutil.Big)(receipt.BlobGasPrice) 1427 } 1428 1429 // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation 1430 if receipt.ContractAddress != (common.Address{}) { 1431 fields["contractAddress"] = receipt.ContractAddress 1432 } 1433 return fields 1434 } 1435 1436 // sign is a helper function that signs a transaction with the private key of the given address. 1437 func (api *TransactionAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) { 1438 // Look up the wallet containing the requested signer 1439 account := accounts.Account{Address: addr} 1440 1441 wallet, err := api.b.AccountManager().Find(account) 1442 if err != nil { 1443 return nil, err 1444 } 1445 // Request the wallet to sign the transaction 1446 return wallet.SignTx(account, tx, api.b.ChainConfig().ChainID) 1447 } 1448 1449 // SubmitTransaction is a helper function that submits tx to txPool and logs a message. 1450 func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) { 1451 // If the transaction fee cap is already specified, ensure the 1452 // fee of the given transaction is _reasonable_. 1453 if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil { 1454 return common.Hash{}, err 1455 } 1456 if !b.UnprotectedAllowed() && !tx.Protected() { 1457 // Ensure only eip155 signed transactions are submitted if EIP155Required is set. 1458 return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed over RPC") 1459 } 1460 if err := b.SendTx(ctx, tx); err != nil { 1461 return common.Hash{}, err 1462 } 1463 // Print a log with full tx details for manual investigations and interventions 1464 head := b.CurrentBlock() 1465 signer := types.MakeSigner(b.ChainConfig(), head.Number, head.Time) 1466 from, err := types.Sender(signer, tx) 1467 if err != nil { 1468 return common.Hash{}, err 1469 } 1470 1471 if tx.To() == nil { 1472 addr := crypto.CreateAddress(from, tx.Nonce()) 1473 log.Info("Submitted contract creation", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "contract", addr.Hex(), "value", tx.Value()) 1474 } else { 1475 log.Info("Submitted transaction", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "recipient", tx.To(), "value", tx.Value()) 1476 } 1477 return tx.Hash(), nil 1478 } 1479 1480 // SendTransaction creates a transaction for the given argument, sign it and submit it to the 1481 // transaction pool. 1482 func (api *TransactionAPI) SendTransaction(ctx context.Context, args TransactionArgs) (common.Hash, error) { 1483 // Look up the wallet containing the requested signer 1484 account := accounts.Account{Address: args.from()} 1485 1486 wallet, err := api.b.AccountManager().Find(account) 1487 if err != nil { 1488 return common.Hash{}, err 1489 } 1490 1491 if args.Nonce == nil { 1492 // Hold the mutex around signing to prevent concurrent assignment of 1493 // the same nonce to multiple accounts. 1494 api.nonceLock.LockAddr(args.from()) 1495 defer api.nonceLock.UnlockAddr(args.from()) 1496 } 1497 if args.IsEIP4844() { 1498 return common.Hash{}, errBlobTxNotSupported 1499 } 1500 1501 // Set some sanity defaults and terminate on failure 1502 if err := args.setDefaults(ctx, api.b, false); err != nil { 1503 return common.Hash{}, err 1504 } 1505 // Assemble the transaction and sign with the wallet 1506 tx := args.ToTransaction(types.LegacyTxType) 1507 1508 signed, err := wallet.SignTx(account, tx, api.b.ChainConfig().ChainID) 1509 if err != nil { 1510 return common.Hash{}, err 1511 } 1512 return SubmitTransaction(ctx, api.b, signed) 1513 } 1514 1515 // FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields) 1516 // on a given unsigned transaction, and returns it to the caller for further 1517 // processing (signing + broadcast). 1518 func (api *TransactionAPI) FillTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) { 1519 args.blobSidecarAllowed = true 1520 1521 // Set some sanity defaults and terminate on failure 1522 if err := args.setDefaults(ctx, api.b, false); err != nil { 1523 return nil, err 1524 } 1525 // Assemble the transaction and obtain rlp 1526 tx := args.ToTransaction(types.LegacyTxType) 1527 data, err := tx.MarshalBinary() 1528 if err != nil { 1529 return nil, err 1530 } 1531 return &SignTransactionResult{data, tx}, nil 1532 } 1533 1534 // SendRawTransaction will add the signed transaction to the transaction pool. 1535 // The sender is responsible for signing the transaction and using the correct nonce. 1536 func (api *TransactionAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) { 1537 tx := new(types.Transaction) 1538 if err := tx.UnmarshalBinary(input); err != nil { 1539 return common.Hash{}, err 1540 } 1541 return SubmitTransaction(ctx, api.b, tx) 1542 } 1543 1544 // Sign calculates an ECDSA signature for: 1545 // keccak256("\x19Ethereum Signed Message:\n" + len(message) + message). 1546 // 1547 // Note, the produced signature conforms to the secp256k1 curve R, S and V values, 1548 // where the V value will be 27 or 28 for legacy reasons. 1549 // 1550 // The account associated with addr must be unlocked. 1551 // 1552 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign 1553 func (api *TransactionAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) { 1554 // Look up the wallet containing the requested signer 1555 account := accounts.Account{Address: addr} 1556 1557 wallet, err := api.b.AccountManager().Find(account) 1558 if err != nil { 1559 return nil, err 1560 } 1561 // Sign the requested hash with the wallet 1562 signature, err := wallet.SignText(account, data) 1563 if err == nil { 1564 signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 1565 } 1566 return signature, err 1567 } 1568 1569 // SignTransactionResult represents a RLP encoded signed transaction. 1570 type SignTransactionResult struct { 1571 Raw hexutil.Bytes `json:"raw"` 1572 Tx *types.Transaction `json:"tx"` 1573 } 1574 1575 // SignTransaction will sign the given transaction with the from account. 1576 // The node needs to have the private key of the account corresponding with 1577 // the given from address and it needs to be unlocked. 1578 func (api *TransactionAPI) SignTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) { 1579 args.blobSidecarAllowed = true 1580 1581 if args.Gas == nil { 1582 return nil, errors.New("gas not specified") 1583 } 1584 if args.GasPrice == nil && (args.MaxPriorityFeePerGas == nil || args.MaxFeePerGas == nil) { 1585 return nil, errors.New("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas") 1586 } 1587 if args.Nonce == nil { 1588 return nil, errors.New("nonce not specified") 1589 } 1590 if err := args.setDefaults(ctx, api.b, false); err != nil { 1591 return nil, err 1592 } 1593 // Before actually sign the transaction, ensure the transaction fee is reasonable. 1594 tx := args.ToTransaction(types.LegacyTxType) 1595 if err := checkTxFee(tx.GasPrice(), tx.Gas(), api.b.RPCTxFeeCap()); err != nil { 1596 return nil, err 1597 } 1598 signed, err := api.sign(args.from(), tx) 1599 if err != nil { 1600 return nil, err 1601 } 1602 // If the transaction-to-sign was a blob transaction, then the signed one 1603 // no longer retains the blobs, only the blob hashes. In this step, we need 1604 // to put back the blob(s). 1605 if args.IsEIP4844() { 1606 signed = signed.WithBlobTxSidecar(&types.BlobTxSidecar{ 1607 Blobs: args.Blobs, 1608 Commitments: args.Commitments, 1609 Proofs: args.Proofs, 1610 }) 1611 } 1612 data, err := signed.MarshalBinary() 1613 if err != nil { 1614 return nil, err 1615 } 1616 return &SignTransactionResult{data, signed}, nil 1617 } 1618 1619 // PendingTransactions returns the transactions that are in the transaction pool 1620 // and have a from address that is one of the accounts this node manages. 1621 func (api *TransactionAPI) PendingTransactions() ([]*RPCTransaction, error) { 1622 pending, err := api.b.GetPoolTransactions() 1623 if err != nil { 1624 return nil, err 1625 } 1626 accounts := make(map[common.Address]struct{}) 1627 for _, wallet := range api.b.AccountManager().Wallets() { 1628 for _, account := range wallet.Accounts() { 1629 accounts[account.Address] = struct{}{} 1630 } 1631 } 1632 curHeader := api.b.CurrentHeader() 1633 transactions := make([]*RPCTransaction, 0, len(pending)) 1634 for _, tx := range pending { 1635 from, _ := types.Sender(api.signer, tx) 1636 if _, exists := accounts[from]; exists { 1637 transactions = append(transactions, NewRPCPendingTransaction(tx, curHeader, api.b.ChainConfig())) 1638 } 1639 } 1640 return transactions, nil 1641 } 1642 1643 // Resend accepts an existing transaction and a new gas price and limit. It will remove 1644 // the given transaction from the pool and reinsert it with the new gas price and limit. 1645 func (api *TransactionAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) { 1646 if sendArgs.Nonce == nil { 1647 return common.Hash{}, errors.New("missing transaction nonce in transaction spec") 1648 } 1649 if err := sendArgs.setDefaults(ctx, api.b, false); err != nil { 1650 return common.Hash{}, err 1651 } 1652 matchTx := sendArgs.ToTransaction(types.LegacyTxType) 1653 1654 // Before replacing the old transaction, ensure the _new_ transaction fee is reasonable. 1655 price := matchTx.GasPrice() 1656 if gasPrice != nil { 1657 price = gasPrice.ToInt() 1658 } 1659 gas := matchTx.Gas() 1660 if gasLimit != nil { 1661 gas = uint64(*gasLimit) 1662 } 1663 if err := checkTxFee(price, gas, api.b.RPCTxFeeCap()); err != nil { 1664 return common.Hash{}, err 1665 } 1666 // Iterate the pending list for replacement 1667 pending, err := api.b.GetPoolTransactions() 1668 if err != nil { 1669 return common.Hash{}, err 1670 } 1671 for _, p := range pending { 1672 wantSigHash := api.signer.Hash(matchTx) 1673 pFrom, err := types.Sender(api.signer, p) 1674 if err == nil && pFrom == sendArgs.from() && api.signer.Hash(p) == wantSigHash { 1675 // Match. Re-sign and send the transaction. 1676 if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 { 1677 sendArgs.GasPrice = gasPrice 1678 } 1679 if gasLimit != nil && *gasLimit != 0 { 1680 sendArgs.Gas = gasLimit 1681 } 1682 signedTx, err := api.sign(sendArgs.from(), sendArgs.ToTransaction(types.LegacyTxType)) 1683 if err != nil { 1684 return common.Hash{}, err 1685 } 1686 if err = api.b.SendTx(ctx, signedTx); err != nil { 1687 return common.Hash{}, err 1688 } 1689 return signedTx.Hash(), nil 1690 } 1691 } 1692 return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash()) 1693 } 1694 1695 // DebugAPI is the collection of Ethereum APIs exposed over the debugging 1696 // namespace. 1697 type DebugAPI struct { 1698 b Backend 1699 } 1700 1701 // NewDebugAPI creates a new instance of DebugAPI. 1702 func NewDebugAPI(b Backend) *DebugAPI { 1703 return &DebugAPI{b: b} 1704 } 1705 1706 // GetRawHeader retrieves the RLP encoding for a single header. 1707 func (api *DebugAPI) GetRawHeader(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { 1708 var hash common.Hash 1709 if h, ok := blockNrOrHash.Hash(); ok { 1710 hash = h 1711 } else { 1712 block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash) 1713 if block == nil || err != nil { 1714 return nil, err 1715 } 1716 hash = block.Hash() 1717 } 1718 header, _ := api.b.HeaderByHash(ctx, hash) 1719 if header == nil { 1720 return nil, fmt.Errorf("header #%d not found", hash) 1721 } 1722 return rlp.EncodeToBytes(header) 1723 } 1724 1725 // GetRawBlock retrieves the RLP encoded for a single block. 1726 func (api *DebugAPI) GetRawBlock(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { 1727 var hash common.Hash 1728 if h, ok := blockNrOrHash.Hash(); ok { 1729 hash = h 1730 } else { 1731 block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash) 1732 if block == nil || err != nil { 1733 return nil, err 1734 } 1735 hash = block.Hash() 1736 } 1737 block, _ := api.b.BlockByHash(ctx, hash) 1738 if block == nil { 1739 return nil, fmt.Errorf("block #%d not found", hash) 1740 } 1741 return rlp.EncodeToBytes(block) 1742 } 1743 1744 // GetRawReceipts retrieves the binary-encoded receipts of a single block. 1745 func (api *DebugAPI) GetRawReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]hexutil.Bytes, error) { 1746 var hash common.Hash 1747 if h, ok := blockNrOrHash.Hash(); ok { 1748 hash = h 1749 } else { 1750 block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash) 1751 if block == nil || err != nil { 1752 return nil, err 1753 } 1754 hash = block.Hash() 1755 } 1756 receipts, err := api.b.GetReceipts(ctx, hash) 1757 if err != nil { 1758 return nil, err 1759 } 1760 result := make([]hexutil.Bytes, len(receipts)) 1761 for i, receipt := range receipts { 1762 b, err := receipt.MarshalBinary() 1763 if err != nil { 1764 return nil, err 1765 } 1766 result[i] = b 1767 } 1768 return result, nil 1769 } 1770 1771 // GetRawTransaction returns the bytes of the transaction for the given hash. 1772 func (api *DebugAPI) GetRawTransaction(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 1773 // Retrieve a finalized transaction, or a pooled otherwise 1774 found, tx, _, _, _ := api.b.GetCanonicalTransaction(hash) 1775 if !found { 1776 if tx = api.b.GetPoolTransaction(hash); tx != nil { 1777 return tx.MarshalBinary() 1778 } 1779 // If also not in the pool there is a chance the tx indexer is still in progress. 1780 if !api.b.TxIndexDone() { 1781 return nil, NewTxIndexingError() 1782 } 1783 // Transaction is not found in the pool and the indexer is done. 1784 return nil, nil 1785 } 1786 return tx.MarshalBinary() 1787 } 1788 1789 // PrintBlock retrieves a block and returns its pretty printed form. 1790 func (api *DebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) { 1791 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1792 if block == nil { 1793 return "", fmt.Errorf("block #%d not found", number) 1794 } 1795 return spew.Sdump(block), nil 1796 } 1797 1798 // ChaindbProperty returns leveldb properties of the key-value database. 1799 func (api *DebugAPI) ChaindbProperty() (string, error) { 1800 return api.b.ChainDb().Stat() 1801 } 1802 1803 // ChaindbCompact flattens the entire key-value database into a single level, 1804 // removing all unused slots and merging all keys. 1805 func (api *DebugAPI) ChaindbCompact() error { 1806 cstart := time.Now() 1807 for b := 0; b <= 255; b++ { 1808 var ( 1809 start = []byte{byte(b)} 1810 end = []byte{byte(b + 1)} 1811 ) 1812 if b == 255 { 1813 end = nil 1814 } 1815 log.Info("Compacting database", "range", fmt.Sprintf("%#X-%#X", start, end), "elapsed", common.PrettyDuration(time.Since(cstart))) 1816 if err := api.b.ChainDb().Compact(start, end); err != nil { 1817 log.Error("Database compaction failed", "err", err) 1818 return err 1819 } 1820 } 1821 return nil 1822 } 1823 1824 // SetHead rewinds the head of the blockchain to a previous block. 1825 func (api *DebugAPI) SetHead(number hexutil.Uint64) error { 1826 header := api.b.CurrentHeader() 1827 if header == nil { 1828 return errors.New("current header is not available") 1829 } 1830 if header.Number.Uint64() <= uint64(number) { 1831 return errors.New("not allowed to rewind to a future block") 1832 } 1833 api.b.SetHead(uint64(number)) 1834 return nil 1835 } 1836 1837 // NetAPI offers network related RPC methods 1838 type NetAPI struct { 1839 net *p2p.Server 1840 networkVersion uint64 1841 } 1842 1843 // NewNetAPI creates a new net API instance. 1844 func NewNetAPI(net *p2p.Server, networkVersion uint64) *NetAPI { 1845 return &NetAPI{net, networkVersion} 1846 } 1847 1848 // Listening returns an indication if the node is listening for network connections. 1849 func (api *NetAPI) Listening() bool { 1850 return true // always listening 1851 } 1852 1853 // PeerCount returns the number of connected peers 1854 func (api *NetAPI) PeerCount() hexutil.Uint { 1855 return hexutil.Uint(api.net.PeerCount()) 1856 } 1857 1858 // Version returns the current ethereum protocol version. 1859 func (api *NetAPI) Version() string { 1860 return fmt.Sprintf("%d", api.networkVersion) 1861 } 1862 1863 // checkTxFee is an internal function used to check whether the fee of 1864 // the given transaction is _reasonable_(under the cap). 1865 func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error { 1866 // Short circuit if there is no cap for transaction fee at all. 1867 if cap == 0 { 1868 return nil 1869 } 1870 feeEth := new(big.Float).Quo(new(big.Float).SetInt(new(big.Int).Mul(gasPrice, new(big.Int).SetUint64(gas))), new(big.Float).SetInt(big.NewInt(params.Ether))) 1871 feeFloat, _ := feeEth.Float64() 1872 if feeFloat > cap { 1873 return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap) 1874 } 1875 return nil 1876 }