# dartBt **Repository Path**: cpsoft13/dart-bt ## Basic Information - **Project Name**: dartBt - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-05-19 - **Last Updated**: 2026-05-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # dart_bt — Pure-Dart BitTorrent Protocol Library 纯 Dart 实现的 BitTorrent 协议库,功能完备、生产可用。支持自定义协议扩展、MSE/PE 加密、多 Peer 并行下载、LEDBAT 拥塞控制,以及做种和端口映射。同时提供 Rust 版本实现 (`rust_bt/`),接口对齐,按需选用。 A production-grade, pure-Dart BitTorrent protocol library. Supports custom protocol extensions, MSE/PE encryption, multi-peer parallel downloads, LEDBAT congestion control, seeding, and NAT traversal. A Rust implementation (`rust_bt/`) is also provided with a matching API surface. --- ## Features / 特性 | 模块 / Module | 说明 / Description | |---|---| | **Bencode** | Bencode 编解码,解析 .torrent 文件 / Encode/decode, parse .torrent files | | **TorrentMeta** | 种子元数据:info_hash、piece 哈希、文件布局 / Metadata parsing | | **PeerWireClient** | Peer wire 协议客户端,支持 RTT 测量 / Protocol client with RTT measurement | | **PeerWireServer** | 做种服务端,支持 choke optimizer / Seeding server with choke optimizer | | **MSE/PE Encryption** | MSE/PE 加密握手 (BEP 10) / Protocol encryption | | **PieceManager** | Rarest-first 调度 + 自适应超时 + Endgame 模式 / Piece scheduling | | **LEDBAT** | 延迟感知拥塞控制,per-peer 独立窗口 / Delay-aware congestion control | | **PEX** | Peer 交换,去中心化节点发现 / Decentralized peer discovery | | **LSD** | 本地服务发现 (BEP 14) / Local service discovery | | **NAT-PMP/UPnP** | 端口映射,外网可达 / Port mapping for WAN reachability | | **FileWriter** | 文件 I/O,支持 resume、CRC32 校验、预分配 / Disk I/O with resume support | | **BtSession** | 完整下载会话编排 / Full download lifecycle orchestration | | **BtEngineImpl** | 多种子并发管理 / Multi-torrent management engine | ### Advanced / 高级特性 - **Multi-peer parallel download** — 同时连接多个 seed/leecher,P2P piece 交换 - **Super seeding support** — 发送 have 触发服务端 reveal 下一个 piece - **Snubbing** — 慢速 peer 自动降级为 1 slot - **Corrupt attribution & banning** — SHA1 失败时按 piece 归属,累计 5 次封禁 - **Per-peer rate limiting** — fair-share 令牌桶,高速 peer 不受低速 peer 拖累 - **Choke optimizer** — 做种时每 10s 评估,优先活跃上传者 - **Event-driven pipeline** — block 到达/unchoke/超时即时补位,500ms 安全网兜底 --- ## Quick Start / 快速开始 ### Dart / Flutter ```yaml # pubspec.yaml dependencies: dart_bt: path: /path/to/dart-bt ``` ```dart import 'package:dart_bt/dart_bt.dart'; void main() async { final meta = await TorrentMeta.fromTorrentFile('asset.torrent'); final session = BtSession( contentId: 'my-content', meta: meta, savePath: '/tmp/downloads', peerIp: '192.168.1.100', peerPort: 6881, ); session.onProgress = (p) => print('${(p * 100).toStringAsFixed(1)}%'); session.onComplete = () => print('Done!'); await session.start(); } ``` ### Rust ```toml # Cargo.toml [dependencies] rust_bt = { path = "rust_bt" } ``` ```rust use rust_bt::{TorrentMeta, BtSession}; use rust_bt::session::SessionCallbacks; use std::sync::Arc; struct MyCallbacks; impl SessionCallbacks for MyCallbacks { fn on_progress(&self, p: f64) { println!("{:.1}%", p * 100.0); } fn on_complete(&self) { println!("Done!"); } fn on_error(&self, e: String) { eprintln!("Error: {e}"); } fn on_seeding_ready(&self, port: u16) { println!("Seeding on :{port}"); } } #[tokio::main] async fn main() -> Result<(), String> { let meta = TorrentMeta::from_torrent_file("asset.torrent")?; let mut session = BtSession::new( "my-content".into(), meta, "/tmp/downloads".into(), "192.168.1.100".into(), 6881, ); session.set_callbacks(Arc::new(MyCallbacks)); session.start().await?; Ok(()) } ``` --- ## Run Tests / 运行测试 ### Dart ```bash # 完整自测试(进程内种子 + 下载) dart run bin/bt_self_test.dart [fileSizeMB] [pieceSizeKB] # 多 Peer 并行测试 dart run bin/bt_multi_peer_test.dart # 连接外部种子测试 dart run bin/bt_test.dart [output_dir] ``` ### Rust ```bash # 自测试 cargo run --bin bt_self_test [fileSizeMB] [pieceSizeKB] # 多 Peer 测试 cargo run --bin bt_multi_peer_test # 多进程 P2P 集成测试(进程内 tracker + seed + 2 leecher) cargo run --bin bt_p2p_integration_test # 真实多进程测试(独立二进制,模拟多设备部署) ./test_p2p_real_processes.sh [fileSizeMB] # 独立 Tracker 服务 cargo run --bin bt_tracker -- --port 17000 --bind 127.0.0.1 # 独立做种服务 cargo run --bin bt_seed_server -- --port 6881 --super-seed --tracker 127.0.0.1:17000 # 下载客户端(tracker 发现 peer) cargo run --bin bt_download_client -- --tracker 127.0.0.1:17000 # 单元测试 cargo test ``` --- ## Project Structure / 项目结构 ``` dart-bt/ ├── lib/ │ ├── dart_bt.dart # Library entry, exports all modules │ └── src/ │ ├── bencode.dart # Bencode encoder/decoder │ ├── torrent_meta.dart # .torrent file parser │ ├── mse.dart # MSE/PE encryption (BEP 10) │ ├── peer_wire.dart # Peer wire protocol client & server │ ├── piece_mgr.dart # Piece scheduler (rarest-first, endgame) │ ├── file_io.dart # File I/O with resume support │ ├── rate_limiter.dart # Token bucket rate limiter │ ├── lsd.dart # Local Service Discovery (BEP 14) │ ├── port_mapping.dart # NAT-PMP / UPnP-IGD port mapping │ ├── session.dart # Download session orchestrator │ └── engine.dart # Multi-torrent engine ├── bin/ │ ├── bt_self_test.dart # In-process seed + download test │ ├── bt_multi_peer_test.dart# Multi-peer parallel test │ └── bt_test.dart # External seed test harness ├── rust_bt/ # Rust implementation │ ├── Cargo.toml │ ├── README.md │ ├── test_p2p_real_processes.sh # Multi-process P2P integration test │ └── src/ │ ├── lib.rs # Crate entry, re-exports │ ├── bencode.rs │ ├── torrent_meta.rs │ ├── mse.rs │ ├── peer_wire.rs │ ├── piece_mgr.rs │ ├── file_io.rs # FileWriter + FileHandlePool │ ├── rate_limiter.rs │ ├── lsd.rs │ ├── port_mapping.rs │ ├── session.rs │ ├── engine.rs │ └── bin/ │ ├── bt_self_test.rs │ ├── bt_multi_peer_test.rs │ ├── bt_p2p_integration_test.rs │ ├── bt_tracker.rs │ ├── bt_seed_server.rs │ └── bt_download_client.rs ├── USAGE.md # Full API reference (双语 / bilingual) ├── pubspec.yaml └── analysis_options.yaml ``` --- ## API Overview / 接口概览 ### Dart ```dart // ── 解析 / Parse ── final meta = await TorrentMeta.fromTorrentFile(path); final dict = await BencodeParser.decodeFile(path); // ── 单种子下载 / Single torrent ── final session = BtSession(contentId, meta, savePath, peerIp, peerPort); session.onProgress = ...; session.onComplete = ...; session.onError = ...; await session.start(); session.pause(); await session.resume(); await session.stop(); session.addPeer(ip, port); // 多 peer / multi-peer session.setDownloadLimit(bytesPerSec); // ── 多种子引擎 / Multi-torrent engine ── final engine = BtEngineImpl(savePath: path); await engine.init(); await engine.addTorrent(torrentPath: p, contentId: id); await engine.connectPeer(infoHash: h, ip: ip, port: pt); await engine.getStatus(infoHash); // → JSON await engine.pause(); await engine.resume(); await engine.destroy(); // ── 做种 / Seeding ── final server = PeerWireServer(infoHash, peerId, numPieces, pieceLength, readRange, hasPiece); final port = await server.bind(0); server.broadcastHave(idx); await server.close(); // ── 工具 / Utilities ── final peerId = generatePeerId(); final limiter = RateLimiter(bytesPerSecond: 1024 * 1024); tryPortMapping(localPort); final lsd = LsdDiscovery(infoHash, listenPort, onPeerDiscovered); ``` ### Rust ```rust // ── 解析 / Parse ── let meta = TorrentMeta::from_torrent_file(path)?; let decoded = bencode::decode_file(path)?; // ── 单种子下载 / Single torrent ── let mut session = BtSession::new(cid, meta, save_path, ip, port); session.set_callbacks(Arc::new(callbacks)); session.start().await?; session.add_peer(ip, port).await?; session.set_download_limit(bytes_per_sec); // ── 多种子引擎 / Multi-torrent engine ── let mut engine = BtEngine::new(save_path); engine.init().await?; engine.add_torrent(path, Some(cid)).await?; engine.connect_peer(info_hash, ip, port).await?; engine.get_status(info_hash).await; // → JSON string engine.destroy().await; // ── 做种 / Seeding ── let mut server = PeerWireServer::new(info_hash, peer_id, num_pieces, piece_length, read_range, has_piece); let port = server.bind(0).await?; server.broadcast_have(idx); server.stop(); // ── 工具 / Utilities ── let peer_id = generate_peer_id(); let limiter = RateLimiter::new(1024 * 1024); port_mapping::try_port_mapping(port).await; let mut lsd = LsdDiscovery::new(info_hash, port, callback); ``` --- ## Requirements / 环境要求 | | Dart | Rust | |---|---|---| | **Language** | Dart SDK 3.2+ | Rust 2021 edition | | **Runtime** | Any Dart VM / Flutter | Tokio async runtime | | **Dependencies** | `crypto` | `tokio`, `sha1`, `rand`, `bytes`, `tracing`, `serde`, `anyhow`, `thiserror` | --- ## License MIT — see [LICENSE](LICENSE) (如果存在 / if present). Repository: [gitee.com/cpsoft13/dart-bt](https://gitee.com/cpsoft13/dart-bt.git)