Files
moon-i2p/bittorrent/bittorrent_test.mbt
T
nandi fbe6818c4e
check / check (macos-latest) (push) Failing after 29s
check / check (ubuntu-latest) (push) Failing after 29s
check / check (windows-latest) (push) Failing after 30s
feat: add I2P BitTorrent engine, DHT, and Firefox torrent extension
- Add pure-MoonBit bittorrent package: bencode codec, metainfo/magnet parsing with path traversal checks, peer wire protocol (BEP 10/9), and I2P Kademlia DHT with KRPC and 54-byte compact nodes
- Add SHA-1 primitive in crypto for torrent info hashes
- Add router torrent API and engine, enabled with --torrent-api (default 127.0.0.1:4445) and --download-dir
- Add Firefox WebExtension torrent manager with native messaging host and packed .xpi
- Add scripts to build a standalone Firefox + router AppImage and install the native host
- Add just targets (proxy, appimage, extension), README docs, and ignore .cache/ and dist/
2026-11-28 13:19:03 -08:00

270 lines
8.6 KiB
MoonBit

///|
test "Bencode encode/decode canonical sorting and raw info slice extraction" {
let val : @bittorrent.BVal = BDict([
(b"z", BInt(-42L)),
(b"a", BList([BBytes(b"hi"), BInt(0L), BBytes(b"")])),
])
let enc = @bittorrent.bencode_encode(val)
assert_eq(enc, b"d1:al2:hii0e0:e1:zi-42ee")
// Keys are sorted lexicographically in encoded output: 1:a before 1:z
let expected : @bittorrent.BVal = BDict([
(b"a", BList([BBytes(b"hi"), BInt(0L), BBytes(b"")])),
(b"z", BInt(-42L)),
])
assert_eq(@bittorrent.bencode_decode(enc), expected)
assert_eq(@bittorrent.bencode_encode(val), b"d1:al2:hii0e0:e1:zi-42ee")
assert_eq(enc, b"d1:al2:hii0e0:e1:zi-42ee")
// Prefix decode leaves trailing raw slice intact (BEP 9 ut_metadata)
let combined = b"d8:msg_typei1e5:piecei0eeRAW_SLICE"
let (hdr, next_off) = @bittorrent.bencode_decode_prefix(combined)
assert_eq(@bittorrent.bdict_get_int(hdr, "msg_type"), Some(1L))
assert_eq(combined[next_off:].to_owned(), b"RAW_SLICE")
}
///|
test "Metainfo parsing, path traversal rejection, and magnet hex/base32 links" {
let data = b"Hello I2P BitTorrent world!"
let phash = @crypto.sha1(data)
let raw_info = @bittorrent.bencode_encode(
BDict([
(b"length", BInt(data.length().to_int64())),
(b"name", BBytes(b"hello.txt")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(phash)),
]),
)
let torrent = @bittorrent.bencode_encode(
BDict([
(b"announce", BBytes(b"http://tracker.insulaocculta.i2p/a")),
(
b"announce-list",
BList([BList([BBytes(b"http://opentracker.dg2.i2p/a")])]),
),
(
b"info",
BDict([
(b"length", BInt(data.length().to_int64())),
(b"name", BBytes(b"hello.txt")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(phash)),
]),
),
]),
)
let meta = @bittorrent.parse_torrent(torrent)
assert_eq(meta.info_hash, @crypto.sha1(raw_info))
assert_eq(meta.name, "hello.txt")
assert_eq(meta.total_length, 27L)
assert_eq(meta.files.length(), 1)
assert_eq(meta.files[0].path, ["hello.txt"])
assert_eq(meta.trackers.length(), 2)
// Reject path traversal segments in multi-file info dictionary
let evil_info = @bittorrent.bencode_encode(
BDict([
(
b"files",
BList([
BDict([
(b"length", BInt(5L)),
(b"path", BList([BBytes(b".."), BBytes(b"etc"), BBytes(b"passwd")])),
]),
]),
),
(b"name", BBytes(b"bad")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(@crypto.sha1(b"12345"))),
]),
)
let mut rejected = false
let _ = @bittorrent.parse_info_dict(evil_info) catch {
_ => {
rejected = true
meta
}
}
assert_true(rejected)
// Hex & Base32 magnet links
let hex_ih = @encoding.hex_encode(meta.info_hash)
let m1 = @bittorrent.parse_magnet(
"magnet:?xt=urn:btih:\{hex_ih}&dn=hello+world.txt&tr=http%3A%2F%2Ftracker.insulaocculta.i2p%2Fa",
)
assert_eq(m1.info_hash, meta.info_hash)
assert_eq(m1.display_name, "hello world.txt")
assert_eq(m1.trackers, ["http://tracker.insulaocculta.i2p/a"])
let b32_ih = @encoding.base32_encode(meta.info_hash)
let m2 = @bittorrent.parse_magnet("magnet:?xt=urn:btih:\{b32_ih}")
assert_eq(m2.info_hash, meta.info_hash)
}
///|
test "Peer wire framing, BEP 10/9, i2p_pex, i2p_dht, and chunked I2P HTTP tracker" {
let ih = @crypto.sha1(b"ih-wire-test")
let pid = @crypto.sha1(b"peer-id-test")
let hs = @bittorrent.encode_handshake(ih, pid)
let (res, dih, dpid) = @bittorrent.decode_handshake(hs)
assert_eq(res[5], b'\x10')
assert_eq(dih, ih)
assert_eq(dpid, pid)
let stream_buf : Array[Byte] = []
let msgs : Array[@bittorrent.PeerMessage] = [
KeepAlive,
Unchoke,
Interested,
Have(7U),
Bitfield(b"\x80"),
Request(1, 0, 16384),
Piece(1, 0, b"payload-bytes"),
Extended(b'\x00', @bittorrent.encode_ext_handshake(metadata_size=Some(512))),
Extended(b'\x03', @bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
]
for m in msgs {
let enc = @bittorrent.encode_peer_message(m)
for i = 0; i < enc.length(); i = i + 1 {
stream_buf.push(enc[i])
}
}
for expected in msgs {
assert_eq(@bittorrent.try_decode_peer_message(stream_buf), Some(expected))
}
assert_eq(@bittorrent.try_decode_peer_message(stream_buf), None)
// Extended handshake + i2p_dht + i2p_pex + ut_metadata
let rext = @bittorrent.decode_ext_handshake(
@bittorrent.encode_ext_handshake(metadata_size=Some(512)),
)
assert_eq(rext.i2p_pex_id, Some(b'\x01'))
assert_eq(rext.ut_metadata_id, Some(b'\x02'))
assert_eq(rext.i2p_dht_id, Some(b'\x03'))
assert_eq(rext.metadata_size, Some(512))
assert_eq(
@bittorrent.decode_i2p_dht_ext(@bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
Some((6881U, 6882U)),
)
let h1 = @common.Hash::sha256(b"peer1")
let h2 = @common.Hash::sha256(b"peer2")
assert_eq(@bittorrent.decode_i2p_pex(@bittorrent.encode_i2p_pex([h1, h2])), [
h1, h2,
])
let md_raw = @bittorrent.encode_metadata_data(0, 128, b"INFO_SLICE")
assert_eq(
@bittorrent.decode_metadata_msg(md_raw),
MetaData(0, 128, b"INFO_SLICE"),
)
// Chunked I2P HTTP tracker response with 32B compact peer hashes
let compact_peers = @encoding.Writer::new(capacity=64)
compact_peers.write_bytes(h1.as_bytes())
compact_peers.write_bytes(h2.as_bytes())
let bbody = @bittorrent.bencode_encode(
BDict([
(b"complete", BInt(3L)),
(b"incomplete", BInt(1L)),
(b"interval", BInt(120L)),
(b"peers", BBytes(compact_peers.to_bytes())),
]),
)
let http_resp = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n\{bbody.length().to_int64()}\r\n"
// Hex chunk size
let hex_len = bbody.length()
let mut hx = ""
if hex_len < 16 {
hx = "0"
}
let _ = http_resp
let chunked = @encoding.Writer::new()
chunked.write_bytes(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
// Compute hex digits of bbody.length()
let digits : Array[Char] = []
let mut n = hex_len
while n > 0 {
let d = n % 16
digits.push(
if d < 10 {
(48 + d).unsafe_to_char()
} else {
(97 + d - 10).unsafe_to_char()
},
)
n = n / 16
}
let hx_sb = StringBuilder()
for k = digits.length() - 1; k >= 0; k = k - 1 {
hx_sb.write_char(digits[k])
}
let _ = hx
chunked.write_bytes(
@encoding.string_to_utf8_bytes(hx_sb.to_string() + "\r\n"),
)
chunked.write_bytes(bbody)
chunked.write_bytes(b"\r\n0\r\n\r\n")
let tresp = @bittorrent.parse_http_tracker_response(chunked.to_bytes())
assert_eq(tresp.interval, 120)
assert_eq(tresp.complete, 3)
assert_eq(tresp.incomplete, 1)
assert_eq(tresp.peers, [h1, h2])
}
///|
test "I2P DHT Secure Node ID, 54B compact nodes, KRPC round-trips, and XOR routing" {
let dh_a = @common.Hash::sha256(b"node-a-dest")
let dh_b = @common.Hash::sha256(b"node-b-dest")
let dht_a = @bittorrent.I2pDht::new(
dh_a,
b"rand14bytes_aa",
b"secret-a",
query_port=6881U,
reply_port=6882U,
)
assert_true(@bittorrent.verify_i2p_dht_node_id(dht_a.local_id, dh_a, 6881U))
assert_true(!@bittorrent.verify_i2p_dht_node_id(dht_a.local_id, dh_a, 6889U))
let id_b = @bittorrent.make_i2p_dht_node_id(dh_b, 6881U, b"rand14bytes_bb")
assert_true(dht_a.upsert_node(id_b, dh_b, 6881U, 1000UL))
assert_eq(dht_a.nodes.length(), 1)
// Tampered Node ID must fail Secure Node ID check
assert_true(!dht_a.upsert_node(Bytes::make(20, b'\x77'), dh_b, 6881U, 1001UL))
// 54B compact node encode/decode round-trip
let nodes_blob = @bittorrent.encode_compact_nodes(dht_a.closest_nodes(id_b))
assert_eq(nodes_blob.length(), 54)
let decoded_nodes = @bittorrent.decode_compact_nodes(
nodes_blob,
now_ms=2000UL,
)
assert_eq(decoded_nodes.length(), 1)
assert_eq(decoded_nodes[0].node_id, id_b)
assert_eq(decoded_nodes[0].dest_hash, dh_b)
assert_eq(decoded_nodes[0].port, 6881U)
// KRPC queries & responses round-trip
let ih = @crypto.sha1(b"dht-swarm-hash")
let tok = dht_a.make_token(dh_b)
assert_true(dht_a.verify_token(dh_b, tok))
assert_true(!dht_a.verify_token(dh_a, tok))
let q_gp : @bittorrent.KrpcMessage = Query(
tx_id=b"t1",
sender_id=id_b,
kind=GetPeers(info_hash=ih),
)
assert_eq(@bittorrent.decode_krpc(@bittorrent.encode_krpc(q_gp)), q_gp)
dht_a.store_peer(ih, dh_b, 5000UL)
assert_eq(dht_a.get_peers_local(ih, 5001UL), [dh_b])
let r_gp : @bittorrent.KrpcMessage = Response(
tx_id=b"t1",
sender_id=dht_a.local_id,
nodes=nodes_blob,
values=[dh_b.as_bytes()],
token=Some(tok),
)
assert_eq(@bittorrent.decode_krpc(@bittorrent.encode_krpc(r_gp)), r_gp)
}