api.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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. "receiptsRoot": 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. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  627. func newRPCRawTransactionFromBlockIndex(b *types.Block, txIndex int) (rpc.HexBytes, error) {
  628. if txIndex >= 0 && txIndex < len(b.Transactions()) {
  629. tx := b.Transactions()[txIndex]
  630. return rlp.EncodeToBytes(tx)
  631. }
  632. return nil, nil
  633. }
  634. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  635. func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) {
  636. for idx, tx := range b.Transactions() {
  637. if tx.Hash() == txHash {
  638. return newRPCTransactionFromBlockIndex(b, idx)
  639. }
  640. }
  641. return nil, nil
  642. }
  643. // PublicTransactionPoolAPI exposes methods for the RPC interface
  644. type PublicTransactionPoolAPI struct {
  645. b Backend
  646. }
  647. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  648. func NewPublicTransactionPoolAPI(b Backend) *PublicTransactionPoolAPI {
  649. return &PublicTransactionPoolAPI{b}
  650. }
  651. func getTransaction(chainDb ethdb.Database, b Backend, txHash common.Hash) (*types.Transaction, bool, error) {
  652. txData, err := chainDb.Get(txHash.Bytes())
  653. isPending := false
  654. tx := new(types.Transaction)
  655. if err == nil && len(txData) > 0 {
  656. if err := rlp.DecodeBytes(txData, tx); err != nil {
  657. return nil, isPending, err
  658. }
  659. } else {
  660. // pending transaction?
  661. tx = b.GetPoolTransaction(txHash)
  662. isPending = true
  663. }
  664. return tx, isPending, nil
  665. }
  666. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  667. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *rpc.HexNumber {
  668. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  669. return rpc.NewHexNumber(len(block.Transactions()))
  670. }
  671. return nil
  672. }
  673. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  674. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *rpc.HexNumber {
  675. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  676. return rpc.NewHexNumber(len(block.Transactions()))
  677. }
  678. return nil
  679. }
  680. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  681. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index rpc.HexNumber) (*RPCTransaction, error) {
  682. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  683. return newRPCTransactionFromBlockIndex(block, index.Int())
  684. }
  685. return nil, nil
  686. }
  687. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  688. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index rpc.HexNumber) (*RPCTransaction, error) {
  689. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  690. return newRPCTransactionFromBlockIndex(block, index.Int())
  691. }
  692. return nil, nil
  693. }
  694. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  695. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index rpc.HexNumber) (rpc.HexBytes, error) {
  696. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  697. return newRPCRawTransactionFromBlockIndex(block, index.Int())
  698. }
  699. return nil, nil
  700. }
  701. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  702. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index rpc.HexNumber) (rpc.HexBytes, error) {
  703. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  704. return newRPCRawTransactionFromBlockIndex(block, index.Int())
  705. }
  706. return nil, nil
  707. }
  708. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  709. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*rpc.HexNumber, error) {
  710. state, _, err := s.b.StateAndHeaderByNumber(blockNr)
  711. if state == nil || err != nil {
  712. return nil, err
  713. }
  714. nonce, err := state.GetNonce(ctx, address)
  715. if err != nil {
  716. return nil, err
  717. }
  718. return rpc.NewHexNumber(nonce), nil
  719. }
  720. // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to
  721. // retrieve block information for a hash. It returns the block hash, block index and transaction index.
  722. func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) {
  723. var txBlock struct {
  724. BlockHash common.Hash
  725. BlockIndex uint64
  726. Index uint64
  727. }
  728. blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001))
  729. if err != nil {
  730. return common.Hash{}, uint64(0), uint64(0), err
  731. }
  732. reader := bytes.NewReader(blockData)
  733. if err = rlp.Decode(reader, &txBlock); err != nil {
  734. return common.Hash{}, uint64(0), uint64(0), err
  735. }
  736. return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil
  737. }
  738. // GetTransactionByHash returns the transaction for the given hash
  739. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, txHash common.Hash) (*RPCTransaction, error) {
  740. var tx *types.Transaction
  741. var isPending bool
  742. var err error
  743. if tx, isPending, err = getTransaction(s.b.ChainDb(), s.b, txHash); err != nil {
  744. glog.V(logger.Debug).Infof("%v\n", err)
  745. return nil, nil
  746. } else if tx == nil {
  747. return nil, nil
  748. }
  749. if isPending {
  750. return newRPCPendingTransaction(tx), nil
  751. }
  752. blockHash, _, _, 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. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  758. return newRPCTransaction(block, txHash)
  759. }
  760. return nil, nil
  761. }
  762. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  763. func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, txHash common.Hash) (rpc.HexBytes, error) {
  764. var tx *types.Transaction
  765. var err error
  766. if tx, _, err = getTransaction(s.b.ChainDb(), s.b, txHash); err != nil {
  767. glog.V(logger.Debug).Infof("%v\n", err)
  768. return nil, nil
  769. } else if tx == nil {
  770. return nil, nil
  771. }
  772. return rlp.EncodeToBytes(tx)
  773. }
  774. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  775. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(txHash common.Hash) (map[string]interface{}, error) {
  776. receipt := core.GetReceipt(s.b.ChainDb(), txHash)
  777. if receipt == nil {
  778. glog.V(logger.Debug).Infof("receipt not found for transaction %s", txHash.Hex())
  779. return nil, nil
  780. }
  781. tx, _, err := getTransaction(s.b.ChainDb(), s.b, txHash)
  782. if err != nil {
  783. glog.V(logger.Debug).Infof("%v\n", err)
  784. return nil, nil
  785. }
  786. txBlock, blockIndex, index, err := getTransactionBlockData(s.b.ChainDb(), txHash)
  787. if err != nil {
  788. glog.V(logger.Debug).Infof("%v\n", err)
  789. return nil, nil
  790. }
  791. from, err := tx.FromFrontier()
  792. if err != nil {
  793. glog.V(logger.Debug).Infof("%v\n", err)
  794. return nil, nil
  795. }
  796. fields := map[string]interface{}{
  797. "root": rpc.HexBytes(receipt.PostState),
  798. "blockHash": txBlock,
  799. "blockNumber": rpc.NewHexNumber(blockIndex),
  800. "transactionHash": txHash,
  801. "transactionIndex": rpc.NewHexNumber(index),
  802. "from": from,
  803. "to": tx.To(),
  804. "gasUsed": rpc.NewHexNumber(receipt.GasUsed),
  805. "cumulativeGasUsed": rpc.NewHexNumber(receipt.CumulativeGasUsed),
  806. "contractAddress": nil,
  807. "logs": receipt.Logs,
  808. "logsBloom": receipt.Bloom,
  809. }
  810. if receipt.Logs == nil {
  811. fields["logs"] = []vm.Logs{}
  812. }
  813. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  814. if receipt.ContractAddress != (common.Address{}) {
  815. fields["contractAddress"] = receipt.ContractAddress
  816. }
  817. return fields, nil
  818. }
  819. // sign is a helper function that signs a transaction with the private key of the given address.
  820. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  821. signature, err := s.b.AccountManager().Sign(addr, tx.SigHash().Bytes())
  822. if err != nil {
  823. return nil, err
  824. }
  825. return tx.WithSignature(signature)
  826. }
  827. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  828. type SendTxArgs struct {
  829. From common.Address `json:"from"`
  830. To *common.Address `json:"to"`
  831. Gas *rpc.HexNumber `json:"gas"`
  832. GasPrice *rpc.HexNumber `json:"gasPrice"`
  833. Value *rpc.HexNumber `json:"value"`
  834. Data string `json:"data"`
  835. Nonce *rpc.HexNumber `json:"nonce"`
  836. }
  837. // prepareSendTxArgs is a helper function that fills in default values for unspecified tx fields.
  838. func prepareSendTxArgs(ctx context.Context, args SendTxArgs, b Backend) (SendTxArgs, error) {
  839. if args.Gas == nil {
  840. args.Gas = rpc.NewHexNumber(defaultGas)
  841. }
  842. if args.GasPrice == nil {
  843. price, err := b.SuggestPrice(ctx)
  844. if err != nil {
  845. return args, err
  846. }
  847. args.GasPrice = rpc.NewHexNumber(price)
  848. }
  849. if args.Value == nil {
  850. args.Value = rpc.NewHexNumber(0)
  851. }
  852. return args, nil
  853. }
  854. // submitTransaction is a helper function that submits tx to txPool and creates a log entry.
  855. func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction, signature []byte) (common.Hash, error) {
  856. signedTx, err := tx.WithSignature(signature)
  857. if err != nil {
  858. return common.Hash{}, err
  859. }
  860. if err := b.SendTx(ctx, signedTx); err != nil {
  861. return common.Hash{}, err
  862. }
  863. if signedTx.To() == nil {
  864. from, _ := signedTx.From()
  865. addr := crypto.CreateAddress(from, signedTx.Nonce())
  866. glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signedTx.Hash().Hex(), addr.Hex())
  867. } else {
  868. glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signedTx.Hash().Hex(), tx.To().Hex())
  869. }
  870. return signedTx.Hash(), nil
  871. }
  872. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  873. // transaction pool.
  874. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  875. var err error
  876. args, err = prepareSendTxArgs(ctx, args, s.b)
  877. if err != nil {
  878. return common.Hash{}, err
  879. }
  880. if args.Nonce == nil {
  881. nonce, err := s.b.GetPoolNonce(ctx, args.From)
  882. if err != nil {
  883. return common.Hash{}, err
  884. }
  885. args.Nonce = rpc.NewHexNumber(nonce)
  886. }
  887. var tx *types.Transaction
  888. if args.To == nil {
  889. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  890. } else {
  891. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  892. }
  893. signature, err := s.b.AccountManager().Sign(args.From, tx.SigHash().Bytes())
  894. if err != nil {
  895. return common.Hash{}, err
  896. }
  897. return submitTransaction(ctx, s.b, tx, signature)
  898. }
  899. // SendRawTransaction will add the signed transaction to the transaction pool.
  900. // The sender is responsible for signing the transaction and using the correct nonce.
  901. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx string) (string, error) {
  902. tx := new(types.Transaction)
  903. if err := rlp.DecodeBytes(common.FromHex(encodedTx), tx); err != nil {
  904. return "", err
  905. }
  906. if err := s.b.SendTx(ctx, tx); err != nil {
  907. return "", err
  908. }
  909. if tx.To() == nil {
  910. from, err := tx.FromFrontier()
  911. if err != nil {
  912. return "", err
  913. }
  914. addr := crypto.CreateAddress(from, tx.Nonce())
  915. glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr)
  916. } else {
  917. glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To())
  918. }
  919. return tx.Hash().Hex(), nil
  920. }
  921. // Sign signs the given hash using the key that matches the address. The key must be
  922. // unlocked in order to sign the hash.
  923. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, hash common.Hash) (string, error) {
  924. signature, error := s.b.AccountManager().Sign(addr, hash[:])
  925. return common.ToHex(signature), error
  926. }
  927. // SignTransactionArgs represents the arguments to sign a transaction.
  928. type SignTransactionArgs struct {
  929. From common.Address
  930. To *common.Address
  931. Nonce *rpc.HexNumber
  932. Value *rpc.HexNumber
  933. Gas *rpc.HexNumber
  934. GasPrice *rpc.HexNumber
  935. Data string
  936. BlockNumber int64
  937. }
  938. // Tx is a helper object for argument and return values
  939. type Tx struct {
  940. tx *types.Transaction
  941. To *common.Address `json:"to"`
  942. From common.Address `json:"from"`
  943. Nonce *rpc.HexNumber `json:"nonce"`
  944. Value *rpc.HexNumber `json:"value"`
  945. Data string `json:"data"`
  946. GasLimit *rpc.HexNumber `json:"gas"`
  947. GasPrice *rpc.HexNumber `json:"gasPrice"`
  948. Hash common.Hash `json:"hash"`
  949. }
  950. // UnmarshalJSON parses JSON data into tx.
  951. func (tx *Tx) UnmarshalJSON(b []byte) (err error) {
  952. req := struct {
  953. To *common.Address `json:"to"`
  954. From common.Address `json:"from"`
  955. Nonce *rpc.HexNumber `json:"nonce"`
  956. Value *rpc.HexNumber `json:"value"`
  957. Data string `json:"data"`
  958. GasLimit *rpc.HexNumber `json:"gas"`
  959. GasPrice *rpc.HexNumber `json:"gasPrice"`
  960. Hash common.Hash `json:"hash"`
  961. }{}
  962. if err := json.Unmarshal(b, &req); err != nil {
  963. return err
  964. }
  965. tx.To = req.To
  966. tx.From = req.From
  967. tx.Nonce = req.Nonce
  968. tx.Value = req.Value
  969. tx.Data = req.Data
  970. tx.GasLimit = req.GasLimit
  971. tx.GasPrice = req.GasPrice
  972. tx.Hash = req.Hash
  973. data := common.Hex2Bytes(tx.Data)
  974. if tx.Nonce == nil {
  975. return fmt.Errorf("need nonce")
  976. }
  977. if tx.Value == nil {
  978. tx.Value = rpc.NewHexNumber(0)
  979. }
  980. if tx.GasLimit == nil {
  981. tx.GasLimit = rpc.NewHexNumber(0)
  982. }
  983. if tx.GasPrice == nil {
  984. tx.GasPrice = rpc.NewHexNumber(int64(50000000000))
  985. }
  986. if req.To == nil {
  987. tx.tx = types.NewContractCreation(tx.Nonce.Uint64(), tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  988. } else {
  989. tx.tx = types.NewTransaction(tx.Nonce.Uint64(), *tx.To, tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  990. }
  991. return nil
  992. }
  993. // SignTransactionResult represents a RLP encoded signed transaction.
  994. type SignTransactionResult struct {
  995. Raw string `json:"raw"`
  996. Tx *Tx `json:"tx"`
  997. }
  998. func newTx(t *types.Transaction) *Tx {
  999. from, _ := t.FromFrontier()
  1000. return &Tx{
  1001. tx: t,
  1002. To: t.To(),
  1003. From: from,
  1004. Value: rpc.NewHexNumber(t.Value()),
  1005. Nonce: rpc.NewHexNumber(t.Nonce()),
  1006. Data: "0x" + common.Bytes2Hex(t.Data()),
  1007. GasLimit: rpc.NewHexNumber(t.Gas()),
  1008. GasPrice: rpc.NewHexNumber(t.GasPrice()),
  1009. Hash: t.Hash(),
  1010. }
  1011. }
  1012. // SignTransaction will sign the given transaction with the from account.
  1013. // The node needs to have the private key of the account corresponding with
  1014. // the given from address and it needs to be unlocked.
  1015. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SignTransactionArgs) (*SignTransactionResult, error) {
  1016. if args.Gas == nil {
  1017. args.Gas = rpc.NewHexNumber(defaultGas)
  1018. }
  1019. if args.GasPrice == nil {
  1020. price, err := s.b.SuggestPrice(ctx)
  1021. if err != nil {
  1022. return nil, err
  1023. }
  1024. args.GasPrice = rpc.NewHexNumber(price)
  1025. }
  1026. if args.Value == nil {
  1027. args.Value = rpc.NewHexNumber(0)
  1028. }
  1029. if args.Nonce == nil {
  1030. nonce, err := s.b.GetPoolNonce(ctx, args.From)
  1031. if err != nil {
  1032. return nil, err
  1033. }
  1034. args.Nonce = rpc.NewHexNumber(nonce)
  1035. }
  1036. var tx *types.Transaction
  1037. if args.To == nil {
  1038. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1039. } else {
  1040. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1041. }
  1042. signedTx, err := s.sign(args.From, tx)
  1043. if err != nil {
  1044. return nil, err
  1045. }
  1046. data, err := rlp.EncodeToBytes(signedTx)
  1047. if err != nil {
  1048. return nil, err
  1049. }
  1050. return &SignTransactionResult{"0x" + common.Bytes2Hex(data), newTx(signedTx)}, nil
  1051. }
  1052. // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1053. // the accounts this node manages.
  1054. func (s *PublicTransactionPoolAPI) PendingTransactions() []*RPCTransaction {
  1055. pending := s.b.GetPoolTransactions()
  1056. transactions := make([]*RPCTransaction, 0, len(pending))
  1057. for _, tx := range pending {
  1058. from, _ := tx.FromFrontier()
  1059. if s.b.AccountManager().HasAddress(from) {
  1060. transactions = append(transactions, newRPCPendingTransaction(tx))
  1061. }
  1062. }
  1063. return transactions
  1064. }
  1065. // Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the
  1066. // pool and reinsert it with the new gas price and limit.
  1067. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, tx Tx, gasPrice, gasLimit *rpc.HexNumber) (common.Hash, error) {
  1068. pending := s.b.GetPoolTransactions()
  1069. for _, p := range pending {
  1070. if pFrom, err := p.FromFrontier(); err == nil && pFrom == tx.From && p.SigHash() == tx.tx.SigHash() {
  1071. if gasPrice == nil {
  1072. gasPrice = rpc.NewHexNumber(tx.tx.GasPrice())
  1073. }
  1074. if gasLimit == nil {
  1075. gasLimit = rpc.NewHexNumber(tx.tx.Gas())
  1076. }
  1077. var newTx *types.Transaction
  1078. if tx.tx.To() == nil {
  1079. newTx = types.NewContractCreation(tx.tx.Nonce(), tx.tx.Value(), gasLimit.BigInt(), gasPrice.BigInt(), tx.tx.Data())
  1080. } else {
  1081. newTx = types.NewTransaction(tx.tx.Nonce(), *tx.tx.To(), tx.tx.Value(), gasLimit.BigInt(), gasPrice.BigInt(), tx.tx.Data())
  1082. }
  1083. signedTx, err := s.sign(tx.From, newTx)
  1084. if err != nil {
  1085. return common.Hash{}, err
  1086. }
  1087. s.b.RemoveTx(tx.Hash)
  1088. if err = s.b.SendTx(ctx, signedTx); err != nil {
  1089. return common.Hash{}, err
  1090. }
  1091. return signedTx.Hash(), nil
  1092. }
  1093. }
  1094. return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash)
  1095. }
  1096. // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
  1097. // debugging endpoint.
  1098. type PublicDebugAPI struct {
  1099. b Backend
  1100. }
  1101. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1102. // of the Ethereum service.
  1103. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1104. return &PublicDebugAPI{b: b}
  1105. }
  1106. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1107. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1108. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1109. if block == nil {
  1110. return "", fmt.Errorf("block #%d not found", number)
  1111. }
  1112. encoded, err := rlp.EncodeToBytes(block)
  1113. if err != nil {
  1114. return "", err
  1115. }
  1116. return fmt.Sprintf("%x", encoded), nil
  1117. }
  1118. // PrintBlock retrieves a block and returns its pretty printed form.
  1119. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1120. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1121. if block == nil {
  1122. return "", fmt.Errorf("block #%d not found", number)
  1123. }
  1124. return fmt.Sprintf("%s", block), nil
  1125. }
  1126. // SeedHash retrieves the seed hash of a block.
  1127. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1128. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1129. if block == nil {
  1130. return "", fmt.Errorf("block #%d not found", number)
  1131. }
  1132. hash, err := ethash.GetSeedHash(number)
  1133. if err != nil {
  1134. return "", err
  1135. }
  1136. return fmt.Sprintf("0x%x", hash), nil
  1137. }
  1138. // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private
  1139. // debugging endpoint.
  1140. type PrivateDebugAPI struct {
  1141. b Backend
  1142. }
  1143. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1144. // of the Ethereum service.
  1145. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1146. return &PrivateDebugAPI{b: b}
  1147. }
  1148. // ChaindbProperty returns leveldb properties of the chain database.
  1149. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1150. ldb, ok := api.b.ChainDb().(interface {
  1151. LDB() *leveldb.DB
  1152. })
  1153. if !ok {
  1154. return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1155. }
  1156. if property == "" {
  1157. property = "leveldb.stats"
  1158. } else if !strings.HasPrefix(property, "leveldb.") {
  1159. property = "leveldb." + property
  1160. }
  1161. return ldb.LDB().GetProperty(property)
  1162. }
  1163. // SetHead rewinds the head of the blockchain to a previous block.
  1164. func (api *PrivateDebugAPI) SetHead(number rpc.HexNumber) {
  1165. api.b.SetHead(uint64(number.Int64()))
  1166. }
  1167. // PublicNetAPI offers network related RPC methods
  1168. type PublicNetAPI struct {
  1169. net *p2p.Server
  1170. networkVersion int
  1171. }
  1172. // NewPublicNetAPI creates a new net API instance.
  1173. func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI {
  1174. return &PublicNetAPI{net, networkVersion}
  1175. }
  1176. // Listening returns an indication if the node is listening for network connections.
  1177. func (s *PublicNetAPI) Listening() bool {
  1178. return true // always listening
  1179. }
  1180. // PeerCount returns the number of connected peers
  1181. func (s *PublicNetAPI) PeerCount() *rpc.HexNumber {
  1182. return rpc.NewHexNumber(s.net.PeerCount())
  1183. }
  1184. // Version returns the current ethereum protocol version.
  1185. func (s *PublicNetAPI) Version() string {
  1186. return fmt.Sprintf("%d", s.networkVersion)
  1187. }