feat: persist I2P torrent list to EDN state file across restarts
- Save active and paused torrents to torrents.edn on add, remove, pause, resume, and metadata fetch, then restore them on router startup. - Default path is $MOON_I2P_DATA_DIR, then $XDG_DATA_HOME, then ~/.local/share/moon-i2p-browser. Add --torrent-state <file> to override, or --no-torrent-state to disable. - Write the state file atomically (temp file, fsync, rename). A corrupt or unsupported file logs a warning and does not block startup. - Verify restored pieces incrementally in the background for large torrents; these show as state "checking" in /api/torrents. - Expose state_file in /api/status and the startup banner. - Add standard RFC 4648 Base64 encode/decode helpers, used for the info-b64 field. - Add the moonedn dependency and pass --torrent-state from the Android service.
This commit is contained in:
1 parent
b803e79199
commit
dd5b132b5a
17 files changed
+1105
-39
No files matched your search
@@ -12,6 +12,7 @@ import {
|
||||
"experiments/moon_i2p/streaming",
|
||||
"experiments/moon_i2p/sam",
|
||||
"experiments/moon_i2p/bittorrent",
|
||||
"jqlssg/moonedn" @edn,
|
||||
}
|
||||
|
||||
supported_targets = "-all+native"
|
||||
@@ -852,3 +852,240 @@ test "POST /api/torrents/add accepts standard, URL-safe, and rejects invalid Bas
|
||||
assert_true(bad_resp.contains("400 Bad Request"))
|
||||
assert_true(bad_resp.contains("invalid torrent_b64"))
|
||||
}
|
||||
|
||||
///|
|
||||
test "torrent list persists and reloads from EDN state file across restarts" {
|
||||
let rand_hex = @encoding.hex_encode(@ntcp2_net.random_bytes(4))
|
||||
let base_dir = "/tmp/moon_i2p_edn_persist_test_\{rand_hex}"
|
||||
let dl_dir = "\{base_dir}/downloads"
|
||||
let state_file = "\{base_dir}/torrents.edn"
|
||||
@ntcp2_net.mkdir_p(dl_dir)
|
||||
|
||||
let make_single_torrent = fn(
|
||||
name : Bytes,
|
||||
payload : Bytes,
|
||||
) -> (Bytes, String) {
|
||||
let piece_len = 16384
|
||||
let hashes = @encoding.Writer::new()
|
||||
let mut off = 0
|
||||
while off < payload.length() {
|
||||
let end = if off + piece_len < payload.length() {
|
||||
off + piece_len
|
||||
} else {
|
||||
payload.length()
|
||||
}
|
||||
hashes.write_bytes(@crypto.sha1(payload[off:end].to_owned()))
|
||||
off = end
|
||||
}
|
||||
let tbytes = @bittorrent.bencode_encode(
|
||||
BDict([
|
||||
(b"announce", BBytes(b"http://tracker.insulaocculta.i2p/a")),
|
||||
(
|
||||
b"info",
|
||||
BDict([
|
||||
(b"length", BInt(payload.length().to_int64())),
|
||||
(b"name", BBytes(name)),
|
||||
(b"piece length", BInt(piece_len.to_int64())),
|
||||
(b"pieces", BBytes(hashes.to_bytes())),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)
|
||||
let meta = @bittorrent.parse_torrent(tbytes) catch {
|
||||
_ => abort("bad test torrent")
|
||||
}
|
||||
(tbytes, @encoding.hex_encode(meta.info_hash))
|
||||
}
|
||||
|
||||
let payload1 = Bytes::make(32768, b'\x5A')
|
||||
@ntcp2_net.write_file_at(dl_dir + "/complete.bin", 0L, payload1)
|
||||
let (t1_bytes, ih1) = make_single_torrent(b"complete.bin", payload1)
|
||||
let (t2_bytes, ih2) = make_single_torrent(
|
||||
b"paused.bin",
|
||||
Bytes::make(16384, b'\x33'),
|
||||
)
|
||||
let (t3_bytes, ih3) = make_single_torrent(
|
||||
b"removed.bin",
|
||||
Bytes::make(16384, b'\x44'),
|
||||
)
|
||||
let ih4 = "0123456789abcdef0123456789abcdef01234567"
|
||||
|
||||
let r1 = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
let api1 = r1.start_torrent_api(
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
download_dir=dl_dir,
|
||||
state_file~,
|
||||
)
|
||||
let rs1 = [r1]
|
||||
|
||||
for tb in [t1_bytes, t2_bytes, t3_bytes] {
|
||||
let b64 = @encoding.base64_std_encode(tb)
|
||||
let resp = test_http_api_request(
|
||||
api1,
|
||||
rs1,
|
||||
"POST",
|
||||
"/api/torrents/add",
|
||||
"127.0.0.1:\{api1}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"torrent_b64\":\"\{b64}\"}",
|
||||
)
|
||||
assert_true(resp.contains("200 OK"))
|
||||
}
|
||||
|
||||
let mag_resp = test_http_api_request(
|
||||
api1,
|
||||
rs1,
|
||||
"POST",
|
||||
"/api/torrents/magnet",
|
||||
"127.0.0.1:\{api1}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"uri\":\"magnet:?xt=urn:btih:\{ih4}&dn=pending-mag&tr=http://tracker.insulaocculta.i2p/a\"}",
|
||||
)
|
||||
assert_true(mag_resp.contains("200 OK"))
|
||||
assert_true(mag_resp.contains(ih4))
|
||||
|
||||
let pause_resp = test_http_api_request(
|
||||
api1,
|
||||
rs1,
|
||||
"POST",
|
||||
"/api/torrents/pause",
|
||||
"127.0.0.1:\{api1}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"info_hash\":\"\{ih2}\"}",
|
||||
)
|
||||
assert_true(pause_resp.contains("200 OK"))
|
||||
|
||||
let rm_resp = test_http_api_request(
|
||||
api1,
|
||||
rs1,
|
||||
"POST",
|
||||
"/api/torrents/remove",
|
||||
"127.0.0.1:\{api1}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"info_hash\":\"\{ih3}\"}",
|
||||
)
|
||||
assert_true(rm_resp.contains("200 OK"))
|
||||
r1.close()
|
||||
|
||||
// Verify persisted EDN structure and contents on disk
|
||||
assert_true(@ntcp2_net.file_exists(state_file))
|
||||
let edn_text = @encoding.utf8_bytes_to_string(
|
||||
@ntcp2_net.read_file_bytes(state_file),
|
||||
)
|
||||
assert_true(!edn_text.contains(ih3))
|
||||
let limits : @edn.Limits = {
|
||||
input: 64 * 1024 * 1024,
|
||||
depth: 64,
|
||||
nodes: 1000000,
|
||||
token: 16 * 1024 * 1024,
|
||||
container: 100000,
|
||||
}
|
||||
let parsed = @edn.read(edn_text, limits~)
|
||||
match parsed {
|
||||
Mapping(root) => {
|
||||
let mut found_ver = false
|
||||
let mut count = -1
|
||||
for entry in root {
|
||||
match entry.0 {
|
||||
Keyword(k) if k == "version" =>
|
||||
match entry.1 {
|
||||
Integer(v) => {
|
||||
assert_eq(v, "1")
|
||||
found_ver = true
|
||||
}
|
||||
_ => fail("expected integer version")
|
||||
}
|
||||
Keyword(k) if k == "torrents" =>
|
||||
match entry.1 {
|
||||
Vector(items) => count = items.length()
|
||||
_ => fail("expected torrents vector")
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
assert_true(found_ver)
|
||||
assert_eq(count, 3)
|
||||
}
|
||||
_ => fail("expected EDN mapping at root")
|
||||
}
|
||||
|
||||
// Restart router 2 with the same state_file and verify full restoration
|
||||
let r2 = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer r2.close()
|
||||
let api2 = r2.start_torrent_api(
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
download_dir=dl_dir,
|
||||
state_file~,
|
||||
)
|
||||
let rs2 = [r2]
|
||||
|
||||
let status2 = test_http_api_request(
|
||||
api2,
|
||||
rs2,
|
||||
"GET",
|
||||
"/api/status",
|
||||
"127.0.0.1:\{api2}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(status2.contains("\"torrent_count\":3"))
|
||||
assert_true(status2.contains("\"state_file\":\"\{state_file}\""))
|
||||
|
||||
let list2 = test_http_api_request(
|
||||
api2,
|
||||
rs2,
|
||||
"GET",
|
||||
"/api/torrents",
|
||||
"127.0.0.1:\{api2}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(list2.contains(ih1))
|
||||
assert_true(list2.contains(ih2))
|
||||
assert_true(list2.contains(ih4))
|
||||
assert_true(!list2.contains(ih3))
|
||||
assert_true(list2.contains("\"downloaded_bytes\":32768"))
|
||||
assert_true(list2.contains("\"completed\":true"))
|
||||
assert_true(list2.contains("\"state\":\"paused\""))
|
||||
assert_true(list2.contains("\"state\":\"metadata\""))
|
||||
assert_true(list2.contains("\"name\":\"pending-mag\""))
|
||||
|
||||
// Verify corrupt EDN file does not crash startup
|
||||
let bad_state = "\{base_dir}/corrupt.edn"
|
||||
@ntcp2_net.write_file_atomic(bad_state, b"{broken edn")
|
||||
let r3 = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer r3.close()
|
||||
let api3 = r3.start_torrent_api(
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
download_dir=dl_dir,
|
||||
state_file=bad_state,
|
||||
)
|
||||
let status3 = test_http_api_request(
|
||||
api3,
|
||||
[r3],
|
||||
"GET",
|
||||
"/api/status",
|
||||
"127.0.0.1:\{api3}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(status3.contains("\"torrent_count\":0"))
|
||||
}
|
||||
@@ -32,8 +32,9 @@ pub fn Router::start_torrent_api(
|
||||
host~ : String = "127.0.0.1",
|
||||
port~ : Int32 = 4445,
|
||||
download_dir~ : String = "",
|
||||
state_file~ : String = "",
|
||||
) -> Int32 raise RouterError {
|
||||
self.enable_torrent_engine(download_dir~)
|
||||
self.enable_torrent_engine(download_dir~, state_file~)
|
||||
match self.torrent_api_listener {
|
||||
Some(l) => return l.port
|
||||
None => ()
|
||||
@@ -336,6 +337,7 @@ fn Router::build_api_status_json(self : Router) -> String {
|
||||
sb.write_string("\"torrent_api_port\":\{self.torrent_api_port()},")
|
||||
sb.write_string("\"torrent_b32\":\"\{api_json_escape(tb32)}\",")
|
||||
sb.write_string("\"download_dir\":\"\{api_json_escape(eng.download_dir)}\",")
|
||||
sb.write_string("\"state_file\":\"\{api_json_escape(eng.state_file)}\",")
|
||||
sb.write_string("\"torrent_count\":\{eng.torrents.length()},")
|
||||
sb.write_string("\"active_torrents\":\{active},")
|
||||
sb.write_string("\"completed_torrents\":\{seeding},")
|
||||
@@ -426,6 +428,8 @@ fn Router::build_api_torrents_json(self : Router) -> String {
|
||||
let inflight_bytes = inflight_blocks.to_int64() * 16384L
|
||||
let state_str = if t.error.length() > 0 {
|
||||
"error"
|
||||
} else if t.verify_cursor >= 0 {
|
||||
"checking"
|
||||
} else if t.paused {
|
||||
"paused"
|
||||
} else if t.completed {
|
||||
|
||||
+120
-19
@@ -91,6 +91,7 @@ priv struct ActiveTorrent {
|
||||
mut uploaded_bytes : UInt64
|
||||
mut have_pieces : Array[Bool]
|
||||
inflight_pieces : Array[ActivePieceBuf]
|
||||
mut verify_cursor : Int32
|
||||
mut meta_size : Int32
|
||||
meta_pieces : Array[(Int32, Bytes)]
|
||||
mut meta_req_ms : UInt64
|
||||
@@ -107,6 +108,7 @@ priv struct TorrentEngine {
|
||||
session_id : String
|
||||
peer_id : Bytes
|
||||
mut download_dir : String
|
||||
mut state_file : String
|
||||
dht : @bittorrent.I2pDht
|
||||
torrents : Array[ActiveTorrent]
|
||||
pending_inbound : Array[TorrentInboundConn]
|
||||
@@ -384,6 +386,29 @@ fn bt_read_span_from_files(
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_verify_piece_at(
|
||||
t : ActiveTorrent,
|
||||
meta : @bittorrent.Metainfo,
|
||||
piece_idx : Int32,
|
||||
) -> Int32 {
|
||||
let plen = bt_piece_length(meta, piece_idx)
|
||||
match bt_read_span_from_files(t, piece_idx, 0, plen) {
|
||||
Some(pbytes) =>
|
||||
if @crypto.ct_eq(@crypto.sha1(pbytes), meta.piece_hashes[piece_idx]) {
|
||||
t.have_pieces[piece_idx] = true
|
||||
plen
|
||||
} else {
|
||||
t.have_pieces[piece_idx] = false
|
||||
0
|
||||
}
|
||||
None => {
|
||||
t.have_pieces[piece_idx] = false
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_verify_existing_pieces(t : ActiveTorrent) -> Unit {
|
||||
let meta = match t.metainfo {
|
||||
@@ -397,20 +422,11 @@ fn bt_verify_existing_pieces(t : ActiveTorrent) -> Unit {
|
||||
let mut done_bytes = 0UL
|
||||
let mut all_have = num > 0
|
||||
for i = 0; i < num; i = i + 1 {
|
||||
let plen = bt_piece_length(meta, i)
|
||||
match bt_read_span_from_files(t, i, 0, plen) {
|
||||
Some(pbytes) =>
|
||||
if @crypto.ct_eq(@crypto.sha1(pbytes), meta.piece_hashes[i]) {
|
||||
t.have_pieces[i] = true
|
||||
done_bytes += plen.to_uint64()
|
||||
} else {
|
||||
t.have_pieces[i] = false
|
||||
all_have = false
|
||||
}
|
||||
None => {
|
||||
t.have_pieces[i] = false
|
||||
all_have = false
|
||||
}
|
||||
let verified_len = bt_verify_piece_at(t, meta, i)
|
||||
if verified_len > 0 {
|
||||
done_bytes += verified_len.to_uint64()
|
||||
} else {
|
||||
all_have = false
|
||||
}
|
||||
}
|
||||
t.downloaded_bytes = done_bytes
|
||||
@@ -421,6 +437,7 @@ fn bt_verify_existing_pieces(t : ActiveTorrent) -> Unit {
|
||||
fn bt_init_torrent_metainfo(
|
||||
t : ActiveTorrent,
|
||||
meta : @bittorrent.Metainfo,
|
||||
defer_verify~ : Bool = false,
|
||||
) -> Unit {
|
||||
t.name = meta.name
|
||||
t.raw_info = meta.raw_info
|
||||
@@ -430,7 +447,66 @@ fn bt_init_torrent_metainfo(
|
||||
for tr in meta.trackers {
|
||||
bt_add_tracker_url(t, tr)
|
||||
}
|
||||
bt_verify_existing_pieces(t)
|
||||
if defer_verify && meta.total_length > 16L * 1024L * 1024L {
|
||||
t.verify_cursor = 0
|
||||
t.downloaded_bytes = 0UL
|
||||
t.completed = false
|
||||
} else {
|
||||
t.verify_cursor = -1
|
||||
bt_verify_existing_pieces(t)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::bt_step_verify_pieces(self : Router, eng : TorrentEngine) -> Bool {
|
||||
for t in eng.torrents {
|
||||
if t.verify_cursor < 0 {
|
||||
continue
|
||||
}
|
||||
let meta = match t.metainfo {
|
||||
Some(m) => m
|
||||
None => {
|
||||
t.verify_cursor = -1
|
||||
return false
|
||||
}
|
||||
}
|
||||
let num = meta.piece_hashes.length()
|
||||
if t.have_pieces.length() != num {
|
||||
t.have_pieces = Array::make(num, false)
|
||||
}
|
||||
let mut checked_bytes = 0L
|
||||
let mut checked_any = false
|
||||
while t.verify_cursor < num &&
|
||||
(checked_bytes == 0L || checked_bytes < 4L * 1024L * 1024L) {
|
||||
let i = t.verify_cursor
|
||||
let plen = bt_piece_length(meta, i)
|
||||
let verified_len = bt_verify_piece_at(t, meta, i)
|
||||
if verified_len > 0 {
|
||||
t.downloaded_bytes += verified_len.to_uint64()
|
||||
}
|
||||
t.verify_cursor += 1
|
||||
checked_bytes += plen.to_int64()
|
||||
checked_any = true
|
||||
}
|
||||
if t.verify_cursor >= num {
|
||||
let mut all_have = num > 0
|
||||
for h in t.have_pieces {
|
||||
if !h {
|
||||
all_have = false
|
||||
break
|
||||
}
|
||||
}
|
||||
t.completed = all_have
|
||||
t.verify_cursor = -1
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] bt verified \{t.info_hash_hex[:12]} (\{t.downloaded_bytes}/\{meta.total_length}B, completed=\{t.completed})",
|
||||
)
|
||||
}
|
||||
}
|
||||
return checked_any
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -629,10 +705,12 @@ fn Router::ensure_torrent_session(self : Router) -> SamSession? {
|
||||
pub fn Router::enable_torrent_engine(
|
||||
self : Router,
|
||||
download_dir~ : String = "",
|
||||
state_file~ : String = "",
|
||||
dht_query_port~ : UInt32 = 6881U,
|
||||
dht_reply_port~ : UInt32 = 6882U,
|
||||
) -> Unit raise RouterError {
|
||||
let dl_trimmed = download_dir.trim().to_owned()
|
||||
let st_trimmed = state_file.trim().to_owned()
|
||||
let clean_dir = if dl_trimmed.length() > 0 {
|
||||
bt_normalize_dir(dl_trimmed)
|
||||
} else {
|
||||
@@ -644,6 +722,10 @@ pub fn Router::enable_torrent_engine(
|
||||
if dl_trimmed.length() > 0 {
|
||||
eng.download_dir = clean_dir
|
||||
}
|
||||
if st_trimmed.length() > 0 && eng.state_file != st_trimmed {
|
||||
eng.state_file = st_trimmed
|
||||
self.load_torrent_state()
|
||||
}
|
||||
return
|
||||
}
|
||||
None => ()
|
||||
@@ -671,6 +753,7 @@ pub fn Router::enable_torrent_engine(
|
||||
session_id: sess.id,
|
||||
peer_id: pw.to_bytes(),
|
||||
download_dir: clean_dir,
|
||||
state_file: st_trimmed,
|
||||
dht,
|
||||
torrents: [],
|
||||
pending_inbound: [],
|
||||
@@ -682,6 +765,9 @@ pub fn Router::enable_torrent_engine(
|
||||
last_ls2_pub_tunnels: self.tunnels.inbound.length(),
|
||||
ls2_gen: 1,
|
||||
})
|
||||
if st_trimmed.length() > 0 {
|
||||
self.load_torrent_state()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -769,6 +855,7 @@ pub fn Router::add_torrent_bytes(
|
||||
bt_add_tracker_url(existing, tr)
|
||||
}
|
||||
existing.paused = false
|
||||
self.save_torrent_state()
|
||||
return hex
|
||||
}
|
||||
None => ()
|
||||
@@ -789,6 +876,7 @@ pub fn Router::add_torrent_bytes(
|
||||
uploaded_bytes: 0UL,
|
||||
have_pieces: Array::make(meta.piece_hashes.length(), false),
|
||||
inflight_pieces: [],
|
||||
verify_cursor: -1,
|
||||
meta_size: meta.raw_info.length(),
|
||||
meta_pieces: [],
|
||||
meta_req_ms: 0UL,
|
||||
@@ -805,6 +893,7 @@ pub fn Router::add_torrent_bytes(
|
||||
Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
|
||||
None => ()
|
||||
}
|
||||
self.save_torrent_state()
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] bt added torrent \{hex[:12]} '\{meta.name}' (\{meta.piece_hashes.length()} pcs, \{meta.total_length}B, \{t.trackers.length()} trackers)",
|
||||
@@ -859,6 +948,7 @@ pub fn Router::add_torrent_magnet(
|
||||
}
|
||||
}
|
||||
existing.paused = false
|
||||
self.save_torrent_state()
|
||||
return hex
|
||||
}
|
||||
None => ()
|
||||
@@ -883,6 +973,7 @@ pub fn Router::add_torrent_magnet(
|
||||
uploaded_bytes: 0UL,
|
||||
have_pieces: [],
|
||||
inflight_pieces: [],
|
||||
verify_cursor: -1,
|
||||
meta_size: 0,
|
||||
meta_pieces: [],
|
||||
meta_req_ms: 0UL,
|
||||
@@ -909,6 +1000,7 @@ pub fn Router::add_torrent_magnet(
|
||||
Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
|
||||
None => ()
|
||||
}
|
||||
self.save_torrent_state()
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] bt added magnet \{hex[:12]} '\{t.name}' (\{t.trackers.length()} trackers)",
|
||||
@@ -947,6 +1039,7 @@ pub fn Router::pause_torrent(self : Router, info_hash_hex : String) -> Bool {
|
||||
}
|
||||
}
|
||||
t.peers.clear()
|
||||
self.save_torrent_state()
|
||||
true
|
||||
}
|
||||
None => false
|
||||
@@ -966,6 +1059,7 @@ pub fn Router::resume_torrent(self : Router, info_hash_hex : String) -> Bool {
|
||||
for tr in t.trackers {
|
||||
tr.next_announce_ms = 0UL
|
||||
}
|
||||
self.save_torrent_state()
|
||||
true
|
||||
}
|
||||
None => false
|
||||
@@ -1009,6 +1103,7 @@ pub fn Router::remove_torrent(self : Router, info_hash_hex : String) -> Bool {
|
||||
}
|
||||
}
|
||||
let _ = eng.torrents.remove(i)
|
||||
self.save_torrent_state()
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1576,7 +1671,7 @@ fn Router::step_dht(
|
||||
// Per-torrent DHT peer lookup & announce
|
||||
let query_cd_ms = if self.public_mode { 60000UL } else { 1500UL }
|
||||
for t in eng.torrents {
|
||||
if t.paused || eng.dht.nodes.length() == 0 {
|
||||
if t.paused || t.verify_cursor >= 0 || eng.dht.nodes.length() == 0 {
|
||||
continue
|
||||
}
|
||||
eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
|
||||
@@ -1632,7 +1727,7 @@ fn Router::step_trackers(
|
||||
let now_sec = (now_ms / 1000UL).to_uint()
|
||||
let mut did_work = false
|
||||
for t in eng.torrents {
|
||||
if t.paused {
|
||||
if t.paused || t.verify_cursor >= 0 {
|
||||
continue
|
||||
}
|
||||
for tr in t.trackers {
|
||||
@@ -2155,6 +2250,7 @@ fn Router::bt_handle_ext_message(
|
||||
}
|
||||
bt_init_torrent_metainfo(t, parsed)
|
||||
t.meta_pieces.clear()
|
||||
self.save_torrent_state()
|
||||
} else {
|
||||
t.meta_pieces.clear()
|
||||
}
|
||||
@@ -2769,6 +2865,11 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
|
||||
self.publish_session_leaseset2(sess)
|
||||
}
|
||||
|
||||
// 0b. Incremental piece verification for restored large torrents
|
||||
if self.bt_step_verify_pieces(eng) {
|
||||
did_work = true
|
||||
}
|
||||
|
||||
// 1. Poll I2P DHT datagrams (proto 0x11 + 0x12) and run DHT maintenance
|
||||
if self.poll_dht_datagrams(eng, sess, mgr, now_ms) {
|
||||
did_work = true
|
||||
@@ -2850,7 +2951,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
|
||||
match parsed_hs {
|
||||
Some((_ext, ih, _remote_pid)) =>
|
||||
match bt_find_torrent_by_ih(eng, ih) {
|
||||
Some(t) if !t.paused => {
|
||||
Some(t) if !t.paused && t.verify_cursor < 0 => {
|
||||
let _ = bt_add_known_peer(t, ib.peer_hash, sess.hash)
|
||||
bt_pop_front_bytes(ib.recv_buf, 68)
|
||||
let rem_buf : Array[Byte] = []
|
||||
@@ -2935,7 +3036,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
|
||||
|
||||
// 4. Spawn outbound peer connections and pump active peer swarms
|
||||
for t in eng.torrents {
|
||||
if t.paused {
|
||||
if t.paused || t.verify_cursor >= 0 {
|
||||
continue
|
||||
}
|
||||
// Spawn up to 16 peers per torrent when incomplete
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
///|
|
||||
/// EDN persistence (`torrents.edn`) for active and paused I2P BitTorrent entries.
|
||||
|
||||
///|
|
||||
/// Explicit `moonedn` limits large enough for torrents with multi-hundred-KiB `:info-b64` blobs.
|
||||
let bt_edn_limits : @edn.Limits = {
|
||||
input: 64 * 1024 * 1024,
|
||||
depth: 64,
|
||||
nodes: 1000000,
|
||||
token: 16 * 1024 * 1024,
|
||||
container: 100000,
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_parent_dir_of_file(path : String) -> String {
|
||||
let mut i = path.length() - 1
|
||||
while i >= 0 {
|
||||
if path[i] == '/' {
|
||||
if i == 0 {
|
||||
return "/"
|
||||
}
|
||||
return path[:i].to_owned()
|
||||
}
|
||||
i -= 1
|
||||
}
|
||||
""
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_edn_map_get_kw(
|
||||
entries : Array[(@edn.Value, @edn.Value)],
|
||||
kw : String,
|
||||
) -> @edn.Value? {
|
||||
for e in entries {
|
||||
match e.0 {
|
||||
Keyword(k) if k == kw => return Some(e.1)
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_encode_torrents_edn(
|
||||
torrents : Array[ActiveTorrent],
|
||||
) -> String raise @edn.EdnError {
|
||||
let items : Array[@edn.Value] = Array(capacity=torrents.length())
|
||||
for t in torrents {
|
||||
let trackers : Array[@edn.Value] = Array(capacity=t.trackers.length())
|
||||
for tr in t.trackers {
|
||||
trackers.push(@edn.Value::Text(tr.url))
|
||||
}
|
||||
let fields : Array[(@edn.Value, @edn.Value)] = [
|
||||
(@edn.Value::Keyword("info-hash"), @edn.Value::Text(t.info_hash_hex)),
|
||||
(@edn.Value::Keyword("name"), @edn.Value::Text(t.name)),
|
||||
(@edn.Value::Keyword("download-dir"), @edn.Value::Text(t.download_dir)),
|
||||
(@edn.Value::Keyword("paused"), @edn.Value::Bool(t.paused)),
|
||||
(@edn.Value::Keyword("trackers"), @edn.Value::Vector(trackers)),
|
||||
]
|
||||
if t.raw_info.length() > 0 {
|
||||
fields.push(
|
||||
(
|
||||
@edn.Value::Keyword("info-b64"),
|
||||
@edn.Value::Text(@encoding.base64_std_encode(t.raw_info)),
|
||||
),
|
||||
)
|
||||
}
|
||||
items.push(@edn.Value::Mapping(fields))
|
||||
}
|
||||
let doc = @edn.Value::Mapping([
|
||||
(@edn.Value::Keyword("version"), @edn.Value::Integer("1")),
|
||||
(@edn.Value::Keyword("torrents"), @edn.Value::Vector(items)),
|
||||
])
|
||||
let body = @edn.pretty(
|
||||
doc,
|
||||
layout={ width: 100, indent: 2, },
|
||||
limits=bt_edn_limits,
|
||||
)
|
||||
";; moon-i2p torrent list (EDN) — restored on router startup\n" +
|
||||
body +
|
||||
"\n"
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::save_torrent_state(self : Router) -> Unit {
|
||||
let eng = match self.torrent_engine {
|
||||
Some(e) => e
|
||||
None => return
|
||||
}
|
||||
if eng.state_file.length() == 0 {
|
||||
return
|
||||
}
|
||||
let parent = bt_parent_dir_of_file(eng.state_file)
|
||||
if parent.length() > 0 {
|
||||
let _ = @ntcp2_net.mkdir_p(parent) catch {
|
||||
e => {
|
||||
println(
|
||||
"warning: failed to create torrent state dir \{parent}: \{bt_net_err_msg(e)}",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
let encoded = bt_encode_torrents_edn(eng.torrents) catch {
|
||||
_ => {
|
||||
println("warning: failed to serialize torrent state to EDN")
|
||||
return
|
||||
}
|
||||
}
|
||||
let bytes = @encoding.string_to_utf8_bytes(encoded)
|
||||
@ntcp2_net.write_file_atomic(eng.state_file, bytes) catch {
|
||||
e =>
|
||||
println(
|
||||
"warning: failed to persist torrent state \{eng.state_file}: \{bt_net_err_msg(e)}",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::load_torrent_state(self : Router) -> Unit {
|
||||
let eng = match self.torrent_engine {
|
||||
Some(e) => e
|
||||
None => return
|
||||
}
|
||||
if eng.state_file.length() == 0 || !@ntcp2_net.file_exists(eng.state_file) {
|
||||
return
|
||||
}
|
||||
let raw = @ntcp2_net.read_file_bytes(eng.state_file) catch {
|
||||
e => {
|
||||
println(
|
||||
"warning: failed to read torrent state \{eng.state_file}: \{bt_net_err_msg(e)}",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
let text = @encoding.utf8_bytes_to_string(raw) catch {
|
||||
_ => {
|
||||
println("warning: invalid UTF-8 in torrent state \{eng.state_file}")
|
||||
return
|
||||
}
|
||||
}
|
||||
let root = @edn.read(text, limits=bt_edn_limits) catch {
|
||||
_ => {
|
||||
println("warning: invalid EDN in torrent state \{eng.state_file}")
|
||||
return
|
||||
}
|
||||
}
|
||||
let root_entries = match root {
|
||||
Mapping(entries) => entries
|
||||
_ => {
|
||||
println("warning: torrent state \{eng.state_file} must be an EDN map")
|
||||
return
|
||||
}
|
||||
}
|
||||
match bt_edn_map_get_kw(root_entries, "version") {
|
||||
Some(Integer("1")) | None => ()
|
||||
Some(_) => {
|
||||
println("warning: unsupported torrent state version in \{eng.state_file}")
|
||||
return
|
||||
}
|
||||
}
|
||||
let items = match bt_edn_map_get_kw(root_entries, "torrents") {
|
||||
Some(Vector(v)) => v
|
||||
_ => return
|
||||
}
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let mut restored = 0
|
||||
for item in items {
|
||||
let fields = match item {
|
||||
Mapping(f) => f
|
||||
_ => continue
|
||||
}
|
||||
let hex_raw = match bt_edn_map_get_kw(fields, "info-hash") {
|
||||
Some(Text(s)) => bt_hex_lower(s.trim().to_owned())
|
||||
_ => continue
|
||||
}
|
||||
let ih = @encoding.hex_decode(hex_raw) catch { _ => continue }
|
||||
if ih.length() != 20 {
|
||||
continue
|
||||
}
|
||||
if bt_find_torrent_by_ih(eng, ih) is Some(_) {
|
||||
continue
|
||||
}
|
||||
let name = match bt_edn_map_get_kw(fields, "name") {
|
||||
Some(Text(s)) if s.length() > 0 => s
|
||||
_ => hex_raw
|
||||
}
|
||||
let target_dir = match bt_edn_map_get_kw(fields, "download-dir") {
|
||||
Some(Text(s)) => {
|
||||
let trimmed = s.trim().to_owned()
|
||||
if trimmed.length() > 0 {
|
||||
let norm = bt_normalize_dir(trimmed)
|
||||
let mk_ok = try {
|
||||
@ntcp2_net.mkdir_p(norm)
|
||||
true
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
if mk_ok {
|
||||
norm
|
||||
} else {
|
||||
eng.download_dir
|
||||
}
|
||||
} else {
|
||||
eng.download_dir
|
||||
}
|
||||
}
|
||||
_ => eng.download_dir
|
||||
}
|
||||
let paused = match bt_edn_map_get_kw(fields, "paused") {
|
||||
Some(Bool(b)) => b
|
||||
_ => false
|
||||
}
|
||||
let tracker_urls : Array[String] = []
|
||||
match bt_edn_map_get_kw(fields, "trackers") {
|
||||
Some(Vector(tv)) =>
|
||||
for entry in tv {
|
||||
match entry {
|
||||
Text(u) if u.length() > 0 => tracker_urls.push(u)
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
let mut meta_opt : @bittorrent.Metainfo? = None
|
||||
match bt_edn_map_get_kw(fields, "info-b64") {
|
||||
Some(Text(b64)) if b64.length() > 0 => {
|
||||
let raw_opt = Some(@encoding.base64_std_decode(b64)) catch {
|
||||
_ => {
|
||||
println(
|
||||
"warning: invalid :info-b64 for \{hex_raw[:12]} in \{eng.state_file}",
|
||||
)
|
||||
None
|
||||
}
|
||||
}
|
||||
match raw_opt {
|
||||
Some(raw_info) =>
|
||||
if @crypto.ct_eq(@crypto.sha1(raw_info), ih) {
|
||||
meta_opt = Some(
|
||||
@bittorrent.parse_info_dict(raw_info, trackers=tracker_urls),
|
||||
) catch {
|
||||
e => {
|
||||
println(
|
||||
"warning: invalid metainfo for \{hex_raw[:12]}: \{bt_err_msg(e)}",
|
||||
)
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println(
|
||||
"warning: info_hash mismatch for \{hex_raw[:12]} in \{eng.state_file}; restoring without metainfo",
|
||||
)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
let t : ActiveTorrent = {
|
||||
info_hash: ih,
|
||||
info_hash_hex: hex_raw,
|
||||
name,
|
||||
download_dir: target_dir,
|
||||
metainfo: None,
|
||||
raw_info: b"",
|
||||
paused,
|
||||
completed: false,
|
||||
error: "",
|
||||
last_tracker_status: "",
|
||||
downloaded_bytes: 0UL,
|
||||
uploaded_bytes: 0UL,
|
||||
have_pieces: [],
|
||||
inflight_pieces: [],
|
||||
verify_cursor: -1,
|
||||
meta_size: 0,
|
||||
meta_pieces: [],
|
||||
meta_req_ms: 0UL,
|
||||
known_peers: [],
|
||||
peer_backoff: [],
|
||||
peers: [],
|
||||
trackers: [],
|
||||
last_dht_lookup_ms: 0UL,
|
||||
last_pex_ms: 0UL,
|
||||
}
|
||||
for tr in tracker_urls {
|
||||
bt_add_tracker_url(t, tr)
|
||||
}
|
||||
match meta_opt {
|
||||
Some(meta) => bt_init_torrent_metainfo(t, meta, defer_verify=true)
|
||||
None => ()
|
||||
}
|
||||
eng.torrents.push(t)
|
||||
match self.find_session_by_id(eng.session_id) {
|
||||
Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
|
||||
None => ()
|
||||
}
|
||||
restored += 1
|
||||
}
|
||||
if restored > 0 {
|
||||
println(" Restored \{restored} torrent(s) from \{eng.state_file}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
///|
|
||||
test "bt_step_verify_pieces verifies multi-MiB torrent incrementally across ticks" {
|
||||
let rand_hex = @encoding.hex_encode(@ntcp2_net.random_bytes(4))
|
||||
let base_dir = "/tmp/moon_i2p_incr_verify_test_\{rand_hex}"
|
||||
@ntcp2_net.mkdir_p(base_dir)
|
||||
|
||||
let piece_len = 1048576
|
||||
let num_pieces = 5
|
||||
let total_len = piece_len * num_pieces
|
||||
let piece0 = Bytes::make(piece_len, b'\x11')
|
||||
let piece1 = Bytes::make(piece_len, b'\x22')
|
||||
let piece2 = Bytes::make(piece_len, b'\x33')
|
||||
let piece3 = Bytes::make(piece_len, b'\x44')
|
||||
let piece4 = Bytes::make(piece_len, b'\x55')
|
||||
let pieces_data = [piece0, piece1, piece2, piece3, piece4]
|
||||
|
||||
let hashes = @encoding.Writer::new()
|
||||
for i = 0; i < num_pieces; i = i + 1 {
|
||||
@ntcp2_net.write_file_at(
|
||||
base_dir + "/incr.bin",
|
||||
(i * piece_len).to_int64(),
|
||||
pieces_data[i],
|
||||
)
|
||||
hashes.write_bytes(@crypto.sha1(pieces_data[i]))
|
||||
}
|
||||
let tbytes = @bittorrent.bencode_encode(
|
||||
BDict([
|
||||
(
|
||||
b"info",
|
||||
BDict([
|
||||
(b"length", BInt(total_len.to_int64())),
|
||||
(b"name", BBytes(b"incr.bin")),
|
||||
(b"piece length", BInt(piece_len.to_int64())),
|
||||
(b"pieces", BBytes(hashes.to_bytes())),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)
|
||||
let meta = @bittorrent.parse_torrent(tbytes)
|
||||
let r = Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer r.close()
|
||||
r.enable_torrent_engine(download_dir=base_dir)
|
||||
let eng = match r.torrent_engine {
|
||||
Some(e) => e
|
||||
None => fail("missing torrent engine")
|
||||
}
|
||||
let hex = @encoding.hex_encode(meta.info_hash)
|
||||
let t : ActiveTorrent = {
|
||||
info_hash: meta.info_hash,
|
||||
info_hash_hex: hex,
|
||||
name: meta.name,
|
||||
download_dir: base_dir,
|
||||
metainfo: Some(meta),
|
||||
raw_info: meta.raw_info,
|
||||
paused: false,
|
||||
completed: false,
|
||||
error: "",
|
||||
last_tracker_status: "",
|
||||
downloaded_bytes: 0UL,
|
||||
uploaded_bytes: 0UL,
|
||||
have_pieces: Array::make(num_pieces, false),
|
||||
inflight_pieces: [],
|
||||
verify_cursor: 0,
|
||||
meta_size: meta.raw_info.length(),
|
||||
meta_pieces: [],
|
||||
meta_req_ms: 0UL,
|
||||
known_peers: [],
|
||||
peer_backoff: [],
|
||||
peers: [],
|
||||
trackers: [],
|
||||
last_dht_lookup_ms: 0UL,
|
||||
last_pex_ms: 0UL,
|
||||
}
|
||||
eng.torrents.push(t)
|
||||
|
||||
assert_true(r.build_api_torrents_json().contains("\"state\":\"checking\""))
|
||||
// Tick 1: 4 MiB budget verifies pieces 0..3 and leaves piece 4 pending
|
||||
assert_true(r.bt_step_verify_pieces(eng))
|
||||
assert_eq(t.verify_cursor, 4)
|
||||
assert_eq(t.downloaded_bytes, (4 * piece_len).to_uint64())
|
||||
assert_true(!t.completed)
|
||||
assert_true(r.build_api_torrents_json().contains("\"state\":\"checking\""))
|
||||
|
||||
// Tick 2: finishes piece 4 and clears checking state
|
||||
assert_true(r.bt_step_verify_pieces(eng))
|
||||
assert_eq(t.verify_cursor, -1)
|
||||
assert_eq(t.downloaded_bytes, total_len.to_uint64())
|
||||
assert_true(t.completed)
|
||||
assert_eq(t.have_pieces, [true, true, true, true, true])
|
||||
assert_true(r.build_api_torrents_json().contains("\"state\":\"seeding\""))
|
||||
assert_true(!r.bt_step_verify_pieces(eng))
|
||||
}
|
||||
|
||||
///|
|
||||
test "EDN persistence round-trips large >64 KiB info-b64 payloads" {
|
||||
let rand_hex = @encoding.hex_encode(@ntcp2_net.random_bytes(4))
|
||||
let base_dir = "/tmp/moon_i2p_large_edn_test_\{rand_hex}"
|
||||
let dl_dir = "\{base_dir}/dl"
|
||||
let state_file = "\{base_dir}/torrents.edn"
|
||||
@ntcp2_net.mkdir_p(dl_dir)
|
||||
|
||||
// 3,000 pieces * 20 bytes = 60,000-byte raw pieces => >60 KiB raw_info => >80 KiB base64 token
|
||||
let raw_pieces = Bytes::make(60000, b'\xAB')
|
||||
let tbytes = @bittorrent.bencode_encode(
|
||||
BDict([
|
||||
(b"announce", BBytes(b"http://tracker.insulaocculta.i2p/a")),
|
||||
(
|
||||
b"info",
|
||||
BDict([
|
||||
(b"length", BInt(3000L * 262144L)),
|
||||
(b"name", BBytes(b"large-catalog.bin")),
|
||||
(b"piece length", BInt(262144L)),
|
||||
(b"pieces", BBytes(raw_pieces)),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)
|
||||
let meta = @bittorrent.parse_torrent(tbytes)
|
||||
assert_true(@encoding.base64_std_encode(meta.raw_info).length() > 70000)
|
||||
|
||||
let r1 = Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
r1.enable_torrent_engine(download_dir=dl_dir, state_file~)
|
||||
let ih = r1.add_torrent_bytes(tbytes, download_dir=dl_dir)
|
||||
r1.close()
|
||||
|
||||
let r2 = Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer r2.close()
|
||||
r2.enable_torrent_engine(download_dir=dl_dir, state_file~)
|
||||
let eng2 = match r2.torrent_engine {
|
||||
Some(e) => e
|
||||
None => fail("missing eng2")
|
||||
}
|
||||
assert_eq(eng2.torrents.length(), 1)
|
||||
assert_eq(eng2.torrents[0].info_hash_hex, ih)
|
||||
assert_eq(eng2.torrents[0].raw_info, meta.raw_info)
|
||||
assert_eq(eng2.torrents[0].verify_cursor, 0)
|
||||
}
|
||||
Reference in new issue
Block a user