api.go 65 KB

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