TTOPM commited on
Commit
9ee5bbb
·
verified ·
1 Parent(s): 8f8f38c

Upload ipfs_client.py

Browse files
src/protocol/decentralized_comm/ipfs_client.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/protocol/decentralized_comm/ipfs_client.py 🌐🗃️
2
+
3
+ import json
4
+ import ipfshttpclient
5
+ import logging
6
+
7
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
8
+
9
+ class IPFSClient:
10
+ """
11
+ Interface to IPFS for storing and retrieving JSON data.
12
+ """
13
+ def __init__(self, ipfs_address: str = "/dns/localhost/tcp/5001/http"):
14
+ self.client = ipfshttpclient.connect(ipfs_address)
15
+ logging.info(f"Connected to IPFS node at {ipfs_address}")
16
+
17
+ def add_json(self, data: dict) -> str:
18
+ try:
19
+ encoded = json.dumps(data).encode("utf-8")
20
+ result = self.client.add_bytes(encoded)
21
+ logging.info(f"Data added to IPFS: CID {result}")
22
+ return result
23
+ except Exception as e:
24
+ logging.error(f"IPFS add_json failed: {e}")
25
+ return None
26
+
27
+ def cat_json(self, cid: str) -> dict:
28
+ try:
29
+ data = self.client.cat(cid).decode("utf-8")
30
+ decoded = json.loads(data)
31
+ logging.info(f"Data retrieved from IPFS: CID {cid}")
32
+ return decoded
33
+ except Exception as e:
34
+ logging.error(f"IPFS cat_json failed for CID {cid}: {e}")
35
+ return None