api.go 83 KB

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