api.go 46 KB

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