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