@TheOneAndOnlyTyroneBostick

import os import json import hashlib import ipfshttpclient import datetime import logging from cryptography.fernet import Fernet from flask import Flask, request, jsonify import paho.mqtt.client as mqtt import threading # Setup logging logging.basicConfig(level=logging.info/, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # Generate or load encryption key KEY_FILE = "encryption.key" if not os.path.exists(KEY_FILE): key = Fernet.generate_key() with open(KEY_FILE, "wb") as key_file: key_file.write(key) os.chmod(KEY_FILE, 0o600) else: with open(KEY_FILE, "rb") as key_file: key = key_file.read() cipher = Fernet(key) # Connect to IPFS try: ipfs_client = ipfshttpclient.connect("/ip4/127.0.0.1/tcp/5001/http%22) except Exception as e: logger.error(f"Failed to connect to IPFS: {e}") exit(1) # MQTT Configuration MQTT_BROKER = "localhost" MQTT_PORT = 1883 MQTT_TOPIC = "backup/tasks" # Flask app for REST API app = Flask(__name__) # Backup log file BACKUP_LOG = "backup_log.jsonl" def encrypt_data(data): """Encrypts data (text or binary).""" if isinstance(data, str): data = data.encode() try: return cipher.encrypt(data) except Exception as e: logger.error(f"Encryption failed: {e}") raise ValueError(f"Encryption failed: {e}") def decrypt_data(encrypted_data): """Decrypts data to binary.""" try: return cipher.decrypt(encrypted_data) except Exception as e: logger.error(f"Decryption failed: {e}") raise ValueError(f"Decryption failed: {e}") def backup_to_ipfs(file_path, source_program="manual"): """Encrypt and upload file to IPFS.""" if not os.path.exists(file_path): logger.error(f"File {file_path} does not exist") raise FileNotFoundError(f"File {file_path} does not exist") with open(file_path, "rb") as f: content = f.read() encrypted_content = encrypt_data(content) temp_encrypted_file = file_path + ".enc" try: with open(temp_encrypted_file, "wb") as ef: ef.write(encrypted_content) res = ipfs_client.add(temp_encrypted_file) finally: if os.path.exists(temp_encrypted_file): os.remove(temp_encrypted_file) # Save metadata metadata = { "filename": os.path.basename(file_path), "timestamp": datetime.datetime.now().isoformat(), "original_hash": hashlib.sha256(content).hexdigest(), "source_program": source_program } metadata_hash = ipfs_client.add_json(metadata) # Log backup backup_info = { "file_hash": res["Hash"], "metadata_hash": metadata_hash, "file_path": file_path, "timestamp": metadata["timestamp"] } with open(BACKUP_LOG, "a") as log: json.dump(backup_info, log) log.write("\n") logger.info(f"Backed up {file_path} to IPFS: {res['Hash']}") return backup_info def verify_integrity(file_path, ipfs_hash): """Checks if the local file matches the backup in IPFS.""" if not os.path.exists(file_path): logger.warning(f"File {file_path} does not exist for verification") return False local_hash = hashlib.sha256(open(file_path, "rb").read()).hexdigest() try: ipfs_file = ipfs_client.cat(ipfs_hash) decrypted_ipfs_data = decrypt_data(ipfs_file) ipfs_hash_check = hashlib.sha256(decrypted_ipfs_data).hexdigest() result = local_hash == ipfs_hash_check logger.info(f"Integrity check for {file_path}: {'Verified' if result else 'Failed'}") return result except Exception as e: logger.error(f"Verification failed: {e}") return False def restore_from_ipfs(ipfs_hash, output_file): """Restores and decrypts a file from IPFS.""" try: encrypted_data = ipfs_client.cat(ipfs_hash) decrypted_data = decrypt_data(encrypted_data) with open(output_file, "wb") as f: f.write(decrypted_data) logger.info(f"File restored: {output_file}") return True except Exception as e: logger.error(f"Restore failed: {e}") return False # REST API Endpoints @app.route("/backup", methods=["POST"]) def api_backup(): """API to trigger a backup.""" data = request.json file_path = data.get("file_path") source_program = data.get("source_program", "api") if not file_path: return jsonify({"error": "file_path is required"}), 400 try: backup_info = backup_to_ipfs(file_path, source_program) return jsonify(backup_info), 200 except Exception as e: logger.error(f"API backup failed: {e}") return jsonify({"error": str(e)}), 500 @app.route("/verify", methods=["POST"]) def api_verify(): """API to verify file integrity.""" data = request.json file_path = data.get("file_path") ipfs_hash = data.get("ipfs_hash") if not file_path or not ipfs_hash: return jsonify({"error": "file_path and ipfs_hash are required"}), 400 result = verify_integrity(file_path, ipfs_hash) return jsonify({"verified": result}), 200 @app.route("/restore", methods=["POST"]) def api_restore(): """API to restore a file.""" data = request.json ipfs_hash = data.get("ipfs_hash") output_file = data.get("output_file") if not ipfs_hash or not output_file: return jsonify({"error": "ipfs_hash and output_file are required"}), 400 success = restore_from_ipfs(ipfs_hash, output_file) return jsonify({"success": success}), 200 # MQTT Setup def on_connect(client, userdata, flags, rc): """Callback for when MQTT client connects.""" if rc == 0: logger.info("Connected to MQTT broker") client.subscribe(MQTT_TOPIC) else: logger.error(f"Failed to connect to MQTT: {rc}") def on_message(client, userdata, msg): """Callback for MQTT messages.""" try: payload = json.loads(msg.payload.decode()) action = payload.get("action") source_program = payload.get("source_program", "mqtt") if action == "backup": file_path = payload.get("file_path") if file_path: backup_info = backup_to_ipfs(file_path, source_program) client.publish(f"{MQTT_TOPIC}/response", json.dumps({ "status": "success", "backup_info": backup_info })) elif action == "verify": file_path = payload.get("file_path") ipfs_hash = payload.get("ipfs_hash") if file_path and ipfs_hash: result = verify_integrity(file_path, ipfs_hash) client.publish(f"{MQTT_TOPIC}/response", json.dumps({ "status": "success", "verified": result })) elif action == "restore": ipfs_hash = payload.get("ipfs_hash") output_file = payload.get("output_file") if ipfs_hash and output_file: success = restore_from_ipfs(ipfs_hash, output_file) client.publish(f"{MQTT_TOPIC}/response", json.dumps({ "status": "success", "success": success })) except Exception as e: logger.error(f"MQTT message processing failed: {e}") client.publish(f"{MQTT_TOPIC}/response", json.dumps({ "status": "error", "error": str(e) })) mqtt_client = mqtt.Client() mqtt_client.on_connect = on_connect mqtt_client.on_message = on_message # Optional GibberLink Integration (Placeholder) # Note: Requires ggwave library and additional setup def gibberlink_communicate(task_data): """Placeholder for GibberLink communication.""" # Example: Encode task_data to sound using ggwave # This requires ggwave installation and setup logger.warning("GibberLink integration not fully implemented. Use API/MQTT instead.") # Pseudo-code: # import ggwave # waveform = ggwave.encode(json.dumps(task_data)) # play_waveform(waveform) # Send to another AI agent # received = listen_waveform() # Receive response # response = ggwave.decode(received) return {"status": "not_implemented"} # Start MQTT client in a separate thread def start_mqtt(): try: mqtt_client.connect(MQTT_BROKER, MQTT_PORT, 60) mqtt_client.loop_start() except Exception as e: logger.error(f"MQTT connection failed: {e}") # Start Flask app in a separate thread def start_flask(): app.run(host="0.0.0.0/", port=5000, debug=False) if _name_ == "__main__": # Start MQTT and Flask in separate threads mqtt_thread = threading.Thread(target=start_mqtt) flask_thread = threading.Thread(target=start_flask) mqtt_thread.start() flask_thread.start() # Example usage try: file_to_backup = "important_data.txt" backup_info = backup_to_ipfs(file_to_backup) print(f"File backed up: {backup_info['file_hash']}") if verify_integrity(file_to_backup, backup_info["file_hash"]): print("Backup integrity verified.") else: print("WARNING: Backup integrity compromised!") restore_from_ipfs(backup_info["file_hash"], "restored_data.txt") except Exception as e: logger.error(f"Main execution failed: {e}")

8 months ago | 1