api.go 44 KB

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