api.go 64 KB

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