api.go 52 KB

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