api.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  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/clique"
  32. "github.com/ethereum/go-ethereum/consensus/ethash"
  33. "github.com/ethereum/go-ethereum/core"
  34. "github.com/ethereum/go-ethereum/core/rawdb"
  35. "github.com/ethereum/go-ethereum/core/types"
  36. "github.com/ethereum/go-ethereum/core/vm"
  37. "github.com/ethereum/go-ethereum/crypto"
  38. "github.com/ethereum/go-ethereum/log"
  39. "github.com/ethereum/go-ethereum/p2p"
  40. "github.com/ethereum/go-ethereum/params"
  41. "github.com/ethereum/go-ethereum/rlp"
  42. "github.com/ethereum/go-ethereum/rpc"
  43. "github.com/syndtr/goleveldb/leveldb"
  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. // signTransaction 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. return wallet.SignTxWithPassphrase(account, passwd, tx, s.b.ChainConfig().ChainID)
  325. }
  326. // SendTransaction will create a transaction from the given arguments and
  327. // tries to sign it with the key associated with args.To. If the given passwd isn't
  328. // able to decrypt the key it fails.
  329. func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  330. if args.Nonce == nil {
  331. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  332. // the same nonce to multiple accounts.
  333. s.nonceLock.LockAddr(args.From)
  334. defer s.nonceLock.UnlockAddr(args.From)
  335. }
  336. signed, err := s.signTransaction(ctx, &args, passwd)
  337. if err != nil {
  338. log.Warn("Failed transaction send attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  339. return common.Hash{}, err
  340. }
  341. return SubmitTransaction(ctx, s.b, signed)
  342. }
  343. // SignTransaction will create a transaction from the given arguments and
  344. // tries to sign it with the key associated with args.To. If the given passwd isn't
  345. // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
  346. // to other nodes
  347. func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
  348. // No need to obtain the noncelock mutex, since we won't be sending this
  349. // tx into the transaction pool, but right back to the user
  350. if args.Gas == nil {
  351. return nil, fmt.Errorf("gas not specified")
  352. }
  353. if args.GasPrice == nil {
  354. return nil, fmt.Errorf("gasPrice not specified")
  355. }
  356. if args.Nonce == nil {
  357. return nil, fmt.Errorf("nonce not specified")
  358. }
  359. signed, err := s.signTransaction(ctx, &args, passwd)
  360. if err != nil {
  361. log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  362. return nil, err
  363. }
  364. data, err := rlp.EncodeToBytes(signed)
  365. if err != nil {
  366. return nil, err
  367. }
  368. return &SignTransactionResult{data, signed}, nil
  369. }
  370. // Sign calculates an Ethereum ECDSA signature for:
  371. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  372. //
  373. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  374. // where the V value will be 27 or 28 for legacy reasons.
  375. //
  376. // The key used to calculate the signature is decrypted with the given password.
  377. //
  378. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  379. func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
  380. // Look up the wallet containing the requested signer
  381. account := accounts.Account{Address: addr}
  382. wallet, err := s.b.AccountManager().Find(account)
  383. if err != nil {
  384. return nil, err
  385. }
  386. // Assemble sign the data with the wallet
  387. signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
  388. if err != nil {
  389. log.Warn("Failed data sign attempt", "address", addr, "err", err)
  390. return nil, err
  391. }
  392. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  393. return signature, nil
  394. }
  395. // EcRecover returns the address for the account that was used to create the signature.
  396. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  397. // the address of:
  398. // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
  399. // addr = ecrecover(hash, signature)
  400. //
  401. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  402. // the V value must be 27 or 28 for legacy reasons.
  403. //
  404. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  405. func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
  406. if len(sig) != 65 {
  407. return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
  408. }
  409. if sig[64] != 27 && sig[64] != 28 {
  410. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  411. }
  412. sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
  413. rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
  414. if err != nil {
  415. return common.Address{}, err
  416. }
  417. return crypto.PubkeyToAddress(*rpk), nil
  418. }
  419. // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
  420. // and will be removed in the future. It primary goal is to give clients time to update.
  421. func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  422. return s.SendTransaction(ctx, args, passwd)
  423. }
  424. // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
  425. // It offers only methods that operate on public data that is freely available to anyone.
  426. type PublicBlockChainAPI struct {
  427. b Backend
  428. }
  429. // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
  430. func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
  431. return &PublicBlockChainAPI{b}
  432. }
  433. // BlockNumber returns the block number of the chain head.
  434. func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
  435. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
  436. return hexutil.Uint64(header.Number.Uint64())
  437. }
  438. // GetBalance returns the amount of wei for the given address in the state of the
  439. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  440. // block numbers are also allowed.
  441. func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Big, error) {
  442. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  443. if state == nil || err != nil {
  444. return nil, err
  445. }
  446. return (*hexutil.Big)(state.GetBalance(address)), state.Error()
  447. }
  448. // Result structs for GetProof
  449. type AccountResult struct {
  450. Address common.Address `json:"address"`
  451. AccountProof []string `json:"accountProof"`
  452. Balance *hexutil.Big `json:"balance"`
  453. CodeHash common.Hash `json:"codeHash"`
  454. Nonce hexutil.Uint64 `json:"nonce"`
  455. StorageHash common.Hash `json:"storageHash"`
  456. StorageProof []StorageResult `json:"storageProof"`
  457. }
  458. type StorageResult struct {
  459. Key string `json:"key"`
  460. Value *hexutil.Big `json:"value"`
  461. Proof []string `json:"proof"`
  462. }
  463. // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
  464. func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNr rpc.BlockNumber) (*AccountResult, error) {
  465. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  466. if state == nil || err != nil {
  467. return nil, err
  468. }
  469. storageTrie := state.StorageTrie(address)
  470. storageHash := types.EmptyRootHash
  471. codeHash := state.GetCodeHash(address)
  472. storageProof := make([]StorageResult, len(storageKeys))
  473. // if we have a storageTrie, (which means the account exists), we can update the storagehash
  474. if storageTrie != nil {
  475. storageHash = storageTrie.Hash()
  476. } else {
  477. // no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
  478. codeHash = crypto.Keccak256Hash(nil)
  479. }
  480. // create the proof for the storageKeys
  481. for i, key := range storageKeys {
  482. if storageTrie != nil {
  483. proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
  484. if storageError != nil {
  485. return nil, storageError
  486. }
  487. storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), common.ToHexArray(proof)}
  488. } else {
  489. storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
  490. }
  491. }
  492. // create the accountProof
  493. accountProof, proofErr := state.GetProof(address)
  494. if proofErr != nil {
  495. return nil, proofErr
  496. }
  497. return &AccountResult{
  498. Address: address,
  499. AccountProof: common.ToHexArray(accountProof),
  500. Balance: (*hexutil.Big)(state.GetBalance(address)),
  501. CodeHash: codeHash,
  502. Nonce: hexutil.Uint64(state.GetNonce(address)),
  503. StorageHash: storageHash,
  504. StorageProof: storageProof,
  505. }, state.Error()
  506. }
  507. // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
  508. // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  509. func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  510. block, err := s.b.BlockByNumber(ctx, blockNr)
  511. if block != nil {
  512. response, err := s.rpcOutputBlock(block, true, fullTx)
  513. if err == nil && blockNr == rpc.PendingBlockNumber {
  514. // Pending blocks need to nil out a few fields
  515. for _, field := range []string{"hash", "nonce", "miner"} {
  516. response[field] = nil
  517. }
  518. }
  519. return response, err
  520. }
  521. return nil, err
  522. }
  523. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  524. // detail, otherwise only the transaction hash is returned.
  525. func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
  526. block, err := s.b.GetBlock(ctx, blockHash)
  527. if block != nil {
  528. return s.rpcOutputBlock(block, true, fullTx)
  529. }
  530. return nil, err
  531. }
  532. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  533. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  534. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
  535. block, err := s.b.BlockByNumber(ctx, blockNr)
  536. if block != nil {
  537. uncles := block.Uncles()
  538. if index >= hexutil.Uint(len(uncles)) {
  539. log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
  540. return nil, nil
  541. }
  542. block = types.NewBlockWithHeader(uncles[index])
  543. return s.rpcOutputBlock(block, false, false)
  544. }
  545. return nil, err
  546. }
  547. // GetUncleByBlockHashAndIndex 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) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
  550. block, err := s.b.GetBlock(ctx, blockHash)
  551. if block != nil {
  552. uncles := block.Uncles()
  553. if index >= hexutil.Uint(len(uncles)) {
  554. log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "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. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  563. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  564. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  565. n := hexutil.Uint(len(block.Uncles()))
  566. return &n
  567. }
  568. return nil
  569. }
  570. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  571. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  572. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  573. n := hexutil.Uint(len(block.Uncles()))
  574. return &n
  575. }
  576. return nil
  577. }
  578. // GetCode returns the code stored at the given address in the state for the given block number.
  579. func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
  580. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  581. if state == nil || err != nil {
  582. return nil, err
  583. }
  584. code := state.GetCode(address)
  585. return code, state.Error()
  586. }
  587. // GetStorageAt returns the storage from the state at the given address, key and
  588. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  589. // numbers are also allowed.
  590. func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
  591. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  592. if state == nil || err != nil {
  593. return nil, err
  594. }
  595. res := state.GetState(address, common.HexToHash(key))
  596. return res[:], state.Error()
  597. }
  598. // CallArgs represents the arguments for a call.
  599. type CallArgs struct {
  600. From *common.Address `json:"from"`
  601. To *common.Address `json:"to"`
  602. Gas *hexutil.Uint64 `json:"gas"`
  603. GasPrice *hexutil.Big `json:"gasPrice"`
  604. Value *hexutil.Big `json:"value"`
  605. Data *hexutil.Bytes `json:"data"`
  606. }
  607. func DoCall(ctx context.Context, b Backend, args CallArgs, blockNr rpc.BlockNumber, vmCfg vm.Config, timeout time.Duration) ([]byte, uint64, bool, error) {
  608. defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  609. state, header, err := b.StateAndHeaderByNumber(ctx, blockNr)
  610. if state == nil || err != nil {
  611. return nil, 0, false, err
  612. }
  613. // Set sender address or use a default if none specified
  614. var addr common.Address
  615. if args.From == nil {
  616. if wallets := b.AccountManager().Wallets(); len(wallets) > 0 {
  617. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  618. addr = accounts[0].Address
  619. }
  620. }
  621. } else {
  622. addr = *args.From
  623. }
  624. // Set default gas & gas price if none were set
  625. gas := uint64(math.MaxUint64 / 2)
  626. if args.Gas != nil {
  627. gas = uint64(*args.Gas)
  628. }
  629. gasPrice := new(big.Int).SetUint64(defaultGasPrice)
  630. if args.GasPrice != nil {
  631. gasPrice = args.GasPrice.ToInt()
  632. }
  633. value := new(big.Int)
  634. if args.Value != nil {
  635. value = args.Value.ToInt()
  636. }
  637. var data []byte
  638. if args.Data != nil {
  639. data = []byte(*args.Data)
  640. }
  641. // Create new call message
  642. msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, data, false)
  643. // Setup context so it may be cancelled the call has completed
  644. // or, in case of unmetered gas, setup a context with a timeout.
  645. var cancel context.CancelFunc
  646. if timeout > 0 {
  647. ctx, cancel = context.WithTimeout(ctx, timeout)
  648. } else {
  649. ctx, cancel = context.WithCancel(ctx)
  650. }
  651. // Make sure the context is cancelled when the call has completed
  652. // this makes sure resources are cleaned up.
  653. defer cancel()
  654. // Get a new instance of the EVM.
  655. evm, vmError, err := b.GetEVM(ctx, msg, state, header)
  656. if err != nil {
  657. return nil, 0, false, err
  658. }
  659. // Wait for the context to be done and cancel the evm. Even if the
  660. // EVM has finished, cancelling may be done (repeatedly)
  661. go func() {
  662. <-ctx.Done()
  663. evm.Cancel()
  664. }()
  665. // Setup the gas pool (also for unmetered requests)
  666. // and apply the message.
  667. gp := new(core.GasPool).AddGas(math.MaxUint64)
  668. res, gas, failed, err := core.ApplyMessage(evm, msg, gp)
  669. if err := vmError(); err != nil {
  670. return nil, 0, false, err
  671. }
  672. return res, gas, failed, err
  673. }
  674. // Call executes the given transaction on the state for the given block number.
  675. // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
  676. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
  677. result, _, _, err := DoCall(ctx, s.b, args, blockNr, vm.Config{}, 5*time.Second)
  678. return (hexutil.Bytes)(result), err
  679. }
  680. func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Uint64, error) {
  681. // Binary search the gas requirement, as it may be higher than the amount used
  682. var (
  683. lo uint64 = params.TxGas - 1
  684. hi uint64
  685. cap uint64
  686. )
  687. if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  688. hi = uint64(*args.Gas)
  689. } else {
  690. // Retrieve the block to act as the gas ceiling
  691. block, err := b.BlockByNumber(ctx, blockNr)
  692. if err != nil {
  693. return 0, err
  694. }
  695. hi = block.GasLimit()
  696. }
  697. cap = hi
  698. // Create a helper to check if a gas allowance results in an executable transaction
  699. executable := func(gas uint64) bool {
  700. args.Gas = (*hexutil.Uint64)(&gas)
  701. _, _, failed, err := DoCall(ctx, b, args, rpc.PendingBlockNumber, vm.Config{}, 0)
  702. if err != nil || failed {
  703. return false
  704. }
  705. return true
  706. }
  707. // Execute the binary search and hone in on an executable gas limit
  708. for lo+1 < hi {
  709. mid := (hi + lo) / 2
  710. if !executable(mid) {
  711. lo = mid
  712. } else {
  713. hi = mid
  714. }
  715. }
  716. // Reject the transaction as invalid if it still fails at the highest allowance
  717. if hi == cap {
  718. if !executable(hi) {
  719. return 0, fmt.Errorf("gas required exceeds allowance or always failing transaction")
  720. }
  721. }
  722. return hexutil.Uint64(hi), nil
  723. }
  724. // EstimateGas returns an estimate of the amount of gas needed to execute the
  725. // given transaction against the current pending block.
  726. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) {
  727. return DoEstimateGas(ctx, s.b, args, rpc.PendingBlockNumber)
  728. }
  729. // ExecutionResult groups all structured logs emitted by the EVM
  730. // while replaying a transaction in debug mode as well as transaction
  731. // execution status, the amount of gas used and the return value
  732. type ExecutionResult struct {
  733. Gas uint64 `json:"gas"`
  734. Failed bool `json:"failed"`
  735. ReturnValue string `json:"returnValue"`
  736. StructLogs []StructLogRes `json:"structLogs"`
  737. }
  738. // StructLogRes stores a structured log emitted by the EVM while replaying a
  739. // transaction in debug mode
  740. type StructLogRes struct {
  741. Pc uint64 `json:"pc"`
  742. Op string `json:"op"`
  743. Gas uint64 `json:"gas"`
  744. GasCost uint64 `json:"gasCost"`
  745. Depth int `json:"depth"`
  746. Error error `json:"error,omitempty"`
  747. Stack *[]string `json:"stack,omitempty"`
  748. Memory *[]string `json:"memory,omitempty"`
  749. Storage *map[string]string `json:"storage,omitempty"`
  750. }
  751. // FormatLogs formats EVM returned structured logs for json output
  752. func FormatLogs(logs []vm.StructLog) []StructLogRes {
  753. formatted := make([]StructLogRes, len(logs))
  754. for index, trace := range logs {
  755. formatted[index] = StructLogRes{
  756. Pc: trace.Pc,
  757. Op: trace.Op.String(),
  758. Gas: trace.Gas,
  759. GasCost: trace.GasCost,
  760. Depth: trace.Depth,
  761. Error: trace.Err,
  762. }
  763. if trace.Stack != nil {
  764. stack := make([]string, len(trace.Stack))
  765. for i, stackValue := range trace.Stack {
  766. stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
  767. }
  768. formatted[index].Stack = &stack
  769. }
  770. if trace.Memory != nil {
  771. memory := make([]string, 0, (len(trace.Memory)+31)/32)
  772. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  773. memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  774. }
  775. formatted[index].Memory = &memory
  776. }
  777. if trace.Storage != nil {
  778. storage := make(map[string]string)
  779. for i, storageValue := range trace.Storage {
  780. storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  781. }
  782. formatted[index].Storage = &storage
  783. }
  784. }
  785. return formatted
  786. }
  787. // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  788. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  789. // transaction hashes.
  790. func RPCMarshalBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  791. head := b.Header() // copies the header once
  792. fields := map[string]interface{}{
  793. "number": (*hexutil.Big)(head.Number),
  794. "hash": b.Hash(),
  795. "parentHash": head.ParentHash,
  796. "nonce": head.Nonce,
  797. "mixHash": head.MixDigest,
  798. "sha3Uncles": head.UncleHash,
  799. "logsBloom": head.Bloom,
  800. "stateRoot": head.Root,
  801. "miner": head.Coinbase,
  802. "difficulty": (*hexutil.Big)(head.Difficulty),
  803. "extraData": hexutil.Bytes(head.Extra),
  804. "size": hexutil.Uint64(b.Size()),
  805. "gasLimit": hexutil.Uint64(head.GasLimit),
  806. "gasUsed": hexutil.Uint64(head.GasUsed),
  807. "timestamp": (*hexutil.Big)(head.Time),
  808. "transactionsRoot": head.TxHash,
  809. "receiptsRoot": head.ReceiptHash,
  810. }
  811. if inclTx {
  812. formatTx := func(tx *types.Transaction) (interface{}, error) {
  813. return tx.Hash(), nil
  814. }
  815. if fullTx {
  816. formatTx = func(tx *types.Transaction) (interface{}, error) {
  817. return newRPCTransactionFromBlockHash(b, tx.Hash()), nil
  818. }
  819. }
  820. txs := b.Transactions()
  821. transactions := make([]interface{}, len(txs))
  822. var err error
  823. for i, tx := range txs {
  824. if transactions[i], err = formatTx(tx); err != nil {
  825. return nil, err
  826. }
  827. }
  828. fields["transactions"] = transactions
  829. }
  830. uncles := b.Uncles()
  831. uncleHashes := make([]common.Hash, len(uncles))
  832. for i, uncle := range uncles {
  833. uncleHashes[i] = uncle.Hash()
  834. }
  835. fields["uncles"] = uncleHashes
  836. return fields, nil
  837. }
  838. // rpcOutputBlock uses the generalized output filler, then adds the total difficulty field, which requires
  839. // a `PublicBlockchainAPI`.
  840. func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  841. fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  842. if err != nil {
  843. return nil, err
  844. }
  845. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(b.Hash()))
  846. return fields, err
  847. }
  848. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  849. type RPCTransaction struct {
  850. BlockHash common.Hash `json:"blockHash"`
  851. BlockNumber *hexutil.Big `json:"blockNumber"`
  852. From common.Address `json:"from"`
  853. Gas hexutil.Uint64 `json:"gas"`
  854. GasPrice *hexutil.Big `json:"gasPrice"`
  855. Hash common.Hash `json:"hash"`
  856. Input hexutil.Bytes `json:"input"`
  857. Nonce hexutil.Uint64 `json:"nonce"`
  858. To *common.Address `json:"to"`
  859. TransactionIndex hexutil.Uint `json:"transactionIndex"`
  860. Value *hexutil.Big `json:"value"`
  861. V *hexutil.Big `json:"v"`
  862. R *hexutil.Big `json:"r"`
  863. S *hexutil.Big `json:"s"`
  864. }
  865. // newRPCTransaction returns a transaction that will serialize to the RPC
  866. // representation, with the given location metadata set (if available).
  867. func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  868. var signer types.Signer = types.FrontierSigner{}
  869. if tx.Protected() {
  870. signer = types.NewEIP155Signer(tx.ChainId())
  871. }
  872. from, _ := types.Sender(signer, tx)
  873. v, r, s := tx.RawSignatureValues()
  874. result := &RPCTransaction{
  875. From: from,
  876. Gas: hexutil.Uint64(tx.Gas()),
  877. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  878. Hash: tx.Hash(),
  879. Input: hexutil.Bytes(tx.Data()),
  880. Nonce: hexutil.Uint64(tx.Nonce()),
  881. To: tx.To(),
  882. Value: (*hexutil.Big)(tx.Value()),
  883. V: (*hexutil.Big)(v),
  884. R: (*hexutil.Big)(r),
  885. S: (*hexutil.Big)(s),
  886. }
  887. if blockHash != (common.Hash{}) {
  888. result.BlockHash = blockHash
  889. result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  890. result.TransactionIndex = hexutil.Uint(index)
  891. }
  892. return result
  893. }
  894. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  895. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  896. return newRPCTransaction(tx, common.Hash{}, 0, 0)
  897. }
  898. // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  899. func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  900. txs := b.Transactions()
  901. if index >= uint64(len(txs)) {
  902. return nil
  903. }
  904. return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  905. }
  906. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  907. func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  908. txs := b.Transactions()
  909. if index >= uint64(len(txs)) {
  910. return nil
  911. }
  912. blob, _ := rlp.EncodeToBytes(txs[index])
  913. return blob
  914. }
  915. // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  916. func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  917. for idx, tx := range b.Transactions() {
  918. if tx.Hash() == hash {
  919. return newRPCTransactionFromBlockIndex(b, uint64(idx))
  920. }
  921. }
  922. return nil
  923. }
  924. // PublicTransactionPoolAPI exposes methods for the RPC interface
  925. type PublicTransactionPoolAPI struct {
  926. b Backend
  927. nonceLock *AddrLocker
  928. }
  929. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  930. func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  931. return &PublicTransactionPoolAPI{b, nonceLock}
  932. }
  933. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  934. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  935. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  936. n := hexutil.Uint(len(block.Transactions()))
  937. return &n
  938. }
  939. return nil
  940. }
  941. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  942. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  943. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  944. n := hexutil.Uint(len(block.Transactions()))
  945. return &n
  946. }
  947. return nil
  948. }
  949. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  950. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  951. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  952. return newRPCTransactionFromBlockIndex(block, uint64(index))
  953. }
  954. return nil
  955. }
  956. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  957. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  958. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  959. return newRPCTransactionFromBlockIndex(block, uint64(index))
  960. }
  961. return nil
  962. }
  963. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  964. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  965. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  966. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  967. }
  968. return nil
  969. }
  970. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  971. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  972. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  973. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  974. }
  975. return nil
  976. }
  977. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  978. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {
  979. // Ask transaction pool for the nonce which includes pending transactions
  980. if blockNr == rpc.PendingBlockNumber {
  981. nonce, err := s.b.GetPoolNonce(ctx, address)
  982. if err != nil {
  983. return nil, err
  984. }
  985. return (*hexutil.Uint64)(&nonce), nil
  986. }
  987. // Resolve block number and use its state to ask for the nonce
  988. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  989. if state == nil || err != nil {
  990. return nil, err
  991. }
  992. nonce := state.GetNonce(address)
  993. return (*hexutil.Uint64)(&nonce), state.Error()
  994. }
  995. // GetTransactionByHash returns the transaction for the given hash
  996. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) *RPCTransaction {
  997. // Try to return an already finalized transaction
  998. if tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash); tx != nil {
  999. return newRPCTransaction(tx, blockHash, blockNumber, index)
  1000. }
  1001. // No finalized transaction, try to retrieve it from the pool
  1002. if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1003. return newRPCPendingTransaction(tx)
  1004. }
  1005. // Transaction unknown, return as such
  1006. return nil
  1007. }
  1008. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1009. func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1010. var tx *types.Transaction
  1011. // Retrieve a finalized transaction, or a pooled otherwise
  1012. if tx, _, _, _ = rawdb.ReadTransaction(s.b.ChainDb(), hash); tx == nil {
  1013. if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1014. // Transaction not found anywhere, abort
  1015. return nil, nil
  1016. }
  1017. }
  1018. // Serialize to RLP and return
  1019. return rlp.EncodeToBytes(tx)
  1020. }
  1021. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1022. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1023. tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
  1024. if tx == nil {
  1025. return nil, nil
  1026. }
  1027. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1028. if err != nil {
  1029. return nil, err
  1030. }
  1031. if len(receipts) <= int(index) {
  1032. return nil, nil
  1033. }
  1034. receipt := receipts[index]
  1035. var signer types.Signer = types.FrontierSigner{}
  1036. if tx.Protected() {
  1037. signer = types.NewEIP155Signer(tx.ChainId())
  1038. }
  1039. from, _ := types.Sender(signer, tx)
  1040. fields := map[string]interface{}{
  1041. "blockHash": blockHash,
  1042. "blockNumber": hexutil.Uint64(blockNumber),
  1043. "transactionHash": hash,
  1044. "transactionIndex": hexutil.Uint64(index),
  1045. "from": from,
  1046. "to": tx.To(),
  1047. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1048. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1049. "contractAddress": nil,
  1050. "logs": receipt.Logs,
  1051. "logsBloom": receipt.Bloom,
  1052. }
  1053. // Assign receipt status or post state.
  1054. if len(receipt.PostState) > 0 {
  1055. fields["root"] = hexutil.Bytes(receipt.PostState)
  1056. } else {
  1057. fields["status"] = hexutil.Uint(receipt.Status)
  1058. }
  1059. if receipt.Logs == nil {
  1060. fields["logs"] = [][]*types.Log{}
  1061. }
  1062. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1063. if receipt.ContractAddress != (common.Address{}) {
  1064. fields["contractAddress"] = receipt.ContractAddress
  1065. }
  1066. return fields, nil
  1067. }
  1068. // sign is a helper function that signs a transaction with the private key of the given address.
  1069. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1070. // Look up the wallet containing the requested signer
  1071. account := accounts.Account{Address: addr}
  1072. wallet, err := s.b.AccountManager().Find(account)
  1073. if err != nil {
  1074. return nil, err
  1075. }
  1076. // Request the wallet to sign the transaction
  1077. return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1078. }
  1079. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1080. type SendTxArgs struct {
  1081. From common.Address `json:"from"`
  1082. To *common.Address `json:"to"`
  1083. Gas *hexutil.Uint64 `json:"gas"`
  1084. GasPrice *hexutil.Big `json:"gasPrice"`
  1085. Value *hexutil.Big `json:"value"`
  1086. Nonce *hexutil.Uint64 `json:"nonce"`
  1087. // We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1088. // newer name and should be preferred by clients.
  1089. Data *hexutil.Bytes `json:"data"`
  1090. Input *hexutil.Bytes `json:"input"`
  1091. }
  1092. // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1093. func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1094. if args.Gas == nil {
  1095. args.Gas = new(hexutil.Uint64)
  1096. *(*uint64)(args.Gas) = 90000
  1097. }
  1098. if args.GasPrice == nil {
  1099. price, err := b.SuggestPrice(ctx)
  1100. if err != nil {
  1101. return err
  1102. }
  1103. args.GasPrice = (*hexutil.Big)(price)
  1104. }
  1105. if args.Value == nil {
  1106. args.Value = new(hexutil.Big)
  1107. }
  1108. if args.Nonce == nil {
  1109. nonce, err := b.GetPoolNonce(ctx, args.From)
  1110. if err != nil {
  1111. return err
  1112. }
  1113. args.Nonce = (*hexutil.Uint64)(&nonce)
  1114. }
  1115. if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1116. return errors.New(`Both "data" and "input" are set and not equal. Please use "input" to pass transaction call data.`)
  1117. }
  1118. if args.To == nil {
  1119. // Contract creation
  1120. var input []byte
  1121. if args.Data != nil {
  1122. input = *args.Data
  1123. } else if args.Input != nil {
  1124. input = *args.Input
  1125. }
  1126. if len(input) == 0 {
  1127. return errors.New(`contract creation without any data provided`)
  1128. }
  1129. }
  1130. return nil
  1131. }
  1132. func (args *SendTxArgs) toTransaction() *types.Transaction {
  1133. var input []byte
  1134. if args.Data != nil {
  1135. input = *args.Data
  1136. } else if args.Input != nil {
  1137. input = *args.Input
  1138. }
  1139. if args.To == nil {
  1140. return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1141. }
  1142. return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1143. }
  1144. // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1145. func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1146. if err := b.SendTx(ctx, tx); err != nil {
  1147. return common.Hash{}, err
  1148. }
  1149. if tx.To() == nil {
  1150. signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1151. from, err := types.Sender(signer, tx)
  1152. if err != nil {
  1153. return common.Hash{}, err
  1154. }
  1155. addr := crypto.CreateAddress(from, tx.Nonce())
  1156. log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1157. } else {
  1158. log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1159. }
  1160. return tx.Hash(), nil
  1161. }
  1162. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1163. // transaction pool.
  1164. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1165. // Look up the wallet containing the requested signer
  1166. account := accounts.Account{Address: args.From}
  1167. wallet, err := s.b.AccountManager().Find(account)
  1168. if err != nil {
  1169. return common.Hash{}, err
  1170. }
  1171. if args.Nonce == nil {
  1172. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  1173. // the same nonce to multiple accounts.
  1174. s.nonceLock.LockAddr(args.From)
  1175. defer s.nonceLock.UnlockAddr(args.From)
  1176. }
  1177. // Set some sanity defaults and terminate on failure
  1178. if err := args.setDefaults(ctx, s.b); err != nil {
  1179. return common.Hash{}, err
  1180. }
  1181. // Assemble the transaction and sign with the wallet
  1182. tx := args.toTransaction()
  1183. signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().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.SignText(account, 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. // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  1341. // given address, returning the address of the recovered signature
  1342. //
  1343. // This is a temporary method to debug the externalsigner integration,
  1344. // TODO: Remove this method when the integration is mature
  1345. func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  1346. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1347. if block == nil {
  1348. return common.Address{}, fmt.Errorf("block #%d not found", number)
  1349. }
  1350. header := block.Header()
  1351. header.Extra = make([]byte, 32+65)
  1352. encoded := clique.CliqueRLP(header)
  1353. // Look up the wallet containing the requested signer
  1354. account := accounts.Account{Address: address}
  1355. wallet, err := api.b.AccountManager().Find(account)
  1356. if err != nil {
  1357. return common.Address{}, err
  1358. }
  1359. signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  1360. if err != nil {
  1361. return common.Address{}, err
  1362. }
  1363. sealHash := clique.SealHash(header).Bytes()
  1364. log.Info("test signing of clique block",
  1365. "Sealhash", fmt.Sprintf("%x", sealHash),
  1366. "signature", fmt.Sprintf("%x", signature))
  1367. pubkey, err := crypto.Ecrecover(sealHash, signature)
  1368. if err != nil {
  1369. return common.Address{}, err
  1370. }
  1371. var signer common.Address
  1372. copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  1373. return signer, nil
  1374. }
  1375. // PrintBlock retrieves a block and returns its pretty printed form.
  1376. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1377. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1378. if block == nil {
  1379. return "", fmt.Errorf("block #%d not found", number)
  1380. }
  1381. return spew.Sdump(block), nil
  1382. }
  1383. // SeedHash retrieves the seed hash of a block.
  1384. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1385. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1386. if block == nil {
  1387. return "", fmt.Errorf("block #%d not found", number)
  1388. }
  1389. return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  1390. }
  1391. // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  1392. // debugging endpoint.
  1393. type PrivateDebugAPI struct {
  1394. b Backend
  1395. }
  1396. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1397. // of the Ethereum service.
  1398. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1399. return &PrivateDebugAPI{b: b}
  1400. }
  1401. // ChaindbProperty returns leveldb properties of the chain database.
  1402. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1403. ldb, ok := api.b.ChainDb().(interface {
  1404. LDB() *leveldb.DB
  1405. })
  1406. if !ok {
  1407. return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1408. }
  1409. if property == "" {
  1410. property = "leveldb.stats"
  1411. } else if !strings.HasPrefix(property, "leveldb.") {
  1412. property = "leveldb." + property
  1413. }
  1414. return ldb.LDB().GetProperty(property)
  1415. }
  1416. func (api *PrivateDebugAPI) ChaindbCompact() error {
  1417. for b := byte(0); b < 255; b++ {
  1418. log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1419. if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  1420. log.Error("Database compaction failed", "err", err)
  1421. return err
  1422. }
  1423. }
  1424. return nil
  1425. }
  1426. // SetHead rewinds the head of the blockchain to a previous block.
  1427. func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1428. api.b.SetHead(uint64(number))
  1429. }
  1430. // PublicNetAPI offers network related RPC methods
  1431. type PublicNetAPI struct {
  1432. net *p2p.Server
  1433. networkVersion uint64
  1434. }
  1435. // NewPublicNetAPI creates a new net API instance.
  1436. func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  1437. return &PublicNetAPI{net, networkVersion}
  1438. }
  1439. // Listening returns an indication if the node is listening for network connections.
  1440. func (s *PublicNetAPI) Listening() bool {
  1441. return true // always listening
  1442. }
  1443. // PeerCount returns the number of connected peers
  1444. func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1445. return hexutil.Uint(s.net.PeerCount())
  1446. }
  1447. // Version returns the current ethereum protocol version.
  1448. func (s *PublicNetAPI) Version() string {
  1449. return fmt.Sprintf("%d", s.networkVersion)
  1450. }