api.go 49 KB

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