api.go 51 KB

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