Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add missing block fields to the type used for eth_getBlockByNumber and eth_getBlockByHash #185

Merged
merged 4 commits into from
Apr 4, 2024

Conversation

m-Peter
Copy link
Collaborator

@m-Peter m-Peter commented Apr 4, 2024

Work towards: #145

Description

Sample output:

{
  "jsonrpc": "2.0",
  "id": 7,
  "result": {
    "number": "0x3",
    "hash": "0x631dff9eec346af7f1ec8843e8bc02be4297d0e40d6ce20839ff07cbfd560e7d",
    "parentHash": "0x4d17f3966a809b9755375ca6229ab5a4caa55f61d54446cad8d0bc6568900b2a",
    "nonce": "0x0100000000000000",
    "sha3Uncles": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "logsBloom": "0x",
    "transactionsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "stateRoot": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "receiptsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "miner": "0x0000000000000000000000000000000000000000",
    "difficulty": "0x0",
    "totalDifficulty": "0x0",
    "extraData": "0x",
    "size": "0x0",
    "gasLimit": "0xe4e1c0",
    "gasUsed": "0x195b0",
    "timestamp": "0x0",
    "transactions": [
      "0xe414f90fea2aebd75e8c0b3b6a4a0c9928e86c16ea724343d884f40bfe2c4c6b"
    ],
    "uncles": [],
    "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
  }
}

Running the following JS script:

const { ethers } = require('ethers')
const provider = new ethers.JsonRpcProvider('http://127.0.0.1:8545')
provider.getBlock("latest").then(console.log)

we no longer get an error, but the response below:

Block {
  provider: JsonRpcProvider {},
  number: 3,
  hash: '0x631dff9eec346af7f1ec8843e8bc02be4297d0e40d6ce20839ff07cbfd560e7d',
  timestamp: 0,
  parentHash: '0x4d17f3966a809b9755375ca6229ab5a4caa55f61d54446cad8d0bc6568900b2a',
  parentBeaconBlockRoot: null,
  nonce: '0x0100000000000000',
  difficulty: 0n,
  gasLimit: 15000000n,
  gasUsed: 103856n,
  stateRoot: '0x0000000000000000000000000000000000000000000000000000000000000000',
  receiptsRoot: '0x0000000000000000000000000000000000000000000000000000000000000000',
  blobGasUsed: null,
  excessBlobGas: null,
  miner: '0x0000000000000000000000000000000000000000',
  extraData: '0x',
  baseFeePerGas: null
}

For contributor use:

  • Targeted PR against master branch
  • Linked to Github issue with discussion and accepted design OR link to spec that describes this work.
  • Code follows the standards mentioned here.
  • Updated relevant documentation
  • Re-reviewed Files changed in the Github PR explorer
  • Added appropriate labels

Summary by CodeRabbit

  • Refactor
    • Enhanced blockchain data retrieval functions for efficiency and consolidated block preparation logic for improved code readability.
  • Documentation
    • Updated the block structure in api/models.go with new fields for a more detailed block representation.
  • Chores
    • Updated the default value for the filter-expiry flag in config/config.go from "5min" to "5m" for defining filter expiration time.

@m-Peter m-Peter added Improvement Bug Something isn't working EVM labels Apr 4, 2024
@m-Peter m-Peter added this to the Flow-EVM-M2 milestone Apr 4, 2024
@m-Peter m-Peter self-assigned this Apr 4, 2024
Copy link
Contributor

coderabbitai bot commented Apr 4, 2024

Walkthrough

The update involves refactoring the GetBlockByHash and GetBlockByNumber functions within the BlockChainAPI structure, optimizing them to utilize a new method, prepareBlockResponse, for block information preparation. Additionally, the Block struct has been enriched with numerous fields including Nonce, Sha3Uncles, and Difficulty, among others, to provide a more comprehensive representation of blockchain data.

Changes

Files Change Summary
api/api.go
api/models.go
Refactored GetBlockByHash and GetBlockByNumber in BlockChainAPI to use prepareBlockResponse. Added fields to Block struct: Nonce, Sha3Uncles, LogsBloom, TransactionsRoot, StateRoot, Miner, Difficulty, TotalDifficulty, ExtraData, Size, GasLimit, GasUsed, Timestamp, Uncles, MixHash.

A whimsical code spree, under the moon's soft glow, 🌜
Where bits and bytes dance, and data rivers flow. 🌊
A rabbit hopped along, with a coder's flair,
Twisting algorithms, with utmost care. 🐰💻
"To the blockchain deep, with new fields we leap,
Through the digital night, our code does creep."
A tale of change, in the coder's keep. 📜✨

  (\(\  
 (- -)  
((') (')

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review Status

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 38db68c and 3cb3db6.
Files selected for processing (2)
  • api/api.go (3 hunks)
  • api/models.go (1 hunks)

api/models.go Outdated
Comment on lines 137 to 156
Number hexutil.Uint64 `json:"number"`
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Nonce hexutil.Uint64 `json:"nonce"`
Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom hexutil.Bytes `json:"logsBloom"`
TransactionsRoot common.Hash `json:"transactionsRoot"`
StateRoot common.Hash `json:"stateRoot"`
ReceiptsRoot common.Hash `json:"receiptsRoot"`
Miner common.Address `json:"miner"`
Difficulty hexutil.Uint64 `json:"difficulty"`
TotalDifficulty hexutil.Uint64 `json:"totalDifficulty"`
ExtraData hexutil.Bytes `json:"extraData"`
Size hexutil.Uint64 `json:"size"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Timestamp hexutil.Uint64 `json:"timestamp"`
Transactions interface{} `json:"transactions"`
Uncles []common.Hash `json:"uncles"`
MixHash common.Hash `json:"mixHash"`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure the Transactions field in the Block struct can correctly handle both transaction hashes and full transaction data based on the context.

-	Transactions     interface{}    `json:"transactions"`
+	Transactions     []interface{}  `json:"transactions"`

This change ensures that the Transactions field can hold a slice of either transaction hashes or full transaction objects, enhancing flexibility and clarity.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
Number hexutil.Uint64 `json:"number"`
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Nonce hexutil.Uint64 `json:"nonce"`
Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom hexutil.Bytes `json:"logsBloom"`
TransactionsRoot common.Hash `json:"transactionsRoot"`
StateRoot common.Hash `json:"stateRoot"`
ReceiptsRoot common.Hash `json:"receiptsRoot"`
Miner common.Address `json:"miner"`
Difficulty hexutil.Uint64 `json:"difficulty"`
TotalDifficulty hexutil.Uint64 `json:"totalDifficulty"`
ExtraData hexutil.Bytes `json:"extraData"`
Size hexutil.Uint64 `json:"size"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Timestamp hexutil.Uint64 `json:"timestamp"`
Transactions interface{} `json:"transactions"`
Uncles []common.Hash `json:"uncles"`
MixHash common.Hash `json:"mixHash"`
Number hexutil.Uint64 `json:"number"`
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Nonce hexutil.Uint64 `json:"nonce"`
Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom hexutil.Bytes `json:"logsBloom"`
TransactionsRoot common.Hash `json:"transactionsRoot"`
StateRoot common.Hash `json:"stateRoot"`
ReceiptsRoot common.Hash `json:"receiptsRoot"`
Miner common.Address `json:"miner"`
Difficulty hexutil.Uint64 `json:"difficulty"`
TotalDifficulty hexutil.Uint64 `json:"totalDifficulty"`
ExtraData hexutil.Bytes `json:"extraData"`
Size hexutil.Uint64 `json:"size"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Timestamp hexutil.Uint64 `json:"timestamp"`
Transactions []interface{} `json:"transactions"`
Uncles []common.Hash `json:"uncles"`
MixHash common.Hash `json:"mixHash"`

api/api.go Outdated
Comment on lines 748 to 786
func (b *BlockChainAPI) prepareBlockResponse(
ctx context.Context,
block *evmTypes.Block,
fullTx bool,
) (*Block, error) {
h, err := block.Hash()
if err != nil {
b.logger.Error().Err(err).Msg("failed to calculate hash for block by number")
return nil, errs.ErrInternal
}

blockResponse := &Block{
Hash: h,
Number: hexutil.Uint64(block.Height),
ParentHash: block.ParentBlockHash,
ReceiptsRoot: block.ReceiptRoot,
Transactions: block.TransactionHashes,
Uncles: []common.Hash{},
GasLimit: hexutil.Uint64(15_000_000),
}

transactions, err := b.fetchBlockTransactions(ctx, block)
if err != nil {
return nil, err
}
for _, tx := range transactions {
blockResponse.GasUsed += tx.Gas
}

if fullTx {
blockResponse.Transactions = transactions
}

return blockResponse, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor the prepareBlockResponse method to ensure the GasUsed calculation is accurate and efficient.

-	for _, tx := range transactions {
-		blockResponse.GasUsed += tx.Gas
-	}
+	if len(transactions) > 0 {
+		totalGasUsed := hexutil.Uint64(0)
+		for _, tx := range transactions {
+			totalGasUsed += tx.Gas
+		}
+		blockResponse.GasUsed = totalGasUsed
+	}

This change ensures that GasUsed is only calculated if there are transactions, and it uses a temporary variable to accumulate the total gas used before assigning it to the Block struct. This approach minimizes potential issues with directly modifying the struct field in a loop and clarifies the intention of the code.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
func (b *BlockChainAPI) prepareBlockResponse(
ctx context.Context,
block *evmTypes.Block,
fullTx bool,
) (*Block, error) {
h, err := block.Hash()
if err != nil {
b.logger.Error().Err(err).Msg("failed to calculate hash for block by number")
return nil, errs.ErrInternal
}
blockResponse := &Block{
Hash: h,
Number: hexutil.Uint64(block.Height),
ParentHash: block.ParentBlockHash,
ReceiptsRoot: block.ReceiptRoot,
Transactions: block.TransactionHashes,
Uncles: []common.Hash{},
GasLimit: hexutil.Uint64(15_000_000),
}
transactions, err := b.fetchBlockTransactions(ctx, block)
if err != nil {
return nil, err
}
for _, tx := range transactions {
blockResponse.GasUsed += tx.Gas
}
if fullTx {
blockResponse.Transactions = transactions
}
return blockResponse, nil
}
func (b *BlockChainAPI) prepareBlockResponse(
ctx context.Context,
block *evmTypes.Block,
fullTx bool,
) (*Block, error) {
h, err := block.Hash()
if err != nil {
b.logger.Error().Err(err).Msg("failed to calculate hash for block by number")
return nil, errs.ErrInternal
}
blockResponse := &Block{
Hash: h,
Number: hexutil.Uint64(block.Height),
ParentHash: block.ParentBlockHash,
ReceiptsRoot: block.ReceiptRoot,
Transactions: block.TransactionHashes,
Uncles: []common.Hash{},
GasLimit: hexutil.Uint64(15_000_000),
}
transactions, err := b.fetchBlockTransactions(ctx, block)
if err != nil {
return nil, err
}
if len(transactions) > 0 {
totalGasUsed := hexutil.Uint64(0)
for _, tx := range transactions {
totalGasUsed += tx.Gas
}
blockResponse.GasUsed = totalGasUsed
}
if fullTx {
blockResponse.Transactions = transactions
}
return blockResponse, nil
}

@m-Peter m-Peter force-pushed the add-missing-block-fields branch from 3cb3db6 to 22afd7c Compare April 4, 2024 10:43
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review Status

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 38db68c and 22afd7c.
Files selected for processing (2)
  • api/api.go (3 hunks)
  • api/models.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • api/api.go

Comment on lines +137 to +156
Number hexutil.Uint64 `json:"number"`
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Nonce types.BlockNonce `json:"nonce"`
Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom hexutil.Bytes `json:"logsBloom"`
TransactionsRoot common.Hash `json:"transactionsRoot"`
StateRoot common.Hash `json:"stateRoot"`
ReceiptsRoot common.Hash `json:"receiptsRoot"`
Miner common.Address `json:"miner"`
Difficulty hexutil.Uint64 `json:"difficulty"`
TotalDifficulty hexutil.Uint64 `json:"totalDifficulty"`
ExtraData hexutil.Bytes `json:"extraData"`
Size hexutil.Uint64 `json:"size"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Timestamp hexutil.Uint64 `json:"timestamp"`
Transactions interface{} `json:"transactions"`
Uncles []common.Hash `json:"uncles"`
MixHash common.Hash `json:"mixHash"`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider changing the Transactions field type from interface{} to []interface{} to explicitly support both transaction hashes and full transaction objects.

-	Transactions     interface{}      `json:"transactions"`
+	Transactions     []interface{}    `json:"transactions"`

This modification ensures that the Transactions field can hold a slice of either transaction hashes or full transaction objects, enhancing flexibility and clarity.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
Number hexutil.Uint64 `json:"number"`
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Nonce types.BlockNonce `json:"nonce"`
Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom hexutil.Bytes `json:"logsBloom"`
TransactionsRoot common.Hash `json:"transactionsRoot"`
StateRoot common.Hash `json:"stateRoot"`
ReceiptsRoot common.Hash `json:"receiptsRoot"`
Miner common.Address `json:"miner"`
Difficulty hexutil.Uint64 `json:"difficulty"`
TotalDifficulty hexutil.Uint64 `json:"totalDifficulty"`
ExtraData hexutil.Bytes `json:"extraData"`
Size hexutil.Uint64 `json:"size"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Timestamp hexutil.Uint64 `json:"timestamp"`
Transactions interface{} `json:"transactions"`
Uncles []common.Hash `json:"uncles"`
MixHash common.Hash `json:"mixHash"`
Number hexutil.Uint64 `json:"number"`
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Nonce types.BlockNonce `json:"nonce"`
Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom hexutil.Bytes `json:"logsBloom"`
TransactionsRoot common.Hash `json:"transactionsRoot"`
StateRoot common.Hash `json:"stateRoot"`
ReceiptsRoot common.Hash `json:"receiptsRoot"`
Miner common.Address `json:"miner"`
Difficulty hexutil.Uint64 `json:"difficulty"`
TotalDifficulty hexutil.Uint64 `json:"totalDifficulty"`
ExtraData hexutil.Bytes `json:"extraData"`
Size hexutil.Uint64 `json:"size"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Timestamp hexutil.Uint64 `json:"timestamp"`
Transactions []interface{} `json:"transactions"`
Uncles []common.Hash `json:"uncles"`
MixHash common.Hash `json:"mixHash"`

@m-Peter
Copy link
Collaborator Author

m-Peter commented Apr 4, 2024

cc @jribbink

Copy link
Contributor

@devbugging devbugging left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, thank you

@devbugging devbugging merged commit fd9c284 into onflow:main Apr 4, 2024
1 check passed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review Status

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 22afd7c and 929969f.
Files selected for processing (2)
  • api/api.go (3 hunks)
  • config/config.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • api/api.go
Additional comments not posted (1)
config/config.go (1)

84-84: Ensure the updated "5m" notation for the filter-expiry flag's default value is consistent with time duration representations elsewhere in the project.

@m-Peter m-Peter deleted the add-missing-block-fields branch April 8, 2024 10:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working EVM Improvement
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

2 participants