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