api.go 55 KB

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