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