Skip to content

refactor: Consolidate scattered validation logic#77

Open
SIDDHANTCOOKIE wants to merge 2 commits intoStabilityNexus:mainfrom
SIDDHANTCOOKIE:refactor/consolidate-validation
Open

refactor: Consolidate scattered validation logic#77
SIDDHANTCOOKIE wants to merge 2 commits intoStabilityNexus:mainfrom
SIDDHANTCOOKIE:refactor/consolidate-validation

Conversation

@SIDDHANTCOOKIE
Copy link
Copy Markdown
Contributor

@SIDDHANTCOOKIE SIDDHANTCOOKIE commented Mar 27, 2026

Addressed Issues:

This PR fundamentally sorts the network's validation logic into two clean, distinct buckets:

  1. Basic Checks (Stateless) -> strictly constrained to native Object methods
    • Signature verification is securely consolidated into a single source of truth.
    • Core formatting (address hex validation, type checking, amount boundaries) is globally unified.
    • Massive blocks of manual dictionary-parsing code for incoming network messages were completely deleted and replaced by robust, exception-safe object serialization.
  2. State Checks (Stateful) -> strictly constrained to the State manager
    • Obsolete and duplicate stateless formatting checks were entirely stripped out of the state execution loop.
    • The state manager now purely focuses on rigorous account mathematics (e.g., verifying balance sufficiency and strict nonce ordering).
      This structurally stops the chain from repeating duplicate security checks, rapidly accelerating network validation and increasing spam resilience, all while resulting in a net decrease of 31 lines of code.

Screenshots/Recordings:

Screenshot 2026-03-27 160146 Screenshot 2026-03-27 160209

Additional Notes:

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

  • Bug Fixes

    • Stricter validation for transactions and blocks—malformed items are now rejected gracefully.
    • Mempool and network now reject invalid transactions/blocks more consistently.
    • CLI send command enforces canonical address format for recipients.
  • Refactor

    • Validation logic unified and simplified across mining, state, mempool, and networking for consistent behavior.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 97154de5-baab-401c-89de-7da78120b0c2

📥 Commits

Reviewing files that changed from the base of the PR and between 3c600c8 and 7859e3a.

📒 Files selected for processing (3)
  • .gitignore
  • minichain/block.py
  • minichain/transaction.py

Walkthrough

Validation and deserialization were consolidated into domain objects: Transaction.from_dict/Block.from_dict now return None on parse errors and is_valid() methods were added; callers (P2P, mempool, state, chain, CLI, mining) were updated to use these methods and apply_transaction replaced the removed validate_and_apply.

Changes

Cohort / File(s) Summary
Domain objects: Transaction & Block
minichain/transaction.py, minichain/block.py
Added Transaction.is_valid_address() and Transaction.is_valid(); Transaction.from_dict() and Block.from_dict() now defensively return None on parse errors; added Block.is_valid() to validate types, merkle root and contained transactions.
State & Chain changes
minichain/state.py, minichain/chain.py
Removed State.validate_and_apply(); switched internal validation use from verify() to is_valid() and callers now use apply_transaction() when constructing/committing state during block acceptance.
Mempool & P2P validation delegation
minichain/mempool.py, minichain/p2p.py
Mempool now calls tx.is_valid() (message updated). P2P payload validation delegates to Transaction.from_dict()/Block.from_dict() and uses their is_valid() results instead of inline field checks; removed is_valid_receiver import.
CLI & Mining
main.py
CLI send command uses Transaction.is_valid_address() for receiver format checks; mining selects mineable transactions via temp_state.apply_transaction(tx) instead of validate_and_apply().
Validators module
minichain/validators.py
Removed standalone is_valid_receiver() helper and its re import.
Tests & ignore
tests/test_protocol_hardening.py, .gitignore
Test updated to use a millisecond-style timestamp for transaction in block schema test; added .node*/ ignore pattern for local persistence dirs.

Sequence Diagram(s)

sequenceDiagram
    participant Peer
    participant P2PNetwork
    participant Transaction
    participant Block
    participant Mempool
    participant State

    Peer->>P2PNetwork: send message (tx/block payload)
    alt payload is transaction
        P2PNetwork->>Transaction: Transaction.from_dict(payload)
        Transaction-->>P2PNetwork: tx or None
        P2PNetwork->>Transaction: tx.is_valid()
        alt valid
            P2PNetwork->>Mempool: add_transaction(tx)
            Mempool-->>P2PNetwork: accepted
        else invalid
            P2PNetwork-->>Peer: reject
        end
    else payload is block
        P2PNetwork->>Block: Block.from_dict(payload)
        Block-->>P2PNetwork: block or None
        P2PNetwork->>Block: block.is_valid()
        alt valid
            P2PNetwork->>State: propose block (apply transactions)
            State->>State: apply_transaction(tx) for each tx
            alt all applied
                State-->>P2PNetwork: commit
            else failure
                State-->>P2PNetwork: reject
            end
        else invalid
            P2PNetwork-->>Peer: reject
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

Python Lang

Suggested reviewers

  • Zahnentferner

Poem

🐰 Hopping through the code tonight,
I stitched validations snug and tight.
From dicts that fail to checks that bind,
Transactions and blocks behave aligned.
A nimble hop — the chain looks bright! ✨

🚥 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 captures the main objective: consolidating scattered validation logic across multiple files into centralized domain objects and state manager.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@minichain/block.py`:
- Around line 121-122: The constructor currently overrides the computed merkle
root with the incoming payload's "merkle_root" (block.merkle_root), which can be
spoofed; remove that unconditional override or (preferred) keep accepting the
field but add verification in is_valid(): compute
_calculate_merkle_root(self.transactions) and compare it to self.merkle_root,
returning False or raising a validation error if they differ; update is_valid()
to reference block.merkle_root, _calculate_merkle_root, and the constructor's
handling of the "merkle_root" payload so the stored value must match the
computed value.

In `@minichain/transaction.py`:
- Around line 72-74: Simplify the nested checks around the receiver by combining
them into one conditional: replace the outer if self.receiver is not None with a
single if that tests both presence and validity (e.g., if self.receiver is not
None and (not isinstance(self.receiver, str) or not
self.is_valid_address(self.receiver)): return False), referencing the receiver
attribute and the is_valid_address method to keep the same behavior but with a
single, clearer condition.
- Around line 44-47: Move the import of the regular expression module out of the
is_valid_address static method to the module level: add import re alongside the
other top-level imports, then remove the inline import inside is_valid_address
so the method simply uses re.fullmatch; this avoids repeated module lookups and
keeps the method body minimal.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4e2d52f3-0c75-442c-917c-cf0ae4a7fa35

📥 Commits

Reviewing files that changed from the base of the PR and between 518c70a and 3c600c8.

📒 Files selected for processing (9)
  • main.py
  • minichain/block.py
  • minichain/chain.py
  • minichain/mempool.py
  • minichain/p2p.py
  • minichain/state.py
  • minichain/transaction.py
  • minichain/validators.py
  • tests/test_protocol_hardening.py
💤 Files with no reviewable changes (1)
  • minichain/validators.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.

1 participant