api.go 50 KB

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