api.go 70 KB

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