api.go 66 KB

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