api.go 52 KB

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