api.go 73 KB

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