api.go 44 KB

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