api.go 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513
  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. type ChainContextBackend interface {
  791. Engine() consensus.Engine
  792. HeaderByNumber(context.Context, rpc.BlockNumber) (*types.Header, error)
  793. }
  794. // ChainContext is an implementation of core.ChainContext. It's main use-case
  795. // is instantiating a vm.BlockContext without having access to the BlockChain object.
  796. type ChainContext struct {
  797. b ChainContextBackend
  798. ctx context.Context
  799. }
  800. // NewChainContext creates a new ChainContext object.
  801. func NewChainContext(ctx context.Context, backend ChainContextBackend) *ChainContext {
  802. return &ChainContext{ctx: ctx, b: backend}
  803. }
  804. func (context *ChainContext) Engine() consensus.Engine {
  805. return context.b.Engine()
  806. }
  807. func (context *ChainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
  808. // This method is called to get the hash for a block number when executing the BLOCKHASH
  809. // opcode. Hence no need to search for non-canonical blocks.
  810. header, err := context.b.HeaderByNumber(context.ctx, rpc.BlockNumber(number))
  811. if err != nil || header.Hash() != hash {
  812. return nil
  813. }
  814. return header
  815. }
  816. 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) {
  817. defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  818. state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  819. if state == nil || err != nil {
  820. return nil, err
  821. }
  822. if err := overrides.Apply(state); err != nil {
  823. return nil, err
  824. }
  825. // Setup context so it may be cancelled the call has completed
  826. // or, in case of unmetered gas, setup a context with a timeout.
  827. var cancel context.CancelFunc
  828. if timeout > 0 {
  829. ctx, cancel = context.WithTimeout(ctx, timeout)
  830. } else {
  831. ctx, cancel = context.WithCancel(ctx)
  832. }
  833. // Make sure the context is cancelled when the call has completed
  834. // this makes sure resources are cleaned up.
  835. defer cancel()
  836. return doCall(ctx, b, args, state, header, timeout, new(core.GasPool).AddGas(globalGasCap), nil)
  837. }
  838. func doCall(ctx context.Context, b Backend, args CallArgs, state *state.StateDB, header *types.Header, timeout time.Duration, gp *core.GasPool, blockContext *vm.BlockContext) (*core.ExecutionResult, error) {
  839. // Get a new instance of the EVM.
  840. msg := args.ToMessage(gp.Gas())
  841. evm, vmError, err := b.GetEVM(ctx, msg, state, header, nil, blockContext)
  842. if err != nil {
  843. return nil, err
  844. }
  845. // Wait for the context to be done and cancel the evm. Even if the
  846. // EVM has finished, cancelling may be done (repeatedly)
  847. gopool.Submit(func() {
  848. <-ctx.Done()
  849. evm.Cancel()
  850. })
  851. // Execute the message.
  852. //gp := new(core.GasPool).AddGas(math.MaxUint64)
  853. result, err := core.ApplyMessage(evm, msg, gp)
  854. if err := vmError(); err != nil {
  855. return nil, err
  856. }
  857. // If the timer caused an abort, return an appropriate error message
  858. if evm.Cancelled() {
  859. return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
  860. }
  861. if err != nil {
  862. return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas())
  863. }
  864. return result, nil
  865. }
  866. func newRevertError(result *core.ExecutionResult) *revertError {
  867. reason, errUnpack := abi.UnpackRevert(result.Revert())
  868. err := errors.New("execution reverted")
  869. if errUnpack == nil {
  870. err = fmt.Errorf("execution reverted: %v", reason)
  871. }
  872. return &revertError{
  873. error: err,
  874. reason: hexutil.Encode(result.Revert()),
  875. }
  876. }
  877. // revertError is an API error that encompassas an EVM revertal with JSON error
  878. // code and a binary data blob.
  879. type revertError struct {
  880. error
  881. reason string // revert reason hex encoded
  882. }
  883. // ErrorCode returns the JSON error code for a revertal.
  884. // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
  885. func (e *revertError) ErrorCode() int {
  886. return 3
  887. }
  888. // ErrorData returns the hex encoded revert reason.
  889. func (e *revertError) ErrorData() interface{} {
  890. return e.reason
  891. }
  892. // Call executes the given transaction on the state for the given block number.
  893. //
  894. // Additionally, the caller can specify a batch of contract for fields overriding.
  895. //
  896. // Note, this function doesn't make and changes in the state/blockchain and is
  897. // useful to execute and retrieve values.
  898. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Bytes, error) {
  899. result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, vm.Config{}, 5*time.Second, s.b.RPCGasCap())
  900. if err != nil {
  901. return nil, err
  902. }
  903. // If the result contains a revert reason, try to unpack and return it.
  904. if len(result.Revert()) > 0 {
  905. return nil, newRevertError(result)
  906. }
  907. return result.Return(), result.Err
  908. }
  909. func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) {
  910. // Binary search the gas requirement, as it may be higher than the amount used
  911. var (
  912. lo uint64 = params.TxGas - 1
  913. hi uint64
  914. cap uint64
  915. )
  916. // Use zero address if sender unspecified.
  917. if args.From == nil {
  918. args.From = new(common.Address)
  919. }
  920. // Determine the highest gas limit can be used during the estimation.
  921. if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  922. hi = uint64(*args.Gas)
  923. } else {
  924. // Retrieve the block to act as the gas ceiling
  925. block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
  926. if err != nil {
  927. return 0, err
  928. }
  929. if block == nil {
  930. return 0, errors.New("block not found")
  931. }
  932. hi = block.GasLimit()
  933. }
  934. // Recap the highest gas limit with account's available balance.
  935. if args.GasPrice != nil && args.GasPrice.ToInt().BitLen() != 0 {
  936. state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  937. if err != nil {
  938. return 0, err
  939. }
  940. balance := state.GetBalance(*args.From) // from can't be nil
  941. available := new(big.Int).Set(balance)
  942. if args.Value != nil {
  943. if args.Value.ToInt().Cmp(available) >= 0 {
  944. return 0, errors.New("insufficient funds for transfer")
  945. }
  946. available.Sub(available, args.Value.ToInt())
  947. }
  948. allowance := new(big.Int).Div(available, args.GasPrice.ToInt())
  949. // If the allowance is larger than maximum uint64, skip checking
  950. if allowance.IsUint64() && hi > allowance.Uint64() {
  951. transfer := args.Value
  952. if transfer == nil {
  953. transfer = new(hexutil.Big)
  954. }
  955. log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
  956. "sent", transfer.ToInt(), "gasprice", args.GasPrice.ToInt(), "fundable", allowance)
  957. hi = allowance.Uint64()
  958. }
  959. }
  960. // Recap the highest gas allowance with specified gascap.
  961. if gasCap != 0 && hi > gasCap {
  962. log.Debug("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  963. hi = gasCap
  964. }
  965. cap = hi
  966. // Create a helper to check if a gas allowance results in an executable transaction
  967. executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
  968. args.Gas = (*hexutil.Uint64)(&gas)
  969. result, err := DoCall(ctx, b, args, blockNrOrHash, nil, vm.Config{}, 0, gasCap)
  970. if err != nil {
  971. if errors.Is(err, core.ErrIntrinsicGas) {
  972. return true, nil, nil // Special case, raise gas limit
  973. }
  974. return true, nil, err // Bail out
  975. }
  976. return result.Failed(), result, nil
  977. }
  978. // Execute the binary search and hone in on an executable gas limit
  979. for lo+1 < hi {
  980. mid := (hi + lo) / 2
  981. failed, _, err := executable(mid)
  982. // If the error is not nil(consensus error), it means the provided message
  983. // call or transaction will never be accepted no matter how much gas it is
  984. // assigned. Return the error directly, don't struggle any more.
  985. if err != nil {
  986. return 0, err
  987. }
  988. if failed {
  989. lo = mid
  990. } else {
  991. hi = mid
  992. }
  993. }
  994. // Reject the transaction as invalid if it still fails at the highest allowance
  995. if hi == cap {
  996. failed, result, err := executable(hi)
  997. if err != nil {
  998. return 0, err
  999. }
  1000. if failed {
  1001. if result != nil && result.Err != vm.ErrOutOfGas {
  1002. if len(result.Revert()) > 0 {
  1003. return 0, newRevertError(result)
  1004. }
  1005. return 0, result.Err
  1006. }
  1007. // Otherwise, the specified gas cap is too low
  1008. return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
  1009. }
  1010. }
  1011. return hexutil.Uint64(hi), nil
  1012. }
  1013. // EstimateGas returns an estimate of the amount of gas needed to execute the
  1014. // given transaction against the current pending block.
  1015. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
  1016. bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1017. if blockNrOrHash != nil {
  1018. bNrOrHash = *blockNrOrHash
  1019. }
  1020. return DoEstimateGas(ctx, s.b, args, bNrOrHash, s.b.RPCGasCap())
  1021. }
  1022. // GetDiffAccounts returns changed accounts in a specific block number.
  1023. func (s *PublicBlockChainAPI) GetDiffAccounts(ctx context.Context, blockNr rpc.BlockNumber) ([]common.Address, error) {
  1024. if s.b.Chain() == nil {
  1025. return nil, fmt.Errorf("blockchain not support get diff accounts")
  1026. }
  1027. header, err := s.b.HeaderByNumber(ctx, blockNr)
  1028. if err != nil {
  1029. return nil, fmt.Errorf("block not found for block number (%d): %v", blockNr, err)
  1030. }
  1031. accounts, err := s.b.Chain().GetDiffAccounts(header.Hash())
  1032. if err == nil || !errors.Is(err, core.ErrDiffLayerNotFound) {
  1033. return accounts, err
  1034. }
  1035. // Replay the block when diff layer not found, it is very slow.
  1036. block, err := s.b.BlockByNumber(ctx, blockNr)
  1037. if err != nil {
  1038. return nil, fmt.Errorf("block not found for block number (%d): %v", blockNr, err)
  1039. }
  1040. _, statedb, err := s.replay(ctx, block, nil)
  1041. if err != nil {
  1042. return nil, err
  1043. }
  1044. return statedb.GetDirtyAccounts(), nil
  1045. }
  1046. func (s *PublicBlockChainAPI) needToReplay(ctx context.Context, block *types.Block, accounts []common.Address) (bool, error) {
  1047. receipts, err := s.b.GetReceipts(ctx, block.Hash())
  1048. if err != nil || len(receipts) != len(block.Transactions()) {
  1049. return false, fmt.Errorf("receipt incorrect for block number (%d): %v", block.NumberU64(), err)
  1050. }
  1051. accountSet := make(map[common.Address]struct{}, len(accounts))
  1052. for _, account := range accounts {
  1053. accountSet[account] = struct{}{}
  1054. }
  1055. spendValueMap := make(map[common.Address]int64, len(accounts))
  1056. receiveValueMap := make(map[common.Address]int64, len(accounts))
  1057. signer := types.MakeSigner(s.b.ChainConfig(), block.Number())
  1058. for index, tx := range block.Transactions() {
  1059. receipt := receipts[index]
  1060. from, err := types.Sender(signer, tx)
  1061. if err != nil {
  1062. return false, fmt.Errorf("get sender for tx failed: %v", err)
  1063. }
  1064. if _, exists := accountSet[from]; exists {
  1065. spendValueMap[from] += int64(receipt.GasUsed) * tx.GasPrice().Int64()
  1066. if receipt.Status == types.ReceiptStatusSuccessful {
  1067. spendValueMap[from] += tx.Value().Int64()
  1068. }
  1069. }
  1070. if tx.To() == nil {
  1071. continue
  1072. }
  1073. if _, exists := accountSet[*tx.To()]; exists && receipt.Status == types.ReceiptStatusSuccessful {
  1074. receiveValueMap[*tx.To()] += tx.Value().Int64()
  1075. }
  1076. }
  1077. parent, err := s.b.BlockByHash(ctx, block.ParentHash())
  1078. if err != nil {
  1079. return false, fmt.Errorf("block not found for block number (%d): %v", block.NumberU64()-1, err)
  1080. }
  1081. parentState, err := s.b.Chain().StateAt(parent.Root())
  1082. if err != nil {
  1083. return false, fmt.Errorf("statedb not found for block number (%d): %v", block.NumberU64()-1, err)
  1084. }
  1085. currentState, err := s.b.Chain().StateAt(block.Root())
  1086. if err != nil {
  1087. return false, fmt.Errorf("statedb not found for block number (%d): %v", block.NumberU64(), err)
  1088. }
  1089. for _, account := range accounts {
  1090. parentBalance := parentState.GetBalance(account).Int64()
  1091. currentBalance := currentState.GetBalance(account).Int64()
  1092. if receiveValueMap[account]-spendValueMap[account] != currentBalance-parentBalance {
  1093. return true, nil
  1094. }
  1095. }
  1096. return false, nil
  1097. }
  1098. func (s *PublicBlockChainAPI) replay(ctx context.Context, block *types.Block, accounts []common.Address) (*types.DiffAccountsInBlock, *state.StateDB, error) {
  1099. result := &types.DiffAccountsInBlock{
  1100. Number: block.NumberU64(),
  1101. BlockHash: block.Hash(),
  1102. Transactions: make([]types.DiffAccountsInTx, 0),
  1103. }
  1104. parent, err := s.b.BlockByHash(ctx, block.ParentHash())
  1105. if err != nil {
  1106. return nil, nil, fmt.Errorf("block not found for block number (%d): %v", block.NumberU64()-1, err)
  1107. }
  1108. statedb, err := s.b.Chain().StateAt(parent.Root())
  1109. if err != nil {
  1110. return nil, nil, fmt.Errorf("state not found for block number (%d): %v", block.NumberU64()-1, err)
  1111. }
  1112. accountSet := make(map[common.Address]struct{}, len(accounts))
  1113. for _, account := range accounts {
  1114. accountSet[account] = struct{}{}
  1115. }
  1116. // Recompute transactions.
  1117. signer := types.MakeSigner(s.b.ChainConfig(), block.Number())
  1118. for _, tx := range block.Transactions() {
  1119. // Skip data empty tx and to is one of the interested accounts tx.
  1120. skip := false
  1121. if len(tx.Data()) == 0 {
  1122. skip = true
  1123. } else if to := tx.To(); to != nil {
  1124. if _, exists := accountSet[*to]; exists {
  1125. skip = true
  1126. }
  1127. }
  1128. diffTx := types.DiffAccountsInTx{
  1129. TxHash: tx.Hash(),
  1130. Accounts: make(map[common.Address]*big.Int, len(accounts)),
  1131. }
  1132. if !skip {
  1133. // Record account balance
  1134. for _, account := range accounts {
  1135. diffTx.Accounts[account] = statedb.GetBalance(account)
  1136. }
  1137. }
  1138. // Apply transaction
  1139. msg, _ := tx.AsMessage(signer)
  1140. txContext := core.NewEVMTxContext(msg)
  1141. context := core.NewEVMBlockContext(block.Header(), s.b.Chain(), nil)
  1142. vmenv := vm.NewEVM(context, txContext, statedb, s.b.ChainConfig(), vm.Config{})
  1143. if posa, ok := s.b.Engine().(consensus.PoSA); ok {
  1144. if isSystem, _ := posa.IsSystemTransaction(tx, block.Header()); isSystem {
  1145. balance := statedb.GetBalance(consensus.SystemAddress)
  1146. if balance.Cmp(common.Big0) > 0 {
  1147. statedb.SetBalance(consensus.SystemAddress, big.NewInt(0))
  1148. statedb.AddBalance(block.Header().Coinbase, balance)
  1149. }
  1150. }
  1151. }
  1152. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  1153. return nil, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  1154. }
  1155. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  1156. if !skip {
  1157. // Compute account balance diff.
  1158. for _, account := range accounts {
  1159. diffTx.Accounts[account] = new(big.Int).Sub(statedb.GetBalance(account), diffTx.Accounts[account])
  1160. if diffTx.Accounts[account].Cmp(big.NewInt(0)) == 0 {
  1161. delete(diffTx.Accounts, account)
  1162. }
  1163. }
  1164. if len(diffTx.Accounts) != 0 {
  1165. result.Transactions = append(result.Transactions, diffTx)
  1166. }
  1167. }
  1168. }
  1169. return result, statedb, nil
  1170. }
  1171. // GetDiffAccountsWithScope returns detailed changes of some interested accounts in a specific block number.
  1172. func (s *PublicBlockChainAPI) GetDiffAccountsWithScope(ctx context.Context, blockNr rpc.BlockNumber, accounts []common.Address) (*types.DiffAccountsInBlock, error) {
  1173. if s.b.Chain() == nil {
  1174. return nil, fmt.Errorf("blockchain not support get diff accounts")
  1175. }
  1176. block, err := s.b.BlockByNumber(ctx, blockNr)
  1177. if err != nil {
  1178. return nil, fmt.Errorf("block not found for block number (%d): %v", blockNr, err)
  1179. }
  1180. needReplay, err := s.needToReplay(ctx, block, accounts)
  1181. if err != nil {
  1182. return nil, err
  1183. }
  1184. if !needReplay {
  1185. return &types.DiffAccountsInBlock{
  1186. Number: uint64(blockNr),
  1187. BlockHash: block.Hash(),
  1188. Transactions: make([]types.DiffAccountsInTx, 0),
  1189. }, nil
  1190. }
  1191. result, _, err := s.replay(ctx, block, accounts)
  1192. return result, err
  1193. }
  1194. // ExecutionResult groups all structured logs emitted by the EVM
  1195. // while replaying a transaction in debug mode as well as transaction
  1196. // execution status, the amount of gas used and the return value
  1197. type ExecutionResult struct {
  1198. Gas uint64 `json:"gas"`
  1199. Failed bool `json:"failed"`
  1200. ReturnValue string `json:"returnValue"`
  1201. StructLogs []StructLogRes `json:"structLogs"`
  1202. }
  1203. // StructLogRes stores a structured log emitted by the EVM while replaying a
  1204. // transaction in debug mode
  1205. type StructLogRes struct {
  1206. Pc uint64 `json:"pc"`
  1207. Op string `json:"op"`
  1208. Gas uint64 `json:"gas"`
  1209. GasCost uint64 `json:"gasCost"`
  1210. Depth int `json:"depth"`
  1211. Error error `json:"error,omitempty"`
  1212. Stack *[]string `json:"stack,omitempty"`
  1213. Memory *[]string `json:"memory,omitempty"`
  1214. Storage *map[string]string `json:"storage,omitempty"`
  1215. }
  1216. // FormatLogs formats EVM returned structured logs for json output
  1217. func FormatLogs(logs []vm.StructLog) []StructLogRes {
  1218. formatted := make([]StructLogRes, len(logs))
  1219. for index, trace := range logs {
  1220. formatted[index] = StructLogRes{
  1221. Pc: trace.Pc,
  1222. Op: trace.Op.String(),
  1223. Gas: trace.Gas,
  1224. GasCost: trace.GasCost,
  1225. Depth: trace.Depth,
  1226. Error: trace.Err,
  1227. }
  1228. if trace.Stack != nil {
  1229. stack := make([]string, len(trace.Stack))
  1230. for i, stackValue := range trace.Stack {
  1231. stack[i] = stackValue.Hex()
  1232. }
  1233. formatted[index].Stack = &stack
  1234. }
  1235. if trace.Memory != nil {
  1236. memory := make([]string, 0, (len(trace.Memory)+31)/32)
  1237. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1238. memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1239. }
  1240. formatted[index].Memory = &memory
  1241. }
  1242. if trace.Storage != nil {
  1243. storage := make(map[string]string)
  1244. for i, storageValue := range trace.Storage {
  1245. storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1246. }
  1247. formatted[index].Storage = &storage
  1248. }
  1249. }
  1250. return formatted
  1251. }
  1252. // RPCMarshalHeader converts the given header to the RPC output .
  1253. func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  1254. return map[string]interface{}{
  1255. "number": (*hexutil.Big)(head.Number),
  1256. "hash": head.Hash(),
  1257. "parentHash": head.ParentHash,
  1258. "nonce": head.Nonce,
  1259. "mixHash": head.MixDigest,
  1260. "sha3Uncles": head.UncleHash,
  1261. "logsBloom": head.Bloom,
  1262. "stateRoot": head.Root,
  1263. "miner": head.Coinbase,
  1264. "difficulty": (*hexutil.Big)(head.Difficulty),
  1265. "extraData": hexutil.Bytes(head.Extra),
  1266. "size": hexutil.Uint64(head.Size()),
  1267. "gasLimit": hexutil.Uint64(head.GasLimit),
  1268. "gasUsed": hexutil.Uint64(head.GasUsed),
  1269. "timestamp": hexutil.Uint64(head.Time),
  1270. "transactionsRoot": head.TxHash,
  1271. "receiptsRoot": head.ReceiptHash,
  1272. }
  1273. }
  1274. // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1275. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1276. // transaction hashes.
  1277. func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1278. fields := RPCMarshalHeader(block.Header())
  1279. fields["size"] = hexutil.Uint64(block.Size())
  1280. if inclTx {
  1281. formatTx := func(tx *types.Transaction) (interface{}, error) {
  1282. return tx.Hash(), nil
  1283. }
  1284. if fullTx {
  1285. formatTx = func(tx *types.Transaction) (interface{}, error) {
  1286. return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  1287. }
  1288. }
  1289. txs := block.Transactions()
  1290. transactions := make([]interface{}, len(txs))
  1291. var err error
  1292. for i, tx := range txs {
  1293. if transactions[i], err = formatTx(tx); err != nil {
  1294. return nil, err
  1295. }
  1296. }
  1297. fields["transactions"] = transactions
  1298. }
  1299. uncles := block.Uncles()
  1300. uncleHashes := make([]common.Hash, len(uncles))
  1301. for i, uncle := range uncles {
  1302. uncleHashes[i] = uncle.Hash()
  1303. }
  1304. fields["uncles"] = uncleHashes
  1305. return fields, nil
  1306. }
  1307. // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1308. // a `PublicBlockchainAPI`.
  1309. func (s *PublicBlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} {
  1310. fields := RPCMarshalHeader(header)
  1311. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash()))
  1312. return fields
  1313. }
  1314. // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1315. // a `PublicBlockchainAPI`.
  1316. func (s *PublicBlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1317. fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  1318. if err != nil {
  1319. return nil, err
  1320. }
  1321. if inclTx {
  1322. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, b.Hash()))
  1323. }
  1324. return fields, err
  1325. }
  1326. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1327. type RPCTransaction struct {
  1328. BlockHash *common.Hash `json:"blockHash"`
  1329. BlockNumber *hexutil.Big `json:"blockNumber"`
  1330. From common.Address `json:"from"`
  1331. Gas hexutil.Uint64 `json:"gas"`
  1332. GasPrice *hexutil.Big `json:"gasPrice"`
  1333. Hash common.Hash `json:"hash"`
  1334. Input hexutil.Bytes `json:"input"`
  1335. Nonce hexutil.Uint64 `json:"nonce"`
  1336. To *common.Address `json:"to"`
  1337. TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
  1338. Value *hexutil.Big `json:"value"`
  1339. Type hexutil.Uint64 `json:"type"`
  1340. Accesses *types.AccessList `json:"accessList,omitempty"`
  1341. ChainID *hexutil.Big `json:"chainId,omitempty"`
  1342. V *hexutil.Big `json:"v"`
  1343. R *hexutil.Big `json:"r"`
  1344. S *hexutil.Big `json:"s"`
  1345. }
  1346. // newRPCTransaction returns a transaction that will serialize to the RPC
  1347. // representation, with the given location metadata set (if available).
  1348. func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  1349. // Determine the signer. For replay-protected transactions, use the most permissive
  1350. // signer, because we assume that signers are backwards-compatible with old
  1351. // transactions. For non-protected transactions, the homestead signer signer is used
  1352. // because the return value of ChainId is zero for those transactions.
  1353. var signer types.Signer
  1354. if tx.Protected() {
  1355. signer = types.LatestSignerForChainID(tx.ChainId())
  1356. } else {
  1357. signer = types.HomesteadSigner{}
  1358. }
  1359. from, _ := types.Sender(signer, tx)
  1360. v, r, s := tx.RawSignatureValues()
  1361. result := &RPCTransaction{
  1362. Type: hexutil.Uint64(tx.Type()),
  1363. From: from,
  1364. Gas: hexutil.Uint64(tx.Gas()),
  1365. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1366. Hash: tx.Hash(),
  1367. Input: hexutil.Bytes(tx.Data()),
  1368. Nonce: hexutil.Uint64(tx.Nonce()),
  1369. To: tx.To(),
  1370. Value: (*hexutil.Big)(tx.Value()),
  1371. V: (*hexutil.Big)(v),
  1372. R: (*hexutil.Big)(r),
  1373. S: (*hexutil.Big)(s),
  1374. }
  1375. if blockHash != (common.Hash{}) {
  1376. result.BlockHash = &blockHash
  1377. result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1378. result.TransactionIndex = (*hexutil.Uint64)(&index)
  1379. }
  1380. if tx.Type() == types.AccessListTxType {
  1381. al := tx.AccessList()
  1382. result.Accesses = &al
  1383. result.ChainID = (*hexutil.Big)(tx.ChainId())
  1384. }
  1385. return result
  1386. }
  1387. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1388. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1389. return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1390. }
  1391. // newRPCTransactionsFromBlockIndex returns transactions that will serialize to the RPC representation.
  1392. func newRPCTransactionsFromBlockIndex(b *types.Block) []*RPCTransaction {
  1393. txs := b.Transactions()
  1394. result := make([]*RPCTransaction, 0, len(txs))
  1395. for idx, tx := range txs {
  1396. result = append(result, newRPCTransaction(tx, b.Hash(), b.NumberU64(), uint64(idx)))
  1397. }
  1398. return result
  1399. }
  1400. // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1401. func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1402. txs := b.Transactions()
  1403. if index >= uint64(len(txs)) {
  1404. return nil
  1405. }
  1406. return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1407. }
  1408. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1409. func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1410. txs := b.Transactions()
  1411. if index >= uint64(len(txs)) {
  1412. return nil
  1413. }
  1414. blob, _ := txs[index].MarshalBinary()
  1415. return blob
  1416. }
  1417. // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1418. func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1419. for idx, tx := range b.Transactions() {
  1420. if tx.Hash() == hash {
  1421. return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1422. }
  1423. }
  1424. return nil
  1425. }
  1426. // accessListResult returns an optional accesslist
  1427. // Its the result of the `debug_createAccessList` RPC call.
  1428. // It contains an error if the transaction itself failed.
  1429. type accessListResult struct {
  1430. Accesslist *types.AccessList `json:"accessList"`
  1431. Error string `json:"error,omitempty"`
  1432. GasUsed hexutil.Uint64 `json:"gasUsed"`
  1433. }
  1434. // CreateAccessList creates a EIP-2930 type AccessList for the given transaction.
  1435. // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
  1436. func (s *PublicBlockChainAPI) CreateAccessList(ctx context.Context, args SendTxArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) {
  1437. bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1438. if blockNrOrHash != nil {
  1439. bNrOrHash = *blockNrOrHash
  1440. }
  1441. acl, gasUsed, vmerr, err := AccessList(ctx, s.b, bNrOrHash, args)
  1442. if err != nil {
  1443. return nil, err
  1444. }
  1445. result := &accessListResult{Accesslist: &acl, GasUsed: hexutil.Uint64(gasUsed)}
  1446. if vmerr != nil {
  1447. result.Error = vmerr.Error()
  1448. }
  1449. return result, nil
  1450. }
  1451. // AccessList creates an access list for the given transaction.
  1452. // If the accesslist creation fails an error is returned.
  1453. // If the transaction itself fails, an vmErr is returned.
  1454. func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrHash, args SendTxArgs) (acl types.AccessList, gasUsed uint64, vmErr error, err error) {
  1455. // Retrieve the execution context
  1456. db, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1457. if db == nil || err != nil {
  1458. return nil, 0, nil, err
  1459. }
  1460. // If the gas amount is not set, extract this as it will depend on access
  1461. // lists and we'll need to reestimate every time
  1462. nogas := args.Gas == nil
  1463. // Ensure any missing fields are filled, extract the recipient and input data
  1464. if err := args.setDefaults(ctx, b); err != nil {
  1465. return nil, 0, nil, err
  1466. }
  1467. var to common.Address
  1468. if args.To != nil {
  1469. to = *args.To
  1470. } else {
  1471. to = crypto.CreateAddress(args.From, uint64(*args.Nonce))
  1472. }
  1473. var input []byte
  1474. if args.Input != nil {
  1475. input = *args.Input
  1476. } else if args.Data != nil {
  1477. input = *args.Data
  1478. }
  1479. // Retrieve the precompiles since they don't need to be added to the access list
  1480. precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number))
  1481. // Create an initial tracer
  1482. prevTracer := vm.NewAccessListTracer(nil, args.From, to, precompiles)
  1483. if args.AccessList != nil {
  1484. prevTracer = vm.NewAccessListTracer(*args.AccessList, args.From, to, precompiles)
  1485. }
  1486. for {
  1487. // Retrieve the current access list to expand
  1488. accessList := prevTracer.AccessList()
  1489. log.Trace("Creating access list", "input", accessList)
  1490. // If no gas amount was specified, each unique access list needs it's own
  1491. // gas calculation. This is quite expensive, but we need to be accurate
  1492. // and it's convered by the sender only anyway.
  1493. if nogas {
  1494. args.Gas = nil
  1495. if err := args.setDefaults(ctx, b); err != nil {
  1496. return nil, 0, nil, err // shouldn't happen, just in case
  1497. }
  1498. }
  1499. // Copy the original db so we don't modify it
  1500. statedb := db.Copy()
  1501. msg := types.NewMessage(args.From, args.To, uint64(*args.Nonce), args.Value.ToInt(), uint64(*args.Gas), args.GasPrice.ToInt(), input, accessList, false)
  1502. // Apply the transaction with the access list tracer
  1503. tracer := vm.NewAccessListTracer(accessList, args.From, to, precompiles)
  1504. config := vm.Config{Tracer: tracer, Debug: true}
  1505. vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config, nil)
  1506. if err != nil {
  1507. return nil, 0, nil, err
  1508. }
  1509. res, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
  1510. if err != nil {
  1511. return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err)
  1512. }
  1513. if tracer.Equal(prevTracer) {
  1514. return accessList, res.UsedGas, res.Err, nil
  1515. }
  1516. prevTracer = tracer
  1517. }
  1518. }
  1519. // PublicTransactionPoolAPI exposes methods for the RPC interface
  1520. type PublicTransactionPoolAPI struct {
  1521. b Backend
  1522. nonceLock *AddrLocker
  1523. signer types.Signer
  1524. }
  1525. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1526. func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1527. // The signer used by the API should always be the 'latest' known one because we expect
  1528. // signers to be backwards-compatible with old transactions.
  1529. signer := types.LatestSigner(b.ChainConfig())
  1530. return &PublicTransactionPoolAPI{b, nonceLock, signer}
  1531. }
  1532. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1533. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1534. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1535. n := hexutil.Uint(len(block.Transactions()))
  1536. return &n
  1537. }
  1538. return nil
  1539. }
  1540. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1541. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1542. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1543. n := hexutil.Uint(len(block.Transactions()))
  1544. return &n
  1545. }
  1546. return nil
  1547. }
  1548. // GetTransactionsByBlockNumber returns all the transactions for the given block number.
  1549. func (s *PublicTransactionPoolAPI) GetTransactionsByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) []*RPCTransaction {
  1550. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1551. return newRPCTransactionsFromBlockIndex(block)
  1552. }
  1553. return nil
  1554. }
  1555. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1556. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1557. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1558. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1559. }
  1560. return nil
  1561. }
  1562. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1563. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1564. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1565. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1566. }
  1567. return nil
  1568. }
  1569. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1570. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1571. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1572. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1573. }
  1574. return nil
  1575. }
  1576. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1577. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1578. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1579. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1580. }
  1581. return nil
  1582. }
  1583. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1584. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1585. // Ask transaction pool for the nonce which includes pending transactions
  1586. if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1587. nonce, err := s.b.GetPoolNonce(ctx, address)
  1588. if err != nil {
  1589. return nil, err
  1590. }
  1591. return (*hexutil.Uint64)(&nonce), nil
  1592. }
  1593. // Resolve block number and use its state to ask for the nonce
  1594. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1595. if state == nil || err != nil {
  1596. return nil, err
  1597. }
  1598. nonce := state.GetNonce(address)
  1599. return (*hexutil.Uint64)(&nonce), state.Error()
  1600. }
  1601. // GetTransactionByHash returns the transaction for the given hash
  1602. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1603. // Try to return an already finalized transaction
  1604. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1605. if err != nil {
  1606. return nil, err
  1607. }
  1608. if tx != nil {
  1609. return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1610. }
  1611. // No finalized transaction, try to retrieve it from the pool
  1612. if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1613. return newRPCPendingTransaction(tx), nil
  1614. }
  1615. // Transaction unknown, return as such
  1616. return nil, nil
  1617. }
  1618. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1619. func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1620. // Retrieve a finalized transaction, or a pooled otherwise
  1621. tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1622. if err != nil {
  1623. return nil, err
  1624. }
  1625. if tx == nil {
  1626. if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1627. // Transaction not found anywhere, abort
  1628. return nil, nil
  1629. }
  1630. }
  1631. // Serialize to RLP and return
  1632. return tx.MarshalBinary()
  1633. }
  1634. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1635. func (s *PublicTransactionPoolAPI) GetTransactionReceiptsByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) ([]map[string]interface{}, error) {
  1636. blockNumber := uint64(blockNr.Int64())
  1637. blockHash := rawdb.ReadCanonicalHash(s.b.ChainDb(), blockNumber)
  1638. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1639. if err != nil {
  1640. return nil, err
  1641. }
  1642. block, err := s.b.BlockByHash(ctx, blockHash)
  1643. if err != nil {
  1644. return nil, err
  1645. }
  1646. txs := block.Transactions()
  1647. if len(txs) != len(receipts) {
  1648. return nil, fmt.Errorf("txs length doesn't equal to receipts' length")
  1649. }
  1650. txReceipts := make([]map[string]interface{}, 0, len(txs))
  1651. for idx, receipt := range receipts {
  1652. tx := txs[idx]
  1653. var signer types.Signer = types.FrontierSigner{}
  1654. if tx.Protected() {
  1655. signer = types.NewEIP155Signer(tx.ChainId())
  1656. }
  1657. from, _ := types.Sender(signer, tx)
  1658. fields := map[string]interface{}{
  1659. "blockHash": blockHash,
  1660. "blockNumber": hexutil.Uint64(blockNumber),
  1661. "transactionHash": tx.Hash(),
  1662. "transactionIndex": hexutil.Uint64(idx),
  1663. "from": from,
  1664. "to": tx.To(),
  1665. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1666. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1667. "contractAddress": nil,
  1668. "logs": receipt.Logs,
  1669. "logsBloom": receipt.Bloom,
  1670. }
  1671. // Assign receipt status or post state.
  1672. if len(receipt.PostState) > 0 {
  1673. fields["root"] = hexutil.Bytes(receipt.PostState)
  1674. } else {
  1675. fields["status"] = hexutil.Uint(receipt.Status)
  1676. }
  1677. if receipt.Logs == nil {
  1678. fields["logs"] = [][]*types.Log{}
  1679. }
  1680. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1681. if receipt.ContractAddress != (common.Address{}) {
  1682. fields["contractAddress"] = receipt.ContractAddress
  1683. }
  1684. txReceipts = append(txReceipts, fields)
  1685. }
  1686. return txReceipts, nil
  1687. }
  1688. // GetTransactionDataAndReceipt returns the original transaction data and transaction receipt for the given transaction hash.
  1689. func (s *PublicTransactionPoolAPI) GetTransactionDataAndReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1690. tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
  1691. if tx == nil {
  1692. return nil, nil
  1693. }
  1694. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1695. if err != nil {
  1696. return nil, err
  1697. }
  1698. if len(receipts) <= int(index) {
  1699. return nil, nil
  1700. }
  1701. receipt := receipts[index]
  1702. var signer types.Signer = types.FrontierSigner{}
  1703. if tx.Protected() {
  1704. signer = types.NewEIP155Signer(tx.ChainId())
  1705. }
  1706. from, _ := types.Sender(signer, tx)
  1707. rpcTransaction := newRPCTransaction(tx, blockHash, blockNumber, index)
  1708. txData := map[string]interface{}{
  1709. "blockHash": rpcTransaction.BlockHash.String(),
  1710. "blockNumber": rpcTransaction.BlockNumber.String(),
  1711. "from": rpcTransaction.From.String(),
  1712. "gas": rpcTransaction.Gas.String(),
  1713. "gasPrice": rpcTransaction.GasPrice.String(),
  1714. "hash": rpcTransaction.Hash.String(),
  1715. "input": rpcTransaction.Input.String(),
  1716. "nonce": rpcTransaction.Nonce.String(),
  1717. "to": rpcTransaction.To.String(),
  1718. "transactionIndex": rpcTransaction.TransactionIndex.String(),
  1719. "value": rpcTransaction.Value.String(),
  1720. "v": rpcTransaction.V.String(),
  1721. "r": rpcTransaction.R.String(),
  1722. "s": rpcTransaction.S.String(),
  1723. }
  1724. fields := map[string]interface{}{
  1725. "blockHash": blockHash,
  1726. "blockNumber": hexutil.Uint64(blockNumber),
  1727. "transactionHash": hash,
  1728. "transactionIndex": hexutil.Uint64(index),
  1729. "from": from,
  1730. "to": tx.To(),
  1731. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1732. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1733. "contractAddress": nil,
  1734. "logs": receipt.Logs,
  1735. "logsBloom": receipt.Bloom,
  1736. }
  1737. // Assign receipt status or post state.
  1738. if len(receipt.PostState) > 0 {
  1739. fields["root"] = hexutil.Bytes(receipt.PostState)
  1740. } else {
  1741. fields["status"] = hexutil.Uint(receipt.Status)
  1742. }
  1743. if receipt.Logs == nil {
  1744. fields["logs"] = [][]*types.Log{}
  1745. }
  1746. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1747. if receipt.ContractAddress != (common.Address{}) {
  1748. fields["contractAddress"] = receipt.ContractAddress
  1749. }
  1750. result := map[string]interface{}{
  1751. "txData": txData,
  1752. "receipt": fields,
  1753. }
  1754. return result, nil
  1755. }
  1756. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1757. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1758. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1759. if err != nil {
  1760. return nil, nil
  1761. }
  1762. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1763. if err != nil {
  1764. return nil, err
  1765. }
  1766. if len(receipts) <= int(index) {
  1767. return nil, nil
  1768. }
  1769. receipt := receipts[index]
  1770. // Derive the sender.
  1771. bigblock := new(big.Int).SetUint64(blockNumber)
  1772. signer := types.MakeSigner(s.b.ChainConfig(), bigblock)
  1773. from, _ := types.Sender(signer, tx)
  1774. fields := map[string]interface{}{
  1775. "blockHash": blockHash,
  1776. "blockNumber": hexutil.Uint64(blockNumber),
  1777. "transactionHash": hash,
  1778. "transactionIndex": hexutil.Uint64(index),
  1779. "from": from,
  1780. "to": tx.To(),
  1781. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1782. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1783. "contractAddress": nil,
  1784. "logs": receipt.Logs,
  1785. "logsBloom": receipt.Bloom,
  1786. "type": hexutil.Uint(tx.Type()),
  1787. }
  1788. // Assign receipt status or post state.
  1789. if len(receipt.PostState) > 0 {
  1790. fields["root"] = hexutil.Bytes(receipt.PostState)
  1791. } else {
  1792. fields["status"] = hexutil.Uint(receipt.Status)
  1793. }
  1794. if receipt.Logs == nil {
  1795. fields["logs"] = [][]*types.Log{}
  1796. }
  1797. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1798. if receipt.ContractAddress != (common.Address{}) {
  1799. fields["contractAddress"] = receipt.ContractAddress
  1800. }
  1801. return fields, nil
  1802. }
  1803. // sign is a helper function that signs a transaction with the private key of the given address.
  1804. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1805. // Look up the wallet containing the requested signer
  1806. account := accounts.Account{Address: addr}
  1807. wallet, err := s.b.AccountManager().Find(account)
  1808. if err != nil {
  1809. return nil, err
  1810. }
  1811. // Request the wallet to sign the transaction
  1812. return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1813. }
  1814. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1815. type SendTxArgs struct {
  1816. From common.Address `json:"from"`
  1817. To *common.Address `json:"to"`
  1818. Gas *hexutil.Uint64 `json:"gas"`
  1819. GasPrice *hexutil.Big `json:"gasPrice"`
  1820. Value *hexutil.Big `json:"value"`
  1821. Nonce *hexutil.Uint64 `json:"nonce"`
  1822. // We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1823. // newer name and should be preferred by clients.
  1824. Data *hexutil.Bytes `json:"data"`
  1825. Input *hexutil.Bytes `json:"input"`
  1826. // For non-legacy transactions
  1827. AccessList *types.AccessList `json:"accessList,omitempty"`
  1828. ChainID *hexutil.Big `json:"chainId,omitempty"`
  1829. }
  1830. // setDefaults fills in default values for unspecified tx fields.
  1831. func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1832. if args.GasPrice == nil {
  1833. price, err := b.SuggestPrice(ctx)
  1834. if err != nil {
  1835. return err
  1836. }
  1837. args.GasPrice = (*hexutil.Big)(price)
  1838. }
  1839. if args.Value == nil {
  1840. args.Value = new(hexutil.Big)
  1841. }
  1842. if args.Nonce == nil {
  1843. nonce, err := b.GetPoolNonce(ctx, args.From)
  1844. if err != nil {
  1845. return err
  1846. }
  1847. args.Nonce = (*hexutil.Uint64)(&nonce)
  1848. }
  1849. if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1850. return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
  1851. }
  1852. if args.To == nil {
  1853. // Contract creation
  1854. var input []byte
  1855. if args.Data != nil {
  1856. input = *args.Data
  1857. } else if args.Input != nil {
  1858. input = *args.Input
  1859. }
  1860. if len(input) == 0 {
  1861. return errors.New(`contract creation without any data provided`)
  1862. }
  1863. }
  1864. // Estimate the gas usage if necessary.
  1865. if args.Gas == nil {
  1866. // For backwards-compatibility reason, we try both input and data
  1867. // but input is preferred.
  1868. input := args.Input
  1869. if input == nil {
  1870. input = args.Data
  1871. }
  1872. callArgs := CallArgs{
  1873. From: &args.From, // From shouldn't be nil
  1874. To: args.To,
  1875. GasPrice: args.GasPrice,
  1876. Value: args.Value,
  1877. Data: input,
  1878. AccessList: args.AccessList,
  1879. }
  1880. pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1881. estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
  1882. if err != nil {
  1883. return err
  1884. }
  1885. args.Gas = &estimated
  1886. log.Trace("Estimate gas usage automatically", "gas", args.Gas)
  1887. }
  1888. if args.ChainID == nil {
  1889. id := (*hexutil.Big)(b.ChainConfig().ChainID)
  1890. args.ChainID = id
  1891. }
  1892. return nil
  1893. }
  1894. // toTransaction converts the arguments to a transaction.
  1895. // This assumes that setDefaults has been called.
  1896. func (args *SendTxArgs) toTransaction() *types.Transaction {
  1897. var input []byte
  1898. if args.Input != nil {
  1899. input = *args.Input
  1900. } else if args.Data != nil {
  1901. input = *args.Data
  1902. }
  1903. var data types.TxData
  1904. if args.AccessList == nil {
  1905. data = &types.LegacyTx{
  1906. To: args.To,
  1907. Nonce: uint64(*args.Nonce),
  1908. Gas: uint64(*args.Gas),
  1909. GasPrice: (*big.Int)(args.GasPrice),
  1910. Value: (*big.Int)(args.Value),
  1911. Data: input,
  1912. }
  1913. } else {
  1914. data = &types.AccessListTx{
  1915. To: args.To,
  1916. ChainID: (*big.Int)(args.ChainID),
  1917. Nonce: uint64(*args.Nonce),
  1918. Gas: uint64(*args.Gas),
  1919. GasPrice: (*big.Int)(args.GasPrice),
  1920. Value: (*big.Int)(args.Value),
  1921. Data: input,
  1922. AccessList: *args.AccessList,
  1923. }
  1924. }
  1925. return types.NewTx(data)
  1926. }
  1927. // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1928. func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1929. // If the transaction fee cap is already specified, ensure the
  1930. // fee of the given transaction is _reasonable_.
  1931. if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil {
  1932. return common.Hash{}, err
  1933. }
  1934. if !b.UnprotectedAllowed() && !tx.Protected() {
  1935. // Ensure only eip155 signed transactions are submitted if EIP155Required is set.
  1936. return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed over RPC")
  1937. }
  1938. if err := b.SendTx(ctx, tx); err != nil {
  1939. return common.Hash{}, err
  1940. }
  1941. // Print a log with full tx details for manual investigations and interventions
  1942. signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1943. from, err := types.Sender(signer, tx)
  1944. if err != nil {
  1945. return common.Hash{}, err
  1946. }
  1947. if tx.To() == nil {
  1948. addr := crypto.CreateAddress(from, tx.Nonce())
  1949. log.Info("Submitted contract creation", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "contract", addr.Hex(), "value", tx.Value())
  1950. } else {
  1951. log.Info("Submitted transaction", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "recipient", tx.To(), "value", tx.Value())
  1952. }
  1953. return tx.Hash(), nil
  1954. }
  1955. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1956. // transaction pool.
  1957. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1958. // Look up the wallet containing the requested signer
  1959. account := accounts.Account{Address: args.From}
  1960. wallet, err := s.b.AccountManager().Find(account)
  1961. if err != nil {
  1962. return common.Hash{}, err
  1963. }
  1964. if args.Nonce == nil {
  1965. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  1966. // the same nonce to multiple accounts.
  1967. s.nonceLock.LockAddr(args.From)
  1968. defer s.nonceLock.UnlockAddr(args.From)
  1969. }
  1970. // Set some sanity defaults and terminate on failure
  1971. if err := args.setDefaults(ctx, s.b); err != nil {
  1972. return common.Hash{}, err
  1973. }
  1974. // Assemble the transaction and sign with the wallet
  1975. tx := args.toTransaction()
  1976. signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1977. if err != nil {
  1978. return common.Hash{}, err
  1979. }
  1980. return SubmitTransaction(ctx, s.b, signed)
  1981. }
  1982. // FillTransaction fills the defaults (nonce, gas, gasPrice) on a given unsigned transaction,
  1983. // and returns it to the caller for further processing (signing + broadcast)
  1984. func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1985. // Set some sanity defaults and terminate on failure
  1986. if err := args.setDefaults(ctx, s.b); err != nil {
  1987. return nil, err
  1988. }
  1989. // Assemble the transaction and obtain rlp
  1990. tx := args.toTransaction()
  1991. data, err := tx.MarshalBinary()
  1992. if err != nil {
  1993. return nil, err
  1994. }
  1995. return &SignTransactionResult{data, tx}, nil
  1996. }
  1997. // SendRawTransaction will add the signed transaction to the transaction pool.
  1998. // The sender is responsible for signing the transaction and using the correct nonce.
  1999. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) {
  2000. tx := new(types.Transaction)
  2001. if err := tx.UnmarshalBinary(input); err != nil {
  2002. return common.Hash{}, err
  2003. }
  2004. return SubmitTransaction(ctx, s.b, tx)
  2005. }
  2006. // Sign calculates an ECDSA signature for:
  2007. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  2008. //
  2009. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  2010. // where the V value will be 27 or 28 for legacy reasons.
  2011. //
  2012. // The account associated with addr must be unlocked.
  2013. //
  2014. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  2015. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  2016. // Look up the wallet containing the requested signer
  2017. account := accounts.Account{Address: addr}
  2018. wallet, err := s.b.AccountManager().Find(account)
  2019. if err != nil {
  2020. return nil, err
  2021. }
  2022. // Sign the requested hash with the wallet
  2023. signature, err := wallet.SignText(account, data)
  2024. if err == nil {
  2025. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  2026. }
  2027. return signature, err
  2028. }
  2029. // SignTransactionResult represents a RLP encoded signed transaction.
  2030. type SignTransactionResult struct {
  2031. Raw hexutil.Bytes `json:"raw"`
  2032. Tx *types.Transaction `json:"tx"`
  2033. }
  2034. // SignTransaction will sign the given transaction with the from account.
  2035. // The node needs to have the private key of the account corresponding with
  2036. // the given from address and it needs to be unlocked.
  2037. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  2038. if args.Gas == nil {
  2039. return nil, fmt.Errorf("gas not specified")
  2040. }
  2041. if args.GasPrice == nil {
  2042. return nil, fmt.Errorf("gasPrice not specified")
  2043. }
  2044. if args.Nonce == nil {
  2045. return nil, fmt.Errorf("nonce not specified")
  2046. }
  2047. if err := args.setDefaults(ctx, s.b); err != nil {
  2048. return nil, err
  2049. }
  2050. // Before actually sign the transaction, ensure the transaction fee is reasonable.
  2051. if err := checkTxFee(args.GasPrice.ToInt(), uint64(*args.Gas), s.b.RPCTxFeeCap()); err != nil {
  2052. return nil, err
  2053. }
  2054. tx, err := s.sign(args.From, args.toTransaction())
  2055. if err != nil {
  2056. return nil, err
  2057. }
  2058. data, err := tx.MarshalBinary()
  2059. if err != nil {
  2060. return nil, err
  2061. }
  2062. return &SignTransactionResult{data, tx}, nil
  2063. }
  2064. // PendingTransactions returns the transactions that are in the transaction pool
  2065. // and have a from address that is one of the accounts this node manages.
  2066. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  2067. pending, err := s.b.GetPoolTransactions()
  2068. if err != nil {
  2069. return nil, err
  2070. }
  2071. accounts := make(map[common.Address]struct{})
  2072. for _, wallet := range s.b.AccountManager().Wallets() {
  2073. for _, account := range wallet.Accounts() {
  2074. accounts[account.Address] = struct{}{}
  2075. }
  2076. }
  2077. transactions := make([]*RPCTransaction, 0, len(pending))
  2078. for _, tx := range pending {
  2079. from, _ := types.Sender(s.signer, tx)
  2080. if _, exists := accounts[from]; exists {
  2081. transactions = append(transactions, newRPCPendingTransaction(tx))
  2082. }
  2083. }
  2084. return transactions, nil
  2085. }
  2086. // Resend accepts an existing transaction and a new gas price and limit. It will remove
  2087. // the given transaction from the pool and reinsert it with the new gas price and limit.
  2088. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  2089. if sendArgs.Nonce == nil {
  2090. return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  2091. }
  2092. if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  2093. return common.Hash{}, err
  2094. }
  2095. matchTx := sendArgs.toTransaction()
  2096. // Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.
  2097. var price = matchTx.GasPrice()
  2098. if gasPrice != nil {
  2099. price = gasPrice.ToInt()
  2100. }
  2101. var gas = matchTx.Gas()
  2102. if gasLimit != nil {
  2103. gas = uint64(*gasLimit)
  2104. }
  2105. if err := checkTxFee(price, gas, s.b.RPCTxFeeCap()); err != nil {
  2106. return common.Hash{}, err
  2107. }
  2108. // Iterate the pending list for replacement
  2109. pending, err := s.b.GetPoolTransactions()
  2110. if err != nil {
  2111. return common.Hash{}, err
  2112. }
  2113. for _, p := range pending {
  2114. wantSigHash := s.signer.Hash(matchTx)
  2115. pFrom, err := types.Sender(s.signer, p)
  2116. if err == nil && pFrom == sendArgs.From && s.signer.Hash(p) == wantSigHash {
  2117. // Match. Re-sign and send the transaction.
  2118. if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  2119. sendArgs.GasPrice = gasPrice
  2120. }
  2121. if gasLimit != nil && *gasLimit != 0 {
  2122. sendArgs.Gas = gasLimit
  2123. }
  2124. signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  2125. if err != nil {
  2126. return common.Hash{}, err
  2127. }
  2128. if err = s.b.SendTx(ctx, signedTx); err != nil {
  2129. return common.Hash{}, err
  2130. }
  2131. return signedTx.Hash(), nil
  2132. }
  2133. }
  2134. return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  2135. }
  2136. // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  2137. // debugging endpoint.
  2138. type PublicDebugAPI struct {
  2139. b Backend
  2140. }
  2141. // NewPublicDebugAPI creates a new API definition for the public debug methods
  2142. // of the Ethereum service.
  2143. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  2144. return &PublicDebugAPI{b: b}
  2145. }
  2146. // GetBlockRlp retrieves the RLP encoded for of a single block.
  2147. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  2148. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2149. if block == nil {
  2150. return "", fmt.Errorf("block #%d not found", number)
  2151. }
  2152. encoded, err := rlp.EncodeToBytes(block)
  2153. if err != nil {
  2154. return "", err
  2155. }
  2156. return fmt.Sprintf("%x", encoded), nil
  2157. }
  2158. // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  2159. // given address, returning the address of the recovered signature
  2160. //
  2161. // This is a temporary method to debug the externalsigner integration,
  2162. // TODO: Remove this method when the integration is mature
  2163. func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  2164. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2165. if block == nil {
  2166. return common.Address{}, fmt.Errorf("block #%d not found", number)
  2167. }
  2168. header := block.Header()
  2169. header.Extra = make([]byte, 32+65)
  2170. encoded := clique.CliqueRLP(header)
  2171. // Look up the wallet containing the requested signer
  2172. account := accounts.Account{Address: address}
  2173. wallet, err := api.b.AccountManager().Find(account)
  2174. if err != nil {
  2175. return common.Address{}, err
  2176. }
  2177. signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  2178. if err != nil {
  2179. return common.Address{}, err
  2180. }
  2181. sealHash := clique.SealHash(header).Bytes()
  2182. log.Info("test signing of clique block",
  2183. "Sealhash", fmt.Sprintf("%x", sealHash),
  2184. "signature", fmt.Sprintf("%x", signature))
  2185. pubkey, err := crypto.Ecrecover(sealHash, signature)
  2186. if err != nil {
  2187. return common.Address{}, err
  2188. }
  2189. var signer common.Address
  2190. copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  2191. return signer, nil
  2192. }
  2193. // PrintBlock retrieves a block and returns its pretty printed form.
  2194. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  2195. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2196. if block == nil {
  2197. return "", fmt.Errorf("block #%d not found", number)
  2198. }
  2199. return spew.Sdump(block), nil
  2200. }
  2201. // SeedHash retrieves the seed hash of a block.
  2202. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  2203. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2204. if block == nil {
  2205. return "", fmt.Errorf("block #%d not found", number)
  2206. }
  2207. return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  2208. }
  2209. // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  2210. // debugging endpoint.
  2211. type PrivateDebugAPI struct {
  2212. b Backend
  2213. }
  2214. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  2215. // of the Ethereum service.
  2216. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  2217. return &PrivateDebugAPI{b: b}
  2218. }
  2219. // ChaindbProperty returns leveldb properties of the key-value database.
  2220. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  2221. if property == "" {
  2222. property = "leveldb.stats"
  2223. } else if !strings.HasPrefix(property, "leveldb.") {
  2224. property = "leveldb." + property
  2225. }
  2226. return api.b.ChainDb().Stat(property)
  2227. }
  2228. // ChaindbCompact flattens the entire key-value database into a single level,
  2229. // removing all unused slots and merging all keys.
  2230. func (api *PrivateDebugAPI) ChaindbCompact() error {
  2231. for b := byte(0); b < 255; b++ {
  2232. log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  2233. if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  2234. log.Error("Database compaction failed", "err", err)
  2235. return err
  2236. }
  2237. }
  2238. return nil
  2239. }
  2240. // SetHead rewinds the head of the blockchain to a previous block.
  2241. func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  2242. api.b.SetHead(uint64(number))
  2243. }
  2244. // PublicNetAPI offers network related RPC methods
  2245. type PublicNetAPI struct {
  2246. net *p2p.Server
  2247. networkVersion uint64
  2248. }
  2249. // NewPublicNetAPI creates a new net API instance.
  2250. func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  2251. return &PublicNetAPI{net, networkVersion}
  2252. }
  2253. // Listening returns an indication if the node is listening for network connections.
  2254. func (s *PublicNetAPI) Listening() bool {
  2255. return true // always listening
  2256. }
  2257. // PeerCount returns the number of connected peers
  2258. func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  2259. return hexutil.Uint(s.net.PeerCount())
  2260. }
  2261. // Version returns the current ethereum protocol version.
  2262. func (s *PublicNetAPI) Version() string {
  2263. return fmt.Sprintf("%d", s.networkVersion)
  2264. }
  2265. // checkTxFee is an internal function used to check whether the fee of
  2266. // the given transaction is _reasonable_(under the cap).
  2267. func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error {
  2268. // Short circuit if there is no cap for transaction fee at all.
  2269. if cap == 0 {
  2270. return nil
  2271. }
  2272. 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)))
  2273. feeFloat, _ := feeEth.Float64()
  2274. if feeFloat > cap {
  2275. return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap)
  2276. }
  2277. return nil
  2278. }
  2279. // toHexSlice creates a slice of hex-strings based on []byte.
  2280. func toHexSlice(b [][]byte) []string {
  2281. r := make([]string, len(b))
  2282. for i := range b {
  2283. r[i] = hexutil.Encode(b[i])
  2284. }
  2285. return r
  2286. }