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