### Install aioipfs Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Install the aioipfs library using pip. ```shell pip install aioipfs ``` -------------------------------- ### Install aioipfs and extras Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Commands to install the base library and optional features like CAR decoding, orjson, or bohort CLI tools. ```shell pip install aioipfs ``` ```shell pip install 'aioipfs[car]' ``` ```shell pip install 'aioipfs[orjson]' ``` ```shell pip install 'aioipfs[bohort]' ``` -------------------------------- ### Install aioipfs with Bohort support Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/bohort.md Install the aioipfs package with the 'bohort' extra to enable the interactive REPL tool. This command installs the necessary dependencies for Bohort. ```shell pip install 'aioipfs[bohort]' ``` -------------------------------- ### Configure and run bohort CLI Source: https://context7.com/cipres/aioipfs/llms.txt Commands for installing, connecting, and managing configurations for the bohort interactive REPL. ```bash # Install with bohort support pip install 'aioipfs[bohort]' # Connect to local node bohort --maddr /ip4/127.0.0.1/tcp/5001 # Connect with Basic Auth bohort --maddr /ip4/127.0.0.1/tcp/5001 --creds 'basic:john:password123' # Connect with Bearer token bohort --maddr /ip4/127.0.0.1/tcp/5001 --creds 'bearer:some-token' # Save node configuration bohort --maddr /ip4/127.0.0.1/tcp/5001 --creds 'basic:john:pass' --save local # Load saved configuration bohort --node local # Disable history bohort --no-history ``` -------------------------------- ### Install aioipfs with CAR support Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Install aioipfs with support for CAR file decoding. ```shell pip install 'aioipfs[car]' ``` -------------------------------- ### Execute commands in bohort REPL Source: https://context7.com/cipres/aioipfs/llms.txt Example commands that can be executed directly within the bohort interactive environment. ```python # Example bohort REPL commands (inside the REPL) await id() print((await id())['AgentVersion']) await bitswap_stat(verbose=True) await files_ls('/') await repo_gc() (await swarm_peers())['Peers'].pop() entries = await add('mydir', recursive=True, cid_version=1) await add_json({'whatever': 12345}) await add_str('bohort') ``` -------------------------------- ### Install aioipfs with orjson support Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Install aioipfs with the orjson library for faster JSON decoding. ```shell pip install 'aioipfs[orjson]' ``` -------------------------------- ### GET /core/get Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Downloads IPFS objects from the network. ```APIDOC ## GET /core/get ### Description Downloads IPFS objects from the network to a specified directory. ### Method GET ### Endpoint client.core.get(cid, dstdir) ### Parameters #### Query Parameters - **cid** (string) - Required - The Content Identifier of the object to download. - **dstdir** (string) - Optional - The destination directory for the downloaded object. ``` -------------------------------- ### GET /core/ls Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Lists the contents of an IPFS path or CID. ```APIDOC ## GET /core/ls ### Description Lists the directory structure or contents of a given path or CID. ### Method GET ### Endpoint client.core.ls(path) ### Parameters #### Query Parameters - **path** (string) - Required - The IPFS path or CID to list. ``` -------------------------------- ### Manage IPLD DAG Nodes and CAR Files Source: https://context7.com/cipres/aioipfs/llms.txt Covers putting, getting, resolving, and exporting/importing DAG nodes and CAR archives. ```python import aioipfs import asyncio from pathlib import Path async def dag_operations(): async with aioipfs.AsyncIPFS() as client: # Put a DAG node from a JSON file result = await client.dag.put( 'data.json', store_codec='dag-cbor', input_codec='dag-json', pin=True ) cid = result['Cid']['/'] print(f"DAG CID: {cid}") # Get a DAG node data = await client.dag.get(cid) print(f"DAG content: {data}") # Get with specific output codec data = await client.dag.get(cid, output_codec='dag-json') # Resolve an IPLD path resolved = await client.dag.resolve(f'{cid}/some/path') print(f"Resolved: {resolved}") # Get DAG statistics (async generator for progress) async for stat in client.dag.stat(cid): print(f"DAG stats: {stat}") # Export DAG to CAR file await client.dag.export(cid, output_path=Path('backup.car')) # Export DAG as raw bytes car_bytes = await client.dag.export(cid) # Export and extract to directory (requires ipfs-car-decoder) await client.dag.export_to_directory(cid, Path('extracted/')) # Import a CAR file result = await client.dag.car_import( 'backup.car', pin_roots=True, stats=True ) print(f"Imported roots: {result}") # Import CAR from bytes with open('archive.car', 'rb') as f: car_data = f.read() result = await client.dag.car_import(car_data, pin_roots=True) asyncio.run(dag_operations()) ``` -------------------------------- ### GET /core/cat Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Retrieves the raw data of an IPFS object. ```APIDOC ## GET /core/cat ### Description Fetches the raw data associated with a specific CID. ### Method GET ### Endpoint client.core.cat(cid) ### Parameters #### Query Parameters - **cid** (string) - Required - The Content Identifier of the object. ``` -------------------------------- ### GET /core/id Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Retrieves information about the IPFS node. ```APIDOC ## GET /core/id ### Description Returns identity and configuration information about the current IPFS node. ### Method GET ### Endpoint client.core.id() ``` -------------------------------- ### Get an IPFS resource Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Asynchronously retrieve a file from IPFS using its CID and save it to a directory. Ensure the event loop is managed. ```python import sys import asyncio import aioipfs async def get(cid: str): client = aioipfs.AsyncIPFS() await client.get(cid, dstdir='.') await client.close() loop = asyncio.get_event_loop() loop.run_until_complete(get(sys.argv[1])) ``` -------------------------------- ### Perform Raw Block Operations Source: https://context7.com/cipres/aioipfs/llms.txt Provides methods for putting, getting, and removing raw IPFS blocks, as well as retrieving block statistics. ```python import aioipfs import asyncio async def block_operations(): async with aioipfs.AsyncIPFS() as client: # Put a raw block result = await client.block.put( 'data.bin', mhtype='sha2-256', pin=True ) cid = result['Key'] print(f"Block CID: {cid}") # Get block statistics stats = await client.block.stat(cid) print(f"Size: {stats['Size']} bytes") # Get raw block data data = await client.block.get(cid) print(f"Block data: {len(data)} bytes") # Remove a block result = await client.block.rm(cid, force=True) print(f"Removed: {result}") asyncio.run(block_operations()) ``` -------------------------------- ### Get IPFS node information Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Retrieve information about the local IPFS node using `api.CoreAPI.id()`. ```python info = await client.core.id() ``` -------------------------------- ### Get raw data of an IPFS object Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Use `api.CoreAPI.cat()` to retrieve the raw data of an IPFS object identified by its CID. ```python bytes = await client.core.cat(cid) ``` -------------------------------- ### Initialize AsyncIPFS Client Source: https://context7.com/cipres/aioipfs/llms.txt Demonstrates various connection methods including multiaddr, host/port, HTTPS, and authentication configurations. Using the client as an async context manager is recommended for automatic resource cleanup. ```python import aioipfs import asyncio async def main(): # Connect using multiaddr (recommended) client = aioipfs.AsyncIPFS(maddr='/ip4/127.0.0.1/tcp/5001') # Connect using host and port client = aioipfs.AsyncIPFS(host='localhost', port=5001) # Connect with HTTPS client = aioipfs.AsyncIPFS(maddr='/ip4/10.0.1.4/tcp/5001/https') # Connect with Basic Auth credentials client = aioipfs.AsyncIPFS( maddr='/ip4/127.0.0.1/tcp/5001', auth=aioipfs.BasicAuth('username', 'password123') ) # Connect with Bearer token authentication client = aioipfs.AsyncIPFS( maddr='/ip4/127.0.0.1/tcp/5001', auth=aioipfs.BearerAuth('my-secret-token') ) # Use as async context manager (recommended) async with aioipfs.AsyncIPFS() as client: info = await client.core.id() print(f"Node ID: {info['ID']}") print(f"Agent Version: {info['AgentVersion']}") # Manual cleanup client = aioipfs.AsyncIPFS() try: info = await client.core.id() finally: await client.close() asyncio.run(main()) ``` -------------------------------- ### Initialize AsyncIPFS client Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Configure the client using multiaddr, host/port, or scheme parameters. ```python import aioipfs client = aioipfs.AsyncIPFS(maddr='/ip4/127.0.0.1/tcp/5001') client = aioipfs.AsyncIPFS(maddr='/dns4/localhost/tcp/5001') ``` ```python client = aioipfs.AsyncIPFS() client = aioipfs.AsyncIPFS(host='10.0.12.3', port=5003) ``` ```python client = aioipfs.AsyncIPFS(maddr='/ip4/10.0.1.4/tcp/5001/https') client = aioipfs.AsyncIPFS(host='10.0.1.4', scheme='https') ``` -------------------------------- ### Instantiate AsyncIPFS with Basic Authentication Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Create an AsyncIPFS client instance with basic authentication credentials. ```python client = aioipfs.AsyncIPFS(auth=aioipfs.BasicAuth('john', 'password123')) ``` -------------------------------- ### Instantiate AsyncIPFS with host and port Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Create an AsyncIPFS client instance by specifying host and port separately. ```python client = aioipfs.AsyncIPFS(host='localhost', port=5001) ``` ```python client = aioipfs.AsyncIPFS(host='::1', port=5201) ``` -------------------------------- ### Use async context manager Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Manage the client lifecycle using an asynchronous context manager. ```python async with aioipfs.AsyncIPFS() as client: async for reply in client.ping(peer_id): ... ``` -------------------------------- ### Instantiate AsyncIPFS with Multiaddr string Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Create an AsyncIPFS client instance using a multiaddr string. ```python client = aioipfs.AsyncIPFS(maddr='/ip4/127.0.0.1/tcp/5001') ``` ```python client = aioipfs.AsyncIPFS(maddr='/dns4/localhost/tcp/5001') ``` -------------------------------- ### Perform MFS Operations with aioipfs Source: https://context7.com/cipres/aioipfs/llms.txt Demonstrates creating directories, writing, reading, listing, copying, moving, removing, flushing, and changing CID versions within the IPFS Mutable File System. Requires an active aioipfs client connection. ```python import aioipfs import asyncio async def mfs_operations(): async with aioipfs.AsyncIPFS() as client: # Create directories await client.files.mkdir('/documents', parents=True) await client.files.mkdir('/documents/2024', cid_version=1) # Write data to a file await client.files.write( '/documents/hello.txt', b'Hello, World!', create=True, truncate=True ) # Write from a local file path await client.files.write( '/documents/config.json', 'local-config.json', create=True, parents=True ) # List directory contents listing = await client.files.ls('/') for entry in listing['Entries']: print(f"{entry['Name']} - {entry['Hash']} ({entry['Size']} bytes)") # List with detailed info listing = await client.files.ls('/documents', long=True) # Read file contents data = await client.files.read('/documents/hello.txt') print(f"Content: {data.decode()}") # Read with offset and count data = await client.files.read('/documents/hello.txt', offset=7, count=5) # Get file/directory stats stats = await client.files.stat('/documents/hello.txt') print(f"CID: {stats['Hash']}, Size: {stats['Size']}") # Copy IPFS content into MFS cid = 'QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG' await client.files.cp(f'/ipfs/{cid}', '/documents/imported') # Move/rename files await client.files.mv('/documents/hello.txt', '/documents/greeting.txt') # Remove files/directories await client.files.rm('/documents/old-file.txt') await client.files.rm('/documents/old-folder', recursive=True) # Flush changes to disk result = await client.files.flush('/documents') print(f"Flushed CID: {result['Cid']}") # Change CID version for a path await client.files.chcid('/documents', cidversion=1) asyncio.run(mfs_operations()) ``` -------------------------------- ### Configure client connection settings Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Set maximum HTTP connections and read timeouts for the client instance. ```python client = aioipfs.AsyncIPFS(host='localhost', port=5008, conns_max=20) client = aioipfs.AsyncIPFS(host='localhost', port=5008, read_timeout=30) ``` -------------------------------- ### Implement PubSub Messaging with aioipfs Source: https://context7.com/cipres/aioipfs/llms.txt Demonstrates subscribing to topics, publishing messages, and managing subscriptions using the PubSub API. ```python import aioipfs import asyncio async def pubsub_subscriber(): """Subscribe to a topic and receive messages""" async with aioipfs.AsyncIPFS() as client: topic = 'my-application-events' print(f"Subscribing to topic: {topic}") try: async for message in client.pubsub.sub(topic, discover=True): sender = message['from'] data = message['data'].decode('utf-8') topics = message['topicIDs'] print(f"From: {sender}") print(f"Data: {data}") print(f"Topics: {topics}") print("---") except aioipfs.APIError as e: print(f"PubSub error: {e.message}") async def pubsub_publisher(): """Publish messages to a topic""" async with aioipfs.AsyncIPFS() as client: topic = 'my-application-events' # Publish string message await client.pubsub.pub(topic, 'Hello from aioipfs!') # Publish bytes await client.pubsub.pub(topic, b'\x00\x01\x02\x03') # List subscribed topics topics = await client.pubsub.ls() print(f"Subscribed topics: {topics['Strings']}") # List peers on a topic peers = await client.pubsub.peers(topic) print(f"Peers on {topic}: {peers}") async def pubsub_echo_service(): """Example echo service using pubsub""" async with aioipfs.AsyncIPFS() as client: async for message in client.pubsub.sub('echo'): print(f"Received: {message['data']}") # Echo back to another topic await client.pubsub.pub('echo-response', message['data']) # Run subscriber and publisher concurrently async def main(): await asyncio.gather( pubsub_subscriber(), pubsub_publisher() ) asyncio.run(main()) ``` -------------------------------- ### Instantiate AsyncIPFS with Multiaddr object Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Create an AsyncIPFS client instance using a multiaddr.Multiaddr object. ```python from multiaddr import Multiaddr client = aioipfs.AsyncIPFS(maddr=Multiaddr('/ip4/127.0.0.1/tcp/5001')) ``` -------------------------------- ### Add files using async list comprehension Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Generate a list of CIDs by adding files to IPFS using an asynchronous list comprehension. ```python cids = [entry['Hash'] async for entry in client.add(dir_path)] ``` -------------------------------- ### Save and load Bohort node configurations Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/bohort.md Save the current configuration parameters for a node using the '--save' option. Load previously saved node configurations using '--node' or '--load'. ```shell bohort --maddr /ip4/127.0.0.1/tcp/5001 --creds 'basic:john:password123' --save local ``` ```shell bohort --node local ``` -------------------------------- ### Instantiate AsyncIPFS with Bearer Token Authentication Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Create an AsyncIPFS client instance with bearer token authentication. ```python client = aioipfs.AsyncIPFS(auth=aioipfs.BearerAuth('my-secret-token')) ``` -------------------------------- ### Configure RPC authentication Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Pass authentication credentials during initialization or update them on an existing client instance. ```python client = aioipfs.AsyncIPFS(auth=aioipfs.BasicAuth('john', 'password123')) client = aioipfs.AsyncIPFS(auth=aioipfs.BearerAuth('my-secret-token')) ``` ```python client.auth = aioipfs.BasicAuth('alice', 'anotherpass') client.auth = None ``` -------------------------------- ### Run Bohort connecting to a kubo node Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/bohort.md Connect to a kubo node by specifying the multiaddr of the RPC service. If no credentials are provided, the default RPC multiaddr will be used. ```shell bohort --maddr /ip4/127.0.0.1/tcp/5001 ``` ```shell bohort --maddr /ip4/127.0.0.1/tcp/5001 --creds 'basic:john:password123' ``` ```shell bohort --maddr /ip4/127.0.0.1/tcp/5001 --creds 'bearer:some-token' ``` -------------------------------- ### Subscribe and publish to Pubsub topic Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Asynchronously subscribe to a Pubsub topic, receive messages, and publish received data back to the same topic. Uses 'async with' for client management. ```python async def pubsub_serve(topic: str): async with aioipfs.AsyncIPFS() as cli: async for message in cli.pubsub.sub(topic): print('Received message from', message['from']) await cli.pubsub.pub(topic, message['data']) ``` -------------------------------- ### Open and Manage P2P Listener Source: https://context7.com/cipres/aioipfs/llms.txt Opens a P2P listener for a custom protocol, lists active listeners, and then closes the listener. Ensure the necessary imports are present. ```python import aioipfs import asyncio import aiohttp async def p2p_service_example(): async with aioipfs.AsyncIPFS() as client: # Open a P2P listener await client.p2p.listener_open( '/x/myservice', '/ip4/127.0.0.1/tcp/8080', allow_custom_protocol=True, report_peerid=True ) # List active listeners listeners = await client.p2p.listener_ls(headers=True) for listener in listeners.get('Listeners', []): print(f"Protocol: {listener['Protocol']}") print(f"Listen: {listener['ListenAddress']}") print(f"Target: {listener['TargetAddress']}") # Close listener await client.p2p.listener_close('/x/myservice') asyncio.run(p2p_service_example()) ``` -------------------------------- ### Dial a P2P service Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Use `client.p2p.dial_service` as an async context manager to establish a connection to a P2P service. It provides the multiaddr and allows access to host and port information. ```python async with client.p2p.dial_service( '12D3KooWRd9Pt1Fri5F4W32uhGm8fBG4pvxEiFwgMru85zmajxcd', '/x/myservice') as ctx: if ctx.failed: # Dialing failed raise Exception('....') # The multiaddr is available as 'ctx.maddr' print(f'Multiaddr': {ctx.maddr}') # The host/port can be retrieved via maddr_host and maddr_port print(f'Host: {ctx.maddr_host}, port: {ctx.maddr_port}') ``` -------------------------------- ### Export UnixFS DAG to directory Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Export a UnixFS DAG to a CAR and unpack it to a local directory. ```python from pathlib import Path import aioipfs async with aioipfs.AsyncIPFS() as client: await client.dag.export_to_directory( 'bafybeiawyahkjt4kzrzc3bjylqupniukbpnbvys7pt536c64gxg7onq36m', Path('car-contents') ) ``` -------------------------------- ### Add file to MFS Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Import a file and link it into the MFS in a single RPC call. ```python async for added in client.core.add('file1.txt', to_files='/file1.txt'): print(added['Hash']) ``` -------------------------------- ### Manage Swarm Network and Peers with aioipfs Source: https://context7.com/cipres/aioipfs/llms.txt Illustrates listing connected peers, retrieving addresses, connecting to, and disconnecting from peers, managing address filters, and configuring peering settings. Requires an active aioipfs client connection. ```python import aioipfs import asyncio async def swarm_operations(): async with aioipfs.AsyncIPFS() as client: # List connected peers peers = await client.swarm.peers(verbose=True, latency=True) for peer in peers['Peers']: print(f"Peer: {peer['Peer']}") print(f" Address: {peer['Addr']}") print(f" Latency: {peer.get('Latency', 'N/A')}") # Get all known addresses addrs = await client.swarm.addrs() # Get local addresses local = await client.swarm.addrs_local(id=True) print(f"Local addresses: {local['Strings']}") # Get listening addresses listen = await client.swarm.addrs_listen() print(f"Listening on: {listen['Strings']}") # Connect to a peer peer_addr = '/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ' result = await client.swarm.connect(peer_addr) print(f"Connected: {result}") # Disconnect from a peer await client.swarm.disconnect(peer_addr) # Add address filter await client.swarm.filters_add('/ip4/192.168.0.0/ipcidr/16') # Remove address filter await client.swarm.filters_rm('/ip4/192.168.0.0/ipcidr/16') # Peering subsystem - add persistent peers await client.swarm.peering.add(peer_addr) # List peering peers peering = await client.swarm.peering.ls() print(f"Peering peers: {peering}") # Remove from peering await client.swarm.peering.rm('QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ') # Get resource manager stats resources = await client.swarm.resources() print(f"Resource usage: {resources}") asyncio.run(swarm_operations()) ``` -------------------------------- ### Export and Import IPNS Keys Source: https://context7.com/cipres/aioipfs/llms.txt Demonstrates exporting an existing IPNS key to a file with a specific format and then importing it back under a new name. Ensure the format is compatible. ```python import aioipfs import asyncio async def key_management(): async with aioipfs.AsyncIPFS() as client: # Export a key exported = await client.key.export( 'my-website', format='libp2p-protobuf-cleartext' ) # Import a key imported = await client.key.key_import( 'exported-key.key', 'imported-name', format='libp2p-protobuf-cleartext' ) asyncio.run(key_management()) ``` -------------------------------- ### Interact with aioipfs RPC methods in Bohort Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/bohort.md Make RPC calls to the kubo node from the Bohort REPL by using the 'await' keyword before the API coroutine. Results are pretty-printed if not stored in a variable. ```shell await id() ``` ```shell print((await id())['AgentVersion']) ``` ```shell await bitswap_stat(verbose=True) ``` ```shell await files_ls('/') ``` ```shell await repo_gc() ``` ```shell (await swarm_peers())['Peers'].pop() ``` ```shell entries = await add('mydir', recursive=True, cid_version=1) ``` ```shell await add_json({'whatever': 12345}) ``` ```shell await add_str('bohort') ``` -------------------------------- ### Configure default RPC method parameters Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/bohort.md Set default keyword arguments for specific RPC methods in the Bohort configuration file. These defaults will be used unless overridden when calling the method. ```yaml rpc_methods: core.add: defaults: recursive: true cid_version: 1 core.add_str: defaults: cid_version: 1 key.gen: defaults: type: 'ed25519' size: 4096 ``` -------------------------------- ### POST /pin/add Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Pins an IPFS object to the local node. ```APIDOC ## POST /pin/add ### Description Adds a CID or IPFS path to the local pin set. ### Method POST ### Endpoint client.pin.add(cid) ### Parameters #### Request Body - **cid** (string) - Required - The CID or path to pin. ``` -------------------------------- ### Configure REPL settings Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/bohort.md Customize the behavior and appearance of the Bohort REPL interface using various settings. These settings control aspects like cursor shape, prompt colors, and completion visualization. ```yaml repl: cursor_shape: Blink block input_prompt_color: ansigreen output_prompt_color: ansiyellow completion_visualisation: POP_UP color_scheme: default show_signature: true enable_history_search: true enable_auto_suggest: true complete_while_typing: false confirm_exit: false ``` -------------------------------- ### Stream Dial and Manage Streams Source: https://context7.com/cipres/aioipfs/llms.txt Initiates a stream dial, lists active streams, and demonstrates closing specific or all streams. Ensure stream IDs are correctly managed. ```python import aioipfs import asyncio async def p2p_service_example(): async with aioipfs.AsyncIPFS() as client: # Stream dial (forward) result = await client.p2p.stream_dial( '/x/otherservice', '/ip4/127.0.0.1/tcp/9000', '/ipfs/QmPeerID' ) # List active streams streams = await client.p2p.stream_ls(headers=True) # Close specific stream await client.p2p.stream_close(stream_id='stream-id') # Close all streams await client.p2p.stream_close(all=True) asyncio.run(p2p_service_example()) ``` -------------------------------- ### Core API - Adding Files Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Methods for adding files, bytes, and strings to the IPFS repository using the Core API. ```APIDOC ## Core API - Adding Files This section details how to add various types of data to IPFS using the `aioipfs.AsyncIPFS.core` API. ### `aioipfs.AsyncIPFS.core.add(source, recursive=False, wrap_with_directory=False, to_files=None, ignore_rules_path=None)` Adds files or directories to the IPFS repository. - **Parameters**: - `source` (str or list): Path to a file/directory or a list of paths/data to add. - `recursive` (bool): If True, recursively adds directories. Defaults to False. - `wrap_with_directory` (bool): If True, wraps the added items in a directory. Defaults to False. - `to_files` (str, optional): Path in the MFS to link the added object to. - `ignore_rules_path` (str, optional): Path to a file containing ignore rules (e.g., .gitignore). - **Returns**: An async generator yielding dictionaries with 'Name', 'Hash', and 'Size' keys for each added item. ### `aioipfs.AsyncIPFS.core.add_bytes(data, to_files=None)` Adds raw bytes to the IPFS repository. - **Parameters**: - `data` (bytes): The bytes data to add. - `to_files` (str, optional): Path in the MFS to link the added object to. - **Returns**: A dictionary containing 'Name', 'Hash', and 'Size' of the added object. ### `aioipfs.AsyncIPFS.core.add_str(data, to_files=None)` Adds a UTF-8 string to the IPFS repository. - **Parameters**: - `data` (str): The string data to add. - `to_files` (str, optional): Path in the MFS to link the added object to. - **Returns**: A dictionary containing 'Name', 'Hash', and 'Size' of the added object. ### Request Example: Adding a file recursively with ignore rules ```python async for added in client.core.add('directory', recursive=True, ignore_rules_path='.ipfsignore'): print(added['Hash']) ``` ### Request Example: Adding bytes and linking to MFS ```python entry = await client.core.add_bytes(b'ABCD', to_files='/abcd') ``` ### Request Example: Adding a string and linking to MFS ```python entry = await client.core.add_str('ABCD', to_files='/abcd') ``` ``` -------------------------------- ### Download IPFS objects Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Use `api.CoreAPI.get()` to download IPFS objects. You can specify a destination directory. ```python await client.core.get('QmRGqvWK44oWu8re5whp43P2M7j5XEDLHmPB3wncYFmCNg') ``` ```python await client.core.get('QmRGqvWK44oWu8re5whp43P2M7j5XEDLHmPB3wncYFmCNg', dstdir='/tmp') ``` -------------------------------- ### Dial P2P Service and Make HTTP Request Source: https://context7.com/cipres/aioipfs/llms.txt Demonstrates dialing a remote P2P service using a peer ID and protocol, then making an HTTP request to it. Handles connection failures. ```python import aioipfs import asyncio import aiohttp async def p2p_service_example(): async with aioipfs.AsyncIPFS() as client: # Dial a remote P2P service (using context manager) peer_id = '12D3KooWRd9Pt1Fri5F4W32uhGm8fBG4pvxEiFwgMru85zmajxcd' async with client.p2p.dial_service(peer_id, '/x/myservice') as ctx: if ctx.failed: print("Failed to dial service") else: print(f"Connected via {ctx.maddr}") print(f"Host: {ctx.maddr_host}, Port: {ctx.maddr_port}") # Make HTTP request to the P2P service async with aiohttp.ClientSession() as session: url = ctx.httpUrl('/api/data') async with session.get(url) as resp: data = await resp.json() print(f"Response: {data}") asyncio.run(p2p_service_example()) ``` -------------------------------- ### Retrieve Content from IPFS Source: https://context7.com/cipres/aioipfs/llms.txt Use the core API to download files, read raw data, and list directory contents. Supports downloading to specific directories, with compression, and progress tracking. Raw data can be retrieved using 'cat' with optional offset and length. ```python import aioipfs import asyncio async def get_content_example(): async with aioipfs.AsyncIPFS() as client: cid = 'QmRGqvWK44oWu8re5whp43P2M7j5XEDLHmPB3wncYFmCNg' # Download file/directory to current directory await client.core.get(cid) # Download to specific directory await client.core.get(cid, dstdir='/tmp/ipfs-downloads') # Download with compression await client.core.get(cid, compress=True, compression_level=6) # Download with progress tracking (async generator) async for status, bytes_read, total_bytes in client.core.getgen(cid): if status == 0: progress = (bytes_read / total_bytes) * 100 if total_bytes else 0 print(f"Downloading: {progress:.1f}%") elif status == 1: print("Download complete!") elif status == -1: print("Download failed!") # Read raw bytes (cat) data = await client.core.cat(cid) print(f"Content: {data.decode('utf-8')}") # Read with offset and length data = await client.core.cat(cid, offset=10, length=100) # List directory contents listing = await client.core.ls(cid) for item in listing['Objects'][0]['Links']: print(f"{item['Name']}: {item['Hash']} ({item['Size']} bytes)") # Stream directory listing async for entry in client.core.ls_streamed(cid): print(f"Entry: {entry}") asyncio.run(get_content_example()) ``` -------------------------------- ### Add files with ignore rules Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Import a directory while excluding files based on an ignore file. ```python async for added in client.core.add('directory', recursive=True, ignore_rules_path='.ipfsignore'): print(added['Hash']) ``` -------------------------------- ### List contents of a path or CID Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Use `api.CoreAPI.ls()` to list the contents of a given IPFS path or CID. ```python listing = await client.core.ls(path) ``` -------------------------------- ### Publish and Resolve IPNS Names Source: https://context7.com/cipres/aioipfs/llms.txt Demonstrates publishing content to IPNS using keys or offline mode, and resolving names recursively or via streams. ```python import aioipfs import asyncio async def ipns_operations(): async with aioipfs.AsyncIPFS() as client: cid = 'QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG' # Publish to IPNS using default key (self) result = await client.name.publish( f'/ipfs/{cid}', lifetime='24h', ttl=3600 ) print(f"Published: {result['Name']} -> {result['Value']}") # Publish using a specific key result = await client.name.publish( f'/ipfs/{cid}', key='myblog', lifetime='48h' ) # Publish offline (save locally without broadcasting) result = await client.name.publish( f'/ipfs/{cid}', allow_offline=True ) # Resolve an IPNS name resolved = await client.name.resolve(result['Name']) print(f"Resolved to: {resolved['Path']}") # Resolve recursively resolved = await client.name.resolve( '/ipns/ipfs.io', recursive=True, nocache=False ) # Resolve with streaming (async generator) async for entry in client.name.resolve_stream('/ipns/ipfs.io'): print(f"Resolution step: {entry}") # IPNS pubsub operations state = await client.name.pubsub.state() print(f"IPNS pubsub enabled: {state['Enabled']}") subs = await client.name.pubsub.subs() print(f"IPNS subscriptions: {subs}") asyncio.run(ipns_operations()) ``` -------------------------------- ### Add files to IPFS Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Add files or directories to the IPFS repository using the CoreAPI. ```python async for added in client.core.add('file1.txt', '/usr/local/src', recursive=True): print(added['Hash']) async for added in client.core.add(['one', 'two', 'three'], wrap_with_directory=True): ... cids = [entry['Hash'] async for entry in client.add(dir_path)] ``` -------------------------------- ### Add Files and Data to IPFS Source: https://context7.com/cipres/aioipfs/llms.txt Covers adding files, directories, raw bytes, strings, and JSON objects to IPFS. The add() method functions as an async generator for progress tracking. ```python import aioipfs import asyncio async def add_files_example(): async with aioipfs.AsyncIPFS() as client: # Add a single file async for added in client.core.add('document.txt'): print(f"Added: {added['Name']} - CID: {added['Hash']}") # Add multiple files async for added in client.core.add('file1.txt', 'file2.txt', 'file3.txt'): print(f"Added: {added['Name']} - CID: {added['Hash']}") # Add a directory recursively async for added in client.core.add('/path/to/directory', recursive=True): print(f"Added: {added['Name']} - CID: {added['Hash']} - Size: {added['Size']}") # Add with CIDv1 and wrap in directory async for added in client.core.add( 'myfile.txt', cid_version=1, wrap_with_directory=True, pin=True ): print(f"Added: {added['Hash']}") # Add and link to MFS (Mutable File System) async for added in client.core.add('config.json', to_files='/config.json'): print(f"Added to MFS: {added['Hash']}") # Add bytes directly entry = await client.core.add_bytes(b'Hello, IPFS!') print(f"Bytes CID: {entry['Hash']}") # Add string data entry = await client.core.add_str('Hello World!', cid_version=1) print(f"String CID: {entry['Hash']}") # Add JSON object entry = await client.core.add_json({'name': 'test', 'value': 42}) print(f"JSON CID: {entry['Hash']}") # Add with .gitignore/.ipfsignore support async for added in client.core.add( 'project/', recursive=True, ignore_rules_path='.ipfsignore' ): print(f"Added: {added['Name']}") asyncio.run(add_files_example()) ``` -------------------------------- ### Dial a P2P service Source: https://gitlab.com/cipres/aioipfs/-/blob/master/README.rst Establish a connection to a P2P service using a client. The 'dial_service' context manager provides connection details. ```python async with aioipfs.AsyncIPFS() as client: async with client.p2p.dial_service(peer_id, '/x/echo') as dial: print(f'Dial host: {dial.maddr_host}, port: {dial.maddr_port}') # Connect to the service now .... ``` -------------------------------- ### Manage Repository and Node Statistics Source: https://context7.com/cipres/aioipfs/llms.txt Covers repository maintenance tasks like garbage collection and integrity verification, alongside node bandwidth and version reporting. ```python import aioipfs import asyncio async def repo_and_stats(): async with aioipfs.AsyncIPFS() as client: # Get repository statistics stats = await client.repo.stat(human=True) print(f"Repo size: {stats['RepoSize']}") print(f"Storage max: {stats['StorageMax']}") print(f"Num objects: {stats['NumObjects']}") # Verify repository integrity result = await client.repo.verify() print(f"Verification: {result}") # Get repo version version = await client.repo.version() print(f"Repo version: {version['Version']}") # Run garbage collection async for gc_result in client.repo.gc(): if 'Key' in gc_result: print(f"GC'd: {gc_result['Key']}") if 'Error' in gc_result: print(f"GC error: {gc_result['Error']}") # Get bandwidth statistics bw = await client.stats.bw() print(f"Total in: {bw['TotalIn']}, Total out: {bw['TotalOut']}") # Get bitswap statistics bitswap = await client.stats.bitswap() print(f"Blocks received: {bitswap['BlocksReceived']}") # Get IPFS version info version = await client.core.version() print(f"IPFS version: {version['Version']}") print(f"Commit: {version['Commit']}") asyncio.run(repo_and_stats()) ``` -------------------------------- ### Configure RPC method timeouts Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/bohort.md Set a timeout in seconds for specific RPC methods within the Bohort configuration. If an RPC call exceeds this timeout, it will be aborted. ```yaml rpc_methods: core.ls: timeout: 60 ``` -------------------------------- ### Dial a remote HTTP service via P2P Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Dial a remote HTTP service using `client.p2p.dial_service` and access its URL via `ctx.httpUrl()`. Requires `aiohttp` for making HTTP requests. ```python async with client.p2p.dial_service( '12D3KooWRd9Pt1Fri5F4W32uhGm8fBG4pvxEiFwgMru85zmajxcd', '/x/http1') as ctx: async with aiohttp.ClientSession() as sess: async with sess.get(ctx.httpUrl('/')) as resp: print(await resp.read()) ``` -------------------------------- ### Export DAG to CAR Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Export a DAG to a .car file using the DagAPI. ```python from pathlib import Path import aioipfs async with aioipfs.AsyncIPFS() as client: await client.dag.export( 'bafybeiawyahkjt4kzrzc3bjylqupniukbpnbvys7pt536c64gxg7onq36m', output_path=Path('output.car') ) ``` -------------------------------- ### Manage Pinned Content with IPFS Pin API Source: https://context7.com/cipres/aioipfs/llms.txt Utilize the Pin API to pin and unpin content, list pinned items, and manage remote pinning services. Supports progress tracking for pinning operations and allows pinning with custom names. Remote services can be added, listed, and used for pinning. ```python import aioipfs import asyncio async def pinning_example(): async with aioipfs.AsyncIPFS() as client: cid = 'QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG' # Pin content with progress tracking async for pinned in client.pin.add(cid): if 'Progress' in pinned: print(f"Pinning progress: {pinned['Progress']}") if 'Pins' in pinned: print(f"Pinned: {pinned['Pins']}") # Pin with a name async for pinned in client.pin.add(cid, name='my-important-file'): print(f"Pinned with name: {pinned}") # List all pinned objects pinned = await client.pin.ls() for cid, info in pinned['Keys'].items(): print(f"CID: {cid}, Type: {info['Type']}") # List specific pin types direct_pins = await client.pin.ls(pintype='direct') recursive_pins = await client.pin.ls(pintype='recursive') # List with names pinned = await client.pin.ls(names=True) # Unpin content result = await client.pin.rm(cid) print(f"Unpinned: {result['Pins']}") # Update a pin (replace old with new) old_cid = 'Qm...' new_cid = 'Qm...' result = await client.pin.update(old_cid, new_cid) # Verify pins integrity result = await client.pin.verify() # Remote pinning service management await client.pin.remote.service.add( 'pinata', 'https://api.pinata.cloud/psa', 'your-api-key' ) # List remote pinning services services = await client.pin.remote.service.ls(stat=True) # Pin to remote service result = await client.pin.remote.add( service='pinata', objPath=cid, name='my-remote-pin' ) # List remote pins async for pin in client.pin.remote.ls(service='pinata', status=['pinned']): print(f"Remote pin: {pin}") asyncio.run(pinning_example()) ``` -------------------------------- ### Tail IPFS event log Source: https://gitlab.com/cipres/aioipfs/-/blob/master/docs/index.md Access the IPFS event log and stream messages using `client.log.tail()`. Requires importing `pprint` for formatted output. ```python import pprint async for msg in client.log.tail(): print(pprint.pprint(msg)) ``` -------------------------------- ### Dial P2P Service by Endpoint Address Source: https://context7.com/cipres/aioipfs/llms.txt Connects to a P2P service using its full endpoint address. Requires the endpoint string to be correctly formatted. ```python import aioipfs import asyncio async def p2p_service_example(): async with aioipfs.AsyncIPFS() as client: # Dial using endpoint address endpoint = '/p2p/12D3KooWAci7T5tA1ZaxBBREVEdLX5FJkH2GBcgbJGW6LqJtBgOp/x/hello' async with client.p2p.dial_endpoint(endpoint) as ctx: if not ctx.failed: print(f"Dialed endpoint: {ctx.maddr}") asyncio.run(p2p_service_example()) ```