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