api.go 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package ethapi
  17. import (
  18. "bytes"
  19. "context"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "strings"
  24. "time"
  25. "github.com/davecgh/go-spew/spew"
  26. "github.com/ethereum/go-ethereum/accounts"
  27. "github.com/ethereum/go-ethereum/accounts/abi"
  28. "github.com/ethereum/go-ethereum/accounts/keystore"
  29. "github.com/ethereum/go-ethereum/accounts/scwallet"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/common/hexutil"
  32. "github.com/ethereum/go-ethereum/common/math"
  33. "github.com/ethereum/go-ethereum/consensus/clique"
  34. "github.com/ethereum/go-ethereum/consensus/ethash"
  35. "github.com/ethereum/go-ethereum/core"
  36. "github.com/ethereum/go-ethereum/core/types"
  37. "github.com/ethereum/go-ethereum/core/vm"
  38. "github.com/ethereum/go-ethereum/crypto"
  39. "github.com/ethereum/go-ethereum/log"
  40. "github.com/ethereum/go-ethereum/p2p"
  41. "github.com/ethereum/go-ethereum/params"
  42. "github.com/ethereum/go-ethereum/rlp"
  43. "github.com/ethereum/go-ethereum/rpc"
  44. "github.com/tyler-smith/go-bip39"
  45. )
  46. // PublicEthereumAPI provides an API to access Ethereum related information.
  47. // It offers only methods that operate on public data that is freely available to anyone.
  48. type PublicEthereumAPI struct {
  49. b Backend
  50. }
  51. // NewPublicEthereumAPI creates a new Ethereum protocol API.
  52. func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
  53. return &PublicEthereumAPI{b}
  54. }
  55. // GasPrice returns a suggestion for a gas price.
  56. func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
  57. price, err := s.b.SuggestPrice(ctx)
  58. return (*hexutil.Big)(price), err
  59. }
  60. // ProtocolVersion returns the current Ethereum protocol version this node supports
  61. func (s *PublicEthereumAPI) ProtocolVersion() hexutil.Uint {
  62. return hexutil.Uint(s.b.ProtocolVersion())
  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.To. 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.To. 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. signed, err := s.signTransaction(ctx, &args, passwd)
  373. if err != nil {
  374. log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  375. return nil, err
  376. }
  377. data, err := rlp.EncodeToBytes(signed)
  378. if err != nil {
  379. return nil, err
  380. }
  381. return &SignTransactionResult{data, signed}, nil
  382. }
  383. // Sign calculates an Ethereum ECDSA signature for:
  384. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  385. //
  386. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  387. // where the V value will be 27 or 28 for legacy reasons.
  388. //
  389. // The key used to calculate the signature is decrypted with the given password.
  390. //
  391. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  392. func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
  393. // Look up the wallet containing the requested signer
  394. account := accounts.Account{Address: addr}
  395. wallet, err := s.b.AccountManager().Find(account)
  396. if err != nil {
  397. return nil, err
  398. }
  399. // Assemble sign the data with the wallet
  400. signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
  401. if err != nil {
  402. log.Warn("Failed data sign attempt", "address", addr, "err", err)
  403. return nil, err
  404. }
  405. signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  406. return signature, nil
  407. }
  408. // EcRecover returns the address for the account that was used to create the signature.
  409. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  410. // the address of:
  411. // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
  412. // addr = ecrecover(hash, signature)
  413. //
  414. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  415. // the V value must be 27 or 28 for legacy reasons.
  416. //
  417. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  418. func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
  419. if len(sig) != crypto.SignatureLength {
  420. return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
  421. }
  422. if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 {
  423. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  424. }
  425. sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1
  426. rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
  427. if err != nil {
  428. return common.Address{}, err
  429. }
  430. return crypto.PubkeyToAddress(*rpk), nil
  431. }
  432. // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
  433. // and will be removed in the future. It primary goal is to give clients time to update.
  434. func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  435. return s.SendTransaction(ctx, args, passwd)
  436. }
  437. // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
  438. func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
  439. wallet, err := s.am.Wallet(url)
  440. if err != nil {
  441. return "", err
  442. }
  443. entropy, err := bip39.NewEntropy(256)
  444. if err != nil {
  445. return "", err
  446. }
  447. mnemonic, err := bip39.NewMnemonic(entropy)
  448. if err != nil {
  449. return "", err
  450. }
  451. seed := bip39.NewSeed(mnemonic, "")
  452. switch wallet := wallet.(type) {
  453. case *scwallet.Wallet:
  454. return mnemonic, wallet.Initialize(seed)
  455. default:
  456. return "", fmt.Errorf("specified wallet does not support initialization")
  457. }
  458. }
  459. // Unpair deletes a pairing between wallet and geth.
  460. func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
  461. wallet, err := s.am.Wallet(url)
  462. if err != nil {
  463. return err
  464. }
  465. switch wallet := wallet.(type) {
  466. case *scwallet.Wallet:
  467. return wallet.Unpair([]byte(pin))
  468. default:
  469. return fmt.Errorf("specified wallet does not support pairing")
  470. }
  471. }
  472. // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
  473. // It offers only methods that operate on public data that is freely available to anyone.
  474. type PublicBlockChainAPI struct {
  475. b Backend
  476. }
  477. // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
  478. func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
  479. return &PublicBlockChainAPI{b}
  480. }
  481. // ChainId returns the chainID value for transaction replay protection.
  482. func (s *PublicBlockChainAPI) ChainId() *hexutil.Big {
  483. return (*hexutil.Big)(s.b.ChainConfig().ChainID)
  484. }
  485. // BlockNumber returns the block number of the chain head.
  486. func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
  487. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
  488. return hexutil.Uint64(header.Number.Uint64())
  489. }
  490. // GetBalance returns the amount of wei for the given address in the state of the
  491. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  492. // block numbers are also allowed.
  493. func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
  494. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  495. if state == nil || err != nil {
  496. return nil, err
  497. }
  498. return (*hexutil.Big)(state.GetBalance(address)), state.Error()
  499. }
  500. // Result structs for GetProof
  501. type AccountResult struct {
  502. Address common.Address `json:"address"`
  503. AccountProof []string `json:"accountProof"`
  504. Balance *hexutil.Big `json:"balance"`
  505. CodeHash common.Hash `json:"codeHash"`
  506. Nonce hexutil.Uint64 `json:"nonce"`
  507. StorageHash common.Hash `json:"storageHash"`
  508. StorageProof []StorageResult `json:"storageProof"`
  509. }
  510. type StorageResult struct {
  511. Key string `json:"key"`
  512. Value *hexutil.Big `json:"value"`
  513. Proof []string `json:"proof"`
  514. }
  515. // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
  516. func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
  517. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  518. if state == nil || err != nil {
  519. return nil, err
  520. }
  521. storageTrie := state.StorageTrie(address)
  522. storageHash := types.EmptyRootHash
  523. codeHash := state.GetCodeHash(address)
  524. storageProof := make([]StorageResult, len(storageKeys))
  525. // if we have a storageTrie, (which means the account exists), we can update the storagehash
  526. if storageTrie != nil {
  527. storageHash = storageTrie.Hash()
  528. } else {
  529. // no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
  530. codeHash = crypto.Keccak256Hash(nil)
  531. }
  532. // create the proof for the storageKeys
  533. for i, key := range storageKeys {
  534. if storageTrie != nil {
  535. proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
  536. if storageError != nil {
  537. return nil, storageError
  538. }
  539. storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), common.ToHexArray(proof)}
  540. } else {
  541. storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
  542. }
  543. }
  544. // create the accountProof
  545. accountProof, proofErr := state.GetProof(address)
  546. if proofErr != nil {
  547. return nil, proofErr
  548. }
  549. return &AccountResult{
  550. Address: address,
  551. AccountProof: common.ToHexArray(accountProof),
  552. Balance: (*hexutil.Big)(state.GetBalance(address)),
  553. CodeHash: codeHash,
  554. Nonce: hexutil.Uint64(state.GetNonce(address)),
  555. StorageHash: storageHash,
  556. StorageProof: storageProof,
  557. }, state.Error()
  558. }
  559. // GetHeaderByNumber returns the requested canonical block header.
  560. // * When blockNr is -1 the chain head is returned.
  561. // * When blockNr is -2 the pending chain head is returned.
  562. func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
  563. header, err := s.b.HeaderByNumber(ctx, number)
  564. if header != nil && err == nil {
  565. response := s.rpcMarshalHeader(ctx, header)
  566. if number == rpc.PendingBlockNumber {
  567. // Pending header need to nil out a few fields
  568. for _, field := range []string{"hash", "nonce", "miner"} {
  569. response[field] = nil
  570. }
  571. }
  572. return response, err
  573. }
  574. return nil, err
  575. }
  576. // GetHeaderByHash returns the requested header by hash.
  577. func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
  578. header, _ := s.b.HeaderByHash(ctx, hash)
  579. if header != nil {
  580. return s.rpcMarshalHeader(ctx, header)
  581. }
  582. return nil
  583. }
  584. // GetBlockByNumber returns the requested canonical block.
  585. // * When blockNr is -1 the chain head is returned.
  586. // * When blockNr is -2 the pending chain head is returned.
  587. // * When fullTx is true all transactions in the block are returned, otherwise
  588. // only the transaction hash is returned.
  589. func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  590. block, err := s.b.BlockByNumber(ctx, number)
  591. if block != nil && err == nil {
  592. response, err := s.rpcMarshalBlock(ctx, block, true, fullTx)
  593. if err == nil && number == rpc.PendingBlockNumber {
  594. // Pending blocks need to nil out a few fields
  595. for _, field := range []string{"hash", "nonce", "miner"} {
  596. response[field] = nil
  597. }
  598. }
  599. return response, err
  600. }
  601. return nil, err
  602. }
  603. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  604. // detail, otherwise only the transaction hash is returned.
  605. func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
  606. block, err := s.b.BlockByHash(ctx, hash)
  607. if block != nil {
  608. return s.rpcMarshalBlock(ctx, block, true, fullTx)
  609. }
  610. return nil, err
  611. }
  612. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  613. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  614. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
  615. block, err := s.b.BlockByNumber(ctx, blockNr)
  616. if block != nil {
  617. uncles := block.Uncles()
  618. if index >= hexutil.Uint(len(uncles)) {
  619. log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
  620. return nil, nil
  621. }
  622. block = types.NewBlockWithHeader(uncles[index])
  623. return s.rpcMarshalBlock(ctx, block, false, false)
  624. }
  625. return nil, err
  626. }
  627. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  628. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  629. func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
  630. block, err := s.b.BlockByHash(ctx, blockHash)
  631. if block != nil {
  632. uncles := block.Uncles()
  633. if index >= hexutil.Uint(len(uncles)) {
  634. log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
  635. return nil, nil
  636. }
  637. block = types.NewBlockWithHeader(uncles[index])
  638. return s.rpcMarshalBlock(ctx, block, false, false)
  639. }
  640. return nil, err
  641. }
  642. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  643. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  644. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  645. n := hexutil.Uint(len(block.Uncles()))
  646. return &n
  647. }
  648. return nil
  649. }
  650. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  651. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  652. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  653. n := hexutil.Uint(len(block.Uncles()))
  654. return &n
  655. }
  656. return nil
  657. }
  658. // GetCode returns the code stored at the given address in the state for the given block number.
  659. func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  660. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  661. if state == nil || err != nil {
  662. return nil, err
  663. }
  664. code := state.GetCode(address)
  665. return code, state.Error()
  666. }
  667. // GetStorageAt returns the storage from the state at the given address, key and
  668. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  669. // numbers are also allowed.
  670. func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  671. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  672. if state == nil || err != nil {
  673. return nil, err
  674. }
  675. res := state.GetState(address, common.HexToHash(key))
  676. return res[:], state.Error()
  677. }
  678. // CallArgs represents the arguments for a call.
  679. type CallArgs struct {
  680. From *common.Address `json:"from"`
  681. To *common.Address `json:"to"`
  682. Gas *hexutil.Uint64 `json:"gas"`
  683. GasPrice *hexutil.Big `json:"gasPrice"`
  684. Value *hexutil.Big `json:"value"`
  685. Data *hexutil.Bytes `json:"data"`
  686. }
  687. // ToMessage converts CallArgs to the Message type used by the core evm
  688. func (args *CallArgs) ToMessage(globalGasCap uint64) types.Message {
  689. // Set sender address or use zero address if none specified.
  690. var addr common.Address
  691. if args.From != nil {
  692. addr = *args.From
  693. }
  694. // Set default gas & gas price if none were set
  695. gas := globalGasCap
  696. if gas == 0 {
  697. gas = uint64(math.MaxUint64 / 2)
  698. }
  699. if args.Gas != nil {
  700. gas = uint64(*args.Gas)
  701. }
  702. if globalGasCap != 0 && globalGasCap < gas {
  703. log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
  704. gas = globalGasCap
  705. }
  706. gasPrice := new(big.Int)
  707. if args.GasPrice != nil {
  708. gasPrice = args.GasPrice.ToInt()
  709. }
  710. value := new(big.Int)
  711. if args.Value != nil {
  712. value = args.Value.ToInt()
  713. }
  714. var data []byte
  715. if args.Data != nil {
  716. data = []byte(*args.Data)
  717. }
  718. msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, data, false)
  719. return msg
  720. }
  721. // account indicates the overriding fields of account during the execution of
  722. // a message call.
  723. // Note, state and stateDiff can't be specified at the same time. If state is
  724. // set, message execution will only use the data in the given state. Otherwise
  725. // if statDiff is set, all diff will be applied first and then execute the call
  726. // message.
  727. type account struct {
  728. Nonce *hexutil.Uint64 `json:"nonce"`
  729. Code *hexutil.Bytes `json:"code"`
  730. Balance **hexutil.Big `json:"balance"`
  731. State *map[common.Hash]common.Hash `json:"state"`
  732. StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
  733. }
  734. func DoCall(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides map[common.Address]account, vmCfg vm.Config, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
  735. defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  736. state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  737. if state == nil || err != nil {
  738. return nil, err
  739. }
  740. // Override the fields of specified contracts before execution.
  741. for addr, account := range overrides {
  742. // Override account nonce.
  743. if account.Nonce != nil {
  744. state.SetNonce(addr, uint64(*account.Nonce))
  745. }
  746. // Override account(contract) code.
  747. if account.Code != nil {
  748. state.SetCode(addr, *account.Code)
  749. }
  750. // Override account balance.
  751. if account.Balance != nil {
  752. state.SetBalance(addr, (*big.Int)(*account.Balance))
  753. }
  754. if account.State != nil && account.StateDiff != nil {
  755. return nil, fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
  756. }
  757. // Replace entire state if caller requires.
  758. if account.State != nil {
  759. state.SetStorage(addr, *account.State)
  760. }
  761. // Apply state diff into specified accounts.
  762. if account.StateDiff != nil {
  763. for key, value := range *account.StateDiff {
  764. state.SetState(addr, key, value)
  765. }
  766. }
  767. }
  768. // Setup context so it may be cancelled the call has completed
  769. // or, in case of unmetered gas, setup a context with a timeout.
  770. var cancel context.CancelFunc
  771. if timeout > 0 {
  772. ctx, cancel = context.WithTimeout(ctx, timeout)
  773. } else {
  774. ctx, cancel = context.WithCancel(ctx)
  775. }
  776. // Make sure the context is cancelled when the call has completed
  777. // this makes sure resources are cleaned up.
  778. defer cancel()
  779. // Get a new instance of the EVM.
  780. msg := args.ToMessage(globalGasCap)
  781. evm, vmError, err := b.GetEVM(ctx, msg, state, header)
  782. if err != nil {
  783. return nil, err
  784. }
  785. // Wait for the context to be done and cancel the evm. Even if the
  786. // EVM has finished, cancelling may be done (repeatedly)
  787. go func() {
  788. <-ctx.Done()
  789. evm.Cancel()
  790. }()
  791. // Setup the gas pool (also for unmetered requests)
  792. // and apply the message.
  793. gp := new(core.GasPool).AddGas(math.MaxUint64)
  794. result, err := core.ApplyMessage(evm, msg, gp)
  795. if err := vmError(); err != nil {
  796. return nil, err
  797. }
  798. // If the timer caused an abort, return an appropriate error message
  799. if evm.Cancelled() {
  800. return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
  801. }
  802. if err != nil {
  803. return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas())
  804. }
  805. return result, nil
  806. }
  807. func newRevertError(result *core.ExecutionResult) *revertError {
  808. reason, errUnpack := abi.UnpackRevert(result.Revert())
  809. err := errors.New("execution reverted")
  810. if errUnpack == nil {
  811. err = fmt.Errorf("execution reverted: %v", reason)
  812. }
  813. return &revertError{
  814. error: err,
  815. reason: hexutil.Encode(result.Revert()),
  816. }
  817. }
  818. // revertError is an API error that encompassas an EVM revertal with JSON error
  819. // code and a binary data blob.
  820. type revertError struct {
  821. error
  822. reason string // revert reason hex encoded
  823. }
  824. // ErrorCode returns the JSON error code for a revertal.
  825. // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
  826. func (e *revertError) ErrorCode() int {
  827. return 3
  828. }
  829. // ErrorData returns the hex encoded revert reason.
  830. func (e *revertError) ErrorData() interface{} {
  831. return e.reason
  832. }
  833. // Call executes the given transaction on the state for the given block number.
  834. //
  835. // Additionally, the caller can specify a batch of contract for fields overriding.
  836. //
  837. // Note, this function doesn't make and changes in the state/blockchain and is
  838. // useful to execute and retrieve values.
  839. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *map[common.Address]account) (hexutil.Bytes, error) {
  840. var accounts map[common.Address]account
  841. if overrides != nil {
  842. accounts = *overrides
  843. }
  844. result, err := DoCall(ctx, s.b, args, blockNrOrHash, accounts, vm.Config{}, 5*time.Second, s.b.RPCGasCap())
  845. if err != nil {
  846. return nil, err
  847. }
  848. // If the result contains a revert reason, try to unpack and return it.
  849. if len(result.Revert()) > 0 {
  850. return nil, newRevertError(result)
  851. }
  852. return result.Return(), result.Err
  853. }
  854. func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) {
  855. // Binary search the gas requirement, as it may be higher than the amount used
  856. var (
  857. lo uint64 = params.TxGas - 1
  858. hi uint64
  859. cap uint64
  860. )
  861. // Use zero address if sender unspecified.
  862. if args.From == nil {
  863. args.From = new(common.Address)
  864. }
  865. // Determine the highest gas limit can be used during the estimation.
  866. if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  867. hi = uint64(*args.Gas)
  868. } else {
  869. // Retrieve the block to act as the gas ceiling
  870. block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
  871. if err != nil {
  872. return 0, err
  873. }
  874. hi = block.GasLimit()
  875. }
  876. // Recap the highest gas limit with account's available balance.
  877. if args.GasPrice != nil && args.GasPrice.ToInt().Uint64() != 0 {
  878. state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  879. if err != nil {
  880. return 0, err
  881. }
  882. balance := state.GetBalance(*args.From) // from can't be nil
  883. available := new(big.Int).Set(balance)
  884. if args.Value != nil {
  885. if args.Value.ToInt().Cmp(available) >= 0 {
  886. return 0, errors.New("insufficient funds for transfer")
  887. }
  888. available.Sub(available, args.Value.ToInt())
  889. }
  890. allowance := new(big.Int).Div(available, args.GasPrice.ToInt())
  891. if hi > allowance.Uint64() {
  892. transfer := args.Value
  893. if transfer == nil {
  894. transfer = new(hexutil.Big)
  895. }
  896. log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
  897. "sent", transfer.ToInt(), "gasprice", args.GasPrice.ToInt(), "fundable", allowance)
  898. hi = allowance.Uint64()
  899. }
  900. }
  901. // Recap the highest gas allowance with specified gascap.
  902. if gasCap != 0 && hi > gasCap {
  903. log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  904. hi = gasCap
  905. }
  906. cap = hi
  907. // Create a helper to check if a gas allowance results in an executable transaction
  908. executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
  909. args.Gas = (*hexutil.Uint64)(&gas)
  910. result, err := DoCall(ctx, b, args, blockNrOrHash, nil, vm.Config{}, 0, gasCap)
  911. if err != nil {
  912. if errors.Is(err, core.ErrIntrinsicGas) {
  913. return true, nil, nil // Special case, raise gas limit
  914. }
  915. return true, nil, err // Bail out
  916. }
  917. return result.Failed(), result, nil
  918. }
  919. // Execute the binary search and hone in on an executable gas limit
  920. for lo+1 < hi {
  921. mid := (hi + lo) / 2
  922. failed, _, err := executable(mid)
  923. // If the error is not nil(consensus error), it means the provided message
  924. // call or transaction will never be accepted no matter how much gas it is
  925. // assigned. Return the error directly, don't struggle any more.
  926. if err != nil {
  927. return 0, err
  928. }
  929. if failed {
  930. lo = mid
  931. } else {
  932. hi = mid
  933. }
  934. }
  935. // Reject the transaction as invalid if it still fails at the highest allowance
  936. if hi == cap {
  937. failed, result, err := executable(hi)
  938. if err != nil {
  939. return 0, err
  940. }
  941. if failed {
  942. if result != nil && result.Err != vm.ErrOutOfGas {
  943. if len(result.Revert()) > 0 {
  944. return 0, newRevertError(result)
  945. }
  946. return 0, result.Err
  947. }
  948. // Otherwise, the specified gas cap is too low
  949. return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
  950. }
  951. }
  952. return hexutil.Uint64(hi), nil
  953. }
  954. // EstimateGas returns an estimate of the amount of gas needed to execute the
  955. // given transaction against the current pending block.
  956. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) {
  957. blockNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  958. return DoEstimateGas(ctx, s.b, args, blockNrOrHash, s.b.RPCGasCap())
  959. }
  960. // ExecutionResult groups all structured logs emitted by the EVM
  961. // while replaying a transaction in debug mode as well as transaction
  962. // execution status, the amount of gas used and the return value
  963. type ExecutionResult struct {
  964. Gas uint64 `json:"gas"`
  965. Failed bool `json:"failed"`
  966. ReturnValue string `json:"returnValue"`
  967. StructLogs []StructLogRes `json:"structLogs"`
  968. }
  969. // StructLogRes stores a structured log emitted by the EVM while replaying a
  970. // transaction in debug mode
  971. type StructLogRes struct {
  972. Pc uint64 `json:"pc"`
  973. Op string `json:"op"`
  974. Gas uint64 `json:"gas"`
  975. GasCost uint64 `json:"gasCost"`
  976. Depth int `json:"depth"`
  977. Error error `json:"error,omitempty"`
  978. Stack *[]string `json:"stack,omitempty"`
  979. Memory *[]string `json:"memory,omitempty"`
  980. Storage *map[string]string `json:"storage,omitempty"`
  981. }
  982. // FormatLogs formats EVM returned structured logs for json output
  983. func FormatLogs(logs []vm.StructLog) []StructLogRes {
  984. formatted := make([]StructLogRes, len(logs))
  985. for index, trace := range logs {
  986. formatted[index] = StructLogRes{
  987. Pc: trace.Pc,
  988. Op: trace.Op.String(),
  989. Gas: trace.Gas,
  990. GasCost: trace.GasCost,
  991. Depth: trace.Depth,
  992. Error: trace.Err,
  993. }
  994. if trace.Stack != nil {
  995. stack := make([]string, len(trace.Stack))
  996. for i, stackValue := range trace.Stack {
  997. stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
  998. }
  999. formatted[index].Stack = &stack
  1000. }
  1001. if trace.Memory != nil {
  1002. memory := make([]string, 0, (len(trace.Memory)+31)/32)
  1003. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1004. memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1005. }
  1006. formatted[index].Memory = &memory
  1007. }
  1008. if trace.Storage != nil {
  1009. storage := make(map[string]string)
  1010. for i, storageValue := range trace.Storage {
  1011. storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1012. }
  1013. formatted[index].Storage = &storage
  1014. }
  1015. }
  1016. return formatted
  1017. }
  1018. // RPCMarshalHeader converts the given header to the RPC output .
  1019. func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  1020. return map[string]interface{}{
  1021. "number": (*hexutil.Big)(head.Number),
  1022. "hash": head.Hash(),
  1023. "parentHash": head.ParentHash,
  1024. "nonce": head.Nonce,
  1025. "mixHash": head.MixDigest,
  1026. "sha3Uncles": head.UncleHash,
  1027. "logsBloom": head.Bloom,
  1028. "stateRoot": head.Root,
  1029. "miner": head.Coinbase,
  1030. "difficulty": (*hexutil.Big)(head.Difficulty),
  1031. "extraData": hexutil.Bytes(head.Extra),
  1032. "size": hexutil.Uint64(head.Size()),
  1033. "gasLimit": hexutil.Uint64(head.GasLimit),
  1034. "gasUsed": hexutil.Uint64(head.GasUsed),
  1035. "timestamp": hexutil.Uint64(head.Time),
  1036. "transactionsRoot": head.TxHash,
  1037. "receiptsRoot": head.ReceiptHash,
  1038. }
  1039. }
  1040. // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1041. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1042. // transaction hashes.
  1043. func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1044. fields := RPCMarshalHeader(block.Header())
  1045. fields["size"] = hexutil.Uint64(block.Size())
  1046. if inclTx {
  1047. formatTx := func(tx *types.Transaction) (interface{}, error) {
  1048. return tx.Hash(), nil
  1049. }
  1050. if fullTx {
  1051. formatTx = func(tx *types.Transaction) (interface{}, error) {
  1052. return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  1053. }
  1054. }
  1055. txs := block.Transactions()
  1056. transactions := make([]interface{}, len(txs))
  1057. var err error
  1058. for i, tx := range txs {
  1059. if transactions[i], err = formatTx(tx); err != nil {
  1060. return nil, err
  1061. }
  1062. }
  1063. fields["transactions"] = transactions
  1064. }
  1065. uncles := block.Uncles()
  1066. uncleHashes := make([]common.Hash, len(uncles))
  1067. for i, uncle := range uncles {
  1068. uncleHashes[i] = uncle.Hash()
  1069. }
  1070. fields["uncles"] = uncleHashes
  1071. return fields, nil
  1072. }
  1073. // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1074. // a `PublicBlockchainAPI`.
  1075. func (s *PublicBlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} {
  1076. fields := RPCMarshalHeader(header)
  1077. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash()))
  1078. return fields
  1079. }
  1080. // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1081. // a `PublicBlockchainAPI`.
  1082. func (s *PublicBlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1083. fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  1084. if err != nil {
  1085. return nil, err
  1086. }
  1087. if inclTx {
  1088. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, b.Hash()))
  1089. }
  1090. return fields, err
  1091. }
  1092. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1093. type RPCTransaction struct {
  1094. BlockHash *common.Hash `json:"blockHash"`
  1095. BlockNumber *hexutil.Big `json:"blockNumber"`
  1096. From common.Address `json:"from"`
  1097. Gas hexutil.Uint64 `json:"gas"`
  1098. GasPrice *hexutil.Big `json:"gasPrice"`
  1099. Hash common.Hash `json:"hash"`
  1100. Input hexutil.Bytes `json:"input"`
  1101. Nonce hexutil.Uint64 `json:"nonce"`
  1102. To *common.Address `json:"to"`
  1103. TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
  1104. Value *hexutil.Big `json:"value"`
  1105. V *hexutil.Big `json:"v"`
  1106. R *hexutil.Big `json:"r"`
  1107. S *hexutil.Big `json:"s"`
  1108. }
  1109. // newRPCTransaction returns a transaction that will serialize to the RPC
  1110. // representation, with the given location metadata set (if available).
  1111. func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  1112. var signer types.Signer = types.FrontierSigner{}
  1113. if tx.Protected() {
  1114. signer = types.NewEIP155Signer(tx.ChainId())
  1115. }
  1116. from, _ := types.Sender(signer, tx)
  1117. v, r, s := tx.RawSignatureValues()
  1118. result := &RPCTransaction{
  1119. From: from,
  1120. Gas: hexutil.Uint64(tx.Gas()),
  1121. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1122. Hash: tx.Hash(),
  1123. Input: hexutil.Bytes(tx.Data()),
  1124. Nonce: hexutil.Uint64(tx.Nonce()),
  1125. To: tx.To(),
  1126. Value: (*hexutil.Big)(tx.Value()),
  1127. V: (*hexutil.Big)(v),
  1128. R: (*hexutil.Big)(r),
  1129. S: (*hexutil.Big)(s),
  1130. }
  1131. if blockHash != (common.Hash{}) {
  1132. result.BlockHash = &blockHash
  1133. result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1134. result.TransactionIndex = (*hexutil.Uint64)(&index)
  1135. }
  1136. return result
  1137. }
  1138. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1139. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1140. return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1141. }
  1142. // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1143. func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1144. txs := b.Transactions()
  1145. if index >= uint64(len(txs)) {
  1146. return nil
  1147. }
  1148. return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1149. }
  1150. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1151. func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1152. txs := b.Transactions()
  1153. if index >= uint64(len(txs)) {
  1154. return nil
  1155. }
  1156. blob, _ := rlp.EncodeToBytes(txs[index])
  1157. return blob
  1158. }
  1159. // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1160. func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1161. for idx, tx := range b.Transactions() {
  1162. if tx.Hash() == hash {
  1163. return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1164. }
  1165. }
  1166. return nil
  1167. }
  1168. // PublicTransactionPoolAPI exposes methods for the RPC interface
  1169. type PublicTransactionPoolAPI struct {
  1170. b Backend
  1171. nonceLock *AddrLocker
  1172. }
  1173. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1174. func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1175. return &PublicTransactionPoolAPI{b, nonceLock}
  1176. }
  1177. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1178. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1179. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1180. n := hexutil.Uint(len(block.Transactions()))
  1181. return &n
  1182. }
  1183. return nil
  1184. }
  1185. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1186. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1187. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1188. n := hexutil.Uint(len(block.Transactions()))
  1189. return &n
  1190. }
  1191. return nil
  1192. }
  1193. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1194. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1195. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1196. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1197. }
  1198. return nil
  1199. }
  1200. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1201. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1202. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1203. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1204. }
  1205. return nil
  1206. }
  1207. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1208. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1209. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1210. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1211. }
  1212. return nil
  1213. }
  1214. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1215. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1216. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1217. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1218. }
  1219. return nil
  1220. }
  1221. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1222. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1223. // Ask transaction pool for the nonce which includes pending transactions
  1224. if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1225. nonce, err := s.b.GetPoolNonce(ctx, address)
  1226. if err != nil {
  1227. return nil, err
  1228. }
  1229. return (*hexutil.Uint64)(&nonce), nil
  1230. }
  1231. // Resolve block number and use its state to ask for the nonce
  1232. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1233. if state == nil || err != nil {
  1234. return nil, err
  1235. }
  1236. nonce := state.GetNonce(address)
  1237. return (*hexutil.Uint64)(&nonce), state.Error()
  1238. }
  1239. // GetTransactionByHash returns the transaction for the given hash
  1240. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1241. // Try to return an already finalized transaction
  1242. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1243. if err != nil {
  1244. return nil, err
  1245. }
  1246. if tx != nil {
  1247. return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1248. }
  1249. // No finalized transaction, try to retrieve it from the pool
  1250. if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1251. return newRPCPendingTransaction(tx), nil
  1252. }
  1253. // Transaction unknown, return as such
  1254. return nil, nil
  1255. }
  1256. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1257. func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1258. // Retrieve a finalized transaction, or a pooled otherwise
  1259. tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1260. if err != nil {
  1261. return nil, err
  1262. }
  1263. if tx == nil {
  1264. if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1265. // Transaction not found anywhere, abort
  1266. return nil, nil
  1267. }
  1268. }
  1269. // Serialize to RLP and return
  1270. return rlp.EncodeToBytes(tx)
  1271. }
  1272. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1273. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1274. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1275. if err != nil {
  1276. return nil, nil
  1277. }
  1278. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1279. if err != nil {
  1280. return nil, err
  1281. }
  1282. if len(receipts) <= int(index) {
  1283. return nil, nil
  1284. }
  1285. receipt := receipts[index]
  1286. var signer types.Signer = types.FrontierSigner{}
  1287. if tx.Protected() {
  1288. signer = types.NewEIP155Signer(tx.ChainId())
  1289. }
  1290. from, _ := types.Sender(signer, tx)
  1291. fields := map[string]interface{}{
  1292. "blockHash": blockHash,
  1293. "blockNumber": hexutil.Uint64(blockNumber),
  1294. "transactionHash": hash,
  1295. "transactionIndex": hexutil.Uint64(index),
  1296. "from": from,
  1297. "to": tx.To(),
  1298. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1299. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1300. "contractAddress": nil,
  1301. "logs": receipt.Logs,
  1302. "logsBloom": receipt.Bloom,
  1303. }
  1304. // Assign receipt status or post state.
  1305. if len(receipt.PostState) > 0 {
  1306. fields["root"] = hexutil.Bytes(receipt.PostState)
  1307. } else {
  1308. fields["status"] = hexutil.Uint(receipt.Status)
  1309. }
  1310. if receipt.Logs == nil {
  1311. fields["logs"] = [][]*types.Log{}
  1312. }
  1313. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1314. if receipt.ContractAddress != (common.Address{}) {
  1315. fields["contractAddress"] = receipt.ContractAddress
  1316. }
  1317. return fields, nil
  1318. }
  1319. // sign is a helper function that signs a transaction with the private key of the given address.
  1320. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1321. // Look up the wallet containing the requested signer
  1322. account := accounts.Account{Address: addr}
  1323. wallet, err := s.b.AccountManager().Find(account)
  1324. if err != nil {
  1325. return nil, err
  1326. }
  1327. // Request the wallet to sign the transaction
  1328. return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1329. }
  1330. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1331. type SendTxArgs struct {
  1332. From common.Address `json:"from"`
  1333. To *common.Address `json:"to"`
  1334. Gas *hexutil.Uint64 `json:"gas"`
  1335. GasPrice *hexutil.Big `json:"gasPrice"`
  1336. Value *hexutil.Big `json:"value"`
  1337. Nonce *hexutil.Uint64 `json:"nonce"`
  1338. // We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1339. // newer name and should be preferred by clients.
  1340. Data *hexutil.Bytes `json:"data"`
  1341. Input *hexutil.Bytes `json:"input"`
  1342. }
  1343. // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1344. func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1345. if args.GasPrice == nil {
  1346. price, err := b.SuggestPrice(ctx)
  1347. if err != nil {
  1348. return err
  1349. }
  1350. args.GasPrice = (*hexutil.Big)(price)
  1351. }
  1352. if args.Value == nil {
  1353. args.Value = new(hexutil.Big)
  1354. }
  1355. if args.Nonce == nil {
  1356. nonce, err := b.GetPoolNonce(ctx, args.From)
  1357. if err != nil {
  1358. return err
  1359. }
  1360. args.Nonce = (*hexutil.Uint64)(&nonce)
  1361. }
  1362. if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1363. return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
  1364. }
  1365. if args.To == nil {
  1366. // Contract creation
  1367. var input []byte
  1368. if args.Data != nil {
  1369. input = *args.Data
  1370. } else if args.Input != nil {
  1371. input = *args.Input
  1372. }
  1373. if len(input) == 0 {
  1374. return errors.New(`contract creation without any data provided`)
  1375. }
  1376. }
  1377. // Estimate the gas usage if necessary.
  1378. if args.Gas == nil {
  1379. // For backwards-compatibility reason, we try both input and data
  1380. // but input is preferred.
  1381. input := args.Input
  1382. if input == nil {
  1383. input = args.Data
  1384. }
  1385. callArgs := CallArgs{
  1386. From: &args.From, // From shouldn't be nil
  1387. To: args.To,
  1388. GasPrice: args.GasPrice,
  1389. Value: args.Value,
  1390. Data: input,
  1391. }
  1392. pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1393. estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
  1394. if err != nil {
  1395. return err
  1396. }
  1397. args.Gas = &estimated
  1398. log.Trace("Estimate gas usage automatically", "gas", args.Gas)
  1399. }
  1400. return nil
  1401. }
  1402. func (args *SendTxArgs) toTransaction() *types.Transaction {
  1403. var input []byte
  1404. if args.Input != nil {
  1405. input = *args.Input
  1406. } else if args.Data != nil {
  1407. input = *args.Data
  1408. }
  1409. if args.To == nil {
  1410. return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1411. }
  1412. return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1413. }
  1414. // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1415. func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1416. // If the transaction fee cap is already specified, ensure the
  1417. // fee of the given transaction is _reasonable_.
  1418. feeEth := new(big.Float).Quo(new(big.Float).SetInt(new(big.Int).Mul(tx.GasPrice(), new(big.Int).SetUint64(tx.Gas()))), new(big.Float).SetInt(big.NewInt(params.Ether)))
  1419. feeFloat, _ := feeEth.Float64()
  1420. if b.RPCTxFeeCap() != 0 && feeFloat > b.RPCTxFeeCap() {
  1421. return common.Hash{}, fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, b.RPCTxFeeCap())
  1422. }
  1423. if err := b.SendTx(ctx, tx); err != nil {
  1424. return common.Hash{}, err
  1425. }
  1426. if tx.To() == nil {
  1427. signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1428. from, err := types.Sender(signer, tx)
  1429. if err != nil {
  1430. return common.Hash{}, err
  1431. }
  1432. addr := crypto.CreateAddress(from, tx.Nonce())
  1433. log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1434. } else {
  1435. log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1436. }
  1437. return tx.Hash(), nil
  1438. }
  1439. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1440. // transaction pool.
  1441. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1442. // Look up the wallet containing the requested signer
  1443. account := accounts.Account{Address: args.From}
  1444. wallet, err := s.b.AccountManager().Find(account)
  1445. if err != nil {
  1446. return common.Hash{}, err
  1447. }
  1448. if args.Nonce == nil {
  1449. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  1450. // the same nonce to multiple accounts.
  1451. s.nonceLock.LockAddr(args.From)
  1452. defer s.nonceLock.UnlockAddr(args.From)
  1453. }
  1454. // Set some sanity defaults and terminate on failure
  1455. if err := args.setDefaults(ctx, s.b); err != nil {
  1456. return common.Hash{}, err
  1457. }
  1458. // Assemble the transaction and sign with the wallet
  1459. tx := args.toTransaction()
  1460. signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1461. if err != nil {
  1462. return common.Hash{}, err
  1463. }
  1464. return SubmitTransaction(ctx, s.b, signed)
  1465. }
  1466. // FillTransaction fills the defaults (nonce, gas, gasPrice) on a given unsigned transaction,
  1467. // and returns it to the caller for further processing (signing + broadcast)
  1468. func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1469. // Set some sanity defaults and terminate on failure
  1470. if err := args.setDefaults(ctx, s.b); err != nil {
  1471. return nil, err
  1472. }
  1473. // Assemble the transaction and obtain rlp
  1474. tx := args.toTransaction()
  1475. data, err := rlp.EncodeToBytes(tx)
  1476. if err != nil {
  1477. return nil, err
  1478. }
  1479. return &SignTransactionResult{data, tx}, nil
  1480. }
  1481. // SendRawTransaction will add the signed transaction to the transaction pool.
  1482. // The sender is responsible for signing the transaction and using the correct nonce.
  1483. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  1484. tx := new(types.Transaction)
  1485. if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1486. return common.Hash{}, err
  1487. }
  1488. return SubmitTransaction(ctx, s.b, tx)
  1489. }
  1490. // Sign calculates an ECDSA signature for:
  1491. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1492. //
  1493. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1494. // where the V value will be 27 or 28 for legacy reasons.
  1495. //
  1496. // The account associated with addr must be unlocked.
  1497. //
  1498. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1499. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1500. // Look up the wallet containing the requested signer
  1501. account := accounts.Account{Address: addr}
  1502. wallet, err := s.b.AccountManager().Find(account)
  1503. if err != nil {
  1504. return nil, err
  1505. }
  1506. // Sign the requested hash with the wallet
  1507. signature, err := wallet.SignText(account, data)
  1508. if err == nil {
  1509. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1510. }
  1511. return signature, err
  1512. }
  1513. // SignTransactionResult represents a RLP encoded signed transaction.
  1514. type SignTransactionResult struct {
  1515. Raw hexutil.Bytes `json:"raw"`
  1516. Tx *types.Transaction `json:"tx"`
  1517. }
  1518. // SignTransaction will sign the given transaction with the from account.
  1519. // The node needs to have the private key of the account corresponding with
  1520. // the given from address and it needs to be unlocked.
  1521. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1522. if args.Gas == nil {
  1523. return nil, fmt.Errorf("gas not specified")
  1524. }
  1525. if args.GasPrice == nil {
  1526. return nil, fmt.Errorf("gasPrice not specified")
  1527. }
  1528. if args.Nonce == nil {
  1529. return nil, fmt.Errorf("nonce not specified")
  1530. }
  1531. if err := args.setDefaults(ctx, s.b); err != nil {
  1532. return nil, err
  1533. }
  1534. tx, err := s.sign(args.From, args.toTransaction())
  1535. if err != nil {
  1536. return nil, err
  1537. }
  1538. data, err := rlp.EncodeToBytes(tx)
  1539. if err != nil {
  1540. return nil, err
  1541. }
  1542. return &SignTransactionResult{data, tx}, nil
  1543. }
  1544. // PendingTransactions returns the transactions that are in the transaction pool
  1545. // and have a from address that is one of the accounts this node manages.
  1546. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1547. pending, err := s.b.GetPoolTransactions()
  1548. if err != nil {
  1549. return nil, err
  1550. }
  1551. accounts := make(map[common.Address]struct{})
  1552. for _, wallet := range s.b.AccountManager().Wallets() {
  1553. for _, account := range wallet.Accounts() {
  1554. accounts[account.Address] = struct{}{}
  1555. }
  1556. }
  1557. transactions := make([]*RPCTransaction, 0, len(pending))
  1558. for _, tx := range pending {
  1559. var signer types.Signer = types.HomesteadSigner{}
  1560. if tx.Protected() {
  1561. signer = types.NewEIP155Signer(tx.ChainId())
  1562. }
  1563. from, _ := types.Sender(signer, tx)
  1564. if _, exists := accounts[from]; exists {
  1565. transactions = append(transactions, newRPCPendingTransaction(tx))
  1566. }
  1567. }
  1568. return transactions, nil
  1569. }
  1570. // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1571. // the given transaction from the pool and reinsert it with the new gas price and limit.
  1572. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1573. if sendArgs.Nonce == nil {
  1574. return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1575. }
  1576. if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1577. return common.Hash{}, err
  1578. }
  1579. matchTx := sendArgs.toTransaction()
  1580. pending, err := s.b.GetPoolTransactions()
  1581. if err != nil {
  1582. return common.Hash{}, err
  1583. }
  1584. for _, p := range pending {
  1585. var signer types.Signer = types.HomesteadSigner{}
  1586. if p.Protected() {
  1587. signer = types.NewEIP155Signer(p.ChainId())
  1588. }
  1589. wantSigHash := signer.Hash(matchTx)
  1590. if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1591. // Match. Re-sign and send the transaction.
  1592. if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1593. sendArgs.GasPrice = gasPrice
  1594. }
  1595. if gasLimit != nil && *gasLimit != 0 {
  1596. sendArgs.Gas = gasLimit
  1597. }
  1598. signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  1599. if err != nil {
  1600. return common.Hash{}, err
  1601. }
  1602. if err = s.b.SendTx(ctx, signedTx); err != nil {
  1603. return common.Hash{}, err
  1604. }
  1605. return signedTx.Hash(), nil
  1606. }
  1607. }
  1608. return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  1609. }
  1610. // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  1611. // debugging endpoint.
  1612. type PublicDebugAPI struct {
  1613. b Backend
  1614. }
  1615. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1616. // of the Ethereum service.
  1617. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1618. return &PublicDebugAPI{b: b}
  1619. }
  1620. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1621. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1622. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1623. if block == nil {
  1624. return "", fmt.Errorf("block #%d not found", number)
  1625. }
  1626. encoded, err := rlp.EncodeToBytes(block)
  1627. if err != nil {
  1628. return "", err
  1629. }
  1630. return fmt.Sprintf("%x", encoded), nil
  1631. }
  1632. // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  1633. // given address, returning the address of the recovered signature
  1634. //
  1635. // This is a temporary method to debug the externalsigner integration,
  1636. // TODO: Remove this method when the integration is mature
  1637. func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  1638. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1639. if block == nil {
  1640. return common.Address{}, fmt.Errorf("block #%d not found", number)
  1641. }
  1642. header := block.Header()
  1643. header.Extra = make([]byte, 32+65)
  1644. encoded := clique.CliqueRLP(header)
  1645. // Look up the wallet containing the requested signer
  1646. account := accounts.Account{Address: address}
  1647. wallet, err := api.b.AccountManager().Find(account)
  1648. if err != nil {
  1649. return common.Address{}, err
  1650. }
  1651. signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  1652. if err != nil {
  1653. return common.Address{}, err
  1654. }
  1655. sealHash := clique.SealHash(header).Bytes()
  1656. log.Info("test signing of clique block",
  1657. "Sealhash", fmt.Sprintf("%x", sealHash),
  1658. "signature", fmt.Sprintf("%x", signature))
  1659. pubkey, err := crypto.Ecrecover(sealHash, signature)
  1660. if err != nil {
  1661. return common.Address{}, err
  1662. }
  1663. var signer common.Address
  1664. copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  1665. return signer, nil
  1666. }
  1667. // PrintBlock retrieves a block and returns its pretty printed form.
  1668. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1669. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1670. if block == nil {
  1671. return "", fmt.Errorf("block #%d not found", number)
  1672. }
  1673. return spew.Sdump(block), nil
  1674. }
  1675. // SeedHash retrieves the seed hash of a block.
  1676. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1677. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1678. if block == nil {
  1679. return "", fmt.Errorf("block #%d not found", number)
  1680. }
  1681. return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  1682. }
  1683. // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  1684. // debugging endpoint.
  1685. type PrivateDebugAPI struct {
  1686. b Backend
  1687. }
  1688. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1689. // of the Ethereum service.
  1690. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1691. return &PrivateDebugAPI{b: b}
  1692. }
  1693. // ChaindbProperty returns leveldb properties of the key-value database.
  1694. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1695. if property == "" {
  1696. property = "leveldb.stats"
  1697. } else if !strings.HasPrefix(property, "leveldb.") {
  1698. property = "leveldb." + property
  1699. }
  1700. return api.b.ChainDb().Stat(property)
  1701. }
  1702. // ChaindbCompact flattens the entire key-value database into a single level,
  1703. // removing all unused slots and merging all keys.
  1704. func (api *PrivateDebugAPI) ChaindbCompact() error {
  1705. for b := byte(0); b < 255; b++ {
  1706. log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1707. if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  1708. log.Error("Database compaction failed", "err", err)
  1709. return err
  1710. }
  1711. }
  1712. return nil
  1713. }
  1714. // SetHead rewinds the head of the blockchain to a previous block.
  1715. func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1716. api.b.SetHead(uint64(number))
  1717. }
  1718. // PublicNetAPI offers network related RPC methods
  1719. type PublicNetAPI struct {
  1720. net *p2p.Server
  1721. networkVersion uint64
  1722. }
  1723. // NewPublicNetAPI creates a new net API instance.
  1724. func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  1725. return &PublicNetAPI{net, networkVersion}
  1726. }
  1727. // Listening returns an indication if the node is listening for network connections.
  1728. func (s *PublicNetAPI) Listening() bool {
  1729. return true // always listening
  1730. }
  1731. // PeerCount returns the number of connected peers
  1732. func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1733. return hexutil.Uint(s.net.PeerCount())
  1734. }
  1735. // Version returns the current ethereum protocol version.
  1736. func (s *PublicNetAPI) Version() string {
  1737. return fmt.Sprintf("%d", s.networkVersion)
  1738. }