graphql.go 31 KB

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