api.go 65 KB

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