A no_std BitTorrent engine with piece verification, selective downloads and seeding.
TypeBit is a download-engine core — a library, not a GUI. You bind it
into your Android (Kotlin), iOS (Swift), desktop, or embedded product and
implement one interface: Host.
Everything else (piece picking, DHT, receipts, rate limiting, anti-leech)
lives behind that seam.
no_std + alloccore with optional hardware-accelerated SHA-1 and C FFI- Four direct core dependencies, plus
socket2with thestdfeature - one crate, no workspace ritual
#![warn(missing_docs)], full docs.rs coverage, CI-gated-D warnings
Hashing throughput and how to reproduce it:
docs/performance.md(cargo bench --features std) — SHA-1 is 4-5× faster than 0.1.9 on x86 CPUs with the Intel SHA extensions (and the ARMv8 crypto path is on by default on aarch64), ~1.1-1.3× on every other target from the scalar rewrite.
| Protocol | Spec | Status |
|---|---|---|
| Metainfo v1 / v2 / hybrid | BEP-3 / BEP-52 | SHA-1 for v1 pieces, SHA-256 Merkle verification for v2. Hybrid files use the v2 swarm and hashes. |
| Peer wire + Fast extension | BEP-6 | ✅ |
| DHT (Kademlia) | BEP-5 | ✅ routing table, KRPC, lookups, peer store |
| PEX | BEP-11 | ✅ |
| Metadata exchange | BEP-9 / BEP-52 | Exchanges the info dictionary and authenticates peer-supplied v2 piece layers against each file root. |
| Private torrents | BEP-27 | Uses one tracker at a time after metadata identifies the torrent as private. Disables DHT, PEX and LSD for that torrent. |
| Web seeds | BEP-19 | Fetches byte ranges for pieces contained in one file. Cross-file v1 pieces use peers. |
| LSD (local discovery) | BEP-14 | ✅ multicast, IPv4 + IPv6 |
| uTP | BEP-29 | ✅ LEDBAT congestion control |
| UDP trackers | BEP-15 | Announce replies decode compact IPv4 or IPv6 peers using the tracker's address family. |
Magnet / btmh |
BEP-9 / BEP-52 | Downloads from v1 and v2 magnets. Hybrid links with both hashes select v2. A btih-only link uses v1. |
| SOCKS5 proxy | RFC 1928/1929 | Outbound peer connections and HTTP tracker requests |
| NAT-PMP / UPnP IGD | RFC 6886 / UPnP | ✅ |
Tested on Windows with a local HTTP tracker and IPv4 loopback. For the seven TCP transfers below, qBittorrent 5.1.4 (libtorrent 2.0.11) dialed TypeBit. The libtorrent 1.2.20 build passed the three v1 TCP transfers. TypeBit also dialed Transmission 4.0.6 (38c164933e) and passed the same three v1 TCP cases. With qBittorrent restricted to uTP, private v1 .torrent files transferred in both directions.
Each transfer uses a deterministic 196,731-byte payload in seven 32 KiB pieces (the last piece is short).
| Transfer | Input to TypeBit | Verified at destination |
|---|---|---|
| TypeBit → qBittorrent | Private v1 .torrent and an existing file |
File bytes and SHA-256 |
| qBittorrent → TypeBit | Private v1 .torrent |
File bytes, SHA-256 and all seven piece hashes |
| qBittorrent → TypeBit | Public v1 magnet | BEP-9 metadata, file bytes, SHA-256 and all seven piece hashes |
| TypeBit → qBittorrent | Private v2 .torrent with piece layers and an existing file |
File bytes and SHA-256, including the short final block |
| qBittorrent → TypeBit | Private v2 .torrent with piece layers |
File bytes, SHA-256 and all seven piece hashes |
| TypeBit ↔ qBittorrent | Public v2 magnet, seven pieces | Each receiver started with only the magnet and obtained the file from the other client. Both 196,731-byte payloads matched. |
| TypeBit ↔ qBittorrent | Private single-file hybrid .torrent with piece layers, via the v2 swarm |
File bytes and SHA-256 in both directions, plus all seven piece hashes on TypeBit |
On a private IPv4 address assigned to the same machine, TypeBit also dialed BitComet 2.23 and sent two 196,731-byte files. After each download, BitComet seeded the file to a fresh TypeBit receiver. The first receiver started from a private v1 .torrent, the second from a public v1 magnet. Both files matched byte for byte, by SHA-256 and by all seven piece hashes.
To reproduce the interoperability tests in PowerShell, set the paths to the qt6_lt20 build, Transmission and BitComet. With libtorrent 1.2, select v1_bidirectional_and_magnet before --. qBittorrent 5.1.4 downloads
$env:TYPEBIT_QBITTORRENT = 'C:\Program Files\qBittorrent\qbittorrent.exe'
$env:TYPEBIT_TRANSMISSION = 'C:\Program Files\Transmission\transmission-daemon.exe'
$env:TYPEBIT_BITCOMET = 'C:\Program Files\BitComet\BitComet.exe'
$env:TYPEBIT_TEST_IPV4 = (Get-NetIPConfiguration | Where-Object IPv4DefaultGateway | Select-Object -First 1).IPv4Address.IPAddress
cargo test --locked --features std --test qbittorrent -- --ignored --skip comparison --nocapture --test-threads=1BitComet 2.23 downloaded 32 MiB from two TypeBit seeds in three byte-checked runs when the seeds dialed BitComet. In the reverse dialing arrangement, BitComet announced but neither seed observed a handshake in 180 seconds. The performance report also records Debian and Ubuntu public swarm results, UDP mapping probes and two outbound uTP simulations. Transfers between two real endpoint-dependent NATs remain unmeasured. Measurements and reproduction commands
links::parse_link accepts magnets, ipfs://, ipns://, direct HTTP(S)/FTP files and Thunder, QQDL or FlashGet wrappers around a supported target. Formats and runtime requirements
- Utility scheduler — piece priority is a function of content semantics, not rarity. A video schedules head/tail pieces first so you can start watching while the middle still downloads.
- Anti-leech engine — reciprocity-based unchoke (tit-for-tat), corrupt block accountability (blame weighted by who supplied the bad blocks), peer-id fingerprinting, per-subnet connection quotas, and a persistent reputation store that remembers a leecher across sessions.
- Download receipts bind the content root, byte range, time window and byte count to the node's Ed25519 signature. A verifier can authenticate this statement.
- Multi-core verification — a piece-hash pool spreads SHA across cores,
with a zero-thread inline fallback for
no_std. One code path, two execution strategies. - uTP transport — BEP-29 with LEDBAT: yields bandwidth under congestion, fills the pipe when idle.
- Rate limiting — global and per-session token buckets, enforced at the wire.
- Disk cache — coalesced write-back with a read-through LRU, so a session doesn't grind your SSD to death.
- Swarm monitoring — recovery estimation and poison/availability observability. It can tell you a swarm is dying before it does.
All cryptography is in-tree and no_std: SHA-1/256/512, Ed25519
(RFC 8032), ChaCha20 (RFC 8439), MD4, Base58/32/64, CSPRNG. No ring, no
openssl, no sha2.
use typebit::links::parse_link;
let link = parse_link(
"magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=hello",
)?;
match link {
typebit::links::DownloadLink::BitTorrent(m) => {
println!("torrent: {}", m.name.as_deref().unwrap_or("<unnamed>"));
}
_ => unreachable!(),
}
# Ok::<(), typebit::Error>(())The engine is generic over Host.
With the std feature you get a complete OS-backed host out of the box:
[dependencies]
typebit = { version = "0.1", features = ["std"] }use typebit::{Engine, EngineConfig};
let mut engine = Engine::new(typebit::host_std::StdHost::new(), EngineConfig::default());
let hash = engine.add_magnet(
"magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567",
"/path/to/downloads",
)?;
engine.start(&hash)?;
// Call tick on a thread suitable for the host's network and disk I/O.
loop {
engine.tick()?;
for ev in engine.take_events() {
println!("event: {ev:?}");
}
println!("progress: {:.1}%", engine.progress(&hash) * 100.0);
std::thread::sleep(std::time::Duration::from_millis(500));
}
# Ok::<(), typebit::Error>(())For embedded / mobile targets implement the ~18 methods of Host yourself —
the engine drives everything else. See
examples/minimal_host.rs for a complete
in-memory implementation, and the
Wiki for the full walkthrough.
For inbound TCP, bind StdHost::listen_tcp before constructing the engine and pass
the bound port to EngineConfig::listen_port. Engine::recheck hashes existing
payload files and rebuilds the verified piece map. To persist a download, call
flush_cache()? before save_state(). Re-add the torrent or magnet and apply
restore_torrent on restart. If the files changed outside the engine, run recheck
before starting the torrent.
| Feature | What you get |
|---|---|
| (default) | bare no_std core |
std |
OS-backed StdHost: sockets, files, clock, DNS |
ffi |
extern "C" ABI for Kotlin / Swift / C# / Go |
cargo run --example parse_links -- 'ipns://docs.ipfs.tech/'
cargo run --example minimal_host # full in-memory Host + engine lifecycle
cargo run --example ffi_demo --features ffi # drive the engine via the C ABIadd_torrent / add_magnet → start(hash) → tick() × N → flush_cache()? → save_state()
│
on_inbound_connection / take_events ◄───┘
add_torrent(&[u8], save_dir)/add_magnet(&str, save_dir)return anInfoHash.start(hash)begins announcing;pause/resume/remove_torrentcontrol the session.tick()drives every session, DHT, UDP socket, port mapper, web seed, uTP socket and the verify pool. Call it on a timer (~100–500 ms).take_events()drainsEngineEvents — add this to your event loop.load_state()restores the DHT table and node identity.restore_torrent()restores each re-added task's verified pieces, priorities, speed limits and reputation. Incomplete pieces are downloaded again.
- Public torrents merge their announce list with
SessionConfig::trackersand, when enabled, built-in fallback trackers. Private.torrentfiles use their own tracker list. Refresh the community list at runtime fromconsts::TRACKERS_LIST_URLviatracker::parse_tracker_listintoSessionConfig::trackers. - Public torrents rotate trackers. Private torrents keep their current tracker until it fails, then disconnect its peers before switching.
- DHT boots from the well-known permanent routers, keeps a real peer store, re-announces on a timer, and degrades gracefully if UDP dies.
With std, transfer::Kubo connects to a local Kubo daemon. add imports a file or directory into UnixFS and recursively pins its Merkle DAG. Share the returned ipfs://<CID>. provide queues a provider announcement, and find_providers checks the routing system. Keep the daemon online to serve blocks over Bitswap. A second node can pin the same CID to keep serving the file independently.
Use read_file for a byte stream, get for a directory tree and export_car for its blocks and links. To share the same files with BitTorrent peers, load their .torrent, recheck the payload and start the torrent session. Each network uses its own content identifier. Setup and verification
src/
crypto/ SHA-1/256/512, Ed25519, ChaCha20, MD4, base58/32/64, PRNG
bencode.rs dependency-free bencode codec with depth/size limits
metainfo.rs v1/v2/hybrid torrent parsing + per-piece layout/verification
magnet.rs magnet URI (BEP-9/53)
links.rs transfer URI parsing and direct-file identities
transfer.rs std adapters for local Kubo and curl
wire.rs peer-wire codec (BEP-6/9/10/11) with frame limits
dht.rs Kademlia routing table + KRPC + lookups + peer store
tracker.rs HTTP + UDP (BEP-15) tracker clients
trackerlist.rs built-in tracker list
lsd.rs local peer discovery (BEP-14)
pex.rs peer exchange (BEP-11)
utp.rs uTP transport (BEP-29, LEDBAT)
leech.rs anti-leech: reciprocity scoring + corrupt-block accountability
ratelimit.rs token-bucket rate limiting
scheduler.rs utility-driven piece scheduling (video head/tail first)
disk_cache.rs coalesced write-back cache + read-through LRU
verify.rs multi-core piece verification (inline fallback for no_std)
receipt.rs provable-download receipts (Ed25519-signed)
socks.rs SOCKS5 (RFC 1928/1929) proxy plumbing
portmap.rs NAT-PMP (RFC 6886) + UPnP IGD
state.rs session state (save / resume)
session.rs per-torrent session state machine
engine.rs top-level engine: host + sessions + DHT + cache + uTP
platform.rs the `Host` seam (the only thing you implement)
- CI enforces
-D warningsacross a feature × OS matrix, rustdoc + doc tests, three bare-metalno_stdtargets, MSRV 1.95,cargo-auditandcargo packageverification before anything merges. - Tag
v0.x.yonmainand thepublishworkflow ships it to crates.io (configure theCARGO_REGISTRY_TOKENsecret).