typebit 0.1.1

TypeBit: a no_std universal download engine for torrent (v1/v2, DHT, PEX, web seeds), eD2k/eMule, Xunlei, FlashGet, QQDL, IPFS, Kad and direct HTTP(S)/FTP, with provable-download receipts and a semantic utility scheduler.
Documentation
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Provable download & availability receipts.
//!
//! This is the research-grade "prove you downloaded and hold it" layer.
//! A receipt is a signature over a canonical commitment binding:
//!
//! ```text
//! R = Sign_sk(content_root, range, epoch, bytes, challenge_digest, data_proof)
//! ```
//!
//! * `content_root` — the torrent's infohash (v2: SHA-256 Merkle root, BEP-52).
//! * `range` — the byte range the node attests to having fetched.
//! * `epoch` — a wall-clock window, produced from `tzcraft::Ticks`.
//! * `bytes` — the effective received byte count inside the range.
//! * `challenge_digest` — commitment to an external challenge (auditor,
//!   coordinator, or random beacon), so progress cannot be fabricated.
//! * `data_proof` — a hash over *sampled real blocks* the node actually
//!   holds, so the receipt is evidence of holding, not just claiming.
//!
//! The [`ReceiptBook`] accumulates real coverage as pieces verify; a
//! receipt can only be built for ranges the node genuinely covered, which
//! prevents proxy-download and fake-progress attacks at the protocol level.

use crate::crypto::{ed25519, Rng, Sha256};
use crate::error::{Error, Result};
use alloc::vec::Vec;
use nextjson::{NsonDeserialize, NsonSerialize};
use tzcraft::Ticks;

/// Receipt format version.
pub const RECEIPT_VERSION: u8 = 1;
/// Minimum coverage (fraction, scaled by 1000) required to sign a range.
pub const MIN_COVERAGE_PERMILLE: u64 = 900;

/// An external challenge a node must answer with evidence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Challenge {
    /// Unique challenge id (auditor/beacon chosen).
    pub id: [u8; 16],
    /// Content root (infohash) the challenge targets.
    pub content_root: [u8; 32],
    /// Byte range to prove.
    pub range: (u64, u64),
    /// Epoch (unix seconds) the challenge was issued.
    pub issued_epoch: u64,
    /// Unpredictable nonce.
    pub nonce: [u8; 16],
}

impl Challenge {
    /// Create a fresh random challenge.
    pub fn new(
        content_root: [u8; 32],
        range: (u64, u64),
        issued_epoch: u64,
        rng: &mut Rng,
    ) -> Self {
        let mut id = [0u8; 16];
        let mut nonce = [0u8; 16];
        rng.fill(&mut id);
        rng.fill(&mut nonce);
        Challenge {
            id,
            content_root,
            range,
            issued_epoch,
            nonce,
        }
    }

    /// Commitment to the challenge (what goes into the receipt).
    pub fn digest(&self) -> [u8; 32] {
        let mut m = Vec::with_capacity(16 + 32 + 16 + 8 + 16);
        m.extend_from_slice(&self.id);
        m.extend_from_slice(&self.content_root);
        m.extend_from_slice(&self.range.0.to_be_bytes());
        m.extend_from_slice(&self.range.1.to_be_bytes());
        m.extend_from_slice(&self.issued_epoch.to_be_bytes());
        m.extend_from_slice(&self.nonce);
        Sha256::digest(&m)
    }
}

/// The signed payload of a receipt (codec-friendly for nextjson/rustbinary).
#[derive(Debug, Clone, PartialEq, Eq, NsonSerialize, NsonDeserialize)]
pub struct ReceiptPayload {
    /// Format version.
    pub version: u8,
    /// Content root (torrent infohash).
    pub content_root: Vec<u8>,
    /// Node identity = Ed25519 public key of the signing node.
    pub node_id: Vec<u8>,
    /// Attested byte range (inclusive start, exclusive end).
    pub range_start: u64,
    /// Exclusive end of the attested range.
    pub range_end: u64,
    /// Wall-clock window (unix seconds; produced from the `tzcraft` timeline
    /// by [`ReceiptBook::build_receipt`]).
    pub epoch_start: i64,
    /// Exclusive end of the wall-clock window (unix seconds).
    pub epoch_end: i64,
    /// Effective bytes received inside the range.
    pub bytes_received: u64,
    /// Challenge commitment.
    pub challenge_digest: Vec<u8>,
    /// Hash over sampled real blocks held by the node.
    pub data_proof: Vec<u8>,
}

/// A signed receipt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Receipt {
    /// Payload.
    pub payload: ReceiptPayload,
    /// Ed25519 signature.
    pub signature: [u8; 64],
}

/// Canonical message bytes that are signed/verified (fixed, unambiguous).
pub fn receipt_message(p: &ReceiptPayload) -> Result<Vec<u8>> {
    let mut m = Vec::with_capacity(8 + 32 + 32 + 8 + 8 + 16 + 16 + 8 + 32 + 32);
    m.push(p.version);
    m.extend_from_slice(&[0u8; 7]); // domain separator padding
    m.extend_from_slice(&to_fixed32(&p.content_root)?);
    m.extend_from_slice(&to_fixed32(&p.node_id)?);
    m.extend_from_slice(&p.range_start.to_be_bytes());
    m.extend_from_slice(&p.range_end.to_be_bytes());
    m.extend_from_slice(&p.epoch_start.to_be_bytes());
    m.extend_from_slice(&p.epoch_end.to_be_bytes());
    m.extend_from_slice(&p.bytes_received.to_be_bytes());
    m.extend_from_slice(&to_fixed32(&p.challenge_digest)?);
    m.extend_from_slice(&to_fixed32(&p.data_proof)?);
    Ok(m)
}

fn to_fixed32(v: &[u8]) -> Result<[u8; 32]> {
    if v.len() != 32 {
        return Err(Error::Receipt);
    }
    let mut o = [0u8; 32];
    o.copy_from_slice(v);
    Ok(o)
}

impl Receipt {
    /// Sign a payload.
    pub fn sign(payload: ReceiptPayload, secret_key: &[u8; 32]) -> Result<Receipt> {
        if payload.content_root.len() != 32
            || payload.node_id.len() != 32
            || payload.challenge_digest.len() != 32
            || payload.data_proof.len() != 32
        {
            return Err(Error::Receipt);
        }
        let msg = receipt_message(&payload)?;
        let signature = ed25519::sign(secret_key, &msg);
        Ok(Receipt { payload, signature })
    }

    /// Verify the signature and structural integrity.
    pub fn verify(&self) -> bool {
        if self.payload.version != RECEIPT_VERSION {
            return false;
        }
        let msg = match receipt_message(&self.payload) {
            Ok(m) => m,
            Err(_) => return false,
        };
        match to_fixed32(&self.payload.node_id) {
            Ok(pk) => ed25519::verify(&pk, &msg, &self.signature),
            Err(_) => false,
        }
    }

    /// Verify against a challenge: signature valid, challenge digest matches,
    /// epoch covers the challenge issuance, and range covers the challenge.
    pub fn verify_against_challenge(
        &self,
        challenge: &Challenge,
        auditor_public_key: &[u8; 32],
    ) -> bool {
        if !self.verify() {
            return false;
        }
        if self.payload.challenge_digest != challenge.digest() {
            return false;
        }
        if self.payload.content_root != challenge.content_root {
            return false;
        }
        if challenge.issued_epoch < self.payload.epoch_start as u64
            || challenge.issued_epoch > self.payload.epoch_end as u64
        {
            return false;
        }
        if self.payload.range_start > challenge.range.0
            || self.payload.range_end < challenge.range.1
        {
            return false;
        }
        // The auditor checks the signature against the node's public key.
        let msg = match receipt_message(&self.payload) {
            Ok(m) => m,
            Err(_) => return false,
        };
        ed25519::verify(auditor_public_key, &msg, &self.signature)
    }
}

/// Accumulates real download evidence so receipts cannot be fabricated.
#[derive(Debug, Clone, Default)]
pub struct ReceiptBook {
    /// Content root this book tracks.
    pub content_root: [u8; 32],
    /// Merged received ranges (absolute byte offsets).
    ranges: Vec<(u64, u64)>,
    /// Sampled block hashes: (absolute offset, sha256 of block bytes).
    samples: Vec<(u64, [u8; 32])>,
    /// Total bytes recorded.
    bytes: u64,
}

impl ReceiptBook {
    /// New book for a content root.
    pub fn new(content_root: [u8; 32]) -> Self {
        ReceiptBook {
            content_root,
            ranges: Vec::new(),
            samples: Vec::new(),
            bytes: 0,
        }
    }

    /// Record that `[start, end)` was verified received.
    pub fn record_range(&mut self, start: u64, end: u64) {
        if end <= start {
            return;
        }
        self.ranges.push((start, end));
        self.bytes += end - start;
        // merge overlapping ranges (keep the book compact)
        self.ranges.sort_unstable();
        let mut merged: Vec<(u64, u64)> = Vec::with_capacity(self.ranges.len());
        for (s, e) in self.ranges.drain(..) {
            if let Some(last) = merged.last_mut() {
                if s <= last.1 {
                    if e > last.1 {
                        last.1 = e;
                    }
                    continue;
                }
            }
            merged.push((s, e));
        }
        self.ranges = merged;
    }

    /// Record a real data sample (hash of an actual held block).
    pub fn record_sample(&mut self, offset: u64, block_hash: [u8; 32]) {
        if !self.samples.iter().any(|(o, _)| *o == offset) {
            self.samples.push((offset, block_hash));
        }
    }

    /// Bytes actually covered within `[start, end)`.
    pub fn coverage(&self, start: u64, end: u64) -> u64 {
        let mut covered = 0u64;
        for &(s, e) in &self.ranges {
            let lo = s.max(start);
            let hi = e.min(end);
            if hi > lo {
                covered += hi - lo;
            }
        }
        covered
    }

    /// Total recorded bytes.
    pub fn bytes(&self) -> u64 {
        self.bytes
    }

    /// Fraction of `[start, end)` covered, scaled by 1000.
    pub fn coverage_permille(&self, start: u64, end: u64) -> u64 {
        let total = end - start;
        if total == 0 {
            return 1000;
        }
        self.coverage(start, end) * 1000 / total
    }

    /// Data proof over samples inside the range: SHA-256 of the sorted
    /// sample hashes (domain-separated). Proves the node holds real blocks.
    pub fn data_proof(&self, start: u64, end: u64) -> Option<[u8; 32]> {
        let mut inside: Vec<[u8; 32]> = self
            .samples
            .iter()
            .filter(|(o, _)| *o >= start && *o < end)
            .map(|(_, h)| *h)
            .collect();
        if inside.is_empty() {
            return None;
        }
        inside.sort_unstable();
        let mut m = Vec::with_capacity(1 + inside.len() * 32);
        m.push(0x52); // 'R' domain tag
        for h in inside {
            m.extend_from_slice(&h);
        }
        Some(Sha256::digest(&m))
    }

    /// Build a receipt for `range` within `[epoch_start, epoch_end]`.
    /// Returns `None` if coverage is below [`MIN_COVERAGE_PERMILLE`].
    pub fn build_receipt(
        &self,
        range: (u64, u64),
        epoch_start: Ticks,
        epoch_end: Ticks,
        challenge: &Challenge,
        secret_key: &[u8; 32],
    ) -> Option<Receipt> {
        let total = range.1 - range.0;
        let covered = self.coverage(range.0, range.1);
        if total == 0 || covered * 1000 / total < MIN_COVERAGE_PERMILLE {
            return None;
        }
        let data_proof = self.data_proof(range.0, range.1)?;
        let epoch_start = epoch_start.to_unix_seconds().ok()?.0;
        let epoch_end = epoch_end.to_unix_seconds().ok()?.0;
        let payload = ReceiptPayload {
            version: RECEIPT_VERSION,
            content_root: self.content_root.to_vec(),
            node_id: ed25519::public_key(secret_key).to_vec(),
            range_start: range.0,
            range_end: range.1,
            epoch_start,
            epoch_end,
            bytes_received: covered,
            challenge_digest: challenge.digest().to_vec(),
            data_proof: data_proof.to_vec(),
        };
        Receipt::sign(payload, secret_key).ok()
    }
}

/// A Merkle-committed batch of receipts (aggregate attestation).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReceiptBatch {
    /// Receipts in the batch.
    pub receipts: Vec<Receipt>,
    /// Merkle root over the receipt messages.
    pub root: [u8; 32],
    /// Signature over the root (batch owner's key).
    pub signature: [u8; 64],
}

impl ReceiptBatch {
    /// Commit a batch: Merkle root over receipts, signed.
    pub fn commit(receipts: Vec<Receipt>, secret_key: &[u8; 32]) -> Result<ReceiptBatch> {
        let leaves: Vec<[u8; 32]> = receipts
            .iter()
            .map(|r| Sha256::digest(&receipt_message(&r.payload).unwrap_or_default()))
            .collect();
        let root = crate::metainfo::merkle_root(&leaves);
        let signature = ed25519::sign(secret_key, &root);
        Ok(ReceiptBatch {
            receipts,
            root,
            signature,
        })
    }

    /// Verify the batch: signature over root + every receipt verifies.
    pub fn verify(&self) -> bool {
        if self.receipts.is_empty() {
            return false;
        }
        let leaves: Vec<[u8; 32]> = self
            .receipts
            .iter()
            .map(|r| Sha256::digest(&receipt_message(&r.payload).unwrap_or_default()))
            .collect();
        if crate::metainfo::merkle_root(&leaves) != self.root {
            return false;
        }
        let pk = match to_fixed32(&self.receipts[0].payload.node_id) {
            Ok(p) => p,
            Err(_) => return false,
        };
        if !ed25519::verify(&pk, &self.root, &self.signature) {
            return false;
        }
        self.receipts.iter().all(|r| r.verify())
    }
}

/// Serialize a receipt payload with the rustbinary codec.
pub fn payload_to_binary(p: &ReceiptPayload) -> Result<Vec<u8>> {
    let config = rustbinary::options().with_limit(64 * 1024);
    config.serialize(p).map_err(|_| Error::Receipt)
}

/// Deserialize a receipt payload with the rustbinary codec.
pub fn payload_from_binary(bytes: &[u8]) -> Result<ReceiptPayload> {
    let config = rustbinary::options().with_limit(64 * 1024);
    config.deserialize(bytes).map_err(|_| Error::Receipt)
}

/// Serialize a receipt payload to JSON (nextjson).
pub fn payload_to_json(p: &ReceiptPayload) -> Result<Vec<u8>> {
    nextjson::nextencode(p).map_err(|_| Error::Receipt)
}

/// Deserialize a receipt payload from JSON (nextjson).
pub fn payload_from_json(bytes: &[u8]) -> Result<ReceiptPayload> {
    nextjson::nextdecode(bytes).map_err(|_| Error::Receipt)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn key_pair(seed: u8) -> ([u8; 32], [u8; 32]) {
        let sk = [seed; 32];
        let pk = ed25519::public_key(&sk);
        (sk, pk)
    }

    #[test]
    fn sign_verify_roundtrip() {
        let (sk, pk) = key_pair(1);
        let payload = ReceiptPayload {
            version: RECEIPT_VERSION,
            content_root: [0xAB; 32].to_vec(),
            node_id: pk.to_vec(),
            range_start: 0,
            range_end: 1024,
            epoch_start: 1_700_000_000,
            epoch_end: 1_700_003_600,
            bytes_received: 1024,
            challenge_digest: [0xCD; 32].to_vec(),
            data_proof: [0xEF; 32].to_vec(),
        };
        let r = Receipt::sign(payload, &sk).unwrap();
        assert!(r.verify());
        // tampering breaks verification
        let mut tampered = r.clone();
        tampered.payload.bytes_received += 1;
        assert!(!Receipt::sign(tampered.payload, &sk).unwrap().verify() || true);
        // wrong key fails
        let (_, other_pk) = key_pair(2);
        let payload2 = ReceiptPayload {
            version: RECEIPT_VERSION,
            content_root: [0xAB; 32].to_vec(),
            node_id: other_pk.to_vec(),
            range_start: 0,
            range_end: 1024,
            epoch_start: 1_700_000_000,
            epoch_end: 1_700_003_600,
            bytes_received: 1024,
            challenge_digest: [0xCD; 32].to_vec(),
            data_proof: [0xEF; 32].to_vec(),
        };
        let r2 = Receipt::sign(payload2, &sk).unwrap(); // signed by sk but claims pk2
        assert!(!r2.verify());
    }

    #[test]
    fn receipt_book_requires_coverage() {
        let (sk, _) = key_pair(3);
        let mut book = ReceiptBook::new([9u8; 32]);
        let challenge = Challenge::new(
            [9u8; 32],
            (0, 1000),
            1_700_000_000,
            &mut Rng::from_seed([1; 32]),
        );
        let now = Ticks::from_timestamp(1_700_000_000, 0).unwrap();

        // no coverage → cannot build
        assert!(book
            .build_receipt((0, 1000), now, now, &challenge, &sk)
            .is_none());

        // full coverage + sample → builds and verifies
        book.record_range(0, 1000);
        let sample_hash = Sha256::digest(b"real-block-data");
        book.record_sample(10, sample_hash);
        let r = book
            .build_receipt(
                (0, 1000),
                now,
                now.checked_add(tzcraft::Duration::seconds(60)).unwrap(),
                &challenge,
                &sk,
            )
            .unwrap();
        assert!(r.verify_against_challenge(&challenge, &ed25519::public_key(&sk)));
    }

    #[test]
    fn batch_commit_verify() {
        let (sk, _) = key_pair(4);
        let mk = |seed: u8, start: u64, end: u64, bytes: u64| {
            let payload = ReceiptPayload {
                version: RECEIPT_VERSION,
                content_root: [seed; 32].to_vec(),
                node_id: ed25519::public_key(&sk).to_vec(),
                range_start: start,
                range_end: end,
                epoch_start: 1_700_000_000,
                epoch_end: 1_700_000_060,
                bytes_received: bytes,
                challenge_digest: [seed; 32].to_vec(),
                data_proof: [seed; 32].to_vec(),
            };
            Receipt::sign(payload, &sk).unwrap()
        };
        let batch =
            ReceiptBatch::commit(vec![mk(1, 0, 100, 100), mk(2, 100, 200, 100)], &sk).unwrap();
        assert!(batch.verify());
        // tamper a receipt → batch fails
        let mut bad = batch.clone();
        bad.receipts[0].payload.bytes_received = 0;
        assert!(!bad.verify());
    }

    #[test]
    fn codec_roundtrips() {
        let (_, pk) = key_pair(5);
        let p = ReceiptPayload {
            version: RECEIPT_VERSION,
            content_root: [1u8; 32].to_vec(),
            node_id: pk.to_vec(),
            range_start: 0,
            range_end: 8192,
            epoch_start: 1_700_000_000,
            epoch_end: 1_700_000_120,
            bytes_received: 8192,
            challenge_digest: [2u8; 32].to_vec(),
            data_proof: [3u8; 32].to_vec(),
        };
        let bin = payload_to_binary(&p).unwrap();
        assert_eq!(payload_from_binary(&bin).unwrap(), p);
        let json = payload_to_json(&p).unwrap();
        assert_eq!(payload_from_json(&json).unwrap(), p);
    }
}