api.go 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  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. bc *core.BlockChain
  404. chainDb ethdb.Database
  405. eventMux *event.TypeMux
  406. am *accounts.Manager
  407. miner *miner.Miner
  408. }
  409. // NewPublicBlockChainAPI creates a new Etheruem blockchain API.
  410. func NewPublicBlockChainAPI(bc *core.BlockChain, m *miner.Miner, chainDb ethdb.Database, eventMux *event.TypeMux, am *accounts.Manager) *PublicBlockChainAPI {
  411. return &PublicBlockChainAPI{bc: bc, miner: m, chainDb: chainDb, eventMux: eventMux, am: am}
  412. }
  413. // BlockNumber returns the block number of the chain head.
  414. func (s *PublicBlockChainAPI) BlockNumber() *big.Int {
  415. return s.bc.CurrentHeader().Number
  416. }
  417. // GetBalance returns the amount of wei for the given address in the state of the
  418. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  419. // block numbers are also allowed.
  420. func (s *PublicBlockChainAPI) GetBalance(address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) {
  421. state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  422. if state == nil || err != nil {
  423. return nil, err
  424. }
  425. return state.GetBalance(address), nil
  426. }
  427. // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
  428. // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  429. func (s *PublicBlockChainAPI) GetBlockByNumber(blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  430. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  431. response, err := s.rpcOutputBlock(block, true, fullTx)
  432. if err == nil && blockNr == rpc.PendingBlockNumber {
  433. // Pending blocks need to nil out a few fields
  434. for _, field := range []string{"hash", "nonce", "logsBloom", "miner"} {
  435. response[field] = nil
  436. }
  437. }
  438. return response, err
  439. }
  440. return nil, nil
  441. }
  442. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  443. // detail, otherwise only the transaction hash is returned.
  444. func (s *PublicBlockChainAPI) GetBlockByHash(blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
  445. if block := s.bc.GetBlock(blockHash); block != nil {
  446. return s.rpcOutputBlock(block, true, fullTx)
  447. }
  448. return nil, nil
  449. }
  450. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  451. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  452. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(blockNr rpc.BlockNumber, index rpc.HexNumber) (map[string]interface{}, error) {
  453. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  454. uncles := block.Uncles()
  455. if index.Int() < 0 || index.Int() >= len(uncles) {
  456. glog.V(logger.Debug).Infof("uncle block on index %d not found for block #%d", index.Int(), blockNr)
  457. return nil, nil
  458. }
  459. block = types.NewBlockWithHeader(uncles[index.Int()])
  460. return s.rpcOutputBlock(block, false, false)
  461. }
  462. return nil, nil
  463. }
  464. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  465. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  466. func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(blockHash common.Hash, index rpc.HexNumber) (map[string]interface{}, error) {
  467. if block := s.bc.GetBlock(blockHash); block != nil {
  468. uncles := block.Uncles()
  469. if index.Int() < 0 || index.Int() >= len(uncles) {
  470. glog.V(logger.Debug).Infof("uncle block on index %d not found for block %s", index.Int(), blockHash.Hex())
  471. return nil, nil
  472. }
  473. block = types.NewBlockWithHeader(uncles[index.Int()])
  474. return s.rpcOutputBlock(block, false, false)
  475. }
  476. return nil, nil
  477. }
  478. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  479. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(blockNr rpc.BlockNumber) *rpc.HexNumber {
  480. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  481. return rpc.NewHexNumber(len(block.Uncles()))
  482. }
  483. return nil
  484. }
  485. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  486. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(blockHash common.Hash) *rpc.HexNumber {
  487. if block := s.bc.GetBlock(blockHash); block != nil {
  488. return rpc.NewHexNumber(len(block.Uncles()))
  489. }
  490. return nil
  491. }
  492. // NewBlocksArgs allows the user to specify if the returned block should include transactions and in which format.
  493. type NewBlocksArgs struct {
  494. IncludeTransactions bool `json:"includeTransactions"`
  495. TransactionDetails bool `json:"transactionDetails"`
  496. }
  497. // NewBlocks triggers a new block event each time a block is appended to the chain. It accepts an argument which allows
  498. // the caller to specify whether the output should contain transactions and in what format.
  499. func (s *PublicBlockChainAPI) NewBlocks(args NewBlocksArgs) (rpc.Subscription, error) {
  500. sub := s.eventMux.Subscribe(core.ChainEvent{})
  501. output := func(rawBlock interface{}) interface{} {
  502. if event, ok := rawBlock.(core.ChainEvent); ok {
  503. notification, err := s.rpcOutputBlock(event.Block, args.IncludeTransactions, args.TransactionDetails)
  504. if err == nil {
  505. return notification
  506. }
  507. }
  508. return rawBlock
  509. }
  510. return rpc.NewSubscriptionWithOutputFormat(sub, output), nil
  511. }
  512. // GetCode returns the code stored at the given address in the state for the given block number.
  513. func (s *PublicBlockChainAPI) GetCode(address common.Address, blockNr rpc.BlockNumber) (string, error) {
  514. state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  515. if state == nil || err != nil {
  516. return "", err
  517. }
  518. res := state.GetCode(address)
  519. if len(res) == 0 { // backwards compatibility
  520. return "0x", nil
  521. }
  522. return common.ToHex(res), nil
  523. }
  524. // GetStorageAt returns the storage from the state at the given address, key and
  525. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  526. // numbers are also allowed.
  527. func (s *PublicBlockChainAPI) GetStorageAt(address common.Address, key string, blockNr rpc.BlockNumber) (string, error) {
  528. state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  529. if state == nil || err != nil {
  530. return "0x", err
  531. }
  532. return state.GetState(address, common.HexToHash(key)).Hex(), nil
  533. }
  534. // callmsg is the message type used for call transactions.
  535. type callmsg struct {
  536. from *state.StateObject
  537. to *common.Address
  538. gas, gasPrice *big.Int
  539. value *big.Int
  540. data []byte
  541. }
  542. // accessor boilerplate to implement core.Message
  543. func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
  544. func (m callmsg) FromFrontier() (common.Address, error) { return m.from.Address(), nil }
  545. func (m callmsg) Nonce() uint64 { return m.from.Nonce() }
  546. func (m callmsg) To() *common.Address { return m.to }
  547. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  548. func (m callmsg) Gas() *big.Int { return m.gas }
  549. func (m callmsg) Value() *big.Int { return m.value }
  550. func (m callmsg) Data() []byte { return m.data }
  551. type CallArgs struct {
  552. From common.Address `json:"from"`
  553. To *common.Address `json:"to"`
  554. Gas rpc.HexNumber `json:"gas"`
  555. GasPrice rpc.HexNumber `json:"gasPrice"`
  556. Value rpc.HexNumber `json:"value"`
  557. Data string `json:"data"`
  558. }
  559. func (s *PublicBlockChainAPI) doCall(args CallArgs, blockNr rpc.BlockNumber) (string, *big.Int, error) {
  560. // Fetch the state associated with the block number
  561. stateDb, block, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  562. if stateDb == nil || err != nil {
  563. return "0x", nil, err
  564. }
  565. stateDb = stateDb.Copy()
  566. // Retrieve the account state object to interact with
  567. var from *state.StateObject
  568. if args.From == (common.Address{}) {
  569. accounts, err := s.am.Accounts()
  570. if err != nil || len(accounts) == 0 {
  571. from = stateDb.GetOrNewStateObject(common.Address{})
  572. } else {
  573. from = stateDb.GetOrNewStateObject(accounts[0].Address)
  574. }
  575. } else {
  576. from = stateDb.GetOrNewStateObject(args.From)
  577. }
  578. from.SetBalance(common.MaxBig)
  579. // Assemble the CALL invocation
  580. msg := callmsg{
  581. from: from,
  582. to: args.To,
  583. gas: args.Gas.BigInt(),
  584. gasPrice: args.GasPrice.BigInt(),
  585. value: args.Value.BigInt(),
  586. data: common.FromHex(args.Data),
  587. }
  588. if msg.gas.Cmp(common.Big0) == 0 {
  589. msg.gas = big.NewInt(50000000)
  590. }
  591. if msg.gasPrice.Cmp(common.Big0) == 0 {
  592. msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
  593. }
  594. // Execute the call and return
  595. vmenv := core.NewEnv(stateDb, s.bc, msg, block.Header(), nil)
  596. gp := new(core.GasPool).AddGas(common.MaxBig)
  597. res, gas, err := core.ApplyMessage(vmenv, msg, gp)
  598. if len(res) == 0 { // backwards compatibility
  599. return "0x", gas, err
  600. }
  601. return common.ToHex(res), gas, err
  602. }
  603. // Call executes the given transaction on the state for the given block number.
  604. // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
  605. func (s *PublicBlockChainAPI) Call(args CallArgs, blockNr rpc.BlockNumber) (string, error) {
  606. result, _, err := s.doCall(args, blockNr)
  607. return result, err
  608. }
  609. // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
  610. func (s *PublicBlockChainAPI) EstimateGas(args CallArgs) (*rpc.HexNumber, error) {
  611. _, gas, err := s.doCall(args, rpc.PendingBlockNumber)
  612. return rpc.NewHexNumber(gas), err
  613. }
  614. // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  615. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  616. // transaction hashes.
  617. func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  618. fields := map[string]interface{}{
  619. "number": rpc.NewHexNumber(b.Number()),
  620. "hash": b.Hash(),
  621. "parentHash": b.ParentHash(),
  622. "nonce": b.Header().Nonce,
  623. "sha3Uncles": b.UncleHash(),
  624. "logsBloom": b.Bloom(),
  625. "stateRoot": b.Root(),
  626. "miner": b.Coinbase(),
  627. "difficulty": rpc.NewHexNumber(b.Difficulty()),
  628. "totalDifficulty": rpc.NewHexNumber(s.bc.GetTd(b.Hash())),
  629. "extraData": fmt.Sprintf("0x%x", b.Extra()),
  630. "size": rpc.NewHexNumber(b.Size().Int64()),
  631. "gasLimit": rpc.NewHexNumber(b.GasLimit()),
  632. "gasUsed": rpc.NewHexNumber(b.GasUsed()),
  633. "timestamp": rpc.NewHexNumber(b.Time()),
  634. "transactionsRoot": b.TxHash(),
  635. "receiptRoot": b.ReceiptHash(),
  636. }
  637. if inclTx {
  638. formatTx := func(tx *types.Transaction) (interface{}, error) {
  639. return tx.Hash(), nil
  640. }
  641. if fullTx {
  642. formatTx = func(tx *types.Transaction) (interface{}, error) {
  643. return newRPCTransaction(b, tx.Hash())
  644. }
  645. }
  646. txs := b.Transactions()
  647. transactions := make([]interface{}, len(txs))
  648. var err error
  649. for i, tx := range b.Transactions() {
  650. if transactions[i], err = formatTx(tx); err != nil {
  651. return nil, err
  652. }
  653. }
  654. fields["transactions"] = transactions
  655. }
  656. uncles := b.Uncles()
  657. uncleHashes := make([]common.Hash, len(uncles))
  658. for i, uncle := range uncles {
  659. uncleHashes[i] = uncle.Hash()
  660. }
  661. fields["uncles"] = uncleHashes
  662. return fields, nil
  663. }
  664. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  665. type RPCTransaction struct {
  666. BlockHash common.Hash `json:"blockHash"`
  667. BlockNumber *rpc.HexNumber `json:"blockNumber"`
  668. From common.Address `json:"from"`
  669. Gas *rpc.HexNumber `json:"gas"`
  670. GasPrice *rpc.HexNumber `json:"gasPrice"`
  671. Hash common.Hash `json:"hash"`
  672. Input string `json:"input"`
  673. Nonce *rpc.HexNumber `json:"nonce"`
  674. To *common.Address `json:"to"`
  675. TransactionIndex *rpc.HexNumber `json:"transactionIndex"`
  676. Value *rpc.HexNumber `json:"value"`
  677. }
  678. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  679. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  680. from, _ := tx.FromFrontier()
  681. return &RPCTransaction{
  682. From: from,
  683. Gas: rpc.NewHexNumber(tx.Gas()),
  684. GasPrice: rpc.NewHexNumber(tx.GasPrice()),
  685. Hash: tx.Hash(),
  686. Input: fmt.Sprintf("0x%x", tx.Data()),
  687. Nonce: rpc.NewHexNumber(tx.Nonce()),
  688. To: tx.To(),
  689. Value: rpc.NewHexNumber(tx.Value()),
  690. }
  691. }
  692. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  693. func newRPCTransactionFromBlockIndex(b *types.Block, txIndex int) (*RPCTransaction, error) {
  694. if txIndex >= 0 && txIndex < len(b.Transactions()) {
  695. tx := b.Transactions()[txIndex]
  696. from, err := tx.FromFrontier()
  697. if err != nil {
  698. return nil, err
  699. }
  700. return &RPCTransaction{
  701. BlockHash: b.Hash(),
  702. BlockNumber: rpc.NewHexNumber(b.Number()),
  703. From: from,
  704. Gas: rpc.NewHexNumber(tx.Gas()),
  705. GasPrice: rpc.NewHexNumber(tx.GasPrice()),
  706. Hash: tx.Hash(),
  707. Input: fmt.Sprintf("0x%x", tx.Data()),
  708. Nonce: rpc.NewHexNumber(tx.Nonce()),
  709. To: tx.To(),
  710. TransactionIndex: rpc.NewHexNumber(txIndex),
  711. Value: rpc.NewHexNumber(tx.Value()),
  712. }, nil
  713. }
  714. return nil, nil
  715. }
  716. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  717. func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) {
  718. for idx, tx := range b.Transactions() {
  719. if tx.Hash() == txHash {
  720. return newRPCTransactionFromBlockIndex(b, idx)
  721. }
  722. }
  723. return nil, nil
  724. }
  725. // PublicTransactionPoolAPI exposes methods for the RPC interface
  726. type PublicTransactionPoolAPI struct {
  727. eventMux *event.TypeMux
  728. chainDb ethdb.Database
  729. gpo *GasPriceOracle
  730. bc *core.BlockChain
  731. miner *miner.Miner
  732. am *accounts.Manager
  733. txPool *core.TxPool
  734. txMu sync.Mutex
  735. }
  736. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  737. func NewPublicTransactionPoolAPI(e *Ethereum) *PublicTransactionPoolAPI {
  738. return &PublicTransactionPoolAPI{
  739. eventMux: e.EventMux(),
  740. gpo: NewGasPriceOracle(e),
  741. chainDb: e.ChainDb(),
  742. bc: e.BlockChain(),
  743. am: e.AccountManager(),
  744. txPool: e.TxPool(),
  745. miner: e.Miner(),
  746. }
  747. }
  748. func getTransaction(chainDb ethdb.Database, txPool *core.TxPool, txHash common.Hash) (*types.Transaction, bool, error) {
  749. txData, err := chainDb.Get(txHash.Bytes())
  750. isPending := false
  751. tx := new(types.Transaction)
  752. if err == nil && len(txData) > 0 {
  753. if err := rlp.DecodeBytes(txData, tx); err != nil {
  754. return nil, isPending, err
  755. }
  756. } else {
  757. // pending transaction?
  758. tx = txPool.GetTransaction(txHash)
  759. isPending = true
  760. }
  761. return tx, isPending, nil
  762. }
  763. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  764. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(blockNr rpc.BlockNumber) *rpc.HexNumber {
  765. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  766. return rpc.NewHexNumber(len(block.Transactions()))
  767. }
  768. return nil
  769. }
  770. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  771. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(blockHash common.Hash) *rpc.HexNumber {
  772. if block := s.bc.GetBlock(blockHash); block != nil {
  773. return rpc.NewHexNumber(len(block.Transactions()))
  774. }
  775. return nil
  776. }
  777. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  778. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(blockNr rpc.BlockNumber, index rpc.HexNumber) (*RPCTransaction, error) {
  779. if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
  780. return newRPCTransactionFromBlockIndex(block, index.Int())
  781. }
  782. return nil, nil
  783. }
  784. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  785. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(blockHash common.Hash, index rpc.HexNumber) (*RPCTransaction, error) {
  786. if block := s.bc.GetBlock(blockHash); block != nil {
  787. return newRPCTransactionFromBlockIndex(block, index.Int())
  788. }
  789. return nil, nil
  790. }
  791. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  792. func (s *PublicTransactionPoolAPI) GetTransactionCount(address common.Address, blockNr rpc.BlockNumber) (*rpc.HexNumber, error) {
  793. state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  794. if state == nil || err != nil {
  795. return nil, err
  796. }
  797. return rpc.NewHexNumber(state.GetNonce(address)), nil
  798. }
  799. // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to
  800. // retrieve block information for a hash. It returns the block hash, block index and transaction index.
  801. func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) {
  802. var txBlock struct {
  803. BlockHash common.Hash
  804. BlockIndex uint64
  805. Index uint64
  806. }
  807. blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001))
  808. if err != nil {
  809. return common.Hash{}, uint64(0), uint64(0), err
  810. }
  811. reader := bytes.NewReader(blockData)
  812. if err = rlp.Decode(reader, &txBlock); err != nil {
  813. return common.Hash{}, uint64(0), uint64(0), err
  814. }
  815. return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil
  816. }
  817. // GetTransactionByHash returns the transaction for the given hash
  818. func (s *PublicTransactionPoolAPI) GetTransactionByHash(txHash common.Hash) (*RPCTransaction, error) {
  819. var tx *types.Transaction
  820. var isPending bool
  821. var err error
  822. if tx, isPending, err = getTransaction(s.chainDb, s.txPool, txHash); err != nil {
  823. glog.V(logger.Debug).Infof("%v\n", err)
  824. return nil, nil
  825. } else if tx == nil {
  826. return nil, nil
  827. }
  828. if isPending {
  829. return newRPCPendingTransaction(tx), nil
  830. }
  831. blockHash, _, _, err := getTransactionBlockData(s.chainDb, txHash)
  832. if err != nil {
  833. glog.V(logger.Debug).Infof("%v\n", err)
  834. return nil, nil
  835. }
  836. if block := s.bc.GetBlock(blockHash); block != nil {
  837. return newRPCTransaction(block, txHash)
  838. }
  839. return nil, nil
  840. }
  841. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  842. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(txHash common.Hash) (map[string]interface{}, error) {
  843. receipt := core.GetReceipt(s.chainDb, txHash)
  844. if receipt == nil {
  845. glog.V(logger.Debug).Infof("receipt not found for transaction %s", txHash.Hex())
  846. return nil, nil
  847. }
  848. tx, _, err := getTransaction(s.chainDb, s.txPool, txHash)
  849. if err != nil {
  850. glog.V(logger.Debug).Infof("%v\n", err)
  851. return nil, nil
  852. }
  853. txBlock, blockIndex, index, err := getTransactionBlockData(s.chainDb, txHash)
  854. if err != nil {
  855. glog.V(logger.Debug).Infof("%v\n", err)
  856. return nil, nil
  857. }
  858. from, err := tx.FromFrontier()
  859. if err != nil {
  860. glog.V(logger.Debug).Infof("%v\n", err)
  861. return nil, nil
  862. }
  863. fields := map[string]interface{}{
  864. "root": common.Bytes2Hex(receipt.PostState),
  865. "blockHash": txBlock,
  866. "blockNumber": rpc.NewHexNumber(blockIndex),
  867. "transactionHash": txHash,
  868. "transactionIndex": rpc.NewHexNumber(index),
  869. "from": from,
  870. "to": tx.To(),
  871. "gasUsed": rpc.NewHexNumber(receipt.GasUsed),
  872. "cumulativeGasUsed": rpc.NewHexNumber(receipt.CumulativeGasUsed),
  873. "contractAddress": nil,
  874. "logs": receipt.Logs,
  875. }
  876. if receipt.Logs == nil {
  877. fields["logs"] = []vm.Logs{}
  878. }
  879. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  880. if bytes.Compare(receipt.ContractAddress.Bytes(), bytes.Repeat([]byte{0}, 20)) != 0 {
  881. fields["contractAddress"] = receipt.ContractAddress
  882. }
  883. return fields, nil
  884. }
  885. // sign is a helper function that signs a transaction with the private key of the given address.
  886. func (s *PublicTransactionPoolAPI) sign(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
  887. acc := accounts.Account{address}
  888. signature, err := s.am.Sign(acc, tx.SigHash().Bytes())
  889. if err != nil {
  890. return nil, err
  891. }
  892. return tx.WithSignature(signature)
  893. }
  894. type SendTxArgs struct {
  895. From common.Address `json:"from"`
  896. To *common.Address `json:"to"`
  897. Gas *rpc.HexNumber `json:"gas"`
  898. GasPrice *rpc.HexNumber `json:"gasPrice"`
  899. Value *rpc.HexNumber `json:"value"`
  900. Data string `json:"data"`
  901. Nonce *rpc.HexNumber `json:"nonce"`
  902. }
  903. // SendTransaction will create a transaction for the given transaction argument, sign it and submit it to the
  904. // transaction pool.
  905. func (s *PublicTransactionPoolAPI) SendTransaction(args SendTxArgs) (common.Hash, error) {
  906. if args.Gas == nil {
  907. args.Gas = rpc.NewHexNumber(defaultGas)
  908. }
  909. if args.GasPrice == nil {
  910. args.GasPrice = rpc.NewHexNumber(s.gpo.SuggestPrice())
  911. }
  912. if args.Value == nil {
  913. args.Value = rpc.NewHexNumber(0)
  914. }
  915. s.txMu.Lock()
  916. defer s.txMu.Unlock()
  917. if args.Nonce == nil {
  918. args.Nonce = rpc.NewHexNumber(s.txPool.State().GetNonce(args.From))
  919. }
  920. var tx *types.Transaction
  921. contractCreation := (args.To == nil)
  922. if contractCreation {
  923. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  924. } else {
  925. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  926. }
  927. signedTx, err := s.sign(args.From, tx)
  928. if err != nil {
  929. return common.Hash{}, err
  930. }
  931. s.txPool.SetLocal(signedTx)
  932. if err := s.txPool.Add(signedTx); err != nil {
  933. return common.Hash{}, err
  934. }
  935. if contractCreation {
  936. addr := crypto.CreateAddress(args.From, args.Nonce.Uint64())
  937. glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signedTx.Hash().Hex(), addr.Hex())
  938. } else {
  939. glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signedTx.Hash().Hex(), tx.To().Hex())
  940. }
  941. return signedTx.Hash(), nil
  942. }
  943. // SendRawTransaction will add the signed transaction to the transaction pool.
  944. // The sender is responsible for signing the transaction and using the correct nonce.
  945. func (s *PublicTransactionPoolAPI) SendRawTransaction(encodedTx string) (string, error) {
  946. tx := new(types.Transaction)
  947. if err := rlp.DecodeBytes(common.FromHex(encodedTx), tx); err != nil {
  948. return "", err
  949. }
  950. s.txPool.SetLocal(tx)
  951. if err := s.txPool.Add(tx); err != nil {
  952. return "", err
  953. }
  954. if tx.To() == nil {
  955. from, err := tx.FromFrontier()
  956. if err != nil {
  957. return "", err
  958. }
  959. addr := crypto.CreateAddress(from, tx.Nonce())
  960. glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr)
  961. } else {
  962. glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To())
  963. }
  964. return tx.Hash().Hex(), nil
  965. }
  966. // Sign will sign the given data string with the given address. The account corresponding with the address needs to
  967. // be unlocked.
  968. func (s *PublicTransactionPoolAPI) Sign(address common.Address, data string) (string, error) {
  969. signature, error := s.am.Sign(accounts.Account{Address: address}, common.HexToHash(data).Bytes())
  970. return common.ToHex(signature), error
  971. }
  972. type SignTransactionArgs struct {
  973. From common.Address
  974. To *common.Address
  975. Nonce *rpc.HexNumber
  976. Value *rpc.HexNumber
  977. Gas *rpc.HexNumber
  978. GasPrice *rpc.HexNumber
  979. Data string
  980. BlockNumber int64
  981. }
  982. // Tx is a helper object for argument and return values
  983. type Tx struct {
  984. tx *types.Transaction
  985. To *common.Address `json:"to"`
  986. From common.Address `json:"from"`
  987. Nonce *rpc.HexNumber `json:"nonce"`
  988. Value *rpc.HexNumber `json:"value"`
  989. Data string `json:"data"`
  990. GasLimit *rpc.HexNumber `json:"gas"`
  991. GasPrice *rpc.HexNumber `json:"gasPrice"`
  992. Hash common.Hash `json:"hash"`
  993. }
  994. func (tx *Tx) UnmarshalJSON(b []byte) (err error) {
  995. req := struct {
  996. To *common.Address `json:"to"`
  997. From common.Address `json:"from"`
  998. Nonce *rpc.HexNumber `json:"nonce"`
  999. Value *rpc.HexNumber `json:"value"`
  1000. Data string `json:"data"`
  1001. GasLimit *rpc.HexNumber `json:"gas"`
  1002. GasPrice *rpc.HexNumber `json:"gasPrice"`
  1003. Hash common.Hash `json:"hash"`
  1004. }{}
  1005. if err := json.Unmarshal(b, &req); err != nil {
  1006. return err
  1007. }
  1008. tx.To = req.To
  1009. tx.From = req.From
  1010. tx.Nonce = req.Nonce
  1011. tx.Value = req.Value
  1012. tx.Data = req.Data
  1013. tx.GasLimit = req.GasLimit
  1014. tx.GasPrice = req.GasPrice
  1015. tx.Hash = req.Hash
  1016. data := common.Hex2Bytes(tx.Data)
  1017. if tx.Nonce == nil {
  1018. return fmt.Errorf("need nonce")
  1019. }
  1020. if tx.Value == nil {
  1021. tx.Value = rpc.NewHexNumber(0)
  1022. }
  1023. if tx.GasLimit == nil {
  1024. tx.GasLimit = rpc.NewHexNumber(0)
  1025. }
  1026. if tx.GasPrice == nil {
  1027. tx.GasPrice = rpc.NewHexNumber(int64(50000000000))
  1028. }
  1029. contractCreation := (req.To == nil)
  1030. if contractCreation {
  1031. tx.tx = types.NewContractCreation(tx.Nonce.Uint64(), tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  1032. } else {
  1033. tx.tx = types.NewTransaction(tx.Nonce.Uint64(), *tx.To, tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  1034. }
  1035. return nil
  1036. }
  1037. type SignTransactionResult struct {
  1038. Raw string `json:"raw"`
  1039. Tx *Tx `json:"tx"`
  1040. }
  1041. func newTx(t *types.Transaction) *Tx {
  1042. from, _ := t.FromFrontier()
  1043. return &Tx{
  1044. tx: t,
  1045. To: t.To(),
  1046. From: from,
  1047. Value: rpc.NewHexNumber(t.Value()),
  1048. Nonce: rpc.NewHexNumber(t.Nonce()),
  1049. Data: "0x" + common.Bytes2Hex(t.Data()),
  1050. GasLimit: rpc.NewHexNumber(t.Gas()),
  1051. GasPrice: rpc.NewHexNumber(t.GasPrice()),
  1052. Hash: t.Hash(),
  1053. }
  1054. }
  1055. // SignTransaction will sign the given transaction with the from account.
  1056. // The node needs to have the private key of the account corresponding with
  1057. // the given from address and it needs to be unlocked.
  1058. func (s *PublicTransactionPoolAPI) SignTransaction(args *SignTransactionArgs) (*SignTransactionResult, error) {
  1059. if args.Gas == nil {
  1060. args.Gas = rpc.NewHexNumber(defaultGas)
  1061. }
  1062. if args.GasPrice == nil {
  1063. args.GasPrice = rpc.NewHexNumber(s.gpo.SuggestPrice())
  1064. }
  1065. if args.Value == nil {
  1066. args.Value = rpc.NewHexNumber(0)
  1067. }
  1068. s.txMu.Lock()
  1069. defer s.txMu.Unlock()
  1070. if args.Nonce == nil {
  1071. args.Nonce = rpc.NewHexNumber(s.txPool.State().GetNonce(args.From))
  1072. }
  1073. var tx *types.Transaction
  1074. contractCreation := (args.To == nil)
  1075. if contractCreation {
  1076. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1077. } else {
  1078. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1079. }
  1080. signedTx, err := s.sign(args.From, tx)
  1081. if err != nil {
  1082. return nil, err
  1083. }
  1084. data, err := rlp.EncodeToBytes(signedTx)
  1085. if err != nil {
  1086. return nil, err
  1087. }
  1088. return &SignTransactionResult{"0x" + common.Bytes2Hex(data), newTx(tx)}, nil
  1089. }
  1090. // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1091. // the accounts this node manages.
  1092. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1093. accounts, err := s.am.Accounts()
  1094. if err != nil {
  1095. return nil, err
  1096. }
  1097. accountSet := set.New()
  1098. for _, account := range accounts {
  1099. accountSet.Add(account.Address)
  1100. }
  1101. pending := s.txPool.GetTransactions()
  1102. transactions := make([]*RPCTransaction, 0)
  1103. for _, tx := range pending {
  1104. if from, _ := tx.FromFrontier(); accountSet.Has(from) {
  1105. transactions = append(transactions, newRPCPendingTransaction(tx))
  1106. }
  1107. }
  1108. return transactions, nil
  1109. }
  1110. // NewPendingTransaction creates a subscription that is triggered each time a transaction enters the transaction pool
  1111. // and is send from one of the transactions this nodes manages.
  1112. func (s *PublicTransactionPoolAPI) NewPendingTransactions() (rpc.Subscription, error) {
  1113. sub := s.eventMux.Subscribe(core.TxPreEvent{})
  1114. accounts, err := s.am.Accounts()
  1115. if err != nil {
  1116. return rpc.Subscription{}, err
  1117. }
  1118. accountSet := set.New()
  1119. for _, account := range accounts {
  1120. accountSet.Add(account.Address)
  1121. }
  1122. accountSetLastUpdates := time.Now()
  1123. output := func(transaction interface{}) interface{} {
  1124. if time.Since(accountSetLastUpdates) > (time.Duration(2) * time.Second) {
  1125. if accounts, err = s.am.Accounts(); err != nil {
  1126. accountSet.Clear()
  1127. for _, account := range accounts {
  1128. accountSet.Add(account.Address)
  1129. }
  1130. accountSetLastUpdates = time.Now()
  1131. }
  1132. }
  1133. tx := transaction.(core.TxPreEvent)
  1134. if from, err := tx.Tx.FromFrontier(); err == nil {
  1135. if accountSet.Has(from) {
  1136. return tx.Tx.Hash()
  1137. }
  1138. }
  1139. return nil
  1140. }
  1141. return rpc.NewSubscriptionWithOutputFormat(sub, output), nil
  1142. }
  1143. // Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the
  1144. // pool and reinsert it with the new gas price and limit.
  1145. func (s *PublicTransactionPoolAPI) Resend(tx *Tx, gasPrice, gasLimit *rpc.HexNumber) (common.Hash, error) {
  1146. pending := s.txPool.GetTransactions()
  1147. for _, p := range pending {
  1148. if pFrom, err := p.FromFrontier(); err == nil && pFrom == tx.From && p.SigHash() == tx.tx.SigHash() {
  1149. if gasPrice == nil {
  1150. gasPrice = rpc.NewHexNumber(tx.tx.GasPrice())
  1151. }
  1152. if gasLimit == nil {
  1153. gasLimit = rpc.NewHexNumber(tx.tx.Gas())
  1154. }
  1155. var newTx *types.Transaction
  1156. contractCreation := (tx.tx.To() == nil)
  1157. if contractCreation {
  1158. newTx = types.NewContractCreation(tx.tx.Nonce(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1159. } else {
  1160. newTx = types.NewTransaction(tx.tx.Nonce(), *tx.tx.To(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1161. }
  1162. signedTx, err := s.sign(tx.From, newTx)
  1163. if err != nil {
  1164. return common.Hash{}, err
  1165. }
  1166. s.txPool.RemoveTx(tx.Hash)
  1167. if err = s.txPool.Add(signedTx); err != nil {
  1168. return common.Hash{}, err
  1169. }
  1170. return signedTx.Hash(), nil
  1171. }
  1172. }
  1173. return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash)
  1174. }
  1175. // PrivateAdminAPI is the collection of Etheruem APIs exposed over the private
  1176. // admin endpoint.
  1177. type PrivateAdminAPI struct {
  1178. eth *Ethereum
  1179. }
  1180. // NewPrivateAdminAPI creates a new API definition for the private admin methods
  1181. // of the Ethereum service.
  1182. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  1183. return &PrivateAdminAPI{eth: eth}
  1184. }
  1185. // SetSolc sets the Solidity compiler path to be used by the node.
  1186. func (api *PrivateAdminAPI) SetSolc(path string) (string, error) {
  1187. solc, err := api.eth.SetSolc(path)
  1188. if err != nil {
  1189. return "", err
  1190. }
  1191. return solc.Info(), nil
  1192. }
  1193. // ExportChain exports the current blockchain into a local file.
  1194. func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
  1195. // Make sure we can create the file to export into
  1196. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  1197. if err != nil {
  1198. return false, err
  1199. }
  1200. defer out.Close()
  1201. // Export the blockchain
  1202. if err := api.eth.BlockChain().Export(out); err != nil {
  1203. return false, err
  1204. }
  1205. return true, nil
  1206. }
  1207. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  1208. for _, b := range bs {
  1209. if !chain.HasBlock(b.Hash()) {
  1210. return false
  1211. }
  1212. }
  1213. return true
  1214. }
  1215. // ImportChain imports a blockchain from a local file.
  1216. func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
  1217. // Make sure the can access the file to import
  1218. in, err := os.Open(file)
  1219. if err != nil {
  1220. return false, err
  1221. }
  1222. defer in.Close()
  1223. // Run actual the import in pre-configured batches
  1224. stream := rlp.NewStream(in, 0)
  1225. blocks, index := make([]*types.Block, 0, 2500), 0
  1226. for batch := 0; ; batch++ {
  1227. // Load a batch of blocks from the input file
  1228. for len(blocks) < cap(blocks) {
  1229. block := new(types.Block)
  1230. if err := stream.Decode(block); err == io.EOF {
  1231. break
  1232. } else if err != nil {
  1233. return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
  1234. }
  1235. blocks = append(blocks, block)
  1236. index++
  1237. }
  1238. if len(blocks) == 0 {
  1239. break
  1240. }
  1241. if hasAllBlocks(api.eth.BlockChain(), blocks) {
  1242. blocks = blocks[:0]
  1243. continue
  1244. }
  1245. // Import the batch and reset the buffer
  1246. if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
  1247. return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
  1248. }
  1249. blocks = blocks[:0]
  1250. }
  1251. return true, nil
  1252. }
  1253. // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
  1254. // debugging endpoint.
  1255. type PublicDebugAPI struct {
  1256. eth *Ethereum
  1257. }
  1258. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1259. // of the Ethereum service.
  1260. func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
  1261. return &PublicDebugAPI{eth: eth}
  1262. }
  1263. // DumpBlock retrieves the entire state of the database at a given block.
  1264. func (api *PublicDebugAPI) DumpBlock(number uint64) (state.World, error) {
  1265. block := api.eth.BlockChain().GetBlockByNumber(number)
  1266. if block == nil {
  1267. return state.World{}, fmt.Errorf("block #%d not found", number)
  1268. }
  1269. stateDb, err := state.New(block.Root(), api.eth.ChainDb())
  1270. if err != nil {
  1271. return state.World{}, err
  1272. }
  1273. return stateDb.RawDump(), nil
  1274. }
  1275. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1276. func (api *PublicDebugAPI) GetBlockRlp(number uint64) (string, error) {
  1277. block := api.eth.BlockChain().GetBlockByNumber(number)
  1278. if block == nil {
  1279. return "", fmt.Errorf("block #%d not found", number)
  1280. }
  1281. encoded, err := rlp.EncodeToBytes(block)
  1282. if err != nil {
  1283. return "", err
  1284. }
  1285. return fmt.Sprintf("%x", encoded), nil
  1286. }
  1287. // PrintBlock retrieves a block and returns its pretty printed form.
  1288. func (api *PublicDebugAPI) PrintBlock(number uint64) (string, error) {
  1289. block := api.eth.BlockChain().GetBlockByNumber(number)
  1290. if block == nil {
  1291. return "", fmt.Errorf("block #%d not found", number)
  1292. }
  1293. return fmt.Sprintf("%s", block), nil
  1294. }
  1295. // SeedHash retrieves the seed hash of a block.
  1296. func (api *PublicDebugAPI) SeedHash(number uint64) (string, error) {
  1297. block := api.eth.BlockChain().GetBlockByNumber(number)
  1298. if block == nil {
  1299. return "", fmt.Errorf("block #%d not found", number)
  1300. }
  1301. hash, err := ethash.GetSeedHash(number)
  1302. if err != nil {
  1303. return "", err
  1304. }
  1305. return fmt.Sprintf("0x%x", hash), nil
  1306. }
  1307. // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private
  1308. // debugging endpoint.
  1309. type PrivateDebugAPI struct {
  1310. eth *Ethereum
  1311. }
  1312. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1313. // of the Ethereum service.
  1314. func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI {
  1315. return &PrivateDebugAPI{eth: eth}
  1316. }
  1317. // BlockTraceResults is the returned value when replaying a block to check for
  1318. // consensus results and full VM trace logs for all included transactions.
  1319. type BlockTraceResult struct {
  1320. Validated bool `json:"validated"`
  1321. StructLogs []structLogRes `json:"structLogs"`
  1322. Error string `json:"error"`
  1323. }
  1324. // TraceBlock processes the given block's RLP but does not import the block in to
  1325. // the chain.
  1326. func (api *PrivateDebugAPI) TraceBlock(blockRlp []byte, config vm.Config) BlockTraceResult {
  1327. var block types.Block
  1328. err := rlp.Decode(bytes.NewReader(blockRlp), &block)
  1329. if err != nil {
  1330. return BlockTraceResult{Error: fmt.Sprintf("could not decode block: %v", err)}
  1331. }
  1332. validated, logs, err := api.traceBlock(&block, config)
  1333. return BlockTraceResult{
  1334. Validated: validated,
  1335. StructLogs: formatLogs(logs),
  1336. Error: err.Error(),
  1337. }
  1338. }
  1339. // TraceBlockFromFile loads the block's RLP from the given file name and attempts to
  1340. // process it but does not import the block in to the chain.
  1341. func (api *PrivateDebugAPI) TraceBlockFromFile(file string, config vm.Config) BlockTraceResult {
  1342. blockRlp, err := ioutil.ReadFile(file)
  1343. if err != nil {
  1344. return BlockTraceResult{Error: fmt.Sprintf("could not read file: %v", err)}
  1345. }
  1346. return api.TraceBlock(blockRlp, config)
  1347. }
  1348. // TraceProcessBlock processes the block by canonical block number.
  1349. func (api *PrivateDebugAPI) TraceBlockByNumber(number uint64, config vm.Config) BlockTraceResult {
  1350. // Fetch the block that we aim to reprocess
  1351. block := api.eth.BlockChain().GetBlockByNumber(number)
  1352. if block == nil {
  1353. return BlockTraceResult{Error: fmt.Sprintf("block #%d not found", number)}
  1354. }
  1355. validated, logs, err := api.traceBlock(block, config)
  1356. return BlockTraceResult{
  1357. Validated: validated,
  1358. StructLogs: formatLogs(logs),
  1359. Error: err.Error(),
  1360. }
  1361. }
  1362. // TraceBlockByHash processes the block by hash.
  1363. func (api *PrivateDebugAPI) TraceBlockByHash(hash common.Hash, config vm.Config) BlockTraceResult {
  1364. // Fetch the block that we aim to reprocess
  1365. block := api.eth.BlockChain().GetBlock(hash)
  1366. if block == nil {
  1367. return BlockTraceResult{Error: fmt.Sprintf("block #%x not found", hash)}
  1368. }
  1369. validated, logs, err := api.traceBlock(block, config)
  1370. return BlockTraceResult{
  1371. Validated: validated,
  1372. StructLogs: formatLogs(logs),
  1373. Error: err.Error(),
  1374. }
  1375. }
  1376. // TraceCollector collects EVM structered logs.
  1377. //
  1378. // TraceCollector implements vm.Collector
  1379. type TraceCollector struct {
  1380. traces []vm.StructLog
  1381. }
  1382. // AddStructLog adds a structered log.
  1383. func (t *TraceCollector) AddStructLog(slog vm.StructLog) {
  1384. t.traces = append(t.traces, slog)
  1385. }
  1386. // traceBlock processes the given block but does not save the state.
  1387. func (api *PrivateDebugAPI) traceBlock(block *types.Block, config vm.Config) (bool, []vm.StructLog, error) {
  1388. // Validate and reprocess the block
  1389. var (
  1390. blockchain = api.eth.BlockChain()
  1391. validator = blockchain.Validator()
  1392. processor = blockchain.Processor()
  1393. collector = &TraceCollector{}
  1394. )
  1395. config.Debug = true // make sure debug is set.
  1396. config.Logger.Collector = collector
  1397. if err := core.ValidateHeader(blockchain.AuxValidator(), block.Header(), blockchain.GetHeader(block.ParentHash()), true, false); err != nil {
  1398. return false, collector.traces, err
  1399. }
  1400. statedb, err := state.New(blockchain.GetBlock(block.ParentHash()).Root(), api.eth.ChainDb())
  1401. if err != nil {
  1402. return false, collector.traces, err
  1403. }
  1404. receipts, _, usedGas, err := processor.Process(block, statedb, &config)
  1405. if err != nil {
  1406. return false, collector.traces, err
  1407. }
  1408. if err := validator.ValidateState(block, blockchain.GetBlock(block.ParentHash()), statedb, receipts, usedGas); err != nil {
  1409. return false, collector.traces, err
  1410. }
  1411. return true, collector.traces, nil
  1412. }
  1413. // SetHead rewinds the head of the blockchain to a previous block.
  1414. func (api *PrivateDebugAPI) SetHead(number uint64) {
  1415. api.eth.BlockChain().SetHead(number)
  1416. }
  1417. // ExecutionResult groups all structured logs emitted by the EVM
  1418. // while replaying a transaction in debug mode as well as the amount of
  1419. // gas used and the return value
  1420. type ExecutionResult struct {
  1421. Gas *big.Int `json:"gas"`
  1422. ReturnValue string `json:"returnValue"`
  1423. StructLogs []structLogRes `json:"structLogs"`
  1424. }
  1425. // structLogRes stores a structured log emitted by the EVM while replaying a
  1426. // transaction in debug mode
  1427. type structLogRes struct {
  1428. Pc uint64 `json:"pc"`
  1429. Op string `json:"op"`
  1430. Gas *big.Int `json:"gas"`
  1431. GasCost *big.Int `json:"gasCost"`
  1432. Depth int `json:"depth"`
  1433. Error string `json:"error"`
  1434. Stack []string `json:"stack"`
  1435. Memory []string `json:"memory"`
  1436. Storage map[string]string `json:"storage"`
  1437. }
  1438. // VmLoggerOptions are the options used for debugging transactions and capturing
  1439. // specific data.
  1440. type VmLoggerOptions struct {
  1441. DisableMemory bool // disable memory capture
  1442. DisableStack bool // disable stack capture
  1443. DisableStorage bool // disable storage capture
  1444. FullStorage bool // show full storage (slow)
  1445. }
  1446. // formatLogs formats EVM returned structured logs for json output
  1447. func formatLogs(structLogs []vm.StructLog) []structLogRes {
  1448. formattedStructLogs := make([]structLogRes, len(structLogs))
  1449. for index, trace := range structLogs {
  1450. formattedStructLogs[index] = structLogRes{
  1451. Pc: trace.Pc,
  1452. Op: trace.Op.String(),
  1453. Gas: trace.Gas,
  1454. GasCost: trace.GasCost,
  1455. Depth: trace.Depth,
  1456. Error: trace.Err.Error(),
  1457. Stack: make([]string, len(trace.Stack)),
  1458. Storage: make(map[string]string),
  1459. }
  1460. for i, stackValue := range trace.Stack {
  1461. formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", common.LeftPadBytes(stackValue.Bytes(), 32))
  1462. }
  1463. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1464. formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1465. }
  1466. for i, storageValue := range trace.Storage {
  1467. formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1468. }
  1469. }
  1470. return formattedStructLogs
  1471. }
  1472. // TraceTransaction returns the structured logs created during the execution of EVM
  1473. // and returns them as a JSON object.
  1474. func (s *PrivateDebugAPI) TraceTransaction(txHash common.Hash, logger vm.LogConfig) (*ExecutionResult, error) {
  1475. // Retrieve the tx from the chain
  1476. tx, _, blockIndex, _ := core.GetTransaction(s.eth.ChainDb(), txHash)
  1477. if tx == nil {
  1478. return nil, fmt.Errorf("Transaction not found")
  1479. }
  1480. block := s.eth.BlockChain().GetBlockByNumber(blockIndex - 1)
  1481. if block == nil {
  1482. return nil, fmt.Errorf("Unable to retrieve prior block")
  1483. }
  1484. // Create the state database
  1485. stateDb, err := state.New(block.Root(), s.eth.ChainDb())
  1486. if err != nil {
  1487. return nil, err
  1488. }
  1489. txFrom, err := tx.FromFrontier()
  1490. if err != nil {
  1491. return nil, fmt.Errorf("Unable to create transaction sender")
  1492. }
  1493. from := stateDb.GetOrNewStateObject(txFrom)
  1494. msg := callmsg{
  1495. from: from,
  1496. to: tx.To(),
  1497. gas: tx.Gas(),
  1498. gasPrice: tx.GasPrice(),
  1499. value: tx.Value(),
  1500. data: tx.Data(),
  1501. }
  1502. vmenv := core.NewEnv(stateDb, s.eth.BlockChain(), msg, block.Header(), &vm.Config{
  1503. Debug: true,
  1504. Logger: logger,
  1505. })
  1506. gp := new(core.GasPool).AddGas(block.GasLimit())
  1507. ret, gas, err := core.ApplyMessage(vmenv, msg, gp)
  1508. if err != nil {
  1509. return nil, fmt.Errorf("Error executing transaction %v", err)
  1510. }
  1511. return &ExecutionResult{
  1512. Gas: gas,
  1513. ReturnValue: fmt.Sprintf("%x", ret),
  1514. StructLogs: formatLogs(vmenv.StructLogs()),
  1515. }, nil
  1516. }
  1517. func (s *PublicBlockChainAPI) TraceCall(args CallArgs, blockNr rpc.BlockNumber) (*ExecutionResult, error) {
  1518. // Fetch the state associated with the block number
  1519. stateDb, block, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
  1520. if stateDb == nil || err != nil {
  1521. return nil, err
  1522. }
  1523. stateDb = stateDb.Copy()
  1524. // Retrieve the account state object to interact with
  1525. var from *state.StateObject
  1526. if args.From == (common.Address{}) {
  1527. accounts, err := s.am.Accounts()
  1528. if err != nil || len(accounts) == 0 {
  1529. from = stateDb.GetOrNewStateObject(common.Address{})
  1530. } else {
  1531. from = stateDb.GetOrNewStateObject(accounts[0].Address)
  1532. }
  1533. } else {
  1534. from = stateDb.GetOrNewStateObject(args.From)
  1535. }
  1536. from.SetBalance(common.MaxBig)
  1537. // Assemble the CALL invocation
  1538. msg := callmsg{
  1539. from: from,
  1540. to: args.To,
  1541. gas: args.Gas.BigInt(),
  1542. gasPrice: args.GasPrice.BigInt(),
  1543. value: args.Value.BigInt(),
  1544. data: common.FromHex(args.Data),
  1545. }
  1546. if msg.gas.Cmp(common.Big0) == 0 {
  1547. msg.gas = big.NewInt(50000000)
  1548. }
  1549. if msg.gasPrice.Cmp(common.Big0) == 0 {
  1550. msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
  1551. }
  1552. // Execute the call and return
  1553. vmenv := core.NewEnv(stateDb, s.bc, msg, block.Header(), nil)
  1554. gp := new(core.GasPool).AddGas(common.MaxBig)
  1555. ret, gas, err := core.ApplyMessage(vmenv, msg, gp)
  1556. return &ExecutionResult{
  1557. Gas: gas,
  1558. ReturnValue: fmt.Sprintf("%x", ret),
  1559. StructLogs: formatLogs(vmenv.StructLogs()),
  1560. }, nil
  1561. }
  1562. // PublicNetAPI offers network related RPC methods
  1563. type PublicNetAPI struct {
  1564. net *p2p.Server
  1565. networkVersion int
  1566. }
  1567. // NewPublicNetAPI creates a new net API instance.
  1568. func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI {
  1569. return &PublicNetAPI{net, networkVersion}
  1570. }
  1571. // Listening returns an indication if the node is listening for network connections.
  1572. func (s *PublicNetAPI) Listening() bool {
  1573. return true // always listening
  1574. }
  1575. // Peercount returns the number of connected peers
  1576. func (s *PublicNetAPI) PeerCount() *rpc.HexNumber {
  1577. return rpc.NewHexNumber(s.net.PeerCount())
  1578. }
  1579. // ProtocolVersion returns the current ethereum protocol version.
  1580. func (s *PublicNetAPI) Version() string {
  1581. return fmt.Sprintf("%d", s.networkVersion)
  1582. }