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