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