1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
//! Piece hash verification, optionally offloaded to a `std` worker pool so
//! the engine loop keeps pumping I/O while SHA-1 / SHA-256 runs on other
//! cores. Under `no_std`, [`VerifyPool`] is a no-op handle (inline
//! verification). Both paths share the pure [`verify_piece`] function, so
//! pooled and inline results are guaranteed identical.
use crate::metainfo::{InfoHash, TorrentKind};
use alloc::vec::Vec;
/// Which hash to check a piece against.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HashKind {
/// v1: SHA-1 of the whole piece.
Sha1,
/// v2: Merkle root of the 16 KiB block SHA-256s (BEP-52).
Sha256Merkle,
}
impl From<TorrentKind> for HashKind {
fn from(k: TorrentKind) -> Self {
match k {
TorrentKind::V1 => HashKind::Sha1,
TorrentKind::V2 | TorrentKind::Hybrid => HashKind::Sha256Merkle,
}
}
}
/// A verification task (all data owned, so it can cross threads freely).
pub struct VerifyJob {
/// Owning torrent (routes the result back to its session).
pub torrent: InfoHash,
/// Piece index.
pub piece: u32,
/// Expected piece length.
pub len: u32,
/// Hash kind.
pub kind: HashKind,
/// Expected hash bytes (20 for v1, 32 for v2).
pub expect: Vec<u8>,
/// Assembled piece bytes.
pub data: Vec<u8>,
}
/// Outcome of a verification task. `data` travels back so the engine can
/// write the verified piece to disk.
pub struct VerifyResult {
/// Owning torrent.
pub torrent: InfoHash,
/// Piece index.
pub piece: u32,
/// Whether the hash matched.
pub ok: bool,
/// The piece bytes.
pub data: Vec<u8>,
}
/// Verify piece bytes against the expected hash. Pure and thread-safe;
/// shared by the inline path and the worker pool.
pub fn verify_piece(kind: HashKind, len: u32, data: &[u8], expect: &[u8]) -> bool {
if data.len() != len as usize {
return false;
}
match kind {
HashKind::Sha1 => expect.len() == 20 && crate::crypto::Sha1::digest(data) == expect[..20],
HashKind::Sha256Merkle => {
if expect.len() != 32 {
return false;
}
let blocks: Vec<[u8; 32]> = data
.chunks(crate::consts::BLOCK_LEN as usize)
.map(crate::crypto::Sha256::digest)
.collect();
crate::metainfo::merkle_root(&blocks) == expect[..32]
}
}
}
// ---------------------------------------------------------------------------
// Worker pool (real threads under `std`)
// ---------------------------------------------------------------------------
#[cfg(feature = "std")]
mod pool {
use super::{VerifyJob, VerifyResult};
use alloc::vec::Vec;
use std::sync::mpsc;
pub(crate) struct VerifyPoolInner {
txs: Vec<mpsc::Sender<VerifyJob>>,
rxs: Vec<mpsc::Receiver<VerifyResult>>,
workers: Vec<std::thread::JoinHandle<()>>,
}
impl VerifyPoolInner {
pub(crate) fn spawn(workers: usize) -> Self {
let n = workers.max(1);
let mut txs = Vec::with_capacity(n);
let mut rxs = Vec::with_capacity(n);
let mut handles = Vec::with_capacity(n);
for _ in 0..n {
let (job_tx, job_rx) = mpsc::channel::<VerifyJob>();
let (res_tx, res_rx) = mpsc::channel::<VerifyResult>();
txs.push(job_tx);
rxs.push(res_rx);
handles.push(std::thread::spawn(move || {
while let Ok(job) = job_rx.recv() {
let ok = super::verify_piece(job.kind, job.len, &job.data, &job.expect);
if res_tx
.send(VerifyResult {
torrent: job.torrent,
piece: job.piece,
ok,
data: job.data,
})
.is_err()
{
break;
}
}
}));
}
VerifyPoolInner {
txs,
rxs,
workers: handles,
}
}
pub(crate) fn submit(&self, job: VerifyJob) {
let idx = (job.piece as usize) % self.txs.len();
let _ = self.txs[idx].send(job);
}
pub(crate) fn poll(&self) -> Option<VerifyResult> {
for rx in &self.rxs {
if let Ok(res) = rx.try_recv() {
return Some(res);
}
}
None
}
}
impl Drop for VerifyPoolInner {
fn drop(&mut self) {
// closing the senders lets the workers drain their queue and exit
self.txs.clear();
for w in self.workers.drain(..) {
let _ = w.join();
}
}
}
}
/// Worker pool. Under `std` this spawns real threads; under `no_std` it is
/// a no-op handle and verification stays inline.
pub struct VerifyPool {
#[cfg(feature = "std")]
inner: pool::VerifyPoolInner,
}
impl VerifyPool {
/// Spawn `workers` verification threads (no-op handle under `no_std`).
pub fn spawn(workers: usize) -> Self {
#[cfg(feature = "std")]
{
VerifyPool {
inner: pool::VerifyPoolInner::spawn(workers),
}
}
#[cfg(not(feature = "std"))]
{
let _ = workers;
VerifyPool {}
}
}
/// Queue a verification task.
pub fn submit(&self, job: VerifyJob) {
#[cfg(feature = "std")]
self.inner.submit(job);
#[cfg(not(feature = "std"))]
{
let _ = job;
}
}
/// Non-blocking poll for a completed result.
pub fn poll(&self) -> Option<VerifyResult> {
#[cfg(feature = "std")]
{
self.inner.poll()
}
#[cfg(not(feature = "std"))]
{
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sha1_verify_matches_and_rejects() {
let data = b"the quick brown fox".to_vec();
let mut expect = crate::crypto::Sha1::digest(&data).to_vec();
assert!(verify_piece(
HashKind::Sha1,
data.len() as u32,
&data,
&expect
));
expect[0] ^= 0xff;
assert!(!verify_piece(
HashKind::Sha1,
data.len() as u32,
&data,
&expect
));
}
#[test]
fn v2_merkle_verify_matches_reference() {
let data: Vec<u8> = (0..(48 * 1024) as u32).map(|i| (i % 251) as u8).collect();
let blocks: Vec<[u8; 32]> = data
.chunks(crate::consts::BLOCK_LEN as usize)
.map(crate::crypto::Sha256::digest)
.collect();
let root = crate::metainfo::merkle_root(&blocks);
assert!(verify_piece(
HashKind::Sha256Merkle,
data.len() as u32,
&data,
&root
));
assert!(!verify_piece(
HashKind::Sha256Merkle,
(data.len() - 1) as u32,
&data,
&root
));
let mut bad = root;
bad[0] ^= 1;
assert!(!verify_piece(
HashKind::Sha256Merkle,
data.len() as u32,
&data,
&bad
));
}
#[test]
fn hash_kind_maps_torrent_kind() {
assert_eq!(HashKind::from(TorrentKind::V1), HashKind::Sha1);
assert_eq!(HashKind::from(TorrentKind::V2), HashKind::Sha256Merkle);
assert_eq!(HashKind::from(TorrentKind::Hybrid), HashKind::Sha256Merkle);
}
#[cfg(feature = "std")]
#[test]
fn pool_verifies_across_workers() {
let pool = VerifyPool::spawn(2);
let torrent = InfoHash::v1([1u8; 20]);
let data: Vec<u8> = (0..(16 * 1024) as u32).map(|i| (i % 251) as u8).collect();
let expect = crate::crypto::Sha1::digest(&data).to_vec();
for p in 0..4u32 {
pool.submit(VerifyJob {
torrent,
piece: p,
len: data.len() as u32,
kind: HashKind::Sha1,
expect: expect.clone(),
data: data.clone(),
});
}
let mut got = 0;
let mut attempts = 0u32;
while got < 4 && attempts < 100_000 {
if let Some(res) = pool.poll() {
assert!(res.ok, "piece {} should verify", res.piece);
assert_eq!(res.torrent, torrent);
assert_eq!(res.data, data);
got += 1;
} else {
std::thread::yield_now();
attempts += 1;
}
}
assert_eq!(got, 4, "all four jobs must complete");
}
}