api.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  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 adn 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 adn 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 Etheruem 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 synching 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 transations.
  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())
  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 usefull 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.From()
  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.From()
  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.From()
  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 == common.Address{})
  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.From()
  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. contractCreation := (req.To == (common.Address{}))
  1005. tx.To = &req.To
  1006. tx.From = req.From
  1007. tx.Nonce = req.Nonce
  1008. tx.Value = req.Value
  1009. tx.Data = req.Data
  1010. tx.GasLimit = req.GasLimit
  1011. tx.GasPrice = req.GasPrice
  1012. tx.Hash = req.Hash
  1013. data := common.Hex2Bytes(tx.Data)
  1014. if tx.Nonce == nil {
  1015. return fmt.Errorf("need nonce")
  1016. }
  1017. if tx.Value == nil {
  1018. tx.Value = rpc.NewHexNumber(0)
  1019. }
  1020. if tx.GasLimit == nil {
  1021. tx.GasLimit = rpc.NewHexNumber(0)
  1022. }
  1023. if tx.GasPrice == nil {
  1024. tx.GasPrice = rpc.NewHexNumber(int64(50000000000))
  1025. }
  1026. if contractCreation {
  1027. tx.tx = types.NewContractCreation(tx.Nonce.Uint64(), tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  1028. } else {
  1029. if tx.To == nil {
  1030. return fmt.Errorf("need to address")
  1031. }
  1032. tx.tx = types.NewTransaction(tx.Nonce.Uint64(), *tx.To, tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  1033. }
  1034. return nil
  1035. }
  1036. type SignTransactionResult struct {
  1037. Raw string `json:"raw"`
  1038. Tx *Tx `json:"tx"`
  1039. }
  1040. func newTx(t *types.Transaction) *Tx {
  1041. from, _ := t.From()
  1042. return &Tx{
  1043. tx: t,
  1044. To: t.To(),
  1045. From: from,
  1046. Value: rpc.NewHexNumber(t.Value()),
  1047. Nonce: rpc.NewHexNumber(t.Nonce()),
  1048. Data: "0x" + common.Bytes2Hex(t.Data()),
  1049. GasLimit: rpc.NewHexNumber(t.Gas()),
  1050. GasPrice: rpc.NewHexNumber(t.GasPrice()),
  1051. Hash: t.Hash(),
  1052. }
  1053. }
  1054. // SignTransaction will sign the given transaction with the from account.
  1055. // The node needs to have the private key of the account corresponding with
  1056. // the given from address and it needs to be unlocked.
  1057. func (s *PublicTransactionPoolAPI) SignTransaction(args *SignTransactionArgs) (*SignTransactionResult, error) {
  1058. if args.Gas == nil {
  1059. args.Gas = rpc.NewHexNumber(defaultGas)
  1060. }
  1061. if args.GasPrice == nil {
  1062. args.GasPrice = rpc.NewHexNumber(s.gpo.SuggestPrice())
  1063. }
  1064. if args.Value == nil {
  1065. args.Value = rpc.NewHexNumber(0)
  1066. }
  1067. s.txMu.Lock()
  1068. defer s.txMu.Unlock()
  1069. if args.Nonce == nil {
  1070. args.Nonce = rpc.NewHexNumber(s.txPool.State().GetNonce(args.From))
  1071. }
  1072. var tx *types.Transaction
  1073. contractCreation := (args.To == common.Address{})
  1074. if contractCreation {
  1075. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1076. } else {
  1077. tx = types.NewTransaction(args.Nonce.Uint64(), args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1078. }
  1079. signedTx, err := s.sign(args.From, tx)
  1080. if err != nil {
  1081. return nil, err
  1082. }
  1083. data, err := rlp.EncodeToBytes(signedTx)
  1084. if err != nil {
  1085. return nil, err
  1086. }
  1087. return &SignTransactionResult{"0x" + common.Bytes2Hex(data), newTx(tx)}, nil
  1088. }
  1089. // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1090. // the accounts this node manages.
  1091. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1092. accounts, err := s.am.Accounts()
  1093. if err != nil {
  1094. return nil, err
  1095. }
  1096. accountSet := set.New()
  1097. for _, account := range accounts {
  1098. accountSet.Add(account.Address)
  1099. }
  1100. pending := s.txPool.GetTransactions()
  1101. transactions := make([]*RPCTransaction, 0)
  1102. for _, tx := range pending {
  1103. if from, _ := tx.From(); accountSet.Has(from) {
  1104. transactions = append(transactions, newRPCPendingTransaction(tx))
  1105. }
  1106. }
  1107. return transactions, nil
  1108. }
  1109. // NewPendingTransaction creates a subscription that is triggered each time a transaction enters the transaction pool
  1110. // and is send from one of the transactions this nodes manages.
  1111. func (s *PublicTransactionPoolAPI) NewPendingTransactions() (rpc.Subscription, error) {
  1112. sub := s.eventMux.Subscribe(core.TxPreEvent{})
  1113. accounts, err := s.am.Accounts()
  1114. if err != nil {
  1115. return rpc.Subscription{}, err
  1116. }
  1117. accountSet := set.New()
  1118. for _, account := range accounts {
  1119. accountSet.Add(account.Address)
  1120. }
  1121. accountSetLastUpdates := time.Now()
  1122. output := func(transaction interface{}) interface{} {
  1123. if time.Since(accountSetLastUpdates) > (time.Duration(2) * time.Second) {
  1124. if accounts, err = s.am.Accounts(); err != nil {
  1125. accountSet.Clear()
  1126. for _, account := range accounts {
  1127. accountSet.Add(account.Address)
  1128. }
  1129. accountSetLastUpdates = time.Now()
  1130. }
  1131. }
  1132. tx := transaction.(core.TxPreEvent)
  1133. if from, err := tx.Tx.From(); err == nil {
  1134. if accountSet.Has(from) {
  1135. return tx.Tx.Hash()
  1136. }
  1137. }
  1138. return nil
  1139. }
  1140. return rpc.NewSubscriptionWithOutputFormat(sub, output), nil
  1141. }
  1142. // Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the
  1143. // pool and reinsert it with the new gas price and limit.
  1144. func (s *PublicTransactionPoolAPI) Resend(tx *Tx, gasPrice, gasLimit *rpc.HexNumber) (common.Hash, error) {
  1145. pending := s.txPool.GetTransactions()
  1146. for _, p := range pending {
  1147. if pFrom, err := p.From(); err == nil && pFrom == tx.From && p.SigHash() == tx.tx.SigHash() {
  1148. if gasPrice == nil {
  1149. gasPrice = rpc.NewHexNumber(tx.tx.GasPrice())
  1150. }
  1151. if gasLimit == nil {
  1152. gasLimit = rpc.NewHexNumber(tx.tx.Gas())
  1153. }
  1154. var newTx *types.Transaction
  1155. contractCreation := (*tx.tx.To() == common.Address{})
  1156. if contractCreation {
  1157. newTx = types.NewContractCreation(tx.tx.Nonce(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1158. } else {
  1159. newTx = types.NewTransaction(tx.tx.Nonce(), *tx.tx.To(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1160. }
  1161. signedTx, err := s.sign(tx.From, newTx)
  1162. if err != nil {
  1163. return common.Hash{}, err
  1164. }
  1165. s.txPool.RemoveTx(tx.Hash)
  1166. if err = s.txPool.Add(signedTx); err != nil {
  1167. return common.Hash{}, err
  1168. }
  1169. return signedTx.Hash(), nil
  1170. }
  1171. }
  1172. return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash)
  1173. }
  1174. // PrivateAdminAPI is the collection of Etheruem APIs exposed over the private
  1175. // admin endpoint.
  1176. type PrivateAdminAPI struct {
  1177. eth *Ethereum
  1178. }
  1179. // NewPrivateAdminAPI creates a new API definition for the private admin methods
  1180. // of the Ethereum service.
  1181. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  1182. return &PrivateAdminAPI{eth: eth}
  1183. }
  1184. // SetSolc sets the Solidity compiler path to be used by the node.
  1185. func (api *PrivateAdminAPI) SetSolc(path string) (string, error) {
  1186. solc, err := api.eth.SetSolc(path)
  1187. if err != nil {
  1188. return "", err
  1189. }
  1190. return solc.Info(), nil
  1191. }
  1192. // ExportChain exports the current blockchain into a local file.
  1193. func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
  1194. // Make sure we can create the file to export into
  1195. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  1196. if err != nil {
  1197. return false, err
  1198. }
  1199. defer out.Close()
  1200. // Export the blockchain
  1201. if err := api.eth.BlockChain().Export(out); err != nil {
  1202. return false, err
  1203. }
  1204. return true, nil
  1205. }
  1206. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  1207. for _, b := range bs {
  1208. if !chain.HasBlock(b.Hash()) {
  1209. return false
  1210. }
  1211. }
  1212. return true
  1213. }
  1214. // ImportChain imports a blockchain from a local file.
  1215. func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
  1216. // Make sure the can access the file to import
  1217. in, err := os.Open(file)
  1218. if err != nil {
  1219. return false, err
  1220. }
  1221. defer in.Close()
  1222. // Run actual the import in pre-configured batches
  1223. stream := rlp.NewStream(in, 0)
  1224. blocks, index := make([]*types.Block, 0, 2500), 0
  1225. for batch := 0; ; batch++ {
  1226. // Load a batch of blocks from the input file
  1227. for len(blocks) < cap(blocks) {
  1228. block := new(types.Block)
  1229. if err := stream.Decode(block); err == io.EOF {
  1230. break
  1231. } else if err != nil {
  1232. return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
  1233. }
  1234. blocks = append(blocks, block)
  1235. index++
  1236. }
  1237. if len(blocks) == 0 {
  1238. break
  1239. }
  1240. if hasAllBlocks(api.eth.BlockChain(), blocks) {
  1241. blocks = blocks[:0]
  1242. continue
  1243. }
  1244. // Import the batch and reset the buffer
  1245. if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
  1246. return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
  1247. }
  1248. blocks = blocks[:0]
  1249. }
  1250. return true, nil
  1251. }
  1252. // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
  1253. // debugging endpoint.
  1254. type PublicDebugAPI struct {
  1255. eth *Ethereum
  1256. }
  1257. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1258. // of the Ethereum service.
  1259. func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
  1260. return &PublicDebugAPI{eth: eth}
  1261. }
  1262. // DumpBlock retrieves the entire state of the database at a given block.
  1263. func (api *PublicDebugAPI) DumpBlock(number uint64) (state.World, error) {
  1264. block := api.eth.BlockChain().GetBlockByNumber(number)
  1265. if block == nil {
  1266. return state.World{}, fmt.Errorf("block #%d not found", number)
  1267. }
  1268. stateDb, err := state.New(block.Root(), api.eth.ChainDb())
  1269. if err != nil {
  1270. return state.World{}, err
  1271. }
  1272. return stateDb.RawDump(), nil
  1273. }
  1274. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1275. func (api *PublicDebugAPI) GetBlockRlp(number uint64) (string, error) {
  1276. block := api.eth.BlockChain().GetBlockByNumber(number)
  1277. if block == nil {
  1278. return "", fmt.Errorf("block #%d not found", number)
  1279. }
  1280. encoded, err := rlp.EncodeToBytes(block)
  1281. if err != nil {
  1282. return "", err
  1283. }
  1284. return fmt.Sprintf("%x", encoded), nil
  1285. }
  1286. // PrintBlock retrieves a block and returns its pretty printed form.
  1287. func (api *PublicDebugAPI) PrintBlock(number uint64) (string, error) {
  1288. block := api.eth.BlockChain().GetBlockByNumber(number)
  1289. if block == nil {
  1290. return "", fmt.Errorf("block #%d not found", number)
  1291. }
  1292. return fmt.Sprintf("%s", block), nil
  1293. }
  1294. // SeedHash retrieves the seed hash of a block.
  1295. func (api *PublicDebugAPI) SeedHash(number uint64) (string, error) {
  1296. block := api.eth.BlockChain().GetBlockByNumber(number)
  1297. if block == nil {
  1298. return "", fmt.Errorf("block #%d not found", number)
  1299. }
  1300. hash, err := ethash.GetSeedHash(number)
  1301. if err != nil {
  1302. return "", err
  1303. }
  1304. return fmt.Sprintf("0x%x", hash), nil
  1305. }
  1306. // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private
  1307. // debugging endpoint.
  1308. type PrivateDebugAPI struct {
  1309. eth *Ethereum
  1310. }
  1311. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1312. // of the Ethereum service.
  1313. func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI {
  1314. return &PrivateDebugAPI{eth: eth}
  1315. }
  1316. // ProcessBlock reprocesses an already owned block.
  1317. func (api *PrivateDebugAPI) ProcessBlock(number uint64) (bool, error) {
  1318. // Fetch the block that we aim to reprocess
  1319. block := api.eth.BlockChain().GetBlockByNumber(number)
  1320. if block == nil {
  1321. return false, fmt.Errorf("block #%d not found", number)
  1322. }
  1323. // Temporarily enable debugging
  1324. defer func(old bool) { vm.Debug = old }(vm.Debug)
  1325. vm.Debug = true
  1326. // Validate and reprocess the block
  1327. var (
  1328. blockchain = api.eth.BlockChain()
  1329. validator = blockchain.Validator()
  1330. processor = blockchain.Processor()
  1331. )
  1332. if err := core.ValidateHeader(blockchain.AuxValidator(), block.Header(), blockchain.GetHeader(block.ParentHash()), true, false); err != nil {
  1333. return false, err
  1334. }
  1335. statedb, err := state.New(blockchain.GetBlock(block.ParentHash()).Root(), api.eth.ChainDb())
  1336. if err != nil {
  1337. return false, err
  1338. }
  1339. receipts, _, usedGas, err := processor.Process(block, statedb)
  1340. if err != nil {
  1341. return false, err
  1342. }
  1343. if err := validator.ValidateState(block, blockchain.GetBlock(block.ParentHash()), statedb, receipts, usedGas); err != nil {
  1344. return false, err
  1345. }
  1346. return true, nil
  1347. }
  1348. // SetHead rewinds the head of the blockchain to a previous block.
  1349. func (api *PrivateDebugAPI) SetHead(number uint64) {
  1350. api.eth.BlockChain().SetHead(number)
  1351. }
  1352. // StructLogRes stores a structured log emitted by the evm while replaying a
  1353. // transaction in debug mode
  1354. type structLogRes struct {
  1355. Pc uint64 `json:"pc"`
  1356. Op string `json:"op"`
  1357. Gas *big.Int `json:"gas"`
  1358. GasCost *big.Int `json:"gasCost"`
  1359. Error error `json:"error"`
  1360. Stack []string `json:"stack"`
  1361. Memory map[string]string `json:"memory"`
  1362. Storage map[string]string `json:"storage"`
  1363. }
  1364. // TransactionExecutionRes groups all structured logs emitted by the evm
  1365. // while replaying a transaction in debug mode as well as the amount of
  1366. // gas used and the return value
  1367. type TransactionExecutionResult struct {
  1368. Gas *big.Int `json:"gas"`
  1369. ReturnValue string `json:"returnValue"`
  1370. StructLogs []structLogRes `json:"structLogs"`
  1371. }
  1372. func (s *PrivateDebugAPI) doReplayTransaction(txHash common.Hash) ([]vm.StructLog, []byte, *big.Int, error) {
  1373. // Retrieve the tx from the chain
  1374. tx, _, blockIndex, _ := core.GetTransaction(s.eth.ChainDb(), txHash)
  1375. if tx == nil {
  1376. return nil, nil, nil, fmt.Errorf("Transaction not found")
  1377. }
  1378. block := s.eth.BlockChain().GetBlockByNumber(blockIndex - 1)
  1379. if block == nil {
  1380. return nil, nil, nil, fmt.Errorf("Unable to retrieve prior block")
  1381. }
  1382. // Create the state database
  1383. stateDb, err := state.New(block.Root(), s.eth.ChainDb())
  1384. if err != nil {
  1385. return nil, nil, nil, err
  1386. }
  1387. txFrom, err := tx.From()
  1388. if err != nil {
  1389. return nil, nil, nil, fmt.Errorf("Unable to create transaction sender")
  1390. }
  1391. from := stateDb.GetOrNewStateObject(txFrom)
  1392. msg := callmsg{
  1393. from: from,
  1394. to: tx.To(),
  1395. gas: tx.Gas(),
  1396. gasPrice: tx.GasPrice(),
  1397. value: tx.Value(),
  1398. data: tx.Data(),
  1399. }
  1400. vmenv := core.NewEnv(stateDb, s.eth.BlockChain(), msg, block.Header())
  1401. gp := new(core.GasPool).AddGas(block.GasLimit())
  1402. vm.GenerateStructLogs = true
  1403. defer func() { vm.GenerateStructLogs = false }()
  1404. ret, gas, err := core.ApplyMessage(vmenv, msg, gp)
  1405. if err != nil {
  1406. return nil, nil, nil, fmt.Errorf("Error executing transaction %v", err)
  1407. }
  1408. return vmenv.StructLogs(), ret, gas, nil
  1409. }
  1410. // Executes a transaction and returns the structured logs of the evm
  1411. // gathered during the execution
  1412. func (s *PrivateDebugAPI) ReplayTransaction(txHash common.Hash, stackDepth int, memorySize int, storageSize int) (*TransactionExecutionResult, error) {
  1413. structLogs, ret, gas, err := s.doReplayTransaction(txHash)
  1414. if err != nil {
  1415. return nil, err
  1416. }
  1417. res := TransactionExecutionResult{
  1418. Gas: gas,
  1419. ReturnValue: fmt.Sprintf("%x", ret),
  1420. StructLogs: make([]structLogRes, len(structLogs)),
  1421. }
  1422. for index, trace := range structLogs {
  1423. stackLength := len(trace.Stack)
  1424. // Return full stack by default
  1425. if stackDepth != -1 && stackDepth < stackLength {
  1426. stackLength = stackDepth
  1427. }
  1428. res.StructLogs[index] = structLogRes{
  1429. Pc: trace.Pc,
  1430. Op: trace.Op.String(),
  1431. Gas: trace.Gas,
  1432. GasCost: trace.GasCost,
  1433. Error: trace.Err,
  1434. Stack: make([]string, stackLength),
  1435. Memory: make(map[string]string),
  1436. Storage: make(map[string]string),
  1437. }
  1438. for i := 0; i < stackLength; i++ {
  1439. res.StructLogs[index].Stack[i] = fmt.Sprintf("%x", common.LeftPadBytes(trace.Stack[i].Bytes(), 32))
  1440. }
  1441. addr := 0
  1442. memorySizeLocal := memorySize
  1443. // Return full memory by default
  1444. if memorySize == -1 {
  1445. memorySizeLocal = len(trace.Memory)
  1446. }
  1447. for i := 0; i+16 <= len(trace.Memory) && addr < memorySizeLocal; i += 16 {
  1448. res.StructLogs[index].Memory[fmt.Sprintf("%04d", addr*16)] = fmt.Sprintf("%x", trace.Memory[i:i+16])
  1449. addr++
  1450. }
  1451. storageLength := len(trace.Stack)
  1452. if storageSize != -1 && storageSize < storageLength {
  1453. storageLength = storageSize
  1454. }
  1455. i := 0
  1456. for storageIndex, storageValue := range trace.Storage {
  1457. if i >= storageLength {
  1458. break
  1459. }
  1460. res.StructLogs[index].Storage[fmt.Sprintf("%x", storageIndex)] = fmt.Sprintf("%x", storageValue)
  1461. i++
  1462. }
  1463. }
  1464. return &res, nil
  1465. }
  1466. // PublicNetAPI offers network related RPC methods
  1467. type PublicNetAPI struct {
  1468. net *p2p.Server
  1469. networkVersion int
  1470. }
  1471. // NewPublicNetAPI creates a new net api instance.
  1472. func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI {
  1473. return &PublicNetAPI{net, networkVersion}
  1474. }
  1475. // Listening returns an indication if the node is listening for network connections.
  1476. func (s *PublicNetAPI) Listening() bool {
  1477. return true // always listening
  1478. }
  1479. // Peercount returns the number of connected peers
  1480. func (s *PublicNetAPI) PeerCount() *rpc.HexNumber {
  1481. return rpc.NewHexNumber(s.net.PeerCount())
  1482. }
  1483. // ProtocolVersion returns the current ethereum protocol version.
  1484. func (s *PublicNetAPI) Version() string {
  1485. return fmt.Sprintf("%d", s.networkVersion)
  1486. }