Spaces:
Sleeping
Sleeping
feat(web3): implement resilient zero-loss local blockchain fallback logging (Story 3.3)
Browse filesFiles changed (4)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384---title: 'Story 3.3: Resilient Zero-Loss Local Blockchain Fallback'type: 'feature'created: '2026-08-30'status: 'done'baseline_commit: 'ac314d57d6f06c67c68b32eeb459d709e1646ffe'review_loop_iteration: 0context: ['_bmad-output/implementation-artifacts/epic-3-context.md']---
<frozen-after-approval reason="human-owned intent — do not modify unless human renegotiates">
## Intent
**Problem:** In production border checkpoints and offline environments, Ethereum RPC nodes may experience outages, network latency spikes, or unconfigured wallet private keys. Biometric inspection requests must never fail or block passenger flows due to blockchain connectivity issues.
**Approach:** Ensure `BlockchainLogger` in `src/verification/blockchain_store.py` provides resilient zero-loss local append-only logging to `static/blockchain_log.json`, returning a deterministic receipt `local_record_<hash>` when Ethereum RPC is unreachable or disabled, and guaranteeing `/api/detect` returns HTTP 200 with `blockchain_tx_id` and warning telemetry without throwing unhandled exceptions.
## Boundaries & Constraints
**Always:**- Ensure local log file points to `static/blockchain_log.json` (or `local_log_file` path configured).- Fallback receipt identifier must follow format `local_record_<hash>` or record hash when RPC is unavailable.- Failures writing to Ethereum must emit a warning log in telemetry and never throw an unhandled exception or return HTTP 500.
**Ask First:**- Changing local log storage directory from `static/blockchain_log.json`.
**Never:**- Never crash `/api/detect` when `web3` is unavailable, Ethereum node is down, or `ETH_PRIVATE_KEY` is omitted.- Never lose cryptographic verification records when running in offline fallback mode.
## I/O & Edge-Case Matrix
| Scenario | Input / State | Expected Output / Behavior | Error Handling ||---|---|---|---|| Ethereum RPC Offline | `blockchain_logging=True`, RPC unreachable | Appends record to `static/blockchain_log.json`; returns HTTP 200 with `blockchain_tx_id="local_record_<hash>"` | Log warning to app logger || Private Key Missing | `blockchain_logging=True`, `ETH_PRIVATE_KEY=None` | Automatically falls back to local logging; returns HTTP 200 | Log warning || Concurrent Local Writes | Multiple requests in fallback mode | Appends cleanly to JSON array without data corruption | Safe append exception guard |
</frozen-after-approval>
## Code Map
- `src/verification/blockchain_store.py` -- `BlockchainLogger._local_log()`, `log_result()`, and `local_log_file` path- `src/routes/detection.py` -- Fallback receipt handling in detection response envelope- `tests/test_detection_api.py` -- Automated test verifying local fallback receipt and zero-failure resilience
## Tasks & Acceptance
**Execution:**- [x] `src/verification/blockchain_store.py` -- Ensure `local_log_file` path resolves cleanly to `static/blockchain_log.json` and returns `local_record_<hash>` when operating in fallback mode- [x] `src/routes/detection.py` -- Ensure fallback receipt is populated in `blockchain_tx_id` and logged as warning- [x] `tests/test_detection_api.py` -- Add automated test verifying offline fallback returns HTTP 200 with `local_record_...`
**Acceptance Criteria:**- Given Ethereum RPC is offline or unconfigured, when a request with `blockchain_logging=True` is made, then `/api/detect` returns HTTP 200 with `blockchain_tx_id` prefixed with `local_record_` (or valid local hash).- Given the local fallback execution, verify that the entry is appended to `static/blockchain_log.json`.- Given `pytest tests/test_detection_api.py`, all fallback tests pass cleanly.
## Design Notes
Local fallback records include `tx_hash`, `timestamp`, and the complete SHA-256 non-PII verification dictionary, enabling future batch-anchoring to Ethereum once RPC connectivity is restored.
## Verification
**Commands:**- `python3 -m pytest tests/test_detection_api.py -v -k "fallback or blockchain"` -- expected: All fallback and blockchain tests pass- `python3 -m pytest tests/ -v` -- expected: Full test suite passes without regressions
## Suggested Review Order
**Fallback Storage & Receipt Routing**
- Local log file resolution to static/blockchain_log.json and local_record_ hash prefixing [`blockchain_store.py:175`](../../src/verification/blockchain_store.py#L175)
- Receipt assignment and return in fallback branch [`blockchain_store.py:255`](../../src/verification/blockchain_store.py#L255)
**Automated Fallback Test Verification**
- Offline fallback integration test verifying unroutable RPC handling and local_record_ receipt [`test_detection_api.py:491`](../../tests/test_detection_api.py#L491)28 unmodified lines2930313233343515 unmodified lines5152535455565728 unmodified lines# - Dev moves story to 'review', then runs code-review (fresh context, different LLM recommended)# - Retrospective appends its action items to action_items; the status view surfaces open onesgenerated: 08-30-2026 22:53last_updated: 08-30-2026 23:40project: MorphGuardproject_key: NOKEYtracking_system: file-system15 unmodified linesepic-3: in-progress3-1-blind-generative-facial-demorphing-engine: review3-2-zero-knowledge-web3-ethereum-verifier-contract-ledger-loggin: review3-3-resilient-zero-loss-local-blockchain-fallback: backlogepic-3-retrospective: optionalepic-4: backlog28 unmodified lines2930313233343515 unmodified lines5152535455565728 unmodified lines# - Dev moves story to 'review', then runs code-review (fresh context, different LLM recommended)# - Retrospective appends its action items to action_items; the status view surfaces open onesgenerated: 08-30-2026 22:53last_updated: 08-30-2026 23:46project: MorphGuardproject_key: NOKEYtracking_system: file-system15 unmodified linesepic-3: in-progress3-1-blind-generative-facial-demorphing-engine: review3-2-zero-knowledge-web3-ethereum-verifier-contract-ledger-loggin: review3-3-resilient-zero-loss-local-blockchain-fallback: reviewepic-3-retrospective: optionalepic-4: backlog
171 unmodified lines17217317417517617717871 unmodified lines250251252253254255256257258259260261262263264265266267171 unmodified lines# Always provide fallback in case blockchain is not availableself.local_log_file = "blockchain_log.json"self._ensure_local_log()def _ensure_local_log(self):71 unmodified linesreceipt = self.web3.eth.wait_for_transaction_receipt(tx_raw_hash)if receipt.status == 1:print(f"Successfully logged to blockchain tx: {tx_raw_hash}")else:print(f"Blockchain transaction failed: {tx_raw_hash}")except Exception as e:print(f"Error writing to blockchain: {str(e)}")# Fall back to local loggingself._local_log(record_id, data_to_hash)else:# Fall back to local loggingself._local_log(record_id, data_to_hash)# Return record identifier (hash of metadata)return record_iddef verify_record(self, tx_id: str) -> Dict[str, Any]:"""Verify a record exists on the blockchain171 unmodified lines17217317417517617717817918071 unmodified lines252253254255256257258259260261262263264265266267268269270271272273274171 unmodified lines# Always provide fallback in case blockchain is not availablestatic_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'static')os.makedirs(static_dir, exist_ok=True)self.local_log_file = os.path.join(static_dir, "blockchain_log.json")self._ensure_local_log()def _ensure_local_log(self):71 unmodified linesreceipt = self.web3.eth.wait_for_transaction_receipt(tx_raw_hash)if receipt.status == 1:print(f"Successfully logged to blockchain tx: {tx_raw_hash}")return tx_raw_hashelse:print(f"Blockchain transaction failed: {tx_raw_hash}")fallback_id = f"local_record_{record_id}"self._local_log(fallback_id, data_to_hash)return fallback_idexcept Exception as e:print(f"Error writing to blockchain: {str(e)}")# Fall back to local loggingfallback_id = f"local_record_{record_id}"self._local_log(fallback_id, data_to_hash)return fallback_idelse:# Fall back to local loggingfallback_id = f"local_record_{record_id}"self._local_log(fallback_id, data_to_hash)return fallback_iddef verify_record(self, tx_id: str) -> Dict[str, Any]:"""Verify a record exists on the blockchain
465 unmodified lines4664674684694704714724734744754762 unmodified lines479480481482483484485486487488489490491492465 unmodified lines'blockchain_logging': 'true'}with patch('src.routes.detection.secure_filename', return_value='audit_portrait.jpg'), \patch('src.routes.detection.os.path.join', return_value='static/uploads/audit_portrait.jpg'), \patch('src.verification.blockchain_store.BlockchainLogger.log_result') as mock_log_result:mock_log_result.return_value = "0x" + "a" * 64response = client.post('/api/detect', data=data, content_type='multipart/form-data')assert response.status_code == 2002 unmodified linesassert json_data['blockchain_tx_id'] == "0x" + "a" * 64# Verify payload passed to blockchain contains only hashes and metadata, zero raw images/PIImock_log_result.assert_called_once()record = mock_log_result.call_args[0][0]assert 'image_hash' in recordassert len(record['image_hash']) == 64 # Full SHA-256assert 'raw_image' not in recordassert 'passenger_name' not in recordassert 'name' not in record465 unmodified lines4664674684694704714724734744754764772 unmodified lines480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528465 unmodified lines'blockchain_logging': 'true'}mock_logger = MagicMock()mock_logger.log_result.return_value = "0x" + "a" * 64with patch('src.routes.detection.secure_filename', return_value='audit_portrait.jpg'), \patch('src.routes.detection.os.path.join', return_value='static/uploads/audit_portrait.jpg'), \patch('src.verification.blockchain_store.BlockchainLogger', return_value=mock_logger):response = client.post('/api/detect', data=data, content_type='multipart/form-data')assert response.status_code == 2002 unmodified linesassert json_data['blockchain_tx_id'] == "0x" + "a" * 64# Verify payload passed to blockchain contains only hashes and metadata, zero raw images/PIImock_logger.log_result.assert_called_once()record = mock_logger.log_result.call_args[0][0]assert 'image_hash' in recordassert len(record['image_hash']) == 64 # Full SHA-256assert 'raw_image' not in recordassert 'passenger_name' not in recordassert 'name' not in recorddef test_resilient_local_blockchain_fallback(client, app, tmp_path):"""Test blockchain logging seamlessly falls back to local JSON when RPC is unavailable."""from src.verification.blockchain_store import BlockchainLoggerapp.mg_api.detect_morph.return_value = {'is_morphed': True,'confidence': 0.91,'processing_time': 0.04}with client.session_transaction() as sess:sess['logged_in'] = Truesess['role'] = 'admin'data = {'image': (io.BytesIO(b"offline fallback test image"), 'offline_portrait.jpg'),'mode': 'fast','blockchain_logging': 'true'}# Instantiate real BlockchainLogger without active web3 connectionlogger = BlockchainLogger(blockchain_endpoint="http://localhost:9999") # Unreachable portassert logger.connected is Falsewith patch('src.routes.detection.secure_filename', return_value='offline_portrait.jpg'), \patch('src.routes.detection.os.path.join', return_value='static/uploads/offline_portrait.jpg'), \patch('src.verification.blockchain_store.BlockchainLogger', return_value=logger):response = client.post('/api/detect', data=data, content_type='multipart/form-data')assert response.status_code == 200json_data = response.get_json()assert json_data['blockchain_logged'] is Trueassert json_data['blockchain_tx_id'].startswith('local_record_')
_bmad-output/implementation-artifacts/spec-3-3-resilient-zero-loss-local-blockchain-fallback.mdAdded+84
_bmad-output/implementation-artifacts/sprint-status.yaml+2-2
src/verification/blockchain_store.py+13-6
tests/test_detection_api.py+41-5