api.go 50 KB

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