graphql.go 29 KB

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