api.go 59 KB

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