Skip to content

feat: implement external genesis configuration support#87

Merged
Zahnentferner merged 2 commits into
StabilityNexus:mainfrom
SIDDHANTCOOKIE:feature/genesis-config
May 29, 2026
Merged

feat: implement external genesis configuration support#87
Zahnentferner merged 2 commits into
StabilityNexus:mainfrom
SIDDHANTCOOKIE:feature/genesis-config

Conversation

@SIDDHANTCOOKIE
Copy link
Copy Markdown
Member

@SIDDHANTCOOKIE SIDDHANTCOOKIE commented May 27, 2026

Addressed Issues:

This PR fulfills the first requirement of Phase 1 (Week 3) of our roadmap by implementing externalized genesis configuration for MiniChain. Previously, the genesis block was hardcoded into chain.py with zero initial balances.
Now, MiniChain boots up by reading genesis.json. This gives us total control over the network's initial state without touching core logic.

Screenshots/Recordings:

image Screenshot 2026-05-28 033850

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

  • New Features

    • Genesis configuration can be loaded from an external JSON file, including chain ID, timestamp, difficulty, and pre-funded accounts.
  • Bug Fixes

    • Genesis validation now verifies the actual genesis block hash instead of assuming a fixed placeholder.
  • Tests

    • Persistence tests updated to assert the restored genesis hash matches the saved chain.
  • Chores

    • Initialization refactored to support configurable genesis loading.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 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: 52c33ba9-d0e8-4652-95f2-e3375730c204

📥 Commits

Reviewing files that changed from the base of the PR and between 310e564 and 568a521.

📒 Files selected for processing (4)
  • genesis.json
  • minichain/chain.py
  • minichain/persistence.py
  • tests/test_persistence.py
💤 Files with no reviewable changes (1)
  • genesis.json

Walkthrough

Adds a filesystem-backed genesis.json and refactors minichain/chain.py to load and apply genesis metadata and allocations; persistence now recomputes/verifies the genesis hash; tests updated to assert the computed genesis hash.

Changes

Genesis Block Configurability

Layer / File(s) Summary
Genesis configuration file
genesis.json
Defines chain_id, timestamp, difficulty, and alloc balances for pre-funded addresses.
Blockchain bootstrap and genesis creation
minichain/chain.py
Adds json, os, sys imports; Blockchain.__init__ accepts genesis_path; _create_genesis_block loads JSON, applies alloc to State, sets timestamp/difficulty, computes genesis header hash, and optionally verifies/overrides with config["hash"].
Persistence genesis validation
minichain/persistence.py
Replaces hard-coded zero-hash check by recomputing calculate_hash(genesis.to_header_dict()) and enforces genesis.index == 0.
Tests updated for computed genesis hash
tests/test_persistence.py
Tests now compare restored genesis block hash against bc.chain[0].hash instead of expecting "0" * 64.

Sequence Diagram(s)

sequenceDiagram
  participant Blockchain
  participant OS
  participant JSON as JSONParser
  participant State
  Blockchain->>OS: read genesis_path file
  OS-->>JSON: file contents
  JSON-->>Blockchain: parsed genesis config
  Blockchain->>State: apply alloc balances
  Blockchain->>Blockchain: set timestamp and difficulty
  Blockchain->>Blockchain: calculate genesis header hash
  Blockchain->>Blockchain: verify or use configured hash
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

Python Lang

Suggested reviewers

  • Zahnentferner

A genesis file hops into view, 🐰
Configured seeds in JSON laid true,
Balances sown, the header's cast anew,
Persistence checks the hash for proof,
A tiny chain wakes up, resilient and true.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: implement external genesis configuration support' accurately describes the main change—enabling external genesis configuration instead of hardcoded logic.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@minichain/chain.py`:
- Around line 52-56: The alloc loop in minichain/chain.py assigns balances from
external JSON without validation; update the loop that iterates over alloc
(where account = self.state.get_account(address) and account['balance'] = ...)
to validate each balance is an integer and non-negative before committing: parse
numeric strings safely (or reject non-numeric), ensure value >= 0, and either
raise a clear ValueError (or log and skip/normalize) when validation fails so
invalid balances are not written into state.
- Around line 44-50: The node currently continues startup with empty state when
genesis.json is missing or invalid; change the logic in chain.py around
genesis_path so that missing file or JSON parse errors cause a fail-fast exit:
if not os.path.exists(genesis_path) or json.load fails, log a clear error via
logger.error (including the exception/message) and terminate startup immediately
(e.g., raise SystemExit or call sys.exit(1)) instead of proceeding with a
default/empty config; update the block handling "with open(genesis_path...)" and
any surrounding code that assumes config to ensure startup is aborted on
load/parse failure.
- Around line 57-67: The code sets genesis_block.hash directly from config which
can create an inconsistent block; change the logic around the genesis Block
creation (the genesis_block assignment) to compute the canonical hash from the
genesis header (use the existing Block.calculate_hash or the module's
calculate_hash function) and then: if config contains a "hash", verify it equals
the computed hash and raise/log an error (or raise an exception) on mismatch; if
no "hash" present, assign the computed hash to genesis_block.hash. Ensure this
verification happens immediately after creating genesis_block and before
returning or persisting it.
🪄 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: 2c0355a2-c2cd-4ae7-903d-390e6dd51d9a

📥 Commits

Reviewing files that changed from the base of the PR and between b08c967 and 310e564.

📒 Files selected for processing (2)
  • genesis.json
  • minichain/chain.py

Comment thread minichain/chain.py
Comment thread minichain/chain.py
Comment thread minichain/chain.py Outdated
@Zahnentferner Zahnentferner merged commit 577e854 into StabilityNexus:main May 29, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants