api.go 50 KB

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