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