api.go 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package eth
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "math/big"
  25. "os"
  26. "sync"
  27. "time"
  28. "github.com/ethereum/ethash"
  29. "github.com/ethereum/go-ethereum/accounts"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/common/compiler"
  32. "github.com/ethereum/go-ethereum/core"
  33. "github.com/ethereum/go-ethereum/core/state"
  34. "github.com/ethereum/go-ethereum/core/types"
  35. "github.com/ethereum/go-ethereum/core/vm"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. "github.com/ethereum/go-ethereum/ethdb"
  38. "github.com/ethereum/go-ethereum/event"
  39. "github.com/ethereum/go-ethereum/logger"
  40. "github.com/ethereum/go-ethereum/logger/glog"
  41. "github.com/ethereum/go-ethereum/miner"
  42. "github.com/ethereum/go-ethereum/p2p"
  43. "github.com/ethereum/go-ethereum/rlp"
  44. "github.com/ethereum/go-ethereum/rpc"
  45. "gopkg.in/fatih/set.v0"
  46. )
  47. const defaultGas = uint64(90000)
  48. // blockByNumber is a commonly used helper function which retrieves and returns
  49. // the block for the given block number, capable of handling two special blocks:
  50. // rpc.LatestBlockNumber and rpc.PendingBlockNumber. It returns nil when no block
  51. // could be found.
  52. func blockByNumber(m *miner.Miner, bc *core.BlockChain, blockNr rpc.BlockNumber) *types.Block {
  53. // Pending block is only known by the miner
  54. if blockNr == rpc.PendingBlockNumber {
  55. block, _ := m.Pending()
  56. return block
  57. }
  58. // Otherwise resolve and return the block
  59. if blockNr == rpc.LatestBlockNumber {
  60. return bc.CurrentBlock()
  61. }
  62. return bc.GetBlockByNumber(uint64(blockNr))
  63. }
  64. // stateAndBlockByNumber is a commonly used helper function which retrieves and
  65. // returns the state and containing block for the given block number, capable of
  66. // handling two special states: rpc.LatestBlockNumber and rpc.PendingBlockNumber.
  67. // It returns nil when no block or state could be found.
  68. func stateAndBlockByNumber(m *miner.Miner, bc *core.BlockChain, blockNr rpc.BlockNumber, chainDb ethdb.Database) (*state.StateDB, *types.Block, error) {
  69. // Pending state is only known by the miner
  70. if blockNr == rpc.PendingBlockNumber {
  71. block, state := m.Pending()
  72. return state, block, nil
  73. }
  74. // Otherwise resolve the block number and return its state
  75. block := blockByNumber(m, bc, blockNr)
  76. if block == nil {
  77. return nil, nil, nil
  78. }
  79. stateDb, err := state.New(block.Root(), chainDb)
  80. return stateDb, block, err
  81. }
  82. // PublicEthereumAPI provides an API to access Ethereum related information.
  83. // It offers only methods that operate on public data that is freely available to anyone.
  84. type PublicEthereumAPI struct {
  85. e *Ethereum
  86. gpo *GasPriceOracle
  87. }
  88. // NewPublicEthereumAPI creates a new Ethereum protocol API.
  89. func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
  90. return &PublicEthereumAPI{e, NewGasPriceOracle(e)}
  91. }
  92. // GasPrice returns a suggestion for a gas price.
  93. func (s *PublicEthereumAPI) GasPrice() *big.Int {
  94. return s.gpo.SuggestPrice()
  95. }
  96. // GetCompilers returns the collection of available smart contract compilers
  97. func (s *PublicEthereumAPI) GetCompilers() ([]string, error) {
  98. solc, err := s.e.Solc()
  99. if err != nil {
  100. return nil, err
  101. }
  102. if solc != nil {
  103. return []string{"Solidity"}, nil
  104. }
  105. return []string{}, nil
  106. }
  107. // CompileSolidity compiles the given solidity source
  108. func (s *PublicEthereumAPI) CompileSolidity(source string) (map[string]*compiler.Contract, error) {
  109. solc, err := s.e.Solc()
  110. if err != nil {
  111. return nil, err
  112. }
  113. if solc == nil {
  114. return nil, errors.New("solc (solidity compiler) not found")
  115. }
  116. return solc.Compile(source)
  117. }
  118. // Etherbase is the address that mining rewards will be send to
  119. func (s *PublicEthereumAPI) Etherbase() (common.Address, error) {
  120. return s.e.Etherbase()
  121. }
  122. // see Etherbase
  123. func (s *PublicEthereumAPI) Coinbase() (common.Address, error) {
  124. return s.Etherbase()
  125. }
  126. // ProtocolVersion returns the current Ethereum protocol version this node supports
  127. func (s *PublicEthereumAPI) ProtocolVersion() *rpc.HexNumber {
  128. return rpc.NewHexNumber(s.e.EthVersion())
  129. }
  130. // Hashrate returns the POW hashrate
  131. func (s *PublicEthereumAPI) Hashrate() *rpc.HexNumber {
  132. return rpc.NewHexNumber(s.e.Miner().HashRate())
  133. }
  134. // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
  135. // yet received the latest block headers from its pears. In case it is synchronizing:
  136. // - startingBlock: block number this node started to synchronise from
  137. // - currentBlock: block number this node is currently importing
  138. // - highestBlock: block number of the highest block header this node has received from peers
  139. // - pulledStates: number of state entries processed until now
  140. // - knownStates: number of known state entries that still need to be pulled
  141. func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
  142. origin, current, height, pulled, known := s.e.Downloader().Progress()
  143. // Return not syncing if the synchronisation already completed
  144. if current >= height {
  145. return false, nil
  146. }
  147. // Otherwise gather the block sync stats
  148. return map[string]interface{}{
  149. "startingBlock": rpc.NewHexNumber(origin),
  150. "currentBlock": rpc.NewHexNumber(current),
  151. "highestBlock": rpc.NewHexNumber(height),
  152. "pulledStates": rpc.NewHexNumber(pulled),
  153. "knownStates": rpc.NewHexNumber(known),
  154. }, nil
  155. }
  156. // PublicMinerAPI provides an API to control the miner.
  157. // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
  158. type PublicMinerAPI struct {
  159. e *Ethereum
  160. agent *miner.RemoteAgent
  161. }
  162. // NewPublicMinerAPI create a new PublicMinerAPI instance.
  163. func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
  164. agent := miner.NewRemoteAgent()
  165. e.Miner().Register(agent)
  166. return &PublicMinerAPI{e, agent}
  167. }
  168. // Mining returns an indication if this node is currently mining.
  169. func (s *PublicMinerAPI) Mining() bool {
  170. return s.e.IsMining()
  171. }
  172. // SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was
  173. // accepted. Note, this is not an indication if the provided work was valid!
  174. func (s *PublicMinerAPI) SubmitWork(nonce rpc.HexNumber, solution, digest common.Hash) bool {
  175. return s.agent.SubmitWork(nonce.Uint64(), digest, solution)
  176. }
  177. // GetWork returns a work package for external miner. The work package consists of 3 strings
  178. // result[0], 32 bytes hex encoded current block header pow-hash
  179. // result[1], 32 bytes hex encoded seed hash used for DAG
  180. // result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
  181. func (s *PublicMinerAPI) GetWork() ([]string, error) {
  182. if !s.e.IsMining() {
  183. if err := s.e.StartMining(0, ""); err != nil {
  184. return nil, err
  185. }
  186. }
  187. if work, err := s.agent.GetWork(); err == nil {
  188. return work[:], nil
  189. } else {
  190. glog.Infof("%v\n", err)
  191. }
  192. return nil, fmt.Errorf("mining not ready")
  193. }
  194. // SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined
  195. // hash rate of all miners which submit work through this node. It accepts the miner hash rate and an identifier which
  196. // must be unique between nodes.
  197. func (s *PublicMinerAPI) SubmitHashrate(hashrate rpc.HexNumber, id common.Hash) bool {
  198. s.agent.SubmitHashrate(id, hashrate.Uint64())
  199. return true
  200. }
  201. // PrivateMinerAPI provides private RPC methods to control the miner.
  202. // These methods can be abused by external users and must be considered insecure for use by untrusted users.
  203. type PrivateMinerAPI struct {
  204. e *Ethereum
  205. }
  206. // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
  207. func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
  208. return &PrivateMinerAPI{e: e}
  209. }
  210. // Start the miner with the given number of threads
  211. func (s *PrivateMinerAPI) Start(threads rpc.HexNumber) (bool, error) {
  212. s.e.StartAutoDAG()
  213. err := s.e.StartMining(threads.Int(), "")
  214. if err == nil {
  215. return true, nil
  216. }
  217. return false, err
  218. }
  219. // Stop the miner
  220. func (s *PrivateMinerAPI) Stop() bool {
  221. s.e.StopMining()
  222. return true
  223. }
  224. // SetExtra sets the extra data string that is included when this miner mines a block.
  225. func (s *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
  226. if err := s.e.Miner().SetExtra([]byte(extra)); err != nil {
  227. return false, err
  228. }
  229. return true, nil
  230. }
  231. // SetGasPrice sets the minimum accepted gas price for the miner.
  232. func (s *PrivateMinerAPI) SetGasPrice(gasPrice rpc.Number) bool {
  233. s.e.Miner().SetGasPrice(gasPrice.BigInt())
  234. return true
  235. }
  236. // SetEtherbase sets the etherbase of the miner
  237. func (s *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
  238. s.e.SetEtherbase(etherbase)
  239. return true
  240. }
  241. // StartAutoDAG starts auto DAG generation. This will prevent the DAG generating on epoch change
  242. // which will cause the node to stop mining during the generation process.
  243. func (s *PrivateMinerAPI) StartAutoDAG() bool {
  244. s.e.StartAutoDAG()
  245. return true
  246. }
  247. // StopAutoDAG stops auto DAG generation
  248. func (s *PrivateMinerAPI) StopAutoDAG() bool {
  249. s.e.StopAutoDAG()
  250. return true
  251. }
  252. // MakeDAG creates the new DAG for the given block number
  253. func (s *PrivateMinerAPI) MakeDAG(blockNr rpc.BlockNumber) (bool, error) {
  254. if err := ethash.MakeDAG(uint64(blockNr.Int64()), ""); err != nil {
  255. return false, err
  256. }
  257. return true, nil
  258. }
  259. // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
  260. type PublicTxPoolAPI struct {
  261. e *Ethereum
  262. }
  263. // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
  264. func NewPublicTxPoolAPI(e *Ethereum) *PublicTxPoolAPI {
  265. return &PublicTxPoolAPI{e}
  266. }
  267. // Content returns the transactions contained within the transaction pool.
  268. func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string][]*RPCTransaction {
  269. content := map[string]map[string]map[string][]*RPCTransaction{
  270. "pending": make(map[string]map[string][]*RPCTransaction),
  271. "queued": make(map[string]map[string][]*RPCTransaction),
  272. }
  273. pending, queue := s.e.TxPool().Content()
  274. // Flatten the pending transactions
  275. for account, batches := range pending {
  276. dump := make(map[string][]*RPCTransaction)
  277. for nonce, txs := range batches {
  278. nonce := fmt.Sprintf("%d", nonce)
  279. for _, tx := range txs {
  280. dump[nonce] = append(dump[nonce], newRPCPendingTransaction(tx))
  281. }
  282. }
  283. content["pending"][account.Hex()] = dump
  284. }
  285. // Flatten the queued transactions
  286. for account, batches := range queue {
  287. dump := make(map[string][]*RPCTransaction)
  288. for nonce, txs := range batches {
  289. nonce := fmt.Sprintf("%d", nonce)
  290. for _, tx := range txs {
  291. dump[nonce] = append(dump[nonce], newRPCPendingTransaction(tx))
  292. }
  293. }
  294. content["queued"][account.Hex()] = dump
  295. }
  296. return content
  297. }
  298. // Status returns the number of pending and queued transaction in the pool.
  299. func (s *PublicTxPoolAPI) Status() map[string]*rpc.HexNumber {
  300. pending, queue := s.e.TxPool().Stats()
  301. return map[string]*rpc.HexNumber{
  302. "pending": rpc.NewHexNumber(pending),
  303. "queued": rpc.NewHexNumber(queue),
  304. }
  305. }
  306. // Inspect retrieves the content of the transaction pool and flattens it into an
  307. // easily inspectable list.
  308. func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string][]string {
  309. content := map[string]map[string]map[string][]string{
  310. "pending": make(map[string]map[string][]string),
  311. "queued": make(map[string]map[string][]string),
  312. }
  313. pending, queue := s.e.TxPool().Content()
  314. // Define a formatter to flatten a transaction into a string
  315. var format = func(tx *types.Transaction) string {
  316. if to := tx.To(); to != nil {
  317. return fmt.Sprintf("%s: %v wei + %v × %v gas", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
  318. }
  319. return fmt.Sprintf("contract creation: %v wei + %v × %v gas", tx.Value(), tx.Gas(), tx.GasPrice())
  320. }
  321. // Flatten the pending transactions
  322. for account, batches := range pending {
  323. dump := make(map[string][]string)
  324. for nonce, txs := range batches {
  325. nonce := fmt.Sprintf("%d", nonce)
  326. for _, tx := range txs {
  327. dump[nonce] = append(dump[nonce], format(tx))
  328. }
  329. }
  330. content["pending"][account.Hex()] = dump
  331. }
  332. // Flatten the queued transactions
  333. for account, batches := range queue {
  334. dump := make(map[string][]string)
  335. for nonce, txs := range batches {
  336. nonce := fmt.Sprintf("%d", nonce)
  337. for _, tx := range txs {
  338. dump[nonce] = append(dump[nonce], format(tx))
  339. }
  340. }
  341. content["queued"][account.Hex()] = dump
  342. }
  343. return content
  344. }
  345. // PublicAccountAPI provides an API to access accounts managed by this node.
  346. // It offers only methods that can retrieve accounts.
  347. type PublicAccountAPI struct {
  348. am *accounts.Manager
  349. }
  350. // NewPublicAccountAPI creates a new PublicAccountAPI.
  351. func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
  352. return &PublicAccountAPI{am: am}
  353. }
  354. // Accounts returns the collection of accounts this node manages
  355. func (s *PublicAccountAPI) Accounts() ([]accounts.Account, error) {
  356. return s.am.Accounts()
  357. }
  358. // PrivateAccountAPI provides an API to access accounts managed by this node.
  359. // It offers methods to create, (un)lock en list accounts.
  360. type PrivateAccountAPI struct {
  361. am *accounts.Manager
  362. }
  363. // NewPrivateAccountAPI create a new PrivateAccountAPI.
  364. func NewPrivateAccountAPI(am *accounts.Manager) *PrivateAccountAPI {
  365. return &PrivateAccountAPI{am}
  366. }
  367. // ListAccounts will return a list of addresses for accounts this node manages.
  368. func (s *PrivateAccountAPI) ListAccounts() ([]common.Address, error) {
  369. accounts, err := s.am.Accounts()
  370. if err != nil {
  371. return nil, err
  372. }
  373. addresses := make([]common.Address, len(accounts))
  374. for i, acc := range accounts {
  375. addresses[i] = acc.Address
  376. }
  377. return addresses, nil
  378. }
  379. // NewAccount will create a new account and returns the address for the new account.
  380. func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
  381. acc, err := s.am.NewAccount(password)
  382. if err == nil {
  383. return acc.Address, nil
  384. }
  385. return common.Address{}, err
  386. }
  387. // UnlockAccount will unlock the account associated with the given address with the given password for duration seconds.
  388. // It returns an indication if the action was successful.
  389. func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration int) bool {
  390. if err := s.am.TimedUnlock(addr, password, time.Duration(duration)*time.Second); err != nil {
  391. glog.V(logger.Info).Infof("%v\n", err)
  392. return false
  393. }
  394. return true
  395. }
  396. // LockAccount will lock the account associated with the given address when it's unlocked.
  397. func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
  398. return s.am.Lock(addr) == nil
  399. }
  400. // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
  401. // It offers only methods that operate on public data that is freely available to anyone.
  402. type PublicBlockChainAPI struct {
  403. config *core.ChainConfig
  404. bc *core.BlockChain
  405. chainDb ethdb.Database
  406. eventMux *event.TypeMux
  407. am *accounts.Manager
  408. miner *miner.Miner
  409. }
  410. // NewPublicBlockChainAPI creates a new Etheruem blockchain API.
  411. func NewPublicBlockChainAPI(config *core.ChainConfig, bc *core.BlockChain, m *miner.Miner, chainDb ethdb.Database, eventMux *event.TypeMux, am *accounts.Manager) *PublicBlockChainAPI {
  412. return &PublicBlockChainAPI{config: config, bc: bc, miner: m, chainDb: chainDb, eventMux: eventMux, am: am}
  413. }
  414. // BlockNumber returns the block number of the chain head.
  415. func (s *PublicBlockChainAPI) BlockNumber() *big.Int {
  416. return s.bc.CurrentHeader().Number
  417. }
  418. // GetBalance returns the amount of wei for the given address in the state of the
  419. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  420. // block numbers are also allowed.
  421. func (s *PublicBlockChainAPI) GetBalance(address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) {
  422. state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  423. if state == nil || err != nil {
  424. return nil, err
  425. }
  426. return state.GetBalance(address), nil
  427. }
  428. // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
  429. // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  430. func (s *PublicBlockChainAPI) GetBlockByNumber(blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  431. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  432. response, err := s.rpcOutputBlock(block, true, fullTx)
  433. if err == nil && blockNr == rpc.PendingBlockNumber {
  434. // Pending blocks need to nil out a few fields
  435. for _, field := range []string{"hash", "nonce", "logsBloom", "miner"} {
  436. response[field] = nil
  437. }
  438. }
  439. return response, err
  440. }
  441. return nil, nil
  442. }
  443. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  444. // detail, otherwise only the transaction hash is returned.
  445. func (s *PublicBlockChainAPI) GetBlockByHash(blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
  446. if block := s.bc.GetBlock(blockHash); block != nil {
  447. return s.rpcOutputBlock(block, true, fullTx)
  448. }
  449. return nil, nil
  450. }
  451. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  452. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  453. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(blockNr rpc.BlockNumber, index rpc.HexNumber) (map[string]interface{}, error) {
  454. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  455. uncles := block.Uncles()
  456. if index.Int() < 0 || index.Int() >= len(uncles) {
  457. glog.V(logger.Debug).Infof("uncle block on index %d not found for block #%d", index.Int(), blockNr)
  458. return nil, nil
  459. }
  460. block = types.NewBlockWithHeader(uncles[index.Int()])
  461. return s.rpcOutputBlock(block, false, false)
  462. }
  463. return nil, nil
  464. }
  465. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  466. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  467. func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(blockHash common.Hash, index rpc.HexNumber) (map[string]interface{}, error) {
  468. if block := s.bc.GetBlock(blockHash); block != nil {
  469. uncles := block.Uncles()
  470. if index.Int() < 0 || index.Int() >= len(uncles) {
  471. glog.V(logger.Debug).Infof("uncle block on index %d not found for block %s", index.Int(), blockHash.Hex())
  472. return nil, nil
  473. }
  474. block = types.NewBlockWithHeader(uncles[index.Int()])
  475. return s.rpcOutputBlock(block, false, false)
  476. }
  477. return nil, nil
  478. }
  479. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  480. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(blockNr rpc.BlockNumber) *rpc.HexNumber {
  481. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  482. return rpc.NewHexNumber(len(block.Uncles()))
  483. }
  484. return nil
  485. }
  486. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  487. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(blockHash common.Hash) *rpc.HexNumber {
  488. if block := s.bc.GetBlock(blockHash); block != nil {
  489. return rpc.NewHexNumber(len(block.Uncles()))
  490. }
  491. return nil
  492. }
  493. // NewBlocksArgs allows the user to specify if the returned block should include transactions and in which format.
  494. type NewBlocksArgs struct {
  495. IncludeTransactions bool `json:"includeTransactions"`
  496. TransactionDetails bool `json:"transactionDetails"`
  497. }
  498. // NewBlocks triggers a new block event each time a block is appended to the chain. It accepts an argument which allows
  499. // the caller to specify whether the output should contain transactions and in what format.
  500. func (s *PublicBlockChainAPI) NewBlocks(args NewBlocksArgs) (rpc.Subscription, error) {
  501. sub := s.eventMux.Subscribe(core.ChainEvent{})
  502. output := func(rawBlock interface{}) interface{} {
  503. if event, ok := rawBlock.(core.ChainEvent); ok {
  504. notification, err := s.rpcOutputBlock(event.Block, args.IncludeTransactions, args.TransactionDetails)
  505. if err == nil {
  506. return notification
  507. }
  508. }
  509. return rawBlock
  510. }
  511. return rpc.NewSubscriptionWithOutputFormat(sub, output), nil
  512. }
  513. // GetCode returns the code stored at the given address in the state for the given block number.
  514. func (s *PublicBlockChainAPI) GetCode(address common.Address, blockNr rpc.BlockNumber) (string, error) {
  515. state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  516. if state == nil || err != nil {
  517. return "", err
  518. }
  519. res := state.GetCode(address)
  520. if len(res) == 0 { // backwards compatibility
  521. return "0x", nil
  522. }
  523. return common.ToHex(res), nil
  524. }
  525. // GetStorageAt returns the storage from the state at the given address, key and
  526. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  527. // numbers are also allowed.
  528. func (s *PublicBlockChainAPI) GetStorageAt(address common.Address, key string, blockNr rpc.BlockNumber) (string, error) {
  529. state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  530. if state == nil || err != nil {
  531. return "0x", err
  532. }
  533. return state.GetState(address, common.HexToHash(key)).Hex(), nil
  534. }
  535. // callmsg is the message type used for call transactions.
  536. type callmsg struct {
  537. from *state.StateObject
  538. to *common.Address
  539. gas, gasPrice *big.Int
  540. value *big.Int
  541. data []byte
  542. }
  543. // accessor boilerplate to implement core.Message
  544. func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
  545. func (m callmsg) FromFrontier() (common.Address, error) { return m.from.Address(), nil }
  546. func (m callmsg) Nonce() uint64 { return m.from.Nonce() }
  547. func (m callmsg) To() *common.Address { return m.to }
  548. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  549. func (m callmsg) Gas() *big.Int { return m.gas }
  550. func (m callmsg) Value() *big.Int { return m.value }
  551. func (m callmsg) Data() []byte { return m.data }
  552. type CallArgs struct {
  553. From common.Address `json:"from"`
  554. To *common.Address `json:"to"`
  555. Gas rpc.HexNumber `json:"gas"`
  556. GasPrice rpc.HexNumber `json:"gasPrice"`
  557. Value rpc.HexNumber `json:"value"`
  558. Data string `json:"data"`
  559. }
  560. func (s *PublicBlockChainAPI) doCall(args CallArgs, blockNr rpc.BlockNumber) (string, *big.Int, error) {
  561. // Fetch the state associated with the block number
  562. stateDb, block, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  563. if stateDb == nil || err != nil {
  564. return "0x", nil, err
  565. }
  566. stateDb = stateDb.Copy()
  567. // Retrieve the account state object to interact with
  568. var from *state.StateObject
  569. if args.From == (common.Address{}) {
  570. accounts, err := s.am.Accounts()
  571. if err != nil || len(accounts) == 0 {
  572. from = stateDb.GetOrNewStateObject(common.Address{})
  573. } else {
  574. from = stateDb.GetOrNewStateObject(accounts[0].Address)
  575. }
  576. } else {
  577. from = stateDb.GetOrNewStateObject(args.From)
  578. }
  579. from.SetBalance(common.MaxBig)
  580. // Assemble the CALL invocation
  581. msg := callmsg{
  582. from: from,
  583. to: args.To,
  584. gas: args.Gas.BigInt(),
  585. gasPrice: args.GasPrice.BigInt(),
  586. value: args.Value.BigInt(),
  587. data: common.FromHex(args.Data),
  588. }
  589. if msg.gas.Cmp(common.Big0) == 0 {
  590. msg.gas = big.NewInt(50000000)
  591. }
  592. if msg.gasPrice.Cmp(common.Big0) == 0 {
  593. msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
  594. }
  595. // Execute the call and return
  596. vmenv := core.NewEnv(stateDb, s.config, s.bc, msg, block.Header(), s.config.VmConfig)
  597. gp := new(core.GasPool).AddGas(common.MaxBig)
  598. res, gas, err := core.ApplyMessage(vmenv, msg, gp)
  599. if len(res) == 0 { // backwards compatibility
  600. return "0x", gas, err
  601. }
  602. return common.ToHex(res), gas, err
  603. }
  604. // Call executes the given transaction on the state for the given block number.
  605. // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
  606. func (s *PublicBlockChainAPI) Call(args CallArgs, blockNr rpc.BlockNumber) (string, error) {
  607. result, _, err := s.doCall(args, blockNr)
  608. return result, err
  609. }
  610. // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
  611. func (s *PublicBlockChainAPI) EstimateGas(args CallArgs) (*rpc.HexNumber, error) {
  612. _, gas, err := s.doCall(args, rpc.PendingBlockNumber)
  613. return rpc.NewHexNumber(gas), err
  614. }
  615. // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  616. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  617. // transaction hashes.
  618. func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  619. fields := map[string]interface{}{
  620. "number": rpc.NewHexNumber(b.Number()),
  621. "hash": b.Hash(),
  622. "parentHash": b.ParentHash(),
  623. "nonce": b.Header().Nonce,
  624. "sha3Uncles": b.UncleHash(),
  625. "logsBloom": b.Bloom(),
  626. "stateRoot": b.Root(),
  627. "miner": b.Coinbase(),
  628. "difficulty": rpc.NewHexNumber(b.Difficulty()),
  629. "totalDifficulty": rpc.NewHexNumber(s.bc.GetTd(b.Hash())),
  630. "extraData": fmt.Sprintf("0x%x", b.Extra()),
  631. "size": rpc.NewHexNumber(b.Size().Int64()),
  632. "gasLimit": rpc.NewHexNumber(b.GasLimit()),
  633. "gasUsed": rpc.NewHexNumber(b.GasUsed()),
  634. "timestamp": rpc.NewHexNumber(b.Time()),
  635. "transactionsRoot": b.TxHash(),
  636. "receiptRoot": b.ReceiptHash(),
  637. }
  638. if inclTx {
  639. formatTx := func(tx *types.Transaction) (interface{}, error) {
  640. return tx.Hash(), nil
  641. }
  642. if fullTx {
  643. formatTx = func(tx *types.Transaction) (interface{}, error) {
  644. return newRPCTransaction(b, tx.Hash())
  645. }
  646. }
  647. txs := b.Transactions()
  648. transactions := make([]interface{}, len(txs))
  649. var err error
  650. for i, tx := range b.Transactions() {
  651. if transactions[i], err = formatTx(tx); err != nil {
  652. return nil, err
  653. }
  654. }
  655. fields["transactions"] = transactions
  656. }
  657. uncles := b.Uncles()
  658. uncleHashes := make([]common.Hash, len(uncles))
  659. for i, uncle := range uncles {
  660. uncleHashes[i] = uncle.Hash()
  661. }
  662. fields["uncles"] = uncleHashes
  663. return fields, nil
  664. }
  665. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  666. type RPCTransaction struct {
  667. BlockHash common.Hash `json:"blockHash"`
  668. BlockNumber *rpc.HexNumber `json:"blockNumber"`
  669. From common.Address `json:"from"`
  670. Gas *rpc.HexNumber `json:"gas"`
  671. GasPrice *rpc.HexNumber `json:"gasPrice"`
  672. Hash common.Hash `json:"hash"`
  673. Input string `json:"input"`
  674. Nonce *rpc.HexNumber `json:"nonce"`
  675. To *common.Address `json:"to"`
  676. TransactionIndex *rpc.HexNumber `json:"transactionIndex"`
  677. Value *rpc.HexNumber `json:"value"`
  678. }
  679. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  680. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  681. from, _ := tx.FromFrontier()
  682. return &RPCTransaction{
  683. From: from,
  684. Gas: rpc.NewHexNumber(tx.Gas()),
  685. GasPrice: rpc.NewHexNumber(tx.GasPrice()),
  686. Hash: tx.Hash(),
  687. Input: fmt.Sprintf("0x%x", tx.Data()),
  688. Nonce: rpc.NewHexNumber(tx.Nonce()),
  689. To: tx.To(),
  690. Value: rpc.NewHexNumber(tx.Value()),
  691. }
  692. }
  693. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  694. func newRPCTransactionFromBlockIndex(b *types.Block, txIndex int) (*RPCTransaction, error) {
  695. if txIndex >= 0 && txIndex < len(b.Transactions()) {
  696. tx := b.Transactions()[txIndex]
  697. from, err := tx.FromFrontier()
  698. if err != nil {
  699. return nil, err
  700. }
  701. return &RPCTransaction{
  702. BlockHash: b.Hash(),
  703. BlockNumber: rpc.NewHexNumber(b.Number()),
  704. From: from,
  705. Gas: rpc.NewHexNumber(tx.Gas()),
  706. GasPrice: rpc.NewHexNumber(tx.GasPrice()),
  707. Hash: tx.Hash(),
  708. Input: fmt.Sprintf("0x%x", tx.Data()),
  709. Nonce: rpc.NewHexNumber(tx.Nonce()),
  710. To: tx.To(),
  711. TransactionIndex: rpc.NewHexNumber(txIndex),
  712. Value: rpc.NewHexNumber(tx.Value()),
  713. }, nil
  714. }
  715. return nil, nil
  716. }
  717. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  718. func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) {
  719. for idx, tx := range b.Transactions() {
  720. if tx.Hash() == txHash {
  721. return newRPCTransactionFromBlockIndex(b, idx)
  722. }
  723. }
  724. return nil, nil
  725. }
  726. // PublicTransactionPoolAPI exposes methods for the RPC interface
  727. type PublicTransactionPoolAPI struct {
  728. eventMux *event.TypeMux
  729. chainDb ethdb.Database
  730. gpo *GasPriceOracle
  731. bc *core.BlockChain
  732. miner *miner.Miner
  733. am *accounts.Manager
  734. txPool *core.TxPool
  735. txMu sync.Mutex
  736. }
  737. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  738. func NewPublicTransactionPoolAPI(e *Ethereum) *PublicTransactionPoolAPI {
  739. return &PublicTransactionPoolAPI{
  740. eventMux: e.EventMux(),
  741. gpo: NewGasPriceOracle(e),
  742. chainDb: e.ChainDb(),
  743. bc: e.BlockChain(),
  744. am: e.AccountManager(),
  745. txPool: e.TxPool(),
  746. miner: e.Miner(),
  747. }
  748. }
  749. func getTransaction(chainDb ethdb.Database, txPool *core.TxPool, txHash common.Hash) (*types.Transaction, bool, error) {
  750. txData, err := chainDb.Get(txHash.Bytes())
  751. isPending := false
  752. tx := new(types.Transaction)
  753. if err == nil && len(txData) > 0 {
  754. if err := rlp.DecodeBytes(txData, tx); err != nil {
  755. return nil, isPending, err
  756. }
  757. } else {
  758. // pending transaction?
  759. tx = txPool.GetTransaction(txHash)
  760. isPending = true
  761. }
  762. return tx, isPending, nil
  763. }
  764. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  765. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(blockNr rpc.BlockNumber) *rpc.HexNumber {
  766. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  767. return rpc.NewHexNumber(len(block.Transactions()))
  768. }
  769. return nil
  770. }
  771. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  772. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(blockHash common.Hash) *rpc.HexNumber {
  773. if block := s.bc.GetBlock(blockHash); block != nil {
  774. return rpc.NewHexNumber(len(block.Transactions()))
  775. }
  776. return nil
  777. }
  778. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  779. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(blockNr rpc.BlockNumber, index rpc.HexNumber) (*RPCTransaction, error) {
  780. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  781. return newRPCTransactionFromBlockIndex(block, index.Int())
  782. }
  783. return nil, nil
  784. }
  785. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  786. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(blockHash common.Hash, index rpc.HexNumber) (*RPCTransaction, error) {
  787. if block := s.bc.GetBlock(blockHash); block != nil {
  788. return newRPCTransactionFromBlockIndex(block, index.Int())
  789. }
  790. return nil, nil
  791. }
  792. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  793. func (s *PublicTransactionPoolAPI) GetTransactionCount(address common.Address, blockNr rpc.BlockNumber) (*rpc.HexNumber, error) {
  794. state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  795. if state == nil || err != nil {
  796. return nil, err
  797. }
  798. return rpc.NewHexNumber(state.GetNonce(address)), nil
  799. }
  800. // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to
  801. // retrieve block information for a hash. It returns the block hash, block index and transaction index.
  802. func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) {
  803. var txBlock struct {
  804. BlockHash common.Hash
  805. BlockIndex uint64
  806. Index uint64
  807. }
  808. blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001))
  809. if err != nil {
  810. return common.Hash{}, uint64(0), uint64(0), err
  811. }
  812. reader := bytes.NewReader(blockData)
  813. if err = rlp.Decode(reader, &txBlock); err != nil {
  814. return common.Hash{}, uint64(0), uint64(0), err
  815. }
  816. return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil
  817. }
  818. // GetTransactionByHash returns the transaction for the given hash
  819. func (s *PublicTransactionPoolAPI) GetTransactionByHash(txHash common.Hash) (*RPCTransaction, error) {
  820. var tx *types.Transaction
  821. var isPending bool
  822. var err error
  823. if tx, isPending, err = getTransaction(s.chainDb, s.txPool, txHash); err != nil {
  824. glog.V(logger.Debug).Infof("%v\n", err)
  825. return nil, nil
  826. } else if tx == nil {
  827. return nil, nil
  828. }
  829. if isPending {
  830. return newRPCPendingTransaction(tx), nil
  831. }
  832. blockHash, _, _, err := getTransactionBlockData(s.chainDb, txHash)
  833. if err != nil {
  834. glog.V(logger.Debug).Infof("%v\n", err)
  835. return nil, nil
  836. }
  837. if block := s.bc.GetBlock(blockHash); block != nil {
  838. return newRPCTransaction(block, txHash)
  839. }
  840. return nil, nil
  841. }
  842. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  843. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(txHash common.Hash) (map[string]interface{}, error) {
  844. receipt := core.GetReceipt(s.chainDb, txHash)
  845. if receipt == nil {
  846. glog.V(logger.Debug).Infof("receipt not found for transaction %s", txHash.Hex())
  847. return nil, nil
  848. }
  849. tx, _, err := getTransaction(s.chainDb, s.txPool, txHash)
  850. if err != nil {
  851. glog.V(logger.Debug).Infof("%v\n", err)
  852. return nil, nil
  853. }
  854. txBlock, blockIndex, index, err := getTransactionBlockData(s.chainDb, txHash)
  855. if err != nil {
  856. glog.V(logger.Debug).Infof("%v\n", err)
  857. return nil, nil
  858. }
  859. from, err := tx.FromFrontier()
  860. if err != nil {
  861. glog.V(logger.Debug).Infof("%v\n", err)
  862. return nil, nil
  863. }
  864. fields := map[string]interface{}{
  865. "root": common.Bytes2Hex(receipt.PostState),
  866. "blockHash": txBlock,
  867. "blockNumber": rpc.NewHexNumber(blockIndex),
  868. "transactionHash": txHash,
  869. "transactionIndex": rpc.NewHexNumber(index),
  870. "from": from,
  871. "to": tx.To(),
  872. "gasUsed": rpc.NewHexNumber(receipt.GasUsed),
  873. "cumulativeGasUsed": rpc.NewHexNumber(receipt.CumulativeGasUsed),
  874. "contractAddress": nil,
  875. "logs": receipt.Logs,
  876. }
  877. if receipt.Logs == nil {
  878. fields["logs"] = []vm.Logs{}
  879. }
  880. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  881. if bytes.Compare(receipt.ContractAddress.Bytes(), bytes.Repeat([]byte{0}, 20)) != 0 {
  882. fields["contractAddress"] = receipt.ContractAddress
  883. }
  884. return fields, nil
  885. }
  886. // sign is a helper function that signs a transaction with the private key of the given address.
  887. func (s *PublicTransactionPoolAPI) sign(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
  888. acc := accounts.Account{address}
  889. signature, err := s.am.Sign(acc, tx.SigHash().Bytes())
  890. if err != nil {
  891. return nil, err
  892. }
  893. return tx.WithSignature(signature)
  894. }
  895. type SendTxArgs struct {
  896. From common.Address `json:"from"`
  897. To *common.Address `json:"to"`
  898. Gas *rpc.HexNumber `json:"gas"`
  899. GasPrice *rpc.HexNumber `json:"gasPrice"`
  900. Value *rpc.HexNumber `json:"value"`
  901. Data string `json:"data"`
  902. Nonce *rpc.HexNumber `json:"nonce"`
  903. }
  904. // SendTransaction will create a transaction for the given transaction argument, sign it and submit it to the
  905. // transaction pool.
  906. func (s *PublicTransactionPoolAPI) SendTransaction(args SendTxArgs) (common.Hash, error) {
  907. if args.Gas == nil {
  908. args.Gas = rpc.NewHexNumber(defaultGas)
  909. }
  910. if args.GasPrice == nil {
  911. args.GasPrice = rpc.NewHexNumber(s.gpo.SuggestPrice())
  912. }
  913. if args.Value == nil {
  914. args.Value = rpc.NewHexNumber(0)
  915. }
  916. s.txMu.Lock()
  917. defer s.txMu.Unlock()
  918. if args.Nonce == nil {
  919. args.Nonce = rpc.NewHexNumber(s.txPool.State().GetNonce(args.From))
  920. }
  921. var tx *types.Transaction
  922. contractCreation := (args.To == nil)
  923. if contractCreation {
  924. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  925. } else {
  926. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  927. }
  928. signedTx, err := s.sign(args.From, tx)
  929. if err != nil {
  930. return common.Hash{}, err
  931. }
  932. s.txPool.SetLocal(signedTx)
  933. if err := s.txPool.Add(signedTx); err != nil {
  934. return common.Hash{}, err
  935. }
  936. if contractCreation {
  937. addr := crypto.CreateAddress(args.From, args.Nonce.Uint64())
  938. glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signedTx.Hash().Hex(), addr.Hex())
  939. } else {
  940. glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signedTx.Hash().Hex(), tx.To().Hex())
  941. }
  942. return signedTx.Hash(), nil
  943. }
  944. // SendRawTransaction will add the signed transaction to the transaction pool.
  945. // The sender is responsible for signing the transaction and using the correct nonce.
  946. func (s *PublicTransactionPoolAPI) SendRawTransaction(encodedTx string) (string, error) {
  947. tx := new(types.Transaction)
  948. if err := rlp.DecodeBytes(common.FromHex(encodedTx), tx); err != nil {
  949. return "", err
  950. }
  951. s.txPool.SetLocal(tx)
  952. if err := s.txPool.Add(tx); err != nil {
  953. return "", err
  954. }
  955. if tx.To() == nil {
  956. from, err := tx.FromFrontier()
  957. if err != nil {
  958. return "", err
  959. }
  960. addr := crypto.CreateAddress(from, tx.Nonce())
  961. glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr)
  962. } else {
  963. glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To())
  964. }
  965. return tx.Hash().Hex(), nil
  966. }
  967. // Sign will sign the given data string with the given address. The account corresponding with the address needs to
  968. // be unlocked.
  969. func (s *PublicTransactionPoolAPI) Sign(address common.Address, data string) (string, error) {
  970. signature, error := s.am.Sign(accounts.Account{Address: address}, common.HexToHash(data).Bytes())
  971. return common.ToHex(signature), error
  972. }
  973. type SignTransactionArgs struct {
  974. From common.Address
  975. To *common.Address
  976. Nonce *rpc.HexNumber
  977. Value *rpc.HexNumber
  978. Gas *rpc.HexNumber
  979. GasPrice *rpc.HexNumber
  980. Data string
  981. BlockNumber int64
  982. }
  983. // Tx is a helper object for argument and return values
  984. type Tx struct {
  985. tx *types.Transaction
  986. To *common.Address `json:"to"`
  987. From common.Address `json:"from"`
  988. Nonce *rpc.HexNumber `json:"nonce"`
  989. Value *rpc.HexNumber `json:"value"`
  990. Data string `json:"data"`
  991. GasLimit *rpc.HexNumber `json:"gas"`
  992. GasPrice *rpc.HexNumber `json:"gasPrice"`
  993. Hash common.Hash `json:"hash"`
  994. }
  995. func (tx *Tx) UnmarshalJSON(b []byte) (err error) {
  996. req := struct {
  997. To *common.Address `json:"to"`
  998. From common.Address `json:"from"`
  999. Nonce *rpc.HexNumber `json:"nonce"`
  1000. Value *rpc.HexNumber `json:"value"`
  1001. Data string `json:"data"`
  1002. GasLimit *rpc.HexNumber `json:"gas"`
  1003. GasPrice *rpc.HexNumber `json:"gasPrice"`
  1004. Hash common.Hash `json:"hash"`
  1005. }{}
  1006. if err := json.Unmarshal(b, &req); err != nil {
  1007. return err
  1008. }
  1009. tx.To = req.To
  1010. tx.From = req.From
  1011. tx.Nonce = req.Nonce
  1012. tx.Value = req.Value
  1013. tx.Data = req.Data
  1014. tx.GasLimit = req.GasLimit
  1015. tx.GasPrice = req.GasPrice
  1016. tx.Hash = req.Hash
  1017. data := common.Hex2Bytes(tx.Data)
  1018. if tx.Nonce == nil {
  1019. return fmt.Errorf("need nonce")
  1020. }
  1021. if tx.Value == nil {
  1022. tx.Value = rpc.NewHexNumber(0)
  1023. }
  1024. if tx.GasLimit == nil {
  1025. tx.GasLimit = rpc.NewHexNumber(0)
  1026. }
  1027. if tx.GasPrice == nil {
  1028. tx.GasPrice = rpc.NewHexNumber(int64(50000000000))
  1029. }
  1030. contractCreation := (req.To == nil)
  1031. if contractCreation {
  1032. tx.tx = types.NewContractCreation(tx.Nonce.Uint64(), tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  1033. } else {
  1034. tx.tx = types.NewTransaction(tx.Nonce.Uint64(), *tx.To, tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  1035. }
  1036. return nil
  1037. }
  1038. type SignTransactionResult struct {
  1039. Raw string `json:"raw"`
  1040. Tx *Tx `json:"tx"`
  1041. }
  1042. func newTx(t *types.Transaction) *Tx {
  1043. from, _ := t.FromFrontier()
  1044. return &Tx{
  1045. tx: t,
  1046. To: t.To(),
  1047. From: from,
  1048. Value: rpc.NewHexNumber(t.Value()),
  1049. Nonce: rpc.NewHexNumber(t.Nonce()),
  1050. Data: "0x" + common.Bytes2Hex(t.Data()),
  1051. GasLimit: rpc.NewHexNumber(t.Gas()),
  1052. GasPrice: rpc.NewHexNumber(t.GasPrice()),
  1053. Hash: t.Hash(),
  1054. }
  1055. }
  1056. // SignTransaction will sign the given transaction with the from account.
  1057. // The node needs to have the private key of the account corresponding with
  1058. // the given from address and it needs to be unlocked.
  1059. func (s *PublicTransactionPoolAPI) SignTransaction(args *SignTransactionArgs) (*SignTransactionResult, error) {
  1060. if args.Gas == nil {
  1061. args.Gas = rpc.NewHexNumber(defaultGas)
  1062. }
  1063. if args.GasPrice == nil {
  1064. args.GasPrice = rpc.NewHexNumber(s.gpo.SuggestPrice())
  1065. }
  1066. if args.Value == nil {
  1067. args.Value = rpc.NewHexNumber(0)
  1068. }
  1069. s.txMu.Lock()
  1070. defer s.txMu.Unlock()
  1071. if args.Nonce == nil {
  1072. args.Nonce = rpc.NewHexNumber(s.txPool.State().GetNonce(args.From))
  1073. }
  1074. var tx *types.Transaction
  1075. contractCreation := (args.To == nil)
  1076. if contractCreation {
  1077. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1078. } else {
  1079. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1080. }
  1081. signedTx, err := s.sign(args.From, tx)
  1082. if err != nil {
  1083. return nil, err
  1084. }
  1085. data, err := rlp.EncodeToBytes(signedTx)
  1086. if err != nil {
  1087. return nil, err
  1088. }
  1089. return &SignTransactionResult{"0x" + common.Bytes2Hex(data), newTx(tx)}, nil
  1090. }
  1091. // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1092. // the accounts this node manages.
  1093. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1094. accounts, err := s.am.Accounts()
  1095. if err != nil {
  1096. return nil, err
  1097. }
  1098. accountSet := set.New()
  1099. for _, account := range accounts {
  1100. accountSet.Add(account.Address)
  1101. }
  1102. pending := s.txPool.GetTransactions()
  1103. transactions := make([]*RPCTransaction, 0)
  1104. for _, tx := range pending {
  1105. if from, _ := tx.FromFrontier(); accountSet.Has(from) {
  1106. transactions = append(transactions, newRPCPendingTransaction(tx))
  1107. }
  1108. }
  1109. return transactions, nil
  1110. }
  1111. // NewPendingTransaction creates a subscription that is triggered each time a transaction enters the transaction pool
  1112. // and is send from one of the transactions this nodes manages.
  1113. func (s *PublicTransactionPoolAPI) NewPendingTransactions() (rpc.Subscription, error) {
  1114. sub := s.eventMux.Subscribe(core.TxPreEvent{})
  1115. accounts, err := s.am.Accounts()
  1116. if err != nil {
  1117. return rpc.Subscription{}, err
  1118. }
  1119. accountSet := set.New()
  1120. for _, account := range accounts {
  1121. accountSet.Add(account.Address)
  1122. }
  1123. accountSetLastUpdates := time.Now()
  1124. output := func(transaction interface{}) interface{} {
  1125. if time.Since(accountSetLastUpdates) > (time.Duration(2) * time.Second) {
  1126. if accounts, err = s.am.Accounts(); err != nil {
  1127. accountSet.Clear()
  1128. for _, account := range accounts {
  1129. accountSet.Add(account.Address)
  1130. }
  1131. accountSetLastUpdates = time.Now()
  1132. }
  1133. }
  1134. tx := transaction.(core.TxPreEvent)
  1135. if from, err := tx.Tx.FromFrontier(); err == nil {
  1136. if accountSet.Has(from) {
  1137. return tx.Tx.Hash()
  1138. }
  1139. }
  1140. return nil
  1141. }
  1142. return rpc.NewSubscriptionWithOutputFormat(sub, output), nil
  1143. }
  1144. // Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the
  1145. // pool and reinsert it with the new gas price and limit.
  1146. func (s *PublicTransactionPoolAPI) Resend(tx *Tx, gasPrice, gasLimit *rpc.HexNumber) (common.Hash, error) {
  1147. pending := s.txPool.GetTransactions()
  1148. for _, p := range pending {
  1149. if pFrom, err := p.FromFrontier(); err == nil && pFrom == tx.From && p.SigHash() == tx.tx.SigHash() {
  1150. if gasPrice == nil {
  1151. gasPrice = rpc.NewHexNumber(tx.tx.GasPrice())
  1152. }
  1153. if gasLimit == nil {
  1154. gasLimit = rpc.NewHexNumber(tx.tx.Gas())
  1155. }
  1156. var newTx *types.Transaction
  1157. contractCreation := (tx.tx.To() == nil)
  1158. if contractCreation {
  1159. newTx = types.NewContractCreation(tx.tx.Nonce(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1160. } else {
  1161. newTx = types.NewTransaction(tx.tx.Nonce(), *tx.tx.To(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1162. }
  1163. signedTx, err := s.sign(tx.From, newTx)
  1164. if err != nil {
  1165. return common.Hash{}, err
  1166. }
  1167. s.txPool.RemoveTx(tx.Hash)
  1168. if err = s.txPool.Add(signedTx); err != nil {
  1169. return common.Hash{}, err
  1170. }
  1171. return signedTx.Hash(), nil
  1172. }
  1173. }
  1174. return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash)
  1175. }
  1176. // PrivateAdminAPI is the collection of Etheruem APIs exposed over the private
  1177. // admin endpoint.
  1178. type PrivateAdminAPI struct {
  1179. eth *Ethereum
  1180. }
  1181. // NewPrivateAdminAPI creates a new API definition for the private admin methods
  1182. // of the Ethereum service.
  1183. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  1184. return &PrivateAdminAPI{eth: eth}
  1185. }
  1186. // SetSolc sets the Solidity compiler path to be used by the node.
  1187. func (api *PrivateAdminAPI) SetSolc(path string) (string, error) {
  1188. solc, err := api.eth.SetSolc(path)
  1189. if err != nil {
  1190. return "", err
  1191. }
  1192. return solc.Info(), nil
  1193. }
  1194. // ExportChain exports the current blockchain into a local file.
  1195. func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
  1196. // Make sure we can create the file to export into
  1197. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  1198. if err != nil {
  1199. return false, err
  1200. }
  1201. defer out.Close()
  1202. // Export the blockchain
  1203. if err := api.eth.BlockChain().Export(out); err != nil {
  1204. return false, err
  1205. }
  1206. return true, nil
  1207. }
  1208. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  1209. for _, b := range bs {
  1210. if !chain.HasBlock(b.Hash()) {
  1211. return false
  1212. }
  1213. }
  1214. return true
  1215. }
  1216. // ImportChain imports a blockchain from a local file.
  1217. func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
  1218. // Make sure the can access the file to import
  1219. in, err := os.Open(file)
  1220. if err != nil {
  1221. return false, err
  1222. }
  1223. defer in.Close()
  1224. // Run actual the import in pre-configured batches
  1225. stream := rlp.NewStream(in, 0)
  1226. blocks, index := make([]*types.Block, 0, 2500), 0
  1227. for batch := 0; ; batch++ {
  1228. // Load a batch of blocks from the input file
  1229. for len(blocks) < cap(blocks) {
  1230. block := new(types.Block)
  1231. if err := stream.Decode(block); err == io.EOF {
  1232. break
  1233. } else if err != nil {
  1234. return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
  1235. }
  1236. blocks = append(blocks, block)
  1237. index++
  1238. }
  1239. if len(blocks) == 0 {
  1240. break
  1241. }
  1242. if hasAllBlocks(api.eth.BlockChain(), blocks) {
  1243. blocks = blocks[:0]
  1244. continue
  1245. }
  1246. // Import the batch and reset the buffer
  1247. if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
  1248. return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
  1249. }
  1250. blocks = blocks[:0]
  1251. }
  1252. return true, nil
  1253. }
  1254. // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
  1255. // debugging endpoint.
  1256. type PublicDebugAPI struct {
  1257. eth *Ethereum
  1258. }
  1259. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1260. // of the Ethereum service.
  1261. func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
  1262. return &PublicDebugAPI{eth: eth}
  1263. }
  1264. // DumpBlock retrieves the entire state of the database at a given block.
  1265. func (api *PublicDebugAPI) DumpBlock(number uint64) (state.World, error) {
  1266. block := api.eth.BlockChain().GetBlockByNumber(number)
  1267. if block == nil {
  1268. return state.World{}, fmt.Errorf("block #%d not found", number)
  1269. }
  1270. stateDb, err := state.New(block.Root(), api.eth.ChainDb())
  1271. if err != nil {
  1272. return state.World{}, err
  1273. }
  1274. return stateDb.RawDump(), nil
  1275. }
  1276. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1277. func (api *PublicDebugAPI) GetBlockRlp(number uint64) (string, error) {
  1278. block := api.eth.BlockChain().GetBlockByNumber(number)
  1279. if block == nil {
  1280. return "", fmt.Errorf("block #%d not found", number)
  1281. }
  1282. encoded, err := rlp.EncodeToBytes(block)
  1283. if err != nil {
  1284. return "", err
  1285. }
  1286. return fmt.Sprintf("%x", encoded), nil
  1287. }
  1288. // PrintBlock retrieves a block and returns its pretty printed form.
  1289. func (api *PublicDebugAPI) PrintBlock(number uint64) (string, error) {
  1290. block := api.eth.BlockChain().GetBlockByNumber(number)
  1291. if block == nil {
  1292. return "", fmt.Errorf("block #%d not found", number)
  1293. }
  1294. return fmt.Sprintf("%s", block), nil
  1295. }
  1296. // SeedHash retrieves the seed hash of a block.
  1297. func (api *PublicDebugAPI) SeedHash(number uint64) (string, error) {
  1298. block := api.eth.BlockChain().GetBlockByNumber(number)
  1299. if block == nil {
  1300. return "", fmt.Errorf("block #%d not found", number)
  1301. }
  1302. hash, err := ethash.GetSeedHash(number)
  1303. if err != nil {
  1304. return "", err
  1305. }
  1306. return fmt.Sprintf("0x%x", hash), nil
  1307. }
  1308. // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private
  1309. // debugging endpoint.
  1310. type PrivateDebugAPI struct {
  1311. config *core.ChainConfig
  1312. eth *Ethereum
  1313. }
  1314. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1315. // of the Ethereum service.
  1316. func NewPrivateDebugAPI(config *core.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
  1317. return &PrivateDebugAPI{config: config, eth: eth}
  1318. }
  1319. // BlockTraceResults is the returned value when replaying a block to check for
  1320. // consensus results and full VM trace logs for all included transactions.
  1321. type BlockTraceResult struct {
  1322. Validated bool `json:"validated"`
  1323. StructLogs []structLogRes `json:"structLogs"`
  1324. Error string `json:"error"`
  1325. }
  1326. // TraceBlock processes the given block's RLP but does not import the block in to
  1327. // the chain.
  1328. func (api *PrivateDebugAPI) TraceBlock(blockRlp []byte, config vm.Config) BlockTraceResult {
  1329. var block types.Block
  1330. err := rlp.Decode(bytes.NewReader(blockRlp), &block)
  1331. if err != nil {
  1332. return BlockTraceResult{Error: fmt.Sprintf("could not decode block: %v", err)}
  1333. }
  1334. validated, logs, err := api.traceBlock(&block, config)
  1335. return BlockTraceResult{
  1336. Validated: validated,
  1337. StructLogs: formatLogs(logs),
  1338. Error: formatError(err),
  1339. }
  1340. }
  1341. // TraceBlockFromFile loads the block's RLP from the given file name and attempts to
  1342. // process it but does not import the block in to the chain.
  1343. func (api *PrivateDebugAPI) TraceBlockFromFile(file string, config vm.Config) BlockTraceResult {
  1344. blockRlp, err := ioutil.ReadFile(file)
  1345. if err != nil {
  1346. return BlockTraceResult{Error: fmt.Sprintf("could not read file: %v", err)}
  1347. }
  1348. return api.TraceBlock(blockRlp, config)
  1349. }
  1350. // TraceProcessBlock processes the block by canonical block number.
  1351. func (api *PrivateDebugAPI) TraceBlockByNumber(number uint64, config vm.Config) BlockTraceResult {
  1352. // Fetch the block that we aim to reprocess
  1353. block := api.eth.BlockChain().GetBlockByNumber(number)
  1354. if block == nil {
  1355. return BlockTraceResult{Error: fmt.Sprintf("block #%d not found", number)}
  1356. }
  1357. validated, logs, err := api.traceBlock(block, config)
  1358. return BlockTraceResult{
  1359. Validated: validated,
  1360. StructLogs: formatLogs(logs),
  1361. Error: formatError(err),
  1362. }
  1363. }
  1364. // TraceBlockByHash processes the block by hash.
  1365. func (api *PrivateDebugAPI) TraceBlockByHash(hash common.Hash, config vm.Config) BlockTraceResult {
  1366. // Fetch the block that we aim to reprocess
  1367. block := api.eth.BlockChain().GetBlock(hash)
  1368. if block == nil {
  1369. return BlockTraceResult{Error: fmt.Sprintf("block #%x not found", hash)}
  1370. }
  1371. validated, logs, err := api.traceBlock(block, config)
  1372. return BlockTraceResult{
  1373. Validated: validated,
  1374. StructLogs: formatLogs(logs),
  1375. Error: formatError(err),
  1376. }
  1377. }
  1378. // TraceCollector collects EVM structered logs.
  1379. //
  1380. // TraceCollector implements vm.Collector
  1381. type TraceCollector struct {
  1382. traces []vm.StructLog
  1383. }
  1384. // AddStructLog adds a structered log.
  1385. func (t *TraceCollector) AddStructLog(slog vm.StructLog) {
  1386. t.traces = append(t.traces, slog)
  1387. }
  1388. // traceBlock processes the given block but does not save the state.
  1389. func (api *PrivateDebugAPI) traceBlock(block *types.Block, config vm.Config) (bool, []vm.StructLog, error) {
  1390. // Validate and reprocess the block
  1391. var (
  1392. blockchain = api.eth.BlockChain()
  1393. validator = blockchain.Validator()
  1394. processor = blockchain.Processor()
  1395. collector = &TraceCollector{}
  1396. )
  1397. config.Debug = true // make sure debug is set.
  1398. config.Logger.Collector = collector
  1399. if err := core.ValidateHeader(api.config, blockchain.AuxValidator(), block.Header(), blockchain.GetHeader(block.ParentHash()), true, false); err != nil {
  1400. return false, collector.traces, err
  1401. }
  1402. statedb, err := state.New(blockchain.GetBlock(block.ParentHash()).Root(), api.eth.ChainDb())
  1403. if err != nil {
  1404. return false, collector.traces, err
  1405. }
  1406. receipts, _, usedGas, err := processor.Process(block, statedb, config)
  1407. if err != nil {
  1408. return false, collector.traces, err
  1409. }
  1410. if err := validator.ValidateState(block, blockchain.GetBlock(block.ParentHash()), statedb, receipts, usedGas); err != nil {
  1411. return false, collector.traces, err
  1412. }
  1413. return true, collector.traces, nil
  1414. }
  1415. // SetHead rewinds the head of the blockchain to a previous block.
  1416. func (api *PrivateDebugAPI) SetHead(number uint64) {
  1417. api.eth.BlockChain().SetHead(number)
  1418. }
  1419. // ExecutionResult groups all structured logs emitted by the EVM
  1420. // while replaying a transaction in debug mode as well as the amount of
  1421. // gas used and the return value
  1422. type ExecutionResult struct {
  1423. Gas *big.Int `json:"gas"`
  1424. ReturnValue string `json:"returnValue"`
  1425. StructLogs []structLogRes `json:"structLogs"`
  1426. }
  1427. // structLogRes stores a structured log emitted by the EVM while replaying a
  1428. // transaction in debug mode
  1429. type structLogRes struct {
  1430. Pc uint64 `json:"pc"`
  1431. Op string `json:"op"`
  1432. Gas *big.Int `json:"gas"`
  1433. GasCost *big.Int `json:"gasCost"`
  1434. Depth int `json:"depth"`
  1435. Error string `json:"error"`
  1436. Stack []string `json:"stack"`
  1437. Memory []string `json:"memory"`
  1438. Storage map[string]string `json:"storage"`
  1439. }
  1440. // VmLoggerOptions are the options used for debugging transactions and capturing
  1441. // specific data.
  1442. type VmLoggerOptions struct {
  1443. DisableMemory bool // disable memory capture
  1444. DisableStack bool // disable stack capture
  1445. DisableStorage bool // disable storage capture
  1446. FullStorage bool // show full storage (slow)
  1447. }
  1448. // formatLogs formats EVM returned structured logs for json output
  1449. func formatLogs(structLogs []vm.StructLog) []structLogRes {
  1450. formattedStructLogs := make([]structLogRes, len(structLogs))
  1451. for index, trace := range structLogs {
  1452. formattedStructLogs[index] = structLogRes{
  1453. Pc: trace.Pc,
  1454. Op: trace.Op.String(),
  1455. Gas: trace.Gas,
  1456. GasCost: trace.GasCost,
  1457. Depth: trace.Depth,
  1458. Error: formatError(trace.Err),
  1459. Stack: make([]string, len(trace.Stack)),
  1460. Storage: make(map[string]string),
  1461. }
  1462. for i, stackValue := range trace.Stack {
  1463. formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", common.LeftPadBytes(stackValue.Bytes(), 32))
  1464. }
  1465. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1466. formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1467. }
  1468. for i, storageValue := range trace.Storage {
  1469. formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1470. }
  1471. }
  1472. return formattedStructLogs
  1473. }
  1474. // formatError formats a Go error into either an empty string or the data content
  1475. // of the error itself.
  1476. func formatError(err error) string {
  1477. if err == nil {
  1478. return ""
  1479. }
  1480. return err.Error()
  1481. }
  1482. // TraceTransaction returns the structured logs created during the execution of EVM
  1483. // and returns them as a JSON object.
  1484. func (s *PrivateDebugAPI) TraceTransaction(txHash common.Hash, logger vm.LogConfig) (*ExecutionResult, error) {
  1485. // Retrieve the tx from the chain
  1486. tx, _, blockIndex, _ := core.GetTransaction(s.eth.ChainDb(), txHash)
  1487. if tx == nil {
  1488. return nil, fmt.Errorf("Transaction not found")
  1489. }
  1490. block := s.eth.BlockChain().GetBlockByNumber(blockIndex - 1)
  1491. if block == nil {
  1492. return nil, fmt.Errorf("Unable to retrieve prior block")
  1493. }
  1494. // Create the state database
  1495. stateDb, err := state.New(block.Root(), s.eth.ChainDb())
  1496. if err != nil {
  1497. return nil, err
  1498. }
  1499. txFrom, err := tx.FromFrontier()
  1500. if err != nil {
  1501. return nil, fmt.Errorf("Unable to create transaction sender")
  1502. }
  1503. from := stateDb.GetOrNewStateObject(txFrom)
  1504. msg := callmsg{
  1505. from: from,
  1506. to: tx.To(),
  1507. gas: tx.Gas(),
  1508. gasPrice: tx.GasPrice(),
  1509. value: tx.Value(),
  1510. data: tx.Data(),
  1511. }
  1512. vmenv := core.NewEnv(stateDb, s.config, s.eth.BlockChain(), msg, block.Header(), vm.Config{
  1513. Debug: true,
  1514. Logger: logger,
  1515. })
  1516. gp := new(core.GasPool).AddGas(block.GasLimit())
  1517. ret, gas, err := core.ApplyMessage(vmenv, msg, gp)
  1518. if err != nil {
  1519. return nil, fmt.Errorf("Error executing transaction %v", err)
  1520. }
  1521. return &ExecutionResult{
  1522. Gas: gas,
  1523. ReturnValue: fmt.Sprintf("%x", ret),
  1524. StructLogs: formatLogs(vmenv.StructLogs()),
  1525. }, nil
  1526. }
  1527. func (s *PublicBlockChainAPI) TraceCall(args CallArgs, blockNr rpc.BlockNumber) (*ExecutionResult, error) {
  1528. // Fetch the state associated with the block number
  1529. stateDb, block, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  1530. if stateDb == nil || err != nil {
  1531. return nil, err
  1532. }
  1533. stateDb = stateDb.Copy()
  1534. // Retrieve the account state object to interact with
  1535. var from *state.StateObject
  1536. if args.From == (common.Address{}) {
  1537. accounts, err := s.am.Accounts()
  1538. if err != nil || len(accounts) == 0 {
  1539. from = stateDb.GetOrNewStateObject(common.Address{})
  1540. } else {
  1541. from = stateDb.GetOrNewStateObject(accounts[0].Address)
  1542. }
  1543. } else {
  1544. from = stateDb.GetOrNewStateObject(args.From)
  1545. }
  1546. from.SetBalance(common.MaxBig)
  1547. // Assemble the CALL invocation
  1548. msg := callmsg{
  1549. from: from,
  1550. to: args.To,
  1551. gas: args.Gas.BigInt(),
  1552. gasPrice: args.GasPrice.BigInt(),
  1553. value: args.Value.BigInt(),
  1554. data: common.FromHex(args.Data),
  1555. }
  1556. if msg.gas.Cmp(common.Big0) == 0 {
  1557. msg.gas = big.NewInt(50000000)
  1558. }
  1559. if msg.gasPrice.Cmp(common.Big0) == 0 {
  1560. msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
  1561. }
  1562. // Execute the call and return
  1563. vmenv := core.NewEnv(stateDb, s.config, s.bc, msg, block.Header(), vm.Config{
  1564. Debug: true,
  1565. })
  1566. gp := new(core.GasPool).AddGas(common.MaxBig)
  1567. ret, gas, err := core.ApplyMessage(vmenv, msg, gp)
  1568. return &ExecutionResult{
  1569. Gas: gas,
  1570. ReturnValue: fmt.Sprintf("%x", ret),
  1571. StructLogs: formatLogs(vmenv.StructLogs()),
  1572. }, nil
  1573. }
  1574. // PublicNetAPI offers network related RPC methods
  1575. type PublicNetAPI struct {
  1576. net *p2p.Server
  1577. networkVersion int
  1578. }
  1579. // NewPublicNetAPI creates a new net API instance.
  1580. func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI {
  1581. return &PublicNetAPI{net, networkVersion}
  1582. }
  1583. // Listening returns an indication if the node is listening for network connections.
  1584. func (s *PublicNetAPI) Listening() bool {
  1585. return true // always listening
  1586. }
  1587. // Peercount returns the number of connected peers
  1588. func (s *PublicNetAPI) PeerCount() *rpc.HexNumber {
  1589. return rpc.NewHexNumber(s.net.PeerCount())
  1590. }
  1591. // ProtocolVersion returns the current ethereum protocol version.
  1592. func (s *PublicNetAPI) Version() string {
  1593. return fmt.Sprintf("%d", s.networkVersion)
  1594. }