Initial commit: rad-lfs-transfer, a Git LFS custom transfer agent backed by IPFS

Implements the Git LFS custom-transfer-agent protocol (init/upload/download/
terminate over stdin/stdout JSON), storing large file content in a local
IPFS (Kubo) daemon rather than a central server. The oid to CID mapping is
carried in git notes on refs/notes/rad-lfs, keyed by each LFS pointer's own
git blob hash, so it replicates with the repository via normal git sync.

Companion to the rad lfs init / seed / unseed support in the paired
heartwood fork.
This commit is contained in:
Maciek "mab122" Bator 2026-07-14 12:29:36 +02:00
commit fb95fd0c68
9 changed files with 2459 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/target
*.sqlite
.DS_Store

1814
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

17
Cargo.toml Normal file
View File

@ -0,0 +1,17 @@
[package]
name = "radicle-lfs-transfer"
version = "0.1.0"
edition = "2024"
description = "Git LFS custom transfer agent backing large files with IPFS, for Radicle"
license = "MIT OR Apache-2.0"
[[bin]]
name = "rad-lfs-transfer"
path = "src/main.rs"
[dependencies]
anyhow = "1.0.103"
reqwest = { version = "0.13.4", features = ["multipart", "stream", "json", "query"] }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.150"
tokio = { version = "1.52.3", features = ["full"] }

176
LICENSE-APACHE Normal file
View File

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

21
LICENSE-MIT Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 the radicle-lfs-transfer contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

63
README.md Normal file
View File

@ -0,0 +1,63 @@
# radicle-lfs-transfer
A [Git LFS custom transfer agent][custom-transfer] that backs large file storage with
[IPFS](https://ipfs.tech), for use with [Radicle](https://radicle.xyz) repositories.
This is the companion binary for the `rad lfs` support added to a
[fork of `heartwood`](../radicle-heartwood-lfs) (Radicle's core node/CLI). It is not meant to
be invoked directly — `git lfs` spawns it automatically once a repository has been set up with
`rad lfs init`.
[custom-transfer]: https://github.com/git-lfs/git-lfs/blob/main/docs/custom-transfers.md
## How it works
Instead of a shared, seed-hosted LFS server, every peer uses their own local IPFS node:
- On `git add`/`git commit`, a pre-commit hook (installed by `rad lfs init`) adds each staged
LFS-tracked file to your local IPFS daemon, pins it, and records the resulting CID as a git
note (`refs/notes/rad-lfs`) attached to the LFS pointer file's own git blob hash. That notes
ref travels with the repository via Radicle's normal replication, alongside everything else.
- `rad-lfs-transfer` implements the other half: when `git lfs push`/`pull` runs, it's invoked
per-object over stdin/stdout JSON (the standard Git LFS custom-transfer-agent protocol) and:
- **upload**: confirms the object is already pinned in IPFS (it should be, from the
pre-commit hook) or adds it if the hook was bypassed.
- **download**: reconstructs the expected pointer blob hash from the requested oid/size,
looks up its `cid=` note, and fetches the content from your local IPFS daemon (which will
pull it from the wider IPFS network if it isn't local yet).
There is no central server anywhere in this design — see the companion `heartwood` fork's
documentation for the full rationale and how `rad seed`/`rad unseed` tie IPFS pinning to
Radicle's existing seeding lifecycle.
## Requirements
- Only needed **at runtime**, not to build or install this binary: a local IPFS (Kubo) daemon
reachable at `http://127.0.0.1:5001` (or wherever `KUBO_API_URL` points). If it's not
running when `git lfs push`/`pull` tries to use it, you'll get a clear error telling you to
start one (`ipfs daemon`) — nothing fails silently, and nothing about building or installing
this binary requires IPFS to be present at all.
- [Git LFS](https://git-lfs.com) installed (`git-lfs` on your `PATH`).
## Build & install
```sh
cargo install --path .
```
This installs the `rad-lfs-transfer` binary to `~/.cargo/bin` (make sure that's on your
`PATH` — it's needed there so `git lfs` can find it once `rad lfs init` configures it).
## Configuration
| Environment variable | Default | Purpose |
|-----------------------|----------------------------|-------------------------------------------|
| `KUBO_API_URL` | `http://127.0.0.1:5001` | Base URL of your local Kubo HTTP RPC API |
You normally don't need to set this yourself — `rad lfs init` wires up everything else
(the transfer-agent config, the pre-commit hook, and the notes-ref refspecs) automatically.
## License
Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT license](LICENSE-MIT) at your option.

103
src/kubo.rs Normal file
View File

@ -0,0 +1,103 @@
use anyhow::{Context, bail};
use serde::Deserialize;
#[derive(Clone)]
pub struct Kubo {
client: reqwest::Client,
api_url: String,
}
#[derive(Deserialize)]
struct AddResponse {
#[serde(rename = "Hash")]
hash: String,
}
impl Kubo {
pub fn new(api_url: String) -> Self {
Self {
client: reqwest::Client::new(),
api_url,
}
}
/// Adds bytes to IPFS using Kubo's normal chunked UnixFS add (default
/// params — no raw-leaves / single-block tricks) and returns the CID.
pub async fn add(&self, bytes: Vec<u8>) -> anyhow::Result<String> {
let part = reqwest::multipart::Part::bytes(bytes).file_name("blob");
let form = reqwest::multipart::Form::new().part("file", part);
let resp = self
.client
.post(format!("{}/api/v0/add", self.api_url))
.multipart(form)
.send()
.await
.context("failed to reach Kubo daemon for /api/v0/add")?;
if !resp.status().is_success() {
bail!("kubo add failed: HTTP {}", resp.status());
}
let body = resp.text().await?;
let line = body
.lines()
.find(|l| !l.trim().is_empty())
.context("empty response from kubo add")?;
let parsed: AddResponse = serde_json::from_str(line)
.with_context(|| format!("failed to parse kubo add response: {line}"))?;
Ok(parsed.hash)
}
/// Explicitly (recursively) pins a CID, decoupled from add-time pinning.
pub async fn pin_add(&self, cid: &str) -> anyhow::Result<()> {
let resp = self
.client
.post(format!("{}/api/v0/pin/add", self.api_url))
.query(&[("arg", cid), ("recursive", "true")])
.send()
.await
.context("failed to reach Kubo daemon for /api/v0/pin/add")?;
if !resp.status().is_success() {
bail!("kubo pin/add failed for {cid}: HTTP {}", resp.status());
}
Ok(())
}
/// Streams the full reassembled file content for a CID via /api/v0/cat.
pub async fn cat(&self, cid: &str) -> anyhow::Result<reqwest::Response> {
let resp = self
.client
.post(format!("{}/api/v0/cat", self.api_url))
.query(&[("arg", cid)])
.send()
.await
.context("failed to reach Kubo daemon for /api/v0/cat")?;
if !resp.status().is_success() {
bail!("kubo cat failed for {cid}: HTTP {}", resp.status());
}
Ok(resp)
}
/// Verifies the local Kubo daemon is actually reachable, for a clear
/// upfront error instead of a confusing failure mid-transfer.
pub async fn healthcheck(&self) -> anyhow::Result<()> {
let resp = self
.client
.post(format!("{}/api/v0/id", self.api_url))
.send()
.await
.with_context(|| {
format!(
"no IPFS (Kubo) daemon reachable at {} — start one with `ipfs daemon`",
self.api_url
)
})?;
if !resp.status().is_success() {
bail!("kubo daemon at {} returned HTTP {}", self.api_url, resp.status());
}
Ok(())
}
}

173
src/main.rs Normal file
View File

@ -0,0 +1,173 @@
mod kubo;
mod notes;
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use kubo::Kubo;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let kubo = Kubo::new(
std::env::var("KUBO_API_URL").unwrap_or_else(|_| "http://127.0.0.1:5001".to_string()),
);
let stdin = tokio::io::stdin();
let mut lines = BufReader::new(stdin).lines();
let mut stdout = tokio::io::stdout();
while let Some(line) = lines.next_line().await? {
if line.trim().is_empty() {
continue;
}
let msg: Value = serde_json::from_str(&line)?;
let event = msg.get("event").and_then(Value::as_str).unwrap_or("");
match event {
"init" => {
let resp = match kubo.healthcheck().await {
Ok(()) => json!({}),
Err(e) => json!({"error": {"code": 1, "message": format!("{e:#}")}}),
};
write_line(&mut stdout, &resp).await?;
}
"upload" => {
let resp = handle_upload(&kubo, &msg).await;
write_line(&mut stdout, &resp).await?;
}
"download" => {
let resp = handle_download(&kubo, &msg).await;
write_line(&mut stdout, &resp).await?;
}
"terminate" => break,
other => {
write_line(
&mut stdout,
&json!({"error": {"code": 2, "message": format!("unknown event: {other}")}}),
)
.await?;
}
}
}
Ok(())
}
async fn handle_upload(kubo: &Kubo, msg: &Value) -> Value {
match upload_inner(kubo, msg).await {
Ok(oid) => json!({"event": "complete", "oid": oid}),
Err((oid, e)) => json!({
"event": "complete",
"oid": oid,
"error": {"code": 3, "message": format!("{e:#}")},
}),
}
}
async fn upload_inner(kubo: &Kubo, msg: &Value) -> Result<String, (String, anyhow::Error)> {
let oid = field_str(msg, "oid").map_err(|e| (String::new(), e))?;
let size = field_i64(msg, "size").map_err(|e| (oid.clone(), e))?;
let path = field_str(msg, "path").map_err(|e| (oid.clone(), e))?;
let blob_sha = notes::pointer_blob_hash(&oid, size)
.await
.map_err(|e| (oid.clone(), e))?;
// The pre-commit hook should already have added+pinned this and written
// the note. If it did, just confirm the pin (idempotent). If not (e.g.
// the hook was bypassed with `--no-verify`), self-heal by adding it now.
match notes::read_cid(&blob_sha).await {
Ok(Some(cid)) => {
kubo.pin_add(&cid).await.map_err(|e| (oid.clone(), e))?;
}
Ok(None) | Err(_) => {
let bytes = tokio::fs::read(&path).await.map_err(|e| {
(
oid.clone(),
anyhow::Error::from(e).context(format!("failed to read {path}")),
)
})?;
let cid = kubo.add(bytes).await.map_err(|e| (oid.clone(), e))?;
kubo.pin_add(&cid).await.map_err(|e| (oid.clone(), e))?;
notes::write_cid(&blob_sha, &cid)
.await
.map_err(|e| (oid.clone(), e))?;
}
}
Ok(oid)
}
async fn handle_download(kubo: &Kubo, msg: &Value) -> Value {
match download_inner(kubo, msg).await {
Ok((oid, path)) => json!({"event": "complete", "oid": oid, "path": path}),
Err((oid, e)) => json!({
"event": "complete",
"oid": oid,
"error": {"code": 3, "message": format!("{e:#}")},
}),
}
}
async fn download_inner(kubo: &Kubo, msg: &Value) -> Result<(String, String), (String, anyhow::Error)> {
let oid = field_str(msg, "oid").map_err(|e| (String::new(), e))?;
let size = field_i64(msg, "size").map_err(|e| (oid.clone(), e))?;
let blob_sha = notes::pointer_blob_hash(&oid, size)
.await
.map_err(|e| (oid.clone(), e))?;
let cid = notes::read_cid(&blob_sha)
.await
.map_err(|e| (oid.clone(), e))?
.ok_or_else(|| {
(
oid.clone(),
anyhow::anyhow!(
"no CID recorded for oid {oid} (no rad-lfs note on pointer blob {blob_sha}); \
the peer that has this object needs to push its refs/notes/rad-lfs ref"
),
)
})?;
let mut resp = kubo.cat(&cid).await.map_err(|e| (oid.clone(), e))?;
let tmp_path = std::env::temp_dir().join(format!("rad-lfs-{oid}"));
let mut file = tokio::fs::File::create(&tmp_path)
.await
.map_err(|e| (oid.clone(), anyhow::Error::from(e)))?;
while let Some(chunk) = resp
.chunk()
.await
.map_err(|e| (oid.clone(), anyhow::Error::from(e)))?
{
file.write_all(&chunk)
.await
.map_err(|e| (oid.clone(), anyhow::Error::from(e)))?;
}
file.flush().await.map_err(|e| (oid.clone(), anyhow::Error::from(e)))?;
Ok((oid, tmp_path.to_string_lossy().to_string()))
}
fn field_str(msg: &Value, key: &str) -> anyhow::Result<String> {
msg.get(key)
.and_then(Value::as_str)
.map(String::from)
.ok_or_else(|| anyhow::anyhow!("missing/invalid field: {key}"))
}
fn field_i64(msg: &Value, key: &str) -> anyhow::Result<i64> {
msg.get(key)
.and_then(Value::as_i64)
.ok_or_else(|| anyhow::anyhow!("missing/invalid field: {key}"))
}
async fn write_line(stdout: &mut tokio::io::Stdout, value: &Value) -> anyhow::Result<()> {
let mut s = serde_json::to_string(value)?;
s.push('\n');
stdout.write_all(s.as_bytes()).await?;
stdout.flush().await?;
Ok(())
}

89
src/notes.rs Normal file
View File

@ -0,0 +1,89 @@
use anyhow::{Context, bail};
use tokio::process::Command;
pub const NOTES_REF: &str = "refs/notes/rad-lfs";
/// Computes the git blob hash for the standard 3-line LFS pointer text for a
/// given oid/size, without needing the file itself or a repo search — the
/// pointer format is fully deterministic. Shells out to `git hash-object`
/// rather than hand-rolling the hash so this automatically respects the
/// repo's actual object format (SHA-1 vs SHA-256).
pub async fn pointer_blob_hash(oid: &str, size: i64) -> anyhow::Result<String> {
let pointer = pointer_text(oid, size);
let mut child = Command::new("git")
.args(["hash-object", "--stdin", "-t", "blob"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.context("failed to spawn `git hash-object`")?;
{
use tokio::io::AsyncWriteExt;
let stdin = child.stdin.as_mut().context("no stdin for git hash-object")?;
stdin.write_all(pointer.as_bytes()).await?;
}
let output = child.wait_with_output().await?;
if !output.status.success() {
bail!(
"git hash-object failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(String::from_utf8(output.stdout)?.trim().to_string())
}
pub fn pointer_text(oid: &str, size: i64) -> String {
format!("version https://git-lfs.github.com/spec/v1\noid sha256:{oid}\nsize {size}\n")
}
/// Reads the `cid=<cid>` note attached to a blob, if any.
pub async fn read_cid(blob_sha: &str) -> anyhow::Result<Option<String>> {
let output = Command::new("git")
.args(["notes", "--ref", NOTES_REF, "show", blob_sha])
.output()
.await
.context("failed to spawn `git notes show`")?;
if !output.status.success() {
// Non-zero exit typically means no note exists for this object.
return Ok(None);
}
let text = String::from_utf8(output.stdout)?;
Ok(parse_cid(&text))
}
/// Writes/overwrites the `cid=<cid>` note on a blob.
pub async fn write_cid(blob_sha: &str, cid: &str) -> anyhow::Result<()> {
let output = Command::new("git")
.args([
"notes",
"--ref",
NOTES_REF,
"add",
"-f",
"-m",
&format!("cid={cid}"),
blob_sha,
])
.output()
.await
.context("failed to spawn `git notes add`")?;
if !output.status.success() {
bail!(
"git notes add failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(())
}
fn parse_cid(note: &str) -> Option<String> {
note.lines()
.find_map(|line| line.strip_prefix("cid="))
.map(|s| s.trim().to_string())
}