api.go 50 KB

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