import hashlib
import json
import time
from datetime import datetime
class LicenseBlock:
def __init__(self, data_hash, source_info, license_terms, previous_hash=''):
"""
data_hash: Hash of the actual dataset file (fingerprint).
source_info: Dict containing origin (url, author, date).
license_terms: Dict containing specific permissions.
previous_hash: Hash of the preceding block in the ledger.
"""
self.timestamp = time.time()
self.data_hash = data_hash
self.source_info = source_info
self.license_terms = license_terms
self.previous_hash = previous_hash
self.nonce = 0 # For future proof-of-work expansion
self.hash = self.calculate_hash()
def calculate_hash(self):
"""Creates a SHA-256 hash of the block contents."""
block_string = json.dumps({
"timestamp": self.timestamp,
"data_hash": self.data_hash,
"source_info": self.source_info,
"license_terms": self.license_terms,
"previous_hash": self.previous_hash,
"nonce": self.nonce
}, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
def to_json(self):
return {
"hash": self.hash,
"previous_hash": self.previous_hash,
"timestamp": datetime.fromtimestamp(self.timestamp).isoformat(),
"data_fingerprint": self.data_hash,
"source": self.source_info,
"license_profile": self.license_terms
}
class DataProvenanceLedger:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
"""The first block in the chain."""
return LicenseBlock(
data_hash="0",
source_info={"origin": "Genesis Block"},
license_terms={"note": "System Initiation"},
previous_hash="0"
)
def get_latest_block(self):
return self.chain[-1]
def add_data_source(self, file_path, source_info, license_terms):
"""
Hashes the actual file and adds it to the ledger.
"""
# 1. Hash the actual file to create a fingerprint
file_hash = self.hash_file(file_path)
# 2. Create new block linked to previous
new_block = LicenseBlock(
data_hash=file_hash,
source_info=source_info,
license_terms=license_terms,
previous_hash=self.get_latest_block().hash
)
self.chain.append(new_block)
print(f"✅ Added to Ledger: {source_info.get('name', 'Unknown')} (Hash: {new_block.hash[:10]}...)")
return new_block
def hash_file(self, file_path):
"""Create a SHA-256 hash of a specific file."""
sha256 = hashlib.sha256()
try:
with open(file_path, 'rb') as f:
# Read in chunks to handle large files
for byte_block in iter(lambda: f.read(4096), b""):
sha256.update(byte_block)
return sha256.hexdigest()
except FileNotFoundError:
return "FILE_NOT_FOUND_PLACEHOLDER"
def verify_integrity(self):
"""Check if the chain has been tampered with."""
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i-1]
# 1. Check if current block's hash is valid
if current_block.hash != current_block.calculate_hash():
return False, f"Tampering detected at block {i} (Hash mismatch)"
# 2. Check if current block points to correct previous block
if current_block.previous_hash != previous_block.hash:
return False, f"Chain broken at block {i} (Link mismatch)"
return True, "Ledger Integrity Verified: Valid"
def audit_compliance(self, usage_profile):
"""
Checks if the intended usage violates any license in the ledger.
usage_profile: dict e.g. {'commercial': True, 'derivative_works': True}
"""
violations = []
for block in self.chain[1:]: # Skip genesis
terms = block.license_terms
source_name = block.source_info.get('name', 'Unknown')
# Logic: If we intend to do X, but license forbids X -> Violation
for key, intent in usage_profile.items():
# If license has the key and it is explicitly False while intent is True
if key in terms and terms[key] is False and intent is True:
violations.append({
"source": source_name,
"restriction": key,
"block_hash": block.hash
})
return violations
# ==========================================
# 3. Usage Demonstration
# ==========================================
# Initialize Ledger
ledger = DataProvenanceLedger()
# Mock Data Files (In real scenario, these are your datasets)
with open("dataset_a.csv", "w") as f: f.write("image_url,label,caption")
with open("dataset_b.txt", "w") as f: f.write("User generated content from social media")
with open("dataset_c.json", "w") as f: f.write('{"code_snippets": ["def foo(): pass"]}')
print("\n--- Adding Data Sources to Ledger ---")
# Entry 1: CC-BY-4.0 Dataset (Commercial OK, Attribution Required)
ledger.add_data_source(
file_path="dataset_a.csv",
source_info={
"name": "OpenImagesV7",
"url": "https://storage.googleapis.com/openimages",
"license_id": "CC-BY-4.0"
},
license_terms={
"commercial_use": True,
"attribution_required": True,
"derivative_works": True,
"share_alike": False
}
)
# Entry 2: Non-Commercial Research Dataset
ledger.add_data_source(
file_path="dataset_b.txt",
source_info={
"name": "AcademicSentimentAnalysis",
"author": "University Research Lab",
"license_id": "CC-NC-4.0"
},
license_terms={
"commercial_use": False, # RESTRICTION
"attribution_required": True,
"derivative_works": True
}
)
# Entry 3: Proprietary Code (Strict No-Distribution)
ledger.add_data_source(
file_path="dataset_c.json",
source_info={
"name": "InternalGitHubScrape",
"date": "2023-10-27"
},
license_terms={
"commercial_use": True,
"derivative_works": False, # RESTRICTION
"redistribution": False
}
)
print("\n--- Ledger Integrity Check ---")
is_valid, msg = ledger.verify_integrity()
print(msg)
print("\n--- Compliance Audit (Scenario: Commercial Product) ---")
# We want to train a model and sell it. Let's check if we are allowed.
intended_use = {
"commercial_use": True,
"derivative_works": True,
"redistribution": True
}
violations = ledger.audit_compliance(intended_use)
if violations:
print(f"❌ COMPLIANCE FAILED. Found {len(violations)} restriction conflicts:")
for v in violations:
print(f" - Conflict in '{v['source']}': Restriction on '{v['restriction']}'")
else:
print("✅ COMPLIANCE PASSED. All data is cleared for this usage.")
print("\n--- Ledger Export (JSON) ---")
# Show the raw chain for the first real block
print(json.dumps(ledger.chain[1].to_json(), indent=2))
# Cleanup mock files
import os
os.remove("dataset_a.csv")
os.remove("dataset_b.txt")
os.remove("dataset_c.json")