api.go 63 KB

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