api.go 74 KB

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