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