api.go 91 KB

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