graphql.go 29 KB

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