py-ipfs-lite 0.1.0__tar.gz

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.
Files changed (39) hide show
  1. py_ipfs_lite-0.1.0/PKG-INFO +141 -0
  2. py_ipfs_lite-0.1.0/README.md +99 -0
  3. py_ipfs_lite-0.1.0/py_ipfs_lite/__init__.py +23 -0
  4. py_ipfs_lite-0.1.0/py_ipfs_lite/api.py +402 -0
  5. py_ipfs_lite-0.1.0/py_ipfs_lite/car.py +188 -0
  6. py_ipfs_lite-0.1.0/py_ipfs_lite/cli.py +293 -0
  7. py_ipfs_lite-0.1.0/py_ipfs_lite/config.py +29 -0
  8. py_ipfs_lite-0.1.0/py_ipfs_lite/dag_utils.py +90 -0
  9. py_ipfs_lite-0.1.0/py_ipfs_lite/exceptions.py +28 -0
  10. py_ipfs_lite-0.1.0/py_ipfs_lite/interfaces.py +146 -0
  11. py_ipfs_lite-0.1.0/py_ipfs_lite/ipns.py +175 -0
  12. py_ipfs_lite-0.1.0/py_ipfs_lite/main.py +11 -0
  13. py_ipfs_lite-0.1.0/py_ipfs_lite/metrics.py +82 -0
  14. py_ipfs_lite-0.1.0/py_ipfs_lite/parser.py +135 -0
  15. py_ipfs_lite-0.1.0/py_ipfs_lite/peer.py +721 -0
  16. py_ipfs_lite-0.1.0/py_ipfs_lite/pin.py +80 -0
  17. py_ipfs_lite-0.1.0/py_ipfs_lite/py.typed +0 -0
  18. py_ipfs_lite-0.1.0/py_ipfs_lite/reprovider.py +64 -0
  19. py_ipfs_lite-0.1.0/py_ipfs_lite/routing.py +193 -0
  20. py_ipfs_lite-0.1.0/py_ipfs_lite/versioning.py +39 -0
  21. py_ipfs_lite-0.1.0/py_ipfs_lite.egg-info/PKG-INFO +141 -0
  22. py_ipfs_lite-0.1.0/py_ipfs_lite.egg-info/SOURCES.txt +37 -0
  23. py_ipfs_lite-0.1.0/py_ipfs_lite.egg-info/dependency_links.txt +1 -0
  24. py_ipfs_lite-0.1.0/py_ipfs_lite.egg-info/entry_points.txt +2 -0
  25. py_ipfs_lite-0.1.0/py_ipfs_lite.egg-info/requires.txt +24 -0
  26. py_ipfs_lite-0.1.0/py_ipfs_lite.egg-info/top_level.txt +1 -0
  27. py_ipfs_lite-0.1.0/pyproject.toml +126 -0
  28. py_ipfs_lite-0.1.0/setup.cfg +4 -0
  29. py_ipfs_lite-0.1.0/tests/test_api.py +52 -0
  30. py_ipfs_lite-0.1.0/tests/test_car.py +72 -0
  31. py_ipfs_lite-0.1.0/tests/test_config_defaults.py +13 -0
  32. py_ipfs_lite-0.1.0/tests/test_exceptions.py +86 -0
  33. py_ipfs_lite-0.1.0/tests/test_ipns.py +148 -0
  34. py_ipfs_lite-0.1.0/tests/test_metrics.py +20 -0
  35. py_ipfs_lite-0.1.0/tests/test_peer.py +245 -0
  36. py_ipfs_lite-0.1.0/tests/test_pin.py +80 -0
  37. py_ipfs_lite-0.1.0/tests/test_reprovider.py +61 -0
  38. py_ipfs_lite-0.1.0/tests/test_routing.py +56 -0
  39. py_ipfs_lite-0.1.0/tests/test_versioning.py +74 -0
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: py-ipfs-lite
3
+ Version: 0.1.0
4
+ Summary: Embeddable lightweight IPFS peer for Python (bootstrap phase)
5
+ Author: py-ipfs-lite contributors
6
+ License: Apache-2.0 OR MIT
7
+ Project-URL: Homepage, https://github.com/IPFS-Meshkit/py-ipfs-lite
8
+ Project-URL: Repository, https://github.com/IPFS-Meshkit/py-ipfs-lite
9
+ Keywords: ipfs,libp2p,bitswap,unixfs,ipld
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Requires-Python: <4.0,>=3.10
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: fastapi>=0.137.1
22
+ Requires-Dist: httpx>=0.28.1
23
+ Requires-Dist: hypercorn>=0.18.0
24
+ Requires-Dist: libp2p>=0.7.0
25
+ Requires-Dist: prometheus-client>=0.25.0
26
+ Requires-Dist: python-multipart>=0.0.32
27
+ Provides-Extra: dev
28
+ Requires-Dist: build>=1.2.1; extra == "dev"
29
+ Requires-Dist: mypy>=1.10.0; extra == "dev"
30
+ Requires-Dist: pre-commit>=3.7.0; extra == "dev"
31
+ Requires-Dist: ruff>=0.6.0; extra == "dev"
32
+ Requires-Dist: mdformat>=0.7.22; extra == "dev"
33
+ Requires-Dist: mdformat-gfm; extra == "dev"
34
+ Provides-Extra: test
35
+ Requires-Dist: pytest>=8.0.0; extra == "test"
36
+ Requires-Dist: pytest-cov>=5.0.0; extra == "test"
37
+ Requires-Dist: pytest-trio>=0.8.0; extra == "test"
38
+ Requires-Dist: pytest-xdist>=3.5.0; extra == "test"
39
+ Provides-Extra: docs
40
+ Requires-Dist: mkdocs-material>=9.0.0; extra == "docs"
41
+ Requires-Dist: mkdocstrings[python]>=0.24.0; extra == "docs"
42
+
43
+ # py-ipfs-lite
44
+
45
+ **py-ipfs-lite** is a lightweight, embeddable Python IPFS peer built on top of `py-libp2p`.
46
+ It provides the core features of IPFS (Blockstore, Bitswap, DHT, IPNI, IPNS, and IPLD DAGs) without the overhead of a heavy Kubo daemon.
47
+
48
+ It is designed to be highly interoperable with standard IPFS implementations like Kubo and go-ipfs-lite, natively supporting `dag-cbor`, CARv1 file import/export, Bitswap streaming, and more.
49
+
50
+ ## Features
51
+
52
+ - **Embedded IPFS Node:** Run a complete IPFS node purely in Python using `trio` or standard async.
53
+ - **Bitswap Protocol:** Interoperate and exchange blocks directly with Kubo daemons.
54
+ - **KadDHT & IPNI Routing:** Local block lookups with lightning-fast routing via the KadDHT network and Delegated HTTP IPNI (`cid.contact`).
55
+ - **IPLD DAG Support:** Fully supports `dag-pb`, `dag-cbor`, and `dag-json` for building decentralized knowledge graphs, versioned datasets, and agent memory chains.
56
+ - **Offline Data Bundles (CAR):** Export and import full or partial DAGs as Content Addressable aRchives (`.car`).
57
+ - **IPNS Mutable Pointers:** Publish and resolve cryptographically signed mutable pointers (IPNS).
58
+ - **FastAPI HTTP Daemon:** A drop-in, Kubo-compatible HTTP API exposing `/api/v0` endpoints for adding files, fetching DAGs, and pinning.
59
+ - **Prometheus Metrics:** Integrated observability for garbage collection, block sizes, and Bitswap traffic.
60
+
61
+ ## Installation
62
+
63
+ py-ipfs-lite uses `uv` for dependency management.
64
+
65
+ ```bash
66
+ # Clone the repository
67
+ git clone https://github.com/IPFS-Meshkit/py-ipfs-lite.git
68
+ cd py-ipfs-lite
69
+
70
+ # Install dependencies using uv
71
+ uv sync
72
+ ```
73
+
74
+ ## Quickstart
75
+
76
+ ### 1. The Python SDK (Embedded Peer)
77
+
78
+ You can run an IPFS peer directly inside your Python application using `trio`:
79
+
80
+ ```python
81
+ import trio
82
+ from py_ipfs_lite.peer import Peer
83
+ from py_ipfs_lite.config import Config
84
+
85
+ async def main():
86
+ # Start an ephemeral in-memory peer
87
+ peer = Peer(Config(blockstore_type="memory"), listen_addrs=["/ip4/127.0.0.1/tcp/0"])
88
+ await peer.start()
89
+
90
+ # Add a file
91
+ cid = await peer.add_file("/path/to/my/file.txt")
92
+ print(f"Added file with CID: {cid}")
93
+
94
+ # Build an IPLD DAG
95
+ node_cid = await peer.add_node({"title": "Hello World", "author": "py-ipfs-lite"}, codec="dag-cbor")
96
+ print(f"Added DAG node with CID: {node_cid}")
97
+
98
+ # Publish to IPNS
99
+ ipns_name = await peer.publish_name(f"/ipfs/{node_cid}")
100
+ print(f"Published to IPNS: {ipns_name}")
101
+
102
+ await peer.close()
103
+
104
+ if __name__ == "__main__":
105
+ trio.run(main)
106
+ ```
107
+
108
+ ### 2. The CLI Daemon & HTTP API
109
+
110
+ You can spin up `py-ipfs-lite` as a standalone daemon that provides a Kubo-compatible HTTP API.
111
+
112
+ ```bash
113
+ # Run the daemon on port 4001, exposing the HTTP API on port 5001
114
+ uv run py-ipfs-lite daemon --api --api-port 5001
115
+ ```
116
+
117
+ Then you can use the standard HTTP API to interact with it:
118
+
119
+ ```bash
120
+ # Add a file
121
+ curl -X POST -F file=@test.txt http://127.0.0.1:5001/api/v0/add
122
+
123
+ # Fetch an IPLD node
124
+ curl -X POST "http://127.0.0.1:5001/api/v0/dag/get?arg=bafy..."
125
+ ```
126
+
127
+ ## What's Next
128
+
129
+ | I want to… | Go to… |
130
+ | --------------------------------------------------------------- | ------------------------------------------------------------------------------ |
131
+ | Understand how `py-ipfs-lite` is structured internally | [docs/architecture.md](docs/architecture.md) |
132
+ | Build verifiable AI agent memory / RAG pipelines | [docs/guides/ai-agents-and-rag.md](docs/guides/ai-agents-and-rag.md) |
133
+ | Export a DAG as a CAR file for Filecoin storage | [docs/guides/car-files-and-filecoin.md](docs/guides/car-files-and-filecoin.md) |
134
+ | Use IPNS mutable pointers and understand the trust model | [docs/guides/ipns.md](docs/guides/ipns.md) |
135
+ | Interoperate with a live Kubo daemon over Bitswap | [docs/guides/interop-with-kubo.md](docs/guides/interop-with-kubo.md) |
136
+ | See the full list of all 21 examples with one-line descriptions | [docs/reference/examples-index.md](docs/reference/examples-index.md) |
137
+ | Browse all documentation | [docs/index.md](docs/index.md) |
138
+
139
+ ## License
140
+
141
+ MIT License
@@ -0,0 +1,99 @@
1
+ # py-ipfs-lite
2
+
3
+ **py-ipfs-lite** is a lightweight, embeddable Python IPFS peer built on top of `py-libp2p`.
4
+ It provides the core features of IPFS (Blockstore, Bitswap, DHT, IPNI, IPNS, and IPLD DAGs) without the overhead of a heavy Kubo daemon.
5
+
6
+ It is designed to be highly interoperable with standard IPFS implementations like Kubo and go-ipfs-lite, natively supporting `dag-cbor`, CARv1 file import/export, Bitswap streaming, and more.
7
+
8
+ ## Features
9
+
10
+ - **Embedded IPFS Node:** Run a complete IPFS node purely in Python using `trio` or standard async.
11
+ - **Bitswap Protocol:** Interoperate and exchange blocks directly with Kubo daemons.
12
+ - **KadDHT & IPNI Routing:** Local block lookups with lightning-fast routing via the KadDHT network and Delegated HTTP IPNI (`cid.contact`).
13
+ - **IPLD DAG Support:** Fully supports `dag-pb`, `dag-cbor`, and `dag-json` for building decentralized knowledge graphs, versioned datasets, and agent memory chains.
14
+ - **Offline Data Bundles (CAR):** Export and import full or partial DAGs as Content Addressable aRchives (`.car`).
15
+ - **IPNS Mutable Pointers:** Publish and resolve cryptographically signed mutable pointers (IPNS).
16
+ - **FastAPI HTTP Daemon:** A drop-in, Kubo-compatible HTTP API exposing `/api/v0` endpoints for adding files, fetching DAGs, and pinning.
17
+ - **Prometheus Metrics:** Integrated observability for garbage collection, block sizes, and Bitswap traffic.
18
+
19
+ ## Installation
20
+
21
+ py-ipfs-lite uses `uv` for dependency management.
22
+
23
+ ```bash
24
+ # Clone the repository
25
+ git clone https://github.com/IPFS-Meshkit/py-ipfs-lite.git
26
+ cd py-ipfs-lite
27
+
28
+ # Install dependencies using uv
29
+ uv sync
30
+ ```
31
+
32
+ ## Quickstart
33
+
34
+ ### 1. The Python SDK (Embedded Peer)
35
+
36
+ You can run an IPFS peer directly inside your Python application using `trio`:
37
+
38
+ ```python
39
+ import trio
40
+ from py_ipfs_lite.peer import Peer
41
+ from py_ipfs_lite.config import Config
42
+
43
+ async def main():
44
+ # Start an ephemeral in-memory peer
45
+ peer = Peer(Config(blockstore_type="memory"), listen_addrs=["/ip4/127.0.0.1/tcp/0"])
46
+ await peer.start()
47
+
48
+ # Add a file
49
+ cid = await peer.add_file("/path/to/my/file.txt")
50
+ print(f"Added file with CID: {cid}")
51
+
52
+ # Build an IPLD DAG
53
+ node_cid = await peer.add_node({"title": "Hello World", "author": "py-ipfs-lite"}, codec="dag-cbor")
54
+ print(f"Added DAG node with CID: {node_cid}")
55
+
56
+ # Publish to IPNS
57
+ ipns_name = await peer.publish_name(f"/ipfs/{node_cid}")
58
+ print(f"Published to IPNS: {ipns_name}")
59
+
60
+ await peer.close()
61
+
62
+ if __name__ == "__main__":
63
+ trio.run(main)
64
+ ```
65
+
66
+ ### 2. The CLI Daemon & HTTP API
67
+
68
+ You can spin up `py-ipfs-lite` as a standalone daemon that provides a Kubo-compatible HTTP API.
69
+
70
+ ```bash
71
+ # Run the daemon on port 4001, exposing the HTTP API on port 5001
72
+ uv run py-ipfs-lite daemon --api --api-port 5001
73
+ ```
74
+
75
+ Then you can use the standard HTTP API to interact with it:
76
+
77
+ ```bash
78
+ # Add a file
79
+ curl -X POST -F file=@test.txt http://127.0.0.1:5001/api/v0/add
80
+
81
+ # Fetch an IPLD node
82
+ curl -X POST "http://127.0.0.1:5001/api/v0/dag/get?arg=bafy..."
83
+ ```
84
+
85
+ ## What's Next
86
+
87
+ | I want to… | Go to… |
88
+ | --------------------------------------------------------------- | ------------------------------------------------------------------------------ |
89
+ | Understand how `py-ipfs-lite` is structured internally | [docs/architecture.md](docs/architecture.md) |
90
+ | Build verifiable AI agent memory / RAG pipelines | [docs/guides/ai-agents-and-rag.md](docs/guides/ai-agents-and-rag.md) |
91
+ | Export a DAG as a CAR file for Filecoin storage | [docs/guides/car-files-and-filecoin.md](docs/guides/car-files-and-filecoin.md) |
92
+ | Use IPNS mutable pointers and understand the trust model | [docs/guides/ipns.md](docs/guides/ipns.md) |
93
+ | Interoperate with a live Kubo daemon over Bitswap | [docs/guides/interop-with-kubo.md](docs/guides/interop-with-kubo.md) |
94
+ | See the full list of all 21 examples with one-line descriptions | [docs/reference/examples-index.md](docs/reference/examples-index.md) |
95
+ | Browse all documentation | [docs/index.md](docs/index.md) |
96
+
97
+ ## License
98
+
99
+ MIT License
@@ -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"
@@ -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))