Repository navigation
Expand file tree
/
Copy pathclient.py
More file actions
78 lines (72 loc) · 2.77 KB
/
Copy pathclient.py
File metadata and controls
78 lines (72 loc) · 2.77 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
import requests
import os
import uuid
import base64
import argparse
import json
from hashlib import sha256
NODE_URL = "http://127.0.0.1:5000"
def chunk_file(file_path, chunk_size=512*1024):
file_id = str(uuid.uuid4())
chunks = []
with open(file_path, "rb") as f:
index = 0
while chunk := f.read(chunk_size):
data_b64 = base64.b64encode(chunk).decode()
checksum = sha256(chunk).hexdigest()
tx = {
"type": "file_chunk",
"file_id": file_id,
"chunk_index": index,
"total_chunks": -1, # sera mis à jour après
"data": data_b64,
"checksum": checksum,
"filename": os.path.basename(file_path)
}
chunks.append(tx)
index += 1
# Mise à jour total_chunks
for tx in chunks:
tx["total_chunks"] = len(chunks)
return file_id, chunks
def upload_file(file_path):
print(f"📤 Upload de {file_path}...")
file_id, chunks = chunk_file(file_path)
for tx in chunks:
requests.post(f"{NODE_URL}/add_transaction", json=tx)
print(f" Chunk {tx['chunk_index']+1}/{tx['total_chunks']} envoyé")
# Miner
requests.get(f"{NODE_URL}/mine")
print(f"✅ Fichier stocké ! File ID : {file_id}")
def download_file(file_id, output_path=None):
print(f"📥 Téléchargement du fichier {file_id}...")
resp = requests.get(f"{NODE_URL}/chain").json()
chunks = []
for block in resp["chain"]:
for tx in block["transactions"]:
if tx.get("type") == "file_chunk" and tx.get("file_id") == file_id:
chunks.append(tx)
if not chunks:
print("❌ Fichier non trouvé")
return
chunks.sort(key=lambda x: x["chunk_index"])
data = b""
for tx in chunks:
data += base64.b64decode(tx["data"])
output = output_path or f"downloaded_{tx['filename']}"
with open(output, "wb") as f:
f.write(data)
print(f"✅ Fichier reconstruit → {output} ({len(data)/1024:.1f} Ko)")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="FileVaultChain Client")
parser.add_argument("action", choices=["upload", "download", "status"])
parser.add_argument("--file", help="Chemin du fichier à uploader")
parser.add_argument("--id", help="File ID à télécharger")
parser.add_argument("--output", help="Chemin de sortie")
args = parser.parse_args()
if args.action == "status":
print(requests.get(f"{NODE_URL}/status").json())
elif args.action == "upload" and args.file:
upload_file(args.file)
elif args.action == "download" and args.id:
download_file(args.id, args.output)