github.com/theQRL/go-zond@v0.2.1/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 Zond node data. 18 package graphql 19 20 import ( 21 "context" 22 "errors" 23 "fmt" 24 "math/big" 25 "sort" 26 "strconv" 27 "strings" 28 "sync" 29 30 "github.com/theQRL/go-zond" 31 "github.com/theQRL/go-zond/common" 32 "github.com/theQRL/go-zond/common/hexutil" 33 "github.com/theQRL/go-zond/common/math" 34 "github.com/theQRL/go-zond/consensus/misc/eip1559" 35 "github.com/theQRL/go-zond/core/state" 36 "github.com/theQRL/go-zond/core/types" 37 "github.com/theQRL/go-zond/internal/zondapi" 38 "github.com/theQRL/go-zond/rlp" 39 "github.com/theQRL/go-zond/rpc" 40 "github.com/theQRL/go-zond/zond/filters" 41 ) 42 43 var ( 44 errBlockInvariant = errors.New("block objects must be instantiated with at least one of num or hash") 45 ) 46 47 type Long int64 48 49 // ImplementsGraphQLType returns true if Long implements the provided GraphQL type. 50 func (b Long) ImplementsGraphQLType(name string) bool { return name == "Long" } 51 52 // UnmarshalGraphQL unmarshals the provided GraphQL query data. 53 func (b *Long) UnmarshalGraphQL(input interface{}) error { 54 var err error 55 switch input := input.(type) { 56 case string: 57 // uncomment to support hex values 58 if strings.HasPrefix(input, "0x") { 59 // apply leniency and support hex representations of longs. 60 value, err := hexutil.DecodeUint64(input) 61 *b = Long(value) 62 return err 63 } else { 64 value, err := strconv.ParseInt(input, 10, 64) 65 *b = Long(value) 66 return err 67 } 68 case int32: 69 *b = Long(input) 70 case int64: 71 *b = Long(input) 72 case float64: 73 *b = Long(input) 74 default: 75 err = fmt.Errorf("unexpected type %T for Long", input) 76 } 77 return err 78 } 79 80 // Account represents a Zond account at a particular block. 81 type Account struct { 82 r *Resolver 83 address common.Address 84 blockNrOrHash rpc.BlockNumberOrHash 85 } 86 87 // getState fetches the StateDB object for an account. 88 func (a *Account) getState(ctx context.Context) (*state.StateDB, error) { 89 state, _, err := a.r.backend.StateAndHeaderByNumberOrHash(ctx, a.blockNrOrHash) 90 return state, err 91 } 92 93 func (a *Account) Address(ctx context.Context) (common.Address, error) { 94 return a.address, nil 95 } 96 97 func (a *Account) Balance(ctx context.Context) (hexutil.Big, error) { 98 state, err := a.getState(ctx) 99 if err != nil { 100 return hexutil.Big{}, err 101 } 102 balance := state.GetBalance(a.address) 103 if balance == nil { 104 return hexutil.Big{}, fmt.Errorf("failed to load balance %x", a.address) 105 } 106 return hexutil.Big(*balance), nil 107 } 108 109 func (a *Account) TransactionCount(ctx context.Context) (hexutil.Uint64, error) { 110 // Ask transaction pool for the nonce which includes pending transactions 111 if blockNr, ok := a.blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber { 112 nonce, err := a.r.backend.GetPoolNonce(ctx, a.address) 113 if err != nil { 114 return 0, err 115 } 116 return hexutil.Uint64(nonce), nil 117 } 118 state, err := a.getState(ctx) 119 if err != nil { 120 return 0, err 121 } 122 return hexutil.Uint64(state.GetNonce(a.address)), nil 123 } 124 125 func (a *Account) Code(ctx context.Context) (hexutil.Bytes, error) { 126 state, err := a.getState(ctx) 127 if err != nil { 128 return hexutil.Bytes{}, err 129 } 130 return state.GetCode(a.address), nil 131 } 132 133 func (a *Account) Storage(ctx context.Context, args struct{ Slot common.Hash }) (common.Hash, error) { 134 state, err := a.getState(ctx) 135 if err != nil { 136 return common.Hash{}, err 137 } 138 return state.GetState(a.address, args.Slot), nil 139 } 140 141 // Log represents an individual log message. All arguments are mandatory. 142 type Log struct { 143 r *Resolver 144 transaction *Transaction 145 log *types.Log 146 } 147 148 func (l *Log) Transaction(ctx context.Context) *Transaction { 149 return l.transaction 150 } 151 152 func (l *Log) Account(ctx context.Context, args BlockNumberArgs) *Account { 153 return &Account{ 154 r: l.r, 155 address: l.log.Address, 156 blockNrOrHash: args.NumberOrLatest(), 157 } 158 } 159 160 func (l *Log) Index(ctx context.Context) hexutil.Uint64 { 161 return hexutil.Uint64(l.log.Index) 162 } 163 164 func (l *Log) Topics(ctx context.Context) []common.Hash { 165 return l.log.Topics 166 } 167 168 func (l *Log) Data(ctx context.Context) hexutil.Bytes { 169 return l.log.Data 170 } 171 172 type AccessTuple struct { 173 address common.Address 174 storageKeys []common.Hash 175 } 176 177 func (at *AccessTuple) Address(ctx context.Context) common.Address { 178 return at.address 179 } 180 181 func (at *AccessTuple) StorageKeys(ctx context.Context) []common.Hash { 182 return at.storageKeys 183 } 184 185 // Withdrawal represents a withdrawal of value from the beacon chain 186 // by a validator. 187 type Withdrawal struct { 188 index uint64 189 validator uint64 190 address common.Address 191 amount uint64 192 } 193 194 func (w *Withdrawal) Index(ctx context.Context) hexutil.Uint64 { 195 return hexutil.Uint64(w.index) 196 } 197 198 func (w *Withdrawal) Validator(ctx context.Context) hexutil.Uint64 { 199 return hexutil.Uint64(w.validator) 200 } 201 202 func (w *Withdrawal) Address(ctx context.Context) common.Address { 203 return w.address 204 } 205 206 func (w *Withdrawal) Amount(ctx context.Context) hexutil.Uint64 { 207 return hexutil.Uint64(w.amount) 208 } 209 210 // Transaction represents a Zond transaction. 211 // backend and hash are mandatory; all others will be fetched when required. 212 type Transaction struct { 213 r *Resolver 214 hash common.Hash // Must be present after initialization 215 mu sync.Mutex 216 // mu protects following resources 217 tx *types.Transaction 218 block *Block 219 index uint64 220 } 221 222 // resolve returns the internal transaction object, fetching it if needed. 223 // It also returns the block the tx belongs to, unless it is a pending tx. 224 func (t *Transaction) resolve(ctx context.Context) (*types.Transaction, *Block) { 225 t.mu.Lock() 226 defer t.mu.Unlock() 227 if t.tx != nil { 228 return t.tx, t.block 229 } 230 // Try to return an already finalized transaction 231 tx, blockHash, _, index, err := t.r.backend.GetTransaction(ctx, t.hash) 232 if err == nil && tx != nil { 233 t.tx = tx 234 blockNrOrHash := rpc.BlockNumberOrHashWithHash(blockHash, false) 235 t.block = &Block{ 236 r: t.r, 237 numberOrHash: &blockNrOrHash, 238 hash: blockHash, 239 } 240 t.index = index 241 return t.tx, t.block 242 } 243 // No finalized transaction, try to retrieve it from the pool 244 t.tx = t.r.backend.GetPoolTransaction(t.hash) 245 return t.tx, nil 246 } 247 248 func (t *Transaction) Hash(ctx context.Context) common.Hash { 249 return t.hash 250 } 251 252 func (t *Transaction) InputData(ctx context.Context) hexutil.Bytes { 253 tx, _ := t.resolve(ctx) 254 if tx == nil { 255 return hexutil.Bytes{} 256 } 257 return tx.Data() 258 } 259 260 func (t *Transaction) Gas(ctx context.Context) hexutil.Uint64 { 261 tx, _ := t.resolve(ctx) 262 if tx == nil { 263 return 0 264 } 265 return hexutil.Uint64(tx.Gas()) 266 } 267 268 func (t *Transaction) GasPrice(ctx context.Context) hexutil.Big { 269 tx, block := t.resolve(ctx) 270 if tx == nil { 271 return hexutil.Big{} 272 } 273 switch tx.Type() { 274 default: 275 if block != nil { 276 if baseFee, _ := block.BaseFeePerGas(ctx); baseFee != nil { 277 // price = min(gasTipCap + baseFee, gasFeeCap) 278 return (hexutil.Big)(*math.BigMin(new(big.Int).Add(tx.GasTipCap(), baseFee.ToInt()), tx.GasFeeCap())) 279 } 280 } 281 return hexutil.Big(*tx.GasPrice()) 282 } 283 } 284 285 func (t *Transaction) EffectiveGasPrice(ctx context.Context) (*hexutil.Big, error) { 286 tx, block := t.resolve(ctx) 287 if tx == nil { 288 return nil, nil 289 } 290 // Pending tx 291 if block == nil { 292 return nil, nil 293 } 294 header, err := block.resolveHeader(ctx) 295 if err != nil || header == nil { 296 return nil, err 297 } 298 if header.BaseFee == nil { 299 return (*hexutil.Big)(tx.GasPrice()), nil 300 } 301 return (*hexutil.Big)(math.BigMin(new(big.Int).Add(tx.GasTipCap(), header.BaseFee), tx.GasFeeCap())), nil 302 } 303 304 func (t *Transaction) MaxFeePerGas(ctx context.Context) *hexutil.Big { 305 tx, _ := t.resolve(ctx) 306 if tx == nil { 307 return nil 308 } 309 switch tx.Type() { 310 case types.DynamicFeeTxType: 311 return (*hexutil.Big)(tx.GasFeeCap()) 312 default: 313 return nil 314 } 315 } 316 317 func (t *Transaction) MaxPriorityFeePerGas(ctx context.Context) *hexutil.Big { 318 tx, _ := t.resolve(ctx) 319 if tx == nil { 320 return nil 321 } 322 switch tx.Type() { 323 case types.DynamicFeeTxType: 324 return (*hexutil.Big)(tx.GasTipCap()) 325 default: 326 return nil 327 } 328 } 329 330 func (t *Transaction) EffectiveTip(ctx context.Context) (*hexutil.Big, error) { 331 tx, block := t.resolve(ctx) 332 if tx == nil { 333 return nil, nil 334 } 335 // Pending tx 336 if block == nil { 337 return nil, nil 338 } 339 header, err := block.resolveHeader(ctx) 340 if err != nil || header == nil { 341 return nil, err 342 } 343 if header.BaseFee == nil { 344 return (*hexutil.Big)(tx.GasPrice()), nil 345 } 346 347 tip, err := tx.EffectiveGasTip(header.BaseFee) 348 if err != nil { 349 return nil, err 350 } 351 return (*hexutil.Big)(tip), nil 352 } 353 354 func (t *Transaction) Value(ctx context.Context) (hexutil.Big, error) { 355 tx, _ := t.resolve(ctx) 356 if tx == nil { 357 return hexutil.Big{}, nil 358 } 359 if tx.Value() == nil { 360 return hexutil.Big{}, fmt.Errorf("invalid transaction value %x", t.hash) 361 } 362 return hexutil.Big(*tx.Value()), nil 363 } 364 365 func (t *Transaction) Nonce(ctx context.Context) hexutil.Uint64 { 366 tx, _ := t.resolve(ctx) 367 if tx == nil { 368 return 0 369 } 370 return hexutil.Uint64(tx.Nonce()) 371 } 372 373 func (t *Transaction) To(ctx context.Context, args BlockNumberArgs) *Account { 374 tx, _ := t.resolve(ctx) 375 if tx == nil { 376 return nil 377 } 378 to := tx.To() 379 if to == nil { 380 return nil 381 } 382 return &Account{ 383 r: t.r, 384 address: *to, 385 blockNrOrHash: args.NumberOrLatest(), 386 } 387 } 388 389 func (t *Transaction) From(ctx context.Context, args BlockNumberArgs) *Account { 390 tx, _ := t.resolve(ctx) 391 if tx == nil { 392 return nil 393 } 394 signer := types.LatestSigner(t.r.backend.ChainConfig()) 395 from, _ := types.Sender(signer, tx) 396 return &Account{ 397 r: t.r, 398 address: from, 399 blockNrOrHash: args.NumberOrLatest(), 400 } 401 } 402 403 func (t *Transaction) Block(ctx context.Context) *Block { 404 _, block := t.resolve(ctx) 405 return block 406 } 407 408 func (t *Transaction) Index(ctx context.Context) *hexutil.Uint64 { 409 _, block := t.resolve(ctx) 410 // Pending tx 411 if block == nil { 412 return nil 413 } 414 index := hexutil.Uint64(t.index) 415 return &index 416 } 417 418 // getReceipt returns the receipt associated with this transaction, if any. 419 func (t *Transaction) getReceipt(ctx context.Context) (*types.Receipt, error) { 420 _, block := t.resolve(ctx) 421 // Pending tx 422 if block == nil { 423 return nil, nil 424 } 425 receipts, err := block.resolveReceipts(ctx) 426 if err != nil { 427 return nil, err 428 } 429 return receipts[t.index], nil 430 } 431 432 func (t *Transaction) Status(ctx context.Context) (*hexutil.Uint64, error) { 433 receipt, err := t.getReceipt(ctx) 434 if err != nil || receipt == nil { 435 return nil, err 436 } 437 if len(receipt.PostState) != 0 { 438 return nil, nil 439 } 440 ret := hexutil.Uint64(receipt.Status) 441 return &ret, nil 442 } 443 444 func (t *Transaction) GasUsed(ctx context.Context) (*hexutil.Uint64, error) { 445 receipt, err := t.getReceipt(ctx) 446 if err != nil || receipt == nil { 447 return nil, err 448 } 449 ret := hexutil.Uint64(receipt.GasUsed) 450 return &ret, nil 451 } 452 453 func (t *Transaction) CumulativeGasUsed(ctx context.Context) (*hexutil.Uint64, error) { 454 receipt, err := t.getReceipt(ctx) 455 if err != nil || receipt == nil { 456 return nil, err 457 } 458 ret := hexutil.Uint64(receipt.CumulativeGasUsed) 459 return &ret, nil 460 } 461 462 func (t *Transaction) CreatedContract(ctx context.Context, args BlockNumberArgs) (*Account, error) { 463 receipt, err := t.getReceipt(ctx) 464 if err != nil || receipt == nil || receipt.ContractAddress == (common.Address{}) { 465 return nil, err 466 } 467 return &Account{ 468 r: t.r, 469 address: receipt.ContractAddress, 470 blockNrOrHash: args.NumberOrLatest(), 471 }, nil 472 } 473 474 func (t *Transaction) Logs(ctx context.Context) (*[]*Log, error) { 475 _, block := t.resolve(ctx) 476 // Pending tx 477 if block == nil { 478 return nil, nil 479 } 480 h, err := block.Hash(ctx) 481 if err != nil { 482 return nil, err 483 } 484 return t.getLogs(ctx, h) 485 } 486 487 // getLogs returns log objects for the given tx. 488 // Assumes block hash is resolved. 489 func (t *Transaction) getLogs(ctx context.Context, hash common.Hash) (*[]*Log, error) { 490 var ( 491 filter = t.r.filterSystem.NewBlockFilter(hash, nil, nil) 492 logs, err = filter.Logs(ctx) 493 ) 494 if err != nil { 495 return nil, err 496 } 497 var ret []*Log 498 // Select tx logs from all block logs 499 ix := sort.Search(len(logs), func(i int) bool { return uint64(logs[i].TxIndex) >= t.index }) 500 for ix < len(logs) && uint64(logs[ix].TxIndex) == t.index { 501 ret = append(ret, &Log{ 502 r: t.r, 503 transaction: t, 504 log: logs[ix], 505 }) 506 ix++ 507 } 508 return &ret, nil 509 } 510 511 func (t *Transaction) Type(ctx context.Context) *hexutil.Uint64 { 512 tx, _ := t.resolve(ctx) 513 txType := hexutil.Uint64(tx.Type()) 514 return &txType 515 } 516 517 func (t *Transaction) AccessList(ctx context.Context) *[]*AccessTuple { 518 tx, _ := t.resolve(ctx) 519 if tx == nil { 520 return nil 521 } 522 accessList := tx.AccessList() 523 ret := make([]*AccessTuple, 0, len(accessList)) 524 for _, al := range accessList { 525 ret = append(ret, &AccessTuple{ 526 address: al.Address, 527 storageKeys: al.StorageKeys, 528 }) 529 } 530 return &ret 531 } 532 func (t *Transaction) PublicKey(ctx context.Context) (hexutil.Bytes, error) { 533 tx, _ := t.resolve(ctx) 534 if tx == nil { 535 return hexutil.Bytes{}, nil 536 } 537 return tx.RawPublicKeyValue(), nil 538 } 539 540 func (t *Transaction) Signature(ctx context.Context) (hexutil.Bytes, error) { 541 tx, err := t.resolve(ctx) 542 if err != nil || tx == nil { 543 return hexutil.Bytes{}, nil 544 } 545 return tx.RawSignatureValue(), nil 546 } 547 func (t *Transaction) Raw(ctx context.Context) (hexutil.Bytes, error) { 548 tx, _ := t.resolve(ctx) 549 if tx == nil { 550 return hexutil.Bytes{}, nil 551 } 552 return tx.MarshalBinary() 553 } 554 555 func (t *Transaction) RawReceipt(ctx context.Context) (hexutil.Bytes, error) { 556 receipt, err := t.getReceipt(ctx) 557 if err != nil || receipt == nil { 558 return hexutil.Bytes{}, err 559 } 560 return receipt.MarshalBinary() 561 } 562 563 type BlockType int 564 565 // Block represents a Zond block. 566 // backend, and numberOrHash are mandatory. All other fields are lazily fetched 567 // when required. 568 type Block struct { 569 r *Resolver 570 numberOrHash *rpc.BlockNumberOrHash // Field resolvers assume numberOrHash is always present 571 mu sync.Mutex 572 // mu protects following resources 573 hash common.Hash // Must be resolved during initialization 574 header *types.Header 575 block *types.Block 576 receipts []*types.Receipt 577 } 578 579 // resolve returns the internal Block object representing this block, fetching 580 // it if necessary. 581 func (b *Block) resolve(ctx context.Context) (*types.Block, error) { 582 b.mu.Lock() 583 defer b.mu.Unlock() 584 if b.block != nil { 585 return b.block, nil 586 } 587 if b.numberOrHash == nil { 588 latest := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) 589 b.numberOrHash = &latest 590 } 591 var err error 592 b.block, err = b.r.backend.BlockByNumberOrHash(ctx, *b.numberOrHash) 593 if b.block != nil { 594 b.hash = b.block.Hash() 595 if b.header == nil { 596 b.header = b.block.Header() 597 } 598 } 599 return b.block, err 600 } 601 602 // resolveHeader returns the internal Header object for this block, fetching it 603 // if necessary. Call this function instead of `resolve` unless you need the 604 // additional data (transactions). 605 func (b *Block) resolveHeader(ctx context.Context) (*types.Header, error) { 606 b.mu.Lock() 607 defer b.mu.Unlock() 608 if b.header != nil { 609 return b.header, nil 610 } 611 if b.numberOrHash == nil && b.hash == (common.Hash{}) { 612 return nil, errBlockInvariant 613 } 614 var err error 615 b.header, err = b.r.backend.HeaderByNumberOrHash(ctx, *b.numberOrHash) 616 if err != nil { 617 return nil, err 618 } 619 if b.hash == (common.Hash{}) { 620 b.hash = b.header.Hash() 621 } 622 return b.header, nil 623 } 624 625 // resolveReceipts returns the list of receipts for this block, fetching them 626 // if necessary. 627 func (b *Block) resolveReceipts(ctx context.Context) ([]*types.Receipt, error) { 628 b.mu.Lock() 629 defer b.mu.Unlock() 630 if b.receipts != nil { 631 return b.receipts, nil 632 } 633 receipts, err := b.r.backend.GetReceipts(ctx, b.hash) 634 if err != nil { 635 return nil, err 636 } 637 b.receipts = receipts 638 return receipts, nil 639 } 640 641 func (b *Block) Number(ctx context.Context) (hexutil.Uint64, error) { 642 header, err := b.resolveHeader(ctx) 643 if err != nil { 644 return 0, err 645 } 646 647 return hexutil.Uint64(header.Number.Uint64()), nil 648 } 649 650 func (b *Block) Hash(ctx context.Context) (common.Hash, error) { 651 b.mu.Lock() 652 defer b.mu.Unlock() 653 return b.hash, nil 654 } 655 656 func (b *Block) GasLimit(ctx context.Context) (hexutil.Uint64, error) { 657 header, err := b.resolveHeader(ctx) 658 if err != nil { 659 return 0, err 660 } 661 return hexutil.Uint64(header.GasLimit), nil 662 } 663 664 func (b *Block) GasUsed(ctx context.Context) (hexutil.Uint64, error) { 665 header, err := b.resolveHeader(ctx) 666 if err != nil { 667 return 0, err 668 } 669 return hexutil.Uint64(header.GasUsed), nil 670 } 671 672 func (b *Block) BaseFeePerGas(ctx context.Context) (*hexutil.Big, error) { 673 header, err := b.resolveHeader(ctx) 674 if err != nil { 675 return nil, err 676 } 677 if header.BaseFee == nil { 678 return nil, nil 679 } 680 return (*hexutil.Big)(header.BaseFee), nil 681 } 682 683 func (b *Block) NextBaseFeePerGas(ctx context.Context) (*hexutil.Big, error) { 684 header, err := b.resolveHeader(ctx) 685 if err != nil { 686 return nil, err 687 } 688 chaincfg := b.r.backend.ChainConfig() 689 nextBaseFee := eip1559.CalcBaseFee(chaincfg, header) 690 return (*hexutil.Big)(nextBaseFee), nil 691 } 692 693 func (b *Block) Parent(ctx context.Context) (*Block, error) { 694 if _, err := b.resolveHeader(ctx); err != nil { 695 return nil, err 696 } 697 if b.header == nil || b.header.Number.Uint64() < 1 { 698 return nil, nil 699 } 700 var ( 701 num = rpc.BlockNumber(b.header.Number.Uint64() - 1) 702 hash = b.header.ParentHash 703 numOrHash = rpc.BlockNumberOrHash{ 704 BlockNumber: &num, 705 BlockHash: &hash, 706 } 707 ) 708 return &Block{ 709 r: b.r, 710 numberOrHash: &numOrHash, 711 hash: hash, 712 }, nil 713 } 714 715 func (b *Block) Timestamp(ctx context.Context) (hexutil.Uint64, error) { 716 header, err := b.resolveHeader(ctx) 717 if err != nil { 718 return 0, err 719 } 720 return hexutil.Uint64(header.Time), nil 721 } 722 723 func (b *Block) Random(ctx context.Context) (common.Hash, error) { 724 header, err := b.resolveHeader(ctx) 725 if err != nil { 726 return common.Hash{}, err 727 } 728 return header.Random, nil 729 } 730 731 func (b *Block) TransactionsRoot(ctx context.Context) (common.Hash, error) { 732 header, err := b.resolveHeader(ctx) 733 if err != nil { 734 return common.Hash{}, err 735 } 736 return header.TxHash, nil 737 } 738 739 func (b *Block) StateRoot(ctx context.Context) (common.Hash, error) { 740 header, err := b.resolveHeader(ctx) 741 if err != nil { 742 return common.Hash{}, err 743 } 744 return header.Root, nil 745 } 746 747 func (b *Block) ReceiptsRoot(ctx context.Context) (common.Hash, error) { 748 header, err := b.resolveHeader(ctx) 749 if err != nil { 750 return common.Hash{}, err 751 } 752 return header.ReceiptHash, nil 753 } 754 755 func (b *Block) ExtraData(ctx context.Context) (hexutil.Bytes, error) { 756 header, err := b.resolveHeader(ctx) 757 if err != nil { 758 return hexutil.Bytes{}, err 759 } 760 return header.Extra, nil 761 } 762 763 func (b *Block) LogsBloom(ctx context.Context) (hexutil.Bytes, error) { 764 header, err := b.resolveHeader(ctx) 765 if err != nil { 766 return hexutil.Bytes{}, err 767 } 768 return header.Bloom.Bytes(), nil 769 } 770 771 func (b *Block) RawHeader(ctx context.Context) (hexutil.Bytes, error) { 772 header, err := b.resolveHeader(ctx) 773 if err != nil { 774 return hexutil.Bytes{}, err 775 } 776 return rlp.EncodeToBytes(header) 777 } 778 779 func (b *Block) Raw(ctx context.Context) (hexutil.Bytes, error) { 780 block, err := b.resolve(ctx) 781 if err != nil { 782 return hexutil.Bytes{}, err 783 } 784 return rlp.EncodeToBytes(block) 785 } 786 787 // BlockNumberArgs encapsulates arguments to accessors that specify a block number. 788 type BlockNumberArgs struct { 789 // TODO: Ideally we could use input unions to allow the query to specify the 790 // block parameter by hash, block number, or tag but input unions aren't part of the 791 // standard GraphQL schema SDL yet, see: https://github.com/graphql/graphql-spec/issues/488 792 Block *Long 793 } 794 795 // NumberOr returns the provided block number argument, or the "current" block number or hash if none 796 // was provided. 797 func (a BlockNumberArgs) NumberOr(current rpc.BlockNumberOrHash) rpc.BlockNumberOrHash { 798 if a.Block != nil { 799 blockNr := rpc.BlockNumber(*a.Block) 800 return rpc.BlockNumberOrHashWithNumber(blockNr) 801 } 802 return current 803 } 804 805 // NumberOrLatest returns the provided block number argument, or the "latest" block number if none 806 // was provided. 807 func (a BlockNumberArgs) NumberOrLatest() rpc.BlockNumberOrHash { 808 return a.NumberOr(rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)) 809 } 810 811 func (b *Block) Miner(ctx context.Context, args BlockNumberArgs) (*Account, error) { 812 header, err := b.resolveHeader(ctx) 813 if err != nil { 814 return nil, err 815 } 816 return &Account{ 817 r: b.r, 818 address: header.Coinbase, 819 blockNrOrHash: args.NumberOrLatest(), 820 }, nil 821 } 822 823 func (b *Block) TransactionCount(ctx context.Context) (*hexutil.Uint64, error) { 824 block, err := b.resolve(ctx) 825 if err != nil || block == nil { 826 return nil, err 827 } 828 count := hexutil.Uint64(len(block.Transactions())) 829 return &count, err 830 } 831 832 func (b *Block) Transactions(ctx context.Context) (*[]*Transaction, error) { 833 block, err := b.resolve(ctx) 834 if err != nil || block == nil { 835 return nil, err 836 } 837 ret := make([]*Transaction, 0, len(block.Transactions())) 838 for i, tx := range block.Transactions() { 839 ret = append(ret, &Transaction{ 840 r: b.r, 841 hash: tx.Hash(), 842 tx: tx, 843 block: b, 844 index: uint64(i), 845 }) 846 } 847 return &ret, nil 848 } 849 850 func (b *Block) TransactionAt(ctx context.Context, args struct{ Index Long }) (*Transaction, error) { 851 block, err := b.resolve(ctx) 852 if err != nil || block == nil { 853 return nil, err 854 } 855 txs := block.Transactions() 856 if args.Index < 0 || int(args.Index) >= len(txs) { 857 return nil, nil 858 } 859 tx := txs[args.Index] 860 return &Transaction{ 861 r: b.r, 862 hash: tx.Hash(), 863 tx: tx, 864 block: b, 865 index: uint64(args.Index), 866 }, nil 867 } 868 869 func (b *Block) WithdrawalsRoot(ctx context.Context) (*common.Hash, error) { 870 header, err := b.resolveHeader(ctx) 871 if err != nil { 872 return nil, err 873 } 874 // Pre-shanghai blocks 875 if header.WithdrawalsHash == nil { 876 return nil, nil 877 } 878 return header.WithdrawalsHash, nil 879 } 880 881 func (b *Block) Withdrawals(ctx context.Context) (*[]*Withdrawal, error) { 882 block, err := b.resolve(ctx) 883 if err != nil || block == nil { 884 return nil, err 885 } 886 // Pre-shanghai blocks 887 if block.Header().WithdrawalsHash == nil { 888 return nil, nil 889 } 890 ret := make([]*Withdrawal, 0, len(block.Withdrawals())) 891 for _, w := range block.Withdrawals() { 892 ret = append(ret, &Withdrawal{ 893 index: w.Index, 894 validator: w.Validator, 895 address: w.Address, 896 amount: w.Amount, 897 }) 898 } 899 return &ret, nil 900 } 901 902 // BlockFilterCriteria encapsulates criteria passed to a `logs` accessor inside 903 // a block. 904 type BlockFilterCriteria struct { 905 Addresses *[]common.Address // restricts matches to events created by specific contracts 906 907 // The Topic list restricts matches to particular event topics. Each event has a list 908 // of topics. Topics matches a prefix of that list. An empty element slice matches any 909 // topic. Non-empty elements represent an alternative that matches any of the 910 // contained topics. 911 // 912 // Examples: 913 // {} or nil matches any topic list 914 // {{A}} matches topic A in first position 915 // {{}, {B}} matches any topic in first position, B in second position 916 // {{A}, {B}} matches topic A in first position, B in second position 917 // {{A, B}}, {C, D}} matches topic (A OR B) in first position, (C OR D) in second position 918 Topics *[][]common.Hash 919 } 920 921 // runFilter accepts a filter and executes it, returning all its results as 922 // `Log` objects. 923 func runFilter(ctx context.Context, r *Resolver, filter *filters.Filter) ([]*Log, error) { 924 logs, err := filter.Logs(ctx) 925 if err != nil || logs == nil { 926 return nil, err 927 } 928 ret := make([]*Log, 0, len(logs)) 929 for _, log := range logs { 930 ret = append(ret, &Log{ 931 r: r, 932 transaction: &Transaction{r: r, hash: log.TxHash}, 933 log: log, 934 }) 935 } 936 return ret, nil 937 } 938 939 func (b *Block) Logs(ctx context.Context, args struct{ Filter BlockFilterCriteria }) ([]*Log, error) { 940 var addresses []common.Address 941 if args.Filter.Addresses != nil { 942 addresses = *args.Filter.Addresses 943 } 944 var topics [][]common.Hash 945 if args.Filter.Topics != nil { 946 topics = *args.Filter.Topics 947 } 948 // Construct the range filter 949 hash, err := b.Hash(ctx) 950 if err != nil { 951 return nil, err 952 } 953 filter := b.r.filterSystem.NewBlockFilter(hash, addresses, topics) 954 955 // Run the filter and return all the logs 956 return runFilter(ctx, b.r, filter) 957 } 958 959 func (b *Block) Account(ctx context.Context, args struct { 960 Address common.Address 961 }) (*Account, error) { 962 return &Account{ 963 r: b.r, 964 address: args.Address, 965 blockNrOrHash: *b.numberOrHash, 966 }, nil 967 } 968 969 // CallData encapsulates arguments to `call` or `estimateGas`. 970 // All arguments are optional. 971 type CallData struct { 972 From *common.Address // The Zond address the call is from. 973 To *common.Address // The Zond address the call is to. 974 Gas *Long // The amount of gas provided for the call. 975 MaxFeePerGas *hexutil.Big // The max price of each unit of gas, in wei. 976 MaxPriorityFeePerGas *hexutil.Big // The max tip of each unit of gas, in wei. 977 Value *hexutil.Big // The value sent along with the call. 978 Data *hexutil.Bytes // Any data sent with the call. 979 } 980 981 // CallResult encapsulates the result of an invocation of the `call` accessor. 982 type CallResult struct { 983 data hexutil.Bytes // The return data from the call 984 gasUsed hexutil.Uint64 // The amount of gas used 985 status hexutil.Uint64 // The return status of the call - 0 for failure or 1 for success. 986 } 987 988 func (c *CallResult) Data() hexutil.Bytes { 989 return c.data 990 } 991 992 func (c *CallResult) GasUsed() hexutil.Uint64 { 993 return c.gasUsed 994 } 995 996 func (c *CallResult) Status() hexutil.Uint64 { 997 return c.status 998 } 999 1000 func (b *Block) Call(ctx context.Context, args struct { 1001 Data zondapi.TransactionArgs 1002 }) (*CallResult, error) { 1003 result, err := zondapi.DoCall(ctx, b.r.backend, args.Data, *b.numberOrHash, nil, nil, b.r.backend.RPCZVMTimeout(), b.r.backend.RPCGasCap()) 1004 if err != nil { 1005 return nil, err 1006 } 1007 status := hexutil.Uint64(1) 1008 if result.Failed() { 1009 status = 0 1010 } 1011 1012 return &CallResult{ 1013 data: result.ReturnData, 1014 gasUsed: hexutil.Uint64(result.UsedGas), 1015 status: status, 1016 }, nil 1017 } 1018 1019 func (b *Block) EstimateGas(ctx context.Context, args struct { 1020 Data zondapi.TransactionArgs 1021 }) (hexutil.Uint64, error) { 1022 return zondapi.DoEstimateGas(ctx, b.r.backend, args.Data, *b.numberOrHash, nil, b.r.backend.RPCGasCap()) 1023 } 1024 1025 type Pending struct { 1026 r *Resolver 1027 } 1028 1029 func (p *Pending) TransactionCount(ctx context.Context) (hexutil.Uint64, error) { 1030 txs, err := p.r.backend.GetPoolTransactions() 1031 return hexutil.Uint64(len(txs)), err 1032 } 1033 1034 func (p *Pending) Transactions(ctx context.Context) (*[]*Transaction, error) { 1035 txs, err := p.r.backend.GetPoolTransactions() 1036 if err != nil { 1037 return nil, err 1038 } 1039 ret := make([]*Transaction, 0, len(txs)) 1040 for i, tx := range txs { 1041 ret = append(ret, &Transaction{ 1042 r: p.r, 1043 hash: tx.Hash(), 1044 tx: tx, 1045 index: uint64(i), 1046 }) 1047 } 1048 return &ret, nil 1049 } 1050 1051 func (p *Pending) Account(ctx context.Context, args struct { 1052 Address common.Address 1053 }) *Account { 1054 pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber) 1055 return &Account{ 1056 r: p.r, 1057 address: args.Address, 1058 blockNrOrHash: pendingBlockNr, 1059 } 1060 } 1061 1062 func (p *Pending) Call(ctx context.Context, args struct { 1063 Data zondapi.TransactionArgs 1064 }) (*CallResult, error) { 1065 pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber) 1066 result, err := zondapi.DoCall(ctx, p.r.backend, args.Data, pendingBlockNr, nil, nil, p.r.backend.RPCZVMTimeout(), p.r.backend.RPCGasCap()) 1067 if err != nil { 1068 return nil, err 1069 } 1070 status := hexutil.Uint64(1) 1071 if result.Failed() { 1072 status = 0 1073 } 1074 1075 return &CallResult{ 1076 data: result.ReturnData, 1077 gasUsed: hexutil.Uint64(result.UsedGas), 1078 status: status, 1079 }, nil 1080 } 1081 1082 func (p *Pending) EstimateGas(ctx context.Context, args struct { 1083 Data zondapi.TransactionArgs 1084 }) (hexutil.Uint64, error) { 1085 latestBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) 1086 return zondapi.DoEstimateGas(ctx, p.r.backend, args.Data, latestBlockNr, nil, p.r.backend.RPCGasCap()) 1087 } 1088 1089 // Resolver is the top-level object in the GraphQL hierarchy. 1090 type Resolver struct { 1091 backend zondapi.Backend 1092 filterSystem *filters.FilterSystem 1093 } 1094 1095 func (r *Resolver) Block(ctx context.Context, args struct { 1096 Number *Long 1097 Hash *common.Hash 1098 }) (*Block, error) { 1099 if args.Number != nil && args.Hash != nil { 1100 return nil, errors.New("only one of number or hash must be specified") 1101 } 1102 var numberOrHash rpc.BlockNumberOrHash 1103 if args.Number != nil { 1104 if *args.Number < 0 { 1105 return nil, nil 1106 } 1107 number := rpc.BlockNumber(*args.Number) 1108 numberOrHash = rpc.BlockNumberOrHashWithNumber(number) 1109 } else if args.Hash != nil { 1110 numberOrHash = rpc.BlockNumberOrHashWithHash(*args.Hash, false) 1111 } else { 1112 numberOrHash = rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) 1113 } 1114 block := &Block{ 1115 r: r, 1116 numberOrHash: &numberOrHash, 1117 } 1118 // Resolve the header, return nil if it doesn't exist. 1119 // Note we don't resolve block directly here since it will require an 1120 // additional network request for light client. 1121 h, err := block.resolveHeader(ctx) 1122 if err != nil { 1123 return nil, err 1124 } else if h == nil { 1125 return nil, nil 1126 } 1127 return block, nil 1128 } 1129 1130 func (r *Resolver) Blocks(ctx context.Context, args struct { 1131 From *Long 1132 To *Long 1133 }) ([]*Block, error) { 1134 from := rpc.BlockNumber(*args.From) 1135 1136 var to rpc.BlockNumber 1137 if args.To != nil { 1138 to = rpc.BlockNumber(*args.To) 1139 } else { 1140 to = rpc.BlockNumber(r.backend.CurrentBlock().Number.Int64()) 1141 } 1142 if to < from { 1143 return []*Block{}, nil 1144 } 1145 var ret []*Block 1146 for i := from; i <= to; i++ { 1147 numberOrHash := rpc.BlockNumberOrHashWithNumber(i) 1148 block := &Block{ 1149 r: r, 1150 numberOrHash: &numberOrHash, 1151 } 1152 // Resolve the header to check for existence. 1153 // Note we don't resolve block directly here since it will require an 1154 // additional network request for light client. 1155 h, err := block.resolveHeader(ctx) 1156 if err != nil { 1157 return nil, err 1158 } else if h == nil { 1159 // Blocks after must be non-existent too, break. 1160 break 1161 } 1162 ret = append(ret, block) 1163 if err := ctx.Err(); err != nil { 1164 return nil, err 1165 } 1166 } 1167 return ret, nil 1168 } 1169 1170 func (r *Resolver) Pending(ctx context.Context) *Pending { 1171 return &Pending{r} 1172 } 1173 1174 func (r *Resolver) Transaction(ctx context.Context, args struct{ Hash common.Hash }) *Transaction { 1175 tx := &Transaction{ 1176 r: r, 1177 hash: args.Hash, 1178 } 1179 // Resolve the transaction; if it doesn't exist, return nil. 1180 t, _ := tx.resolve(ctx) 1181 if t == nil { 1182 return nil 1183 } 1184 return tx 1185 } 1186 1187 func (r *Resolver) SendRawTransaction(ctx context.Context, args struct{ Data hexutil.Bytes }) (common.Hash, error) { 1188 tx := new(types.Transaction) 1189 if err := tx.UnmarshalBinary(args.Data); err != nil { 1190 return common.Hash{}, err 1191 } 1192 hash, err := zondapi.SubmitTransaction(ctx, r.backend, tx) 1193 return hash, err 1194 } 1195 1196 // FilterCriteria encapsulates the arguments to `logs` on the root resolver object. 1197 type FilterCriteria struct { 1198 FromBlock *Long // beginning of the queried range, nil means genesis block 1199 ToBlock *Long // end of the range, nil means latest block 1200 Addresses *[]common.Address // restricts matches to events created by specific contracts 1201 1202 // The Topic list restricts matches to particular event topics. Each event has a list 1203 // of topics. Topics matches a prefix of that list. An empty element slice matches any 1204 // topic. Non-empty elements represent an alternative that matches any of the 1205 // contained topics. 1206 // 1207 // Examples: 1208 // {} or nil matches any topic list 1209 // {{A}} matches topic A in first position 1210 // {{}, {B}} matches any topic in first position, B in second position 1211 // {{A}, {B}} matches topic A in first position, B in second position 1212 // {{A, B}}, {C, D}} matches topic (A OR B) in first position, (C OR D) in second position 1213 Topics *[][]common.Hash 1214 } 1215 1216 func (r *Resolver) Logs(ctx context.Context, args struct{ Filter FilterCriteria }) ([]*Log, error) { 1217 // Convert the RPC block numbers into internal representations 1218 begin := rpc.LatestBlockNumber.Int64() 1219 if args.Filter.FromBlock != nil { 1220 begin = int64(*args.Filter.FromBlock) 1221 } 1222 end := rpc.LatestBlockNumber.Int64() 1223 if args.Filter.ToBlock != nil { 1224 end = int64(*args.Filter.ToBlock) 1225 } 1226 var addresses []common.Address 1227 if args.Filter.Addresses != nil { 1228 addresses = *args.Filter.Addresses 1229 } 1230 var topics [][]common.Hash 1231 if args.Filter.Topics != nil { 1232 topics = *args.Filter.Topics 1233 } 1234 // Construct the range filter 1235 filter := r.filterSystem.NewRangeFilter(begin, end, addresses, topics) 1236 return runFilter(ctx, r, filter) 1237 } 1238 1239 func (r *Resolver) GasPrice(ctx context.Context) (hexutil.Big, error) { 1240 tipcap, err := r.backend.SuggestGasTipCap(ctx) 1241 if err != nil { 1242 return hexutil.Big{}, err 1243 } 1244 if head := r.backend.CurrentHeader(); head.BaseFee != nil { 1245 tipcap.Add(tipcap, head.BaseFee) 1246 } 1247 return (hexutil.Big)(*tipcap), nil 1248 } 1249 1250 func (r *Resolver) MaxPriorityFeePerGas(ctx context.Context) (hexutil.Big, error) { 1251 tipcap, err := r.backend.SuggestGasTipCap(ctx) 1252 if err != nil { 1253 return hexutil.Big{}, err 1254 } 1255 return (hexutil.Big)(*tipcap), nil 1256 } 1257 1258 func (r *Resolver) ChainID(ctx context.Context) (hexutil.Big, error) { 1259 return hexutil.Big(*r.backend.ChainConfig().ChainID), nil 1260 } 1261 1262 // SyncState represents the synchronisation status returned from the `syncing` accessor. 1263 type SyncState struct { 1264 progress zond.SyncProgress 1265 } 1266 1267 func (s *SyncState) StartingBlock() hexutil.Uint64 { 1268 return hexutil.Uint64(s.progress.StartingBlock) 1269 } 1270 func (s *SyncState) CurrentBlock() hexutil.Uint64 { 1271 return hexutil.Uint64(s.progress.CurrentBlock) 1272 } 1273 func (s *SyncState) HighestBlock() hexutil.Uint64 { 1274 return hexutil.Uint64(s.progress.HighestBlock) 1275 } 1276 func (s *SyncState) SyncedAccounts() hexutil.Uint64 { 1277 return hexutil.Uint64(s.progress.SyncedAccounts) 1278 } 1279 func (s *SyncState) SyncedAccountBytes() hexutil.Uint64 { 1280 return hexutil.Uint64(s.progress.SyncedAccountBytes) 1281 } 1282 func (s *SyncState) SyncedBytecodes() hexutil.Uint64 { 1283 return hexutil.Uint64(s.progress.SyncedBytecodes) 1284 } 1285 func (s *SyncState) SyncedBytecodeBytes() hexutil.Uint64 { 1286 return hexutil.Uint64(s.progress.SyncedBytecodeBytes) 1287 } 1288 func (s *SyncState) SyncedStorage() hexutil.Uint64 { 1289 return hexutil.Uint64(s.progress.SyncedStorage) 1290 } 1291 func (s *SyncState) SyncedStorageBytes() hexutil.Uint64 { 1292 return hexutil.Uint64(s.progress.SyncedStorageBytes) 1293 } 1294 func (s *SyncState) HealedTrienodes() hexutil.Uint64 { 1295 return hexutil.Uint64(s.progress.HealedTrienodes) 1296 } 1297 func (s *SyncState) HealedTrienodeBytes() hexutil.Uint64 { 1298 return hexutil.Uint64(s.progress.HealedTrienodeBytes) 1299 } 1300 func (s *SyncState) HealedBytecodes() hexutil.Uint64 { 1301 return hexutil.Uint64(s.progress.HealedBytecodes) 1302 } 1303 func (s *SyncState) HealedBytecodeBytes() hexutil.Uint64 { 1304 return hexutil.Uint64(s.progress.HealedBytecodeBytes) 1305 } 1306 func (s *SyncState) HealingTrienodes() hexutil.Uint64 { 1307 return hexutil.Uint64(s.progress.HealingTrienodes) 1308 } 1309 func (s *SyncState) HealingBytecode() hexutil.Uint64 { 1310 return hexutil.Uint64(s.progress.HealingBytecode) 1311 } 1312 1313 // Syncing returns false in case the node is currently not syncing with the network. It can be up-to-date or has not 1314 // yet received the latest block headers from its pears. In case it is synchronizing: 1315 // - startingBlock: block number this node started to synchronize from 1316 // - currentBlock: block number this node is currently importing 1317 // - highestBlock: block number of the highest block header this node has received from peers 1318 // - syncedAccounts: number of accounts downloaded 1319 // - syncedAccountBytes: number of account trie bytes persisted to disk 1320 // - syncedBytecodes: number of bytecodes downloaded 1321 // - syncedBytecodeBytes: number of bytecode bytes downloaded 1322 // - syncedStorage: number of storage slots downloaded 1323 // - syncedStorageBytes: number of storage trie bytes persisted to disk 1324 // - healedTrienodes: number of state trie nodes downloaded 1325 // - healedTrienodeBytes: number of state trie bytes persisted to disk 1326 // - healedBytecodes: number of bytecodes downloaded 1327 // - healedBytecodeBytes: number of bytecodes persisted to disk 1328 // - healingTrienodes: number of state trie nodes pending 1329 // - healingBytecode: number of bytecodes pending 1330 func (r *Resolver) Syncing() (*SyncState, error) { 1331 progress := r.backend.SyncProgress() 1332 1333 // Return not syncing if the synchronisation already completed 1334 if progress.CurrentBlock >= progress.HighestBlock { 1335 return nil, nil 1336 } 1337 // Otherwise gather the block sync stats 1338 return &SyncState{progress}, nil 1339 }