api.go 63 KB

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