py-ipfs-lite 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- py_ipfs_lite/__init__.py +23 -0
- py_ipfs_lite/api.py +402 -0
- py_ipfs_lite/car.py +188 -0
- py_ipfs_lite/cli.py +293 -0
- py_ipfs_lite/config.py +29 -0
- py_ipfs_lite/dag_utils.py +90 -0
- py_ipfs_lite/exceptions.py +28 -0
- py_ipfs_lite/interfaces.py +146 -0
- py_ipfs_lite/ipns.py +175 -0
- py_ipfs_lite/main.py +11 -0
- py_ipfs_lite/metrics.py +82 -0
- py_ipfs_lite/parser.py +135 -0
- py_ipfs_lite/peer.py +721 -0
- py_ipfs_lite/pin.py +80 -0
- py_ipfs_lite/py.typed +0 -0
- py_ipfs_lite/reprovider.py +64 -0
- py_ipfs_lite/routing.py +193 -0
- py_ipfs_lite/versioning.py +39 -0
- py_ipfs_lite-0.1.0.dist-info/METADATA +141 -0
- py_ipfs_lite-0.1.0.dist-info/RECORD +23 -0
- py_ipfs_lite-0.1.0.dist-info/WHEEL +5 -0
- py_ipfs_lite-0.1.0.dist-info/entry_points.txt +2 -0
- py_ipfs_lite-0.1.0.dist-info/top_level.txt +1 -0
py_ipfs_lite/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from py_ipfs_lite.config import AddParams, Config
|
|
2
|
+
from py_ipfs_lite.interfaces import BlockStore, DagService, Exchange, Host, Routing
|
|
3
|
+
from py_ipfs_lite.peer import (
|
|
4
|
+
Peer,
|
|
5
|
+
default_bootstrap_peers,
|
|
6
|
+
new_in_memory_datastore,
|
|
7
|
+
setup_libp2p,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Peer",
|
|
12
|
+
"Config",
|
|
13
|
+
"AddParams",
|
|
14
|
+
"Host",
|
|
15
|
+
"Routing",
|
|
16
|
+
"BlockStore",
|
|
17
|
+
"Exchange",
|
|
18
|
+
"DagService",
|
|
19
|
+
"setup_libp2p",
|
|
20
|
+
"default_bootstrap_peers",
|
|
21
|
+
"new_in_memory_datastore",
|
|
22
|
+
]
|
|
23
|
+
__version__ = "0.1.0"
|
py_ipfs_lite/api.py
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import tempfile
|
|
5
|
+
from collections.abc import AsyncGenerator
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from fastapi import FastAPI, File, HTTPException, Query, Request, UploadFile
|
|
10
|
+
from fastapi.responses import JSONResponse, Response
|
|
11
|
+
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
|
|
12
|
+
|
|
13
|
+
from py_ipfs_lite.config import Config
|
|
14
|
+
from py_ipfs_lite.exceptions import (
|
|
15
|
+
BlockNotFoundError,
|
|
16
|
+
IPFSLiteError,
|
|
17
|
+
PeerNotStartedError,
|
|
18
|
+
PinNotFoundError,
|
|
19
|
+
RoutingError,
|
|
20
|
+
)
|
|
21
|
+
from py_ipfs_lite.peer import Peer
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("py_ipfs_lite.api")
|
|
24
|
+
# The actual instantiation of the peer depends on how the daemon is run,
|
|
25
|
+
# but we can set up a default initialization inside the lifespan if none exists.
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@asynccontextmanager
|
|
29
|
+
async def lifespan(app: FastAPI) -> AsyncGenerator[Any, None]:
|
|
30
|
+
# Check if a peer was already provided (e.g. injected during setup)
|
|
31
|
+
peer = getattr(app.state, "peer", None)
|
|
32
|
+
if not peer:
|
|
33
|
+
# If not, initialize a default one for the daemon
|
|
34
|
+
from libp2p.utils.address_validation import (
|
|
35
|
+
find_free_port,
|
|
36
|
+
get_available_interfaces,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
config = Config()
|
|
40
|
+
port = find_free_port()
|
|
41
|
+
listen_addrs = get_available_interfaces(port)
|
|
42
|
+
peer = Peer(config, listen_addrs=listen_addrs)
|
|
43
|
+
app.state.peer = peer
|
|
44
|
+
|
|
45
|
+
# Start the peer
|
|
46
|
+
await peer.start()
|
|
47
|
+
|
|
48
|
+
logger.info(f"Daemon P2P Peer ID: {peer.host.id()}") # type: ignore[union-attr]
|
|
49
|
+
for addr in peer.host.addrs(): # type: ignore[union-attr]
|
|
50
|
+
logger.info(f" P2P Listening on: {addr}")
|
|
51
|
+
|
|
52
|
+
yield
|
|
53
|
+
|
|
54
|
+
# Clean up on shutdown
|
|
55
|
+
await peer.close()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
app = FastAPI(title="py-ipfs-lite HTTP API", lifespan=lifespan)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@app.exception_handler(IPFSLiteError)
|
|
62
|
+
async def ipfs_lite_exception_handler(request: Request, exc: IPFSLiteError) -> Any:
|
|
63
|
+
status_code = 500
|
|
64
|
+
if isinstance(exc, (BlockNotFoundError, PinNotFoundError, RoutingError)):
|
|
65
|
+
status_code = 404
|
|
66
|
+
elif isinstance(exc, PeerNotStartedError):
|
|
67
|
+
status_code = 503
|
|
68
|
+
return JSONResponse(status_code=status_code, content={"detail": str(exc)})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@app.post("/api/v0/add")
|
|
72
|
+
async def add_file(request: Request, file: UploadFile = File(...)) -> Any:
|
|
73
|
+
"""Add a file to the local blockstore and announce it."""
|
|
74
|
+
peer: Peer = request.app.state.peer
|
|
75
|
+
|
|
76
|
+
# Save the uploaded file to a temporary file, then add it via peer
|
|
77
|
+
fd, path = tempfile.mkstemp()
|
|
78
|
+
try:
|
|
79
|
+
with os.fdopen(fd, "wb") as f:
|
|
80
|
+
content = await file.read()
|
|
81
|
+
f.write(content)
|
|
82
|
+
|
|
83
|
+
cid_str = await peer.add_file(path)
|
|
84
|
+
return JSONResponse(
|
|
85
|
+
content={"Name": file.filename, "Hash": cid_str, "Size": str(len(content))}
|
|
86
|
+
)
|
|
87
|
+
except Exception as e:
|
|
88
|
+
if isinstance(e, IPFSLiteError):
|
|
89
|
+
raise
|
|
90
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
91
|
+
finally:
|
|
92
|
+
os.remove(path)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@app.post("/api/v0/cat")
|
|
96
|
+
@app.get("/api/v0/cat")
|
|
97
|
+
async def cat_file(
|
|
98
|
+
request: Request,
|
|
99
|
+
arg: str = Query(..., description="The path to the IPFS object(s) to be outputted"),
|
|
100
|
+
) -> Any:
|
|
101
|
+
"""Fetch a file by its CID."""
|
|
102
|
+
peer: Peer = request.app.state.peer
|
|
103
|
+
try:
|
|
104
|
+
content_iter = await peer.get_file(arg, stream=True)
|
|
105
|
+
from fastapi.responses import StreamingResponse
|
|
106
|
+
|
|
107
|
+
return StreamingResponse(content_iter, media_type="application/octet-stream") # type: ignore[arg-type]
|
|
108
|
+
except Exception as e:
|
|
109
|
+
if isinstance(e, IPFSLiteError):
|
|
110
|
+
raise
|
|
111
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@app.post("/api/v0/dag/put")
|
|
115
|
+
async def dag_put(
|
|
116
|
+
request: Request, store_codec: str = Query("dag-json", alias="store-codec")
|
|
117
|
+
) -> Any:
|
|
118
|
+
"""Store a generic DAG node."""
|
|
119
|
+
peer: Peer = request.app.state.peer
|
|
120
|
+
body = await request.body()
|
|
121
|
+
try:
|
|
122
|
+
node_data = json.loads(body)
|
|
123
|
+
cid_str = await peer.add_node(node_data, codec=store_codec)
|
|
124
|
+
return JSONResponse(content={"Cid": {"/": cid_str}})
|
|
125
|
+
except Exception as e:
|
|
126
|
+
if isinstance(e, IPFSLiteError):
|
|
127
|
+
raise
|
|
128
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@app.post("/api/v0/dag/get")
|
|
132
|
+
@app.get("/api/v0/dag/get")
|
|
133
|
+
async def dag_get(
|
|
134
|
+
request: Request, arg: str = Query(..., description="The object to get")
|
|
135
|
+
) -> Any:
|
|
136
|
+
"""Retrieve a generic DAG node."""
|
|
137
|
+
peer: Peer = request.app.state.peer
|
|
138
|
+
try:
|
|
139
|
+
node_data = await peer.get_node(arg)
|
|
140
|
+
return JSONResponse(content=node_data)
|
|
141
|
+
except Exception as e:
|
|
142
|
+
if isinstance(e, IPFSLiteError):
|
|
143
|
+
raise
|
|
144
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@app.post("/api/v0/block/stat")
|
|
148
|
+
async def block_stat(
|
|
149
|
+
request: Request,
|
|
150
|
+
arg: str = Query(
|
|
151
|
+
..., description="The base58 multihash of an existing block to stat"
|
|
152
|
+
),
|
|
153
|
+
) -> Any:
|
|
154
|
+
"""Check if a block exists locally and get its size."""
|
|
155
|
+
peer: Peer = request.app.state.peer
|
|
156
|
+
from libp2p.bitswap.cid import parse_cid
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
cid = parse_cid(arg)
|
|
160
|
+
has = await peer.blockstore.has(cid) # type: ignore[union-attr]
|
|
161
|
+
if not has:
|
|
162
|
+
raise HTTPException(status_code=404, detail="Block not found locally")
|
|
163
|
+
|
|
164
|
+
# To get size we must read it
|
|
165
|
+
data = await peer.blockstore.get(cid) # type: ignore[union-attr]
|
|
166
|
+
return JSONResponse(content={"Key": arg, "Size": len(data)}) # type: ignore[arg-type]
|
|
167
|
+
except HTTPException:
|
|
168
|
+
raise
|
|
169
|
+
except Exception as e:
|
|
170
|
+
if isinstance(e, IPFSLiteError):
|
|
171
|
+
raise
|
|
172
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@app.post("/api/v0/block/rm")
|
|
176
|
+
async def block_rm(
|
|
177
|
+
request: Request,
|
|
178
|
+
arg: str = Query(..., description="Bash58 multihash of block(s) to remove"),
|
|
179
|
+
) -> Any:
|
|
180
|
+
"""Remove a raw block from the local blockstore."""
|
|
181
|
+
peer: Peer = request.app.state.peer
|
|
182
|
+
try:
|
|
183
|
+
await peer.remove_node(arg)
|
|
184
|
+
return JSONResponse(content={"Hash": arg, "Error": ""})
|
|
185
|
+
except Exception as e:
|
|
186
|
+
if isinstance(e, IPFSLiteError):
|
|
187
|
+
raise
|
|
188
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@app.post("/api/v0/pin/add")
|
|
192
|
+
async def pin_add(
|
|
193
|
+
request: Request,
|
|
194
|
+
arg: str = Query(..., description="Path to object(s) to be pinned"),
|
|
195
|
+
recursive: bool = Query(True),
|
|
196
|
+
) -> Any:
|
|
197
|
+
"""Pin a CID."""
|
|
198
|
+
peer: Peer = request.app.state.peer
|
|
199
|
+
try:
|
|
200
|
+
await peer.add_pin(arg, recursive=recursive)
|
|
201
|
+
return JSONResponse(content={"Pins": [arg]})
|
|
202
|
+
except Exception as e:
|
|
203
|
+
if isinstance(e, IPFSLiteError):
|
|
204
|
+
raise
|
|
205
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@app.post("/api/v0/pin/rm")
|
|
209
|
+
async def pin_rm(
|
|
210
|
+
request: Request,
|
|
211
|
+
arg: str = Query(..., description="Path to object(s) to be unpinned"),
|
|
212
|
+
) -> Any:
|
|
213
|
+
"""Unpin a CID."""
|
|
214
|
+
peer: Peer = request.app.state.peer
|
|
215
|
+
try:
|
|
216
|
+
await peer.remove_pin(arg)
|
|
217
|
+
return JSONResponse(content={"Pins": [arg]})
|
|
218
|
+
except Exception as e:
|
|
219
|
+
if isinstance(e, IPFSLiteError):
|
|
220
|
+
raise
|
|
221
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@app.post("/api/v0/repo/gc")
|
|
225
|
+
async def repo_gc(request: Request) -> Any:
|
|
226
|
+
"""Run garbage collection."""
|
|
227
|
+
peer: Peer = request.app.state.peer
|
|
228
|
+
try:
|
|
229
|
+
import dataclasses
|
|
230
|
+
|
|
231
|
+
stats = await peer.gc()
|
|
232
|
+
return JSONResponse(content=dataclasses.asdict(stats))
|
|
233
|
+
except Exception as e:
|
|
234
|
+
if isinstance(e, IPFSLiteError):
|
|
235
|
+
raise
|
|
236
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@app.post("/api/v0/refs/local")
|
|
240
|
+
async def refs_local(request: Request) -> Any:
|
|
241
|
+
"""List all CIDs stored in the local blockstore."""
|
|
242
|
+
peer: Peer = request.app.state.peer
|
|
243
|
+
try:
|
|
244
|
+
keys = peer.blockstore.all_keys() # type: ignore[union-attr]
|
|
245
|
+
results = []
|
|
246
|
+
for k in keys:
|
|
247
|
+
results.append({"Ref": k, "Err": ""})
|
|
248
|
+
# Kubo streams this as NDJSON, but returning a JSON array of objects is easier for testing
|
|
249
|
+
return JSONResponse(content={"Refs": results})
|
|
250
|
+
except Exception as e:
|
|
251
|
+
if isinstance(e, IPFSLiteError):
|
|
252
|
+
raise
|
|
253
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@app.post("/api/v0/version")
|
|
257
|
+
@app.get("/api/v0/version")
|
|
258
|
+
async def api_version() -> Any:
|
|
259
|
+
"""Get the version of py-ipfs-lite."""
|
|
260
|
+
return JSONResponse(
|
|
261
|
+
content={"Version": "0.1.0", "Commit": "", "System": "py-ipfs-lite"}
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
@app.post("/api/v0/id")
|
|
266
|
+
@app.get("/api/v0/id")
|
|
267
|
+
async def api_id(request: Request) -> Any:
|
|
268
|
+
"""Show IPFS node id info."""
|
|
269
|
+
peer: Peer = request.app.state.peer
|
|
270
|
+
return JSONResponse(
|
|
271
|
+
content={
|
|
272
|
+
"ID": peer.host.id().to_base58(), # type: ignore[union-attr]
|
|
273
|
+
"Addresses": [str(addr) for addr in peer.host.addrs()], # type: ignore[union-attr]
|
|
274
|
+
}
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@app.post("/api/v0/repo/stat")
|
|
279
|
+
@app.get("/api/v0/repo/stat")
|
|
280
|
+
async def repo_stat(request: Request) -> Any:
|
|
281
|
+
"""Get stats for the currently used repo."""
|
|
282
|
+
peer: Peer = request.app.state.peer
|
|
283
|
+
try:
|
|
284
|
+
from libp2p.bitswap.cid import cid_to_bytes, parse_cid
|
|
285
|
+
|
|
286
|
+
keys = peer.blockstore.all_keys() # type: ignore[union-attr]
|
|
287
|
+
num_objects = len(keys)
|
|
288
|
+
# get_size can be called synchronously in the underlying memory/fs blockstore in py_ipfs_lite
|
|
289
|
+
repo_size = sum(
|
|
290
|
+
peer.blockstore.get_size(cid_to_bytes(parse_cid(k))) # type: ignore[union-attr, misc]
|
|
291
|
+
for k in keys
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
path = peer.config.blockstore_path
|
|
295
|
+
if peer.config.blockstore_type == "memory":
|
|
296
|
+
path = ""
|
|
297
|
+
|
|
298
|
+
return JSONResponse(
|
|
299
|
+
content={
|
|
300
|
+
"NumObjects": num_objects,
|
|
301
|
+
"RepoSize": repo_size,
|
|
302
|
+
"RepoPath": path,
|
|
303
|
+
"Version": "1",
|
|
304
|
+
}
|
|
305
|
+
)
|
|
306
|
+
except Exception as e:
|
|
307
|
+
if isinstance(e, IPFSLiteError):
|
|
308
|
+
raise
|
|
309
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@app.post("/api/v0/swarm/peers")
|
|
313
|
+
@app.get("/api/v0/swarm/peers")
|
|
314
|
+
async def swarm_peers(request: Request) -> Any:
|
|
315
|
+
"""List peers with open connections."""
|
|
316
|
+
peer: Peer = request.app.state.peer
|
|
317
|
+
network = peer.host.get_network() # type: ignore[union-attr]
|
|
318
|
+
peers_data = []
|
|
319
|
+
|
|
320
|
+
try:
|
|
321
|
+
if hasattr(network, "connections"):
|
|
322
|
+
conns_dict = network.connections
|
|
323
|
+
for peer_id_obj, conns in conns_dict.items():
|
|
324
|
+
if not isinstance(conns, list):
|
|
325
|
+
conns = [conns]
|
|
326
|
+
|
|
327
|
+
for c in conns:
|
|
328
|
+
addr_str = ""
|
|
329
|
+
try:
|
|
330
|
+
if hasattr(c, "remote_addr"):
|
|
331
|
+
addr_str = str(c.remote_addr)
|
|
332
|
+
elif hasattr(c, "get_remote_multiaddr"):
|
|
333
|
+
addr_str = str(c.get_remote_multiaddr())
|
|
334
|
+
except Exception:
|
|
335
|
+
pass
|
|
336
|
+
|
|
337
|
+
peers_data.append(
|
|
338
|
+
{
|
|
339
|
+
"Peer": peer_id_obj.to_base58(),
|
|
340
|
+
"Addr": addr_str,
|
|
341
|
+
"Direction": 0,
|
|
342
|
+
}
|
|
343
|
+
)
|
|
344
|
+
except Exception as e:
|
|
345
|
+
logger.warning(f"Failed to list swarm peers: {e}")
|
|
346
|
+
|
|
347
|
+
return JSONResponse(content={"Peers": peers_data})
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
@app.get("/debug/metrics/prometheus")
|
|
351
|
+
async def metrics() -> Any:
|
|
352
|
+
"""Expose Prometheus metrics."""
|
|
353
|
+
return Response(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
@app.post("/api/v0/repo/version")
|
|
357
|
+
@app.get("/api/v0/repo/version")
|
|
358
|
+
async def repo_version(request: Request) -> Any:
|
|
359
|
+
"""Return the datastore/repo version."""
|
|
360
|
+
peer: Peer = request.app.state.peer
|
|
361
|
+
|
|
362
|
+
if peer.config.blockstore_type == "filesystem" and peer.config.blockstore_path:
|
|
363
|
+
from py_ipfs_lite.versioning import get_repo_version
|
|
364
|
+
|
|
365
|
+
v = get_repo_version(peer.config.blockstore_path)
|
|
366
|
+
else:
|
|
367
|
+
v = "memory"
|
|
368
|
+
|
|
369
|
+
return JSONResponse(content={"Version": v})
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
@app.post("/api/v0/name/publish")
|
|
373
|
+
async def name_publish(
|
|
374
|
+
request: Request,
|
|
375
|
+
arg: str = Query(..., description="IPFS path of the object to be published"),
|
|
376
|
+
) -> Any:
|
|
377
|
+
"""Publish an IPNS record."""
|
|
378
|
+
peer: Peer = request.app.state.peer
|
|
379
|
+
try:
|
|
380
|
+
# Default lifetime is 24 hours.
|
|
381
|
+
name = await peer.publish_name(arg, lifetime_hours=24)
|
|
382
|
+
return JSONResponse(content={"Name": name, "Value": arg})
|
|
383
|
+
except Exception as e:
|
|
384
|
+
if isinstance(e, IPFSLiteError):
|
|
385
|
+
raise
|
|
386
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
@app.post("/api/v0/name/resolve")
|
|
390
|
+
@app.get("/api/v0/name/resolve")
|
|
391
|
+
async def name_resolve(
|
|
392
|
+
request: Request, arg: str = Query(..., description="The IPNS name to resolve")
|
|
393
|
+
) -> Any:
|
|
394
|
+
"""Resolve an IPNS record."""
|
|
395
|
+
peer: Peer = request.app.state.peer
|
|
396
|
+
try:
|
|
397
|
+
value = await peer.resolve_name(arg)
|
|
398
|
+
return JSONResponse(content={"Path": value})
|
|
399
|
+
except Exception as e:
|
|
400
|
+
if isinstance(e, IPFSLiteError):
|
|
401
|
+
raise
|
|
402
|
+
raise HTTPException(status_code=500, detail=str(e))
|
py_ipfs_lite/car.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import io
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import trio
|
|
5
|
+
import varint
|
|
6
|
+
from cbor2 import CBORTag, dumps, loads
|
|
7
|
+
from libp2p.bitswap.cid import (
|
|
8
|
+
_normalise_codec,
|
|
9
|
+
cid_to_bytes,
|
|
10
|
+
format_cid_for_display,
|
|
11
|
+
parse_cid,
|
|
12
|
+
parse_cid_codec,
|
|
13
|
+
)
|
|
14
|
+
from libp2p.bitswap.dag import decode_dag_pb
|
|
15
|
+
|
|
16
|
+
from py_ipfs_lite.dag_utils import decode_node
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class BufferedAsyncReader:
|
|
20
|
+
def __init__(self, f: Any, buffer_size: Any = 65536) -> None:
|
|
21
|
+
self.f = f
|
|
22
|
+
self.buffer_size = buffer_size
|
|
23
|
+
self.buffer = bytearray()
|
|
24
|
+
self.offset = 0
|
|
25
|
+
|
|
26
|
+
async def read_exactly(self, n: int) -> bytes:
|
|
27
|
+
while len(self.buffer) - self.offset < n:
|
|
28
|
+
chunk = await self.f.read(self.buffer_size)
|
|
29
|
+
if not chunk:
|
|
30
|
+
if len(self.buffer) - self.offset == 0 and n > 0:
|
|
31
|
+
raise EOFError("Unexpected EOF")
|
|
32
|
+
break
|
|
33
|
+
self.buffer.extend(chunk)
|
|
34
|
+
|
|
35
|
+
data = self.buffer[self.offset : self.offset + n]
|
|
36
|
+
self.offset += n
|
|
37
|
+
if self.offset > self.buffer_size * 2:
|
|
38
|
+
self.buffer = self.buffer[self.offset :]
|
|
39
|
+
self.offset = 0
|
|
40
|
+
return bytes(data)
|
|
41
|
+
|
|
42
|
+
async def read_varint(self) -> int:
|
|
43
|
+
shift = 0
|
|
44
|
+
result = 0
|
|
45
|
+
while True:
|
|
46
|
+
if self.offset >= len(self.buffer):
|
|
47
|
+
chunk = await self.f.read(self.buffer_size)
|
|
48
|
+
if not chunk:
|
|
49
|
+
if shift == 0:
|
|
50
|
+
raise TypeError("EOF")
|
|
51
|
+
raise EOFError("Unexpected EOF reading varint")
|
|
52
|
+
self.buffer.extend(chunk)
|
|
53
|
+
|
|
54
|
+
val = self.buffer[self.offset]
|
|
55
|
+
self.offset += 1
|
|
56
|
+
|
|
57
|
+
result |= (val & 0x7F) << shift
|
|
58
|
+
if not (val & 0x80):
|
|
59
|
+
break
|
|
60
|
+
shift += 7
|
|
61
|
+
|
|
62
|
+
if self.offset > self.buffer_size * 2:
|
|
63
|
+
self.buffer = self.buffer[self.offset :]
|
|
64
|
+
self.offset = 0
|
|
65
|
+
|
|
66
|
+
return result
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_cid_len(data: bytes) -> int:
|
|
70
|
+
if data[0] == 0x12 and data[1] == 0x20:
|
|
71
|
+
return 34
|
|
72
|
+
|
|
73
|
+
stream = io.BytesIO(data)
|
|
74
|
+
_version = varint.decode_stream(stream)
|
|
75
|
+
_codec = varint.decode_stream(stream)
|
|
76
|
+
_mh_code = varint.decode_stream(stream)
|
|
77
|
+
mh_len = varint.decode_stream(stream)
|
|
78
|
+
stream.read(mh_len)
|
|
79
|
+
return stream.tell()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
async def export_car(peer: Any, cid_str: str, output_path: str) -> None:
|
|
83
|
+
root_cid = parse_cid(cid_str)
|
|
84
|
+
|
|
85
|
+
async with await trio.open_file(output_path, "wb") as f:
|
|
86
|
+
# Header
|
|
87
|
+
header_dict = {
|
|
88
|
+
"version": 1,
|
|
89
|
+
"roots": [CBORTag(42, b"\x00" + cid_to_bytes(root_cid))],
|
|
90
|
+
}
|
|
91
|
+
header_bytes = dumps(header_dict)
|
|
92
|
+
await f.write(varint.encode(len(header_bytes)))
|
|
93
|
+
await f.write(header_bytes)
|
|
94
|
+
|
|
95
|
+
# Traverse
|
|
96
|
+
queue = [cid_to_bytes(root_cid)]
|
|
97
|
+
visited = set()
|
|
98
|
+
|
|
99
|
+
while queue:
|
|
100
|
+
curr_cid_bytes = queue.pop(0)
|
|
101
|
+
if curr_cid_bytes in visited:
|
|
102
|
+
continue
|
|
103
|
+
visited.add(curr_cid_bytes)
|
|
104
|
+
|
|
105
|
+
data = await peer.blockstore.get(curr_cid_bytes)
|
|
106
|
+
if data is None:
|
|
107
|
+
data = await peer.exchange.get_block(curr_cid_bytes)
|
|
108
|
+
if data is None:
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
block_len = len(curr_cid_bytes) + len(data)
|
|
112
|
+
await f.write(varint.encode(block_len))
|
|
113
|
+
await f.write(curr_cid_bytes)
|
|
114
|
+
await f.write(data)
|
|
115
|
+
|
|
116
|
+
codec = parse_cid_codec(curr_cid_bytes)
|
|
117
|
+
norm_codec = _normalise_codec(codec)
|
|
118
|
+
|
|
119
|
+
if str(norm_codec) == "dag-pb":
|
|
120
|
+
try:
|
|
121
|
+
node_links, _ = decode_dag_pb(data)
|
|
122
|
+
for link in node_links:
|
|
123
|
+
if hasattr(link, "cid"):
|
|
124
|
+
queue.append(link.cid)
|
|
125
|
+
except Exception:
|
|
126
|
+
pass
|
|
127
|
+
elif str(norm_codec) in ("dag-json", "dag-cbor", "ipld", "dag-jose"):
|
|
128
|
+
try:
|
|
129
|
+
decoded = decode_node(data, codec)
|
|
130
|
+
|
|
131
|
+
def extract_links(obj: Any) -> None:
|
|
132
|
+
if isinstance(obj, dict):
|
|
133
|
+
if "/" in obj and isinstance(obj["/"], (str, bytes)):
|
|
134
|
+
try:
|
|
135
|
+
link_cid = parse_cid(obj["/"])
|
|
136
|
+
queue.append(cid_to_bytes(link_cid))
|
|
137
|
+
except Exception:
|
|
138
|
+
pass
|
|
139
|
+
for v in obj.values():
|
|
140
|
+
extract_links(v)
|
|
141
|
+
elif isinstance(obj, list):
|
|
142
|
+
for item in obj:
|
|
143
|
+
extract_links(item)
|
|
144
|
+
|
|
145
|
+
extract_links(decoded)
|
|
146
|
+
except Exception:
|
|
147
|
+
pass
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def import_car(peer: Any, input_path: str) -> list[str]:
|
|
151
|
+
roots = [] # type: ignore[var-annotated]
|
|
152
|
+
async with await trio.open_file(input_path, "rb") as raw_f:
|
|
153
|
+
f = BufferedAsyncReader(raw_f)
|
|
154
|
+
# Header length
|
|
155
|
+
try:
|
|
156
|
+
header_len = await f.read_varint()
|
|
157
|
+
except TypeError:
|
|
158
|
+
return roots
|
|
159
|
+
|
|
160
|
+
header_bytes = await f.read_exactly(header_len)
|
|
161
|
+
header = loads(header_bytes)
|
|
162
|
+
if header.get("version") != 1:
|
|
163
|
+
raise ValueError(f"Unsupported CAR version: {header.get('version')}")
|
|
164
|
+
|
|
165
|
+
for root in header.get("roots", []):
|
|
166
|
+
if isinstance(root, CBORTag) and root.tag == 42:
|
|
167
|
+
cid_bytes = root.value[1:]
|
|
168
|
+
cid = parse_cid(cid_bytes)
|
|
169
|
+
roots.append(format_cid_for_display(cid))
|
|
170
|
+
|
|
171
|
+
# Read blocks
|
|
172
|
+
while True:
|
|
173
|
+
try:
|
|
174
|
+
block_len = await f.read_varint()
|
|
175
|
+
except TypeError:
|
|
176
|
+
break
|
|
177
|
+
|
|
178
|
+
block_data_full = await f.read_exactly(block_len)
|
|
179
|
+
if not block_data_full:
|
|
180
|
+
break
|
|
181
|
+
|
|
182
|
+
cid_len = get_cid_len(block_data_full)
|
|
183
|
+
cid_bytes = block_data_full[:cid_len]
|
|
184
|
+
data = block_data_full[cid_len:]
|
|
185
|
+
|
|
186
|
+
await peer.blockstore.put(cid_bytes, data)
|
|
187
|
+
|
|
188
|
+
return roots
|