Skip to content

Refactor for conceptual minimality in validation and deserialization flows#62

Merged
Zahnentferner merged 1 commit intoStabilityNexus:mainfrom
SIDDHANTCOOKIE:refactor-reduce-duplicates
Mar 21, 2026
Merged

Refactor for conceptual minimality in validation and deserialization flows#62
Zahnentferner merged 1 commit intoStabilityNexus:mainfrom
SIDDHANTCOOKIE:refactor-reduce-duplicates

Conversation

@SIDDHANTCOOKIE
Copy link
Copy Markdown
Contributor

@SIDDHANTCOOKIE SIDDHANTCOOKIE commented Mar 20, 2026

Addressed Issues:

This PR reduces duplicated logic so core rules live in one place, making the code easier to reason about and less likely to drift over time.
It is intentionally minimal and non-breaking.

Screenshots/Recordings:

image

has non breaking changes

Additional Notes:

What changed

  • Added Transaction.from_dict(...) and reused it for incoming network transactions.
  • Added Block.from_dict(...) and reused it for:
    • incoming network blocks
    • persistence block deserialization
  • Centralized block linkage + hash checks into validate_block_link_and_hash(...) in minichain/chain.py.
  • Reused the same block validation helper in persistence integrity checks.
  • Removed one dead variable in main.py (nonce_counter).

Scope and safety

  • No protocol or feature behavior changes intended.
  • This is a structural refactor focused on deduplication and conceptual minimality.
  • Existing logic paths now call shared helpers instead of re-implementing equivalent logic.

AI Usage Disclosure:

We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact. AI slop is strongly discouraged and may lead to banning and blocking. Do not spam our repos with AI slop.

Check one of the checkboxes below:

  • This PR does not contain AI-generated code at all.
  • This PR contains AI-generated code. I have read the AI Usage Policy and this PR complies with this policy. I have tested the code locally and I am responsible for it.

I have used the following AI models and tools: TODO

Checklist

  • My PR addresses a single issue, fixes a single bug or makes a single improvement.
  • My code follows the project's code style and conventions
  • If applicable, I have made corresponding changes or additions to the documentation
  • If applicable, I have made corresponding changes or additions to tests
  • My changes generate no new warnings or errors
  • I have joined the Discord server and I will share a link to this PR with the project maintainers there
  • I have read the Contribution Guidelines
  • Once I submit my PR, CodeRabbit AI will automatically review it and I will address CodeRabbit's comments.
  • I have filled this PR template completely and carefully, and I understand that my PR may be closed without review otherwise.

Summary by CodeRabbit

  • Refactor
    • Improved deserialization of blocks and transactions from P2P network messages.
    • Consolidated block validation logic for linkage and hash verification.
    • Streamlined transaction nonce handling to use chain state directly.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 20, 2026

Walkthrough

The changes refactor deserialization and validation logic across the blockchain codebase. New from_dict() classmethods are introduced to Transaction and Block for standardized deserialization. Block validation logic is extracted into a reusable validate_block_link_and_hash() helper function, replacing inline checks and reducing code duplication across modules.

Changes

Cohort / File(s) Summary
Deserialization Methods
minichain/transaction.py, minichain/block.py
Added from_dict() classmethods to enable centralized deserialization from dictionary payloads, replacing ad-hoc manual reconstruction patterns.
Message Parsing Updates
main.py
Updated P2P message parsing to use new Transaction.from_dict() and Block.from_dict() methods; removed mutable nonce_counter closure variable in favor of chain state lookup.
Validation Extraction
minichain/chain.py, minichain/persistence.py
Extracted block linkage and hash verification into validate_block_link_and_hash() helper; updated Blockchain.add_block() and chain integrity checks to delegate validation to this function rather than inline checks.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

Python Lang

Suggested reviewers

  • Zahnentferner

Poem

🐰 Hop along, refactors bright!
from_dict() shines in morning light,
Validation cleaned, no mess in sight—
Blockchain code now organized just right! 🥕✨

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main objective of the pull request—refactoring code to reduce duplicated logic in validation and deserialization—which aligns with the core changes across all modified files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

You can validate your CodeRabbit configuration file in your editor.

If your editor has YAML language server, you can enable auto-completion and validation by adding # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json at the top of your CodeRabbit configuration file.

Copy link
Copy Markdown
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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
main.py (1)

331-331: ⚠️ Potential issue | 🔴 Critical

host is undefined at this line — NameError will crash the node on startup.

The run_node function uses host on line 331, but this variable is not defined in the function's scope. The function signature is:

async def run_node(port: int, connect_to: str | None, fund: int, datadir: str | None):

The --host argument from argparse (line 362) is never passed to run_node. Although host is assigned later in the function when connect_to is provided (from connect_to.rsplit(":", 1)), this occurs after line 331 and only when the --connect flag is used. This will cause a NameError in all cases, including the default startup path.

🐛 Proposed fix

Update the function signature and call site:

-async def run_node(port: int, connect_to: str | None, fund: int, datadir: str | None):
+async def run_node(port: int, host: str, connect_to: str | None, fund: int, datadir: str | None):

And in main():

-        asyncio.run(run_node(args.port, args.connect, args.fund, args.datadir))
+        asyncio.run(run_node(args.port, args.host, args.connect, args.fund, args.datadir))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@main.py` at line 331, The bug is that run_node uses an undefined host
variable at the call to network.start(port=port, host=host); update run_node to
accept a host parameter (e.g., async def run_node(port: int, connect_to: str |
None, fund: int, datadir: str | None, host: str | None)) and use that parameter
when calling network.start, and then pass the parsed --host value from main()
into run_node where it is invoked; ensure the host parameter type/nullable
default matches existing usage and update any other call sites of run_node
accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@main.py`:
- Line 331: The bug is that run_node uses an undefined host variable at the call
to network.start(port=port, host=host); update run_node to accept a host
parameter (e.g., async def run_node(port: int, connect_to: str | None, fund:
int, datadir: str | None, host: str | None)) and use that parameter when calling
network.start, and then pass the parsed --host value from main() into run_node
where it is invoked; ensure the host parameter type/nullable default matches
existing usage and update any other call sites of run_node accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 21ea5171-3ca1-4b31-97d6-8ad4b843f862

📥 Commits

Reviewing files that changed from the base of the PR and between 7004eec and 7eed7b7.

📒 Files selected for processing (5)
  • main.py
  • minichain/block.py
  • minichain/chain.py
  • minichain/persistence.py
  • minichain/transaction.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants