api.go 46 KB

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