generated from StabilityNexus/Template-Repo
-
-
Notifications
You must be signed in to change notification settings - Fork 7
feat: Introduce Merkle Tree for Transaction Verification (SPV Support) #28
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
Open
Muneerali199
wants to merge
8
commits into
StabilityNexus:main
Choose a base branch
from
Muneerali199:feature/merkle-tree-spv-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+661
−117
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b4b1611
feat: add Merkle Tree for SPV transaction verification
Muneerali199 557e78f
fix: address code review issues
Muneerali199 49dd969
fix: additional code review issues
Muneerali199 f38211a
fix: additional code review issues
Muneerali199 dae3fcd
fix: additional code review issues
Muneerali199 f75d68a
Fix TOCTOU race in mining.py by capturing chain.last_block once
Muneerali199 3a3b299
Fix multiple issues for thread safety and code quality
Muneerali199 e9c6ee1
Fix indentation and remove incorrect contract deployment logic
Muneerali199 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| from contextlib import asynccontextmanager | ||
| from fastapi import FastAPI, HTTPException, Query | ||
| from pydantic import BaseModel | ||
| from typing import List, Optional, Union, Dict | ||
|
|
||
| from core import Blockchain, Block, State, Transaction | ||
| from core.merkle import MerkleTree | ||
| from node import Mempool | ||
| from core.mining import mine_and_process_block | ||
|
|
||
|
|
||
| blockchain: Optional[Blockchain] = None | ||
| mempool: Optional[Mempool] = None | ||
| pending_nonce_map: Dict[str, int] = {} | ||
|
|
||
|
|
||
| @asynccontextmanager | ||
| async def lifespan(app: FastAPI): | ||
| global blockchain, mempool | ||
| blockchain = Blockchain() | ||
| mempool = Mempool() | ||
| yield | ||
| blockchain.save_to_file() | ||
|
|
||
|
|
||
| app = FastAPI(title="MiniChain API", description="SPV-enabled blockchain API", lifespan=lifespan) | ||
|
|
||
|
|
||
| class TransactionResponse(BaseModel): | ||
| sender: str | ||
| receiver: Optional[str] = None | ||
| amount: int | ||
| nonce: int | ||
| data: Optional[Union[dict, str]] = None | ||
| timestamp: int | ||
| signature: Optional[str] = None | ||
| hash: Optional[str] = None | ||
|
|
||
|
|
||
| class BlockResponse(BaseModel): | ||
| index: int | ||
| previous_hash: str | ||
| merkle_root: Optional[str] | ||
| timestamp: int | ||
| difficulty: Optional[int] | ||
| nonce: int | ||
| hash: Optional[str] = None | ||
| transactions: List[TransactionResponse] | ||
| merkle_proofs: Optional[dict] = None | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| class VerifyTransactionResponse(BaseModel): | ||
| tx_hash: str | ||
| block_index: int | ||
| merkle_root: str | ||
| proof: List[dict] | ||
| verification_status: bool | ||
| message: str | ||
|
|
||
|
|
||
| class ChainInfo(BaseModel): | ||
| length: int | ||
| blocks: List[dict] | ||
|
|
||
|
|
||
| @app.get("/") | ||
| def root(): | ||
| return {"message": "MiniChain API with SPV Support"} | ||
|
|
||
|
|
||
| @app.get("/chain", response_model=ChainInfo) | ||
| def get_chain(): | ||
| chain_copy = blockchain.get_chain_copy() | ||
|
|
||
| return { | ||
| "length": len(chain_copy), | ||
| "blocks": [block.to_dict() for block in chain_copy] | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| @app.get("/block/{block_index}", response_model=BlockResponse) | ||
| def get_block(block_index: int): | ||
| chain_copy = blockchain.get_chain_copy() | ||
|
|
||
| if block_index < 0 or block_index >= len(chain_copy): | ||
| raise HTTPException(status_code=404, detail="Block not found") | ||
|
|
||
| block = chain_copy[block_index] | ||
|
|
||
| block_dict = block.to_dict() | ||
|
|
||
| merkle_proofs = {} | ||
| for i, _ in enumerate(block.transactions): | ||
| tx_hash = block.get_tx_hash(i) | ||
| if tx_hash: | ||
| proof = block.get_merkle_proof(i) | ||
| if proof is not None: | ||
| merkle_proofs[tx_hash] = proof | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return { | ||
| **block_dict, | ||
| "merkle_proofs": merkle_proofs | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| @app.get("/verify_transaction", response_model=VerifyTransactionResponse) | ||
| def verify_transaction( | ||
| tx_hash: str = Query(..., description="Transaction hash to verify"), | ||
| block_index: int = Query(..., description="Block index to verify against") | ||
| ): | ||
| chain_copy = blockchain.get_chain_copy() | ||
|
|
||
| if block_index < 0 or block_index >= len(chain_copy): | ||
| raise HTTPException(status_code=404, detail="Block not found") | ||
|
|
||
| block = chain_copy[block_index] | ||
|
|
||
| tx_found = False | ||
| tx_index = -1 | ||
| for i, _ in enumerate(block.transactions): | ||
| tx_hash_computed = block.get_tx_hash(i) | ||
| if tx_hash_computed == tx_hash: | ||
| tx_found = True | ||
| tx_index = i | ||
| break | ||
|
|
||
| if not tx_found: | ||
| return { | ||
| "tx_hash": tx_hash, | ||
| "block_index": block_index, | ||
| "merkle_root": block.merkle_root or "", | ||
| "proof": [], | ||
| "verification_status": False, | ||
| "message": "Transaction not found in block" | ||
| } | ||
|
|
||
| proof = block.get_merkle_proof(tx_index) | ||
| merkle_root = block.merkle_root or "" | ||
|
|
||
| if proof is None: | ||
| return { | ||
| "tx_hash": tx_hash, | ||
| "block_index": block_index, | ||
| "merkle_root": merkle_root, | ||
| "proof": [], | ||
| "verification_status": False, | ||
| "message": "Failed to generate Merkle proof" | ||
| } | ||
|
|
||
| verification_status = MerkleTree.verify_proof(tx_hash, proof, merkle_root) | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return { | ||
| "tx_hash": tx_hash, | ||
| "block_index": block_index, | ||
| "merkle_root": merkle_root, | ||
| "proof": proof, | ||
| "verification_status": verification_status, | ||
| "message": "Transaction verified successfully" if verification_status else "Verification failed" | ||
| } | ||
|
|
||
|
|
||
| @app.post("/mine") | ||
| def mine_block_endpoint(): | ||
| block, *_ = mine_and_process_block(blockchain, mempool, pending_nonce_map) | ||
|
|
||
| if block: | ||
| return {"message": "Block mined successfully", "block": block.to_dict()} | ||
| else: | ||
| raise HTTPException(status_code=400, detail="Failed to mine block") | ||
|
Comment on lines
162
to
169
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Unnecessary
♻️ Proposed fix `@app.post`("/mine")
def mine_block_endpoint():
- global pending_nonce_map
-
block, *_ = mine_and_process_block(blockchain, mempool, pending_nonce_map)🤖 Prompt for AI Agents |
||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import uvicorn | ||
| uvicorn.run(app, host="127.0.0.1", port=8000) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.