Quickstart

Let's dive into iroh by building a simple peer-to-peer file transfer tool in rust!

What we'll build

At the end we should be able to transfer a file from one device by running this:

$ cargo run -- send ./file.txt
Indexing file.
File analyzed. Fetch this file by running:
cargo run -- receive blobabvojvy[...] file.txt

And then fetch it on any other device like so:

$ cargo run -- receive blobabvojvy[...] file.txt
Starting download.
Finished download.
Copying to destination.
Finished copying.
Shutting down.

In this guide we'll be omitting the import statements required to get this working. If you're ever confused about what to import, take a look at the imports in the complete example.

Get set up

We'll assume you've set up rust and cargo on your machine.

Initialize a new project by running cargo init file-transfer, then cd file-transfer and install all the packages we're going to use: cargo add iroh iroh-blobs tokio anyhow.

From here on we'll be working inside the src/main.rs file.

Create an iroh::Endpoint

To start interacting with other iroh nodes, we need to build an iroh::Endpoint. This is what manages the possibly changing network underneath, maintains a connection to the closest relay, and finds ways to address devices by NodeId.

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Create an endpoint, it allows creating and accepting
    // connections in the iroh p2p world
    let endpoint = Endpoint::builder().discovery_n0().bind().await?;

    // ...

    Ok(())
}

There we go, this is all we need to open connections or accept them.

Using an existing protocol: iroh-blobs

Instead of writing our own protocol from scratch, let's use iroh-blobs, which already does what we want: It loads files from your file system and provides a protocol for seekable, resumable downloads of these files.

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Create an endpoint, it allows creating and accepting
    // connections in the iroh p2p world
    let endpoint = Endpoint::builder().discovery_n0().bind().await?;

    // We initialize an in-memory backing store for iroh-blobs
    let store = MemStore::new();
    // Then we initialize a struct that can accept blobs requests over iroh connections
    let blobs = Blobs::new(&store, endpoint.clone(), None);

    // ...

    Ok(())
}

With these two lines, we've initialized iroh-blobs and gave it access to our Endpoint.

At this point what we want to do depends on whether we want to accept incoming iroh connections from the network or create outbound iroh connections to other nodes. Which one we want to do depends on if the executable was called with send as an argument or receive, so let's parse these two options out from the CLI arguments and match on them:

// Grab all passed in arguments, the first one is the binary itself, so we skip it.
let args: Vec<String> = std::env::args().skip(1).collect();
// Convert to &str, so we can pattern-match easily:
let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();

match arg_refs.as_slice() {
    ["send", filename] => {
        todo!();
    }
    ["receive", ticket, filename] => {
        todo!();
    }
    _ => {
        println!("Couldn't parse command line arguments: {args:?}");
        println!("Usage:");
        println!("    # to send:");
        println!("    cargo run --example transfer -- send [FILE]");
        println!("    # this will print a ticket.");
        println!();
        println!("    # to receive:");
        println!("    cargo run --example transfer -- receive [TICKET] [FILE]");
    }
}

We're also going to print some simple help text when there's no arguments or we can't parse them.

What's left to do now is fill in the two todo!()s!

Getting ready to send

If we want to make a file available over the network with iroh-blobs, we first need to hash this file.

let filename: PathBuf = filename.parse()?;
let abs_path = std::path::absolute(&filename)?;

println!("Hashing file.");

// When we import a blob, we get back a "tag" that refers to said blob in the store
// and allows us to control when/if it gets garbage-collected
let tag = store.blobs().add_path(abs_path).await?;

The return value tag contains the final piece of information such that another node can fetch a blob from us.

We'll use a BlobTicket to put the file's BLAKE3 hash and our endpoint's NodeId into a single copy-able string:

let node_id = endpoint.node_id();
let ticket = BlobTicket::new(node_id.into(), tag.hash, tag.format);

println!("File hashed. Fetch this file by running:");
println!(
    "cargo run --example transfer -- receive {ticket} {}",
    filename.display()
);

Now we've imported the file and produced instructions for how to fetch it, but we're actually not yet actively listening for incoming connections yet! (iroh-blobs won't do so unless you specifically tell it to do that.)

For that we'll use iroh's Router. Similar to routers in webserver libraries, it runs a loop accepting incoming connections and routes them to the specific handler. However, instead of handlers being organized by HTTP paths, it routes based on "ALPNs". Read more about ALPNs and the router on the protocol and router documentation pages.

In our case, we only need a single protocol, but constructing a router also takes care of running the accept loop, so that makes our life easier:

// For sending files we build a router that accepts blobs connections & routes them
// to the blobs protocol.
let router = Router::builder(endpoint)
    .accept(iroh_blobs::ALPN, blobs)
    .spawn();

tokio::signal::ctrl_c().await?;

// Gracefully shut down the node
println!("Shutting down.");
router.shutdown().await?;

And as you can see, as a final step we wait for the user to stop the file providing side by hitting Ctrl+C in the console and once they do so, we shut down the router gracefully.

Connecting to the other side to receive

On the connection side, we got the ticket and the path from the CLI arguments and we can parse them into their struct versions.

With them parsed

  • we first construct a Downloader (that can help us coordinate multiple downloads from multiple peers if we'd want to)
  • and then call .download with the information contained in the ticket and wait for the download to finish:
let filename: PathBuf = filename.parse()?;
let abs_path = std::path::absolute(filename)?;
let ticket: BlobTicket = ticket.parse()?;

// For receiving files, we create a "downloader" that allows us to fetch files
// from other nodes via iroh connections
let downloader = store.downloader(&endpoint);

println!("Starting download.");

downloader
    .download(ticket.hash(), Some(ticket.node_addr().node_id))
    .await?;

println!("Finished download.");

As a final step, we'll export the file we just downloaded into our in-memory blobs database to the desired file path:

println!("Copying to destination.");

store.blobs().export(ticket.hash(), abs_path).await?;

println!("Finished copying.");

Before we leave, we'll gracefully shut down our endpoint in the receive branch, too:

// Gracefully shut down the node
println!("Shutting down.");
endpoint.close().await;

That's it!

You've now successfully built a small tool for peer-to-peer file transfers! 🎉

The full example with the very latest version of iroh and iroh-blobs can be viewed on github.

If you're hungry for more, check out