-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathblockchain_supply_chain.py
More file actions
868 lines (759 loc) · 32.9 KB
/
Copy pathblockchain_supply_chain.py
File metadata and controls
868 lines (759 loc) · 32.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
"""
Blockchain-Based Agricultural Supply Chain Traceability System
with transaction atomicity and rollback support.
"""
import hashlib
import hmac
import json
import os
import time
import uuid
from collections import OrderedDict
from datetime import datetime, timezone
from typing import Dict, List, Optional
from dataclasses import dataclass, asdict, field
import qrcode
import io
import copy as _copy
import base64
import secrets
@dataclass
class BlockchainRecord:
"""Record stored in blockchain"""
timestamp: str
actor: str
action: str
location: str
data: Dict
hash: str = ""
# previous_hash links this block to the one before it.
# The genesis block uses the sentinel value below.
previous_hash: str = ""
# Well-known sentinel stored in the genesis block's previous_hash
# so validators can distinguish it from a legitimately missing link.
GENESIS_PREVIOUS_HASH: str = "0" * 64
def to_dict(self) -> Dict:
"""Serialize record to dict (hash excluded — matches calculate_hash input)"""
return {
"timestamp": self.timestamp,
"actor": self.actor,
"action": self.action,
"location": self.location,
"data": self.data,
"previous_hash": self.previous_hash,
}
def calculate_hash(self) -> str:
"""Calculate SHA256 hash of record (excludes hash field, includes previous_hash)"""
record_string = json.dumps(self.to_dict(), sort_keys=True)
return hashlib.sha256(record_string.encode()).hexdigest()
@staticmethod
def from_dict(data: Dict) -> 'BlockchainRecord':
"""Reconstruct record from dict, then compute and verify hash"""
record = BlockchainRecord(
timestamp=data["timestamp"],
actor=data["actor"],
action=data["action"],
location=data["location"],
data=data.get("data", {}),
previous_hash=data.get("previous_hash", BlockchainRecord.GENESIS_PREVIOUS_HASH),
)
if "hash" in data:
record.hash = data["hash"]
return record
@dataclass
class ProductBatch:
"""Agricultural product batch"""
batch_id: str
crop_type: str
farm_id: str
quantity: float
unit: str # kg, tons, etc
planting_date: str
harvesting_date: str
farmer_name: str
certifications: List[str] = field(default_factory=list)
quality_score: float = 0.0
created_at: str = ""
blockchain_records: List[Dict] = field(default_factory=list)
def __post_init__(self):
if not self.created_at:
self.created_at = datetime.now().isoformat()
@dataclass
class SupplyChainNode:
"""Supply chain transaction node"""
node_id: str
batch_id: str
node_type: str # farm, warehouse, distributor, retailer, consumer
actor_name: str
location: str
timestamp: str
action: str # harvested, stored, transported, verified, sold
temperature: Optional[float] = None
humidity: Optional[float] = None
quality_check: Optional[str] = None
notes: str = ""
class SupplyChainBlockchain:
"""Blockchain for agricultural supply chain with basic atomicity"""
def __init__(self, repository=None, signing_key: Optional[str] = None):
self.chain: List[BlockchainRecord] = []
self.products: Dict[str, ProductBatch] = {}
self.supply_chain_nodes: Dict[str, List[SupplyChainNode]] = {}
self.smart_contracts: Dict[str, SmartContract] = {}
self.verified_actors: Dict[str, Dict] = {}
self.idempotency_cache: Dict[str, object] = {}
self._trace_batches: Dict[str, Dict] = {}
self._processed_transaction_ids: OrderedDict[str, None] = OrderedDict()
self._harvest_ids: set[str] = set()
self._repository = repository
# Hydrate in-memory product store from persistent storage on startup
# so that batch operations remain available after a server restart.
if self._repository is not None:
try:
persisted = self._repository.load_all_batches()
for batch_id, batch_data in (persisted or {}).items():
if isinstance(batch_data, ProductBatch):
self.products[batch_id] = batch_data
self.supply_chain_nodes.setdefault(batch_id, [])
elif isinstance(batch_data, dict):
self.products[batch_id] = ProductBatch(**batch_data)
self.supply_chain_nodes.setdefault(batch_id, [])
except Exception:
# Repository unavailable at startup — proceed with empty state;
# individual operations will fail-fast if persistence is required.
pass
# ------------- Utilities for atomicity -------------
def _snapshot_state(self):
"""Create snapshot of current state for rollback"""
return {
"chain_len": len(self.chain),
"products_copy": _copy.deepcopy(self.products),
"supply_chain_nodes_copy": {k: list(v) for k, v in self.supply_chain_nodes.items()},
"smart_contracts_copy": _copy.deepcopy(self.smart_contracts),
"trace_batches_copy": _copy.deepcopy(self._trace_batches),
"verified_actors_copy": _copy.deepcopy(self.verified_actors),
}
def _rollback_to_snapshot(self, snap):
"""Rollback state to snapshot point"""
self.chain = self.chain[: snap["chain_len"]]
self.products = _copy.deepcopy(snap["products_copy"])
self.supply_chain_nodes = {k: list(v) for k, v in snap["supply_chain_nodes_copy"].items()}
self.smart_contracts = _copy.deepcopy(snap["smart_contracts_copy"])
self._trace_batches = _copy.deepcopy(snap["trace_batches_copy"])
self.verified_actors = _copy.deepcopy(snap["verified_actors_copy"])
# ------------- Core operations -------------
def register_actor(self, actor_id: str, name: str, actor_type: str, location: str) -> Dict:
"""Register supply chain participant atomically"""
snap = self._snapshot_state()
try:
actor_data = {
"actor_id": actor_id,
"name": name,
"type": actor_type,
"location": location,
"registered_at": datetime.now().isoformat(),
"verified": True,
"transactions": 0,
"rating": 5.0,
}
self.verified_actors[actor_id] = actor_data
if self._repository is not None:
self._repository.save_actor(actor_id, actor_data)
return actor_data
except Exception:
self._rollback_to_snapshot(snap)
raise
def create_product_batch(
self,
crop_type: str,
farm_id: str,
quantity: float,
unit: str,
planting_date: str,
harvesting_date: str,
farmer_name: str,
owner_uid: str = "",
harvest_id: str = "",
idempotency_key: Optional[str] = None,
owner_uid: str = "",
harvest_id: str = "",
) -> ProductBatch:
"""Create product batch atomically with harvest_id dedup."""
# Check cache
if idempotency_key and idempotency_key in self.idempotency_cache:
return self.idempotency_cache[idempotency_key]
snap = self._snapshot_state()
try:
batch_id = f"BATCH-{uuid.uuid4().hex[:12].upper()}"
batch = ProductBatch(...)
record = BlockchainRecord(...)
record.hash = record.calculate_hash()
owner_uid: str = "",
harvest_id: str = "",
) -> ProductBatch:
"""Create new product batch atomically with harvest_id deduplication."""
snap = self._snapshot_state()
try:
batch_id = f"BATCH-{uuid.uuid4().hex[:12].upper()}"
if harvest_id:
self._record_harvest_id(harvest_id)
transaction_payload = {
"crop_type": crop_type,
"farm_id": farm_id,
"quantity": quantity,
"planting_date": planting_date,
"harvesting_date": harvesting_date,
"harvest_id": harvest_id or "",
}
transaction_id = self._generate_transaction_id(transaction_payload)
self._validate_transaction_uniqueness(transaction_id)
batch = ProductBatch(
batch_id=batch_id,
crop_type=crop_type,
farm_id=farm_id,
quantity=quantity,
unit=unit,
planting_date=planting_date,
harvesting_date=harvesting_date,
farmer_name=farmer_name,
owner_uid=owner_uid,
)
record = self._link_record(BlockchainRecord(
timestamp=datetime.now(timezone.utc).isoformat(),
actor=farmer_name,
action="created_batch",
location=farm_id,
data=asdict(batch),
previous_hash=self.chain[-1].hash if self.chain else BlockchainRecord.GENESIS_PREVIOUS_HASH,
)
record.hash = record.calculate_hash()
)
record.previous_hash = record.calculate_hash()
# Commit
self.products[batch_id] = batch
self.supply_chain_nodes[batch_id] = []
self.chain.append(record)
batch.blockchain_records.append(record.serialize())
if idempotency_key:
self.idempotency_cache[idempotency_key] = batch
self._record_transaction_id(transaction_id)
# Persist immediately so the batch survives a server restart.
if self._repository is not None:
self._repository.save_batch(batch_id, asdict(batch))
return batch
owner_uid: str = "",
harvest_id: str = "",
idempotency_key: Optional[str] = None,
except Exception as e:
import logging
logging.error(f"Blockchain error: {e}")
self._rollback_to_snapshot(snap)
raise
def add_supply_chain_node(
self,
batch_id: str,
node_type: str,
actor_name: str,
location: str,
action: str,
harvest_id: str = "",
**kwargs,
) -> SupplyChainNode:
"""Add node to supply chain atomically with harvest_id dedup."""
if batch_id not in self.products:
raise ValueError(f"Batch {batch_id} not found")
snap = self._snapshot_state()
try:
if harvest_id:
self._record_harvest_id(harvest_id)
transaction_payload = {
"batch_id": batch_id,
"actor_name": actor_name,
"location": location,
"action": action,
"timestamp": datetime.now(timezone.utc).isoformat(),
"harvest_id": harvest_id or "",
**kwargs,
}
transaction_id = self._generate_transaction_id(transaction_payload)
self._validate_transaction_uniqueness(transaction_id)
node_id = f"NODE-{uuid.uuid4().hex[:12].upper()}"
node = SupplyChainNode(
node_id=node_id,
batch_id=batch_id,
node_type=node_type,
actor_name=actor_name,
location=location,
timestamp=datetime.now(timezone.utc).isoformat(),
action=action,
temperature=kwargs.get("temperature"),
humidity=kwargs.get("humidity"),
quality_check=kwargs.get("quality_check"),
notes=kwargs.get("notes", ""),
)
record = self._link_record(BlockchainRecord(
timestamp=datetime.now(timezone.utc).isoformat(),
actor=actor_name,
action=action,
location=location,
data=asdict(node),
previous_hash=self.chain[-1].hash if self.chain else BlockchainRecord.GENESIS_PREVIOUS_HASH,
)
record.hash = record.calculate_hash()
)
record.previous_hash = record.calculate_hash()
# Commit
self.supply_chain_nodes.setdefault(batch_id, []).append(node)
self.chain.append(record)
self.products[batch_id].blockchain_records.append(record.serialize())
if self._repository is not None:
self._repository.create(asdict(node))
return node
except Exception:
self._rollback_to_snapshot(snap)
raise
def create_smart_contract(
self,
batch_id: str,
seller: str,
buyer: str,
price: float,
terms: Optional[Dict] = None,
created_by_uid: str = "",
harvest_id: str = "",
) -> SmartContract:
"""Create smart contract for transaction atomically with harvest_id dedup."""
if batch_id not in self.products:
raise ValueError(f"Batch {batch_id} not found")
snap = self._snapshot_state()
try:
if harvest_id:
self._record_harvest_id(harvest_id)
contract_id = f"CONTRACT-{uuid.uuid4().hex[:12].upper()}"
transaction_payload = {
"batch_id": batch_id,
"seller": seller,
"buyer": buyer,
"price": price,
"harvest_id": harvest_id or "",
}
transaction_id = self._generate_transaction_id(transaction_payload)
self._validate_transaction_uniqueness(transaction_id)
contract = SmartContract(
contract_id=contract_id,
batch_id=batch_id,
seller=seller,
buyer=buyer,
price=price,
created_by_uid=created_by_uid,
terms=terms or {},
)
record = self._link_record(BlockchainRecord(
timestamp=datetime.now(timezone.utc).isoformat(),
actor=seller,
action="contract_created",
location="contract",
data=asdict(contract),
previous_hash=self.chain[-1].hash if self.chain else BlockchainRecord.GENESIS_PREVIOUS_HASH,
)
record.hash = record.calculate_hash()
)
record.previous_hash = record.calculate_hash()
# Commit
self.smart_contracts[contract_id] = contract
self._link_and_append(record)
return contract
except Exception:
self._rollback_to_snapshot(snap)
raise
def execute_smart_contract(self, contract_id: str) -> Dict:
"""Execute smart contract atomically with rollback on failure"""
if contract_id not in self.smart_contracts:
raise ValueError(f"Contract {contract_id} not found")
snap = self._snapshot_state()
contract = self.smart_contracts[contract_id]
try:
if contract.status != "pending":
raise ValueError(f"Contract {contract_id} cannot be executed (status: {contract.status})")
# Prepare execution record first (may raise)
record = BlockchainRecord(
timestamp=datetime.now().isoformat(),
actor=contract.buyer,
action="contract_executed",
location="contract",
data={
"contract_id": contract_id,
"batch_id": contract.batch_id,
"amount": contract.price,
"currency": contract.currency,
},
previous_hash=self.chain[-1].hash if self.chain else BlockchainRecord.GENESIS_PREVIOUS_HASH,
)
record.hash = record.calculate_hash()
# Commit state updates atomically
contract.status = "executed"
contract.executed_at = datetime.now().isoformat()
self.chain.append(record)
return {
"success": True,
"contract_id": contract_id,
"executed_at": contract.executed_at,
"amount": contract.price,
}
except Exception:
self._rollback_to_snapshot(snapshot)
raise
def generate_qr_code(self, batch_id: str) -> str:
"""Generate QR code for product batch"""
if batch_id not in self.products:
raise ValueError(f"Batch {batch_id} not found")
batch = self.products[batch_id]
proof = self._build_trace_proof(batch_id)
qr_data = {
"batch_id": batch_id,
"crop_type": batch.crop_type,
"quantity": batch.quantity,
"unit": batch.unit,
"farmer": batch.farmer_name,
"harvested": batch.harvesting_date,
"verification_url": f"https://fasalsaathi.agri/verify/{token_id}",
"trace_proof": proof["proof_hash"],
"block_hash": proof["latest_block_hash"],
}
if proof["signature"]:
qr_data["trace_signature"] = proof["signature"]
if self._signing_key:
payload = json.dumps(qr_data, sort_keys=True)
sig = hmac.new(self._signing_key.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
qr_data["sig"] = sig
qr_data["proof"] = "signed"
qr_data["verification_url"] = f"https://fasalsaathi.agri/verify/{batch_id}?proof={sig}"
else:
qr_data["verification_url"] = f"https://fasalsaathi.agri/verify/{batch_id}"
qr_code = qrcode.QRCode(version=1, box_size=10, border=5)
qr_code.add_data(self._canonical_json(qr_data))
qr_code.make(fit=True)
qr_image = qr_code.make_image(fill_color="black", back_color="white")
qr_buffer = io.BytesIO()
qr_image.save(qr_buffer, format="PNG")
qr_base64 = base64.b64encode(qr_buffer.getvalue()).decode()
return qr_base64
def get_traceability_qr_payload(self, batch_id: str) -> Dict:
"""Return a signed payload suitable for QR encoding or API clients."""
if batch_id not in self.products:
raise ValueError(f"Batch {batch_id} not found")
batch = self.products[batch_id]
proof = self._build_trace_proof(batch_id)
payload = {
"batch_id": batch_id,
"crop_type": batch.crop_type,
"farmer": batch.farmer_name,
"verification_url": f"https://fasalsaathi.agri/verify/{token_id}",
"trace_proof": proof["proof_hash"],
"block_hash": proof["latest_block_hash"],
"issued_at": datetime.now(timezone.utc).isoformat(),
}
if proof["signature"]:
payload["trace_signature"] = proof["signature"]
payload["verification_url_with_proof"] = (
f"https://fasalsaathi.agri/verify/{batch_id}"
f"?proof={proof['proof_hash']}&sig={proof['signature']}"
)
else:
payload["verification_url_with_proof"] = payload["verification_url"] + f"?proof={proof['proof_hash']}"
return payload
def verify_batch(self, batch_id: str) -> Dict:
def verify_batch(self, batch_id: str, proof: Optional[str] = None) -> Dict:
"""Verify product batch authenticity"""
if batch_id not in self.products:
return {"success": False, "message": "Batch not found"}
batch = self.products[batch_id]
records = self.supply_chain_nodes.get(batch_id, [])
verification_score = 0.0
if len(records) >= 1:
verification_score += 40
quality_verifications = [r for r in records if r.quality_check == "passed"]
if quality_verifications:
verification_score += 15
registered_count = 0
for record in records:
if record.actor_name in self.verified_actors:
registered_count += 1
if registered_count > 0:
verification_score += 15
blockchain_intact = self._verify_blockchain_integrity()
trace_proof = self._build_trace_proof(batch_id)
if blockchain_intact:
verification_score = min(100, verification_score + 10)
if not self._signing_key:
authenticated = "unauthenticated"
elif proof:
expected = hmac.new(self._signing_key.encode("utf-8"), batch_id.encode("utf-8"), hashlib.sha256).hexdigest()
authenticated = hmac.compare_digest(expected, proof)
else:
authenticated = verification_score >= 70
return {
"success": True,
"batch_id": batch_id,
"product": batch.crop_type,
"quantity": batch.quantity,
"farmer": batch.farmer_name,
"verification_score": min(100, verification_score),
"authenticated": authenticated,
"blockchain_records": len(batch.blockchain_records),
"supply_chain_nodes": len(records),
"certifications": batch.certifications,
"quality_score": batch.quality_score,
"harvested_date": batch.harvesting_date,
"integrity_ok": blockchain_intact,
"trace_proof": trace_proof["proof_hash"],
"trace_signature": trace_proof["signature"],
"latest_block_hash": trace_proof["latest_block_hash"],
}
def get_supply_chain_journey(self, batch_id: str) -> Dict:
"""Get complete supply chain journey"""
if batch_id not in self.products:
raise ValueError(f"Batch {batch_id} not found")
batch = self.products[batch_id]
nodes = self.supply_chain_nodes.get(batch_id, [])
journey = {
"batch_id": batch_id,
"product": batch.crop_type,
"quantity": batch.quantity,
"farmer": batch.farmer_name,
"created_at": batch.created_at,
"nodes": [],
}
for node in nodes:
journey["nodes"].append({
"timestamp": node.timestamp,
"actor": node.actor_name,
"type": node.node_type,
"location": node.location,
"action": node.action,
"temperature": node.temperature,
"humidity": node.humidity,
"quality_check": node.quality_check,
"notes": node.notes,
})
return journey
def get_supply_chain_analytics(self, batch_id: str) -> Dict:
"""Get analytics for supply chain"""
if batch_id not in self.products:
raise ValueError(f"Batch {batch_id} not found")
batch = self.products[batch_id]
nodes = self.supply_chain_nodes.get(batch_id, [])
contracts = [c for c in self.smart_contracts.values() if c.batch_id == batch_id]
total_journey_time = 0
if len(nodes) >= 2:
start_time = datetime.fromisoformat(nodes[0].timestamp)
end_time = datetime.fromisoformat(nodes[-1].timestamp)
total_journey_time = (end_time - start_time).total_seconds() / 3600
avg_temperature = None
temps = [n.temperature for n in nodes if n.temperature is not None]
if temps:
avg_temperature = sum(temps) / len(temps)
node_types = {}
for node in nodes:
node_types[node.node_type] = node_types.get(node.node_type, 0) + 1
return {
"batch_id": batch_id,
"product": batch.crop_type,
"total_journey_hours": round(total_journey_time, 2),
"supply_chain_steps": len(nodes),
"node_types_distribution": node_types,
"average_temperature": round(avg_temperature, 2) if avg_temperature else None,
"quality_verifications": len([n for n in nodes if n.quality_check]),
"transactions": len(contracts),
"final_price": contracts[-1].price if contracts else None,
}
# Required top-level keys that every transaction payload must contain
# for structural validity. The chain is considered compromised if any
# block is missing these fields, which catches forged/truncated payloads.
_REQUIRED_PAYLOAD_KEYS: tuple = () # relax at class level; per-action checks below
def _verify_blockchain_integrity(self) -> bool:
"""Return True only when the full chain passes integrity validation.
Delegates to validate_chain_integrity() and returns the boolean
summary so existing callers (verify_batch) continue to work.
"""
report = self.validate_chain_integrity()
return report["valid"]
def validate_chain_integrity(self) -> Dict:
"""Full chain integrity validation with structured error reporting.
Checks performed for every block (index i):
1. Self-hash: block.hash == block.calculate_hash() (detects payload tampering)
2. Chain link: block.previous_hash == chain[i-1].hash (detects relationship manipulation)
Genesis block must carry GENESIS_PREVIOUS_HASH sentinel.
3. Timestamp ordering: block.timestamp >= chain[i-1].timestamp
(detects back-dated block insertion)
4. Payload structure: block.actor and block.action are non-empty strings
(detects forged/truncated payloads)
Returns a dict with:
valid bool — True iff all checks pass
chain_length int
errors list — human-readable descriptions of each failure
"""
import logging as _log
_logger = _log.getLogger(__name__)
errors: List[str] = []
chain = self.chain
for i, block in enumerate(chain):
# --- Check 1: self-hash integrity ---
expected_hash = block.calculate_hash()
if block.hash != expected_hash:
msg = (
f"Block {i} hash mismatch: stored={block.hash[:12]}… "
f"expected={expected_hash[:12]}… — payload may have been tampered with."
)
errors.append(msg)
_logger.error(msg)
# --- Check 2: chain linkage ---
if i == 0:
# Genesis block must reference the sentinel, not a real block.
if block.previous_hash != BlockchainRecord.GENESIS_PREVIOUS_HASH:
msg = (
f"Genesis block (index 0) has unexpected previous_hash "
f"'{block.previous_hash[:12]}…' — chain may have been prepended."
)
errors.append(msg)
_logger.error(msg)
else:
prev_block = chain[i - 1]
if block.previous_hash != prev_block.hash:
msg = (
f"Block {i} broken chain link: previous_hash={block.previous_hash[:12]}… "
f"but block {i - 1} hash={prev_block.hash[:12]}… — "
f"block relationship may have been manipulated."
)
errors.append(msg)
_logger.error(msg)
# --- Check 3: timestamp ordering ---
if i > 0:
try:
prev_ts = datetime.fromisoformat(chain[i - 1].timestamp)
curr_ts = datetime.fromisoformat(block.timestamp)
if curr_ts < prev_ts:
msg = (
f"Block {i} timestamp ({block.timestamp}) is earlier than "
f"block {i - 1} timestamp ({chain[i - 1].timestamp}) — "
f"possible back-dated block insertion."
)
errors.append(msg)
_logger.error(msg)
except ValueError:
msg = f"Block {i} contains an unparseable timestamp '{block.timestamp}'."
errors.append(msg)
_logger.error(msg)
# --- Check 4: payload structural integrity ---
if not isinstance(block.actor, str) or not block.actor.strip():
msg = f"Block {i} has an empty or invalid actor field."
errors.append(msg)
_logger.error(msg)
if not isinstance(block.action, str) or not block.action.strip():
msg = f"Block {i} has an empty or invalid action field."
errors.append(msg)
_logger.error(msg)
is_valid = len(errors) == 0
if is_valid:
_logger.debug("Blockchain integrity check passed (%d blocks).", len(chain))
else:
_logger.warning(
"Blockchain integrity check FAILED: %d error(s) in %d block(s).",
len(errors), len(chain),
)
return {
"valid": is_valid,
"chain_length": len(chain),
"errors": errors,
}
def get_blockchain_record_count(self) -> int:
"""Get total records in blockchain"""
return len(self.chain)
def get_blockchain_stats(self) -> dict:
"""Return dedup stats for /health/blockchain."""
return {
"total_blocks": len(self.chain),
"unique_harvest_ids": len(self._harvest_ids),
"duplicate_prevented": len(self._processed_transaction_ids) - len(self._harvest_ids),
"integrity_ok": self._verify_blockchain_integrity(),
}
def get_certified_products(self) -> List[Dict]:
"""Get all certified products ready for marketplace"""
certified = []
for batch_id, batch in self.products.items():
verification = self.verify_batch(batch_id)
if verification.get("authenticated"):
certified.append({
"batch_id": batch_id,
"product": batch.crop_type,
"quantity": batch.quantity,
"farmer": batch.farmer_name,
"verification_score": verification.get("verification_score"),
"certifications": batch.certifications,
"quality_score": batch.quality_score,
})
return certified
def _snapshot_state(self) -> Dict:
"""Snapshot mutable state for rollback."""
return {
"_trace_batches": dict(self._trace_batches),
"chain": list(self.chain),
}
def _rollback(self, snapshot: Dict) -> None:
"""Restore state from a snapshot."""
self._trace_batches.clear()
self._trace_batches.update(snapshot["_trace_batches"])
self.chain = snapshot["chain"]
# ------------- QR Traceability (farmer-facing) -------------
def register_trace_batch(self, payload: Dict) -> Dict:
"""Store a QR-traceability batch submitted from the frontend."""
batch_id = payload.get("id")
if not batch_id:
raise ValueError("Batch ID is required")
if batch_id in self._trace_batches:
raise ValueError(f"Batch {batch_id} is already registered")
entry = {
"id": batch_id,
"crop": payload.get("crop", ""),
"variety": payload.get("variety", ""),
"harvestDate": payload.get("harvestDate", ""),
"farm": payload.get("farm", ""),
"status": payload.get("status", "Pending Verification"),
"registeredByUid": payload.get("registeredByUid", ""),
"registeredAt": datetime.utcnow().isoformat() + "Z",
"journey": payload.get("journey", []),
}
self._trace_batches[batch_id] = entry
# Also record the registration on the blockchain for auditability.
record = BlockchainRecord(
timestamp=entry["registeredAt"],
actor=entry["registeredByUid"] or "unknown",
action="trace_batch_registered",
location=entry["farm"],
data={"batch_id": batch_id, "crop": entry["crop"]},
previous_hash=self.chain[-1].hash if self.chain else BlockchainRecord.GENESIS_PREVIOUS_HASH,
)
record.hash = record.calculate_hash()
self.chain.append(record)
# Also record the registration on the blockchain for auditability.
record = BlockchainRecord(
timestamp=entry["registeredAt"],
actor=entry["registeredByUid"] or "unknown",
action="trace_batch_registered",
location=entry["farm"],
data={"batch_id": batch_id, "crop": entry["crop"]},
)
record.hash = record.calculate_hash()
self.chain.append(record)
return entry
except Exception:
self._rollback_to_snapshot(snap)
raise
def get_trace_batch(self, batch_id: str) -> Optional[Dict]:
"""Fetch a QR-traceability batch by ID. Returns None if not found."""
batch = self._trace_batches.get(batch_id)
if not batch:
return None
batch_copy = _copy.deepcopy(batch)
if batch_id in self.products:
batch_copy["traceability"] = self.get_traceability_qr_payload(batch_id)
return batch_copy