Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ jobs:
pip install -r requirements.txt

- name: Run tests
env:
INITIAL_ADMIN_PASSWORD: testadmin123
SESSION_SECRET: ci-session-secret
run: |
python -m pytest tests/ -v --tb=short

Expand All @@ -58,8 +61,14 @@ jobs:
docker run -d -p 5000:5000 --name test-app \
-e DATABASE_URL=sqlite:////tmp/credify.db \
-e INITIAL_ADMIN_PASSWORD=testadmin123 \
-e SESSION_SECRET=ci-session-secret \
credify:${{ github.sha }}
sleep 15
for i in {1..30}; do
if curl -fsS http://localhost:5000/ > /dev/null; then
break
fi
sleep 2
done
curl -f http://localhost:5000/ || exit 1
docker stop test-app
docker rm test-app
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/docker-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ jobs:
push: true
tags: |
udaycodespace/credify:latest
udaycodespace/credify:v2.1.0
udaycodespace/credify:v2
udaycodespace/credify:sha-${{ github.sha }}
cache-from: type=registry,ref=udaycodespace/credify:buildcache
cache-to: type=registry,ref=udaycodespace/credify:buildcache,mode=max
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,5 @@ htmlcov/
.coverage
dist/
build/
*.egg-info/
*.egg-info/
credify-verify/
1,043 changes: 272 additions & 771 deletions README.md

Large diffs are not rendered by default.

30 changes: 21 additions & 9 deletions app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,36 @@ def init_extensions(app):
blockchain.create_genesis_block()

# P2P multi-node init
peer_nodes_env = os.environ.get("PEER_NODES", "")
if peer_nodes_env:
for peer in peer_nodes_env.split(","):
if peer.strip():
try:
blockchain.register_node(peer.strip())
except Exception as e:
logging.warning(f"Invalid peer URI: {peer.strip()}")
blockchain.node_id = app.config.get("NODE_ID", "standalone")
blockchain.node_address = (app.config.get("NODE_ADDRESS", "") or "").strip().rstrip("/")
local_node_address = (app.config.get("NODE_ADDRESS", "") or "").strip().rstrip("/")
peer_nodes = app.config.get("PEER_NODES", [])

if peer_nodes:
for peer in peer_nodes:
if local_node_address and peer == local_node_address:
continue
try:
blockchain.register_node(peer)
except Exception:
logging.warning(f"Invalid peer URI: {peer}")
if blockchain.nodes:
threading.Thread(target=_initial_sync, args=(app,), daemon=True).start()

configured_node_validators = app.config.get("VALIDATOR_NODES", [])
if configured_node_validators:
blockchain.set_node_validators(configured_node_validators)
else:
blockchain.set_node_validators([blockchain._get_current_node_ref(), *blockchain.nodes])


def _initial_sync(app):
"""Background peer synchronization task"""
time.sleep(5)
with app.app_context():
try:
logging.info(f"Syncing with peers: {blockchain.nodes}...")
node_id = app.config.get("NODE_ID", "standalone")
logging.info(f"Node {node_id} syncing with peers: {blockchain.nodes}...")
if blockchain.resolve_conflicts():
logging.info(f"Synchronized chain. New length: {len(blockchain.chain)}")
except Exception as e:
Expand Down
2 changes: 1 addition & 1 deletion app/blueprints/admin/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ def api_system_stats():
stats["blockchain"] = {
"blocks": len(blockchain.chain),
"peers": len(blockchain.nodes),
"node_name": os.environ.get("NODE_NAME", "standalone"),
"node_name": current_app.config.get("NODE_ID") or os.environ.get("NODE_NAME", "standalone"),
"validators": blockchain.VALIDATORS,
}

Expand Down
81 changes: 58 additions & 23 deletions app/blueprints/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,29 +79,23 @@ def receive_peer_block():
if not block_data:
return jsonify({"success": False, "message": "No block data provided"}), 400

# 1. Reconstruct block object
new_block = blockchain.block_model(
index=block_data["index"],
timestamp=block_data["timestamp"],
data=json.dumps(block_data["data"]),
merkle_root=block_data.get("merkle_root"),
previous_hash=block_data["previous_hash"],
nonce=block_data["nonce"],
hash=block_data["hash"],
signed_by=block_data.get("signed_by"),
signature=block_data.get("signature"),
)
required_fields = {"index", "timestamp", "data", "previous_hash", "nonce", "hash"}
missing = [field for field in required_fields if field not in block_data]
if missing:
return jsonify({"success": False, "message": f"Missing required fields: {', '.join(missing)}"}), 400

# 2. Simple validation against local chain
last_block = blockchain.get_latest_block()
if last_block and block_data["index"] <= last_block.index:
return jsonify({"success": False, "message": "Block already exists or is outdated"}), 409
source_node = blockchain.normalize_node_ref(request.headers.get("X-Node-Address") or request.headers.get("X-Source-Node"))
origin_node = (request.headers.get("X-Origin-Node") or request.headers.get("X-Source-Node") or "unknown").strip()
sender_node = source_node or blockchain.normalize_node_ref(block_data.get("proposed_by"))

if last_block and block_data["previous_hash"] != last_block.hash:
return jsonify({"success": False, "message": "Previous hash mismatch. Sync required."}), 400
if not blockchain.is_validator_node(sender_node):
return jsonify({"success": False, "message": f"Unauthorized validator node: {sender_node or 'unknown'}"}), 403

# 3. Cryptographic validation (simplified for the model bridge)
# Create a Block object for validation methods
# Idempotency gate: if already present, ignore safely.
if blockchain.has_block(block_data["index"], block_data["hash"]):
return jsonify({"success": True, "message": "Duplicate block ignored"}), 200

# 1. Validate block object before any persistence
from core.blockchain import Block

v_block = Block(
Expand All @@ -110,6 +104,8 @@ def receive_peer_block():
block_data["previous_hash"],
signed_by=block_data.get("signed_by"),
signature=block_data.get("signature"),
proposed_by=block_data.get("proposed_by"),
status=block_data.get("status"),
)
v_block.timestamp = block_data["timestamp"]
v_block.nonce = block_data["nonce"]
Expand All @@ -119,16 +115,55 @@ def receive_peer_block():
if v_block.hash != v_block.calculate_hash():
return jsonify({"success": False, "message": "Invalid block hash"}), 400

if blockchain.crypto_manager and v_block.signature:
if v_block.merkle_root and v_block.merkle_root != v_block.calculate_merkle_root():
return jsonify({"success": False, "message": "Invalid Merkle root"}), 400

if v_block.index > 0 and v_block.signed_by not in blockchain.VALIDATORS:
return jsonify({"success": False, "message": "Unauthorized block signer"}), 403

if blockchain.crypto_manager:
if not v_block.signature:
return jsonify({"success": False, "message": "Missing digital signature"}), 400
if not blockchain.crypto_manager.verify_signature(v_block.hash, v_block.signature):
return jsonify({"success": False, "message": "Invalid digital signature"}), 400

# All checks passed, add to local DB and chain
# Finality gate: old blocks may omit status; accepted blocks become FINALIZED.
if v_block.status not in (None, "FINALIZED"):
return jsonify({"success": False, "message": "Block status must be FINALIZED"}), 400

# 2. Validate against local chain linkage
last_block = blockchain.get_latest_block()
if last_block and block_data["index"] <= last_block.index:
return jsonify({"success": True, "message": "Outdated block ignored"}), 200

if last_block and block_data["previous_hash"] != last_block.hash:
return jsonify({"success": False, "message": "Previous hash mismatch. Sync required."}), 400

# 3. Persist only after full validation
new_block = blockchain.block_model(
index=block_data["index"],
timestamp=block_data["timestamp"],
data=json.dumps(block_data["data"]),
merkle_root=block_data.get("merkle_root"),
previous_hash=block_data["previous_hash"],
nonce=block_data["nonce"],
hash=block_data["hash"],
signed_by=block_data.get("signed_by"),
signature=block_data.get("signature"),
)

db.session.add(new_block)
db.session.commit()
v_block.status = "FINALIZED"
blockchain.chain.append(v_block)

logging.info(f"Accepted peer block {block_data['index']} from {block_data.get('signed_by')}")
# Controlled gossip propagation: relay accepted blocks, never back to sender.
blockchain.broadcast_block(v_block, source_node=source_node, origin_node=origin_node)

logging.info(
f"Accepted peer block {block_data['index']} from signer={block_data.get('signed_by')} "
f"source={source_node or 'unknown'} origin={origin_node} sender={sender_node or 'unknown'}"
)
return jsonify({"success": True, "message": "Block accepted and added to chain"})

except Exception as e:
Expand Down
21 changes: 21 additions & 0 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ class Config:
SECRET_KEY = os.environ.get("SESSION_SECRET", "dev-secret-key-change-in-production")
DEBUG = True
PORT = int(os.environ.get("PORT", 5000))
HOST = os.environ.get("HOST", "0.0.0.0")

# Multi-node settings (backward compatible aliases)
NODE_ID = os.environ.get("NODE_ID") or os.environ.get("NODE_NAME") or "standalone"
NODE_ADDRESS = (os.environ.get("NODE_ADDRESS") or "").strip()
PEER_NODES = [
peer.strip().rstrip("/")
for peer in os.environ.get("PEER_NODES", "").split(",")
if peer.strip()
]

# IPFS settings
IPFS_ENDPOINTS = [
Expand All @@ -47,6 +57,17 @@ class Config:
# Blockchain settings - FIXED paths
BLOCKCHAIN_DIFFICULTY = 0
VALIDATOR_USERNAMES = ["admin", "issuer1"]
VALIDATOR_NODES = [
node.strip().rstrip("/")
for node in os.environ.get(
"VALIDATORS",
os.environ.get(
"VALIDATOR_NODES",
"node1:5000,node2:5000,node3:5000,node4:5000,node5:5000,standalone",
),
).split(",")
if node.strip()
]
BLOCKCHAIN_FILE = DATA_DIR / "blockchain_data.json"

# Crypto settings - FIXED path
Expand Down
Loading
Loading