api.go 83 KB

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