graphql.go 30 KB

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