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
use crate::hash::Algorithm;
use crate::hash::SHA256_HASH_SIZE;
use crate::Hash;
use crate::{Error, Kind};
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use tendermint_proto::types::{
CanonicalPartSetHeader as RawCanonicalPartSetHeader, PartSetHeader as RawPartSetHeader,
};
use tendermint_proto::Protobuf;
#[derive(
Clone, Copy, Debug, Default, Hash, Eq, PartialEq, PartialOrd, Ord, Deserialize, Serialize,
)]
#[serde(try_from = "RawPartSetHeader", into = "RawPartSetHeader")]
#[non_exhaustive]
pub struct Header {
pub total: u32,
pub hash: Hash,
}
impl Protobuf<RawPartSetHeader> for Header {}
impl TryFrom<RawPartSetHeader> for Header {
type Error = Error;
fn try_from(value: RawPartSetHeader) -> Result<Self, Self::Error> {
if !value.hash.is_empty() && value.hash.len() != SHA256_HASH_SIZE {
return Err(Kind::InvalidHashSize.into());
}
Ok(Self {
total: value.total,
hash: Hash::from_bytes(Algorithm::Sha256, &value.hash)?,
})
}
}
impl From<Header> for RawPartSetHeader {
fn from(value: Header) -> Self {
RawPartSetHeader {
total: value.total,
hash: value.hash.into(),
}
}
}
impl TryFrom<RawCanonicalPartSetHeader> for Header {
type Error = Error;
fn try_from(value: RawCanonicalPartSetHeader) -> Result<Self, Self::Error> {
if !value.hash.is_empty() && value.hash.len() != SHA256_HASH_SIZE {
return Err(Kind::InvalidHashSize.into());
}
Ok(Self {
total: value.total,
hash: Hash::from_bytes(Algorithm::Sha256, &value.hash)?,
})
}
}
impl From<Header> for RawCanonicalPartSetHeader {
fn from(value: Header) -> Self {
RawCanonicalPartSetHeader {
total: value.total,
hash: value.hash.into(),
}
}
}
impl Header {
pub fn new(total: u32, hash: Hash) -> Result<Self, Error> {
if total == 0 && hash != Hash::None {
return Err(Kind::InvalidPartSetHeader
.context("zero total with existing hash")
.into());
}
if total != 0 && hash == Hash::None {
return Err(Kind::InvalidPartSetHeader
.context("non-zero total with empty hash")
.into());
}
Ok(Header { total, hash })
}
}