api.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  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. "encoding/hex"
  20. "errors"
  21. "fmt"
  22. "math"
  23. "math/big"
  24. "strings"
  25. "time"
  26. "github.com/ethereum/ethash"
  27. "github.com/ethereum/go-ethereum/accounts"
  28. "github.com/ethereum/go-ethereum/accounts/keystore"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/common/hexutil"
  31. "github.com/ethereum/go-ethereum/core"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/core/vm"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/ethdb"
  36. "github.com/ethereum/go-ethereum/logger"
  37. "github.com/ethereum/go-ethereum/logger/glog"
  38. "github.com/ethereum/go-ethereum/p2p"
  39. "github.com/ethereum/go-ethereum/rlp"
  40. "github.com/ethereum/go-ethereum/rpc"
  41. "github.com/syndtr/goleveldb/leveldb"
  42. "github.com/syndtr/goleveldb/leveldb/util"
  43. "golang.org/x/net/context"
  44. )
  45. const defaultGas = 90000
  46. var emptyHex = "0x"
  47. // PublicEthereumAPI provides an API to access Ethereum related information.
  48. // It offers only methods that operate on public data that is freely available to anyone.
  49. type PublicEthereumAPI struct {
  50. b Backend
  51. }
  52. // NewPublicEthereumAPI creates a new Etheruem protocol API.
  53. func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
  54. return &PublicEthereumAPI{b}
  55. }
  56. // GasPrice returns a suggestion for a gas price.
  57. func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*big.Int, error) {
  58. return s.b.SuggestPrice(ctx)
  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 nonce, tx := range txs {
  105. dump[fmt.Sprintf("%d", 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 nonce, tx := range txs {
  113. dump[fmt.Sprintf("%d", 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 × %v gas", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
  139. }
  140. return fmt.Sprintf("contract creation: %v wei + %v × %v gas", 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 nonce, tx := range txs {
  146. dump[fmt.Sprintf("%d", 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 nonce, tx := range txs {
  154. dump[fmt.Sprintf("%d", 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. var addresses []common.Address
  172. for _, wallet := range s.am.Wallets() {
  173. for _, account := range wallet.Accounts() {
  174. addresses = append(addresses, account.Address)
  175. }
  176. }
  177. return addresses
  178. }
  179. // PrivateAccountAPI provides an API to access accounts managed by this node.
  180. // It offers methods to create, (un)lock en list accounts. Some methods accept
  181. // passwords and are therefore considered private by default.
  182. type PrivateAccountAPI struct {
  183. am *accounts.Manager
  184. b Backend
  185. }
  186. // NewPrivateAccountAPI create a new PrivateAccountAPI.
  187. func NewPrivateAccountAPI(b Backend) *PrivateAccountAPI {
  188. return &PrivateAccountAPI{
  189. am: b.AccountManager(),
  190. b: b,
  191. }
  192. }
  193. // ListAccounts will return a list of addresses for accounts this node manages.
  194. func (s *PrivateAccountAPI) ListAccounts() []common.Address {
  195. var addresses []common.Address
  196. for _, wallet := range s.am.Wallets() {
  197. for _, account := range wallet.Accounts() {
  198. addresses = append(addresses, account.Address)
  199. }
  200. }
  201. return addresses
  202. }
  203. // rawWallet is a JSON representation of an accounts.Wallet interface, with its
  204. // data contents extracted into plain fields.
  205. type rawWallet struct {
  206. Type string `json:"type"`
  207. URL string `json:"url"`
  208. Status string `json:"status"`
  209. Accounts []accounts.Account `json:"accounts"`
  210. }
  211. // ListWallets will return a list of wallets this node manages.
  212. func (s *PrivateAccountAPI) ListWallets() []rawWallet {
  213. var wallets []rawWallet
  214. for _, wallet := range s.am.Wallets() {
  215. wallets = append(wallets, rawWallet{
  216. Type: wallet.Type(),
  217. URL: wallet.URL(),
  218. Status: wallet.Status(),
  219. Accounts: wallet.Accounts(),
  220. })
  221. }
  222. return wallets
  223. }
  224. // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
  225. // it for later reuse.
  226. func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
  227. wallet, err := s.am.Wallet(url)
  228. if err != nil {
  229. return accounts.Account{}, err
  230. }
  231. if pin == nil {
  232. pin = new(bool)
  233. }
  234. return wallet.Derive(path, *pin)
  235. }
  236. // NewAccount will create a new account and returns the address for the new account.
  237. func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
  238. acc, err := fetchKeystore(s.am).NewAccount(password)
  239. if err == nil {
  240. return acc.Address, nil
  241. }
  242. return common.Address{}, err
  243. }
  244. // fetchKeystore retrives the encrypted keystore from the account manager.
  245. func fetchKeystore(am *accounts.Manager) *keystore.KeyStore {
  246. return am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  247. }
  248. // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
  249. // encrypting it with the passphrase.
  250. func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
  251. hexkey, err := hex.DecodeString(privkey)
  252. if err != nil {
  253. return common.Address{}, err
  254. }
  255. acc, err := fetchKeystore(s.am).ImportECDSA(crypto.ToECDSA(hexkey), password)
  256. return acc.Address, err
  257. }
  258. // UnlockAccount will unlock the account associated with the given address with
  259. // the given password for duration seconds. If duration is nil it will use a
  260. // default of 300 seconds. It returns an indication if the account was unlocked.
  261. func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *uint64) (bool, error) {
  262. const max = uint64(time.Duration(math.MaxInt64) / time.Second)
  263. var d time.Duration
  264. if duration == nil {
  265. d = 300 * time.Second
  266. } else if *duration > max {
  267. return false, errors.New("unlock duration too large")
  268. } else {
  269. d = time.Duration(*duration) * time.Second
  270. }
  271. err := fetchKeystore(s.am).TimedUnlock(accounts.Account{Address: addr}, password, d)
  272. return err == nil, err
  273. }
  274. // LockAccount will lock the account associated with the given address when it's unlocked.
  275. func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
  276. return fetchKeystore(s.am).Lock(addr) == nil
  277. }
  278. // SendTransaction will create a transaction from the given arguments and
  279. // tries to sign it with the key associated with args.To. If the given passwd isn't
  280. // able to decrypt the key it fails.
  281. func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  282. // Set some sanity defaults and terminate on failure
  283. if err := args.setDefaults(ctx, s.b); err != nil {
  284. return common.Hash{}, err
  285. }
  286. // Look up the wallet containing the requested signer
  287. account := accounts.Account{Address: args.From}
  288. wallet, err := s.am.Find(account)
  289. if err != nil {
  290. return common.Hash{}, err
  291. }
  292. // Assemble the transaction and sign with the wallet
  293. tx := args.toTransaction()
  294. var chainID *big.Int
  295. if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  296. chainID = config.ChainId
  297. }
  298. signed, err := wallet.SignTxWithPassphrase(account, passwd, tx, chainID)
  299. if err != nil {
  300. return common.Hash{}, err
  301. }
  302. return submitTransaction(ctx, s.b, signed)
  303. }
  304. // signHash is a helper function that calculates a hash for the given message that can be
  305. // safely used to calculate a signature from.
  306. //
  307. // The hash is calulcated as
  308. // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
  309. //
  310. // This gives context to the signed message and prevents signing of transactions.
  311. func signHash(data []byte) []byte {
  312. msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
  313. return crypto.Keccak256([]byte(msg))
  314. }
  315. // Sign calculates an Ethereum ECDSA signature for:
  316. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  317. //
  318. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  319. // where the V value will be 27 or 28 for legacy reasons.
  320. //
  321. // The key used to calculate the signature is decrypted with the given password.
  322. //
  323. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  324. func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
  325. // Look up the wallet containing the requested signer
  326. account := accounts.Account{Address: addr}
  327. wallet, err := s.b.AccountManager().Find(account)
  328. if err != nil {
  329. return nil, err
  330. }
  331. // Assemble sign the data with the wallet
  332. signature, err := wallet.SignHashWithPassphrase(account, passwd, signHash(data))
  333. if err != nil {
  334. return nil, err
  335. }
  336. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  337. return signature, nil
  338. }
  339. // EcRecover returns the address for the account that was used to create the signature.
  340. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  341. // the address of:
  342. // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
  343. // addr = ecrecover(hash, signature)
  344. //
  345. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  346. // the V value must be be 27 or 28 for legacy reasons.
  347. //
  348. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  349. func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
  350. if len(sig) != 65 {
  351. return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
  352. }
  353. if sig[64] != 27 && sig[64] != 28 {
  354. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  355. }
  356. sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
  357. rpk, err := crypto.Ecrecover(signHash(data), sig)
  358. if err != nil {
  359. return common.Address{}, err
  360. }
  361. pubKey := crypto.ToECDSAPub(rpk)
  362. recoveredAddr := crypto.PubkeyToAddress(*pubKey)
  363. return recoveredAddr, nil
  364. }
  365. // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
  366. // and will be removed in the future. It primary goal is to give clients time to update.
  367. func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  368. return s.SendTransaction(ctx, args, passwd)
  369. }
  370. // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
  371. // It offers only methods that operate on public data that is freely available to anyone.
  372. type PublicBlockChainAPI struct {
  373. b Backend
  374. }
  375. // NewPublicBlockChainAPI creates a new Etheruem blockchain API.
  376. func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
  377. return &PublicBlockChainAPI{b}
  378. }
  379. // BlockNumber returns the block number of the chain head.
  380. func (s *PublicBlockChainAPI) BlockNumber() *big.Int {
  381. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
  382. return header.Number
  383. }
  384. // GetBalance returns the amount of wei for the given address in the state of the
  385. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  386. // block numbers are also allowed.
  387. func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) {
  388. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  389. if state == nil || err != nil {
  390. return nil, err
  391. }
  392. return state.GetBalance(ctx, address)
  393. }
  394. // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
  395. // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  396. func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  397. block, err := s.b.BlockByNumber(ctx, blockNr)
  398. if block != nil {
  399. response, err := s.rpcOutputBlock(block, true, fullTx)
  400. if err == nil && blockNr == rpc.PendingBlockNumber {
  401. // Pending blocks need to nil out a few fields
  402. for _, field := range []string{"hash", "nonce", "logsBloom", "miner"} {
  403. response[field] = nil
  404. }
  405. }
  406. return response, err
  407. }
  408. return nil, err
  409. }
  410. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  411. // detail, otherwise only the transaction hash is returned.
  412. func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
  413. block, err := s.b.GetBlock(ctx, blockHash)
  414. if block != nil {
  415. return s.rpcOutputBlock(block, true, fullTx)
  416. }
  417. return nil, err
  418. }
  419. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  420. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  421. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
  422. block, err := s.b.BlockByNumber(ctx, blockNr)
  423. if block != nil {
  424. uncles := block.Uncles()
  425. if index >= hexutil.Uint(len(uncles)) {
  426. glog.V(logger.Debug).Infof("uncle block on index %d not found for block #%d", index, blockNr)
  427. return nil, nil
  428. }
  429. block = types.NewBlockWithHeader(uncles[index])
  430. return s.rpcOutputBlock(block, false, false)
  431. }
  432. return nil, err
  433. }
  434. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  435. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  436. func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
  437. block, err := s.b.GetBlock(ctx, blockHash)
  438. if block != nil {
  439. uncles := block.Uncles()
  440. if index >= hexutil.Uint(len(uncles)) {
  441. glog.V(logger.Debug).Infof("uncle block on index %d not found for block %s", index, blockHash.Hex())
  442. return nil, nil
  443. }
  444. block = types.NewBlockWithHeader(uncles[index])
  445. return s.rpcOutputBlock(block, false, false)
  446. }
  447. return nil, err
  448. }
  449. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  450. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  451. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  452. n := hexutil.Uint(len(block.Uncles()))
  453. return &n
  454. }
  455. return nil
  456. }
  457. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  458. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  459. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  460. n := hexutil.Uint(len(block.Uncles()))
  461. return &n
  462. }
  463. return nil
  464. }
  465. // GetCode returns the code stored at the given address in the state for the given block number.
  466. func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (string, error) {
  467. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  468. if state == nil || err != nil {
  469. return "", err
  470. }
  471. res, err := state.GetCode(ctx, address)
  472. if len(res) == 0 || err != nil { // backwards compatibility
  473. return "0x", err
  474. }
  475. return common.ToHex(res), nil
  476. }
  477. // GetStorageAt returns the storage from the state at the given address, key and
  478. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  479. // numbers are also allowed.
  480. func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (string, error) {
  481. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  482. if state == nil || err != nil {
  483. return "0x", err
  484. }
  485. res, err := state.GetState(ctx, address, common.HexToHash(key))
  486. if err != nil {
  487. return "0x", err
  488. }
  489. return res.Hex(), nil
  490. }
  491. // callmsg is the message type used for call transitions.
  492. type callmsg struct {
  493. addr common.Address
  494. to *common.Address
  495. gas, gasPrice *big.Int
  496. value *big.Int
  497. data []byte
  498. }
  499. // accessor boilerplate to implement core.Message
  500. func (m callmsg) From() (common.Address, error) { return m.addr, nil }
  501. func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil }
  502. func (m callmsg) Nonce() uint64 { return 0 }
  503. func (m callmsg) CheckNonce() bool { return false }
  504. func (m callmsg) To() *common.Address { return m.to }
  505. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  506. func (m callmsg) Gas() *big.Int { return m.gas }
  507. func (m callmsg) Value() *big.Int { return m.value }
  508. func (m callmsg) Data() []byte { return m.data }
  509. // CallArgs represents the arguments for a call.
  510. type CallArgs struct {
  511. From common.Address `json:"from"`
  512. To *common.Address `json:"to"`
  513. Gas hexutil.Big `json:"gas"`
  514. GasPrice hexutil.Big `json:"gasPrice"`
  515. Value hexutil.Big `json:"value"`
  516. Data hexutil.Bytes `json:"data"`
  517. }
  518. func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber, vmCfg vm.Config) ([]byte, *big.Int, error) {
  519. defer func(start time.Time) { glog.V(logger.Debug).Infof("call took %v", time.Since(start)) }(time.Now())
  520. state, header, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  521. if state == nil || err != nil {
  522. return nil, common.Big0, err
  523. }
  524. // Set sender address or use a default if none specified
  525. addr := args.From
  526. if addr == (common.Address{}) {
  527. if wallets := s.b.AccountManager().Wallets(); len(wallets) > 0 {
  528. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  529. addr = accounts[0].Address
  530. }
  531. }
  532. }
  533. // Set default gas & gas price if none were set
  534. gas, gasPrice := args.Gas.ToInt(), args.GasPrice.ToInt()
  535. if gas.BitLen() == 0 {
  536. gas = big.NewInt(50000000)
  537. }
  538. if gasPrice.BitLen() == 0 {
  539. gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
  540. }
  541. // Create new call message
  542. msg := types.NewMessage(addr, args.To, 0, args.Value.ToInt(), gas, gasPrice, args.Data, false)
  543. // Setup context so it may be cancelled the call has completed
  544. // or, in case of unmetered gas, setup a context with a timeout.
  545. var cancel context.CancelFunc
  546. if vmCfg.DisableGasMetering {
  547. ctx, cancel = context.WithTimeout(ctx, time.Second*5)
  548. } else {
  549. ctx, cancel = context.WithCancel(ctx)
  550. }
  551. // Make sure the context is cancelled when the call has completed
  552. // this makes sure resources are cleaned up.
  553. defer func() { cancel() }()
  554. // Get a new instance of the EVM.
  555. evm, vmError, err := s.b.GetEVM(ctx, msg, state, header, vmCfg)
  556. if err != nil {
  557. return nil, common.Big0, err
  558. }
  559. // Wait for the context to be done and cancel the evm. Even if the
  560. // EVM has finished, cancelling may be done (repeatedly)
  561. go func() {
  562. select {
  563. case <-ctx.Done():
  564. evm.Cancel()
  565. }
  566. }()
  567. // Setup the gas pool (also for unmetered requests)
  568. // and apply the message.
  569. gp := new(core.GasPool).AddGas(common.MaxBig)
  570. res, gas, err := core.ApplyMessage(evm, msg, gp)
  571. if err := vmError(); err != nil {
  572. return nil, common.Big0, err
  573. }
  574. return res, gas, err
  575. }
  576. // Call executes the given transaction on the state for the given block number.
  577. // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
  578. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
  579. result, _, err := s.doCall(ctx, args, blockNr, vm.Config{DisableGasMetering: true})
  580. return (hexutil.Bytes)(result), err
  581. }
  582. // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
  583. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (*hexutil.Big, error) {
  584. // Binary search the gas requirement, as it may be higher than the amount used
  585. var lo, hi uint64
  586. if (*big.Int)(&args.Gas).BitLen() > 0 {
  587. hi = (*big.Int)(&args.Gas).Uint64()
  588. } else {
  589. // Retrieve the current pending block to act as the gas ceiling
  590. block, err := s.b.BlockByNumber(ctx, rpc.PendingBlockNumber)
  591. if err != nil {
  592. return nil, err
  593. }
  594. hi = block.GasLimit().Uint64()
  595. }
  596. for lo+1 < hi {
  597. // Take a guess at the gas, and check transaction validity
  598. mid := (hi + lo) / 2
  599. (*big.Int)(&args.Gas).SetUint64(mid)
  600. _, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber, vm.Config{})
  601. // If the transaction became invalid or used all the gas (failed), raise the gas limit
  602. if err != nil || gas.Cmp((*big.Int)(&args.Gas)) == 0 {
  603. lo = mid
  604. continue
  605. }
  606. // Otherwise assume the transaction succeeded, lower the gas limit
  607. hi = mid
  608. }
  609. return (*hexutil.Big)(new(big.Int).SetUint64(hi)), nil
  610. }
  611. // ExecutionResult groups all structured logs emitted by the EVM
  612. // while replaying a transaction in debug mode as well as the amount of
  613. // gas used and the return value
  614. type ExecutionResult struct {
  615. Gas *big.Int `json:"gas"`
  616. ReturnValue string `json:"returnValue"`
  617. StructLogs []StructLogRes `json:"structLogs"`
  618. }
  619. // StructLogRes stores a structured log emitted by the EVM while replaying a
  620. // transaction in debug mode
  621. type StructLogRes struct {
  622. Pc uint64 `json:"pc"`
  623. Op string `json:"op"`
  624. Gas *big.Int `json:"gas"`
  625. GasCost *big.Int `json:"gasCost"`
  626. Depth int `json:"depth"`
  627. Error error `json:"error"`
  628. Stack []string `json:"stack"`
  629. Memory []string `json:"memory"`
  630. Storage map[string]string `json:"storage"`
  631. }
  632. // formatLogs formats EVM returned structured logs for json output
  633. func FormatLogs(structLogs []vm.StructLog) []StructLogRes {
  634. formattedStructLogs := make([]StructLogRes, len(structLogs))
  635. for index, trace := range structLogs {
  636. formattedStructLogs[index] = StructLogRes{
  637. Pc: trace.Pc,
  638. Op: trace.Op.String(),
  639. Gas: trace.Gas,
  640. GasCost: trace.GasCost,
  641. Depth: trace.Depth,
  642. Error: trace.Err,
  643. Stack: make([]string, len(trace.Stack)),
  644. Storage: make(map[string]string),
  645. }
  646. for i, stackValue := range trace.Stack {
  647. formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", common.LeftPadBytes(stackValue.Bytes(), 32))
  648. }
  649. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  650. formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  651. }
  652. for i, storageValue := range trace.Storage {
  653. formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  654. }
  655. }
  656. return formattedStructLogs
  657. }
  658. // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  659. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  660. // transaction hashes.
  661. func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  662. head := b.Header() // copies the header once
  663. fields := map[string]interface{}{
  664. "number": (*hexutil.Big)(head.Number),
  665. "hash": b.Hash(),
  666. "parentHash": head.ParentHash,
  667. "nonce": head.Nonce,
  668. "mixHash": head.MixDigest,
  669. "sha3Uncles": head.UncleHash,
  670. "logsBloom": head.Bloom,
  671. "stateRoot": head.Root,
  672. "miner": head.Coinbase,
  673. "difficulty": (*hexutil.Big)(head.Difficulty),
  674. "totalDifficulty": (*hexutil.Big)(s.b.GetTd(b.Hash())),
  675. "extraData": hexutil.Bytes(head.Extra),
  676. "size": hexutil.Uint64(uint64(b.Size().Int64())),
  677. "gasLimit": (*hexutil.Big)(head.GasLimit),
  678. "gasUsed": (*hexutil.Big)(head.GasUsed),
  679. "timestamp": (*hexutil.Big)(head.Time),
  680. "transactionsRoot": head.TxHash,
  681. "receiptsRoot": head.ReceiptHash,
  682. }
  683. if inclTx {
  684. formatTx := func(tx *types.Transaction) (interface{}, error) {
  685. return tx.Hash(), nil
  686. }
  687. if fullTx {
  688. formatTx = func(tx *types.Transaction) (interface{}, error) {
  689. return newRPCTransaction(b, tx.Hash())
  690. }
  691. }
  692. txs := b.Transactions()
  693. transactions := make([]interface{}, len(txs))
  694. var err error
  695. for i, tx := range b.Transactions() {
  696. if transactions[i], err = formatTx(tx); err != nil {
  697. return nil, err
  698. }
  699. }
  700. fields["transactions"] = transactions
  701. }
  702. uncles := b.Uncles()
  703. uncleHashes := make([]common.Hash, len(uncles))
  704. for i, uncle := range uncles {
  705. uncleHashes[i] = uncle.Hash()
  706. }
  707. fields["uncles"] = uncleHashes
  708. return fields, nil
  709. }
  710. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  711. type RPCTransaction struct {
  712. BlockHash common.Hash `json:"blockHash"`
  713. BlockNumber *hexutil.Big `json:"blockNumber"`
  714. From common.Address `json:"from"`
  715. Gas *hexutil.Big `json:"gas"`
  716. GasPrice *hexutil.Big `json:"gasPrice"`
  717. Hash common.Hash `json:"hash"`
  718. Input hexutil.Bytes `json:"input"`
  719. Nonce hexutil.Uint64 `json:"nonce"`
  720. To *common.Address `json:"to"`
  721. TransactionIndex hexutil.Uint `json:"transactionIndex"`
  722. Value *hexutil.Big `json:"value"`
  723. V *hexutil.Big `json:"v"`
  724. R *hexutil.Big `json:"r"`
  725. S *hexutil.Big `json:"s"`
  726. }
  727. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  728. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  729. var signer types.Signer = types.FrontierSigner{}
  730. if tx.Protected() {
  731. signer = types.NewEIP155Signer(tx.ChainId())
  732. }
  733. from, _ := types.Sender(signer, tx)
  734. v, r, s := tx.RawSignatureValues()
  735. return &RPCTransaction{
  736. From: from,
  737. Gas: (*hexutil.Big)(tx.Gas()),
  738. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  739. Hash: tx.Hash(),
  740. Input: hexutil.Bytes(tx.Data()),
  741. Nonce: hexutil.Uint64(tx.Nonce()),
  742. To: tx.To(),
  743. Value: (*hexutil.Big)(tx.Value()),
  744. V: (*hexutil.Big)(v),
  745. R: (*hexutil.Big)(r),
  746. S: (*hexutil.Big)(s),
  747. }
  748. }
  749. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  750. func newRPCTransactionFromBlockIndex(b *types.Block, txIndex uint) (*RPCTransaction, error) {
  751. if txIndex < uint(len(b.Transactions())) {
  752. tx := b.Transactions()[txIndex]
  753. var signer types.Signer = types.FrontierSigner{}
  754. if tx.Protected() {
  755. signer = types.NewEIP155Signer(tx.ChainId())
  756. }
  757. from, _ := types.Sender(signer, tx)
  758. v, r, s := tx.RawSignatureValues()
  759. return &RPCTransaction{
  760. BlockHash: b.Hash(),
  761. BlockNumber: (*hexutil.Big)(b.Number()),
  762. From: from,
  763. Gas: (*hexutil.Big)(tx.Gas()),
  764. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  765. Hash: tx.Hash(),
  766. Input: hexutil.Bytes(tx.Data()),
  767. Nonce: hexutil.Uint64(tx.Nonce()),
  768. To: tx.To(),
  769. TransactionIndex: hexutil.Uint(txIndex),
  770. Value: (*hexutil.Big)(tx.Value()),
  771. V: (*hexutil.Big)(v),
  772. R: (*hexutil.Big)(r),
  773. S: (*hexutil.Big)(s),
  774. }, nil
  775. }
  776. return nil, nil
  777. }
  778. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  779. func newRPCRawTransactionFromBlockIndex(b *types.Block, txIndex uint) (hexutil.Bytes, error) {
  780. if txIndex < uint(len(b.Transactions())) {
  781. tx := b.Transactions()[txIndex]
  782. return rlp.EncodeToBytes(tx)
  783. }
  784. return nil, nil
  785. }
  786. // newRPCTransaction returns a transaction that will serialize to the RPC representation.
  787. func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) {
  788. for idx, tx := range b.Transactions() {
  789. if tx.Hash() == txHash {
  790. return newRPCTransactionFromBlockIndex(b, uint(idx))
  791. }
  792. }
  793. return nil, nil
  794. }
  795. // PublicTransactionPoolAPI exposes methods for the RPC interface
  796. type PublicTransactionPoolAPI struct {
  797. b Backend
  798. }
  799. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  800. func NewPublicTransactionPoolAPI(b Backend) *PublicTransactionPoolAPI {
  801. return &PublicTransactionPoolAPI{b}
  802. }
  803. func getTransaction(chainDb ethdb.Database, b Backend, txHash common.Hash) (*types.Transaction, bool, error) {
  804. txData, err := chainDb.Get(txHash.Bytes())
  805. isPending := false
  806. tx := new(types.Transaction)
  807. if err == nil && len(txData) > 0 {
  808. if err := rlp.DecodeBytes(txData, tx); err != nil {
  809. return nil, isPending, err
  810. }
  811. } else {
  812. // pending transaction?
  813. tx = b.GetPoolTransaction(txHash)
  814. isPending = true
  815. }
  816. return tx, isPending, nil
  817. }
  818. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  819. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  820. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  821. n := hexutil.Uint(len(block.Transactions()))
  822. return &n
  823. }
  824. return nil
  825. }
  826. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  827. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  828. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  829. n := hexutil.Uint(len(block.Transactions()))
  830. return &n
  831. }
  832. return nil
  833. }
  834. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  835. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (*RPCTransaction, error) {
  836. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  837. return newRPCTransactionFromBlockIndex(block, uint(index))
  838. }
  839. return nil, nil
  840. }
  841. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  842. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (*RPCTransaction, error) {
  843. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  844. return newRPCTransactionFromBlockIndex(block, uint(index))
  845. }
  846. return nil, nil
  847. }
  848. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  849. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (hexutil.Bytes, error) {
  850. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  851. return newRPCRawTransactionFromBlockIndex(block, uint(index))
  852. }
  853. return nil, nil
  854. }
  855. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  856. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (hexutil.Bytes, error) {
  857. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  858. return newRPCRawTransactionFromBlockIndex(block, uint(index))
  859. }
  860. return nil, nil
  861. }
  862. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  863. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {
  864. state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  865. if state == nil || err != nil {
  866. return nil, err
  867. }
  868. nonce, err := state.GetNonce(ctx, address)
  869. if err != nil {
  870. return nil, err
  871. }
  872. return (*hexutil.Uint64)(&nonce), nil
  873. }
  874. // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to
  875. // retrieve block information for a hash. It returns the block hash, block index and transaction index.
  876. func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) {
  877. var txBlock struct {
  878. BlockHash common.Hash
  879. BlockIndex uint64
  880. Index uint64
  881. }
  882. blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001))
  883. if err != nil {
  884. return common.Hash{}, uint64(0), uint64(0), err
  885. }
  886. reader := bytes.NewReader(blockData)
  887. if err = rlp.Decode(reader, &txBlock); err != nil {
  888. return common.Hash{}, uint64(0), uint64(0), err
  889. }
  890. return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil
  891. }
  892. // GetTransactionByHash returns the transaction for the given hash
  893. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, txHash common.Hash) (*RPCTransaction, error) {
  894. var tx *types.Transaction
  895. var isPending bool
  896. var err error
  897. if tx, isPending, err = getTransaction(s.b.ChainDb(), s.b, txHash); err != nil {
  898. glog.V(logger.Debug).Infof("%v\n", err)
  899. return nil, nil
  900. } else if tx == nil {
  901. return nil, nil
  902. }
  903. if isPending {
  904. return newRPCPendingTransaction(tx), nil
  905. }
  906. blockHash, _, _, err := getTransactionBlockData(s.b.ChainDb(), txHash)
  907. if err != nil {
  908. glog.V(logger.Debug).Infof("%v\n", err)
  909. return nil, nil
  910. }
  911. if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  912. return newRPCTransaction(block, txHash)
  913. }
  914. return nil, nil
  915. }
  916. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  917. func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, txHash common.Hash) (hexutil.Bytes, error) {
  918. var tx *types.Transaction
  919. var err error
  920. if tx, _, err = getTransaction(s.b.ChainDb(), s.b, txHash); err != nil {
  921. glog.V(logger.Debug).Infof("%v\n", err)
  922. return nil, nil
  923. } else if tx == nil {
  924. return nil, nil
  925. }
  926. return rlp.EncodeToBytes(tx)
  927. }
  928. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  929. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(txHash common.Hash) (map[string]interface{}, error) {
  930. receipt := core.GetReceipt(s.b.ChainDb(), txHash)
  931. if receipt == nil {
  932. glog.V(logger.Debug).Infof("receipt not found for transaction %s", txHash.Hex())
  933. return nil, nil
  934. }
  935. tx, _, err := getTransaction(s.b.ChainDb(), s.b, txHash)
  936. if err != nil {
  937. glog.V(logger.Debug).Infof("%v\n", err)
  938. return nil, nil
  939. }
  940. txBlock, blockIndex, index, err := getTransactionBlockData(s.b.ChainDb(), txHash)
  941. if err != nil {
  942. glog.V(logger.Debug).Infof("%v\n", err)
  943. return nil, nil
  944. }
  945. var signer types.Signer = types.FrontierSigner{}
  946. if tx.Protected() {
  947. signer = types.NewEIP155Signer(tx.ChainId())
  948. }
  949. from, _ := types.Sender(signer, tx)
  950. fields := map[string]interface{}{
  951. "root": hexutil.Bytes(receipt.PostState),
  952. "blockHash": txBlock,
  953. "blockNumber": hexutil.Uint64(blockIndex),
  954. "transactionHash": txHash,
  955. "transactionIndex": hexutil.Uint64(index),
  956. "from": from,
  957. "to": tx.To(),
  958. "gasUsed": (*hexutil.Big)(receipt.GasUsed),
  959. "cumulativeGasUsed": (*hexutil.Big)(receipt.CumulativeGasUsed),
  960. "contractAddress": nil,
  961. "logs": receipt.Logs,
  962. "logsBloom": receipt.Bloom,
  963. }
  964. if receipt.Logs == nil {
  965. fields["logs"] = [][]*types.Log{}
  966. }
  967. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  968. if receipt.ContractAddress != (common.Address{}) {
  969. fields["contractAddress"] = receipt.ContractAddress
  970. }
  971. return fields, nil
  972. }
  973. // sign is a helper function that signs a transaction with the private key of the given address.
  974. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  975. // Look up the wallet containing the requested signer
  976. account := accounts.Account{Address: addr}
  977. wallet, err := s.b.AccountManager().Find(account)
  978. if err != nil {
  979. return nil, err
  980. }
  981. // Request the wallet to sign the transaction
  982. var chainID *big.Int
  983. if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  984. chainID = config.ChainId
  985. }
  986. return wallet.SignTx(account, tx, chainID)
  987. }
  988. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  989. type SendTxArgs struct {
  990. From common.Address `json:"from"`
  991. To *common.Address `json:"to"`
  992. Gas *hexutil.Big `json:"gas"`
  993. GasPrice *hexutil.Big `json:"gasPrice"`
  994. Value *hexutil.Big `json:"value"`
  995. Data hexutil.Bytes `json:"data"`
  996. Nonce *hexutil.Uint64 `json:"nonce"`
  997. }
  998. // prepareSendTxArgs is a helper function that fills in default values for unspecified tx fields.
  999. func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1000. if args.Gas == nil {
  1001. args.Gas = (*hexutil.Big)(big.NewInt(defaultGas))
  1002. }
  1003. if args.GasPrice == nil {
  1004. price, err := b.SuggestPrice(ctx)
  1005. if err != nil {
  1006. return err
  1007. }
  1008. args.GasPrice = (*hexutil.Big)(price)
  1009. }
  1010. if args.Value == nil {
  1011. args.Value = new(hexutil.Big)
  1012. }
  1013. if args.Nonce == nil {
  1014. nonce, err := b.GetPoolNonce(ctx, args.From)
  1015. if err != nil {
  1016. return err
  1017. }
  1018. args.Nonce = (*hexutil.Uint64)(&nonce)
  1019. }
  1020. return nil
  1021. }
  1022. func (args *SendTxArgs) toTransaction() *types.Transaction {
  1023. if args.To == nil {
  1024. return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), (*big.Int)(args.Gas), (*big.Int)(args.GasPrice), args.Data)
  1025. }
  1026. return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), (*big.Int)(args.Gas), (*big.Int)(args.GasPrice), args.Data)
  1027. }
  1028. // submitTransaction is a helper function that submits tx to txPool and logs a message.
  1029. func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1030. if err := b.SendTx(ctx, tx); err != nil {
  1031. return common.Hash{}, err
  1032. }
  1033. if tx.To() == nil {
  1034. signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1035. from, _ := types.Sender(signer, tx)
  1036. addr := crypto.CreateAddress(from, tx.Nonce())
  1037. glog.V(logger.Info).Infof("Tx(%s) created: %s\n", tx.Hash().Hex(), addr.Hex())
  1038. } else {
  1039. glog.V(logger.Info).Infof("Tx(%s) to: %s\n", tx.Hash().Hex(), tx.To().Hex())
  1040. }
  1041. return tx.Hash(), nil
  1042. }
  1043. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1044. // transaction pool.
  1045. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1046. // Set some sanity defaults and terminate on failure
  1047. if err := args.setDefaults(ctx, s.b); err != nil {
  1048. return common.Hash{}, err
  1049. }
  1050. // Look up the wallet containing the requested signer
  1051. account := accounts.Account{Address: args.From}
  1052. wallet, err := s.b.AccountManager().Find(account)
  1053. if err != nil {
  1054. return common.Hash{}, err
  1055. }
  1056. // Assemble the transaction and sign with the wallet
  1057. tx := args.toTransaction()
  1058. var chainID *big.Int
  1059. if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  1060. chainID = config.ChainId
  1061. }
  1062. signed, err := wallet.SignTx(account, tx, chainID)
  1063. if err != nil {
  1064. return common.Hash{}, err
  1065. }
  1066. return submitTransaction(ctx, s.b, signed)
  1067. }
  1068. // SendRawTransaction will add the signed transaction to the transaction pool.
  1069. // The sender is responsible for signing the transaction and using the correct nonce.
  1070. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (string, error) {
  1071. tx := new(types.Transaction)
  1072. if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1073. return "", err
  1074. }
  1075. if err := s.b.SendTx(ctx, tx); err != nil {
  1076. return "", err
  1077. }
  1078. signer := types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number())
  1079. if tx.To() == nil {
  1080. from, err := types.Sender(signer, tx)
  1081. if err != nil {
  1082. return "", err
  1083. }
  1084. addr := crypto.CreateAddress(from, tx.Nonce())
  1085. glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr)
  1086. } else {
  1087. glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To())
  1088. }
  1089. return tx.Hash().Hex(), nil
  1090. }
  1091. // Sign calculates an ECDSA signature for:
  1092. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1093. //
  1094. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1095. // where the V value will be 27 or 28 for legacy reasons.
  1096. //
  1097. // The account associated with addr must be unlocked.
  1098. //
  1099. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1100. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1101. // Look up the wallet containing the requested signer
  1102. account := accounts.Account{Address: addr}
  1103. wallet, err := s.b.AccountManager().Find(account)
  1104. if err != nil {
  1105. return nil, err
  1106. }
  1107. // Sign the requested hash with the wallet
  1108. signature, err := wallet.SignHash(account, signHash(data))
  1109. if err == nil {
  1110. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1111. }
  1112. return signature, err
  1113. }
  1114. // SignTransactionResult represents a RLP encoded signed transaction.
  1115. type SignTransactionResult struct {
  1116. Raw hexutil.Bytes `json:"raw"`
  1117. Tx *types.Transaction `json:"tx"`
  1118. }
  1119. // SignTransaction will sign the given transaction with the from account.
  1120. // The node needs to have the private key of the account corresponding with
  1121. // the given from address and it needs to be unlocked.
  1122. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1123. if err := args.setDefaults(ctx, s.b); err != nil {
  1124. return nil, err
  1125. }
  1126. tx, err := s.sign(args.From, args.toTransaction())
  1127. if err != nil {
  1128. return nil, err
  1129. }
  1130. data, err := rlp.EncodeToBytes(tx)
  1131. if err != nil {
  1132. return nil, err
  1133. }
  1134. return &SignTransactionResult{data, tx}, nil
  1135. }
  1136. // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1137. // the accounts this node manages.
  1138. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1139. pending, err := s.b.GetPoolTransactions()
  1140. if err != nil {
  1141. return nil, err
  1142. }
  1143. transactions := make([]*RPCTransaction, 0, len(pending))
  1144. for _, tx := range pending {
  1145. var signer types.Signer = types.HomesteadSigner{}
  1146. if tx.Protected() {
  1147. signer = types.NewEIP155Signer(tx.ChainId())
  1148. }
  1149. from, _ := types.Sender(signer, tx)
  1150. if _, err := s.b.AccountManager().Find(accounts.Account{Address: from}); err == nil {
  1151. transactions = append(transactions, newRPCPendingTransaction(tx))
  1152. }
  1153. }
  1154. return transactions, nil
  1155. }
  1156. // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1157. // the given transaction from the pool and reinsert it with the new gas price and limit.
  1158. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice, gasLimit *hexutil.Big) (common.Hash, error) {
  1159. if sendArgs.Nonce == nil {
  1160. return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1161. }
  1162. if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1163. return common.Hash{}, err
  1164. }
  1165. matchTx := sendArgs.toTransaction()
  1166. pending, err := s.b.GetPoolTransactions()
  1167. if err != nil {
  1168. return common.Hash{}, err
  1169. }
  1170. for _, p := range pending {
  1171. var signer types.Signer = types.HomesteadSigner{}
  1172. if p.Protected() {
  1173. signer = types.NewEIP155Signer(p.ChainId())
  1174. }
  1175. wantSigHash := signer.Hash(matchTx)
  1176. if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1177. // Match. Re-sign and send the transaction.
  1178. if gasPrice != nil {
  1179. sendArgs.GasPrice = gasPrice
  1180. }
  1181. if gasLimit != nil {
  1182. sendArgs.Gas = gasLimit
  1183. }
  1184. signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  1185. if err != nil {
  1186. return common.Hash{}, err
  1187. }
  1188. s.b.RemoveTx(p.Hash())
  1189. if err = s.b.SendTx(ctx, signedTx); err != nil {
  1190. return common.Hash{}, err
  1191. }
  1192. return signedTx.Hash(), nil
  1193. }
  1194. }
  1195. return common.Hash{}, fmt.Errorf("Transaction %#x not found", matchTx.Hash())
  1196. }
  1197. // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
  1198. // debugging endpoint.
  1199. type PublicDebugAPI struct {
  1200. b Backend
  1201. }
  1202. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1203. // of the Ethereum service.
  1204. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1205. return &PublicDebugAPI{b: b}
  1206. }
  1207. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1208. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1209. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1210. if block == nil {
  1211. return "", fmt.Errorf("block #%d not found", number)
  1212. }
  1213. encoded, err := rlp.EncodeToBytes(block)
  1214. if err != nil {
  1215. return "", err
  1216. }
  1217. return fmt.Sprintf("%x", encoded), nil
  1218. }
  1219. // PrintBlock retrieves a block and returns its pretty printed form.
  1220. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1221. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1222. if block == nil {
  1223. return "", fmt.Errorf("block #%d not found", number)
  1224. }
  1225. return fmt.Sprintf("%s", block), nil
  1226. }
  1227. // SeedHash retrieves the seed hash of a block.
  1228. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1229. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1230. if block == nil {
  1231. return "", fmt.Errorf("block #%d not found", number)
  1232. }
  1233. hash, err := ethash.GetSeedHash(number)
  1234. if err != nil {
  1235. return "", err
  1236. }
  1237. return fmt.Sprintf("0x%x", hash), nil
  1238. }
  1239. // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private
  1240. // debugging endpoint.
  1241. type PrivateDebugAPI struct {
  1242. b Backend
  1243. }
  1244. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1245. // of the Ethereum service.
  1246. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1247. return &PrivateDebugAPI{b: b}
  1248. }
  1249. // ChaindbProperty returns leveldb properties of the chain database.
  1250. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1251. ldb, ok := api.b.ChainDb().(interface {
  1252. LDB() *leveldb.DB
  1253. })
  1254. if !ok {
  1255. return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1256. }
  1257. if property == "" {
  1258. property = "leveldb.stats"
  1259. } else if !strings.HasPrefix(property, "leveldb.") {
  1260. property = "leveldb." + property
  1261. }
  1262. return ldb.LDB().GetProperty(property)
  1263. }
  1264. func (api *PrivateDebugAPI) ChaindbCompact() error {
  1265. ldb, ok := api.b.ChainDb().(interface {
  1266. LDB() *leveldb.DB
  1267. })
  1268. if !ok {
  1269. return fmt.Errorf("chaindbCompact does not work for memory databases")
  1270. }
  1271. for b := byte(0); b < 255; b++ {
  1272. glog.V(logger.Info).Infof("compacting chain DB range 0x%0.2X-0x%0.2X", b, b+1)
  1273. err := ldb.LDB().CompactRange(util.Range{Start: []byte{b}, Limit: []byte{b + 1}})
  1274. if err != nil {
  1275. glog.Errorf("compaction error: %v", err)
  1276. return err
  1277. }
  1278. }
  1279. return nil
  1280. }
  1281. // SetHead rewinds the head of the blockchain to a previous block.
  1282. func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1283. api.b.SetHead(uint64(number))
  1284. }
  1285. // PublicNetAPI offers network related RPC methods
  1286. type PublicNetAPI struct {
  1287. net *p2p.Server
  1288. networkVersion int
  1289. }
  1290. // NewPublicNetAPI creates a new net API instance.
  1291. func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI {
  1292. return &PublicNetAPI{net, networkVersion}
  1293. }
  1294. // Listening returns an indication if the node is listening for network connections.
  1295. func (s *PublicNetAPI) Listening() bool {
  1296. return true // always listening
  1297. }
  1298. // PeerCount returns the number of connected peers
  1299. func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1300. return hexutil.Uint(s.net.PeerCount())
  1301. }
  1302. // Version returns the current ethereum protocol version.
  1303. func (s *PublicNetAPI) Version() string {
  1304. return fmt.Sprintf("%d", s.networkVersion)
  1305. }