api.go 80 KB

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