api.go 47 KB

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