api.go 53 KB

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