api.go 49 KB

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