graphql.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. // Copyright 2018 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 graphql provides a GraphQL interface to Ethereum node data.
  17. package graphql
  18. import (
  19. "context"
  20. "fmt"
  21. "net"
  22. "net/http"
  23. "time"
  24. "github.com/ethereum/go-ethereum"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/hexutil"
  27. "github.com/ethereum/go-ethereum/core/rawdb"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/eth"
  32. "github.com/ethereum/go-ethereum/eth/filters"
  33. "github.com/ethereum/go-ethereum/internal/ethapi"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/node"
  36. "github.com/ethereum/go-ethereum/p2p"
  37. "github.com/ethereum/go-ethereum/rlp"
  38. "github.com/ethereum/go-ethereum/rpc"
  39. graphqlgo "github.com/graph-gophers/graphql-go"
  40. "github.com/graph-gophers/graphql-go/relay"
  41. )
  42. // Account represents an Ethereum account at a particular block.
  43. type Account struct {
  44. backend *eth.EthAPIBackend
  45. address common.Address
  46. blockNumber rpc.BlockNumber
  47. }
  48. // getState fetches the StateDB object for an account.
  49. func (a *Account) getState(ctx context.Context) (*state.StateDB, error) {
  50. state, _, err := a.backend.StateAndHeaderByNumber(ctx, a.blockNumber)
  51. return state, err
  52. }
  53. func (a *Account) Address(ctx context.Context) (common.Address, error) {
  54. return a.address, nil
  55. }
  56. func (a *Account) Balance(ctx context.Context) (hexutil.Big, error) {
  57. state, err := a.getState(ctx)
  58. if err != nil {
  59. return hexutil.Big{}, err
  60. }
  61. return hexutil.Big(*state.GetBalance(a.address)), nil
  62. }
  63. func (a *Account) TransactionCount(ctx context.Context) (hexutil.Uint64, error) {
  64. state, err := a.getState(ctx)
  65. if err != nil {
  66. return 0, err
  67. }
  68. return hexutil.Uint64(state.GetNonce(a.address)), nil
  69. }
  70. func (a *Account) Code(ctx context.Context) (hexutil.Bytes, error) {
  71. state, err := a.getState(ctx)
  72. if err != nil {
  73. return hexutil.Bytes{}, err
  74. }
  75. return hexutil.Bytes(state.GetCode(a.address)), nil
  76. }
  77. func (a *Account) Storage(ctx context.Context, args struct{ Slot common.Hash }) (common.Hash, error) {
  78. state, err := a.getState(ctx)
  79. if err != nil {
  80. return common.Hash{}, err
  81. }
  82. return state.GetState(a.address, args.Slot), nil
  83. }
  84. // Log represents an individual log message. All arguments are mandatory.
  85. type Log struct {
  86. backend *eth.EthAPIBackend
  87. transaction *Transaction
  88. log *types.Log
  89. }
  90. func (l *Log) Transaction(ctx context.Context) *Transaction {
  91. return l.transaction
  92. }
  93. func (l *Log) Account(ctx context.Context, args BlockNumberArgs) *Account {
  94. return &Account{
  95. backend: l.backend,
  96. address: l.log.Address,
  97. blockNumber: args.Number(),
  98. }
  99. }
  100. func (l *Log) Index(ctx context.Context) int32 {
  101. return int32(l.log.Index)
  102. }
  103. func (l *Log) Topics(ctx context.Context) []common.Hash {
  104. return l.log.Topics
  105. }
  106. func (l *Log) Data(ctx context.Context) hexutil.Bytes {
  107. return hexutil.Bytes(l.log.Data)
  108. }
  109. // Transaction represents an Ethereum transaction.
  110. // backend and hash are mandatory; all others will be fetched when required.
  111. type Transaction struct {
  112. backend *eth.EthAPIBackend
  113. hash common.Hash
  114. tx *types.Transaction
  115. block *Block
  116. index uint64
  117. }
  118. // resolve returns the internal transaction object, fetching it if needed.
  119. func (t *Transaction) resolve(ctx context.Context) (*types.Transaction, error) {
  120. if t.tx == nil {
  121. tx, blockHash, _, index := rawdb.ReadTransaction(t.backend.ChainDb(), t.hash)
  122. if tx != nil {
  123. t.tx = tx
  124. t.block = &Block{
  125. backend: t.backend,
  126. hash: blockHash,
  127. }
  128. t.index = index
  129. } else {
  130. t.tx = t.backend.GetPoolTransaction(t.hash)
  131. }
  132. }
  133. return t.tx, nil
  134. }
  135. func (tx *Transaction) Hash(ctx context.Context) common.Hash {
  136. return tx.hash
  137. }
  138. func (t *Transaction) InputData(ctx context.Context) (hexutil.Bytes, error) {
  139. tx, err := t.resolve(ctx)
  140. if err != nil || tx == nil {
  141. return hexutil.Bytes{}, err
  142. }
  143. return hexutil.Bytes(tx.Data()), nil
  144. }
  145. func (t *Transaction) Gas(ctx context.Context) (hexutil.Uint64, error) {
  146. tx, err := t.resolve(ctx)
  147. if err != nil || tx == nil {
  148. return 0, err
  149. }
  150. return hexutil.Uint64(tx.Gas()), nil
  151. }
  152. func (t *Transaction) GasPrice(ctx context.Context) (hexutil.Big, error) {
  153. tx, err := t.resolve(ctx)
  154. if err != nil || tx == nil {
  155. return hexutil.Big{}, err
  156. }
  157. return hexutil.Big(*tx.GasPrice()), nil
  158. }
  159. func (t *Transaction) Value(ctx context.Context) (hexutil.Big, error) {
  160. tx, err := t.resolve(ctx)
  161. if err != nil || tx == nil {
  162. return hexutil.Big{}, err
  163. }
  164. return hexutil.Big(*tx.Value()), nil
  165. }
  166. func (t *Transaction) Nonce(ctx context.Context) (hexutil.Uint64, error) {
  167. tx, err := t.resolve(ctx)
  168. if err != nil || tx == nil {
  169. return 0, err
  170. }
  171. return hexutil.Uint64(tx.Nonce()), nil
  172. }
  173. func (t *Transaction) To(ctx context.Context, args BlockNumberArgs) (*Account, error) {
  174. tx, err := t.resolve(ctx)
  175. if err != nil || tx == nil {
  176. return nil, err
  177. }
  178. to := tx.To()
  179. if to == nil {
  180. return nil, nil
  181. }
  182. return &Account{
  183. backend: t.backend,
  184. address: *to,
  185. blockNumber: args.Number(),
  186. }, nil
  187. }
  188. func (t *Transaction) From(ctx context.Context, args BlockNumberArgs) (*Account, error) {
  189. tx, err := t.resolve(ctx)
  190. if err != nil || tx == nil {
  191. return nil, err
  192. }
  193. var signer types.Signer = types.FrontierSigner{}
  194. if tx.Protected() {
  195. signer = types.NewEIP155Signer(tx.ChainId())
  196. }
  197. from, _ := types.Sender(signer, tx)
  198. return &Account{
  199. backend: t.backend,
  200. address: from,
  201. blockNumber: args.Number(),
  202. }, nil
  203. }
  204. func (t *Transaction) Block(ctx context.Context) (*Block, error) {
  205. if _, err := t.resolve(ctx); err != nil {
  206. return nil, err
  207. }
  208. return t.block, nil
  209. }
  210. func (t *Transaction) Index(ctx context.Context) (*int32, error) {
  211. if _, err := t.resolve(ctx); err != nil {
  212. return nil, err
  213. }
  214. if t.block == nil {
  215. return nil, nil
  216. }
  217. index := int32(t.index)
  218. return &index, nil
  219. }
  220. // getReceipt returns the receipt associated with this transaction, if any.
  221. func (t *Transaction) getReceipt(ctx context.Context) (*types.Receipt, error) {
  222. if _, err := t.resolve(ctx); err != nil {
  223. return nil, err
  224. }
  225. if t.block == nil {
  226. return nil, nil
  227. }
  228. receipts, err := t.block.resolveReceipts(ctx)
  229. if err != nil {
  230. return nil, err
  231. }
  232. return receipts[t.index], nil
  233. }
  234. func (t *Transaction) Status(ctx context.Context) (*hexutil.Uint64, error) {
  235. receipt, err := t.getReceipt(ctx)
  236. if err != nil || receipt == nil {
  237. return nil, err
  238. }
  239. ret := hexutil.Uint64(receipt.Status)
  240. return &ret, nil
  241. }
  242. func (t *Transaction) GasUsed(ctx context.Context) (*hexutil.Uint64, error) {
  243. receipt, err := t.getReceipt(ctx)
  244. if err != nil || receipt == nil {
  245. return nil, err
  246. }
  247. ret := hexutil.Uint64(receipt.GasUsed)
  248. return &ret, nil
  249. }
  250. func (t *Transaction) CumulativeGasUsed(ctx context.Context) (*hexutil.Uint64, error) {
  251. receipt, err := t.getReceipt(ctx)
  252. if err != nil || receipt == nil {
  253. return nil, err
  254. }
  255. ret := hexutil.Uint64(receipt.CumulativeGasUsed)
  256. return &ret, nil
  257. }
  258. func (t *Transaction) CreatedContract(ctx context.Context, args BlockNumberArgs) (*Account, error) {
  259. receipt, err := t.getReceipt(ctx)
  260. if err != nil || receipt == nil || receipt.ContractAddress == (common.Address{}) {
  261. return nil, err
  262. }
  263. return &Account{
  264. backend: t.backend,
  265. address: receipt.ContractAddress,
  266. blockNumber: args.Number(),
  267. }, nil
  268. }
  269. func (t *Transaction) Logs(ctx context.Context) (*[]*Log, error) {
  270. receipt, err := t.getReceipt(ctx)
  271. if err != nil || receipt == nil {
  272. return nil, err
  273. }
  274. ret := make([]*Log, 0, len(receipt.Logs))
  275. for _, log := range receipt.Logs {
  276. ret = append(ret, &Log{
  277. backend: t.backend,
  278. transaction: t,
  279. log: log,
  280. })
  281. }
  282. return &ret, nil
  283. }
  284. // Block represennts an Ethereum block.
  285. // backend, and either num or hash are mandatory. All other fields are lazily fetched
  286. // when required.
  287. type Block struct {
  288. backend *eth.EthAPIBackend
  289. num *rpc.BlockNumber
  290. hash common.Hash
  291. header *types.Header
  292. block *types.Block
  293. receipts []*types.Receipt
  294. }
  295. // resolve returns the internal Block object representing this block, fetching
  296. // it if necessary.
  297. func (b *Block) resolve(ctx context.Context) (*types.Block, error) {
  298. if b.block != nil {
  299. return b.block, nil
  300. }
  301. var err error
  302. if b.hash != (common.Hash{}) {
  303. b.block, err = b.backend.GetBlock(ctx, b.hash)
  304. } else {
  305. b.block, err = b.backend.BlockByNumber(ctx, *b.num)
  306. }
  307. if b.block != nil {
  308. b.header = b.block.Header()
  309. }
  310. return b.block, err
  311. }
  312. // resolveHeader returns the internal Header object for this block, fetching it
  313. // if necessary. Call this function instead of `resolve` unless you need the
  314. // additional data (transactions and uncles).
  315. func (b *Block) resolveHeader(ctx context.Context) (*types.Header, error) {
  316. if b.header == nil {
  317. if _, err := b.resolve(ctx); err != nil {
  318. return nil, err
  319. }
  320. }
  321. return b.header, nil
  322. }
  323. // resolveReceipts returns the list of receipts for this block, fetching them
  324. // if necessary.
  325. func (b *Block) resolveReceipts(ctx context.Context) ([]*types.Receipt, error) {
  326. if b.receipts == nil {
  327. hash := b.hash
  328. if hash == (common.Hash{}) {
  329. header, err := b.resolveHeader(ctx)
  330. if err != nil {
  331. return nil, err
  332. }
  333. hash = header.Hash()
  334. }
  335. receipts, err := b.backend.GetReceipts(ctx, hash)
  336. if err != nil {
  337. return nil, err
  338. }
  339. b.receipts = []*types.Receipt(receipts)
  340. }
  341. return b.receipts, nil
  342. }
  343. func (b *Block) Number(ctx context.Context) (hexutil.Uint64, error) {
  344. if b.num == nil || *b.num == rpc.LatestBlockNumber {
  345. header, err := b.resolveHeader(ctx)
  346. if err != nil {
  347. return 0, err
  348. }
  349. num := rpc.BlockNumber(header.Number.Uint64())
  350. b.num = &num
  351. }
  352. return hexutil.Uint64(*b.num), nil
  353. }
  354. func (b *Block) Hash(ctx context.Context) (common.Hash, error) {
  355. if b.hash == (common.Hash{}) {
  356. header, err := b.resolveHeader(ctx)
  357. if err != nil {
  358. return common.Hash{}, err
  359. }
  360. b.hash = header.Hash()
  361. }
  362. return b.hash, nil
  363. }
  364. func (b *Block) GasLimit(ctx context.Context) (hexutil.Uint64, error) {
  365. header, err := b.resolveHeader(ctx)
  366. if err != nil {
  367. return 0, err
  368. }
  369. return hexutil.Uint64(header.GasLimit), nil
  370. }
  371. func (b *Block) GasUsed(ctx context.Context) (hexutil.Uint64, error) {
  372. header, err := b.resolveHeader(ctx)
  373. if err != nil {
  374. return 0, err
  375. }
  376. return hexutil.Uint64(header.GasUsed), nil
  377. }
  378. func (b *Block) Parent(ctx context.Context) (*Block, error) {
  379. // If the block hasn't been fetched, and we'll need it, fetch it.
  380. if b.num == nil && b.hash != (common.Hash{}) && b.header == nil {
  381. if _, err := b.resolve(ctx); err != nil {
  382. return nil, err
  383. }
  384. }
  385. if b.header != nil && b.block.NumberU64() > 0 {
  386. num := rpc.BlockNumber(b.header.Number.Uint64() - 1)
  387. return &Block{
  388. backend: b.backend,
  389. num: &num,
  390. hash: b.header.ParentHash,
  391. }, nil
  392. } else if b.num != nil && *b.num != 0 {
  393. num := *b.num - 1
  394. return &Block{
  395. backend: b.backend,
  396. num: &num,
  397. }, nil
  398. }
  399. return nil, nil
  400. }
  401. func (b *Block) Difficulty(ctx context.Context) (hexutil.Big, error) {
  402. header, err := b.resolveHeader(ctx)
  403. if err != nil {
  404. return hexutil.Big{}, err
  405. }
  406. return hexutil.Big(*header.Difficulty), nil
  407. }
  408. func (b *Block) Timestamp(ctx context.Context) (hexutil.Big, error) {
  409. header, err := b.resolveHeader(ctx)
  410. if err != nil {
  411. return hexutil.Big{}, err
  412. }
  413. return hexutil.Big(*header.Time), nil
  414. }
  415. func (b *Block) Nonce(ctx context.Context) (hexutil.Bytes, error) {
  416. header, err := b.resolveHeader(ctx)
  417. if err != nil {
  418. return hexutil.Bytes{}, err
  419. }
  420. return hexutil.Bytes(header.Nonce[:]), nil
  421. }
  422. func (b *Block) MixHash(ctx context.Context) (common.Hash, error) {
  423. header, err := b.resolveHeader(ctx)
  424. if err != nil {
  425. return common.Hash{}, err
  426. }
  427. return header.MixDigest, nil
  428. }
  429. func (b *Block) TransactionsRoot(ctx context.Context) (common.Hash, error) {
  430. header, err := b.resolveHeader(ctx)
  431. if err != nil {
  432. return common.Hash{}, err
  433. }
  434. return header.TxHash, nil
  435. }
  436. func (b *Block) StateRoot(ctx context.Context) (common.Hash, error) {
  437. header, err := b.resolveHeader(ctx)
  438. if err != nil {
  439. return common.Hash{}, err
  440. }
  441. return header.Root, nil
  442. }
  443. func (b *Block) ReceiptsRoot(ctx context.Context) (common.Hash, error) {
  444. header, err := b.resolveHeader(ctx)
  445. if err != nil {
  446. return common.Hash{}, err
  447. }
  448. return header.ReceiptHash, nil
  449. }
  450. func (b *Block) OmmerHash(ctx context.Context) (common.Hash, error) {
  451. header, err := b.resolveHeader(ctx)
  452. if err != nil {
  453. return common.Hash{}, err
  454. }
  455. return header.UncleHash, nil
  456. }
  457. func (b *Block) OmmerCount(ctx context.Context) (*int32, error) {
  458. block, err := b.resolve(ctx)
  459. if err != nil || block == nil {
  460. return nil, err
  461. }
  462. count := int32(len(block.Uncles()))
  463. return &count, err
  464. }
  465. func (b *Block) Ommers(ctx context.Context) (*[]*Block, error) {
  466. block, err := b.resolve(ctx)
  467. if err != nil || block == nil {
  468. return nil, err
  469. }
  470. ret := make([]*Block, 0, len(block.Uncles()))
  471. for _, uncle := range block.Uncles() {
  472. blockNumber := rpc.BlockNumber(uncle.Number.Uint64())
  473. ret = append(ret, &Block{
  474. backend: b.backend,
  475. num: &blockNumber,
  476. hash: uncle.Hash(),
  477. header: uncle,
  478. })
  479. }
  480. return &ret, nil
  481. }
  482. func (b *Block) ExtraData(ctx context.Context) (hexutil.Bytes, error) {
  483. header, err := b.resolveHeader(ctx)
  484. if err != nil {
  485. return hexutil.Bytes{}, err
  486. }
  487. return hexutil.Bytes(header.Extra), nil
  488. }
  489. func (b *Block) LogsBloom(ctx context.Context) (hexutil.Bytes, error) {
  490. header, err := b.resolveHeader(ctx)
  491. if err != nil {
  492. return hexutil.Bytes{}, err
  493. }
  494. return hexutil.Bytes(header.Bloom.Bytes()), nil
  495. }
  496. func (b *Block) TotalDifficulty(ctx context.Context) (hexutil.Big, error) {
  497. h := b.hash
  498. if h == (common.Hash{}) {
  499. header, err := b.resolveHeader(ctx)
  500. if err != nil {
  501. return hexutil.Big{}, err
  502. }
  503. h = header.Hash()
  504. }
  505. return hexutil.Big(*b.backend.GetTd(h)), nil
  506. }
  507. // BlockNumberArgs encapsulates arguments to accessors that specify a block number.
  508. type BlockNumberArgs struct {
  509. Block *hexutil.Uint64
  510. }
  511. // Number returns the provided block number, or rpc.LatestBlockNumber if none
  512. // was provided.
  513. func (a BlockNumberArgs) Number() rpc.BlockNumber {
  514. if a.Block != nil {
  515. return rpc.BlockNumber(*a.Block)
  516. }
  517. return rpc.LatestBlockNumber
  518. }
  519. func (b *Block) Miner(ctx context.Context, args BlockNumberArgs) (*Account, error) {
  520. block, err := b.resolve(ctx)
  521. if err != nil {
  522. return nil, err
  523. }
  524. return &Account{
  525. backend: b.backend,
  526. address: block.Coinbase(),
  527. blockNumber: args.Number(),
  528. }, nil
  529. }
  530. func (b *Block) TransactionCount(ctx context.Context) (*int32, error) {
  531. block, err := b.resolve(ctx)
  532. if err != nil || block == nil {
  533. return nil, err
  534. }
  535. count := int32(len(block.Transactions()))
  536. return &count, err
  537. }
  538. func (b *Block) Transactions(ctx context.Context) (*[]*Transaction, error) {
  539. block, err := b.resolve(ctx)
  540. if err != nil || block == nil {
  541. return nil, err
  542. }
  543. ret := make([]*Transaction, 0, len(block.Transactions()))
  544. for i, tx := range block.Transactions() {
  545. ret = append(ret, &Transaction{
  546. backend: b.backend,
  547. hash: tx.Hash(),
  548. tx: tx,
  549. block: b,
  550. index: uint64(i),
  551. })
  552. }
  553. return &ret, nil
  554. }
  555. func (b *Block) TransactionAt(ctx context.Context, args struct{ Index int32 }) (*Transaction, error) {
  556. block, err := b.resolve(ctx)
  557. if err != nil || block == nil {
  558. return nil, err
  559. }
  560. txes := block.Transactions()
  561. if args.Index < 0 || int(args.Index) >= len(txes) {
  562. return nil, nil
  563. }
  564. tx := txes[args.Index]
  565. return &Transaction{
  566. backend: b.backend,
  567. hash: tx.Hash(),
  568. tx: tx,
  569. block: b,
  570. index: uint64(args.Index),
  571. }, nil
  572. }
  573. func (b *Block) OmmerAt(ctx context.Context, args struct{ Index int32 }) (*Block, error) {
  574. block, err := b.resolve(ctx)
  575. if err != nil || block == nil {
  576. return nil, err
  577. }
  578. uncles := block.Uncles()
  579. if args.Index < 0 || int(args.Index) >= len(uncles) {
  580. return nil, nil
  581. }
  582. uncle := uncles[args.Index]
  583. blockNumber := rpc.BlockNumber(uncle.Number.Uint64())
  584. return &Block{
  585. backend: b.backend,
  586. num: &blockNumber,
  587. hash: uncle.Hash(),
  588. header: uncle,
  589. }, nil
  590. }
  591. // BlockFilterCriteria encapsulates criteria passed to a `logs` accessor inside
  592. // a block.
  593. type BlockFilterCriteria struct {
  594. Addresses *[]common.Address // restricts matches to events created by specific contracts
  595. // The Topic list restricts matches to particular event topics. Each event has a list
  596. // of topics. Topics matches a prefix of that list. An empty element slice matches any
  597. // topic. Non-empty elements represent an alternative that matches any of the
  598. // contained topics.
  599. //
  600. // Examples:
  601. // {} or nil matches any topic list
  602. // {{A}} matches topic A in first position
  603. // {{}, {B}} matches any topic in first position, B in second position
  604. // {{A}, {B}} matches topic A in first position, B in second position
  605. // {{A, B}}, {C, D}} matches topic (A OR B) in first position, (C OR D) in second position
  606. Topics *[][]common.Hash
  607. }
  608. // runFilter accepts a filter and executes it, returning all its results as
  609. // `Log` objects.
  610. func runFilter(ctx context.Context, be *eth.EthAPIBackend, filter *filters.Filter) ([]*Log, error) {
  611. logs, err := filter.Logs(ctx)
  612. if err != nil || logs == nil {
  613. return nil, err
  614. }
  615. ret := make([]*Log, 0, len(logs))
  616. for _, log := range logs {
  617. ret = append(ret, &Log{
  618. backend: be,
  619. transaction: &Transaction{backend: be, hash: log.TxHash},
  620. log: log,
  621. })
  622. }
  623. return ret, nil
  624. }
  625. func (b *Block) Logs(ctx context.Context, args struct{ Filter BlockFilterCriteria }) ([]*Log, error) {
  626. var addresses []common.Address
  627. if args.Filter.Addresses != nil {
  628. addresses = *args.Filter.Addresses
  629. }
  630. var topics [][]common.Hash
  631. if args.Filter.Topics != nil {
  632. topics = *args.Filter.Topics
  633. }
  634. hash := b.hash
  635. if hash == (common.Hash{}) {
  636. block, err := b.resolve(ctx)
  637. if err != nil {
  638. return nil, err
  639. }
  640. hash = block.Hash()
  641. }
  642. // Construct the range filter
  643. filter := filters.NewBlockFilter(b.backend, hash, addresses, topics)
  644. // Run the filter and return all the logs
  645. return runFilter(ctx, b.backend, filter)
  646. }
  647. // Resolver is the top-level object in the GraphQL hierarchy.
  648. type Resolver struct {
  649. backend *eth.EthAPIBackend
  650. }
  651. func (r *Resolver) Block(ctx context.Context, args struct {
  652. Number *hexutil.Uint64
  653. Hash *common.Hash
  654. }) (*Block, error) {
  655. var block *Block
  656. if args.Number != nil {
  657. num := rpc.BlockNumber(uint64(*args.Number))
  658. block = &Block{
  659. backend: r.backend,
  660. num: &num,
  661. }
  662. } else if args.Hash != nil {
  663. block = &Block{
  664. backend: r.backend,
  665. hash: *args.Hash,
  666. }
  667. } else {
  668. num := rpc.LatestBlockNumber
  669. block = &Block{
  670. backend: r.backend,
  671. num: &num,
  672. }
  673. }
  674. // Resolve the block; if it doesn't exist, return nil.
  675. b, err := block.resolve(ctx)
  676. if err != nil {
  677. return nil, err
  678. } else if b == nil {
  679. return nil, nil
  680. }
  681. return block, nil
  682. }
  683. func (r *Resolver) Blocks(ctx context.Context, args struct {
  684. From hexutil.Uint64
  685. To *hexutil.Uint64
  686. }) ([]*Block, error) {
  687. from := rpc.BlockNumber(args.From)
  688. var to rpc.BlockNumber
  689. if args.To != nil {
  690. to = rpc.BlockNumber(*args.To)
  691. } else {
  692. to = rpc.BlockNumber(r.backend.CurrentBlock().Number().Int64())
  693. }
  694. if to < from {
  695. return []*Block{}, nil
  696. }
  697. ret := make([]*Block, 0, to-from+1)
  698. for i := from; i <= to; i++ {
  699. num := i
  700. ret = append(ret, &Block{
  701. backend: r.backend,
  702. num: &num,
  703. })
  704. }
  705. return ret, nil
  706. }
  707. func (r *Resolver) Account(ctx context.Context, args struct {
  708. Address common.Address
  709. BlockNumber *hexutil.Uint64
  710. }) *Account {
  711. blockNumber := rpc.LatestBlockNumber
  712. if args.BlockNumber != nil {
  713. blockNumber = rpc.BlockNumber(*args.BlockNumber)
  714. }
  715. return &Account{
  716. backend: r.backend,
  717. address: args.Address,
  718. blockNumber: blockNumber,
  719. }
  720. }
  721. func (r *Resolver) Transaction(ctx context.Context, args struct{ Hash common.Hash }) (*Transaction, error) {
  722. tx := &Transaction{
  723. backend: r.backend,
  724. hash: args.Hash,
  725. }
  726. // Resolve the transaction; if it doesn't exist, return nil.
  727. t, err := tx.resolve(ctx)
  728. if err != nil {
  729. return nil, err
  730. } else if t == nil {
  731. return nil, nil
  732. }
  733. return tx, nil
  734. }
  735. func (r *Resolver) SendRawTransaction(ctx context.Context, args struct{ Data hexutil.Bytes }) (common.Hash, error) {
  736. tx := new(types.Transaction)
  737. if err := rlp.DecodeBytes(args.Data, tx); err != nil {
  738. return common.Hash{}, err
  739. }
  740. hash, err := ethapi.SubmitTransaction(ctx, r.backend, tx)
  741. return hash, err
  742. }
  743. // CallData encapsulates arguments to `call` or `estimateGas`.
  744. // All arguments are optional.
  745. type CallData struct {
  746. From *common.Address // The Ethereum address the call is from.
  747. To *common.Address // The Ethereum address the call is to.
  748. Gas *hexutil.Uint64 // The amount of gas provided for the call.
  749. GasPrice *hexutil.Big // The price of each unit of gas, in wei.
  750. Value *hexutil.Big // The value sent along with the call.
  751. Data *hexutil.Bytes // Any data sent with the call.
  752. }
  753. // CallResult encapsulates the result of an invocation of the `call` accessor.
  754. type CallResult struct {
  755. data hexutil.Bytes // The return data from the call
  756. gasUsed hexutil.Uint64 // The amount of gas used
  757. status hexutil.Uint64 // The return status of the call - 0 for failure or 1 for success.
  758. }
  759. func (c *CallResult) Data() hexutil.Bytes {
  760. return c.data
  761. }
  762. func (c *CallResult) GasUsed() hexutil.Uint64 {
  763. return c.gasUsed
  764. }
  765. func (c *CallResult) Status() hexutil.Uint64 {
  766. return c.status
  767. }
  768. func (r *Resolver) Call(ctx context.Context, args struct {
  769. Data ethapi.CallArgs
  770. BlockNumber *hexutil.Uint64
  771. }) (*CallResult, error) {
  772. blockNumber := rpc.LatestBlockNumber
  773. if args.BlockNumber != nil {
  774. blockNumber = rpc.BlockNumber(*args.BlockNumber)
  775. }
  776. result, gas, failed, err := ethapi.DoCall(ctx, r.backend, args.Data, blockNumber, vm.Config{}, 5*time.Second)
  777. status := hexutil.Uint64(1)
  778. if failed {
  779. status = 0
  780. }
  781. return &CallResult{
  782. data: hexutil.Bytes(result),
  783. gasUsed: hexutil.Uint64(gas),
  784. status: status,
  785. }, err
  786. }
  787. func (r *Resolver) EstimateGas(ctx context.Context, args struct {
  788. Data ethapi.CallArgs
  789. BlockNumber *hexutil.Uint64
  790. }) (hexutil.Uint64, error) {
  791. blockNumber := rpc.LatestBlockNumber
  792. if args.BlockNumber != nil {
  793. blockNumber = rpc.BlockNumber(*args.BlockNumber)
  794. }
  795. gas, err := ethapi.DoEstimateGas(ctx, r.backend, args.Data, blockNumber)
  796. return gas, err
  797. }
  798. // FilterCriteria encapsulates the arguments to `logs` on the root resolver object.
  799. type FilterCriteria struct {
  800. FromBlock *hexutil.Uint64 // beginning of the queried range, nil means genesis block
  801. ToBlock *hexutil.Uint64 // end of the range, nil means latest block
  802. Addresses *[]common.Address // restricts matches to events created by specific contracts
  803. // The Topic list restricts matches to particular event topics. Each event has a list
  804. // of topics. Topics matches a prefix of that list. An empty element slice matches any
  805. // topic. Non-empty elements represent an alternative that matches any of the
  806. // contained topics.
  807. //
  808. // Examples:
  809. // {} or nil matches any topic list
  810. // {{A}} matches topic A in first position
  811. // {{}, {B}} matches any topic in first position, B in second position
  812. // {{A}, {B}} matches topic A in first position, B in second position
  813. // {{A, B}}, {C, D}} matches topic (A OR B) in first position, (C OR D) in second position
  814. Topics *[][]common.Hash
  815. }
  816. func (r *Resolver) Logs(ctx context.Context, args struct{ Filter FilterCriteria }) ([]*Log, error) {
  817. // Convert the RPC block numbers into internal representations
  818. begin := rpc.LatestBlockNumber.Int64()
  819. if args.Filter.FromBlock != nil {
  820. begin = int64(*args.Filter.FromBlock)
  821. }
  822. end := rpc.LatestBlockNumber.Int64()
  823. if args.Filter.ToBlock != nil {
  824. end = int64(*args.Filter.ToBlock)
  825. }
  826. var addresses []common.Address
  827. if args.Filter.Addresses != nil {
  828. addresses = *args.Filter.Addresses
  829. }
  830. var topics [][]common.Hash
  831. if args.Filter.Topics != nil {
  832. topics = *args.Filter.Topics
  833. }
  834. // Construct the range filter
  835. filter := filters.NewRangeFilter(filters.Backend(r.backend), begin, end, addresses, topics)
  836. return runFilter(ctx, r.backend, filter)
  837. }
  838. func (r *Resolver) GasPrice(ctx context.Context) (hexutil.Big, error) {
  839. price, err := r.backend.SuggestPrice(ctx)
  840. return hexutil.Big(*price), err
  841. }
  842. func (r *Resolver) ProtocolVersion(ctx context.Context) (int32, error) {
  843. return int32(r.backend.ProtocolVersion()), nil
  844. }
  845. // SyncState represents the synchronisation status returned from the `syncing` accessor.
  846. type SyncState struct {
  847. progress ethereum.SyncProgress
  848. }
  849. func (s *SyncState) StartingBlock() hexutil.Uint64 {
  850. return hexutil.Uint64(s.progress.StartingBlock)
  851. }
  852. func (s *SyncState) CurrentBlock() hexutil.Uint64 {
  853. return hexutil.Uint64(s.progress.CurrentBlock)
  854. }
  855. func (s *SyncState) HighestBlock() hexutil.Uint64 {
  856. return hexutil.Uint64(s.progress.HighestBlock)
  857. }
  858. func (s *SyncState) PulledStates() *hexutil.Uint64 {
  859. ret := hexutil.Uint64(s.progress.PulledStates)
  860. return &ret
  861. }
  862. func (s *SyncState) KnownStates() *hexutil.Uint64 {
  863. ret := hexutil.Uint64(s.progress.KnownStates)
  864. return &ret
  865. }
  866. // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
  867. // yet received the latest block headers from its pears. In case it is synchronizing:
  868. // - startingBlock: block number this node started to synchronise from
  869. // - currentBlock: block number this node is currently importing
  870. // - highestBlock: block number of the highest block header this node has received from peers
  871. // - pulledStates: number of state entries processed until now
  872. // - knownStates: number of known state entries that still need to be pulled
  873. func (r *Resolver) Syncing() (*SyncState, error) {
  874. progress := r.backend.Downloader().Progress()
  875. // Return not syncing if the synchronisation already completed
  876. if progress.CurrentBlock >= progress.HighestBlock {
  877. return nil, nil
  878. }
  879. // Otherwise gather the block sync stats
  880. return &SyncState{progress}, nil
  881. }
  882. // NewHandler returns a new `http.Handler` that will answer GraphQL queries.
  883. // It additionally exports an interactive query browser on the / endpoint.
  884. func NewHandler(be *eth.EthAPIBackend) (http.Handler, error) {
  885. q := Resolver{be}
  886. s, err := graphqlgo.ParseSchema(schema, &q)
  887. if err != nil {
  888. return nil, err
  889. }
  890. h := &relay.Handler{Schema: s}
  891. mux := http.NewServeMux()
  892. mux.Handle("/", GraphiQL{})
  893. mux.Handle("/graphql", h)
  894. mux.Handle("/graphql/", h)
  895. return mux, nil
  896. }
  897. // Service encapsulates a GraphQL service.
  898. type Service struct {
  899. endpoint string // The host:port endpoint for this service.
  900. cors []string // Allowed CORS domains
  901. vhosts []string // Recognised vhosts
  902. timeouts rpc.HTTPTimeouts // Timeout settings for HTTP requests.
  903. backend *eth.EthAPIBackend // The backend that queries will operate onn.
  904. handler http.Handler // The `http.Handler` used to answer queries.
  905. listener net.Listener // The listening socket.
  906. }
  907. // Protocols returns the list of protocols exported by this service.
  908. func (s *Service) Protocols() []p2p.Protocol { return nil }
  909. // APIs returns the list of APIs exported by this service.
  910. func (s *Service) APIs() []rpc.API { return nil }
  911. // Start is called after all services have been constructed and the networking
  912. // layer was also initialized to spawn any goroutines required by the service.
  913. func (s *Service) Start(server *p2p.Server) error {
  914. var err error
  915. s.handler, err = NewHandler(s.backend)
  916. if err != nil {
  917. return err
  918. }
  919. if s.listener, err = net.Listen("tcp", s.endpoint); err != nil {
  920. return err
  921. }
  922. go rpc.NewHTTPServer(s.cors, s.vhosts, s.timeouts, s.handler).Serve(s.listener)
  923. log.Info("GraphQL endpoint opened", "url", fmt.Sprintf("http://%s", s.endpoint))
  924. return nil
  925. }
  926. // Stop terminates all goroutines belonging to the service, blocking until they
  927. // are all terminated.
  928. func (s *Service) Stop() error {
  929. if s.listener != nil {
  930. s.listener.Close()
  931. s.listener = nil
  932. log.Info("GraphQL endpoint closed", "url", fmt.Sprintf("http://%s", s.endpoint))
  933. }
  934. return nil
  935. }
  936. // NewService constructs a new service instance.
  937. func NewService(backend *eth.EthAPIBackend, endpoint string, cors, vhosts []string, timeouts rpc.HTTPTimeouts) (*Service, error) {
  938. return &Service{
  939. endpoint: endpoint,
  940. cors: cors,
  941. vhosts: vhosts,
  942. timeouts: timeouts,
  943. backend: backend,
  944. }, nil
  945. }
  946. // RegisterGraphQLService is a utility function to construct a new service and register it against a node.
  947. func RegisterGraphQLService(stack *node.Node, endpoint string, cors, vhosts []string, timeouts rpc.HTTPTimeouts) error {
  948. return stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  949. var ethereum *eth.Ethereum
  950. if err := ctx.Service(&ethereum); err != nil {
  951. return nil, err
  952. }
  953. return NewService(ethereum.APIBackend, endpoint, cors, vhosts, timeouts)
  954. })
  955. }