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