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
//! Functions for validating or performing the proof of work
//! used by the Bitmessage protocol.

use std::{
    fmt,
    io::{self, Read, Write},
    mem::size_of,
};

use serde::{Deserialize, Serialize};

use crate::{
    config::Config,
    hash::{double_sha512_2inputs, sha512, Hash512},
    io::{LenBm, ReadFrom, WriteTo},
    time::Time,
    var_type::VarInt,
};

/// The nonce of a proof of work.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Nonce(u64);

impl fmt::Display for Nonce {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:016x}", self.0)
    }
}

impl From<u64> for Nonce {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl Nonce {
    /// Constructs a nonce from a value.
    pub fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the value as `u64`.
    pub fn as_u64(self) -> u64 {
        self.0
    }
}

impl WriteTo for Nonce {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.0.write_to(w)
    }
}

impl ReadFrom for Nonce {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self(u64::read_from(r)?))
    }
}

impl LenBm for Nonce {
    fn len_bm(&self) -> usize {
        self.0.len_bm()
    }
}

/// One of parameters of the proof of work used by the Bitmessage protocol.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize)]
pub struct NonceTrialsPerByte(u64);

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

impl From<u64> for NonceTrialsPerByte {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl NonceTrialsPerByte {
    /// Constructs a nonce trials per byte from a value.
    pub fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the value as `u64`.
    pub fn as_u64(self) -> u64 {
        self.0
    }
}

impl WriteTo for NonceTrialsPerByte {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        let v: VarInt = self.0.into();
        v.write_to(w)
    }
}

impl ReadFrom for NonceTrialsPerByte {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        let v = VarInt::read_from(r)?;
        Ok(Self(v.as_u64()))
    }
}

/// One of parameters of the proof of work used by the Bitmessage protocol.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize)]
pub struct PayloadLengthExtraBytes(u64);

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

impl From<u64> for PayloadLengthExtraBytes {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl PayloadLengthExtraBytes {
    /// Constructs a payload length extra bytes from a value.
    pub fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the value as `u64`.
    pub fn as_u64(self) -> u64 {
        self.0
    }
}

impl WriteTo for PayloadLengthExtraBytes {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        let v: VarInt = self.0.into();
        v.write_to(w)
    }
}

impl ReadFrom for PayloadLengthExtraBytes {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        let v = VarInt::read_from(r)?;
        Ok(Self(v.as_u64()))
    }
}

const MIN_TTL: u64 = 300;

fn effective_ttl(expires_time: Time, now: Time) -> u64 {
    if expires_time < now {
        MIN_TTL
    } else {
        let ttl = expires_time.as_secs() - now.as_secs();
        u64::max(ttl, MIN_TTL)
    }
}

fn effective_nonce_trials_per_byte(
    config: &Config,
    nonce_trials_per_byte: NonceTrialsPerByte,
) -> NonceTrialsPerByte {
    NonceTrialsPerByte::max(nonce_trials_per_byte, config.nonce_trials_per_byte())
}

fn effective_payload_length_extra_bytes(
    config: &Config,
    payload_length_extra_bytes: PayloadLengthExtraBytes,
) -> PayloadLengthExtraBytes {
    PayloadLengthExtraBytes::max(
        payload_length_extra_bytes,
        config.payload_length_extra_bytes(),
    )
}

fn target_by_ttl(
    payload_length: u64,
    ttl: u64,
    nonce_trials_per_byte: NonceTrialsPerByte,
    payload_length_extra_bytes: PayloadLengthExtraBytes,
) -> u64 {
    let length = payload_length + size_of::<u64>() as u64 + payload_length_extra_bytes.as_u64();
    let denominator = nonce_trials_per_byte.as_u64() * (length + (ttl * length / 0x10000));
    const NUMERATOR: u128 = 0x1_0000_0000_0000_0000;
    (NUMERATOR / denominator as u128) as u64
}

fn initial_hash(payload: impl AsRef<[u8]>) -> Hash512 {
    sha512(payload)
}

fn is_valid(initial_hash: Hash512, target: u64, nonce: Nonce) -> Result<(), ValidateError> {
    let result_hash = double_sha512_2inputs(&nonce.as_u64().to_be_bytes(), initial_hash);
    let mut trial_bytes = [0; 8];
    trial_bytes.copy_from_slice(&result_hash[0..8]);
    let trial_value = u64::from_be_bytes(trial_bytes);
    if trial_value <= target {
        Ok(())
    } else {
        Err(ValidateError::Insufficient {
            target,
            value: trial_value,
        })
    }
}

/// An error which can be returne when validating a proof of work.
///
/// This error is used as the error type for the [`validate()`] method.
///
/// [`validate()`]: fn.validate.html
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ValidateError {
    /// The proof of work was insufficient.
    /// The target value and the actual value are returned
    /// as payloads of this variant.
    Insufficient { target: u64, value: u64 },
}

impl fmt::Display for ValidateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Insufficient { target, value } => write!(
                f,
                "value {:016x} is insufficient for target {:016x}",
                value, target
            ),
        }
    }
}

impl std::error::Error for ValidateError {}

/// Validates a proof of work used by the Bitmessage protocol.
pub fn validate(
    config: &Config,
    payload: impl AsRef<[u8]>,
    expires_time: Time,
    nonce_trials_per_byte: NonceTrialsPerByte,
    payload_length_extra_bytes: PayloadLengthExtraBytes,
    nonce: Nonce,
    now: Time,
) -> Result<(), ValidateError> {
    let payload = payload.as_ref();
    let target = target_by_ttl(
        payload.len() as u64,
        effective_ttl(expires_time, now),
        effective_nonce_trials_per_byte(config, nonce_trials_per_byte),
        effective_payload_length_extra_bytes(config, payload_length_extra_bytes),
    );
    is_valid(initial_hash(payload), target, nonce)
}