api.go 49 KB

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