api.go 61 KB

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