api.go 55 KB

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