graphql.go 30 KB

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