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