-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipfs_handler.py
More file actions
350 lines (288 loc) · 12 KB
/
Copy pathipfs_handler.py
File metadata and controls
350 lines (288 loc) · 12 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
"""
Encryptum Clone - IPFS Integration Module (HTTP Gateway Method)
Bypasses version compatibility issues by using HTTP API directly
"""
import requests
import json
import tempfile
import os
from typing import Dict, Any
import logging
from datetime import datetime
class EncryptumIPFS:
"""IPFS handler using HTTP API directly"""
def __init__(self, ipfs_host='127.0.0.1', ipfs_port=5001, gateway_url='https://ipfs.io/ipfs/'):
self.host = ipfs_host
self.port = ipfs_port
self.gateway_url = gateway_url
self.base_url = f"http://{ipfs_host}:{ipfs_port}/api/v0"
self.logger = logging.getLogger(__name__)
# Test connection
try:
self.test_connection()
print("✅ Connected to IPFS node via HTTP API")
except Exception as e:
self.logger.error(f"Failed to connect to IPFS: {str(e)}")
raise Exception(f"Failed to connect to IPFS: {str(e)}")
def test_connection(self):
"""Test IPFS connection using HTTP API"""
try:
response = requests.post(f"{self.base_url}/id", timeout=10)
if response.status_code == 200:
node_info = response.json()
node_id = node_info.get('ID', 'Unknown')[:20]
self.logger.info(f"Connected to IPFS node: {node_id}...")
# Try to get version
try:
version_response = requests.post(f"{self.base_url}/version", timeout=5)
if version_response.status_code == 200:
version_info = version_response.json()
print(f" IPFS Version: {version_info.get('Version', 'Unknown')}")
except:
print(f" IPFS Version: Unable to determine")
return True
else:
raise Exception(f"HTTP {response.status_code}: {response.text}")
except requests.exceptions.RequestException as e:
raise Exception(f"Cannot connect to IPFS HTTP API: {e}")
def store_encrypted_file(self, encrypted_data: bytes, metadata: dict) -> dict:
"""
Store encrypted file on IPFS using HTTP API
Args:
encrypted_data: Encrypted file bytes
metadata: File metadata
Returns:
dict: Storage result with CIDs
"""
try:
# Store main file
files = {'file': ('encrypted_file', encrypted_data, 'application/octet-stream')}
response = requests.post(
f"{self.base_url}/add",
files=files,
params={'only-hash': 'false', 'pin': 'true'},
timeout=60
)
if response.status_code != 200:
raise Exception(f"IPFS add failed: HTTP {response.status_code}: {response.text}")
# Parse response - IPFS returns newline-separated JSON
lines = response.text.strip().split('\n')
result = json.loads(lines[-1]) # Last line contains the final result
cid = result.get('Hash')
if not cid:
raise Exception("No CID returned from IPFS")
# Enhance metadata
enhanced_metadata = {
**metadata,
'upload_timestamp': datetime.now().isoformat(),
'file_cid': cid
}
# Store metadata
metadata_json = json.dumps(enhanced_metadata, indent=2).encode()
metadata_files = {'file': ('metadata.json', metadata_json, 'application/json')}
metadata_response = requests.post(
f"{self.base_url}/add",
files=metadata_files,
params={'only-hash': 'false', 'pin': 'true'},
timeout=30
)
if metadata_response.status_code != 200:
raise Exception(f"Metadata storage failed: HTTP {metadata_response.status_code}")
metadata_lines = metadata_response.text.strip().split('\n')
metadata_result = json.loads(metadata_lines[-1])
metadata_cid = metadata_result.get('Hash')
if not metadata_cid:
raise Exception("No metadata CID returned from IPFS")
result_data = {
'file_cid': cid,
'metadata_cid': metadata_cid,
'gateway_url': f"{self.gateway_url}{cid}",
'metadata_gateway_url': f"{self.gateway_url}{metadata_cid}",
'ipfs_urls': {
'file': f"ipfs://{cid}",
'metadata': f"ipfs://{metadata_cid}"
}
}
self.logger.info(f"File stored on IPFS: {cid}")
return result_data
except Exception as e:
self.logger.error(f"IPFS storage failed: {str(e)}")
raise Exception(f"IPFS storage failed: {str(e)}")
def retrieve_file(self, cid: str) -> bytes:
"""
Retrieve file from IPFS using HTTP API
Args:
cid: Content identifier
Returns:
bytes: File data
"""
try:
self.logger.info(f"Retrieving file from IPFS: {cid}")
response = requests.post(
f"{self.base_url}/cat",
params={'arg': cid},
timeout=60
)
if response.status_code != 200:
raise Exception(f"Failed to retrieve file: HTTP {response.status_code}: {response.text}")
return response.content
except Exception as e:
self.logger.error(f"IPFS retrieval failed: {str(e)}")
raise Exception(f"IPFS retrieval failed: {str(e)}")
def retrieve_metadata(self, metadata_cid: str) -> dict:
"""
Retrieve metadata from IPFS using HTTP API
Args:
metadata_cid: Metadata content identifier
Returns:
dict: Metadata
"""
try:
self.logger.info(f"Retrieving metadata from IPFS: {metadata_cid}")
response = requests.post(
f"{self.base_url}/cat",
params={'arg': metadata_cid},
timeout=30
)
if response.status_code != 200:
raise Exception(f"Failed to retrieve metadata: HTTP {response.status_code}")
return json.loads(response.content.decode())
except Exception as e:
self.logger.error(f"Metadata retrieval failed: {str(e)}")
raise Exception(f"Metadata retrieval failed: {str(e)}")
def pin_file(self, cid: str):
"""
Pin file using HTTP API
Args:
cid: Content identifier to pin
"""
try:
response = requests.post(
f"{self.base_url}/pin/add",
params={'arg': cid},
timeout=30
)
if response.status_code == 200:
self.logger.info(f"Pinned file: {cid}")
print(f"📌 Pinned file: {cid}")
else:
self.logger.warning(f"Could not pin file {cid}: HTTP {response.status_code}")
except Exception as e:
self.logger.warning(f"Could not pin file {cid}: {str(e)}")
def unpin_file(self, cid: str):
"""
Unpin file using HTTP API
Args:
cid: Content identifier to unpin
"""
try:
response = requests.post(
f"{self.base_url}/pin/rm",
params={'arg': cid},
timeout=30
)
if response.status_code == 200:
self.logger.info(f"Unpinned file: {cid}")
else:
self.logger.warning(f"Could not unpin file {cid}: HTTP {response.status_code}")
except Exception as e:
self.logger.warning(f"Could not unpin file {cid}: {str(e)}")
def get_file_stats(self, cid: str) -> dict:
"""
Get file statistics using HTTP API
Args:
cid: Content identifier
Returns:
dict: File statistics
"""
try:
response = requests.post(
f"{self.base_url}/object/stat",
params={'arg': cid},
timeout=30
)
if response.status_code == 200:
stats = response.json()
return {
'cid': cid,
'size': stats.get('CumulativeSize', 0),
'num_links': stats.get('NumLinks', 0),
'block_size': stats.get('BlockSize', 0)
}
else:
return {'cid': cid, 'size': 0, 'num_links': 0, 'block_size': 0}
except Exception as e:
self.logger.error(f"Failed to get stats for {cid}: {str(e)}")
return {'cid': cid, 'size': 0, 'num_links': 0, 'block_size': 0}
def list_pinned_files(self) -> list:
"""
List pinned files using HTTP API
Returns:
list: List of pinned CIDs
"""
try:
response = requests.post(
f"{self.base_url}/pin/ls",
params={'type': 'recursive'},
timeout=30
)
if response.status_code == 200:
result = response.json()
if 'Keys' in result:
return list(result['Keys'].keys())
return []
except Exception as e:
self.logger.error(f"Failed to list pinned files: {str(e)}")
return []
def get_node_info(self) -> dict:
"""
Get IPFS node information using HTTP API
Returns:
dict: Node information
"""
try:
# Get node ID
id_response = requests.post(f"{self.base_url}/id", timeout=10)
node_info = {}
if id_response.status_code == 200:
node_data = id_response.json()
node_info.update({
'peer_id': node_data.get('ID', 'Unknown'),
'public_key': node_data.get('PublicKey', 'Unknown'),
'addresses': node_data.get('Addresses', []),
'agent_version': node_data.get('AgentVersion', 'Unknown'),
'protocol_version': node_data.get('ProtocolVersion', 'Unknown')
})
# Get version
try:
version_response = requests.post(f"{self.base_url}/version", timeout=10)
if version_response.status_code == 200:
version_data = version_response.json()
node_info.update({
'ipfs_version': version_data.get('Version', 'Unknown'),
'commit': version_data.get('Commit', 'Unknown')
})
except:
node_info.update({
'ipfs_version': 'Unknown',
'commit': 'Unknown'
})
return node_info
except Exception as e:
self.logger.error(f"Failed to get node info: {str(e)}")
return {
'peer_id': 'Unknown',
'ipfs_version': 'Unknown',
'error': str(e)
}
def check_connection(self) -> bool:
"""
Check if IPFS connection is healthy
Returns:
bool: True if connected
"""
try:
response = requests.post(f"{self.base_url}/id", timeout=5)
return response.status_code == 200
except:
return False