api.go 86 KB

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