api.go 51 KB

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