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
// Conserve backup system.
// Copyright 2015, 2016, 2017, 2018, 2019, 2020 Martin Pool.

// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

//! Block hash address type.

use std::cmp::Ordering;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::{Debug, Display};
use std::hash::{Hash, Hasher};
use std::str::FromStr;

use blake2_rfc::blake2b::Blake2bResult;
use serde::{Deserialize, Serialize};

use crate::*;

/// The hash of a block of body data.
///
/// Stored in memory as compact bytes, but translatable to and from
/// hex strings.o
///
/// ```
/// use std::str::FromStr;
/// use conserve::blockhash::BlockHash;
///
/// let hex_hash = concat!(
///     "00000000000000000000000000000000",
///     "00000000000000000000000000000000",
///     "00000000000000000000000000000000",
///     "00000000000000000000000000000000",);
/// let hash = BlockHash::from_str(hex_hash)
///     .unwrap();
/// let hash2 = hash.clone();
/// assert_eq!(hash2.to_string(), hex_hash);
/// ```
#[derive(Clone, Deserialize, Serialize)]
#[serde(into = "String")]
#[serde(try_from = "&str")]
pub struct BlockHash {
    /// Binary hash.
    bin: [u8; BLAKE_HASH_SIZE_BYTES],
}

#[derive(Debug)]
pub struct BlockHashParseError {
    rejected_string: String,
}

impl Display for BlockHashParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Failed to parse hash string: {:?}", self.rejected_string)
    }
}

impl FromStr for BlockHash {
    type Err = BlockHashParseError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        if s.len() != BLAKE_HASH_SIZE_BYTES * 2 {
            return Err(BlockHashParseError {
                rejected_string: s.to_owned(),
            });
        }
        let mut bin = [0; BLAKE_HASH_SIZE_BYTES];
        hex::decode_to_slice(s, &mut bin)
            .map_err(|_| BlockHashParseError {
                rejected_string: s.to_owned(),
            })
            .and(Ok(BlockHash { bin }))
    }
}

impl TryFrom<&str> for BlockHash {
    type Error = BlockHashParseError;

    fn try_from(s: &str) -> std::result::Result<Self, Self::Error> {
        BlockHash::from_str(s)
    }
}

impl Debug for BlockHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(self, f)
    }
}

impl Display for BlockHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", hex::encode(&self.bin[..]))
    }
}

impl From<BlockHash> for String {
    fn from(hash: BlockHash) -> String {
        hex::encode(&hash.bin[..])
    }
}

impl From<Blake2bResult> for BlockHash {
    fn from(hash: Blake2bResult) -> BlockHash {
        let mut bin = [0; BLAKE_HASH_SIZE_BYTES];
        bin.copy_from_slice(hash.as_bytes());
        BlockHash { bin }
    }
}

impl Ord for BlockHash {
    fn cmp(&self, other: &Self) -> Ordering {
        self.bin.cmp(&other.bin)
    }
}

impl PartialOrd for BlockHash {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.bin.cmp(&other.bin))
    }
}

impl PartialEq for BlockHash {
    fn eq(&self, other: &Self) -> bool {
        self.bin[..] == other.bin[..]
    }
}

impl Eq for BlockHash {}

impl Hash for BlockHash {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.bin.hash(state);
    }
}