api.go 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  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. func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
  433. wallet, err := s.am.Wallet(url)
  434. if err != nil {
  435. return "", err
  436. }
  437. entropy, err := bip39.NewEntropy(256)
  438. if err != nil {
  439. return "", err
  440. }
  441. mnemonic, err := bip39.NewMnemonic(entropy)
  442. if err != nil {
  443. return "", err
  444. }
  445. seed := bip39.NewSeed(mnemonic, "")
  446. switch wallet := wallet.(type) {
  447. case *scwallet.Wallet:
  448. return mnemonic, wallet.Initialize(seed)
  449. default:
  450. return "", fmt.Errorf("Specified wallet does not support initialization")
  451. }
  452. }
  453. func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
  454. wallet, err := s.am.Wallet(url)
  455. if err != nil {
  456. return err
  457. }
  458. switch wallet := wallet.(type) {
  459. case *scwallet.Wallet:
  460. return wallet.Unpair([]byte(pin))
  461. default:
  462. return fmt.Errorf("Specified wallet does not support pairing")
  463. }
  464. }
  465. // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
  466. // It offers only methods that operate on public data that is freely available to anyone.
  467. type PublicBlockChainAPI struct {
  468. b Backend
  469. }
  470. // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
  471. func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
  472. return &PublicBlockChainAPI{b}
  473. }
  474. // BlockNumber returns the block number of the chain head.
  475. func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
  476. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
  477. return hexutil.Uint64(header.Number.Uint64())
  478. }
  479. // GetBalance returns the amount of wei for the given address in the state of the
  480. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  481. // block numbers are also allowed.
  482. func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Big, error) {
  483. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  484. if state == nil || err != nil {
  485. return nil, err
  486. }
  487. return (*hexutil.Big)(state.GetBalance(address)), state.Error()
  488. }
  489. // Result structs for GetProof
  490. type AccountResult struct {
  491. Address common.Address `json:"address"`
  492. AccountProof []string `json:"accountProof"`
  493. Balance *hexutil.Big `json:"balance"`
  494. CodeHash common.Hash `json:"codeHash"`
  495. Nonce hexutil.Uint64 `json:"nonce"`
  496. StorageHash common.Hash `json:"storageHash"`
  497. StorageProof []StorageResult `json:"storageProof"`
  498. }
  499. type StorageResult struct {
  500. Key string `json:"key"`
  501. Value *hexutil.Big `json:"value"`
  502. Proof []string `json:"proof"`
  503. }
  504. // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
  505. func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNr rpc.BlockNumber) (*AccountResult, error) {
  506. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  507. if state == nil || err != nil {
  508. return nil, err
  509. }
  510. storageTrie := state.StorageTrie(address)
  511. storageHash := types.EmptyRootHash
  512. codeHash := state.GetCodeHash(address)
  513. storageProof := make([]StorageResult, len(storageKeys))
  514. // if we have a storageTrie, (which means the account exists), we can update the storagehash
  515. if storageTrie != nil {
  516. storageHash = storageTrie.Hash()
  517. } else {
  518. // no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
  519. codeHash = crypto.Keccak256Hash(nil)
  520. }
  521. // create the proof for the storageKeys
  522. for i, key := range storageKeys {
  523. if storageTrie != nil {
  524. proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
  525. if storageError != nil {
  526. return nil, storageError
  527. }
  528. storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), common.ToHexArray(proof)}
  529. } else {
  530. storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
  531. }
  532. }
  533. // create the accountProof
  534. accountProof, proofErr := state.GetProof(address)
  535. if proofErr != nil {
  536. return nil, proofErr
  537. }
  538. return &AccountResult{
  539. Address: address,
  540. AccountProof: common.ToHexArray(accountProof),
  541. Balance: (*hexutil.Big)(state.GetBalance(address)),
  542. CodeHash: codeHash,
  543. Nonce: hexutil.Uint64(state.GetNonce(address)),
  544. StorageHash: storageHash,
  545. StorageProof: storageProof,
  546. }, state.Error()
  547. }
  548. // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
  549. // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  550. func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  551. block, err := s.b.BlockByNumber(ctx, blockNr)
  552. if block != nil {
  553. response, err := s.rpcOutputBlock(block, true, fullTx)
  554. if err == nil && blockNr == rpc.PendingBlockNumber {
  555. // Pending blocks need to nil out a few fields
  556. for _, field := range []string{"hash", "nonce", "miner"} {
  557. response[field] = nil
  558. }
  559. }
  560. return response, err
  561. }
  562. return nil, err
  563. }
  564. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  565. // detail, otherwise only the transaction hash is returned.
  566. func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
  567. block, err := s.b.GetBlock(ctx, blockHash)
  568. if block != nil {
  569. return s.rpcOutputBlock(block, true, fullTx)
  570. }
  571. return nil, err
  572. }
  573. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  574. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  575. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
  576. block, err := s.b.BlockByNumber(ctx, blockNr)
  577. if block != nil {
  578. uncles := block.Uncles()
  579. if index >= hexutil.Uint(len(uncles)) {
  580. log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
  581. return nil, nil
  582. }
  583. block = types.NewBlockWithHeader(uncles[index])
  584. return s.rpcOutputBlock(block, false, false)
  585. }
  586. return nil, err
  587. }
  588. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  589. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  590. func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
  591. block, err := s.b.GetBlock(ctx, blockHash)
  592. if block != nil {
  593. uncles := block.Uncles()
  594. if index >= hexutil.Uint(len(uncles)) {
  595. log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
  596. return nil, nil
  597. }
  598. block = types.NewBlockWithHeader(uncles[index])
  599. return s.rpcOutputBlock(block, false, false)
  600. }
  601. return nil, err
  602. }
  603. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  604. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  605. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  606. n := hexutil.Uint(len(block.Uncles()))
  607. return &n
  608. }
  609. return nil
  610. }
  611. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  612. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  613. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  614. n := hexutil.Uint(len(block.Uncles()))
  615. return &n
  616. }
  617. return nil
  618. }
  619. // GetCode returns the code stored at the given address in the state for the given block number.
  620. func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
  621. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  622. if state == nil || err != nil {
  623. return nil, err
  624. }
  625. code := state.GetCode(address)
  626. return code, state.Error()
  627. }
  628. // GetStorageAt returns the storage from the state at the given address, key and
  629. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  630. // numbers are also allowed.
  631. func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
  632. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  633. if state == nil || err != nil {
  634. return nil, err
  635. }
  636. res := state.GetState(address, common.HexToHash(key))
  637. return res[:], state.Error()
  638. }
  639. // CallArgs represents the arguments for a call.
  640. type CallArgs struct {
  641. From *common.Address `json:"from"`
  642. To *common.Address `json:"to"`
  643. Gas *hexutil.Uint64 `json:"gas"`
  644. GasPrice *hexutil.Big `json:"gasPrice"`
  645. Value *hexutil.Big `json:"value"`
  646. Data *hexutil.Bytes `json:"data"`
  647. }
  648. func DoCall(ctx context.Context, b Backend, args CallArgs, blockNr rpc.BlockNumber, vmCfg vm.Config, timeout time.Duration) ([]byte, uint64, bool, error) {
  649. defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  650. state, header, err := b.StateAndHeaderByNumber(ctx, blockNr)
  651. if state == nil || err != nil {
  652. return nil, 0, false, err
  653. }
  654. // Set sender address or use a default if none specified
  655. var addr common.Address
  656. if args.From == nil {
  657. if wallets := b.AccountManager().Wallets(); len(wallets) > 0 {
  658. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  659. addr = accounts[0].Address
  660. }
  661. }
  662. } else {
  663. addr = *args.From
  664. }
  665. // Set default gas & gas price if none were set
  666. gas := uint64(math.MaxUint64 / 2)
  667. if args.Gas != nil {
  668. gas = uint64(*args.Gas)
  669. }
  670. gasPrice := new(big.Int).SetUint64(defaultGasPrice)
  671. if args.GasPrice != nil {
  672. gasPrice = args.GasPrice.ToInt()
  673. }
  674. value := new(big.Int)
  675. if args.Value != nil {
  676. value = args.Value.ToInt()
  677. }
  678. var data []byte
  679. if args.Data != nil {
  680. data = []byte(*args.Data)
  681. }
  682. // Create new call message
  683. msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, data, false)
  684. // Setup context so it may be cancelled the call has completed
  685. // or, in case of unmetered gas, setup a context with a timeout.
  686. var cancel context.CancelFunc
  687. if timeout > 0 {
  688. ctx, cancel = context.WithTimeout(ctx, timeout)
  689. } else {
  690. ctx, cancel = context.WithCancel(ctx)
  691. }
  692. // Make sure the context is cancelled when the call has completed
  693. // this makes sure resources are cleaned up.
  694. defer cancel()
  695. // Get a new instance of the EVM.
  696. evm, vmError, err := b.GetEVM(ctx, msg, state, header)
  697. if err != nil {
  698. return nil, 0, false, err
  699. }
  700. // Wait for the context to be done and cancel the evm. Even if the
  701. // EVM has finished, cancelling may be done (repeatedly)
  702. go func() {
  703. <-ctx.Done()
  704. evm.Cancel()
  705. }()
  706. // Setup the gas pool (also for unmetered requests)
  707. // and apply the message.
  708. gp := new(core.GasPool).AddGas(math.MaxUint64)
  709. res, gas, failed, err := core.ApplyMessage(evm, msg, gp)
  710. if err := vmError(); err != nil {
  711. return nil, 0, false, err
  712. }
  713. return res, gas, failed, err
  714. }
  715. // Call executes the given transaction on the state for the given block number.
  716. // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
  717. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
  718. result, _, _, err := DoCall(ctx, s.b, args, blockNr, vm.Config{}, 5*time.Second)
  719. return (hexutil.Bytes)(result), err
  720. }
  721. func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Uint64, error) {
  722. // Binary search the gas requirement, as it may be higher than the amount used
  723. var (
  724. lo uint64 = params.TxGas - 1
  725. hi uint64
  726. cap uint64
  727. )
  728. if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  729. hi = uint64(*args.Gas)
  730. } else {
  731. // Retrieve the block to act as the gas ceiling
  732. block, err := b.BlockByNumber(ctx, blockNr)
  733. if err != nil {
  734. return 0, err
  735. }
  736. hi = block.GasLimit()
  737. }
  738. cap = hi
  739. // Create a helper to check if a gas allowance results in an executable transaction
  740. executable := func(gas uint64) bool {
  741. args.Gas = (*hexutil.Uint64)(&gas)
  742. _, _, failed, err := DoCall(ctx, b, args, rpc.PendingBlockNumber, vm.Config{}, 0)
  743. if err != nil || failed {
  744. return false
  745. }
  746. return true
  747. }
  748. // Execute the binary search and hone in on an executable gas limit
  749. for lo+1 < hi {
  750. mid := (hi + lo) / 2
  751. if !executable(mid) {
  752. lo = mid
  753. } else {
  754. hi = mid
  755. }
  756. }
  757. // Reject the transaction as invalid if it still fails at the highest allowance
  758. if hi == cap {
  759. if !executable(hi) {
  760. return 0, fmt.Errorf("gas required exceeds allowance or always failing transaction")
  761. }
  762. }
  763. return hexutil.Uint64(hi), nil
  764. }
  765. // EstimateGas returns an estimate of the amount of gas needed to execute the
  766. // given transaction against the current pending block.
  767. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) {
  768. return DoEstimateGas(ctx, s.b, args, rpc.PendingBlockNumber)
  769. }
  770. // ExecutionResult groups all structured logs emitted by the EVM
  771. // while replaying a transaction in debug mode as well as transaction
  772. // execution status, the amount of gas used and the return value
  773. type ExecutionResult struct {
  774. Gas uint64 `json:"gas"`
  775. Failed bool `json:"failed"`
  776. ReturnValue string `json:"returnValue"`
  777. StructLogs []StructLogRes `json:"structLogs"`
  778. }
  779. // StructLogRes stores a structured log emitted by the EVM while replaying a
  780. // transaction in debug mode
  781. type StructLogRes struct {
  782. Pc uint64 `json:"pc"`
  783. Op string `json:"op"`
  784. Gas uint64 `json:"gas"`
  785. GasCost uint64 `json:"gasCost"`
  786. Depth int `json:"depth"`
  787. Error error `json:"error,omitempty"`
  788. Stack *[]string `json:"stack,omitempty"`
  789. Memory *[]string `json:"memory,omitempty"`
  790. Storage *map[string]string `json:"storage,omitempty"`
  791. }
  792. // FormatLogs formats EVM returned structured logs for json output
  793. func FormatLogs(logs []vm.StructLog) []StructLogRes {
  794. formatted := make([]StructLogRes, len(logs))
  795. for index, trace := range logs {
  796. formatted[index] = StructLogRes{
  797. Pc: trace.Pc,
  798. Op: trace.Op.String(),
  799. Gas: trace.Gas,
  800. GasCost: trace.GasCost,
  801. Depth: trace.Depth,
  802. Error: trace.Err,
  803. }
  804. if trace.Stack != nil {
  805. stack := make([]string, len(trace.Stack))
  806. for i, stackValue := range trace.Stack {
  807. stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
  808. }
  809. formatted[index].Stack = &stack
  810. }
  811. if trace.Memory != nil {
  812. memory := make([]string, 0, (len(trace.Memory)+31)/32)
  813. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  814. memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  815. }
  816. formatted[index].Memory = &memory
  817. }
  818. if trace.Storage != nil {
  819. storage := make(map[string]string)
  820. for i, storageValue := range trace.Storage {
  821. storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  822. }
  823. formatted[index].Storage = &storage
  824. }
  825. }
  826. return formatted
  827. }
  828. // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  829. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  830. // transaction hashes.
  831. func RPCMarshalBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  832. head := b.Header() // copies the header once
  833. fields := map[string]interface{}{
  834. "number": (*hexutil.Big)(head.Number),
  835. "hash": b.Hash(),
  836. "parentHash": head.ParentHash,
  837. "nonce": head.Nonce,
  838. "mixHash": head.MixDigest,
  839. "sha3Uncles": head.UncleHash,
  840. "logsBloom": head.Bloom,
  841. "stateRoot": head.Root,
  842. "miner": head.Coinbase,
  843. "difficulty": (*hexutil.Big)(head.Difficulty),
  844. "extraData": hexutil.Bytes(head.Extra),
  845. "size": hexutil.Uint64(b.Size()),
  846. "gasLimit": hexutil.Uint64(head.GasLimit),
  847. "gasUsed": hexutil.Uint64(head.GasUsed),
  848. "timestamp": hexutil.Uint64(head.Time),
  849. "transactionsRoot": head.TxHash,
  850. "receiptsRoot": head.ReceiptHash,
  851. }
  852. if inclTx {
  853. formatTx := func(tx *types.Transaction) (interface{}, error) {
  854. return tx.Hash(), nil
  855. }
  856. if fullTx {
  857. formatTx = func(tx *types.Transaction) (interface{}, error) {
  858. return newRPCTransactionFromBlockHash(b, tx.Hash()), nil
  859. }
  860. }
  861. txs := b.Transactions()
  862. transactions := make([]interface{}, len(txs))
  863. var err error
  864. for i, tx := range txs {
  865. if transactions[i], err = formatTx(tx); err != nil {
  866. return nil, err
  867. }
  868. }
  869. fields["transactions"] = transactions
  870. }
  871. uncles := b.Uncles()
  872. uncleHashes := make([]common.Hash, len(uncles))
  873. for i, uncle := range uncles {
  874. uncleHashes[i] = uncle.Hash()
  875. }
  876. fields["uncles"] = uncleHashes
  877. return fields, nil
  878. }
  879. // rpcOutputBlock uses the generalized output filler, then adds the total difficulty field, which requires
  880. // a `PublicBlockchainAPI`.
  881. func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  882. fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  883. if err != nil {
  884. return nil, err
  885. }
  886. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(b.Hash()))
  887. return fields, err
  888. }
  889. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  890. type RPCTransaction struct {
  891. BlockHash common.Hash `json:"blockHash"`
  892. BlockNumber *hexutil.Big `json:"blockNumber"`
  893. From common.Address `json:"from"`
  894. Gas hexutil.Uint64 `json:"gas"`
  895. GasPrice *hexutil.Big `json:"gasPrice"`
  896. Hash common.Hash `json:"hash"`
  897. Input hexutil.Bytes `json:"input"`
  898. Nonce hexutil.Uint64 `json:"nonce"`
  899. To *common.Address `json:"to"`
  900. TransactionIndex hexutil.Uint `json:"transactionIndex"`
  901. Value *hexutil.Big `json:"value"`
  902. V *hexutil.Big `json:"v"`
  903. R *hexutil.Big `json:"r"`
  904. S *hexutil.Big `json:"s"`
  905. }
  906. // newRPCTransaction returns a transaction that will serialize to the RPC
  907. // representation, with the given location metadata set (if available).
  908. func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  909. var signer types.Signer = types.FrontierSigner{}
  910. if tx.Protected() {
  911. signer = types.NewEIP155Signer(tx.ChainId())
  912. }
  913. from, _ := types.Sender(signer, tx)
  914. v, r, s := tx.RawSignatureValues()
  915. result := &RPCTransaction{
  916. From: from,
  917. Gas: hexutil.Uint64(tx.Gas()),
  918. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  919. Hash: tx.Hash(),
  920. Input: hexutil.Bytes(tx.Data()),
  921. Nonce: hexutil.Uint64(tx.Nonce()),
  922. To: tx.To(),
  923. Value: (*hexutil.Big)(tx.Value()),
  924. V: (*hexutil.Big)(v),
  925. R: (*hexutil.Big)(r),
  926. S: (*hexutil.Big)(s),
  927. }
  928. if blockHash != (common.Hash{}) {
  929. result.BlockHash = blockHash
  930. result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  931. result.TransactionIndex = hexutil.Uint(index)
  932. }
  933. return result
  934. }
  935. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  936. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  937. return newRPCTransaction(tx, common.Hash{}, 0, 0)
  938. }
  939. // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  940. func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  941. txs := b.Transactions()
  942. if index >= uint64(len(txs)) {
  943. return nil
  944. }
  945. return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  946. }
  947. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  948. func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  949. txs := b.Transactions()
  950. if index >= uint64(len(txs)) {
  951. return nil
  952. }
  953. blob, _ := rlp.EncodeToBytes(txs[index])
  954. return blob
  955. }
  956. // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  957. func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  958. for idx, tx := range b.Transactions() {
  959. if tx.Hash() == hash {
  960. return newRPCTransactionFromBlockIndex(b, uint64(idx))
  961. }
  962. }
  963. return nil
  964. }
  965. // PublicTransactionPoolAPI exposes methods for the RPC interface
  966. type PublicTransactionPoolAPI struct {
  967. b Backend
  968. nonceLock *AddrLocker
  969. }
  970. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  971. func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  972. return &PublicTransactionPoolAPI{b, nonceLock}
  973. }
  974. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  975. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  976. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  977. n := hexutil.Uint(len(block.Transactions()))
  978. return &n
  979. }
  980. return nil
  981. }
  982. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  983. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  984. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  985. n := hexutil.Uint(len(block.Transactions()))
  986. return &n
  987. }
  988. return nil
  989. }
  990. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  991. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  992. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  993. return newRPCTransactionFromBlockIndex(block, uint64(index))
  994. }
  995. return nil
  996. }
  997. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  998. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  999. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1000. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1001. }
  1002. return nil
  1003. }
  1004. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1005. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1006. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1007. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1008. }
  1009. return nil
  1010. }
  1011. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1012. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1013. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1014. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1015. }
  1016. return nil
  1017. }
  1018. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1019. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {
  1020. // Ask transaction pool for the nonce which includes pending transactions
  1021. if blockNr == rpc.PendingBlockNumber {
  1022. nonce, err := s.b.GetPoolNonce(ctx, address)
  1023. if err != nil {
  1024. return nil, err
  1025. }
  1026. return (*hexutil.Uint64)(&nonce), nil
  1027. }
  1028. // Resolve block number and use its state to ask for the nonce
  1029. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  1030. if state == nil || err != nil {
  1031. return nil, err
  1032. }
  1033. nonce := state.GetNonce(address)
  1034. return (*hexutil.Uint64)(&nonce), state.Error()
  1035. }
  1036. // GetTransactionByHash returns the transaction for the given hash
  1037. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) *RPCTransaction {
  1038. // Try to return an already finalized transaction
  1039. if tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash); tx != nil {
  1040. return newRPCTransaction(tx, blockHash, blockNumber, index)
  1041. }
  1042. // No finalized transaction, try to retrieve it from the pool
  1043. if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1044. return newRPCPendingTransaction(tx)
  1045. }
  1046. // Transaction unknown, return as such
  1047. return nil
  1048. }
  1049. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1050. func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1051. var tx *types.Transaction
  1052. // Retrieve a finalized transaction, or a pooled otherwise
  1053. if tx, _, _, _ = rawdb.ReadTransaction(s.b.ChainDb(), hash); tx == nil {
  1054. if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1055. // Transaction not found anywhere, abort
  1056. return nil, nil
  1057. }
  1058. }
  1059. // Serialize to RLP and return
  1060. return rlp.EncodeToBytes(tx)
  1061. }
  1062. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1063. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1064. tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
  1065. if tx == nil {
  1066. return nil, nil
  1067. }
  1068. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1069. if err != nil {
  1070. return nil, err
  1071. }
  1072. if len(receipts) <= int(index) {
  1073. return nil, nil
  1074. }
  1075. receipt := receipts[index]
  1076. var signer types.Signer = types.FrontierSigner{}
  1077. if tx.Protected() {
  1078. signer = types.NewEIP155Signer(tx.ChainId())
  1079. }
  1080. from, _ := types.Sender(signer, tx)
  1081. fields := map[string]interface{}{
  1082. "blockHash": blockHash,
  1083. "blockNumber": hexutil.Uint64(blockNumber),
  1084. "transactionHash": hash,
  1085. "transactionIndex": hexutil.Uint64(index),
  1086. "from": from,
  1087. "to": tx.To(),
  1088. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1089. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1090. "contractAddress": nil,
  1091. "logs": receipt.Logs,
  1092. "logsBloom": receipt.Bloom,
  1093. }
  1094. // Assign receipt status or post state.
  1095. if len(receipt.PostState) > 0 {
  1096. fields["root"] = hexutil.Bytes(receipt.PostState)
  1097. } else {
  1098. fields["status"] = hexutil.Uint(receipt.Status)
  1099. }
  1100. if receipt.Logs == nil {
  1101. fields["logs"] = [][]*types.Log{}
  1102. }
  1103. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1104. if receipt.ContractAddress != (common.Address{}) {
  1105. fields["contractAddress"] = receipt.ContractAddress
  1106. }
  1107. return fields, nil
  1108. }
  1109. // sign is a helper function that signs a transaction with the private key of the given address.
  1110. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1111. // Look up the wallet containing the requested signer
  1112. account := accounts.Account{Address: addr}
  1113. wallet, err := s.b.AccountManager().Find(account)
  1114. if err != nil {
  1115. return nil, err
  1116. }
  1117. // Request the wallet to sign the transaction
  1118. return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1119. }
  1120. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1121. type SendTxArgs struct {
  1122. From common.Address `json:"from"`
  1123. To *common.Address `json:"to"`
  1124. Gas *hexutil.Uint64 `json:"gas"`
  1125. GasPrice *hexutil.Big `json:"gasPrice"`
  1126. Value *hexutil.Big `json:"value"`
  1127. Nonce *hexutil.Uint64 `json:"nonce"`
  1128. // We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1129. // newer name and should be preferred by clients.
  1130. Data *hexutil.Bytes `json:"data"`
  1131. Input *hexutil.Bytes `json:"input"`
  1132. }
  1133. // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1134. func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1135. if args.Gas == nil {
  1136. args.Gas = new(hexutil.Uint64)
  1137. *(*uint64)(args.Gas) = 90000
  1138. }
  1139. if args.GasPrice == nil {
  1140. price, err := b.SuggestPrice(ctx)
  1141. if err != nil {
  1142. return err
  1143. }
  1144. args.GasPrice = (*hexutil.Big)(price)
  1145. }
  1146. if args.Value == nil {
  1147. args.Value = new(hexutil.Big)
  1148. }
  1149. if args.Nonce == nil {
  1150. nonce, err := b.GetPoolNonce(ctx, args.From)
  1151. if err != nil {
  1152. return err
  1153. }
  1154. args.Nonce = (*hexutil.Uint64)(&nonce)
  1155. }
  1156. if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1157. return errors.New(`Both "data" and "input" are set and not equal. Please use "input" to pass transaction call data.`)
  1158. }
  1159. if args.To == nil {
  1160. // Contract creation
  1161. var input []byte
  1162. if args.Data != nil {
  1163. input = *args.Data
  1164. } else if args.Input != nil {
  1165. input = *args.Input
  1166. }
  1167. if len(input) == 0 {
  1168. return errors.New(`contract creation without any data provided`)
  1169. }
  1170. }
  1171. return nil
  1172. }
  1173. func (args *SendTxArgs) toTransaction() *types.Transaction {
  1174. var input []byte
  1175. if args.Data != nil {
  1176. input = *args.Data
  1177. } else if args.Input != nil {
  1178. input = *args.Input
  1179. }
  1180. if args.To == nil {
  1181. return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1182. }
  1183. return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1184. }
  1185. // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1186. func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1187. if err := b.SendTx(ctx, tx); err != nil {
  1188. return common.Hash{}, err
  1189. }
  1190. if tx.To() == nil {
  1191. signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1192. from, err := types.Sender(signer, tx)
  1193. if err != nil {
  1194. return common.Hash{}, err
  1195. }
  1196. addr := crypto.CreateAddress(from, tx.Nonce())
  1197. log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1198. } else {
  1199. log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1200. }
  1201. return tx.Hash(), nil
  1202. }
  1203. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1204. // transaction pool.
  1205. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1206. // Look up the wallet containing the requested signer
  1207. account := accounts.Account{Address: args.From}
  1208. wallet, err := s.b.AccountManager().Find(account)
  1209. if err != nil {
  1210. return common.Hash{}, err
  1211. }
  1212. if args.Nonce == nil {
  1213. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  1214. // the same nonce to multiple accounts.
  1215. s.nonceLock.LockAddr(args.From)
  1216. defer s.nonceLock.UnlockAddr(args.From)
  1217. }
  1218. // Set some sanity defaults and terminate on failure
  1219. if err := args.setDefaults(ctx, s.b); err != nil {
  1220. return common.Hash{}, err
  1221. }
  1222. // Assemble the transaction and sign with the wallet
  1223. tx := args.toTransaction()
  1224. signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1225. if err != nil {
  1226. return common.Hash{}, err
  1227. }
  1228. return SubmitTransaction(ctx, s.b, signed)
  1229. }
  1230. // SendRawTransaction will add the signed transaction to the transaction pool.
  1231. // The sender is responsible for signing the transaction and using the correct nonce.
  1232. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  1233. tx := new(types.Transaction)
  1234. if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1235. return common.Hash{}, err
  1236. }
  1237. return SubmitTransaction(ctx, s.b, tx)
  1238. }
  1239. // Sign calculates an ECDSA signature for:
  1240. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1241. //
  1242. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1243. // where the V value will be 27 or 28 for legacy reasons.
  1244. //
  1245. // The account associated with addr must be unlocked.
  1246. //
  1247. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1248. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1249. // Look up the wallet containing the requested signer
  1250. account := accounts.Account{Address: addr}
  1251. wallet, err := s.b.AccountManager().Find(account)
  1252. if err != nil {
  1253. return nil, err
  1254. }
  1255. // Sign the requested hash with the wallet
  1256. signature, err := wallet.SignText(account, data)
  1257. if err == nil {
  1258. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1259. }
  1260. return signature, err
  1261. }
  1262. // SignTransactionResult represents a RLP encoded signed transaction.
  1263. type SignTransactionResult struct {
  1264. Raw hexutil.Bytes `json:"raw"`
  1265. Tx *types.Transaction `json:"tx"`
  1266. }
  1267. // SignTransaction will sign the given transaction with the from account.
  1268. // The node needs to have the private key of the account corresponding with
  1269. // the given from address and it needs to be unlocked.
  1270. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1271. if args.Gas == nil {
  1272. return nil, fmt.Errorf("gas not specified")
  1273. }
  1274. if args.GasPrice == nil {
  1275. return nil, fmt.Errorf("gasPrice not specified")
  1276. }
  1277. if args.Nonce == nil {
  1278. return nil, fmt.Errorf("nonce not specified")
  1279. }
  1280. if err := args.setDefaults(ctx, s.b); err != nil {
  1281. return nil, err
  1282. }
  1283. tx, err := s.sign(args.From, args.toTransaction())
  1284. if err != nil {
  1285. return nil, err
  1286. }
  1287. data, err := rlp.EncodeToBytes(tx)
  1288. if err != nil {
  1289. return nil, err
  1290. }
  1291. return &SignTransactionResult{data, tx}, nil
  1292. }
  1293. // PendingTransactions returns the transactions that are in the transaction pool
  1294. // and have a from address that is one of the accounts this node manages.
  1295. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1296. pending, err := s.b.GetPoolTransactions()
  1297. if err != nil {
  1298. return nil, err
  1299. }
  1300. accounts := make(map[common.Address]struct{})
  1301. for _, wallet := range s.b.AccountManager().Wallets() {
  1302. for _, account := range wallet.Accounts() {
  1303. accounts[account.Address] = struct{}{}
  1304. }
  1305. }
  1306. transactions := make([]*RPCTransaction, 0, len(pending))
  1307. for _, tx := range pending {
  1308. var signer types.Signer = types.HomesteadSigner{}
  1309. if tx.Protected() {
  1310. signer = types.NewEIP155Signer(tx.ChainId())
  1311. }
  1312. from, _ := types.Sender(signer, tx)
  1313. if _, exists := accounts[from]; exists {
  1314. transactions = append(transactions, newRPCPendingTransaction(tx))
  1315. }
  1316. }
  1317. return transactions, nil
  1318. }
  1319. // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1320. // the given transaction from the pool and reinsert it with the new gas price and limit.
  1321. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1322. if sendArgs.Nonce == nil {
  1323. return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1324. }
  1325. if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1326. return common.Hash{}, err
  1327. }
  1328. matchTx := sendArgs.toTransaction()
  1329. pending, err := s.b.GetPoolTransactions()
  1330. if err != nil {
  1331. return common.Hash{}, err
  1332. }
  1333. for _, p := range pending {
  1334. var signer types.Signer = types.HomesteadSigner{}
  1335. if p.Protected() {
  1336. signer = types.NewEIP155Signer(p.ChainId())
  1337. }
  1338. wantSigHash := signer.Hash(matchTx)
  1339. if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1340. // Match. Re-sign and send the transaction.
  1341. if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1342. sendArgs.GasPrice = gasPrice
  1343. }
  1344. if gasLimit != nil && *gasLimit != 0 {
  1345. sendArgs.Gas = gasLimit
  1346. }
  1347. signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  1348. if err != nil {
  1349. return common.Hash{}, err
  1350. }
  1351. if err = s.b.SendTx(ctx, signedTx); err != nil {
  1352. return common.Hash{}, err
  1353. }
  1354. return signedTx.Hash(), nil
  1355. }
  1356. }
  1357. return common.Hash{}, fmt.Errorf("Transaction %#x not found", matchTx.Hash())
  1358. }
  1359. // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  1360. // debugging endpoint.
  1361. type PublicDebugAPI struct {
  1362. b Backend
  1363. }
  1364. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1365. // of the Ethereum service.
  1366. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1367. return &PublicDebugAPI{b: b}
  1368. }
  1369. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1370. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1371. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1372. if block == nil {
  1373. return "", fmt.Errorf("block #%d not found", number)
  1374. }
  1375. encoded, err := rlp.EncodeToBytes(block)
  1376. if err != nil {
  1377. return "", err
  1378. }
  1379. return fmt.Sprintf("%x", encoded), nil
  1380. }
  1381. // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  1382. // given address, returning the address of the recovered signature
  1383. //
  1384. // This is a temporary method to debug the externalsigner integration,
  1385. // TODO: Remove this method when the integration is mature
  1386. func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  1387. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1388. if block == nil {
  1389. return common.Address{}, fmt.Errorf("block #%d not found", number)
  1390. }
  1391. header := block.Header()
  1392. header.Extra = make([]byte, 32+65)
  1393. encoded := clique.CliqueRLP(header)
  1394. // Look up the wallet containing the requested signer
  1395. account := accounts.Account{Address: address}
  1396. wallet, err := api.b.AccountManager().Find(account)
  1397. if err != nil {
  1398. return common.Address{}, err
  1399. }
  1400. signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  1401. if err != nil {
  1402. return common.Address{}, err
  1403. }
  1404. sealHash := clique.SealHash(header).Bytes()
  1405. log.Info("test signing of clique block",
  1406. "Sealhash", fmt.Sprintf("%x", sealHash),
  1407. "signature", fmt.Sprintf("%x", signature))
  1408. pubkey, err := crypto.Ecrecover(sealHash, signature)
  1409. if err != nil {
  1410. return common.Address{}, err
  1411. }
  1412. var signer common.Address
  1413. copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  1414. return signer, nil
  1415. }
  1416. // PrintBlock retrieves a block and returns its pretty printed form.
  1417. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1418. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1419. if block == nil {
  1420. return "", fmt.Errorf("block #%d not found", number)
  1421. }
  1422. return spew.Sdump(block), nil
  1423. }
  1424. // SeedHash retrieves the seed hash of a block.
  1425. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1426. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1427. if block == nil {
  1428. return "", fmt.Errorf("block #%d not found", number)
  1429. }
  1430. return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  1431. }
  1432. // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  1433. // debugging endpoint.
  1434. type PrivateDebugAPI struct {
  1435. b Backend
  1436. }
  1437. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1438. // of the Ethereum service.
  1439. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1440. return &PrivateDebugAPI{b: b}
  1441. }
  1442. // ChaindbProperty returns leveldb properties of the chain database.
  1443. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1444. ldb, ok := api.b.ChainDb().(interface {
  1445. LDB() *leveldb.DB
  1446. })
  1447. if !ok {
  1448. return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1449. }
  1450. if property == "" {
  1451. property = "leveldb.stats"
  1452. } else if !strings.HasPrefix(property, "leveldb.") {
  1453. property = "leveldb." + property
  1454. }
  1455. return ldb.LDB().GetProperty(property)
  1456. }
  1457. func (api *PrivateDebugAPI) ChaindbCompact() error {
  1458. for b := byte(0); b < 255; b++ {
  1459. log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1460. if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  1461. log.Error("Database compaction failed", "err", err)
  1462. return err
  1463. }
  1464. }
  1465. return nil
  1466. }
  1467. // SetHead rewinds the head of the blockchain to a previous block.
  1468. func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1469. api.b.SetHead(uint64(number))
  1470. }
  1471. // PublicNetAPI offers network related RPC methods
  1472. type PublicNetAPI struct {
  1473. net *p2p.Server
  1474. networkVersion uint64
  1475. }
  1476. // NewPublicNetAPI creates a new net API instance.
  1477. func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  1478. return &PublicNetAPI{net, networkVersion}
  1479. }
  1480. // Listening returns an indication if the node is listening for network connections.
  1481. func (s *PublicNetAPI) Listening() bool {
  1482. return true // always listening
  1483. }
  1484. // PeerCount returns the number of connected peers
  1485. func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1486. return hexutil.Uint(s.net.PeerCount())
  1487. }
  1488. // Version returns the current ethereum protocol version.
  1489. func (s *PublicNetAPI) Version() string {
  1490. return fmt.Sprintf("%d", s.networkVersion)
  1491. }