api.go 70 KB

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