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