api.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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. state, header, err := s.b.StateAndHeaderByNumber(blockNr)
  407. if state == nil || err != nil {
  408. return "0x", common.Big0, err
  409. }
  410. // Set the account address to interact with
  411. var addr common.Address
  412. if args.From == (common.Address{}) {
  413. accounts := s.b.AccountManager().Accounts()
  414. if len(accounts) == 0 {
  415. addr = common.Address{}
  416. } else {
  417. addr = accounts[0].Address
  418. }
  419. } else {
  420. addr = args.From
  421. }
  422. // Assemble the CALL invocation
  423. msg := callmsg{
  424. addr: addr,
  425. to: args.To,
  426. gas: args.Gas.BigInt(),
  427. gasPrice: args.GasPrice.BigInt(),
  428. value: args.Value.BigInt(),
  429. data: common.FromHex(args.Data),
  430. }
  431. if msg.gas.Cmp(common.Big0) == 0 {
  432. msg.gas = big.NewInt(50000000)
  433. }
  434. if msg.gasPrice.Cmp(common.Big0) == 0 {
  435. msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
  436. }
  437. // Execute the call and return
  438. vmenv, vmError, err := s.b.GetVMEnv(ctx, msg, state, header)
  439. if err != nil {
  440. return "0x", common.Big0, err
  441. }
  442. gp := new(core.GasPool).AddGas(common.MaxBig)
  443. res, gas, err := core.ApplyMessage(vmenv, msg, gp)
  444. if err := vmError(); err != nil {
  445. return "0x", common.Big0, err
  446. }
  447. if len(res) == 0 { // backwards compatability
  448. return "0x", gas, err
  449. }
  450. return common.ToHex(res), gas, err
  451. }
  452. // Call executes the given transaction on the state for the given block number.
  453. // It doesn't make and changes in the state/blockchain and is usefull to execute and retrieve values.
  454. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (string, error) {
  455. result, _, err := s.doCall(ctx, args, blockNr)
  456. return result, err
  457. }
  458. // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
  459. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (*rpc.HexNumber, error) {
  460. _, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber)
  461. return rpc.NewHexNumber(gas), err
  462. }
  463. // ExecutionResult groups all structured logs emitted by the EVM
  464. // while replaying a transaction in debug mode as well as the amount of
  465. // gas used and the return value
  466. type ExecutionResult struct {
  467. Gas *big.Int `json:"gas"`
  468. ReturnValue string `json:"returnValue"`
  469. StructLogs []StructLogRes `json:"structLogs"`
  470. }
  471. // StructLogRes stores a structured log emitted by the EVM while replaying a
  472. // transaction in debug mode
  473. type StructLogRes struct {
  474. Pc uint64 `json:"pc"`
  475. Op string `json:"op"`
  476. Gas *big.Int `json:"gas"`
  477. GasCost *big.Int `json:"gasCost"`
  478. Depth int `json:"depth"`
  479. Error error `json:"error"`
  480. Stack []string `json:"stack"`
  481. Memory []string `json:"memory"`
  482. Storage map[string]string `json:"storage"`
  483. }
  484. // formatLogs formats EVM returned structured logs for json output
  485. func FormatLogs(structLogs []vm.StructLog) []StructLogRes {
  486. formattedStructLogs := make([]StructLogRes, len(structLogs))
  487. for index, trace := range structLogs {
  488. formattedStructLogs[index] = StructLogRes{
  489. Pc: trace.Pc,
  490. Op: trace.Op.String(),
  491. Gas: trace.Gas,
  492. GasCost: trace.GasCost,
  493. Depth: trace.Depth,
  494. Error: trace.Err,
  495. Stack: make([]string, len(trace.Stack)),
  496. Storage: make(map[string]string),
  497. }
  498. for i, stackValue := range trace.Stack {
  499. formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", common.LeftPadBytes(stackValue.Bytes(), 32))
  500. }
  501. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  502. formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  503. }
  504. for i, storageValue := range trace.Storage {
  505. formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  506. }
  507. }
  508. return formattedStructLogs
  509. }
  510. // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  511. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  512. // transaction hashes.
  513. func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  514. head := b.Header() // copies the header once
  515. fields := map[string]interface{}{
  516. "number": rpc.NewHexNumber(head.Number),
  517. "hash": b.Hash(),
  518. "parentHash": head.ParentHash,
  519. "nonce": head.Nonce,
  520. "mixHash": head.MixDigest,
  521. "sha3Uncles": head.UncleHash,
  522. "logsBloom": head.Bloom,
  523. "stateRoot": head.Root,
  524. "miner": head.Coinbase,
  525. "difficulty": rpc.NewHexNumber(head.Difficulty),
  526. "totalDifficulty": rpc.NewHexNumber(s.b.GetTd(b.Hash())),
  527. "extraData": rpc.HexBytes(head.Extra),
  528. "size": rpc.NewHexNumber(b.Size().Int64()),
  529. "gasLimit": rpc.NewHexNumber(head.GasLimit),
  530. "gasUsed": rpc.NewHexNumber(head.GasUsed),
  531. "timestamp": rpc.NewHexNumber(head.Time),
  532. "transactionsRoot": head.TxHash,
  533. "receiptRoot": head.ReceiptHash,
  534. }
  535. if inclTx {
  536. formatTx := func(tx *types.Transaction) (interface{}, error) {
  537. return tx.Hash(), nil
  538. }
  539. if fullTx {
  540. formatTx = func(tx *types.Transaction) (interface{}, error) {
  541. return newRPCTransaction(b, tx.Hash())
  542. }
  543. }
  544. txs := b.Transactions()
  545. transactions := make([]interface{}, len(txs))
  546. var err error
  547. for i, tx := range b.Transactions() {
  548. if transactions[i], err = formatTx(tx); err != nil {
  549. return nil, err
  550. }
  551. }
  552. fields["transactions"] = transactions
  553. }
  554. uncles := b.Uncles()
  555. uncleHashes := make([]common.Hash, len(uncles))
  556. for i, uncle := range uncles {
  557. uncleHashes[i] = uncle.Hash()
  558. }
  559. fields["uncles"] = uncleHashes
  560. return fields, nil
  561. }
  562. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  563. type RPCTransaction struct {
  564. BlockHash common.Hash `json:"blockHash"`
  565. BlockNumber *rpc.HexNumber `json:"blockNumber"`
  566. From common.Address `json:"from"`
  567. Gas *rpc.HexNumber `json:"gas"`
  568. GasPrice *rpc.HexNumber `json:"gasPrice"`
  569. Hash common.Hash `json:"hash"`
  570. Input rpc.HexBytes `json:"input"`
  571. Nonce *rpc.HexNumber `json:"nonce"`
  572. To *common.Address `json:"to"`
  573. TransactionIndex *rpc.HexNumber `json:"transactionIndex"`
  574. Value *rpc.HexNumber `json:"value"`
  575. V *rpc.HexNumber `json:"v"`
  576. R *rpc.HexNumber `json:"r"`
  577. S *rpc.HexNumber `json:"s"`
  578. }
  579. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  580. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  581. from, _ := tx.FromFrontier()
  582. v, r, s := tx.SignatureValues()
  583. return &RPCTransaction{
  584. From: from,
  585. Gas: rpc.NewHexNumber(tx.Gas()),
  586. GasPrice: rpc.NewHexNumber(tx.GasPrice()),
  587. Hash: tx.Hash(),
  588. Input: rpc.HexBytes(tx.Data()),
  589. Nonce: rpc.NewHexNumber(tx.Nonce()),
  590. To: tx.To(),
  591. Value: rpc.NewHexNumber(tx.Value()),
  592. V: rpc.NewHexNumber(v),
  593. R: rpc.NewHexNumber(r),
  594. S: rpc.NewHexNumber(s),
  595. }
  596. }
  597. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  598. func newRPCTransactionFromBlockIndex(b *types.Block, txIndex int) (*RPCTransaction, error) {
  599. if txIndex >= 0 && txIndex < len(b.Transactions()) {
  600. tx := b.Transactions()[txIndex]
  601. from, err := tx.FromFrontier()
  602. if err != nil {
  603. return nil, err
  604. }
  605. v, r, s := tx.SignatureValues()
  606. return &RPCTransaction{
  607. BlockHash: b.Hash(),
  608. BlockNumber: rpc.NewHexNumber(b.Number()),
  609. From: from,
  610. Gas: rpc.NewHexNumber(tx.Gas()),
  611. GasPrice: rpc.NewHexNumber(tx.GasPrice()),
  612. Hash: tx.Hash(),
  613. Input: rpc.HexBytes(tx.Data()),
  614. Nonce: rpc.NewHexNumber(tx.Nonce()),
  615. To: tx.To(),
  616. TransactionIndex: rpc.NewHexNumber(txIndex),
  617. Value: rpc.NewHexNumber(tx.Value()),
  618. V: rpc.NewHexNumber(v),
  619. R: rpc.NewHexNumber(r),
  620. S: rpc.NewHexNumber(s),
  621. }, nil
  622. }
  623. return nil, nil
  624. }
  625. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  626. func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) {
  627. for idx, tx := range b.Transactions() {
  628. if tx.Hash() == txHash {
  629. return newRPCTransactionFromBlockIndex(b, idx)
  630. }
  631. }
  632. return nil, nil
  633. }
  634. // PublicTransactionPoolAPI exposes methods for the RPC interface
  635. type PublicTransactionPoolAPI struct {
  636. b Backend
  637. }
  638. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  639. func NewPublicTransactionPoolAPI(b Backend) *PublicTransactionPoolAPI {
  640. return &PublicTransactionPoolAPI{b}
  641. }
  642. func getTransaction(chainDb ethdb.Database, b Backend, txHash common.Hash) (*types.Transaction, bool, error) {
  643. txData, err := chainDb.Get(txHash.Bytes())
  644. isPending := false
  645. tx := new(types.Transaction)
  646. if err == nil && len(txData) > 0 {
  647. if err := rlp.DecodeBytes(txData, tx); err != nil {
  648. return nil, isPending, err
  649. }
  650. } else {
  651. // pending transaction?
  652. tx = b.GetPoolTransaction(txHash)
  653. isPending = true
  654. }
  655. return tx, isPending, nil
  656. }
  657. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  658. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *rpc.HexNumber {
  659. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  660. return rpc.NewHexNumber(len(block.Transactions()))
  661. }
  662. return nil
  663. }
  664. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  665. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *rpc.HexNumber {
  666. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  667. return rpc.NewHexNumber(len(block.Transactions()))
  668. }
  669. return nil
  670. }
  671. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  672. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index rpc.HexNumber) (*RPCTransaction, error) {
  673. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  674. return newRPCTransactionFromBlockIndex(block, index.Int())
  675. }
  676. return nil, nil
  677. }
  678. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  679. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index rpc.HexNumber) (*RPCTransaction, error) {
  680. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  681. return newRPCTransactionFromBlockIndex(block, index.Int())
  682. }
  683. return nil, nil
  684. }
  685. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  686. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*rpc.HexNumber, error) {
  687. state, _, err := s.b.StateAndHeaderByNumber(blockNr)
  688. if state == nil || err != nil {
  689. return nil, err
  690. }
  691. nonce, err := state.GetNonce(ctx, address)
  692. if err != nil {
  693. return nil, err
  694. }
  695. return rpc.NewHexNumber(nonce), nil
  696. }
  697. // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to
  698. // retrieve block information for a hash. It returns the block hash, block index and transaction index.
  699. func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) {
  700. var txBlock struct {
  701. BlockHash common.Hash
  702. BlockIndex uint64
  703. Index uint64
  704. }
  705. blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001))
  706. if err != nil {
  707. return common.Hash{}, uint64(0), uint64(0), err
  708. }
  709. reader := bytes.NewReader(blockData)
  710. if err = rlp.Decode(reader, &txBlock); err != nil {
  711. return common.Hash{}, uint64(0), uint64(0), err
  712. }
  713. return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil
  714. }
  715. // GetTransactionByHash returns the transaction for the given hash
  716. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, txHash common.Hash) (*RPCTransaction, error) {
  717. var tx *types.Transaction
  718. var isPending bool
  719. var err error
  720. if tx, isPending, err = getTransaction(s.b.ChainDb(), s.b, txHash); err != nil {
  721. glog.V(logger.Debug).Infof("%v\n", err)
  722. return nil, nil
  723. } else if tx == nil {
  724. return nil, nil
  725. }
  726. if isPending {
  727. return newRPCPendingTransaction(tx), nil
  728. }
  729. blockHash, _, _, err := getTransactionBlockData(s.b.ChainDb(), txHash)
  730. if err != nil {
  731. glog.V(logger.Debug).Infof("%v\n", err)
  732. return nil, nil
  733. }
  734. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  735. return newRPCTransaction(block, txHash)
  736. }
  737. return nil, nil
  738. }
  739. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  740. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(txHash common.Hash) (map[string]interface{}, error) {
  741. receipt := core.GetReceipt(s.b.ChainDb(), txHash)
  742. if receipt == nil {
  743. glog.V(logger.Debug).Infof("receipt not found for transaction %s", txHash.Hex())
  744. return nil, nil
  745. }
  746. tx, _, err := getTransaction(s.b.ChainDb(), s.b, txHash)
  747. if err != nil {
  748. glog.V(logger.Debug).Infof("%v\n", err)
  749. return nil, nil
  750. }
  751. txBlock, blockIndex, index, err := getTransactionBlockData(s.b.ChainDb(), txHash)
  752. if err != nil {
  753. glog.V(logger.Debug).Infof("%v\n", err)
  754. return nil, nil
  755. }
  756. from, err := tx.FromFrontier()
  757. if err != nil {
  758. glog.V(logger.Debug).Infof("%v\n", err)
  759. return nil, nil
  760. }
  761. fields := map[string]interface{}{
  762. "root": rpc.HexBytes(receipt.PostState),
  763. "blockHash": txBlock,
  764. "blockNumber": rpc.NewHexNumber(blockIndex),
  765. "transactionHash": txHash,
  766. "transactionIndex": rpc.NewHexNumber(index),
  767. "from": from,
  768. "to": tx.To(),
  769. "gasUsed": rpc.NewHexNumber(receipt.GasUsed),
  770. "cumulativeGasUsed": rpc.NewHexNumber(receipt.CumulativeGasUsed),
  771. "contractAddress": nil,
  772. "logs": receipt.Logs,
  773. "logsBloom": receipt.Bloom,
  774. }
  775. if receipt.Logs == nil {
  776. fields["logs"] = []vm.Logs{}
  777. }
  778. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  779. if receipt.ContractAddress != (common.Address{}) {
  780. fields["contractAddress"] = receipt.ContractAddress
  781. }
  782. return fields, nil
  783. }
  784. // sign is a helper function that signs a transaction with the private key of the given address.
  785. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  786. signature, err := s.b.AccountManager().Sign(addr, tx.SigHash().Bytes())
  787. if err != nil {
  788. return nil, err
  789. }
  790. return tx.WithSignature(signature)
  791. }
  792. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  793. type SendTxArgs struct {
  794. From common.Address `json:"from"`
  795. To *common.Address `json:"to"`
  796. Gas *rpc.HexNumber `json:"gas"`
  797. GasPrice *rpc.HexNumber `json:"gasPrice"`
  798. Value *rpc.HexNumber `json:"value"`
  799. Data string `json:"data"`
  800. Nonce *rpc.HexNumber `json:"nonce"`
  801. }
  802. // prepareSendTxArgs is a helper function that fills in default values for unspecified tx fields.
  803. func prepareSendTxArgs(ctx context.Context, args SendTxArgs, b Backend) (SendTxArgs, error) {
  804. if args.Gas == nil {
  805. args.Gas = rpc.NewHexNumber(defaultGas)
  806. }
  807. if args.GasPrice == nil {
  808. price, err := b.SuggestPrice(ctx)
  809. if err != nil {
  810. return args, err
  811. }
  812. args.GasPrice = rpc.NewHexNumber(price)
  813. }
  814. if args.Value == nil {
  815. args.Value = rpc.NewHexNumber(0)
  816. }
  817. return args, nil
  818. }
  819. // submitTransaction is a helper function that submits tx to txPool and creates a log entry.
  820. func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction, signature []byte) (common.Hash, error) {
  821. signedTx, err := tx.WithSignature(signature)
  822. if err != nil {
  823. return common.Hash{}, err
  824. }
  825. if err := b.SendTx(ctx, signedTx); err != nil {
  826. return common.Hash{}, err
  827. }
  828. if signedTx.To() == nil {
  829. from, _ := signedTx.From()
  830. addr := crypto.CreateAddress(from, signedTx.Nonce())
  831. glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signedTx.Hash().Hex(), addr.Hex())
  832. } else {
  833. glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signedTx.Hash().Hex(), tx.To().Hex())
  834. }
  835. return signedTx.Hash(), nil
  836. }
  837. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  838. // transaction pool.
  839. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  840. var err error
  841. args, err = prepareSendTxArgs(ctx, args, s.b)
  842. if err != nil {
  843. return common.Hash{}, err
  844. }
  845. if args.Nonce == nil {
  846. nonce, err := s.b.GetPoolNonce(ctx, args.From)
  847. if err != nil {
  848. return common.Hash{}, err
  849. }
  850. args.Nonce = rpc.NewHexNumber(nonce)
  851. }
  852. var tx *types.Transaction
  853. if args.To == nil {
  854. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  855. } else {
  856. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  857. }
  858. signature, err := s.b.AccountManager().Sign(args.From, tx.SigHash().Bytes())
  859. if err != nil {
  860. return common.Hash{}, err
  861. }
  862. return submitTransaction(ctx, s.b, tx, signature)
  863. }
  864. // SendRawTransaction will add the signed transaction to the transaction pool.
  865. // The sender is responsible for signing the transaction and using the correct nonce.
  866. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx string) (string, error) {
  867. tx := new(types.Transaction)
  868. if err := rlp.DecodeBytes(common.FromHex(encodedTx), tx); err != nil {
  869. return "", err
  870. }
  871. if err := s.b.SendTx(ctx, tx); err != nil {
  872. return "", err
  873. }
  874. if tx.To() == nil {
  875. from, err := tx.FromFrontier()
  876. if err != nil {
  877. return "", err
  878. }
  879. addr := crypto.CreateAddress(from, tx.Nonce())
  880. glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr)
  881. } else {
  882. glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To())
  883. }
  884. return tx.Hash().Hex(), nil
  885. }
  886. // Sign signs the given hash using the key that matches the address. The key must be
  887. // unlocked in order to sign the hash.
  888. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, hash common.Hash) (string, error) {
  889. signature, error := s.b.AccountManager().Sign(addr, hash[:])
  890. return common.ToHex(signature), error
  891. }
  892. // SignTransactionArgs represents the arguments to sign a transaction.
  893. type SignTransactionArgs struct {
  894. From common.Address
  895. To *common.Address
  896. Nonce *rpc.HexNumber
  897. Value *rpc.HexNumber
  898. Gas *rpc.HexNumber
  899. GasPrice *rpc.HexNumber
  900. Data string
  901. BlockNumber int64
  902. }
  903. // Tx is a helper object for argument and return values
  904. type Tx struct {
  905. tx *types.Transaction
  906. To *common.Address `json:"to"`
  907. From common.Address `json:"from"`
  908. Nonce *rpc.HexNumber `json:"nonce"`
  909. Value *rpc.HexNumber `json:"value"`
  910. Data string `json:"data"`
  911. GasLimit *rpc.HexNumber `json:"gas"`
  912. GasPrice *rpc.HexNumber `json:"gasPrice"`
  913. Hash common.Hash `json:"hash"`
  914. }
  915. // UnmarshalJSON parses JSON data into tx.
  916. func (tx *Tx) UnmarshalJSON(b []byte) (err error) {
  917. req := struct {
  918. To *common.Address `json:"to"`
  919. From common.Address `json:"from"`
  920. Nonce *rpc.HexNumber `json:"nonce"`
  921. Value *rpc.HexNumber `json:"value"`
  922. Data string `json:"data"`
  923. GasLimit *rpc.HexNumber `json:"gas"`
  924. GasPrice *rpc.HexNumber `json:"gasPrice"`
  925. Hash common.Hash `json:"hash"`
  926. }{}
  927. if err := json.Unmarshal(b, &req); err != nil {
  928. return err
  929. }
  930. tx.To = req.To
  931. tx.From = req.From
  932. tx.Nonce = req.Nonce
  933. tx.Value = req.Value
  934. tx.Data = req.Data
  935. tx.GasLimit = req.GasLimit
  936. tx.GasPrice = req.GasPrice
  937. tx.Hash = req.Hash
  938. data := common.Hex2Bytes(tx.Data)
  939. if tx.Nonce == nil {
  940. return fmt.Errorf("need nonce")
  941. }
  942. if tx.Value == nil {
  943. tx.Value = rpc.NewHexNumber(0)
  944. }
  945. if tx.GasLimit == nil {
  946. tx.GasLimit = rpc.NewHexNumber(0)
  947. }
  948. if tx.GasPrice == nil {
  949. tx.GasPrice = rpc.NewHexNumber(int64(50000000000))
  950. }
  951. if req.To == nil {
  952. tx.tx = types.NewContractCreation(tx.Nonce.Uint64(), tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  953. } else {
  954. tx.tx = types.NewTransaction(tx.Nonce.Uint64(), *tx.To, tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data)
  955. }
  956. return nil
  957. }
  958. // SignTransactionResult represents a RLP encoded signed transaction.
  959. type SignTransactionResult struct {
  960. Raw string `json:"raw"`
  961. Tx *Tx `json:"tx"`
  962. }
  963. func newTx(t *types.Transaction) *Tx {
  964. from, _ := t.FromFrontier()
  965. return &Tx{
  966. tx: t,
  967. To: t.To(),
  968. From: from,
  969. Value: rpc.NewHexNumber(t.Value()),
  970. Nonce: rpc.NewHexNumber(t.Nonce()),
  971. Data: "0x" + common.Bytes2Hex(t.Data()),
  972. GasLimit: rpc.NewHexNumber(t.Gas()),
  973. GasPrice: rpc.NewHexNumber(t.GasPrice()),
  974. Hash: t.Hash(),
  975. }
  976. }
  977. // SignTransaction will sign the given transaction with the from account.
  978. // The node needs to have the private key of the account corresponding with
  979. // the given from address and it needs to be unlocked.
  980. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SignTransactionArgs) (*SignTransactionResult, error) {
  981. if args.Gas == nil {
  982. args.Gas = rpc.NewHexNumber(defaultGas)
  983. }
  984. if args.GasPrice == nil {
  985. price, err := s.b.SuggestPrice(ctx)
  986. if err != nil {
  987. return nil, err
  988. }
  989. args.GasPrice = rpc.NewHexNumber(price)
  990. }
  991. if args.Value == nil {
  992. args.Value = rpc.NewHexNumber(0)
  993. }
  994. if args.Nonce == nil {
  995. nonce, err := s.b.GetPoolNonce(ctx, args.From)
  996. if err != nil {
  997. return nil, err
  998. }
  999. args.Nonce = rpc.NewHexNumber(nonce)
  1000. }
  1001. var tx *types.Transaction
  1002. if args.To == nil {
  1003. tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1004. } else {
  1005. tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data))
  1006. }
  1007. signedTx, err := s.sign(args.From, tx)
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. data, err := rlp.EncodeToBytes(signedTx)
  1012. if err != nil {
  1013. return nil, err
  1014. }
  1015. return &SignTransactionResult{"0x" + common.Bytes2Hex(data), newTx(signedTx)}, nil
  1016. }
  1017. // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1018. // the accounts this node manages.
  1019. func (s *PublicTransactionPoolAPI) PendingTransactions() []*RPCTransaction {
  1020. pending := s.b.GetPoolTransactions()
  1021. transactions := make([]*RPCTransaction, 0, len(pending))
  1022. for _, tx := range pending {
  1023. from, _ := tx.FromFrontier()
  1024. if s.b.AccountManager().HasAddress(from) {
  1025. transactions = append(transactions, newRPCPendingTransaction(tx))
  1026. }
  1027. }
  1028. return transactions
  1029. }
  1030. // Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the
  1031. // pool and reinsert it with the new gas price and limit.
  1032. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, tx *Tx, gasPrice, gasLimit *rpc.HexNumber) (common.Hash, error) {
  1033. pending := s.b.GetPoolTransactions()
  1034. for _, p := range pending {
  1035. if pFrom, err := p.FromFrontier(); err == nil && pFrom == tx.From && p.SigHash() == tx.tx.SigHash() {
  1036. if gasPrice == nil {
  1037. gasPrice = rpc.NewHexNumber(tx.tx.GasPrice())
  1038. }
  1039. if gasLimit == nil {
  1040. gasLimit = rpc.NewHexNumber(tx.tx.Gas())
  1041. }
  1042. var newTx *types.Transaction
  1043. if tx.tx.To() == nil {
  1044. newTx = types.NewContractCreation(tx.tx.Nonce(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1045. } else {
  1046. newTx = types.NewTransaction(tx.tx.Nonce(), *tx.tx.To(), tx.tx.Value(), gasPrice.BigInt(), gasLimit.BigInt(), tx.tx.Data())
  1047. }
  1048. signedTx, err := s.sign(tx.From, newTx)
  1049. if err != nil {
  1050. return common.Hash{}, err
  1051. }
  1052. s.b.RemoveTx(tx.Hash)
  1053. if err = s.b.SendTx(ctx, signedTx); err != nil {
  1054. return common.Hash{}, err
  1055. }
  1056. return signedTx.Hash(), nil
  1057. }
  1058. }
  1059. return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash)
  1060. }
  1061. // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
  1062. // debugging endpoint.
  1063. type PublicDebugAPI struct {
  1064. b Backend
  1065. }
  1066. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1067. // of the Ethereum service.
  1068. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1069. return &PublicDebugAPI{b: b}
  1070. }
  1071. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1072. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1073. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1074. if block == nil {
  1075. return "", fmt.Errorf("block #%d not found", number)
  1076. }
  1077. encoded, err := rlp.EncodeToBytes(block)
  1078. if err != nil {
  1079. return "", err
  1080. }
  1081. return fmt.Sprintf("%x", encoded), nil
  1082. }
  1083. // PrintBlock retrieves a block and returns its pretty printed form.
  1084. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1085. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1086. if block == nil {
  1087. return "", fmt.Errorf("block #%d not found", number)
  1088. }
  1089. return fmt.Sprintf("%s", block), nil
  1090. }
  1091. // SeedHash retrieves the seed hash of a block.
  1092. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1093. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1094. if block == nil {
  1095. return "", fmt.Errorf("block #%d not found", number)
  1096. }
  1097. hash, err := ethash.GetSeedHash(number)
  1098. if err != nil {
  1099. return "", err
  1100. }
  1101. return fmt.Sprintf("0x%x", hash), nil
  1102. }
  1103. // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private
  1104. // debugging endpoint.
  1105. type PrivateDebugAPI struct {
  1106. b Backend
  1107. }
  1108. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1109. // of the Ethereum service.
  1110. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1111. return &PrivateDebugAPI{b: b}
  1112. }
  1113. // ChaindbProperty returns leveldb properties of the chain database.
  1114. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1115. ldb, ok := api.b.ChainDb().(interface {
  1116. LDB() *leveldb.DB
  1117. })
  1118. if !ok {
  1119. return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1120. }
  1121. if property == "" {
  1122. property = "leveldb.stats"
  1123. } else if !strings.HasPrefix(property, "leveldb.") {
  1124. property = "leveldb." + property
  1125. }
  1126. return ldb.LDB().GetProperty(property)
  1127. }
  1128. // SetHead rewinds the head of the blockchain to a previous block.
  1129. func (api *PrivateDebugAPI) SetHead(number rpc.HexNumber) {
  1130. api.b.SetHead(uint64(number.Int64()))
  1131. }
  1132. // PublicNetAPI offers network related RPC methods
  1133. type PublicNetAPI struct {
  1134. net *p2p.Server
  1135. networkVersion int
  1136. }
  1137. // NewPublicNetAPI creates a new net API instance.
  1138. func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI {
  1139. return &PublicNetAPI{net, networkVersion}
  1140. }
  1141. // Listening returns an indication if the node is listening for network connections.
  1142. func (s *PublicNetAPI) Listening() bool {
  1143. return true // always listening
  1144. }
  1145. // PeerCount returns the number of connected peers
  1146. func (s *PublicNetAPI) PeerCount() *rpc.HexNumber {
  1147. return rpc.NewHexNumber(s.net.PeerCount())
  1148. }
  1149. // Version returns the current ethereum protocol version.
  1150. func (s *PublicNetAPI) Version() string {
  1151. return fmt.Sprintf("%d", s.networkVersion)
  1152. }