api.go 58 KB

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