api.go 51 KB

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