api.go 50 KB

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