api.go 52 KB

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