github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/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 "encoding/hex" 23 "errors" 24 "fmt" 25 "math/big" 26 "strings" 27 "time" 28 29 "github.com/ethereum/go-ethereum/accounts" 30 "github.com/ethereum/go-ethereum/accounts/keystore" 31 "github.com/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/common/hexutil" 33 "github.com/ethereum/go-ethereum/common/math" 34 "github.com/ethereum/go-ethereum/core" 35 "github.com/ethereum/go-ethereum/core/types" 36 "github.com/ethereum/go-ethereum/core/vm" 37 "github.com/ethereum/go-ethereum/crypto" 38 "github.com/ethereum/go-ethereum/ethdb" 39 "github.com/ethereum/go-ethereum/log" 40 "github.com/ethereum/go-ethereum/p2p" 41 "github.com/ethereum/go-ethereum/params" 42 "github.com/ethereum/go-ethereum/pow" 43 "github.com/ethereum/go-ethereum/rlp" 44 "github.com/ethereum/go-ethereum/rpc" 45 "github.com/syndtr/goleveldb/leveldb" 46 "github.com/syndtr/goleveldb/leveldb/util" 47 ) 48 49 const ( 50 defaultGas = 90000 51 defaultGasPrice = 50 * params.Shannon 52 emptyHex = "0x" 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 Etheruem 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) (*big.Int, error) { 68 return s.b.SuggestPrice(ctx) 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 nonce, tx := range txs { 122 dump[fmt.Sprintf("%d", 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 nonce, tx := range txs { 130 dump[fmt.Sprintf("%d", 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 × %v gas", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice()) 159 } 160 return fmt.Sprintf("contract creation: %v wei + %v × %v gas", 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 nonce, tx := range txs { 166 dump[fmt.Sprintf("%d", 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 nonce, tx := range txs { 174 dump[fmt.Sprintf("%d", 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 var addresses []common.Address 195 for _, wallet := range s.am.Wallets() { 196 for _, account := range wallet.Accounts() { 197 addresses = append(addresses, account.Address) 198 } 199 } 200 return addresses 201 } 202 203 // PrivateAccountAPI provides an API to access accounts managed by this node. 204 // It offers methods to create, (un)lock en list accounts. Some methods accept 205 // passwords and are therefore considered private by default. 206 type PrivateAccountAPI struct { 207 am *accounts.Manager 208 b Backend 209 } 210 211 // NewPrivateAccountAPI create a new PrivateAccountAPI. 212 func NewPrivateAccountAPI(b Backend) *PrivateAccountAPI { 213 return &PrivateAccountAPI{ 214 am: b.AccountManager(), 215 b: b, 216 } 217 } 218 219 // ListAccounts will return a list of addresses for accounts this node manages. 220 func (s *PrivateAccountAPI) ListAccounts() []common.Address { 221 var addresses []common.Address 222 for _, wallet := range s.am.Wallets() { 223 for _, account := range wallet.Accounts() { 224 addresses = append(addresses, account.Address) 225 } 226 } 227 return addresses 228 } 229 230 // rawWallet is a JSON representation of an accounts.Wallet interface, with its 231 // data contents extracted into plain fields. 232 type rawWallet struct { 233 URL string `json:"url"` 234 Status string `json:"status"` 235 Accounts []accounts.Account `json:"accounts"` 236 } 237 238 // ListWallets will return a list of wallets this node manages. 239 func (s *PrivateAccountAPI) ListWallets() []rawWallet { 240 var wallets []rawWallet 241 for _, wallet := range s.am.Wallets() { 242 wallets = append(wallets, rawWallet{ 243 URL: wallet.URL().String(), 244 Status: wallet.Status(), 245 Accounts: wallet.Accounts(), 246 }) 247 } 248 return wallets 249 } 250 251 // DeriveAccount requests a HD wallet to derive a new account, optionally pinning 252 // it for later reuse. 253 func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) { 254 wallet, err := s.am.Wallet(url) 255 if err != nil { 256 return accounts.Account{}, err 257 } 258 derivPath, err := accounts.ParseDerivationPath(path) 259 if err != nil { 260 return accounts.Account{}, err 261 } 262 if pin == nil { 263 pin = new(bool) 264 } 265 return wallet.Derive(derivPath, *pin) 266 } 267 268 // NewAccount will create a new account and returns the address for the new account. 269 func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) { 270 acc, err := fetchKeystore(s.am).NewAccount(password) 271 if err == nil { 272 return acc.Address, nil 273 } 274 return common.Address{}, err 275 } 276 277 // fetchKeystore retrives the encrypted keystore from the account manager. 278 func fetchKeystore(am *accounts.Manager) *keystore.KeyStore { 279 return am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 280 } 281 282 // ImportRawKey stores the given hex encoded ECDSA key into the key directory, 283 // encrypting it with the passphrase. 284 func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) { 285 hexkey, err := hex.DecodeString(privkey) 286 if err != nil { 287 return common.Address{}, err 288 } 289 290 acc, err := fetchKeystore(s.am).ImportECDSA(crypto.ToECDSA(hexkey), password) 291 return acc.Address, err 292 } 293 294 // UnlockAccount will unlock the account associated with the given address with 295 // the given password for duration seconds. If duration is nil it will use a 296 // default of 300 seconds. It returns an indication if the account was unlocked. 297 func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *uint64) (bool, error) { 298 const max = uint64(time.Duration(math.MaxInt64) / time.Second) 299 var d time.Duration 300 if duration == nil { 301 d = 300 * time.Second 302 } else if *duration > max { 303 return false, errors.New("unlock duration too large") 304 } else { 305 d = time.Duration(*duration) * time.Second 306 } 307 err := fetchKeystore(s.am).TimedUnlock(accounts.Account{Address: addr}, password, d) 308 return err == nil, err 309 } 310 311 // LockAccount will lock the account associated with the given address when it's unlocked. 312 func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool { 313 return fetchKeystore(s.am).Lock(addr) == nil 314 } 315 316 // SendTransaction will create a transaction from the given arguments and 317 // tries to sign it with the key associated with args.To. If the given passwd isn't 318 // able to decrypt the key it fails. 319 func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) { 320 // Set some sanity defaults and terminate on failure 321 if err := args.setDefaults(ctx, s.b); err != nil { 322 return common.Hash{}, err 323 } 324 // Look up the wallet containing the requested signer 325 account := accounts.Account{Address: args.From} 326 327 wallet, err := s.am.Find(account) 328 if err != nil { 329 return common.Hash{}, err 330 } 331 // Assemble the transaction and sign with the wallet 332 tx := args.toTransaction() 333 334 var chainID *big.Int 335 if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) { 336 chainID = config.ChainId 337 } 338 signed, err := wallet.SignTxWithPassphrase(account, passwd, tx, chainID) 339 if err != nil { 340 return common.Hash{}, err 341 } 342 return submitTransaction(ctx, s.b, signed) 343 } 344 345 // signHash is a helper function that calculates a hash for the given message that can be 346 // safely used to calculate a signature from. 347 // 348 // The hash is calulcated as 349 // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}). 350 // 351 // This gives context to the signed message and prevents signing of transactions. 352 func signHash(data []byte) []byte { 353 msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data) 354 return crypto.Keccak256([]byte(msg)) 355 } 356 357 // Sign calculates an Ethereum ECDSA signature for: 358 // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message)) 359 // 360 // Note, the produced signature conforms to the secp256k1 curve R, S and V values, 361 // where the V value will be 27 or 28 for legacy reasons. 362 // 363 // The key used to calculate the signature is decrypted with the given password. 364 // 365 // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign 366 func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) { 367 // Look up the wallet containing the requested signer 368 account := accounts.Account{Address: addr} 369 370 wallet, err := s.b.AccountManager().Find(account) 371 if err != nil { 372 return nil, err 373 } 374 // Assemble sign the data with the wallet 375 signature, err := wallet.SignHashWithPassphrase(account, passwd, signHash(data)) 376 if err != nil { 377 return nil, err 378 } 379 signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 380 return signature, nil 381 } 382 383 // EcRecover returns the address for the account that was used to create the signature. 384 // Note, this function is compatible with eth_sign and personal_sign. As such it recovers 385 // the address of: 386 // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message}) 387 // addr = ecrecover(hash, signature) 388 // 389 // Note, the signature must conform to the secp256k1 curve R, S and V values, where 390 // the V value must be be 27 or 28 for legacy reasons. 391 // 392 // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover 393 func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) { 394 if len(sig) != 65 { 395 return common.Address{}, fmt.Errorf("signature must be 65 bytes long") 396 } 397 if sig[64] != 27 && sig[64] != 28 { 398 return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)") 399 } 400 sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1 401 402 rpk, err := crypto.Ecrecover(signHash(data), sig) 403 if err != nil { 404 return common.Address{}, err 405 } 406 pubKey := crypto.ToECDSAPub(rpk) 407 recoveredAddr := crypto.PubkeyToAddress(*pubKey) 408 return recoveredAddr, nil 409 } 410 411 // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated 412 // and will be removed in the future. It primary goal is to give clients time to update. 413 func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) { 414 return s.SendTransaction(ctx, args, passwd) 415 } 416 417 // PublicBlockChainAPI provides an API to access the Ethereum blockchain. 418 // It offers only methods that operate on public data that is freely available to anyone. 419 type PublicBlockChainAPI struct { 420 b Backend 421 } 422 423 // NewPublicBlockChainAPI creates a new Etheruem blockchain API. 424 func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI { 425 return &PublicBlockChainAPI{b} 426 } 427 428 // BlockNumber returns the block number of the chain head. 429 func (s *PublicBlockChainAPI) BlockNumber() *big.Int { 430 header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available 431 return header.Number 432 } 433 434 // GetBalance returns the amount of wei for the given address in the state of the 435 // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta 436 // block numbers are also allowed. 437 func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) { 438 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 439 if state == nil || err != nil { 440 return nil, err 441 } 442 443 return state.GetBalance(ctx, address) 444 } 445 446 // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all 447 // transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 448 func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { 449 block, err := s.b.BlockByNumber(ctx, blockNr) 450 if block != nil { 451 response, err := s.rpcOutputBlock(block, true, fullTx) 452 if err == nil && blockNr == rpc.PendingBlockNumber { 453 // Pending blocks need to nil out a few fields 454 for _, field := range []string{"hash", "nonce", "miner"} { 455 response[field] = nil 456 } 457 } 458 return response, err 459 } 460 return nil, err 461 } 462 463 // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full 464 // detail, otherwise only the transaction hash is returned. 465 func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) { 466 block, err := s.b.GetBlock(ctx, blockHash) 467 if block != nil { 468 return s.rpcOutputBlock(block, true, fullTx) 469 } 470 return nil, err 471 } 472 473 // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true 474 // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 475 func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) { 476 block, err := s.b.BlockByNumber(ctx, blockNr) 477 if block != nil { 478 uncles := block.Uncles() 479 if index >= hexutil.Uint(len(uncles)) { 480 log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index) 481 return nil, nil 482 } 483 block = types.NewBlockWithHeader(uncles[index]) 484 return s.rpcOutputBlock(block, false, false) 485 } 486 return nil, err 487 } 488 489 // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true 490 // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 491 func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) { 492 block, err := s.b.GetBlock(ctx, blockHash) 493 if block != nil { 494 uncles := block.Uncles() 495 if index >= hexutil.Uint(len(uncles)) { 496 log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index) 497 return nil, nil 498 } 499 block = types.NewBlockWithHeader(uncles[index]) 500 return s.rpcOutputBlock(block, false, false) 501 } 502 return nil, err 503 } 504 505 // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number 506 func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint { 507 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 508 n := hexutil.Uint(len(block.Uncles())) 509 return &n 510 } 511 return nil 512 } 513 514 // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash 515 func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint { 516 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 517 n := hexutil.Uint(len(block.Uncles())) 518 return &n 519 } 520 return nil 521 } 522 523 // GetCode returns the code stored at the given address in the state for the given block number. 524 func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (string, error) { 525 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 526 if state == nil || err != nil { 527 return "", err 528 } 529 res, err := state.GetCode(ctx, address) 530 if len(res) == 0 || err != nil { // backwards compatibility 531 return "0x", err 532 } 533 return common.ToHex(res), nil 534 } 535 536 // GetStorageAt returns the storage from the state at the given address, key and 537 // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block 538 // numbers are also allowed. 539 func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (string, error) { 540 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 541 if state == nil || err != nil { 542 return "0x", err 543 } 544 res, err := state.GetState(ctx, address, common.HexToHash(key)) 545 if err != nil { 546 return "0x", err 547 } 548 return res.Hex(), nil 549 } 550 551 // callmsg is the message type used for call transitions. 552 type callmsg struct { 553 addr common.Address 554 to *common.Address 555 gas, gasPrice *big.Int 556 value *big.Int 557 data []byte 558 } 559 560 // accessor boilerplate to implement core.Message 561 func (m callmsg) From() (common.Address, error) { return m.addr, nil } 562 func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil } 563 func (m callmsg) Nonce() uint64 { return 0 } 564 func (m callmsg) CheckNonce() bool { return false } 565 func (m callmsg) To() *common.Address { return m.to } 566 func (m callmsg) GasPrice() *big.Int { return m.gasPrice } 567 func (m callmsg) Gas() *big.Int { return m.gas } 568 func (m callmsg) Value() *big.Int { return m.value } 569 func (m callmsg) Data() []byte { return m.data } 570 571 // CallArgs represents the arguments for a call. 572 type CallArgs struct { 573 From common.Address `json:"from"` 574 To *common.Address `json:"to"` 575 Gas hexutil.Big `json:"gas"` 576 GasPrice hexutil.Big `json:"gasPrice"` 577 Value hexutil.Big `json:"value"` 578 Data hexutil.Bytes `json:"data"` 579 } 580 581 func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber, vmCfg vm.Config) ([]byte, *big.Int, error) { 582 defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now()) 583 584 state, header, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 585 if state == nil || err != nil { 586 return nil, common.Big0, err 587 } 588 // Set sender address or use a default if none specified 589 addr := args.From 590 if addr == (common.Address{}) { 591 if wallets := s.b.AccountManager().Wallets(); len(wallets) > 0 { 592 if accounts := wallets[0].Accounts(); len(accounts) > 0 { 593 addr = accounts[0].Address 594 } 595 } 596 } 597 // Set default gas & gas price if none were set 598 gas, gasPrice := args.Gas.ToInt(), args.GasPrice.ToInt() 599 if gas.Sign() == 0 { 600 gas = big.NewInt(50000000) 601 } 602 if gasPrice.Sign() == 0 { 603 gasPrice = new(big.Int).SetUint64(defaultGasPrice) 604 } 605 606 // Create new call message 607 msg := types.NewMessage(addr, args.To, 0, args.Value.ToInt(), gas, gasPrice, args.Data, false) 608 609 // Setup context so it may be cancelled the call has completed 610 // or, in case of unmetered gas, setup a context with a timeout. 611 var cancel context.CancelFunc 612 if vmCfg.DisableGasMetering { 613 ctx, cancel = context.WithTimeout(ctx, time.Second*5) 614 } else { 615 ctx, cancel = context.WithCancel(ctx) 616 } 617 // Make sure the context is cancelled when the call has completed 618 // this makes sure resources are cleaned up. 619 defer func() { cancel() }() 620 621 // Get a new instance of the EVM. 622 evm, vmError, err := s.b.GetEVM(ctx, msg, state, header, vmCfg) 623 if err != nil { 624 return nil, common.Big0, err 625 } 626 // Wait for the context to be done and cancel the evm. Even if the 627 // EVM has finished, cancelling may be done (repeatedly) 628 go func() { 629 select { 630 case <-ctx.Done(): 631 evm.Cancel() 632 } 633 }() 634 635 // Setup the gas pool (also for unmetered requests) 636 // and apply the message. 637 gp := new(core.GasPool).AddGas(math.MaxBig256) 638 res, gas, err := core.ApplyMessage(evm, msg, gp) 639 if err := vmError(); err != nil { 640 return nil, common.Big0, err 641 } 642 return res, gas, err 643 } 644 645 // Call executes the given transaction on the state for the given block number. 646 // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values. 647 func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error) { 648 result, _, err := s.doCall(ctx, args, blockNr, vm.Config{DisableGasMetering: true}) 649 return (hexutil.Bytes)(result), err 650 } 651 652 // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction. 653 func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (*hexutil.Big, error) { 654 // Binary search the gas requirement, as it may be higher than the amount used 655 var lo, hi uint64 656 if (*big.Int)(&args.Gas).Sign() != 0 { 657 hi = (*big.Int)(&args.Gas).Uint64() 658 } else { 659 // Retrieve the current pending block to act as the gas ceiling 660 block, err := s.b.BlockByNumber(ctx, rpc.PendingBlockNumber) 661 if err != nil { 662 return nil, err 663 } 664 hi = block.GasLimit().Uint64() 665 } 666 for lo+1 < hi { 667 // Take a guess at the gas, and check transaction validity 668 mid := (hi + lo) / 2 669 (*big.Int)(&args.Gas).SetUint64(mid) 670 671 _, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber, vm.Config{}) 672 673 // If the transaction became invalid or used all the gas (failed), raise the gas limit 674 if err != nil || gas.Cmp((*big.Int)(&args.Gas)) == 0 { 675 lo = mid 676 continue 677 } 678 // Otherwise assume the transaction succeeded, lower the gas limit 679 hi = mid 680 } 681 return (*hexutil.Big)(new(big.Int).SetUint64(hi)), nil 682 } 683 684 // ExecutionResult groups all structured logs emitted by the EVM 685 // while replaying a transaction in debug mode as well as the amount of 686 // gas used and the return value 687 type ExecutionResult struct { 688 Gas *big.Int `json:"gas"` 689 ReturnValue string `json:"returnValue"` 690 StructLogs []StructLogRes `json:"structLogs"` 691 } 692 693 // StructLogRes stores a structured log emitted by the EVM while replaying a 694 // transaction in debug mode 695 type StructLogRes struct { 696 Pc uint64 `json:"pc"` 697 Op string `json:"op"` 698 Gas uint64 `json:"gas"` 699 GasCost uint64 `json:"gasCost"` 700 Depth int `json:"depth"` 701 Error error `json:"error"` 702 Stack []string `json:"stack"` 703 Memory []string `json:"memory"` 704 Storage map[string]string `json:"storage"` 705 } 706 707 // formatLogs formats EVM returned structured logs for json output 708 func FormatLogs(structLogs []vm.StructLog) []StructLogRes { 709 formattedStructLogs := make([]StructLogRes, len(structLogs)) 710 for index, trace := range structLogs { 711 formattedStructLogs[index] = StructLogRes{ 712 Pc: trace.Pc, 713 Op: trace.Op.String(), 714 Gas: trace.Gas, 715 GasCost: trace.GasCost, 716 Depth: trace.Depth, 717 Error: trace.Err, 718 Stack: make([]string, len(trace.Stack)), 719 Storage: make(map[string]string), 720 } 721 722 for i, stackValue := range trace.Stack { 723 formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32)) 724 } 725 726 for i := 0; i+32 <= len(trace.Memory); i += 32 { 727 formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32])) 728 } 729 730 for i, storageValue := range trace.Storage { 731 formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue) 732 } 733 } 734 return formattedStructLogs 735 } 736 737 // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are 738 // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain 739 // transaction hashes. 740 func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) { 741 head := b.Header() // copies the header once 742 fields := map[string]interface{}{ 743 "number": (*hexutil.Big)(head.Number), 744 "hash": b.Hash(), 745 "parentHash": head.ParentHash, 746 "nonce": head.Nonce, 747 "mixHash": head.MixDigest, 748 "sha3Uncles": head.UncleHash, 749 "logsBloom": head.Bloom, 750 "stateRoot": head.Root, 751 "miner": head.Coinbase, 752 "difficulty": (*hexutil.Big)(head.Difficulty), 753 "totalDifficulty": (*hexutil.Big)(s.b.GetTd(b.Hash())), 754 "extraData": hexutil.Bytes(head.Extra), 755 "size": hexutil.Uint64(uint64(b.Size().Int64())), 756 "gasLimit": (*hexutil.Big)(head.GasLimit), 757 "gasUsed": (*hexutil.Big)(head.GasUsed), 758 "timestamp": (*hexutil.Big)(head.Time), 759 "transactionsRoot": head.TxHash, 760 "receiptsRoot": head.ReceiptHash, 761 } 762 763 if inclTx { 764 formatTx := func(tx *types.Transaction) (interface{}, error) { 765 return tx.Hash(), nil 766 } 767 768 if fullTx { 769 formatTx = func(tx *types.Transaction) (interface{}, error) { 770 return newRPCTransaction(b, tx.Hash()) 771 } 772 } 773 774 txs := b.Transactions() 775 transactions := make([]interface{}, len(txs)) 776 var err error 777 for i, tx := range b.Transactions() { 778 if transactions[i], err = formatTx(tx); err != nil { 779 return nil, err 780 } 781 } 782 fields["transactions"] = transactions 783 } 784 785 uncles := b.Uncles() 786 uncleHashes := make([]common.Hash, len(uncles)) 787 for i, uncle := range uncles { 788 uncleHashes[i] = uncle.Hash() 789 } 790 fields["uncles"] = uncleHashes 791 792 return fields, nil 793 } 794 795 // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction 796 type RPCTransaction struct { 797 BlockHash common.Hash `json:"blockHash"` 798 BlockNumber *hexutil.Big `json:"blockNumber"` 799 From common.Address `json:"from"` 800 Gas *hexutil.Big `json:"gas"` 801 GasPrice *hexutil.Big `json:"gasPrice"` 802 Hash common.Hash `json:"hash"` 803 Input hexutil.Bytes `json:"input"` 804 Nonce hexutil.Uint64 `json:"nonce"` 805 To *common.Address `json:"to"` 806 TransactionIndex hexutil.Uint `json:"transactionIndex"` 807 Value *hexutil.Big `json:"value"` 808 V *hexutil.Big `json:"v"` 809 R *hexutil.Big `json:"r"` 810 S *hexutil.Big `json:"s"` 811 } 812 813 // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation 814 func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction { 815 var signer types.Signer = types.FrontierSigner{} 816 if tx.Protected() { 817 signer = types.NewEIP155Signer(tx.ChainId()) 818 } 819 from, _ := types.Sender(signer, tx) 820 v, r, s := tx.RawSignatureValues() 821 return &RPCTransaction{ 822 From: from, 823 Gas: (*hexutil.Big)(tx.Gas()), 824 GasPrice: (*hexutil.Big)(tx.GasPrice()), 825 Hash: tx.Hash(), 826 Input: hexutil.Bytes(tx.Data()), 827 Nonce: hexutil.Uint64(tx.Nonce()), 828 To: tx.To(), 829 Value: (*hexutil.Big)(tx.Value()), 830 V: (*hexutil.Big)(v), 831 R: (*hexutil.Big)(r), 832 S: (*hexutil.Big)(s), 833 } 834 } 835 836 // newRPCTransaction returns a transaction that will serialize to the RPC representation. 837 func newRPCTransactionFromBlockIndex(b *types.Block, txIndex uint) (*RPCTransaction, error) { 838 if txIndex < uint(len(b.Transactions())) { 839 tx := b.Transactions()[txIndex] 840 var signer types.Signer = types.FrontierSigner{} 841 if tx.Protected() { 842 signer = types.NewEIP155Signer(tx.ChainId()) 843 } 844 from, _ := types.Sender(signer, tx) 845 v, r, s := tx.RawSignatureValues() 846 return &RPCTransaction{ 847 BlockHash: b.Hash(), 848 BlockNumber: (*hexutil.Big)(b.Number()), 849 From: from, 850 Gas: (*hexutil.Big)(tx.Gas()), 851 GasPrice: (*hexutil.Big)(tx.GasPrice()), 852 Hash: tx.Hash(), 853 Input: hexutil.Bytes(tx.Data()), 854 Nonce: hexutil.Uint64(tx.Nonce()), 855 To: tx.To(), 856 TransactionIndex: hexutil.Uint(txIndex), 857 Value: (*hexutil.Big)(tx.Value()), 858 V: (*hexutil.Big)(v), 859 R: (*hexutil.Big)(r), 860 S: (*hexutil.Big)(s), 861 }, nil 862 } 863 864 return nil, nil 865 } 866 867 // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index. 868 func newRPCRawTransactionFromBlockIndex(b *types.Block, txIndex uint) (hexutil.Bytes, error) { 869 if txIndex < uint(len(b.Transactions())) { 870 tx := b.Transactions()[txIndex] 871 return rlp.EncodeToBytes(tx) 872 } 873 874 return nil, nil 875 } 876 877 // newRPCTransaction returns a transaction that will serialize to the RPC representation. 878 func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) { 879 for idx, tx := range b.Transactions() { 880 if tx.Hash() == txHash { 881 return newRPCTransactionFromBlockIndex(b, uint(idx)) 882 } 883 } 884 885 return nil, nil 886 } 887 888 // PublicTransactionPoolAPI exposes methods for the RPC interface 889 type PublicTransactionPoolAPI struct { 890 b Backend 891 } 892 893 // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool. 894 func NewPublicTransactionPoolAPI(b Backend) *PublicTransactionPoolAPI { 895 return &PublicTransactionPoolAPI{b} 896 } 897 898 func getTransaction(chainDb ethdb.Database, b Backend, txHash common.Hash) (*types.Transaction, bool, error) { 899 txData, err := chainDb.Get(txHash.Bytes()) 900 isPending := false 901 tx := new(types.Transaction) 902 903 if err == nil && len(txData) > 0 { 904 if err := rlp.DecodeBytes(txData, tx); err != nil { 905 return nil, isPending, err 906 } 907 } else { 908 // pending transaction? 909 tx = b.GetPoolTransaction(txHash) 910 isPending = true 911 } 912 913 return tx, isPending, nil 914 } 915 916 // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number. 917 func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint { 918 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 919 n := hexutil.Uint(len(block.Transactions())) 920 return &n 921 } 922 return nil 923 } 924 925 // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash. 926 func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint { 927 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 928 n := hexutil.Uint(len(block.Transactions())) 929 return &n 930 } 931 return nil 932 } 933 934 // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index. 935 func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (*RPCTransaction, error) { 936 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 937 return newRPCTransactionFromBlockIndex(block, uint(index)) 938 } 939 return nil, nil 940 } 941 942 // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index. 943 func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (*RPCTransaction, error) { 944 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 945 return newRPCTransactionFromBlockIndex(block, uint(index)) 946 } 947 return nil, nil 948 } 949 950 // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index. 951 func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (hexutil.Bytes, error) { 952 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 953 return newRPCRawTransactionFromBlockIndex(block, uint(index)) 954 } 955 return nil, nil 956 } 957 958 // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index. 959 func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (hexutil.Bytes, error) { 960 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 961 return newRPCRawTransactionFromBlockIndex(block, uint(index)) 962 } 963 return nil, nil 964 } 965 966 // GetTransactionCount returns the number of transactions the given address has sent for the given block number 967 func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) { 968 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 969 if state == nil || err != nil { 970 return nil, err 971 } 972 nonce, err := state.GetNonce(ctx, address) 973 if err != nil { 974 return nil, err 975 } 976 return (*hexutil.Uint64)(&nonce), nil 977 } 978 979 // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to 980 // retrieve block information for a hash. It returns the block hash, block index and transaction index. 981 func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) { 982 var txBlock struct { 983 BlockHash common.Hash 984 BlockIndex uint64 985 Index uint64 986 } 987 988 blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001)) 989 if err != nil { 990 return common.Hash{}, uint64(0), uint64(0), err 991 } 992 993 reader := bytes.NewReader(blockData) 994 if err = rlp.Decode(reader, &txBlock); err != nil { 995 return common.Hash{}, uint64(0), uint64(0), err 996 } 997 998 return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil 999 } 1000 1001 // GetTransactionByHash returns the transaction for the given hash 1002 func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) { 1003 var tx *types.Transaction 1004 var isPending bool 1005 var err error 1006 1007 if tx, isPending, err = getTransaction(s.b.ChainDb(), s.b, hash); err != nil { 1008 log.Debug("Failed to retrieve transaction", "hash", hash, "err", err) 1009 return nil, nil 1010 } else if tx == nil { 1011 return nil, nil 1012 } 1013 if isPending { 1014 return newRPCPendingTransaction(tx), nil 1015 } 1016 1017 blockHash, _, _, err := getTransactionBlockData(s.b.ChainDb(), hash) 1018 if err != nil { 1019 log.Debug("Failed to retrieve transaction block", "hash", hash, "err", err) 1020 return nil, nil 1021 } 1022 1023 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 1024 return newRPCTransaction(block, hash) 1025 } 1026 return nil, nil 1027 } 1028 1029 // GetRawTransactionByHash returns the bytes of the transaction for the given hash. 1030 func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 1031 var tx *types.Transaction 1032 var err error 1033 1034 if tx, _, err = getTransaction(s.b.ChainDb(), s.b, hash); err != nil { 1035 log.Debug("Failed to retrieve transaction", "hash", hash, "err", err) 1036 return nil, nil 1037 } else if tx == nil { 1038 return nil, nil 1039 } 1040 1041 return rlp.EncodeToBytes(tx) 1042 } 1043 1044 // GetTransactionReceipt returns the transaction receipt for the given transaction hash. 1045 func (s *PublicTransactionPoolAPI) GetTransactionReceipt(hash common.Hash) (map[string]interface{}, error) { 1046 receipt := core.GetReceipt(s.b.ChainDb(), hash) 1047 if receipt == nil { 1048 log.Debug("Receipt not found for transaction", "hash", hash) 1049 return nil, nil 1050 } 1051 1052 tx, _, err := getTransaction(s.b.ChainDb(), s.b, hash) 1053 if err != nil { 1054 log.Debug("Failed to retrieve transaction", "hash", hash, "err", err) 1055 return nil, nil 1056 } 1057 1058 txBlock, blockIndex, index, err := getTransactionBlockData(s.b.ChainDb(), hash) 1059 if err != nil { 1060 log.Debug("Failed to retrieve transaction block", "hash", hash, "err", err) 1061 return nil, nil 1062 } 1063 1064 var signer types.Signer = types.FrontierSigner{} 1065 if tx.Protected() { 1066 signer = types.NewEIP155Signer(tx.ChainId()) 1067 } 1068 from, _ := types.Sender(signer, tx) 1069 1070 fields := map[string]interface{}{ 1071 "root": hexutil.Bytes(receipt.PostState), 1072 "blockHash": txBlock, 1073 "blockNumber": hexutil.Uint64(blockIndex), 1074 "transactionHash": hash, 1075 "transactionIndex": hexutil.Uint64(index), 1076 "from": from, 1077 "to": tx.To(), 1078 "gasUsed": (*hexutil.Big)(receipt.GasUsed), 1079 "cumulativeGasUsed": (*hexutil.Big)(receipt.CumulativeGasUsed), 1080 "contractAddress": nil, 1081 "logs": receipt.Logs, 1082 "logsBloom": receipt.Bloom, 1083 } 1084 if receipt.Logs == nil { 1085 fields["logs"] = [][]*types.Log{} 1086 } 1087 // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation 1088 if receipt.ContractAddress != (common.Address{}) { 1089 fields["contractAddress"] = receipt.ContractAddress 1090 } 1091 return fields, nil 1092 } 1093 1094 // sign is a helper function that signs a transaction with the private key of the given address. 1095 func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) { 1096 // Look up the wallet containing the requested signer 1097 account := accounts.Account{Address: addr} 1098 1099 wallet, err := s.b.AccountManager().Find(account) 1100 if err != nil { 1101 return nil, err 1102 } 1103 // Request the wallet to sign the transaction 1104 var chainID *big.Int 1105 if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) { 1106 chainID = config.ChainId 1107 } 1108 return wallet.SignTx(account, tx, chainID) 1109 } 1110 1111 // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool. 1112 type SendTxArgs struct { 1113 From common.Address `json:"from"` 1114 To *common.Address `json:"to"` 1115 Gas *hexutil.Big `json:"gas"` 1116 GasPrice *hexutil.Big `json:"gasPrice"` 1117 Value *hexutil.Big `json:"value"` 1118 Data hexutil.Bytes `json:"data"` 1119 Nonce *hexutil.Uint64 `json:"nonce"` 1120 } 1121 1122 // prepareSendTxArgs is a helper function that fills in default values for unspecified tx fields. 1123 func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error { 1124 if args.Gas == nil { 1125 args.Gas = (*hexutil.Big)(big.NewInt(defaultGas)) 1126 } 1127 if args.GasPrice == nil { 1128 price, err := b.SuggestPrice(ctx) 1129 if err != nil { 1130 return err 1131 } 1132 args.GasPrice = (*hexutil.Big)(price) 1133 } 1134 if args.Value == nil { 1135 args.Value = new(hexutil.Big) 1136 } 1137 if args.Nonce == nil { 1138 nonce, err := b.GetPoolNonce(ctx, args.From) 1139 if err != nil { 1140 return err 1141 } 1142 args.Nonce = (*hexutil.Uint64)(&nonce) 1143 } 1144 return nil 1145 } 1146 1147 func (args *SendTxArgs) toTransaction() *types.Transaction { 1148 if args.To == nil { 1149 return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), (*big.Int)(args.Gas), (*big.Int)(args.GasPrice), args.Data) 1150 } 1151 return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), (*big.Int)(args.Gas), (*big.Int)(args.GasPrice), args.Data) 1152 } 1153 1154 // submitTransaction is a helper function that submits tx to txPool and logs a message. 1155 func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) { 1156 if err := b.SendTx(ctx, tx); err != nil { 1157 return common.Hash{}, err 1158 } 1159 if tx.To() == nil { 1160 signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number()) 1161 from, _ := types.Sender(signer, tx) 1162 addr := crypto.CreateAddress(from, tx.Nonce()) 1163 log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex()) 1164 } else { 1165 log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To()) 1166 } 1167 return tx.Hash(), nil 1168 } 1169 1170 // SendTransaction creates a transaction for the given argument, sign it and submit it to the 1171 // transaction pool. 1172 func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) { 1173 // Set some sanity defaults and terminate on failure 1174 if err := args.setDefaults(ctx, s.b); err != nil { 1175 return common.Hash{}, err 1176 } 1177 // Look up the wallet containing the requested signer 1178 account := accounts.Account{Address: args.From} 1179 1180 wallet, err := s.b.AccountManager().Find(account) 1181 if err != nil { 1182 return common.Hash{}, err 1183 } 1184 // Assemble the transaction and sign with the wallet 1185 tx := args.toTransaction() 1186 1187 var chainID *big.Int 1188 if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) { 1189 chainID = config.ChainId 1190 } 1191 signed, err := wallet.SignTx(account, tx, chainID) 1192 if err != nil { 1193 return common.Hash{}, err 1194 } 1195 return submitTransaction(ctx, s.b, signed) 1196 } 1197 1198 // SendRawTransaction will add the signed transaction to the transaction pool. 1199 // The sender is responsible for signing the transaction and using the correct nonce. 1200 func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (string, error) { 1201 tx := new(types.Transaction) 1202 if err := rlp.DecodeBytes(encodedTx, tx); err != nil { 1203 return "", err 1204 } 1205 1206 if err := s.b.SendTx(ctx, tx); err != nil { 1207 return "", err 1208 } 1209 1210 signer := types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number()) 1211 if tx.To() == nil { 1212 from, err := types.Sender(signer, tx) 1213 if err != nil { 1214 return "", err 1215 } 1216 addr := crypto.CreateAddress(from, tx.Nonce()) 1217 log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex()) 1218 } else { 1219 log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To()) 1220 } 1221 1222 return tx.Hash().Hex(), nil 1223 } 1224 1225 // Sign calculates an ECDSA signature for: 1226 // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message). 1227 // 1228 // Note, the produced signature conforms to the secp256k1 curve R, S and V values, 1229 // where the V value will be 27 or 28 for legacy reasons. 1230 // 1231 // The account associated with addr must be unlocked. 1232 // 1233 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign 1234 func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) { 1235 // Look up the wallet containing the requested signer 1236 account := accounts.Account{Address: addr} 1237 1238 wallet, err := s.b.AccountManager().Find(account) 1239 if err != nil { 1240 return nil, err 1241 } 1242 // Sign the requested hash with the wallet 1243 signature, err := wallet.SignHash(account, signHash(data)) 1244 if err == nil { 1245 signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 1246 } 1247 return signature, err 1248 } 1249 1250 // SignTransactionResult represents a RLP encoded signed transaction. 1251 type SignTransactionResult struct { 1252 Raw hexutil.Bytes `json:"raw"` 1253 Tx *types.Transaction `json:"tx"` 1254 } 1255 1256 // SignTransaction will sign the given transaction with the from account. 1257 // The node needs to have the private key of the account corresponding with 1258 // the given from address and it needs to be unlocked. 1259 func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) { 1260 if err := args.setDefaults(ctx, s.b); err != nil { 1261 return nil, err 1262 } 1263 tx, err := s.sign(args.From, args.toTransaction()) 1264 if err != nil { 1265 return nil, err 1266 } 1267 data, err := rlp.EncodeToBytes(tx) 1268 if err != nil { 1269 return nil, err 1270 } 1271 return &SignTransactionResult{data, tx}, nil 1272 } 1273 1274 // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of 1275 // the accounts this node manages. 1276 func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) { 1277 pending, err := s.b.GetPoolTransactions() 1278 if err != nil { 1279 return nil, err 1280 } 1281 1282 transactions := make([]*RPCTransaction, 0, len(pending)) 1283 for _, tx := range pending { 1284 var signer types.Signer = types.HomesteadSigner{} 1285 if tx.Protected() { 1286 signer = types.NewEIP155Signer(tx.ChainId()) 1287 } 1288 from, _ := types.Sender(signer, tx) 1289 if _, err := s.b.AccountManager().Find(accounts.Account{Address: from}); err == nil { 1290 transactions = append(transactions, newRPCPendingTransaction(tx)) 1291 } 1292 } 1293 return transactions, nil 1294 } 1295 1296 // Resend accepts an existing transaction and a new gas price and limit. It will remove 1297 // the given transaction from the pool and reinsert it with the new gas price and limit. 1298 func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice, gasLimit *hexutil.Big) (common.Hash, error) { 1299 if sendArgs.Nonce == nil { 1300 return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec") 1301 } 1302 if err := sendArgs.setDefaults(ctx, s.b); err != nil { 1303 return common.Hash{}, err 1304 } 1305 matchTx := sendArgs.toTransaction() 1306 pending, err := s.b.GetPoolTransactions() 1307 if err != nil { 1308 return common.Hash{}, err 1309 } 1310 1311 for _, p := range pending { 1312 var signer types.Signer = types.HomesteadSigner{} 1313 if p.Protected() { 1314 signer = types.NewEIP155Signer(p.ChainId()) 1315 } 1316 wantSigHash := signer.Hash(matchTx) 1317 1318 if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash { 1319 // Match. Re-sign and send the transaction. 1320 if gasPrice != nil { 1321 sendArgs.GasPrice = gasPrice 1322 } 1323 if gasLimit != nil { 1324 sendArgs.Gas = gasLimit 1325 } 1326 signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction()) 1327 if err != nil { 1328 return common.Hash{}, err 1329 } 1330 s.b.RemoveTx(p.Hash()) 1331 if err = s.b.SendTx(ctx, signedTx); err != nil { 1332 return common.Hash{}, err 1333 } 1334 return signedTx.Hash(), nil 1335 } 1336 } 1337 1338 return common.Hash{}, fmt.Errorf("Transaction %#x not found", matchTx.Hash()) 1339 } 1340 1341 // PublicDebugAPI is the collection of Etheruem APIs exposed over the public 1342 // debugging endpoint. 1343 type PublicDebugAPI struct { 1344 b Backend 1345 } 1346 1347 // NewPublicDebugAPI creates a new API definition for the public debug methods 1348 // of the Ethereum service. 1349 func NewPublicDebugAPI(b Backend) *PublicDebugAPI { 1350 return &PublicDebugAPI{b: b} 1351 } 1352 1353 // GetBlockRlp retrieves the RLP encoded for of a single block. 1354 func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) { 1355 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1356 if block == nil { 1357 return "", fmt.Errorf("block #%d not found", number) 1358 } 1359 encoded, err := rlp.EncodeToBytes(block) 1360 if err != nil { 1361 return "", err 1362 } 1363 return fmt.Sprintf("%x", encoded), nil 1364 } 1365 1366 // PrintBlock retrieves a block and returns its pretty printed form. 1367 func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) { 1368 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1369 if block == nil { 1370 return "", fmt.Errorf("block #%d not found", number) 1371 } 1372 return fmt.Sprintf("%s", block), nil 1373 } 1374 1375 // SeedHash retrieves the seed hash of a block. 1376 func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) { 1377 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1378 if block == nil { 1379 return "", fmt.Errorf("block #%d not found", number) 1380 } 1381 return fmt.Sprintf("0x%x", pow.EthashSeedHash(number)), nil 1382 } 1383 1384 // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private 1385 // debugging endpoint. 1386 type PrivateDebugAPI struct { 1387 b Backend 1388 } 1389 1390 // NewPrivateDebugAPI creates a new API definition for the private debug methods 1391 // of the Ethereum service. 1392 func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI { 1393 return &PrivateDebugAPI{b: b} 1394 } 1395 1396 // ChaindbProperty returns leveldb properties of the chain database. 1397 func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) { 1398 ldb, ok := api.b.ChainDb().(interface { 1399 LDB() *leveldb.DB 1400 }) 1401 if !ok { 1402 return "", fmt.Errorf("chaindbProperty does not work for memory databases") 1403 } 1404 if property == "" { 1405 property = "leveldb.stats" 1406 } else if !strings.HasPrefix(property, "leveldb.") { 1407 property = "leveldb." + property 1408 } 1409 return ldb.LDB().GetProperty(property) 1410 } 1411 1412 func (api *PrivateDebugAPI) ChaindbCompact() error { 1413 ldb, ok := api.b.ChainDb().(interface { 1414 LDB() *leveldb.DB 1415 }) 1416 if !ok { 1417 return fmt.Errorf("chaindbCompact does not work for memory databases") 1418 } 1419 for b := byte(0); b < 255; b++ { 1420 log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) 1421 err := ldb.LDB().CompactRange(util.Range{Start: []byte{b}, Limit: []byte{b + 1}}) 1422 if err != nil { 1423 log.Error("Database compaction failed", "err", err) 1424 return err 1425 } 1426 } 1427 return nil 1428 } 1429 1430 // SetHead rewinds the head of the blockchain to a previous block. 1431 func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) { 1432 api.b.SetHead(uint64(number)) 1433 } 1434 1435 // PublicNetAPI offers network related RPC methods 1436 type PublicNetAPI struct { 1437 net *p2p.Server 1438 networkVersion int 1439 } 1440 1441 // NewPublicNetAPI creates a new net API instance. 1442 func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI { 1443 return &PublicNetAPI{net, networkVersion} 1444 } 1445 1446 // Listening returns an indication if the node is listening for network connections. 1447 func (s *PublicNetAPI) Listening() bool { 1448 return true // always listening 1449 } 1450 1451 // PeerCount returns the number of connected peers 1452 func (s *PublicNetAPI) PeerCount() hexutil.Uint { 1453 return hexutil.Uint(s.net.PeerCount()) 1454 } 1455 1456 // Version returns the current ethereum protocol version. 1457 func (s *PublicNetAPI) Version() string { 1458 return fmt.Sprintf("%d", s.networkVersion) 1459 }