graphql.go 32 KB

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