api.go 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472
  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. "context"
  19. "crypto/rand"
  20. "encoding/hex"
  21. "errors"
  22. "fmt"
  23. "github.com/ethereum/go-ethereum/consensus"
  24. "math/big"
  25. "strings"
  26. "time"
  27. "github.com/davecgh/go-spew/spew"
  28. "github.com/ethereum/go-ethereum/accounts"
  29. "github.com/ethereum/go-ethereum/accounts/abi"
  30. "github.com/ethereum/go-ethereum/accounts/keystore"
  31. "github.com/ethereum/go-ethereum/accounts/scwallet"
  32. "github.com/ethereum/go-ethereum/common"
  33. "github.com/ethereum/go-ethereum/common/hexutil"
  34. "github.com/ethereum/go-ethereum/common/math"
  35. "github.com/ethereum/go-ethereum/consensus/ethash"
  36. "github.com/ethereum/go-ethereum/consensus/misc"
  37. "github.com/ethereum/go-ethereum/core"
  38. "github.com/ethereum/go-ethereum/core/state"
  39. "github.com/ethereum/go-ethereum/core/types"
  40. "github.com/ethereum/go-ethereum/core/vm"
  41. "github.com/ethereum/go-ethereum/crypto"
  42. "github.com/ethereum/go-ethereum/eth/tracers/logger"
  43. "github.com/ethereum/go-ethereum/log"
  44. "github.com/ethereum/go-ethereum/p2p"
  45. "github.com/ethereum/go-ethereum/params"
  46. "github.com/ethereum/go-ethereum/rlp"
  47. "github.com/ethereum/go-ethereum/rpc"
  48. "github.com/tyler-smith/go-bip39"
  49. "golang.org/x/crypto/sha3"
  50. )
  51. // EthereumAPI provides an API to access Ethereum related information.
  52. type EthereumAPI struct {
  53. b Backend
  54. }
  55. // NewEthereumAPI creates a new Ethereum protocol API.
  56. func NewEthereumAPI(b Backend) *EthereumAPI {
  57. return &EthereumAPI{b}
  58. }
  59. // GasPrice returns a suggestion for a gas price for legacy transactions.
  60. func (s *EthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
  61. tipcap, err := s.b.SuggestGasTipCap(ctx)
  62. if err != nil {
  63. return nil, err
  64. }
  65. if head := s.b.CurrentHeader(); head.BaseFee != nil {
  66. tipcap.Add(tipcap, head.BaseFee)
  67. }
  68. return (*hexutil.Big)(tipcap), err
  69. }
  70. // MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee transactions.
  71. func (s *EthereumAPI) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) {
  72. tipcap, err := s.b.SuggestGasTipCap(ctx)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return (*hexutil.Big)(tipcap), err
  77. }
  78. type feeHistoryResult struct {
  79. OldestBlock *hexutil.Big `json:"oldestBlock"`
  80. Reward [][]*hexutil.Big `json:"reward,omitempty"`
  81. BaseFee []*hexutil.Big `json:"baseFeePerGas,omitempty"`
  82. GasUsedRatio []float64 `json:"gasUsedRatio"`
  83. }
  84. // FeeHistory returns the fee market history.
  85. func (s *EthereumAPI) FeeHistory(ctx context.Context, blockCount rpc.DecimalOrHex, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) {
  86. oldest, reward, baseFee, gasUsed, err := s.b.FeeHistory(ctx, int(blockCount), lastBlock, rewardPercentiles)
  87. if err != nil {
  88. return nil, err
  89. }
  90. results := &feeHistoryResult{
  91. OldestBlock: (*hexutil.Big)(oldest),
  92. GasUsedRatio: gasUsed,
  93. }
  94. if reward != nil {
  95. results.Reward = make([][]*hexutil.Big, len(reward))
  96. for i, w := range reward {
  97. results.Reward[i] = make([]*hexutil.Big, len(w))
  98. for j, v := range w {
  99. results.Reward[i][j] = (*hexutil.Big)(v)
  100. }
  101. }
  102. }
  103. if baseFee != nil {
  104. results.BaseFee = make([]*hexutil.Big, len(baseFee))
  105. for i, v := range baseFee {
  106. results.BaseFee[i] = (*hexutil.Big)(v)
  107. }
  108. }
  109. return results, nil
  110. }
  111. // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
  112. // yet received the latest block headers from its pears. In case it is synchronizing:
  113. // - startingBlock: block number this node started to synchronise from
  114. // - currentBlock: block number this node is currently importing
  115. // - highestBlock: block number of the highest block header this node has received from peers
  116. // - pulledStates: number of state entries processed until now
  117. // - knownStates: number of known state entries that still need to be pulled
  118. func (s *EthereumAPI) Syncing() (interface{}, error) {
  119. progress := s.b.SyncProgress()
  120. // Return not syncing if the synchronisation already completed
  121. if progress.CurrentBlock >= progress.HighestBlock {
  122. return false, nil
  123. }
  124. // Otherwise gather the block sync stats
  125. return map[string]interface{}{
  126. "startingBlock": hexutil.Uint64(progress.StartingBlock),
  127. "currentBlock": hexutil.Uint64(progress.CurrentBlock),
  128. "highestBlock": hexutil.Uint64(progress.HighestBlock),
  129. "syncedAccounts": hexutil.Uint64(progress.SyncedAccounts),
  130. "syncedAccountBytes": hexutil.Uint64(progress.SyncedAccountBytes),
  131. "syncedBytecodes": hexutil.Uint64(progress.SyncedBytecodes),
  132. "syncedBytecodeBytes": hexutil.Uint64(progress.SyncedBytecodeBytes),
  133. "syncedStorage": hexutil.Uint64(progress.SyncedStorage),
  134. "syncedStorageBytes": hexutil.Uint64(progress.SyncedStorageBytes),
  135. "healedTrienodes": hexutil.Uint64(progress.HealedTrienodes),
  136. "healedTrienodeBytes": hexutil.Uint64(progress.HealedTrienodeBytes),
  137. "healedBytecodes": hexutil.Uint64(progress.HealedBytecodes),
  138. "healedBytecodeBytes": hexutil.Uint64(progress.HealedBytecodeBytes),
  139. "healingTrienodes": hexutil.Uint64(progress.HealingTrienodes),
  140. "healingBytecode": hexutil.Uint64(progress.HealingBytecode),
  141. }, nil
  142. }
  143. // TxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
  144. type TxPoolAPI struct {
  145. b Backend
  146. }
  147. // NewTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
  148. func NewTxPoolAPI(b Backend) *TxPoolAPI {
  149. return &TxPoolAPI{b}
  150. }
  151. // Content returns the transactions contained within the transaction pool.
  152. func (s *TxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
  153. content := map[string]map[string]map[string]*RPCTransaction{
  154. "pending": make(map[string]map[string]*RPCTransaction),
  155. "queued": make(map[string]map[string]*RPCTransaction),
  156. }
  157. pending, queue := s.b.TxPoolContent()
  158. curHeader := s.b.CurrentHeader()
  159. // Flatten the pending transactions
  160. for account, txs := range pending {
  161. dump := make(map[string]*RPCTransaction)
  162. for _, tx := range txs {
  163. dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
  164. }
  165. content["pending"][account.Hex()] = dump
  166. }
  167. // Flatten the queued transactions
  168. for account, txs := range queue {
  169. dump := make(map[string]*RPCTransaction)
  170. for _, tx := range txs {
  171. dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
  172. }
  173. content["queued"][account.Hex()] = dump
  174. }
  175. return content
  176. }
  177. // ContentFrom returns the transactions contained within the transaction pool.
  178. func (s *TxPoolAPI) ContentFrom(addr common.Address) map[string]map[string]*RPCTransaction {
  179. content := make(map[string]map[string]*RPCTransaction, 2)
  180. pending, queue := s.b.TxPoolContentFrom(addr)
  181. curHeader := s.b.CurrentHeader()
  182. // Build the pending transactions
  183. dump := make(map[string]*RPCTransaction, len(pending))
  184. for _, tx := range pending {
  185. dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
  186. }
  187. content["pending"] = dump
  188. // Build the queued transactions
  189. dump = make(map[string]*RPCTransaction, len(queue))
  190. for _, tx := range queue {
  191. dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
  192. }
  193. content["queued"] = dump
  194. return content
  195. }
  196. // Status returns the number of pending and queued transaction in the pool.
  197. func (s *TxPoolAPI) Status() map[string]hexutil.Uint {
  198. pending, queue := s.b.Stats()
  199. return map[string]hexutil.Uint{
  200. "pending": hexutil.Uint(pending),
  201. "queued": hexutil.Uint(queue),
  202. }
  203. }
  204. // Inspect retrieves the content of the transaction pool and flattens it into an
  205. // easily inspectable list.
  206. func (s *TxPoolAPI) Inspect() map[string]map[string]map[string]string {
  207. content := map[string]map[string]map[string]string{
  208. "pending": make(map[string]map[string]string),
  209. "queued": make(map[string]map[string]string),
  210. }
  211. pending, queue := s.b.TxPoolContent()
  212. // Define a formatter to flatten a transaction into a string
  213. var format = func(tx *types.Transaction) string {
  214. if to := tx.To(); to != nil {
  215. return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
  216. }
  217. return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice())
  218. }
  219. // Flatten the pending transactions
  220. for account, txs := range pending {
  221. dump := make(map[string]string)
  222. for _, tx := range txs {
  223. dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
  224. }
  225. content["pending"][account.Hex()] = dump
  226. }
  227. // Flatten the queued transactions
  228. for account, txs := range queue {
  229. dump := make(map[string]string)
  230. for _, tx := range txs {
  231. dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
  232. }
  233. content["queued"][account.Hex()] = dump
  234. }
  235. return content
  236. }
  237. // EthereumAccountAPI provides an API to access accounts managed by this node.
  238. // It offers only methods that can retrieve accounts.
  239. type EthereumAccountAPI struct {
  240. am *accounts.Manager
  241. }
  242. // NewEthereumAccountAPI creates a new EthereumAccountAPI.
  243. func NewEthereumAccountAPI(am *accounts.Manager) *EthereumAccountAPI {
  244. return &EthereumAccountAPI{am: am}
  245. }
  246. // Accounts returns the collection of accounts this node manages.
  247. func (s *EthereumAccountAPI) Accounts() []common.Address {
  248. return s.am.Accounts()
  249. }
  250. // PersonalAccountAPI provides an API to access accounts managed by this node.
  251. // It offers methods to create, (un)lock en list accounts. Some methods accept
  252. // passwords and are therefore considered private by default.
  253. type PersonalAccountAPI struct {
  254. am *accounts.Manager
  255. nonceLock *AddrLocker
  256. b Backend
  257. }
  258. // NewPersonalAccountAPI create a new PersonalAccountAPI.
  259. func NewPersonalAccountAPI(b Backend, nonceLock *AddrLocker) *PersonalAccountAPI {
  260. return &PersonalAccountAPI{
  261. am: b.AccountManager(),
  262. nonceLock: nonceLock,
  263. b: b,
  264. }
  265. }
  266. // ListAccounts will return a list of addresses for accounts this node manages.
  267. func (s *PersonalAccountAPI) ListAccounts() []common.Address {
  268. return s.am.Accounts()
  269. }
  270. // rawWallet is a JSON representation of an accounts.Wallet interface, with its
  271. // data contents extracted into plain fields.
  272. type rawWallet struct {
  273. URL string `json:"url"`
  274. Status string `json:"status"`
  275. Failure string `json:"failure,omitempty"`
  276. Accounts []accounts.Account `json:"accounts,omitempty"`
  277. }
  278. // ListWallets will return a list of wallets this node manages.
  279. func (s *PersonalAccountAPI) ListWallets() []rawWallet {
  280. wallets := make([]rawWallet, 0) // return [] instead of nil if empty
  281. for _, wallet := range s.am.Wallets() {
  282. status, failure := wallet.Status()
  283. raw := rawWallet{
  284. URL: wallet.URL().String(),
  285. Status: status,
  286. Accounts: wallet.Accounts(),
  287. }
  288. if failure != nil {
  289. raw.Failure = failure.Error()
  290. }
  291. wallets = append(wallets, raw)
  292. }
  293. return wallets
  294. }
  295. // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
  296. // connection and attempting to authenticate via the provided passphrase. Note,
  297. // the method may return an extra challenge requiring a second open (e.g. the
  298. // Trezor PIN matrix challenge).
  299. func (s *PersonalAccountAPI) OpenWallet(url string, passphrase *string) error {
  300. wallet, err := s.am.Wallet(url)
  301. if err != nil {
  302. return err
  303. }
  304. pass := ""
  305. if passphrase != nil {
  306. pass = *passphrase
  307. }
  308. return wallet.Open(pass)
  309. }
  310. // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
  311. // it for later reuse.
  312. func (s *PersonalAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
  313. wallet, err := s.am.Wallet(url)
  314. if err != nil {
  315. return accounts.Account{}, err
  316. }
  317. derivPath, err := accounts.ParseDerivationPath(path)
  318. if err != nil {
  319. return accounts.Account{}, err
  320. }
  321. if pin == nil {
  322. pin = new(bool)
  323. }
  324. return wallet.Derive(derivPath, *pin)
  325. }
  326. // NewAccount will create a new account and returns the address for the new account.
  327. func (s *PersonalAccountAPI) NewAccount(password string) (common.Address, error) {
  328. ks, err := fetchKeystore(s.am)
  329. if err != nil {
  330. return common.Address{}, err
  331. }
  332. acc, err := ks.NewAccount(password)
  333. if err == nil {
  334. log.Info("Your new key was generated", "address", acc.Address)
  335. log.Warn("Please backup your key file!", "path", acc.URL.Path)
  336. log.Warn("Please remember your password!")
  337. return acc.Address, nil
  338. }
  339. return common.Address{}, err
  340. }
  341. // fetchKeystore retrieves the encrypted keystore from the account manager.
  342. func fetchKeystore(am *accounts.Manager) (*keystore.KeyStore, error) {
  343. if ks := am.Backends(keystore.KeyStoreType); len(ks) > 0 {
  344. return ks[0].(*keystore.KeyStore), nil
  345. }
  346. return nil, errors.New("local keystore not used")
  347. }
  348. // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
  349. // encrypting it with the passphrase.
  350. func (s *PersonalAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
  351. key, err := crypto.HexToECDSA(privkey)
  352. if err != nil {
  353. return common.Address{}, err
  354. }
  355. ks, err := fetchKeystore(s.am)
  356. if err != nil {
  357. return common.Address{}, err
  358. }
  359. acc, err := ks.ImportECDSA(key, password)
  360. return acc.Address, err
  361. }
  362. // UnlockAccount will unlock the account associated with the given address with
  363. // the given password for duration seconds. If duration is nil it will use a
  364. // default of 300 seconds. It returns an indication if the account was unlocked.
  365. func (s *PersonalAccountAPI) UnlockAccount(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) {
  366. // When the API is exposed by external RPC(http, ws etc), unless the user
  367. // explicitly specifies to allow the insecure account unlocking, otherwise
  368. // it is disabled.
  369. if s.b.ExtRPCEnabled() && !s.b.AccountManager().Config().InsecureUnlockAllowed {
  370. return false, errors.New("account unlock with HTTP access is forbidden")
  371. }
  372. const max = uint64(time.Duration(math.MaxInt64) / time.Second)
  373. var d time.Duration
  374. if duration == nil {
  375. d = 300 * time.Second
  376. } else if *duration > max {
  377. return false, errors.New("unlock duration too large")
  378. } else {
  379. d = time.Duration(*duration) * time.Second
  380. }
  381. ks, err := fetchKeystore(s.am)
  382. if err != nil {
  383. return false, err
  384. }
  385. err = ks.TimedUnlock(accounts.Account{Address: addr}, password, d)
  386. if err != nil {
  387. log.Warn("Failed account unlock attempt", "address", addr, "err", err)
  388. }
  389. return err == nil, err
  390. }
  391. // LockAccount will lock the account associated with the given address when it's unlocked.
  392. func (s *PersonalAccountAPI) LockAccount(addr common.Address) bool {
  393. if ks, err := fetchKeystore(s.am); err == nil {
  394. return ks.Lock(addr) == nil
  395. }
  396. return false
  397. }
  398. // signTransaction sets defaults and signs the given transaction
  399. // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
  400. // and release it after the transaction has been submitted to the tx pool
  401. func (s *PersonalAccountAPI) signTransaction(ctx context.Context, args *TransactionArgs, passwd string) (*types.Transaction, error) {
  402. // Look up the wallet containing the requested signer
  403. account := accounts.Account{Address: args.from()}
  404. wallet, err := s.am.Find(account)
  405. if err != nil {
  406. return nil, err
  407. }
  408. // Set some sanity defaults and terminate on failure
  409. if err := args.setDefaults(ctx, s.b); err != nil {
  410. return nil, err
  411. }
  412. // Assemble the transaction and sign with the wallet
  413. tx := args.toTransaction()
  414. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber)
  415. chainId := s.b.ChainConfig().ChainID
  416. if header != nil && s.b.ChainConfig().IsEthPoWFork(header.Number) {
  417. chainId = s.b.ChainConfig().ChainID_ALT
  418. }
  419. return wallet.SignTxWithPassphrase(account, passwd, tx, chainId)
  420. }
  421. // SendTransaction will create a transaction from the given arguments and
  422. // tries to sign it with the key associated with args.From. If the given
  423. // passwd isn't able to decrypt the key it fails.
  424. func (s *PersonalAccountAPI) SendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) {
  425. if args.Nonce == nil {
  426. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  427. // the same nonce to multiple accounts.
  428. s.nonceLock.LockAddr(args.from())
  429. defer s.nonceLock.UnlockAddr(args.from())
  430. }
  431. signed, err := s.signTransaction(ctx, &args, passwd)
  432. if err != nil {
  433. log.Warn("Failed transaction send attempt", "from", args.from(), "to", args.To, "value", args.Value.ToInt(), "err", err)
  434. return common.Hash{}, err
  435. }
  436. return SubmitTransaction(ctx, s.b, signed)
  437. }
  438. // SignTransaction will create a transaction from the given arguments and
  439. // tries to sign it with the key associated with args.From. If the given passwd isn't
  440. // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
  441. // to other nodes
  442. func (s *PersonalAccountAPI) SignTransaction(ctx context.Context, args TransactionArgs, passwd string) (*SignTransactionResult, error) {
  443. // No need to obtain the noncelock mutex, since we won't be sending this
  444. // tx into the transaction pool, but right back to the user
  445. if args.From == nil {
  446. return nil, fmt.Errorf("sender not specified")
  447. }
  448. if args.Gas == nil {
  449. return nil, fmt.Errorf("gas not specified")
  450. }
  451. if args.GasPrice == nil && (args.MaxFeePerGas == nil || args.MaxPriorityFeePerGas == nil) {
  452. return nil, fmt.Errorf("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas")
  453. }
  454. if args.Nonce == nil {
  455. return nil, fmt.Errorf("nonce not specified")
  456. }
  457. // Before actually signing the transaction, ensure the transaction fee is reasonable.
  458. tx := args.toTransaction()
  459. if err := checkTxFee(tx.GasPrice(), tx.Gas(), s.b.RPCTxFeeCap()); err != nil {
  460. return nil, err
  461. }
  462. signed, err := s.signTransaction(ctx, &args, passwd)
  463. if err != nil {
  464. log.Warn("Failed transaction sign attempt", "from", args.from(), "to", args.To, "value", args.Value.ToInt(), "err", err)
  465. return nil, err
  466. }
  467. data, err := signed.MarshalBinary()
  468. if err != nil {
  469. return nil, err
  470. }
  471. return &SignTransactionResult{data, signed}, nil
  472. }
  473. // Sign calculates an Ethereum ECDSA signature for:
  474. // keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))
  475. //
  476. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  477. // where the V value will be 27 or 28 for legacy reasons.
  478. //
  479. // The key used to calculate the signature is decrypted with the given password.
  480. //
  481. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  482. func (s *PersonalAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
  483. // Look up the wallet containing the requested signer
  484. account := accounts.Account{Address: addr}
  485. wallet, err := s.b.AccountManager().Find(account)
  486. if err != nil {
  487. return nil, err
  488. }
  489. // Assemble sign the data with the wallet
  490. signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
  491. if err != nil {
  492. log.Warn("Failed data sign attempt", "address", addr, "err", err)
  493. return nil, err
  494. }
  495. signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  496. return signature, nil
  497. }
  498. // EcRecover returns the address for the account that was used to create the signature.
  499. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  500. // the address of:
  501. // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
  502. // addr = ecrecover(hash, signature)
  503. //
  504. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  505. // the V value must be 27 or 28 for legacy reasons.
  506. //
  507. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  508. func (s *PersonalAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
  509. if len(sig) != crypto.SignatureLength {
  510. return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
  511. }
  512. if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 {
  513. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  514. }
  515. sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1
  516. rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
  517. if err != nil {
  518. return common.Address{}, err
  519. }
  520. return crypto.PubkeyToAddress(*rpk), nil
  521. }
  522. // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
  523. func (s *PersonalAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
  524. wallet, err := s.am.Wallet(url)
  525. if err != nil {
  526. return "", err
  527. }
  528. entropy, err := bip39.NewEntropy(256)
  529. if err != nil {
  530. return "", err
  531. }
  532. mnemonic, err := bip39.NewMnemonic(entropy)
  533. if err != nil {
  534. return "", err
  535. }
  536. seed := bip39.NewSeed(mnemonic, "")
  537. switch wallet := wallet.(type) {
  538. case *scwallet.Wallet:
  539. return mnemonic, wallet.Initialize(seed)
  540. default:
  541. return "", fmt.Errorf("specified wallet does not support initialization")
  542. }
  543. }
  544. // Unpair deletes a pairing between wallet and geth.
  545. func (s *PersonalAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
  546. wallet, err := s.am.Wallet(url)
  547. if err != nil {
  548. return err
  549. }
  550. switch wallet := wallet.(type) {
  551. case *scwallet.Wallet:
  552. return wallet.Unpair([]byte(pin))
  553. default:
  554. return fmt.Errorf("specified wallet does not support pairing")
  555. }
  556. }
  557. // BlockChainAPI provides an API to access Ethereum blockchain data.
  558. type BlockChainAPI struct {
  559. b Backend
  560. }
  561. // NewBlockChainAPI creates a new Ethereum blockchain API.
  562. func NewBlockChainAPI(b Backend) *BlockChainAPI {
  563. return &BlockChainAPI{b}
  564. }
  565. // ChainId is the EIP-155 replay-protection chain id for the current Ethereum chain config.
  566. //
  567. // Note, this method does not conform to EIP-695 because the configured chain ID is always
  568. // returned, regardless of the current head block. We used to return an error when the chain
  569. // wasn't synced up to a block where EIP-155 is enabled, but this behavior caused issues
  570. // in CL clients.
  571. func (api *BlockChainAPI) ChainId() *hexutil.Big {
  572. header, _ := api.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber)
  573. if header != nil && api.b.ChainConfig().IsEthPoWFork(header.Number) {
  574. return (*hexutil.Big)(api.b.ChainConfig().ChainID_ALT)
  575. }
  576. return (*hexutil.Big)(api.b.ChainConfig().ChainID)
  577. }
  578. // BlockNumber returns the block number of the chain head.
  579. func (s *BlockChainAPI) BlockNumber() hexutil.Uint64 {
  580. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
  581. return hexutil.Uint64(header.Number.Uint64())
  582. }
  583. // GetBalance returns the amount of wei for the given address in the state of the
  584. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  585. // block numbers are also allowed.
  586. func (s *BlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
  587. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  588. if state == nil || err != nil {
  589. return nil, err
  590. }
  591. return (*hexutil.Big)(state.GetBalance(address)), state.Error()
  592. }
  593. // Result structs for GetProof
  594. type AccountResult struct {
  595. Address common.Address `json:"address"`
  596. AccountProof []string `json:"accountProof"`
  597. Balance *hexutil.Big `json:"balance"`
  598. CodeHash common.Hash `json:"codeHash"`
  599. Nonce hexutil.Uint64 `json:"nonce"`
  600. StorageHash common.Hash `json:"storageHash"`
  601. StorageProof []StorageResult `json:"storageProof"`
  602. }
  603. type StorageResult struct {
  604. Key string `json:"key"`
  605. Value *hexutil.Big `json:"value"`
  606. Proof []string `json:"proof"`
  607. }
  608. // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
  609. func (s *BlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
  610. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  611. if state == nil || err != nil {
  612. return nil, err
  613. }
  614. storageTrie := state.StorageTrie(address)
  615. storageHash := types.EmptyRootHash
  616. codeHash := state.GetCodeHash(address)
  617. storageProof := make([]StorageResult, len(storageKeys))
  618. // if we have a storageTrie, (which means the account exists), we can update the storagehash
  619. if storageTrie != nil {
  620. storageHash = storageTrie.Hash()
  621. } else {
  622. // no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
  623. codeHash = crypto.Keccak256Hash(nil)
  624. }
  625. // create the proof for the storageKeys
  626. for i, key := range storageKeys {
  627. if storageTrie != nil {
  628. proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
  629. if storageError != nil {
  630. return nil, storageError
  631. }
  632. storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), toHexSlice(proof)}
  633. } else {
  634. storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
  635. }
  636. }
  637. // create the accountProof
  638. accountProof, proofErr := state.GetProof(address)
  639. if proofErr != nil {
  640. return nil, proofErr
  641. }
  642. return &AccountResult{
  643. Address: address,
  644. AccountProof: toHexSlice(accountProof),
  645. Balance: (*hexutil.Big)(state.GetBalance(address)),
  646. CodeHash: codeHash,
  647. Nonce: hexutil.Uint64(state.GetNonce(address)),
  648. StorageHash: storageHash,
  649. StorageProof: storageProof,
  650. }, state.Error()
  651. }
  652. // GetHeaderByNumber returns the requested canonical block header.
  653. // * When blockNr is -1 the chain head is returned.
  654. // * When blockNr is -2 the pending chain head is returned.
  655. func (s *BlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
  656. header, err := s.b.HeaderByNumber(ctx, number)
  657. if header != nil && err == nil {
  658. response := s.rpcMarshalHeader(ctx, header)
  659. if number == rpc.PendingBlockNumber {
  660. // Pending header need to nil out a few fields
  661. for _, field := range []string{"hash", "nonce", "miner"} {
  662. response[field] = nil
  663. }
  664. }
  665. return response, err
  666. }
  667. return nil, err
  668. }
  669. // GetHeaderByHash returns the requested header by hash.
  670. func (s *BlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
  671. header, _ := s.b.HeaderByHash(ctx, hash)
  672. if header != nil {
  673. return s.rpcMarshalHeader(ctx, header)
  674. }
  675. return nil
  676. }
  677. // GetBlockByNumber returns the requested canonical block.
  678. // - When blockNr is -1 the chain head is returned.
  679. // - When blockNr is -2 the pending chain head is returned.
  680. // - When fullTx is true all transactions in the block are returned, otherwise
  681. // only the transaction hash is returned.
  682. func (s *BlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  683. block, err := s.b.BlockByNumber(ctx, number)
  684. if block != nil && err == nil {
  685. response, err := s.rpcMarshalBlock(ctx, block, true, fullTx)
  686. if err == nil && number == rpc.PendingBlockNumber {
  687. // Pending blocks need to nil out a few fields
  688. for _, field := range []string{"hash", "nonce", "miner"} {
  689. response[field] = nil
  690. }
  691. }
  692. return response, err
  693. }
  694. return nil, err
  695. }
  696. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  697. // detail, otherwise only the transaction hash is returned.
  698. func (s *BlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
  699. block, err := s.b.BlockByHash(ctx, hash)
  700. if block != nil {
  701. return s.rpcMarshalBlock(ctx, block, true, fullTx)
  702. }
  703. return nil, err
  704. }
  705. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index.
  706. func (s *BlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
  707. block, err := s.b.BlockByNumber(ctx, blockNr)
  708. if block != nil {
  709. uncles := block.Uncles()
  710. if index >= hexutil.Uint(len(uncles)) {
  711. log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
  712. return nil, nil
  713. }
  714. block = types.NewBlockWithHeader(uncles[index])
  715. return s.rpcMarshalBlock(ctx, block, false, false)
  716. }
  717. return nil, err
  718. }
  719. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index.
  720. func (s *BlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
  721. block, err := s.b.BlockByHash(ctx, blockHash)
  722. if block != nil {
  723. uncles := block.Uncles()
  724. if index >= hexutil.Uint(len(uncles)) {
  725. log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
  726. return nil, nil
  727. }
  728. block = types.NewBlockWithHeader(uncles[index])
  729. return s.rpcMarshalBlock(ctx, block, false, false)
  730. }
  731. return nil, err
  732. }
  733. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  734. func (s *BlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  735. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  736. n := hexutil.Uint(len(block.Uncles()))
  737. return &n
  738. }
  739. return nil
  740. }
  741. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  742. func (s *BlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  743. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  744. n := hexutil.Uint(len(block.Uncles()))
  745. return &n
  746. }
  747. return nil
  748. }
  749. // GetCode returns the code stored at the given address in the state for the given block number.
  750. func (s *BlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  751. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  752. if state == nil || err != nil {
  753. return nil, err
  754. }
  755. code := state.GetCode(address)
  756. return code, state.Error()
  757. }
  758. // GetStorageAt returns the storage from the state at the given address, key and
  759. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  760. // numbers are also allowed.
  761. func (s *BlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  762. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  763. if state == nil || err != nil {
  764. return nil, err
  765. }
  766. res := state.GetState(address, common.HexToHash(key))
  767. return res[:], state.Error()
  768. }
  769. // OverrideAccount indicates the overriding fields of account during the execution
  770. // of a message call.
  771. // Note, state and stateDiff can't be specified at the same time. If state is
  772. // set, message execution will only use the data in the given state. Otherwise
  773. // if statDiff is set, all diff will be applied first and then execute the call
  774. // message.
  775. type OverrideAccount struct {
  776. Nonce *hexutil.Uint64 `json:"nonce"`
  777. Code *hexutil.Bytes `json:"code"`
  778. Balance **hexutil.Big `json:"balance"`
  779. State *map[common.Hash]common.Hash `json:"state"`
  780. StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
  781. }
  782. // StateOverride is the collection of overridden accounts.
  783. type StateOverride map[common.Address]OverrideAccount
  784. // Apply overrides the fields of specified accounts into the given state.
  785. func (diff *StateOverride) Apply(state *state.StateDB) error {
  786. if diff == nil {
  787. return nil
  788. }
  789. for addr, account := range *diff {
  790. // Override account nonce.
  791. if account.Nonce != nil {
  792. state.SetNonce(addr, uint64(*account.Nonce))
  793. }
  794. // Override account(contract) code.
  795. if account.Code != nil {
  796. state.SetCode(addr, *account.Code)
  797. }
  798. // Override account balance.
  799. if account.Balance != nil {
  800. state.SetBalance(addr, (*big.Int)(*account.Balance))
  801. }
  802. if account.State != nil && account.StateDiff != nil {
  803. return fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
  804. }
  805. // Replace entire state if caller requires.
  806. if account.State != nil {
  807. state.SetStorage(addr, *account.State)
  808. }
  809. // Apply state diff into specified accounts.
  810. if account.StateDiff != nil {
  811. for key, value := range *account.StateDiff {
  812. state.SetState(addr, key, value)
  813. }
  814. }
  815. }
  816. return nil
  817. }
  818. // BlockOverrides is a set of header fields to override.
  819. type BlockOverrides struct {
  820. Number *hexutil.Big
  821. Difficulty *hexutil.Big
  822. Time *hexutil.Big
  823. GasLimit *hexutil.Uint64
  824. Coinbase *common.Address
  825. Random *common.Hash
  826. BaseFee *hexutil.Big
  827. }
  828. // Apply overrides the given header fields into the given block context.
  829. func (diff *BlockOverrides) Apply(blockCtx *vm.BlockContext) {
  830. if diff == nil {
  831. return
  832. }
  833. if diff.Number != nil {
  834. blockCtx.BlockNumber = diff.Number.ToInt()
  835. }
  836. if diff.Difficulty != nil {
  837. blockCtx.Difficulty = diff.Difficulty.ToInt()
  838. }
  839. if diff.Time != nil {
  840. blockCtx.Time = diff.Time.ToInt()
  841. }
  842. if diff.GasLimit != nil {
  843. blockCtx.GasLimit = uint64(*diff.GasLimit)
  844. }
  845. if diff.Coinbase != nil {
  846. blockCtx.Coinbase = *diff.Coinbase
  847. }
  848. if diff.Random != nil {
  849. blockCtx.Random = diff.Random
  850. }
  851. if diff.BaseFee != nil {
  852. blockCtx.BaseFee = diff.BaseFee.ToInt()
  853. }
  854. }
  855. type ChainContextBackend interface {
  856. Engine() consensus.Engine
  857. HeaderByNumber(context.Context, rpc.BlockNumber) (*types.Header, error)
  858. }
  859. // ChainContext is an implementation of core.ChainContext. It's main use-case
  860. // is instantiating a vm.BlockContext without having access to the BlockChain object.
  861. type ChainContext struct {
  862. b ChainContextBackend
  863. ctx context.Context
  864. }
  865. // NewChainContext creates a new ChainContext object.
  866. func NewChainContext(ctx context.Context, backend ChainContextBackend) *ChainContext {
  867. return &ChainContext{ctx: ctx, b: backend}
  868. }
  869. func (context *ChainContext) Engine() consensus.Engine {
  870. return context.b.Engine()
  871. }
  872. func (context *ChainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
  873. // This method is called to get the hash for a block number when executing the BLOCKHASH
  874. // opcode. Hence no need to search for non-canonical blocks.
  875. header, err := context.b.HeaderByNumber(context.ctx, rpc.BlockNumber(number))
  876. if err != nil || header.Hash() != hash {
  877. return nil
  878. }
  879. return header
  880. }
  881. func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
  882. defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  883. state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  884. if state == nil || err != nil {
  885. return nil, err
  886. }
  887. if err := overrides.Apply(state); err != nil {
  888. return nil, err
  889. }
  890. // Setup context so it may be cancelled the call has completed
  891. // or, in case of unmetered gas, setup a context with a timeout.
  892. var cancel context.CancelFunc
  893. if timeout > 0 {
  894. ctx, cancel = context.WithTimeout(ctx, timeout)
  895. } else {
  896. ctx, cancel = context.WithCancel(ctx)
  897. }
  898. // Make sure the context is cancelled when the call has completed
  899. // this makes sure resources are cleaned up.
  900. defer cancel()
  901. return doCall(ctx, b, args, state, header, timeout, new(core.GasPool).AddGas(globalGasCap), nil)
  902. }
  903. func doCall(ctx context.Context, b Backend, args TransactionArgs, state *state.StateDB, header *types.Header, timeout time.Duration, gp *core.GasPool, blockContext *vm.BlockContext) (*core.ExecutionResult, error) {
  904. // Get a new instance of the EVM.
  905. msg, err := args.ToMessage(gp.Gas(), header.BaseFee)
  906. if err != nil {
  907. return nil, err
  908. }
  909. evm, vmError, err := b.GetEVM(ctx, msg, state, header, &vm.Config{NoBaseFee: true}, blockContext)
  910. if err != nil {
  911. return nil, err
  912. }
  913. // Wait for the context to be done and cancel the evm. Even if the
  914. // EVM has finished, cancelling may be done (repeatedly)
  915. go func() {
  916. <-ctx.Done()
  917. evm.Cancel()
  918. }()
  919. // Execute the message.
  920. result, err := core.ApplyMessage(evm, msg, gp)
  921. if err := vmError(); err != nil {
  922. return nil, err
  923. }
  924. // If the timer caused an abort, return an appropriate error message
  925. if evm.Cancelled() {
  926. return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
  927. }
  928. if err != nil {
  929. return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas())
  930. }
  931. return result, nil
  932. }
  933. // BatchCallConfig is the config object to be passed to eth_batchCall.
  934. type BatchCallConfig struct {
  935. Block rpc.BlockNumberOrHash
  936. StateOverrides *StateOverride
  937. Calls []BatchCallArgs
  938. }
  939. // BatchCallArgs is the object specifying each call within eth_batchCall. It
  940. // extends TransactionArgs with the list of block metadata overrides.
  941. type BatchCallArgs struct {
  942. TransactionArgs
  943. BlockOverrides *BlockOverrides
  944. }
  945. // CallResult is the result of one call.
  946. type CallResult struct {
  947. Return hexutil.Bytes
  948. Error error
  949. }
  950. // BatchCall executes a series of transactions on the state of a given block as base.
  951. // The base state can be overridden once before transactions are executed.
  952. //
  953. // Additionally, each call can override block context fields such as number.
  954. //
  955. // Note, this function doesn't make any changes in the state/blockchain and is
  956. // useful to execute and retrieve values.
  957. func (s *BlockChainAPI) BatchCall(ctx context.Context, config BatchCallConfig) ([]CallResult, error) {
  958. state, header, err := s.b.StateAndHeaderByNumberOrHash(ctx, config.Block)
  959. if state == nil || err != nil {
  960. return nil, err
  961. }
  962. // State overrides are applied once before all calls
  963. if err := config.StateOverrides.Apply(state); err != nil {
  964. return nil, err
  965. }
  966. // Setup context so it may be cancelled before the calls completed
  967. // or, in case of unmetered gas, setup a context with a timeout.
  968. var (
  969. cancel context.CancelFunc
  970. timeout = s.b.RPCEVMTimeout()
  971. )
  972. if timeout > 0 {
  973. ctx, cancel = context.WithTimeout(ctx, timeout)
  974. } else {
  975. ctx, cancel = context.WithCancel(ctx)
  976. }
  977. // Make sure the context is cancelled when the call has completed
  978. // this makes sure resources are cleaned up.
  979. defer cancel()
  980. var (
  981. results []CallResult
  982. // Each tx and all the series of txes shouldn't consume more gas than cap
  983. globalGasCap = s.b.RPCGasCap()
  984. gp = new(core.GasPool).AddGas(globalGasCap)
  985. )
  986. for _, call := range config.Calls {
  987. blockContext := core.NewEVMBlockContext(header, NewChainContext(ctx, s.b), nil)
  988. if call.BlockOverrides != nil {
  989. call.BlockOverrides.Apply(&blockContext)
  990. }
  991. result, err := doCall(ctx, s.b, call.TransactionArgs, state, header, timeout, gp, &blockContext)
  992. if err != nil {
  993. return nil, err
  994. }
  995. // If the result contains a revert reason, try to unpack it.
  996. if len(result.Revert()) > 0 {
  997. result.Err = newRevertError(result)
  998. }
  999. results = append(results, CallResult{Return: result.Return(), Error: result.Err})
  1000. }
  1001. return results, nil
  1002. }
  1003. func newRevertError(result *core.ExecutionResult) *revertError {
  1004. reason, errUnpack := abi.UnpackRevert(result.Revert())
  1005. err := errors.New("execution reverted")
  1006. if errUnpack == nil {
  1007. err = fmt.Errorf("execution reverted: %v", reason)
  1008. }
  1009. return &revertError{
  1010. error: err,
  1011. reason: hexutil.Encode(result.Revert()),
  1012. }
  1013. }
  1014. // revertError is an API error that encompasses an EVM revertal with JSON error
  1015. // code and a binary data blob.
  1016. type revertError struct {
  1017. error
  1018. reason string // revert reason hex encoded
  1019. }
  1020. // ErrorCode returns the JSON error code for a revertal.
  1021. // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
  1022. func (e *revertError) ErrorCode() int {
  1023. return 3
  1024. }
  1025. // ErrorData returns the hex encoded revert reason.
  1026. func (e *revertError) ErrorData() interface{} {
  1027. return e.reason
  1028. }
  1029. // Call executes the given transaction on the state for the given block number.
  1030. //
  1031. // Additionally, the caller can specify a batch of contract for fields overriding.
  1032. //
  1033. // Note, this function doesn't make and changes in the state/blockchain and is
  1034. // useful to execute and retrieve values.
  1035. func (s *BlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Bytes, error) {
  1036. result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, s.b.RPCEVMTimeout(), s.b.RPCGasCap())
  1037. if err != nil {
  1038. return nil, err
  1039. }
  1040. // If the result contains a revert reason, try to unpack and return it.
  1041. if len(result.Revert()) > 0 {
  1042. return nil, newRevertError(result)
  1043. }
  1044. return result.Return(), result.Err
  1045. }
  1046. func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) {
  1047. // Binary search the gas requirement, as it may be higher than the amount used
  1048. var (
  1049. lo uint64 = params.TxGas - 1
  1050. hi uint64
  1051. cap uint64
  1052. )
  1053. // Use zero address if sender unspecified.
  1054. if args.From == nil {
  1055. args.From = new(common.Address)
  1056. }
  1057. // Determine the highest gas limit can be used during the estimation.
  1058. if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  1059. hi = uint64(*args.Gas)
  1060. } else {
  1061. // Retrieve the block to act as the gas ceiling
  1062. block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
  1063. if err != nil {
  1064. return 0, err
  1065. }
  1066. if block == nil {
  1067. return 0, errors.New("block not found")
  1068. }
  1069. hi = block.GasLimit()
  1070. }
  1071. // Normalize the max fee per gas the call is willing to spend.
  1072. var feeCap *big.Int
  1073. if args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) {
  1074. return 0, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
  1075. } else if args.GasPrice != nil {
  1076. feeCap = args.GasPrice.ToInt()
  1077. } else if args.MaxFeePerGas != nil {
  1078. feeCap = args.MaxFeePerGas.ToInt()
  1079. } else {
  1080. feeCap = common.Big0
  1081. }
  1082. // Recap the highest gas limit with account's available balance.
  1083. if feeCap.BitLen() != 0 {
  1084. state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1085. if err != nil {
  1086. return 0, err
  1087. }
  1088. balance := state.GetBalance(*args.From) // from can't be nil
  1089. available := new(big.Int).Set(balance)
  1090. if args.Value != nil {
  1091. if args.Value.ToInt().Cmp(available) >= 0 {
  1092. return 0, errors.New("insufficient funds for transfer")
  1093. }
  1094. available.Sub(available, args.Value.ToInt())
  1095. }
  1096. allowance := new(big.Int).Div(available, feeCap)
  1097. // If the allowance is larger than maximum uint64, skip checking
  1098. if allowance.IsUint64() && hi > allowance.Uint64() {
  1099. transfer := args.Value
  1100. if transfer == nil {
  1101. transfer = new(hexutil.Big)
  1102. }
  1103. log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
  1104. "sent", transfer.ToInt(), "maxFeePerGas", feeCap, "fundable", allowance)
  1105. hi = allowance.Uint64()
  1106. }
  1107. }
  1108. // Recap the highest gas allowance with specified gascap.
  1109. if gasCap != 0 && hi > gasCap {
  1110. log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  1111. hi = gasCap
  1112. }
  1113. cap = hi
  1114. // Create a helper to check if a gas allowance results in an executable transaction
  1115. executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
  1116. args.Gas = (*hexutil.Uint64)(&gas)
  1117. result, err := DoCall(ctx, b, args, blockNrOrHash, nil, 0, gasCap)
  1118. if err != nil {
  1119. if errors.Is(err, core.ErrIntrinsicGas) {
  1120. return true, nil, nil // Special case, raise gas limit
  1121. }
  1122. return true, nil, err // Bail out
  1123. }
  1124. return result.Failed(), result, nil
  1125. }
  1126. // Execute the binary search and hone in on an executable gas limit
  1127. for lo+1 < hi {
  1128. mid := (hi + lo) / 2
  1129. failed, _, err := executable(mid)
  1130. // If the error is not nil(consensus error), it means the provided message
  1131. // call or transaction will never be accepted no matter how much gas it is
  1132. // assigned. Return the error directly, don't struggle any more.
  1133. if err != nil {
  1134. return 0, err
  1135. }
  1136. if failed {
  1137. lo = mid
  1138. } else {
  1139. hi = mid
  1140. }
  1141. }
  1142. // Reject the transaction as invalid if it still fails at the highest allowance
  1143. if hi == cap {
  1144. failed, result, err := executable(hi)
  1145. if err != nil {
  1146. return 0, err
  1147. }
  1148. if failed {
  1149. if result != nil && result.Err != vm.ErrOutOfGas {
  1150. if len(result.Revert()) > 0 {
  1151. return 0, newRevertError(result)
  1152. }
  1153. return 0, result.Err
  1154. }
  1155. // Otherwise, the specified gas cap is too low
  1156. return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
  1157. }
  1158. }
  1159. return hexutil.Uint64(hi), nil
  1160. }
  1161. // EstimateGas returns an estimate of the amount of gas needed to execute the
  1162. // given transaction against the current pending block.
  1163. func (s *BlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
  1164. bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1165. if blockNrOrHash != nil {
  1166. bNrOrHash = *blockNrOrHash
  1167. }
  1168. return DoEstimateGas(ctx, s.b, args, bNrOrHash, s.b.RPCGasCap())
  1169. }
  1170. // RPCMarshalHeader converts the given header to the RPC output .
  1171. func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  1172. result := map[string]interface{}{
  1173. "number": (*hexutil.Big)(head.Number),
  1174. "hash": head.Hash(),
  1175. "parentHash": head.ParentHash,
  1176. "nonce": head.Nonce,
  1177. "mixHash": head.MixDigest,
  1178. "sha3Uncles": head.UncleHash,
  1179. "logsBloom": head.Bloom,
  1180. "stateRoot": head.Root,
  1181. "miner": head.Coinbase,
  1182. "difficulty": (*hexutil.Big)(head.Difficulty),
  1183. "extraData": hexutil.Bytes(head.Extra),
  1184. "size": hexutil.Uint64(head.Size()),
  1185. "gasLimit": hexutil.Uint64(head.GasLimit),
  1186. "gasUsed": hexutil.Uint64(head.GasUsed),
  1187. "timestamp": hexutil.Uint64(head.Time),
  1188. "transactionsRoot": head.TxHash,
  1189. "receiptsRoot": head.ReceiptHash,
  1190. }
  1191. if head.BaseFee != nil {
  1192. result["baseFeePerGas"] = (*hexutil.Big)(head.BaseFee)
  1193. }
  1194. return result
  1195. }
  1196. // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1197. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1198. // transaction hashes.
  1199. func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *params.ChainConfig) (map[string]interface{}, error) {
  1200. fields := RPCMarshalHeader(block.Header())
  1201. fields["size"] = hexutil.Uint64(block.Size())
  1202. if inclTx {
  1203. formatTx := func(tx *types.Transaction) (interface{}, error) {
  1204. return tx.Hash(), nil
  1205. }
  1206. if fullTx {
  1207. formatTx = func(tx *types.Transaction) (interface{}, error) {
  1208. return newRPCTransactionFromBlockHash(block, tx.Hash(), config), nil
  1209. }
  1210. }
  1211. txs := block.Transactions()
  1212. transactions := make([]interface{}, len(txs))
  1213. var err error
  1214. for i, tx := range txs {
  1215. if transactions[i], err = formatTx(tx); err != nil {
  1216. return nil, err
  1217. }
  1218. }
  1219. fields["transactions"] = transactions
  1220. }
  1221. uncles := block.Uncles()
  1222. uncleHashes := make([]common.Hash, len(uncles))
  1223. for i, uncle := range uncles {
  1224. uncleHashes[i] = uncle.Hash()
  1225. }
  1226. fields["uncles"] = uncleHashes
  1227. return fields, nil
  1228. }
  1229. // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1230. // a `BlockchainAPI`.
  1231. func (s *BlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} {
  1232. fields := RPCMarshalHeader(header)
  1233. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash()))
  1234. return fields
  1235. }
  1236. // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1237. // a `BlockchainAPI`.
  1238. func (s *BlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1239. fields, err := RPCMarshalBlock(b, inclTx, fullTx, s.b.ChainConfig())
  1240. if err != nil {
  1241. return nil, err
  1242. }
  1243. if inclTx {
  1244. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, b.Hash()))
  1245. }
  1246. return fields, err
  1247. }
  1248. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1249. type RPCTransaction struct {
  1250. BlockHash *common.Hash `json:"blockHash"`
  1251. BlockNumber *hexutil.Big `json:"blockNumber"`
  1252. From common.Address `json:"from"`
  1253. Gas hexutil.Uint64 `json:"gas"`
  1254. GasPrice *hexutil.Big `json:"gasPrice"`
  1255. GasFeeCap *hexutil.Big `json:"maxFeePerGas,omitempty"`
  1256. GasTipCap *hexutil.Big `json:"maxPriorityFeePerGas,omitempty"`
  1257. Hash common.Hash `json:"hash"`
  1258. Input hexutil.Bytes `json:"input"`
  1259. Nonce hexutil.Uint64 `json:"nonce"`
  1260. To *common.Address `json:"to"`
  1261. TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
  1262. Value *hexutil.Big `json:"value"`
  1263. Type hexutil.Uint64 `json:"type"`
  1264. Accesses *types.AccessList `json:"accessList,omitempty"`
  1265. ChainID *hexutil.Big `json:"chainId,omitempty"`
  1266. V *hexutil.Big `json:"v"`
  1267. R *hexutil.Big `json:"r"`
  1268. S *hexutil.Big `json:"s"`
  1269. }
  1270. // newRPCTransaction returns a transaction that will serialize to the RPC
  1271. // representation, with the given location metadata set (if available).
  1272. func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64, baseFee *big.Int, config *params.ChainConfig) *RPCTransaction {
  1273. signer := types.MakeSigner(config, new(big.Int).SetUint64(blockNumber))
  1274. from, _ := types.Sender(signer, tx)
  1275. v, r, s := tx.RawSignatureValues()
  1276. result := &RPCTransaction{
  1277. Type: hexutil.Uint64(tx.Type()),
  1278. From: from,
  1279. Gas: hexutil.Uint64(tx.Gas()),
  1280. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1281. Hash: tx.Hash(),
  1282. Input: hexutil.Bytes(tx.Data()),
  1283. Nonce: hexutil.Uint64(tx.Nonce()),
  1284. To: tx.To(),
  1285. Value: (*hexutil.Big)(tx.Value()),
  1286. V: (*hexutil.Big)(v),
  1287. R: (*hexutil.Big)(r),
  1288. S: (*hexutil.Big)(s),
  1289. }
  1290. if blockHash != (common.Hash{}) {
  1291. result.BlockHash = &blockHash
  1292. result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1293. result.TransactionIndex = (*hexutil.Uint64)(&index)
  1294. }
  1295. switch tx.Type() {
  1296. case types.LegacyTxType:
  1297. // if a legacy transaction has an EIP-155 chain id, include it explicitly
  1298. if id := tx.ChainId(); id.Sign() != 0 {
  1299. result.ChainID = (*hexutil.Big)(id)
  1300. }
  1301. case types.AccessListTxType:
  1302. al := tx.AccessList()
  1303. result.Accesses = &al
  1304. result.ChainID = (*hexutil.Big)(tx.ChainId())
  1305. case types.DynamicFeeTxType:
  1306. al := tx.AccessList()
  1307. result.Accesses = &al
  1308. result.ChainID = (*hexutil.Big)(tx.ChainId())
  1309. result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
  1310. result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
  1311. // if the transaction has been mined, compute the effective gas price
  1312. if baseFee != nil && blockHash != (common.Hash{}) {
  1313. // price = min(tip, gasFeeCap - baseFee) + baseFee
  1314. price := math.BigMin(new(big.Int).Add(tx.GasTipCap(), baseFee), tx.GasFeeCap())
  1315. result.GasPrice = (*hexutil.Big)(price)
  1316. } else {
  1317. result.GasPrice = (*hexutil.Big)(tx.GasFeeCap())
  1318. }
  1319. }
  1320. return result
  1321. }
  1322. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1323. func newRPCPendingTransaction(tx *types.Transaction, current *types.Header, config *params.ChainConfig) *RPCTransaction {
  1324. var baseFee *big.Int
  1325. blockNumber := uint64(0)
  1326. if current != nil {
  1327. baseFee = misc.CalcBaseFee(config, current)
  1328. blockNumber = current.Number.Uint64()
  1329. }
  1330. return newRPCTransaction(tx, common.Hash{}, blockNumber, 0, baseFee, config)
  1331. }
  1332. // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1333. func newRPCTransactionFromBlockIndex(b *types.Block, index uint64, config *params.ChainConfig) *RPCTransaction {
  1334. txs := b.Transactions()
  1335. if index >= uint64(len(txs)) {
  1336. return nil
  1337. }
  1338. return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index, b.BaseFee(), config)
  1339. }
  1340. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1341. func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1342. txs := b.Transactions()
  1343. if index >= uint64(len(txs)) {
  1344. return nil
  1345. }
  1346. blob, _ := txs[index].MarshalBinary()
  1347. return blob
  1348. }
  1349. // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1350. func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash, config *params.ChainConfig) *RPCTransaction {
  1351. for idx, tx := range b.Transactions() {
  1352. if tx.Hash() == hash {
  1353. return newRPCTransactionFromBlockIndex(b, uint64(idx), config)
  1354. }
  1355. }
  1356. return nil
  1357. }
  1358. // accessListResult returns an optional accesslist
  1359. // Its the result of the `debug_createAccessList` RPC call.
  1360. // It contains an error if the transaction itself failed.
  1361. type accessListResult struct {
  1362. Accesslist *types.AccessList `json:"accessList"`
  1363. Error string `json:"error,omitempty"`
  1364. GasUsed hexutil.Uint64 `json:"gasUsed"`
  1365. }
  1366. // CreateAccessList creates a EIP-2930 type AccessList for the given transaction.
  1367. // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
  1368. func (s *BlockChainAPI) CreateAccessList(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) {
  1369. bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1370. if blockNrOrHash != nil {
  1371. bNrOrHash = *blockNrOrHash
  1372. }
  1373. acl, gasUsed, vmerr, err := AccessList(ctx, s.b, bNrOrHash, args)
  1374. if err != nil {
  1375. return nil, err
  1376. }
  1377. result := &accessListResult{Accesslist: &acl, GasUsed: hexutil.Uint64(gasUsed)}
  1378. if vmerr != nil {
  1379. result.Error = vmerr.Error()
  1380. }
  1381. return result, nil
  1382. }
  1383. // AccessList creates an access list for the given transaction.
  1384. // If the accesslist creation fails an error is returned.
  1385. // If the transaction itself fails, an vmErr is returned.
  1386. func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrHash, args TransactionArgs) (acl types.AccessList, gasUsed uint64, vmErr error, err error) {
  1387. // Retrieve the execution context
  1388. db, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1389. if db == nil || err != nil {
  1390. return nil, 0, nil, err
  1391. }
  1392. // If the gas amount is not set, default to RPC gas cap.
  1393. if args.Gas == nil {
  1394. tmp := hexutil.Uint64(b.RPCGasCap())
  1395. args.Gas = &tmp
  1396. }
  1397. // Ensure any missing fields are filled, extract the recipient and input data
  1398. if err := args.setDefaults(ctx, b); err != nil {
  1399. return nil, 0, nil, err
  1400. }
  1401. var to common.Address
  1402. if args.To != nil {
  1403. to = *args.To
  1404. } else {
  1405. to = crypto.CreateAddress(args.from(), uint64(*args.Nonce))
  1406. }
  1407. isPostMerge := header.Difficulty.Cmp(common.Big0) == 0
  1408. // Retrieve the precompiles since they don't need to be added to the access list
  1409. precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number, isPostMerge))
  1410. // Create an initial tracer
  1411. prevTracer := logger.NewAccessListTracer(nil, args.from(), to, precompiles)
  1412. if args.AccessList != nil {
  1413. prevTracer = logger.NewAccessListTracer(*args.AccessList, args.from(), to, precompiles)
  1414. }
  1415. for {
  1416. // Retrieve the current access list to expand
  1417. accessList := prevTracer.AccessList()
  1418. log.Trace("Creating access list", "input", accessList)
  1419. // Copy the original db so we don't modify it
  1420. statedb := db.Copy()
  1421. // Set the accesslist to the last al
  1422. args.AccessList = &accessList
  1423. msg, err := args.ToMessage(b.RPCGasCap(), header.BaseFee)
  1424. if err != nil {
  1425. return nil, 0, nil, err
  1426. }
  1427. // Apply the transaction with the access list tracer
  1428. tracer := logger.NewAccessListTracer(accessList, args.from(), to, precompiles)
  1429. config := vm.Config{Tracer: tracer, Debug: true, NoBaseFee: true}
  1430. vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config, nil)
  1431. if err != nil {
  1432. return nil, 0, nil, err
  1433. }
  1434. res, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
  1435. if err != nil {
  1436. return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err)
  1437. }
  1438. if tracer.Equal(prevTracer) {
  1439. return accessList, res.UsedGas, res.Err, nil
  1440. }
  1441. prevTracer = tracer
  1442. }
  1443. }
  1444. // TransactionAPI exposes methods for reading and creating transaction data.
  1445. type TransactionAPI struct {
  1446. b Backend
  1447. nonceLock *AddrLocker
  1448. signer types.Signer
  1449. }
  1450. // NewTransactionAPI creates a new RPC service with methods for interacting with transactions.
  1451. func NewTransactionAPI(b Backend, nonceLock *AddrLocker) *TransactionAPI {
  1452. // The signer used by the API should always be the 'latest' known one because we expect
  1453. // signers to be backwards-compatible with old transactions.
  1454. signer := types.LatestSigner(b.ChainConfig())
  1455. return &TransactionAPI{b, nonceLock, signer}
  1456. }
  1457. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1458. func (s *TransactionAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1459. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1460. n := hexutil.Uint(len(block.Transactions()))
  1461. return &n
  1462. }
  1463. return nil
  1464. }
  1465. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1466. func (s *TransactionAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1467. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1468. n := hexutil.Uint(len(block.Transactions()))
  1469. return &n
  1470. }
  1471. return nil
  1472. }
  1473. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1474. func (s *TransactionAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1475. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1476. return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig())
  1477. }
  1478. return nil
  1479. }
  1480. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1481. func (s *TransactionAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1482. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1483. return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig())
  1484. }
  1485. return nil
  1486. }
  1487. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1488. func (s *TransactionAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1489. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1490. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1491. }
  1492. return nil
  1493. }
  1494. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1495. func (s *TransactionAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1496. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1497. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1498. }
  1499. return nil
  1500. }
  1501. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1502. func (s *TransactionAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1503. // Ask transaction pool for the nonce which includes pending transactions
  1504. if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1505. nonce, err := s.b.GetPoolNonce(ctx, address)
  1506. if err != nil {
  1507. return nil, err
  1508. }
  1509. return (*hexutil.Uint64)(&nonce), nil
  1510. }
  1511. // Resolve block number and use its state to ask for the nonce
  1512. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1513. if state == nil || err != nil {
  1514. return nil, err
  1515. }
  1516. nonce := state.GetNonce(address)
  1517. return (*hexutil.Uint64)(&nonce), state.Error()
  1518. }
  1519. // GetTransactionByHash returns the transaction for the given hash
  1520. func (s *TransactionAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1521. // Try to return an already finalized transaction
  1522. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1523. if err != nil {
  1524. return nil, err
  1525. }
  1526. if tx != nil {
  1527. header, err := s.b.HeaderByHash(ctx, blockHash)
  1528. if err != nil {
  1529. return nil, err
  1530. }
  1531. return newRPCTransaction(tx, blockHash, blockNumber, index, header.BaseFee, s.b.ChainConfig()), nil
  1532. }
  1533. // No finalized transaction, try to retrieve it from the pool
  1534. if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1535. return newRPCPendingTransaction(tx, s.b.CurrentHeader(), s.b.ChainConfig()), nil
  1536. }
  1537. // Transaction unknown, return as such
  1538. return nil, nil
  1539. }
  1540. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1541. func (s *TransactionAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1542. // Retrieve a finalized transaction, or a pooled otherwise
  1543. tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1544. if err != nil {
  1545. return nil, err
  1546. }
  1547. if tx == nil {
  1548. if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1549. // Transaction not found anywhere, abort
  1550. return nil, nil
  1551. }
  1552. }
  1553. // Serialize to RLP and return
  1554. return tx.MarshalBinary()
  1555. }
  1556. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1557. func (s *TransactionAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1558. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1559. if err != nil {
  1560. // When the transaction doesn't exist, the RPC method should return JSON null
  1561. // as per specification.
  1562. return nil, nil
  1563. }
  1564. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1565. if err != nil {
  1566. return nil, err
  1567. }
  1568. if len(receipts) <= int(index) {
  1569. return nil, nil
  1570. }
  1571. receipt := receipts[index]
  1572. // Derive the sender.
  1573. bigblock := new(big.Int).SetUint64(blockNumber)
  1574. signer := types.MakeSigner(s.b.ChainConfig(), bigblock)
  1575. from, _ := types.Sender(signer, tx)
  1576. fields := map[string]interface{}{
  1577. "blockHash": blockHash,
  1578. "blockNumber": hexutil.Uint64(blockNumber),
  1579. "transactionHash": hash,
  1580. "transactionIndex": hexutil.Uint64(index),
  1581. "from": from,
  1582. "to": tx.To(),
  1583. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1584. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1585. "contractAddress": nil,
  1586. "logs": receipt.Logs,
  1587. "logsBloom": receipt.Bloom,
  1588. "type": hexutil.Uint(tx.Type()),
  1589. }
  1590. // Assign the effective gas price paid
  1591. if !s.b.ChainConfig().IsLondon(bigblock) {
  1592. fields["effectiveGasPrice"] = hexutil.Uint64(tx.GasPrice().Uint64())
  1593. } else {
  1594. header, err := s.b.HeaderByHash(ctx, blockHash)
  1595. if err != nil {
  1596. return nil, err
  1597. }
  1598. gasPrice := new(big.Int).Add(header.BaseFee, tx.EffectiveGasTipValue(header.BaseFee))
  1599. fields["effectiveGasPrice"] = hexutil.Uint64(gasPrice.Uint64())
  1600. }
  1601. // Assign receipt status or post state.
  1602. if len(receipt.PostState) > 0 {
  1603. fields["root"] = hexutil.Bytes(receipt.PostState)
  1604. } else {
  1605. fields["status"] = hexutil.Uint(receipt.Status)
  1606. }
  1607. if receipt.Logs == nil {
  1608. fields["logs"] = []*types.Log{}
  1609. }
  1610. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1611. if receipt.ContractAddress != (common.Address{}) {
  1612. fields["contractAddress"] = receipt.ContractAddress
  1613. }
  1614. return fields, nil
  1615. }
  1616. // sign is a helper function that signs a transaction with the private key of the given address.
  1617. func (s *TransactionAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1618. // Look up the wallet containing the requested signer
  1619. account := accounts.Account{Address: addr}
  1620. wallet, err := s.b.AccountManager().Find(account)
  1621. if err != nil {
  1622. return nil, err
  1623. }
  1624. // Request the wallet to sign the transaction
  1625. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber)
  1626. chainId := s.b.ChainConfig().ChainID
  1627. if header != nil && s.b.ChainConfig().IsEthPoWFork(header.Number) {
  1628. chainId = s.b.ChainConfig().ChainID_ALT
  1629. }
  1630. return wallet.SignTx(account, tx, chainId)
  1631. }
  1632. // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1633. func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1634. // If the transaction fee cap is already specified, ensure the
  1635. // fee of the given transaction is _reasonable_.
  1636. if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil {
  1637. return common.Hash{}, err
  1638. }
  1639. if !b.UnprotectedAllowed() && !tx.Protected() {
  1640. // Ensure only eip155 signed transactions are submitted if EIP155Required is set.
  1641. return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed over RPC")
  1642. }
  1643. // check eip155 sign after EthPow block
  1644. if b.ChainConfig().IsEthPoWFork(b.CurrentBlock().Number()) && !tx.Protected() {
  1645. return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed")
  1646. }
  1647. if err := b.SendTx(ctx, tx); err != nil {
  1648. return common.Hash{}, err
  1649. }
  1650. // Print a log with full tx details for manual investigations and interventions
  1651. signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1652. from, err := types.Sender(signer, tx)
  1653. if err != nil {
  1654. return common.Hash{}, err
  1655. }
  1656. if tx.To() == nil {
  1657. addr := crypto.CreateAddress(from, tx.Nonce())
  1658. log.Info("Submitted contract creation", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "contract", addr.Hex(), "value", tx.Value())
  1659. } else {
  1660. log.Info("Submitted transaction", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "recipient", tx.To(), "value", tx.Value())
  1661. }
  1662. return tx.Hash(), nil
  1663. }
  1664. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1665. // transaction pool.
  1666. func (s *TransactionAPI) SendTransaction(ctx context.Context, args TransactionArgs) (common.Hash, error) {
  1667. // Look up the wallet containing the requested signer
  1668. account := accounts.Account{Address: args.from()}
  1669. wallet, err := s.b.AccountManager().Find(account)
  1670. if err != nil {
  1671. return common.Hash{}, err
  1672. }
  1673. if args.Nonce == nil {
  1674. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  1675. // the same nonce to multiple accounts.
  1676. s.nonceLock.LockAddr(args.from())
  1677. defer s.nonceLock.UnlockAddr(args.from())
  1678. }
  1679. // Set some sanity defaults and terminate on failure
  1680. if err := args.setDefaults(ctx, s.b); err != nil {
  1681. return common.Hash{}, err
  1682. }
  1683. // Assemble the transaction and sign with the wallet
  1684. tx := args.toTransaction()
  1685. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber)
  1686. chainId := s.b.ChainConfig().ChainID
  1687. if header != nil && s.b.ChainConfig().IsEthPoWFork(header.Number) {
  1688. chainId = s.b.ChainConfig().ChainID_ALT
  1689. }
  1690. signed, err := wallet.SignTx(account, tx, chainId)
  1691. if err != nil {
  1692. return common.Hash{}, err
  1693. }
  1694. return SubmitTransaction(ctx, s.b, signed)
  1695. }
  1696. // FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields)
  1697. // on a given unsigned transaction, and returns it to the caller for further
  1698. // processing (signing + broadcast).
  1699. func (s *TransactionAPI) FillTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
  1700. // Set some sanity defaults and terminate on failure
  1701. if err := args.setDefaults(ctx, s.b); err != nil {
  1702. return nil, err
  1703. }
  1704. // Assemble the transaction and obtain rlp
  1705. tx := args.toTransaction()
  1706. data, err := tx.MarshalBinary()
  1707. if err != nil {
  1708. return nil, err
  1709. }
  1710. return &SignTransactionResult{data, tx}, nil
  1711. }
  1712. // SendRawTransaction will add the signed transaction to the transaction pool.
  1713. // The sender is responsible for signing the transaction and using the correct nonce.
  1714. func (s *TransactionAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) {
  1715. tx := new(types.Transaction)
  1716. if err := tx.UnmarshalBinary(input); err != nil {
  1717. return common.Hash{}, err
  1718. }
  1719. return SubmitTransaction(ctx, s.b, tx)
  1720. }
  1721. // Sign calculates an ECDSA signature for:
  1722. // keccak256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1723. //
  1724. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1725. // where the V value will be 27 or 28 for legacy reasons.
  1726. //
  1727. // The account associated with addr must be unlocked.
  1728. //
  1729. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1730. func (s *TransactionAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1731. // Look up the wallet containing the requested signer
  1732. account := accounts.Account{Address: addr}
  1733. wallet, err := s.b.AccountManager().Find(account)
  1734. if err != nil {
  1735. return nil, err
  1736. }
  1737. // Sign the requested hash with the wallet
  1738. signature, err := wallet.SignText(account, data)
  1739. if err == nil {
  1740. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1741. }
  1742. return signature, err
  1743. }
  1744. // SignTransactionResult represents a RLP encoded signed transaction.
  1745. type SignTransactionResult struct {
  1746. Raw hexutil.Bytes `json:"raw"`
  1747. Tx *types.Transaction `json:"tx"`
  1748. }
  1749. // SignTransaction will sign the given transaction with the from account.
  1750. // The node needs to have the private key of the account corresponding with
  1751. // the given from address and it needs to be unlocked.
  1752. func (s *TransactionAPI) SignTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
  1753. if args.Gas == nil {
  1754. return nil, fmt.Errorf("gas not specified")
  1755. }
  1756. if args.GasPrice == nil && (args.MaxPriorityFeePerGas == nil || args.MaxFeePerGas == nil) {
  1757. return nil, fmt.Errorf("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas")
  1758. }
  1759. if args.Nonce == nil {
  1760. return nil, fmt.Errorf("nonce not specified")
  1761. }
  1762. if err := args.setDefaults(ctx, s.b); err != nil {
  1763. return nil, err
  1764. }
  1765. // Before actually sign the transaction, ensure the transaction fee is reasonable.
  1766. tx := args.toTransaction()
  1767. if err := checkTxFee(tx.GasPrice(), tx.Gas(), s.b.RPCTxFeeCap()); err != nil {
  1768. return nil, err
  1769. }
  1770. signed, err := s.sign(args.from(), tx)
  1771. if err != nil {
  1772. return nil, err
  1773. }
  1774. data, err := signed.MarshalBinary()
  1775. if err != nil {
  1776. return nil, err
  1777. }
  1778. return &SignTransactionResult{data, signed}, nil
  1779. }
  1780. // PendingTransactions returns the transactions that are in the transaction pool
  1781. // and have a from address that is one of the accounts this node manages.
  1782. func (s *TransactionAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1783. pending, err := s.b.GetPoolTransactions()
  1784. if err != nil {
  1785. return nil, err
  1786. }
  1787. accounts := make(map[common.Address]struct{})
  1788. for _, wallet := range s.b.AccountManager().Wallets() {
  1789. for _, account := range wallet.Accounts() {
  1790. accounts[account.Address] = struct{}{}
  1791. }
  1792. }
  1793. curHeader := s.b.CurrentHeader()
  1794. transactions := make([]*RPCTransaction, 0, len(pending))
  1795. for _, tx := range pending {
  1796. from, _ := types.Sender(s.signer, tx)
  1797. if _, exists := accounts[from]; exists {
  1798. transactions = append(transactions, newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig()))
  1799. }
  1800. }
  1801. return transactions, nil
  1802. }
  1803. // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1804. // the given transaction from the pool and reinsert it with the new gas price and limit.
  1805. func (s *TransactionAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1806. if sendArgs.Nonce == nil {
  1807. return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1808. }
  1809. if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1810. return common.Hash{}, err
  1811. }
  1812. matchTx := sendArgs.toTransaction()
  1813. // Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.
  1814. var price = matchTx.GasPrice()
  1815. if gasPrice != nil {
  1816. price = gasPrice.ToInt()
  1817. }
  1818. var gas = matchTx.Gas()
  1819. if gasLimit != nil {
  1820. gas = uint64(*gasLimit)
  1821. }
  1822. if err := checkTxFee(price, gas, s.b.RPCTxFeeCap()); err != nil {
  1823. return common.Hash{}, err
  1824. }
  1825. // Iterate the pending list for replacement
  1826. pending, err := s.b.GetPoolTransactions()
  1827. if err != nil {
  1828. return common.Hash{}, err
  1829. }
  1830. for _, p := range pending {
  1831. wantSigHash := s.signer.Hash(matchTx)
  1832. pFrom, err := types.Sender(s.signer, p)
  1833. if err == nil && pFrom == sendArgs.from() && s.signer.Hash(p) == wantSigHash {
  1834. // Match. Re-sign and send the transaction.
  1835. if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1836. sendArgs.GasPrice = gasPrice
  1837. }
  1838. if gasLimit != nil && *gasLimit != 0 {
  1839. sendArgs.Gas = gasLimit
  1840. }
  1841. signedTx, err := s.sign(sendArgs.from(), sendArgs.toTransaction())
  1842. if err != nil {
  1843. return common.Hash{}, err
  1844. }
  1845. if err = s.b.SendTx(ctx, signedTx); err != nil {
  1846. return common.Hash{}, err
  1847. }
  1848. return signedTx.Hash(), nil
  1849. }
  1850. }
  1851. return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  1852. }
  1853. // DebugAPI is the collection of Ethereum APIs exposed over the debugging
  1854. // namespace.
  1855. type DebugAPI struct {
  1856. b Backend
  1857. }
  1858. // NewDebugAPI creates a new instance of DebugAPI.
  1859. func NewDebugAPI(b Backend) *DebugAPI {
  1860. return &DebugAPI{b: b}
  1861. }
  1862. // GetHeaderRlp retrieves the RLP encoded for of a single header.
  1863. func (api *DebugAPI) GetHeaderRlp(ctx context.Context, number uint64) (hexutil.Bytes, error) {
  1864. header, _ := api.b.HeaderByNumber(ctx, rpc.BlockNumber(number))
  1865. if header == nil {
  1866. return nil, fmt.Errorf("header #%d not found", number)
  1867. }
  1868. return rlp.EncodeToBytes(header)
  1869. }
  1870. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1871. func (api *DebugAPI) GetBlockRlp(ctx context.Context, number uint64) (hexutil.Bytes, error) {
  1872. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1873. if block == nil {
  1874. return nil, fmt.Errorf("block #%d not found", number)
  1875. }
  1876. return rlp.EncodeToBytes(block)
  1877. }
  1878. // GetRawReceipts retrieves the binary-encoded raw receipts of a single block.
  1879. func (api *DebugAPI) GetRawReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]hexutil.Bytes, error) {
  1880. var hash common.Hash
  1881. if h, ok := blockNrOrHash.Hash(); ok {
  1882. hash = h
  1883. } else {
  1884. block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash)
  1885. if err != nil {
  1886. return nil, err
  1887. }
  1888. hash = block.Hash()
  1889. }
  1890. receipts, err := api.b.GetReceipts(ctx, hash)
  1891. if err != nil {
  1892. return nil, err
  1893. }
  1894. result := make([]hexutil.Bytes, len(receipts))
  1895. for i, receipt := range receipts {
  1896. b, err := receipt.MarshalBinary()
  1897. if err != nil {
  1898. return nil, err
  1899. }
  1900. result[i] = b
  1901. }
  1902. return result, nil
  1903. }
  1904. // PrintBlock retrieves a block and returns its pretty printed form.
  1905. func (api *DebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1906. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1907. if block == nil {
  1908. return "", fmt.Errorf("block #%d not found", number)
  1909. }
  1910. return spew.Sdump(block), nil
  1911. }
  1912. // SeedHash retrieves the seed hash of a block.
  1913. func (api *DebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1914. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1915. if block == nil {
  1916. return "", fmt.Errorf("block #%d not found", number)
  1917. }
  1918. return fmt.Sprintf("%#x", ethash.SeedHash(number)), nil
  1919. }
  1920. // ChaindbProperty returns leveldb properties of the key-value database.
  1921. func (api *DebugAPI) ChaindbProperty(property string) (string, error) {
  1922. if property == "" {
  1923. property = "leveldb.stats"
  1924. } else if !strings.HasPrefix(property, "leveldb.") {
  1925. property = "leveldb." + property
  1926. }
  1927. return api.b.ChainDb().Stat(property)
  1928. }
  1929. // ChaindbCompact flattens the entire key-value database into a single level,
  1930. // removing all unused slots and merging all keys.
  1931. func (api *DebugAPI) ChaindbCompact() error {
  1932. for b := byte(0); b < 255; b++ {
  1933. log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1934. if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  1935. log.Error("Database compaction failed", "err", err)
  1936. return err
  1937. }
  1938. }
  1939. return nil
  1940. }
  1941. // SetHead rewinds the head of the blockchain to a previous block.
  1942. func (api *DebugAPI) SetHead(number hexutil.Uint64) {
  1943. api.b.SetHead(uint64(number))
  1944. }
  1945. // NetAPI offers network related RPC methods
  1946. type NetAPI struct {
  1947. net *p2p.Server
  1948. networkVersion uint64
  1949. }
  1950. // NewNetAPI creates a new net API instance.
  1951. func NewNetAPI(net *p2p.Server, networkVersion uint64) *NetAPI {
  1952. return &NetAPI{net, networkVersion}
  1953. }
  1954. // Listening returns an indication if the node is listening for network connections.
  1955. func (s *NetAPI) Listening() bool {
  1956. return true // always listening
  1957. }
  1958. // PeerCount returns the number of connected peers
  1959. func (s *NetAPI) PeerCount() hexutil.Uint {
  1960. return hexutil.Uint(s.net.PeerCount())
  1961. }
  1962. // Version returns the current ethereum protocol version.
  1963. func (s *NetAPI) Version() string {
  1964. return fmt.Sprintf("%d", s.networkVersion)
  1965. }
  1966. // checkTxFee is an internal function used to check whether the fee of
  1967. // the given transaction is _reasonable_(under the cap).
  1968. func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error {
  1969. // Short circuit if there is no cap for transaction fee at all.
  1970. if cap == 0 {
  1971. return nil
  1972. }
  1973. 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)))
  1974. feeFloat, _ := feeEth.Float64()
  1975. if feeFloat > cap {
  1976. return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap)
  1977. }
  1978. return nil
  1979. }
  1980. // toHexSlice creates a slice of hex-strings based on []byte.
  1981. func toHexSlice(b [][]byte) []string {
  1982. r := make([]string, len(b))
  1983. for i := range b {
  1984. r[i] = hexutil.Encode(b[i])
  1985. }
  1986. return r
  1987. }
  1988. // ---------------------------------------------------------------- FlashBots ----------------------------------------------------------------
  1989. // BundleAPI offers an API for accepting bundled transactions
  1990. type BundleAPI struct {
  1991. b Backend
  1992. chain *core.BlockChain
  1993. }
  1994. // NewBundleAPI creates a new Tx Bundle API instance.
  1995. func NewBundleAPI(b Backend, chain *core.BlockChain) *BundleAPI {
  1996. return &BundleAPI{b, chain}
  1997. }
  1998. // CallBundleArgs represents the arguments for a call.
  1999. type CallBundleArgs struct {
  2000. Txs []hexutil.Bytes `json:"txs"`
  2001. BlockNumber rpc.BlockNumber `json:"blockNumber"`
  2002. StateBlockNumberOrHash rpc.BlockNumberOrHash `json:"stateBlockNumber"`
  2003. Coinbase *string `json:"coinbase"`
  2004. Timestamp *uint64 `json:"timestamp"`
  2005. Timeout *int64 `json:"timeout"`
  2006. GasLimit *uint64 `json:"gasLimit"`
  2007. Difficulty *big.Int `json:"difficulty"`
  2008. BaseFee *big.Int `json:"baseFee"`
  2009. }
  2010. // CallBundle will simulate a bundle of transactions at the top of a given block
  2011. // number with the state of another (or the same) block. This can be used to
  2012. // simulate future blocks with the current state, or it can be used to simulate
  2013. // a past block.
  2014. // The sender is responsible for signing the transactions and using the correct
  2015. // nonce and ensuring validity
  2016. func (s *BundleAPI) CallBundle(ctx context.Context, args CallBundleArgs) (map[string]interface{}, error) {
  2017. if len(args.Txs) == 0 {
  2018. return nil, errors.New("bundle missing txs")
  2019. }
  2020. if args.BlockNumber == 0 {
  2021. return nil, errors.New("bundle missing blockNumber")
  2022. }
  2023. var txs types.Transactions
  2024. for _, encodedTx := range args.Txs {
  2025. tx := new(types.Transaction)
  2026. if err := tx.UnmarshalBinary(encodedTx); err != nil {
  2027. return nil, err
  2028. }
  2029. txs = append(txs, tx)
  2030. }
  2031. defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  2032. timeoutMilliSeconds := int64(5000)
  2033. if args.Timeout != nil {
  2034. timeoutMilliSeconds = *args.Timeout
  2035. }
  2036. timeout := time.Millisecond * time.Duration(timeoutMilliSeconds)
  2037. state, parent, err := s.b.StateAndHeaderByNumberOrHash(ctx, args.StateBlockNumberOrHash)
  2038. if state == nil || err != nil {
  2039. return nil, err
  2040. }
  2041. blockNumber := big.NewInt(int64(args.BlockNumber))
  2042. timestamp := parent.Time + 1
  2043. if args.Timestamp != nil {
  2044. timestamp = *args.Timestamp
  2045. }
  2046. coinbase := parent.Coinbase
  2047. if args.Coinbase != nil {
  2048. coinbase = common.HexToAddress(*args.Coinbase)
  2049. }
  2050. difficulty := parent.Difficulty
  2051. if args.Difficulty != nil {
  2052. difficulty = args.Difficulty
  2053. }
  2054. gasLimit := parent.GasLimit
  2055. if args.GasLimit != nil {
  2056. gasLimit = *args.GasLimit
  2057. }
  2058. var baseFee *big.Int
  2059. if args.BaseFee != nil {
  2060. baseFee = args.BaseFee
  2061. } else if s.b.ChainConfig().IsLondon(big.NewInt(args.BlockNumber.Int64())) {
  2062. baseFee = misc.CalcBaseFee(s.b.ChainConfig(), parent)
  2063. }
  2064. header := &types.Header{
  2065. ParentHash: parent.Hash(),
  2066. Number: blockNumber,
  2067. GasLimit: gasLimit,
  2068. Time: timestamp,
  2069. Difficulty: difficulty,
  2070. Coinbase: coinbase,
  2071. BaseFee: baseFee,
  2072. }
  2073. // Setup context so it may be cancelled the call has completed
  2074. // or, in case of unmetered gas, setup a context with a timeout.
  2075. var cancel context.CancelFunc
  2076. if timeout > 0 {
  2077. ctx, cancel = context.WithTimeout(ctx, timeout)
  2078. } else {
  2079. ctx, cancel = context.WithCancel(ctx)
  2080. }
  2081. // Make sure the context is cancelled when the call has completed
  2082. // this makes sure resources are cleaned up.
  2083. defer cancel()
  2084. vmconfig := vm.Config{}
  2085. // Setup the gas pool (also for unmetered requests)
  2086. // and apply the message.
  2087. gp := new(core.GasPool).AddGas(math.MaxUint64)
  2088. results := []map[string]interface{}{}
  2089. coinbaseBalanceBefore := state.GetBalance(coinbase)
  2090. bundleHash := sha3.NewLegacyKeccak256()
  2091. signer := types.MakeSigner(s.b.ChainConfig(), blockNumber)
  2092. var totalGasUsed uint64
  2093. gasFees := new(big.Int)
  2094. for i, tx := range txs {
  2095. coinbaseBalanceBeforeTx := state.GetBalance(coinbase)
  2096. state.Prepare(tx.Hash(), i)
  2097. receipt, result, err := core.ApplyTransactionWithResult(s.b.ChainConfig(), s.chain, &coinbase, gp, state, header, tx, &header.GasUsed, vmconfig)
  2098. if err != nil {
  2099. return nil, fmt.Errorf("err: %w; txhash %s", err, tx.Hash())
  2100. }
  2101. txHash := tx.Hash().String()
  2102. from, err := types.Sender(signer, tx)
  2103. if err != nil {
  2104. return nil, fmt.Errorf("err: %w; txhash %s", err, tx.Hash())
  2105. }
  2106. to := "0x"
  2107. if tx.To() != nil {
  2108. to = tx.To().String()
  2109. }
  2110. jsonResult := map[string]interface{}{
  2111. "txHash": txHash,
  2112. "gasUsed": receipt.GasUsed,
  2113. "fromAddress": from.String(),
  2114. "toAddress": to,
  2115. }
  2116. totalGasUsed += receipt.GasUsed
  2117. gasPrice, err := tx.EffectiveGasTip(header.BaseFee)
  2118. if err != nil {
  2119. return nil, fmt.Errorf("err: %w; txhash %s", err, tx.Hash())
  2120. }
  2121. gasFeesTx := new(big.Int).Mul(big.NewInt(int64(receipt.GasUsed)), gasPrice)
  2122. gasFees.Add(gasFees, gasFeesTx)
  2123. bundleHash.Write(tx.Hash().Bytes())
  2124. if result.Err != nil {
  2125. jsonResult["error"] = result.Err.Error()
  2126. revert := result.Revert()
  2127. if len(revert) > 0 {
  2128. jsonResult["revert"] = string(revert)
  2129. }
  2130. } else {
  2131. dst := make([]byte, hex.EncodedLen(len(result.Return())))
  2132. hex.Encode(dst, result.Return())
  2133. jsonResult["value"] = "0x" + string(dst)
  2134. }
  2135. coinbaseDiffTx := new(big.Int).Sub(state.GetBalance(coinbase), coinbaseBalanceBeforeTx)
  2136. jsonResult["coinbaseDiff"] = coinbaseDiffTx.String()
  2137. jsonResult["gasFees"] = gasFeesTx.String()
  2138. jsonResult["ethSentToCoinbase"] = new(big.Int).Sub(coinbaseDiffTx, gasFeesTx).String()
  2139. jsonResult["gasPrice"] = new(big.Int).Div(coinbaseDiffTx, big.NewInt(int64(receipt.GasUsed))).String()
  2140. jsonResult["gasUsed"] = receipt.GasUsed
  2141. results = append(results, jsonResult)
  2142. }
  2143. ret := map[string]interface{}{}
  2144. ret["results"] = results
  2145. coinbaseDiff := new(big.Int).Sub(state.GetBalance(coinbase), coinbaseBalanceBefore)
  2146. ret["coinbaseDiff"] = coinbaseDiff.String()
  2147. ret["gasFees"] = gasFees.String()
  2148. ret["ethSentToCoinbase"] = new(big.Int).Sub(coinbaseDiff, gasFees).String()
  2149. ret["bundleGasPrice"] = new(big.Int).Div(coinbaseDiff, big.NewInt(int64(totalGasUsed))).String()
  2150. ret["totalGasUsed"] = totalGasUsed
  2151. ret["stateBlockNumber"] = parent.Number.Int64()
  2152. ret["bundleHash"] = "0x" + common.Bytes2Hex(bundleHash.Sum(nil))
  2153. return ret, nil
  2154. }
  2155. // EstimateGasBundleArgs represents the arguments for a call
  2156. type EstimateGasBundleArgs struct {
  2157. Txs []TransactionArgs `json:"txs"`
  2158. BlockNumber rpc.BlockNumber `json:"blockNumber"`
  2159. StateBlockNumberOrHash rpc.BlockNumberOrHash `json:"stateBlockNumber"`
  2160. Coinbase *string `json:"coinbase"`
  2161. Timestamp *uint64 `json:"timestamp"`
  2162. Timeout *int64 `json:"timeout"`
  2163. }
  2164. func (s *BundleAPI) EstimateGasBundle(ctx context.Context, args EstimateGasBundleArgs) (map[string]interface{}, error) {
  2165. if len(args.Txs) == 0 {
  2166. return nil, errors.New("bundle missing txs")
  2167. }
  2168. if args.BlockNumber == 0 {
  2169. return nil, errors.New("bundle missing blockNumber")
  2170. }
  2171. timeoutMS := int64(5000)
  2172. if args.Timeout != nil {
  2173. timeoutMS = *args.Timeout
  2174. }
  2175. timeout := time.Millisecond * time.Duration(timeoutMS)
  2176. state, parent, err := s.b.StateAndHeaderByNumberOrHash(ctx, args.StateBlockNumberOrHash)
  2177. if state == nil || err != nil {
  2178. return nil, err
  2179. }
  2180. blockNumber := big.NewInt(int64(args.BlockNumber))
  2181. timestamp := parent.Time + 1
  2182. if args.Timestamp != nil {
  2183. timestamp = *args.Timestamp
  2184. }
  2185. coinbase := parent.Coinbase
  2186. if args.Coinbase != nil {
  2187. coinbase = common.HexToAddress(*args.Coinbase)
  2188. }
  2189. header := &types.Header{
  2190. ParentHash: parent.Hash(),
  2191. Number: blockNumber,
  2192. GasLimit: parent.GasLimit,
  2193. Time: timestamp,
  2194. Difficulty: parent.Difficulty,
  2195. Coinbase: coinbase,
  2196. BaseFee: parent.BaseFee,
  2197. }
  2198. // Setup context so it may be cancelled when the call
  2199. // has completed or, in case of unmetered gas, setup
  2200. // a context with a timeout
  2201. var cancel context.CancelFunc
  2202. if timeout > 0 {
  2203. ctx, cancel = context.WithTimeout(ctx, timeout)
  2204. } else {
  2205. ctx, cancel = context.WithCancel(ctx)
  2206. }
  2207. // Make sure the context is cancelled when the call has completed
  2208. // This makes sure resources are cleaned up
  2209. defer cancel()
  2210. // RPC Call gas cap
  2211. globalGasCap := s.b.RPCGasCap()
  2212. // Results
  2213. results := []map[string]interface{}{}
  2214. // Copy the original db so we don't modify it
  2215. statedb := state.Copy()
  2216. // Gas pool
  2217. gp := new(core.GasPool).AddGas(math.MaxUint64)
  2218. // Block context
  2219. blockContext := core.NewEVMBlockContext(header, s.chain, &coinbase)
  2220. // Feed each of the transactions into the VM ctx
  2221. // And try and estimate the gas used
  2222. for i, txArgs := range args.Txs {
  2223. // Since its a txCall we'll just prepare the
  2224. // state with a random hash
  2225. var randomHash common.Hash
  2226. rand.Read(randomHash[:])
  2227. // New random hash since its a call
  2228. statedb.Prepare(randomHash, i)
  2229. // Convert tx args to msg to apply state transition
  2230. msg, err := txArgs.ToMessage(globalGasCap, header.BaseFee)
  2231. if err != nil {
  2232. return nil, err
  2233. }
  2234. // Prepare the hashes
  2235. txContext := core.NewEVMTxContext(msg)
  2236. // Get EVM Environment
  2237. vmenv := vm.NewEVM(blockContext, txContext, statedb, s.b.ChainConfig(), vm.Config{NoBaseFee: true})
  2238. // Apply state transition
  2239. result, err := core.ApplyMessage(vmenv, msg, gp)
  2240. if err != nil {
  2241. return nil, err
  2242. }
  2243. // Modifications are committed to the state
  2244. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  2245. statedb.Finalise(vmenv.ChainConfig().IsEIP158(blockNumber))
  2246. // Append result
  2247. jsonResult := map[string]interface{}{
  2248. "gasUsed": result.UsedGas,
  2249. }
  2250. results = append(results, jsonResult)
  2251. }
  2252. // Return results
  2253. ret := map[string]interface{}{}
  2254. ret["results"] = results
  2255. return ret, nil
  2256. }