api.go 55 KB

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