api.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. // Copyright 2016 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 ethapi
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "encoding/json"
  21. "fmt"
  22. "math/big"
  23. "strings"
  24. "time"
  25. "github.com/ethereum/ethash"
  26. "github.com/ethereum/go-ethereum/accounts"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/logger"
  34. "github.com/ethereum/go-ethereum/logger/glog"
  35. "github.com/ethereum/go-ethereum/p2p"
  36. "github.com/ethereum/go-ethereum/rlp"
  37. "github.com/ethereum/go-ethereum/rpc"
  38. "github.com/syndtr/goleveldb/leveldb"
  39. "golang.org/x/net/context"
  40. )
  41. const defaultGas = uint64(90000)
  42. // PublicEthereumAPI provides an API to access Ethereum related information.
  43. // It offers only methods that operate on public data that is freely available to anyone.
  44. type PublicEthereumAPI struct {
  45. b Backend
  46. }
  47. // NewPublicEthereumAPI creates a new Etheruem protocol API.
  48. func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
  49. return &PublicEthereumAPI{b}
  50. }
  51. // GasPrice returns a suggestion for a gas price.
  52. func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*big.Int, error) {
  53. return s.b.SuggestPrice(ctx)
  54. }
  55. // ProtocolVersion returns the current Ethereum protocol version this node supports
  56. func (s *PublicEthereumAPI) ProtocolVersion() *rpc.HexNumber {
  57. return rpc.NewHexNumber(s.b.ProtocolVersion())
  58. }
  59. // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
  60. // yet received the latest block headers from its pears. In case it is synchronizing:
  61. // - startingBlock: block number this node started to synchronise from
  62. // - currentBlock: block number this node is currently importing
  63. // - highestBlock: block number of the highest block header this node has received from peers
  64. // - pulledStates: number of state entries processed until now
  65. // - knownStates: number of known state entries that still need to be pulled
  66. func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
  67. progress := s.b.Downloader().Progress()
  68. // Return not syncing if the synchronisation already completed
  69. if progress.CurrentBlock >= progress.HighestBlock {
  70. return false, nil
  71. }
  72. // Otherwise gather the block sync stats
  73. return map[string]interface{}{
  74. "startingBlock": rpc.NewHexNumber(progress.StartingBlock),
  75. "currentBlock": rpc.NewHexNumber(progress.CurrentBlock),
  76. "highestBlock": rpc.NewHexNumber(progress.HighestBlock),
  77. "pulledStates": rpc.NewHexNumber(progress.PulledStates),
  78. "knownStates": rpc.NewHexNumber(progress.KnownStates),
  79. }, nil
  80. }
  81. // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
  82. type PublicTxPoolAPI struct {
  83. b Backend
  84. }
  85. // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
  86. func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI {
  87. return &PublicTxPoolAPI{b}
  88. }
  89. // Content returns the transactions contained within the transaction pool.
  90. func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
  91. content := map[string]map[string]map[string]*RPCTransaction{
  92. "pending": make(map[string]map[string]*RPCTransaction),
  93. "queued": make(map[string]map[string]*RPCTransaction),
  94. }
  95. pending, queue := s.b.TxPoolContent()
  96. // Flatten the pending transactions
  97. for account, txs := range pending {
  98. dump := make(map[string]*RPCTransaction)
  99. for nonce, tx := range txs {
  100. dump[fmt.Sprintf("%d", nonce)] = newRPCPendingTransaction(tx)
  101. }
  102. content["pending"][account.Hex()] = dump
  103. }
  104. // Flatten the queued transactions
  105. for account, txs := range queue {
  106. dump := make(map[string]*RPCTransaction)
  107. for nonce, tx := range txs {
  108. dump[fmt.Sprintf("%d", nonce)] = newRPCPendingTransaction(tx)
  109. }
  110. content["queued"][account.Hex()] = dump
  111. }
  112. return content
  113. }
  114. // Status returns the number of pending and queued transaction in the pool.
  115. func (s *PublicTxPoolAPI) Status() map[string]*rpc.HexNumber {
  116. pending, queue := s.b.Stats()
  117. return map[string]*rpc.HexNumber{
  118. "pending": rpc.NewHexNumber(pending),
  119. "queued": rpc.NewHexNumber(queue),
  120. }
  121. }
  122. // Inspect retrieves the content of the transaction pool and flattens it into an
  123. // easily inspectable list.
  124. func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string {
  125. content := map[string]map[string]map[string]string{
  126. "pending": make(map[string]map[string]string),
  127. "queued": make(map[string]map[string]string),
  128. }
  129. pending, queue := s.b.TxPoolContent()
  130. // Define a formatter to flatten a transaction into a string
  131. var format = func(tx *types.Transaction) string {
  132. if to := tx.To(); to != nil {
  133. return fmt.Sprintf("%s: %v wei + %v × %v gas", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
  134. }
  135. return fmt.Sprintf("contract creation: %v wei + %v × %v gas", tx.Value(), tx.Gas(), tx.GasPrice())
  136. }
  137. // Flatten the pending transactions
  138. for account, txs := range pending {
  139. dump := make(map[string]string)
  140. for nonce, tx := range txs {
  141. dump[fmt.Sprintf("%d", nonce)] = format(tx)
  142. }
  143. content["pending"][account.Hex()] = dump
  144. }
  145. // Flatten the queued transactions
  146. for account, txs := range queue {
  147. dump := make(map[string]string)
  148. for nonce, tx := range txs {
  149. dump[fmt.Sprintf("%d", nonce)] = format(tx)
  150. }
  151. content["queued"][account.Hex()] = dump
  152. }
  153. return content
  154. }
  155. // PublicAccountAPI provides an API to access accounts managed by this node.
  156. // It offers only methods that can retrieve accounts.
  157. type PublicAccountAPI struct {
  158. am *accounts.Manager
  159. }
  160. // NewPublicAccountAPI creates a new PublicAccountAPI.
  161. func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
  162. return &PublicAccountAPI{am: am}
  163. }
  164. // Accounts returns the collection of accounts this node manages
  165. func (s *PublicAccountAPI) Accounts() []accounts.Account {
  166. return s.am.Accounts()
  167. }
  168. // PrivateAccountAPI provides an API to access accounts managed by this node.
  169. // It offers methods to create, (un)lock en list accounts. Some methods accept
  170. // passwords and are therefore considered private by default.
  171. type PrivateAccountAPI struct {
  172. am *accounts.Manager
  173. b Backend
  174. }
  175. // NewPrivateAccountAPI create a new PrivateAccountAPI.
  176. func NewPrivateAccountAPI(b Backend) *PrivateAccountAPI {
  177. return &PrivateAccountAPI{
  178. am: b.AccountManager(),
  179. b: b,
  180. }
  181. }
  182. // ListAccounts will return a list of addresses for accounts this node manages.
  183. func (s *PrivateAccountAPI) ListAccounts() []common.Address {
  184. accounts := s.am.Accounts()
  185. addresses := make([]common.Address, len(accounts))
  186. for i, acc := range accounts {
  187. addresses[i] = acc.Address
  188. }
  189. return addresses
  190. }
  191. // NewAccount will create a new account and returns the address for the new account.
  192. func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
  193. acc, err := s.am.NewAccount(password)
  194. if err == nil {
  195. return acc.Address, nil
  196. }
  197. return common.Address{}, err
  198. }
  199. // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
  200. // encrypting it with the passphrase.
  201. func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
  202. hexkey, err := hex.DecodeString(privkey)
  203. if err != nil {
  204. return common.Address{}, err
  205. }
  206. acc, err := s.am.ImportECDSA(crypto.ToECDSA(hexkey), password)
  207. return acc.Address, err
  208. }
  209. // UnlockAccount will unlock the account associated with the given address with
  210. // the given password for duration seconds. If duration is nil it will use a
  211. // default of 300 seconds. It returns an indication if the account was unlocked.
  212. func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *rpc.HexNumber) (bool, error) {
  213. if duration == nil {
  214. duration = rpc.NewHexNumber(300)
  215. }
  216. a := accounts.Account{Address: addr}
  217. d := time.Duration(duration.Int64()) * time.Second
  218. if err := s.am.TimedUnlock(a, password, d); err != nil {
  219. return false, err
  220. }
  221. return true, nil
  222. }
  223. // LockAccount will lock the account associated with the given address when it's unlocked.
  224. func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
  225. return s.am.Lock(addr) == nil
  226. }
  227. // SendTransaction will create a transaction from the given arguments and
  228. // tries to sign it with the key associated with args.To. If the given passwd isn't
  229. // able to decrypt the key it fails.
  230. func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  231. var err error
  232. args, err = prepareSendTxArgs(ctx, args, s.b)
  233. if err != nil {
  234. return common.Hash{}, err
  235. }
  236. if args.Nonce == nil {
  237. nonce, err := s.b.GetPoolNonce(ctx, args.From)
  238. if err != nil {
  239. return common.Hash{}, err
  240. }
  241. args.Nonce = rpc.NewHexNumber(nonce)
  242. }
  243. var tx *types.Transaction
  244. if args.To == nil {
  245. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  246. } else {
  247. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  248. }
  249. signature, err := s.am.SignWithPassphrase(args.From, passwd, tx.SigHash().Bytes())
  250. if err != nil {
  251. return common.Hash{}, err
  252. }
  253. return submitTransaction(ctx, s.b, tx, signature)
  254. }
  255. // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
  256. // and will be removed in the future. It primary goal is to give clients time to update.
  257. func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  258. return s.SendTransaction(ctx, args, passwd)
  259. }
  260. // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
  261. // It offers only methods that operate on public data that is freely available to anyone.
  262. type PublicBlockChainAPI struct {
  263. b Backend
  264. }
  265. // NewPublicBlockChainAPI creates a new Etheruem blockchain API.
  266. func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
  267. return &PublicBlockChainAPI{b}
  268. }
  269. // BlockNumber returns the block number of the chain head.
  270. func (s *PublicBlockChainAPI) BlockNumber() *big.Int {
  271. return s.b.HeaderByNumber(rpc.LatestBlockNumber).Number
  272. }
  273. // GetBalance returns the amount of wei for the given address in the state of the
  274. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  275. // block numbers are also allowed.
  276. func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) {
  277. state, _, err := s.b.StateAndHeaderByNumber(blockNr)
  278. if state == nil || err != nil {
  279. return nil, err
  280. }
  281. return state.GetBalance(ctx, address)
  282. }
  283. // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
  284. // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  285. func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  286. block, err := s.b.BlockByNumber(ctx, blockNr)
  287. if block != nil {
  288. response, err := s.rpcOutputBlock(block, true, fullTx)
  289. if err == nil && blockNr == rpc.PendingBlockNumber {
  290. // Pending blocks need to nil out a few fields
  291. for _, field := range []string{"hash", "nonce", "logsBloom", "miner"} {
  292. response[field] = nil
  293. }
  294. }
  295. return response, err
  296. }
  297. return nil, err
  298. }
  299. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  300. // detail, otherwise only the transaction hash is returned.
  301. func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
  302. block, err := s.b.GetBlock(ctx, blockHash)
  303. if block != nil {
  304. return s.rpcOutputBlock(block, true, fullTx)
  305. }
  306. return nil, err
  307. }
  308. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  309. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  310. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index rpc.HexNumber) (map[string]interface{}, error) {
  311. block, err := s.b.BlockByNumber(ctx, blockNr)
  312. if block != nil {
  313. uncles := block.Uncles()
  314. if index.Int() < 0 || index.Int() >= len(uncles) {
  315. glog.V(logger.Debug).Infof("uncle block on index %d not found for block #%d", index.Int(), blockNr)
  316. return nil, nil
  317. }
  318. block = types.NewBlockWithHeader(uncles[index.Int()])
  319. return s.rpcOutputBlock(block, false, false)
  320. }
  321. return nil, err
  322. }
  323. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  324. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  325. func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index rpc.HexNumber) (map[string]interface{}, error) {
  326. block, err := s.b.GetBlock(ctx, blockHash)
  327. if block != nil {
  328. uncles := block.Uncles()
  329. if index.Int() < 0 || index.Int() >= len(uncles) {
  330. glog.V(logger.Debug).Infof("uncle block on index %d not found for block %s", index.Int(), blockHash.Hex())
  331. return nil, nil
  332. }
  333. block = types.NewBlockWithHeader(uncles[index.Int()])
  334. return s.rpcOutputBlock(block, false, false)
  335. }
  336. return nil, err
  337. }
  338. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  339. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *rpc.HexNumber {
  340. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  341. return rpc.NewHexNumber(len(block.Uncles()))
  342. }
  343. return nil
  344. }
  345. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  346. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *rpc.HexNumber {
  347. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  348. return rpc.NewHexNumber(len(block.Uncles()))
  349. }
  350. return nil
  351. }
  352. // GetCode returns the code stored at the given address in the state for the given block number.
  353. func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (string, error) {
  354. state, _, err := s.b.StateAndHeaderByNumber(blockNr)
  355. if state == nil || err != nil {
  356. return "", err
  357. }
  358. res, err := state.GetCode(ctx, address)
  359. if len(res) == 0 || err != nil { // backwards compatibility
  360. return "0x", err
  361. }
  362. return common.ToHex(res), nil
  363. }
  364. // GetStorageAt returns the storage from the state at the given address, key and
  365. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  366. // numbers are also allowed.
  367. func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (string, error) {
  368. state, _, err := s.b.StateAndHeaderByNumber(blockNr)
  369. if state == nil || err != nil {
  370. return "0x", err
  371. }
  372. res, err := state.GetState(ctx, address, common.HexToHash(key))
  373. if err != nil {
  374. return "0x", err
  375. }
  376. return res.Hex(), nil
  377. }
  378. // callmsg is the message type used for call transations.
  379. type callmsg struct {
  380. addr common.Address
  381. to *common.Address
  382. gas, gasPrice *big.Int
  383. value *big.Int
  384. data []byte
  385. }
  386. // accessor boilerplate to implement core.Message
  387. func (m callmsg) From() (common.Address, error) { return m.addr, nil }
  388. func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil }
  389. func (m callmsg) Nonce() uint64 { return 0 }
  390. func (m callmsg) CheckNonce() bool { return false }
  391. func (m callmsg) To() *common.Address { return m.to }
  392. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  393. func (m callmsg) Gas() *big.Int { return m.gas }
  394. func (m callmsg) Value() *big.Int { return m.value }
  395. func (m callmsg) Data() []byte { return m.data }
  396. // CallArgs represents the arguments for a call.
  397. type CallArgs struct {
  398. From common.Address `json:"from"`
  399. To *common.Address `json:"to"`
  400. Gas rpc.HexNumber `json:"gas"`
  401. GasPrice rpc.HexNumber `json:"gasPrice"`
  402. Value rpc.HexNumber `json:"value"`
  403. Data string `json:"data"`
  404. }
  405. func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (string, *big.Int, error) {
  406. defer func(start time.Time) { glog.V(logger.Debug).Infof("call took %v", time.Since(start)) }(time.Now())
  407. state, header, err := s.b.StateAndHeaderByNumber(blockNr)
  408. if state == nil || err != nil {
  409. return "0x", common.Big0, err
  410. }
  411. // Set the account address to interact with
  412. var addr common.Address
  413. if args.From == (common.Address{}) {
  414. accounts := s.b.AccountManager().Accounts()
  415. if len(accounts) == 0 {
  416. addr = common.Address{}
  417. } else {
  418. addr = accounts[0].Address
  419. }
  420. } else {
  421. addr = args.From
  422. }
  423. // Assemble the CALL invocation
  424. msg := callmsg{
  425. addr: addr,
  426. to: args.To,
  427. gas: args.Gas.BigInt(),
  428. gasPrice: args.GasPrice.BigInt(),
  429. value: args.Value.BigInt(),
  430. data: common.FromHex(args.Data),
  431. }
  432. if msg.gas.Cmp(common.Big0) == 0 {
  433. msg.gas = big.NewInt(50000000)
  434. }
  435. if msg.gasPrice.Cmp(common.Big0) == 0 {
  436. msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
  437. }
  438. // Execute the call and return
  439. vmenv, vmError, err := s.b.GetVMEnv(ctx, msg, state, header)
  440. if err != nil {
  441. return "0x", common.Big0, err
  442. }
  443. gp := new(core.GasPool).AddGas(common.MaxBig)
  444. res, gas, err := core.ApplyMessage(vmenv, msg, gp)
  445. if err := vmError(); err != nil {
  446. return "0x", common.Big0, err
  447. }
  448. if len(res) == 0 { // backwards compatability
  449. return "0x", gas, err
  450. }
  451. return common.ToHex(res), gas, err
  452. }
  453. // Call executes the given transaction on the state for the given block number.
  454. // It doesn't make and changes in the state/blockchain and is usefull to execute and retrieve values.
  455. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (string, error) {
  456. result, _, err := s.doCall(ctx, args, blockNr)
  457. return result, err
  458. }
  459. // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
  460. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (*rpc.HexNumber, error) {
  461. _, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber)
  462. return rpc.NewHexNumber(gas), err
  463. }
  464. // ExecutionResult groups all structured logs emitted by the EVM
  465. // while replaying a transaction in debug mode as well as the amount of
  466. // gas used and the return value
  467. type ExecutionResult struct {
  468. Gas *big.Int `json:"gas"`
  469. ReturnValue string `json:"returnValue"`
  470. StructLogs []StructLogRes `json:"structLogs"`
  471. }
  472. // StructLogRes stores a structured log emitted by the EVM while replaying a
  473. // transaction in debug mode
  474. type StructLogRes struct {
  475. Pc uint64 `json:"pc"`
  476. Op string `json:"op"`
  477. Gas *big.Int `json:"gas"`
  478. GasCost *big.Int `json:"gasCost"`
  479. Depth int `json:"depth"`
  480. Error error `json:"error"`
  481. Stack []string `json:"stack"`
  482. Memory []string `json:"memory"`
  483. Storage map[string]string `json:"storage"`
  484. }
  485. // formatLogs formats EVM returned structured logs for json output
  486. func FormatLogs(structLogs []vm.StructLog) []StructLogRes {
  487. formattedStructLogs := make([]StructLogRes, len(structLogs))
  488. for index, trace := range structLogs {
  489. formattedStructLogs[index] = StructLogRes{
  490. Pc: trace.Pc,
  491. Op: trace.Op.String(),
  492. Gas: trace.Gas,
  493. GasCost: trace.GasCost,
  494. Depth: trace.Depth,
  495. Error: trace.Err,
  496. Stack: make([]string, len(trace.Stack)),
  497. Storage: make(map[string]string),
  498. }
  499. for i, stackValue := range trace.Stack {
  500. formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", common.LeftPadBytes(stackValue.Bytes(), 32))
  501. }
  502. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  503. formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  504. }
  505. for i, storageValue := range trace.Storage {
  506. formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  507. }
  508. }
  509. return formattedStructLogs
  510. }
  511. // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  512. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  513. // transaction hashes.
  514. func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  515. head := b.Header() // copies the header once
  516. fields := map[string]interface{}{
  517. "number": rpc.NewHexNumber(head.Number),
  518. "hash": b.Hash(),
  519. "parentHash": head.ParentHash,
  520. "nonce": head.Nonce,
  521. "mixHash": head.MixDigest,
  522. "sha3Uncles": head.UncleHash,
  523. "logsBloom": head.Bloom,
  524. "stateRoot": head.Root,
  525. "miner": head.Coinbase,
  526. "difficulty": rpc.NewHexNumber(head.Difficulty),
  527. "totalDifficulty": rpc.NewHexNumber(s.b.GetTd(b.Hash())),
  528. "extraData": rpc.HexBytes(head.Extra),
  529. "size": rpc.NewHexNumber(b.Size().Int64()),
  530. "gasLimit": rpc.NewHexNumber(head.GasLimit),
  531. "gasUsed": rpc.NewHexNumber(head.GasUsed),
  532. "timestamp": rpc.NewHexNumber(head.Time),
  533. "transactionsRoot": head.TxHash,
  534. "receiptRoot": head.ReceiptHash,
  535. }
  536. if inclTx {
  537. formatTx := func(tx *types.Transaction) (interface{}, error) {
  538. return tx.Hash(), nil
  539. }
  540. if fullTx {
  541. formatTx = func(tx *types.Transaction) (interface{}, error) {
  542. return newRPCTransaction(b, tx.Hash())
  543. }
  544. }
  545. txs := b.Transactions()
  546. transactions := make([]interface{}, len(txs))
  547. var err error
  548. for i, tx := range b.Transactions() {
  549. if transactions[i], err = formatTx(tx); err != nil {
  550. return nil, err
  551. }
  552. }
  553. fields["transactions"] = transactions
  554. }
  555. uncles := b.Uncles()
  556. uncleHashes := make([]common.Hash, len(uncles))
  557. for i, uncle := range uncles {
  558. uncleHashes[i] = uncle.Hash()
  559. }
  560. fields["uncles"] = uncleHashes
  561. return fields, nil
  562. }
  563. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  564. type RPCTransaction struct {
  565. BlockHash common.Hash `json:"blockHash"`
  566. BlockNumber *rpc.HexNumber `json:"blockNumber"`
  567. From common.Address `json:"from"`
  568. Gas *rpc.HexNumber `json:"gas"`
  569. GasPrice *rpc.HexNumber `json:"gasPrice"`
  570. Hash common.Hash `json:"hash"`
  571. Input rpc.HexBytes `json:"input"`
  572. Nonce *rpc.HexNumber `json:"nonce"`
  573. To *common.Address `json:"to"`
  574. TransactionIndex *rpc.HexNumber `json:"transactionIndex"`
  575. Value *rpc.HexNumber `json:"value"`
  576. V *rpc.HexNumber `json:"v"`
  577. R *rpc.HexNumber `json:"r"`
  578. S *rpc.HexNumber `json:"s"`
  579. }
  580. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  581. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  582. from, _ := tx.FromFrontier()
  583. v, r, s := tx.SignatureValues()
  584. return &RPCTransaction{
  585. From: from,
  586. Gas: rpc.NewHexNumber(tx.Gas()),
  587. GasPrice: rpc.NewHexNumber(tx.GasPrice()),
  588. Hash: tx.Hash(),
  589. Input: rpc.HexBytes(tx.Data()),
  590. Nonce: rpc.NewHexNumber(tx.Nonce()),
  591. To: tx.To(),
  592. Value: rpc.NewHexNumber(tx.Value()),
  593. V: rpc.NewHexNumber(v),
  594. R: rpc.NewHexNumber(r),
  595. S: rpc.NewHexNumber(s),
  596. }
  597. }
  598. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  599. func newRPCTransactionFromBlockIndex(b *types.Block, txIndex int) (*RPCTransaction, error) {
  600. if txIndex >= 0 && txIndex < len(b.Transactions()) {
  601. tx := b.Transactions()[txIndex]
  602. from, err := tx.FromFrontier()
  603. if err != nil {
  604. return nil, err
  605. }
  606. v, r, s := tx.SignatureValues()
  607. return &RPCTransaction{
  608. BlockHash: b.Hash(),
  609. BlockNumber: rpc.NewHexNumber(b.Number()),
  610. From: from,
  611. Gas: rpc.NewHexNumber(tx.Gas()),
  612. GasPrice: rpc.NewHexNumber(tx.GasPrice()),
  613. Hash: tx.Hash(),
  614. Input: rpc.HexBytes(tx.Data()),
  615. Nonce: rpc.NewHexNumber(tx.Nonce()),
  616. To: tx.To(),
  617. TransactionIndex: rpc.NewHexNumber(txIndex),
  618. Value: rpc.NewHexNumber(tx.Value()),
  619. V: rpc.NewHexNumber(v),
  620. R: rpc.NewHexNumber(r),
  621. S: rpc.NewHexNumber(s),
  622. }, nil
  623. }
  624. return nil, nil
  625. }
  626. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  627. func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) {
  628. for idx, tx := range b.Transactions() {
  629. if tx.Hash() == txHash {
  630. return newRPCTransactionFromBlockIndex(b, idx)
  631. }
  632. }
  633. return nil, nil
  634. }
  635. // PublicTransactionPoolAPI exposes methods for the RPC interface
  636. type PublicTransactionPoolAPI struct {
  637. b Backend
  638. }
  639. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  640. func NewPublicTransactionPoolAPI(b Backend) *PublicTransactionPoolAPI {
  641. return &PublicTransactionPoolAPI{b}
  642. }
  643. func getTransaction(chainDb ethdb.Database, b Backend, txHash common.Hash) (*types.Transaction, bool, error) {
  644. txData, err := chainDb.Get(txHash.Bytes())
  645. isPending := false
  646. tx := new(types.Transaction)
  647. if err == nil && len(txData) > 0 {
  648. if err := rlp.DecodeBytes(txData, tx); err != nil {
  649. return nil, isPending, err
  650. }
  651. } else {
  652. // pending transaction?
  653. tx = b.GetPoolTransaction(txHash)
  654. isPending = true
  655. }
  656. return tx, isPending, nil
  657. }
  658. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  659. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *rpc.HexNumber {
  660. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  661. return rpc.NewHexNumber(len(block.Transactions()))
  662. }
  663. return nil
  664. }
  665. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  666. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *rpc.HexNumber {
  667. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  668. return rpc.NewHexNumber(len(block.Transactions()))
  669. }
  670. return nil
  671. }
  672. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  673. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index rpc.HexNumber) (*RPCTransaction, error) {
  674. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  675. return newRPCTransactionFromBlockIndex(block, index.Int())
  676. }
  677. return nil, nil
  678. }
  679. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  680. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index rpc.HexNumber) (*RPCTransaction, error) {
  681. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  682. return newRPCTransactionFromBlockIndex(block, index.Int())
  683. }
  684. return nil, nil
  685. }
  686. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  687. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*rpc.HexNumber, error) {
  688. state, _, err := s.b.StateAndHeaderByNumber(blockNr)
  689. if state == nil || err != nil {
  690. return nil, err
  691. }
  692. nonce, err := state.GetNonce(ctx, address)
  693. if err != nil {
  694. return nil, err
  695. }
  696. return rpc.NewHexNumber(nonce), nil
  697. }
  698. // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to
  699. // retrieve block information for a hash. It returns the block hash, block index and transaction index.
  700. func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) {
  701. var txBlock struct {
  702. BlockHash common.Hash
  703. BlockIndex uint64
  704. Index uint64
  705. }
  706. blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001))
  707. if err != nil {
  708. return common.Hash{}, uint64(0), uint64(0), err
  709. }
  710. reader := bytes.NewReader(blockData)
  711. if err = rlp.Decode(reader, &txBlock); err != nil {
  712. return common.Hash{}, uint64(0), uint64(0), err
  713. }
  714. return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil
  715. }
  716. // GetTransactionByHash returns the transaction for the given hash
  717. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, txHash common.Hash) (*RPCTransaction, error) {
  718. var tx *types.Transaction
  719. var isPending bool
  720. var err error
  721. if tx, isPending, err = getTransaction(s.b.ChainDb(), s.b, txHash); err != nil {
  722. glog.V(logger.Debug).Infof("%v\n", err)
  723. return nil, nil
  724. } else if tx == nil {
  725. return nil, nil
  726. }
  727. if isPending {
  728. return newRPCPendingTransaction(tx), nil
  729. }
  730. blockHash, _, _, err := getTransactionBlockData(s.b.ChainDb(), txHash)
  731. if err != nil {
  732. glog.V(logger.Debug).Infof("%v\n", err)
  733. return nil, nil
  734. }
  735. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  736. return newRPCTransaction(block, txHash)
  737. }
  738. return nil, nil
  739. }
  740. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  741. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(txHash common.Hash) (map[string]interface{}, error) {
  742. receipt := core.GetReceipt(s.b.ChainDb(), txHash)
  743. if receipt == nil {
  744. glog.V(logger.Debug).Infof("receipt not found for transaction %s", txHash.Hex())
  745. return nil, nil
  746. }
  747. tx, _, err := getTransaction(s.b.ChainDb(), s.b, txHash)
  748. if err != nil {
  749. glog.V(logger.Debug).Infof("%v\n", err)
  750. return nil, nil
  751. }
  752. txBlock, blockIndex, index, err := getTransactionBlockData(s.b.ChainDb(), txHash)
  753. if err != nil {
  754. glog.V(logger.Debug).Infof("%v\n", err)
  755. return nil, nil
  756. }
  757. from, err := tx.FromFrontier()
  758. if err != nil {
  759. glog.V(logger.Debug).Infof("%v\n", err)
  760. return nil, nil
  761. }
  762. fields := map[string]interface{}{
  763. "root": rpc.HexBytes(receipt.PostState),
  764. "blockHash": txBlock,
  765. "blockNumber": rpc.NewHexNumber(blockIndex),
  766. "transactionHash": txHash,
  767. "transactionIndex": rpc.NewHexNumber(index),
  768. "from": from,
  769. "to": tx.To(),
  770. "gasUsed": rpc.NewHexNumber(receipt.GasUsed),
  771. "cumulativeGasUsed": rpc.NewHexNumber(receipt.CumulativeGasUsed),
  772. "contractAddress": nil,
  773. "logs": receipt.Logs,
  774. "logsBloom": receipt.Bloom,
  775. }
  776. if receipt.Logs == nil {
  777. fields["logs"] = []vm.Logs{}
  778. }
  779. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  780. if receipt.ContractAddress != (common.Address{}) {
  781. fields["contractAddress"] = receipt.ContractAddress
  782. }
  783. return fields, nil
  784. }
  785. // sign is a helper function that signs a transaction with the private key of the given address.
  786. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  787. signature, err := s.b.AccountManager().Sign(addr, tx.SigHash().Bytes())
  788. if err != nil {
  789. return nil, err
  790. }
  791. return tx.WithSignature(signature)
  792. }
  793. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  794. type SendTxArgs struct {
  795. From common.Address `json:"from"`
  796. To *common.Address `json:"to"`
  797. Gas *rpc.HexNumber `json:"gas"`
  798. GasPrice *rpc.HexNumber `json:"gasPrice"`
  799. Value *rpc.HexNumber `json:"value"`
  800. Data string `json:"data"`
  801. Nonce *rpc.HexNumber `json:"nonce"`
  802. }
  803. // prepareSendTxArgs is a helper function that fills in default values for unspecified tx fields.
  804. func prepareSendTxArgs(ctx context.Context, args SendTxArgs, b Backend) (SendTxArgs, error) {
  805. if args.Gas == nil {
  806. args.Gas = rpc.NewHexNumber(defaultGas)
  807. }
  808. if args.GasPrice == nil {
  809. price, err := b.SuggestPrice(ctx)
  810. if err != nil {
  811. return args, err
  812. }
  813. args.GasPrice = rpc.NewHexNumber(price)
  814. }
  815. if args.Value == nil {
  816. args.Value = rpc.NewHexNumber(0)
  817. }
  818. return args, nil
  819. }
  820. // submitTransaction is a helper function that submits tx to txPool and creates a log entry.
  821. func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction, signature []byte) (common.Hash, error) {
  822. signedTx, err := tx.WithSignature(signature)
  823. if err != nil {
  824. return common.Hash{}, err
  825. }
  826. if err := b.SendTx(ctx, signedTx); err != nil {
  827. return common.Hash{}, err
  828. }
  829. if signedTx.To() == nil {
  830. from, _ := signedTx.From()
  831. addr := crypto.CreateAddress(from, signedTx.Nonce())
  832. glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signedTx.Hash().Hex(), addr.Hex())
  833. } else {
  834. glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signedTx.Hash().Hex(), tx.To().Hex())
  835. }
  836. return signedTx.Hash(), nil
  837. }
  838. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  839. // transaction pool.
  840. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  841. var err error
  842. args, err = prepareSendTxArgs(ctx, args, s.b)
  843. if err != nil {
  844. return common.Hash{}, err
  845. }
  846. if args.Nonce == nil {
  847. nonce, err := s.b.GetPoolNonce(ctx, args.From)
  848. if err != nil {
  849. return common.Hash{}, err
  850. }
  851. args.Nonce = rpc.NewHexNumber(nonce)
  852. }
  853. var tx *types.Transaction
  854. if args.To == nil {
  855. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  856. } else {
  857. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  858. }
  859. signature, err := s.b.AccountManager().Sign(args.From, tx.SigHash().Bytes())
  860. if err != nil {
  861. return common.Hash{}, err
  862. }
  863. return submitTransaction(ctx, s.b, tx, signature)
  864. }
  865. // SendRawTransaction will add the signed transaction to the transaction pool.
  866. // The sender is responsible for signing the transaction and using the correct nonce.
  867. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx string) (string, error) {
  868. tx := new(types.Transaction)
  869. if err := rlp.DecodeBytes(common.FromHex(encodedTx), tx); err != nil {
  870. return "", err
  871. }
  872. if err := s.b.SendTx(ctx, tx); err != nil {
  873. return "", err
  874. }
  875. if tx.To() == nil {
  876. from, err := tx.FromFrontier()
  877. if err != nil {
  878. return "", err
  879. }
  880. addr := crypto.CreateAddress(from, tx.Nonce())
  881. glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr)
  882. } else {
  883. glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To())
  884. }
  885. return tx.Hash().Hex(), nil
  886. }
  887. // Sign signs the given hash using the key that matches the address. The key must be
  888. // unlocked in order to sign the hash.
  889. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, hash common.Hash) (string, error) {
  890. signature, error := s.b.AccountManager().Sign(addr, hash[:])
  891. return common.ToHex(signature), error
  892. }
  893. // SignTransactionArgs represents the arguments to sign a transaction.
  894. type SignTransactionArgs struct {
  895. From common.Address
  896. To *common.Address
  897. Nonce *rpc.HexNumber
  898. Value *rpc.HexNumber
  899. Gas *rpc.HexNumber
  900. GasPrice *rpc.HexNumber
  901. Data string
  902. BlockNumber int64
  903. }
  904. // Tx is a helper object for argument and return values
  905. type Tx struct {
  906. tx *types.Transaction
  907. To *common.Address `json:"to"`
  908. From common.Address `json:"from"`
  909. Nonce *rpc.HexNumber `json:"nonce"`
  910. Value *rpc.HexNumber `json:"value"`
  911. Data string `json:"data"`
  912. GasLimit *rpc.HexNumber `json:"gas"`
  913. GasPrice *rpc.HexNumber `json:"gasPrice"`
  914. Hash common.Hash `json:"hash"`
  915. }
  916. // UnmarshalJSON parses JSON data into tx.
  917. func (tx *Tx) UnmarshalJSON(b []byte) (err error) {
  918. req := struct {
  919. To *common.Address `json:"to"`
  920. From common.Address `json:"from"`
  921. Nonce *rpc.HexNumber `json:"nonce"`
  922. Value *rpc.HexNumber `json:"value"`
  923. Data string `json:"data"`
  924. GasLimit *rpc.HexNumber `json:"gas"`
  925. GasPrice *rpc.HexNumber `json:"gasPrice"`
  926. Hash common.Hash `json:"hash"`
  927. }{}
  928. if err := json.Unmarshal(b, &req); err != nil {
  929. return err
  930. }
  931. tx.To = req.To
  932. tx.From = req.From
  933. tx.Nonce = req.Nonce
  934. tx.Value = req.Value
  935. tx.Data = req.Data
  936. tx.GasLimit = req.GasLimit
  937. tx.GasPrice = req.GasPrice
  938. tx.Hash = req.Hash
  939. data := common.Hex2Bytes(tx.Data)
  940. if tx.Nonce == nil {
  941. return fmt.Errorf("need nonce")
  942. }
  943. if tx.Value == nil {
  944. tx.Value = rpc.NewHexNumber(0)
  945. }
  946. if tx.GasLimit == nil {
  947. tx.GasLimit = rpc.NewHexNumber(0)
  948. }
  949. if tx.GasPrice == nil {
  950. tx.GasPrice = rpc.NewHexNumber(int64(50000000000))
  951. }
  952. if req.To == nil {
  953. tx.tx = types.NewContractCreation(tx.Nonce.Uint64(), tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  954. } else {
  955. tx.tx = types.NewTransaction(tx.Nonce.Uint64(), *tx.To, tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  956. }
  957. return nil
  958. }
  959. // SignTransactionResult represents a RLP encoded signed transaction.
  960. type SignTransactionResult struct {
  961. Raw string `json:"raw"`
  962. Tx *Tx `json:"tx"`
  963. }
  964. func newTx(t *types.Transaction) *Tx {
  965. from, _ := t.FromFrontier()
  966. return &Tx{
  967. tx: t,
  968. To: t.To(),
  969. From: from,
  970. Value: rpc.NewHexNumber(t.Value()),
  971. Nonce: rpc.NewHexNumber(t.Nonce()),
  972. Data: "0x" + common.Bytes2Hex(t.Data()),
  973. GasLimit: rpc.NewHexNumber(t.Gas()),
  974. GasPrice: rpc.NewHexNumber(t.GasPrice()),
  975. Hash: t.Hash(),
  976. }
  977. }
  978. // SignTransaction will sign the given transaction with the from account.
  979. // The node needs to have the private key of the account corresponding with
  980. // the given from address and it needs to be unlocked.
  981. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SignTransactionArgs) (*SignTransactionResult, error) {
  982. if args.Gas == nil {
  983. args.Gas = rpc.NewHexNumber(defaultGas)
  984. }
  985. if args.GasPrice == nil {
  986. price, err := s.b.SuggestPrice(ctx)
  987. if err != nil {
  988. return nil, err
  989. }
  990. args.GasPrice = rpc.NewHexNumber(price)
  991. }
  992. if args.Value == nil {
  993. args.Value = rpc.NewHexNumber(0)
  994. }
  995. if args.Nonce == nil {
  996. nonce, err := s.b.GetPoolNonce(ctx, args.From)
  997. if err != nil {
  998. return nil, err
  999. }
  1000. args.Nonce = rpc.NewHexNumber(nonce)
  1001. }
  1002. var tx *types.Transaction
  1003. if args.To == nil {
  1004. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1005. } else {
  1006. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1007. }
  1008. signedTx, err := s.sign(args.From, tx)
  1009. if err != nil {
  1010. return nil, err
  1011. }
  1012. data, err := rlp.EncodeToBytes(signedTx)
  1013. if err != nil {
  1014. return nil, err
  1015. }
  1016. return &SignTransactionResult{"0x" + common.Bytes2Hex(data), newTx(signedTx)}, nil
  1017. }
  1018. // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1019. // the accounts this node manages.
  1020. func (s *PublicTransactionPoolAPI) PendingTransactions() []*RPCTransaction {
  1021. pending := s.b.GetPoolTransactions()
  1022. transactions := make([]*RPCTransaction, 0, len(pending))
  1023. for _, tx := range pending {
  1024. from, _ := tx.FromFrontier()
  1025. if s.b.AccountManager().HasAddress(from) {
  1026. transactions = append(transactions, newRPCPendingTransaction(tx))
  1027. }
  1028. }
  1029. return transactions
  1030. }
  1031. // Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the
  1032. // pool and reinsert it with the new gas price and limit.
  1033. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, tx *Tx, gasPrice, gasLimit *rpc.HexNumber) (common.Hash, error) {
  1034. pending := s.b.GetPoolTransactions()
  1035. for _, p := range pending {
  1036. if pFrom, err := p.FromFrontier(); err == nil && pFrom == tx.From && p.SigHash() == tx.tx.SigHash() {
  1037. if gasPrice == nil {
  1038. gasPrice = rpc.NewHexNumber(tx.tx.GasPrice())
  1039. }
  1040. if gasLimit == nil {
  1041. gasLimit = rpc.NewHexNumber(tx.tx.Gas())
  1042. }
  1043. var newTx *types.Transaction
  1044. if tx.tx.To() == nil {
  1045. newTx = types.NewContractCreation(tx.tx.Nonce(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1046. } else {
  1047. newTx = types.NewTransaction(tx.tx.Nonce(), *tx.tx.To(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1048. }
  1049. signedTx, err := s.sign(tx.From, newTx)
  1050. if err != nil {
  1051. return common.Hash{}, err
  1052. }
  1053. s.b.RemoveTx(tx.Hash)
  1054. if err = s.b.SendTx(ctx, signedTx); err != nil {
  1055. return common.Hash{}, err
  1056. }
  1057. return signedTx.Hash(), nil
  1058. }
  1059. }
  1060. return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash)
  1061. }
  1062. // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
  1063. // debugging endpoint.
  1064. type PublicDebugAPI struct {
  1065. b Backend
  1066. }
  1067. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1068. // of the Ethereum service.
  1069. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1070. return &PublicDebugAPI{b: b}
  1071. }
  1072. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1073. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1074. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1075. if block == nil {
  1076. return "", fmt.Errorf("block #%d not found", number)
  1077. }
  1078. encoded, err := rlp.EncodeToBytes(block)
  1079. if err != nil {
  1080. return "", err
  1081. }
  1082. return fmt.Sprintf("%x", encoded), nil
  1083. }
  1084. // PrintBlock retrieves a block and returns its pretty printed form.
  1085. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1086. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1087. if block == nil {
  1088. return "", fmt.Errorf("block #%d not found", number)
  1089. }
  1090. return fmt.Sprintf("%s", block), nil
  1091. }
  1092. // SeedHash retrieves the seed hash of a block.
  1093. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1094. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1095. if block == nil {
  1096. return "", fmt.Errorf("block #%d not found", number)
  1097. }
  1098. hash, err := ethash.GetSeedHash(number)
  1099. if err != nil {
  1100. return "", err
  1101. }
  1102. return fmt.Sprintf("0x%x", hash), nil
  1103. }
  1104. // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private
  1105. // debugging endpoint.
  1106. type PrivateDebugAPI struct {
  1107. b Backend
  1108. }
  1109. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1110. // of the Ethereum service.
  1111. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1112. return &PrivateDebugAPI{b: b}
  1113. }
  1114. // ChaindbProperty returns leveldb properties of the chain database.
  1115. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1116. ldb, ok := api.b.ChainDb().(interface {
  1117. LDB() *leveldb.DB
  1118. })
  1119. if !ok {
  1120. return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1121. }
  1122. if property == "" {
  1123. property = "leveldb.stats"
  1124. } else if !strings.HasPrefix(property, "leveldb.") {
  1125. property = "leveldb." + property
  1126. }
  1127. return ldb.LDB().GetProperty(property)
  1128. }
  1129. // SetHead rewinds the head of the blockchain to a previous block.
  1130. func (api *PrivateDebugAPI) SetHead(number rpc.HexNumber) {
  1131. api.b.SetHead(uint64(number.Int64()))
  1132. }
  1133. // PublicNetAPI offers network related RPC methods
  1134. type PublicNetAPI struct {
  1135. net *p2p.Server
  1136. networkVersion int
  1137. }
  1138. // NewPublicNetAPI creates a new net API instance.
  1139. func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI {
  1140. return &PublicNetAPI{net, networkVersion}
  1141. }
  1142. // Listening returns an indication if the node is listening for network connections.
  1143. func (s *PublicNetAPI) Listening() bool {
  1144. return true // always listening
  1145. }
  1146. // PeerCount returns the number of connected peers
  1147. func (s *PublicNetAPI) PeerCount() *rpc.HexNumber {
  1148. return rpc.NewHexNumber(s.net.PeerCount())
  1149. }
  1150. // Version returns the current ethereum protocol version.
  1151. func (s *PublicNetAPI) Version() string {
  1152. return fmt.Sprintf("%d", s.networkVersion)
  1153. }