api.go 63 KB

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