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
#[cfg(feature = "proofs")]
mod zero;
#[cfg(feature = "proofs")]
pub use zero::zero_piece_commitment;
use cid::Cid;
use encoding::tuple::*;
use serde::{Deserialize, Serialize};
#[derive(PartialEq, Debug, Eq, Clone, Copy)]
pub struct UnpaddedPieceSize(pub u64);
impl UnpaddedPieceSize {
pub fn padded(self) -> PaddedPieceSize {
PaddedPieceSize(self.0 + (self.0 / 127))
}
pub fn validate(self) -> Result<(), &'static str> {
if self.0 < 127 {
return Err("minimum piece size is 127 bytes");
}
if self.0 >> self.0.trailing_zeros() != 127 {
return Err("unpadded piece size must be a power of 2 multiple of 127");
}
Ok(())
}
}
#[derive(PartialEq, Debug, Eq, Clone, Copy, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PaddedPieceSize(pub u64);
impl PaddedPieceSize {
pub fn unpadded(self) -> UnpaddedPieceSize {
UnpaddedPieceSize(self.0 - (self.0 / 128))
}
pub fn validate(self) -> Result<(), &'static str> {
if self.0 < 128 {
return Err("minimum piece size is 128 bytes");
}
if self.0.count_ones() != 1 {
return Err("padded piece size must be a power of 2");
}
Ok(())
}
}
#[derive(Serialize_tuple, Deserialize_tuple, PartialEq, Clone)]
pub struct PieceInfo {
pub size: PaddedPieceSize,
pub cid: Cid,
}
#[cfg(feature = "proofs")]
use std::convert::TryFrom;
#[cfg(feature = "proofs")]
impl TryFrom<&PieceInfo> for filecoin_proofs_api::PieceInfo {
type Error = &'static str;
fn try_from(p: &PieceInfo) -> Result<Self, Self::Error> {
Ok(Self {
commitment: commcid::cid_to_piece_commitment_v1(&p.cid)?,
size: p.size.unpadded().into(),
})
}
}
#[cfg(feature = "proofs")]
impl From<UnpaddedPieceSize> for filecoin_proofs_api::UnpaddedBytesAmount {
fn from(p: UnpaddedPieceSize) -> Self {
Self(p.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip_piece_size() {
let p_piece = PaddedPieceSize(0b10000000);
p_piece.validate().unwrap();
let up_piece = p_piece.unpadded();
up_piece.validate().unwrap();
assert_eq!(&up_piece, &UnpaddedPieceSize(127));
assert_eq!(&p_piece, &up_piece.padded());
}
#[test]
fn invalid_piece_checks() {
let p = PaddedPieceSize(127);
assert_eq!(p.validate(), Err("minimum piece size is 128 bytes"));
let p = UnpaddedPieceSize(126);
assert_eq!(p.validate(), Err("minimum piece size is 127 bytes"));
let p = PaddedPieceSize(0b10000001);
assert_eq!(p.validate(), Err("padded piece size must be a power of 2"));
assert_eq!(UnpaddedPieceSize(0b1111111000).validate(), Ok(()));
assert_eq!(
UnpaddedPieceSize(0b1110111000).validate(),
Err("unpadded piece size must be a power of 2 multiple of 127")
);
}
}