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