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
#[macro_use]
extern crate log;

use chrono::{DateTime, Utc};
use crypto::digest::Digest;
use crypto::sha1::Sha1;
use crypto::sha3::Sha3;
use rand::distributions::{Alphanumeric, Distribution};
use rand::thread_rng;
use std::convert::TryFrom;
use std::fmt;

simpl::err!(HcError,
    {Int@std::num::ParseIntError;}
);

fn _hash<T: Digest>(hasher: &mut T, challenge: &str, bits: u32) -> String {
    let mut counter = 0;
    let hex_digits = ((bits as f32) / 4.).ceil() as usize;
    let zeros = String::from_utf8(vec![b'0'; hex_digits]).unwrap();
    loop {
        hasher.input_str(&format!("{}:{:x}", challenge, counter));
        if hasher.result_str()[..hex_digits] == zeros {
            debug!("{}", hasher.result_str());
            return format!("{:x}", counter);
        };
        hasher.reset();
        counter += 1
    }
}

/// Answer a generalized hashcash version 1 challenge
/// Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter'
/// This internal function accepts a generalized prefix 'challenge',
/// and returns only a suffix that produces the requested SHA leading zeros.
///
/// NOTE: Number of requested bits is rounded up to the nearest multiple of 4
fn _mint(challenge: &str, bits: u32) -> String {
    if cfg!(feature = "sha1") {
        let mut hasher = Sha1::new();
        _hash(&mut hasher, challenge, bits)
    } else {
        let mut hasher = Sha3::sha3_256();
        _hash(&mut hasher, challenge, bits)
    }
}

/// Check whether a stamp is valid
///
/// Optionally, the stamp may be checked for a specific resource, and/or
/// it may require a minimum bit value, and/or it may be checked for
/// expiration, and/or it may be checked for double spending.
///
/// If 'check_expiration' is specified, it should contain an expiration DateTime<Utc>
///
/// NOTE: Every valid (version 1) stamp must meet its claimed bit value
/// NOTE: Check floor of 4-bit multiples (overly permissive in acceptance)
///     """
pub fn check_with_params(
    stamp: &str,
    resource: Option<&str>,
    bits: Option<u32>,
    expiration: Option<DateTime<Utc>>,
) -> Result<bool, HcError> {
    let stamp = Stamp::try_from(stamp)?;
    if !stamp.check_version() {
        return Err(HcError::from(
            format!(
                "Can only check version 1 stamp, got version {}",
                stamp.version
            )
            .as_str(),
        ));
    }
    if !stamp.check_resource(resource) {
        return Ok(false);
    }
    if !stamp.check_bits(bits) {
        return Ok(false);
    }
    if !stamp.check_expiration(expiration) {
        return Ok(false);
    }
    Ok(stamp.check())
}

/// Check whether a stamp is valid
pub fn check(stamp: &str) -> Result<bool> {
    check_with_params(stamp, None, None, None)
}

#[derive(Debug)]
pub struct Stamp {
    version: String,
    claim: u32,
    ts: String,
    resource: String,
    ext: String,
    rand: String,
    counter: String,
}

impl Stamp {
    fn check_version(&self) -> bool {
        self.version == "1"
    }

    fn check_resource(&self, resource: Option<&str>) -> bool {
        if let Some(resource) = resource {
            self.resource == resource
        } else {
            true
        }
    }

    fn check_bits(&self, bits: Option<u32>) -> bool {
        if let Some(bits) = bits {
            bits <= self.claim
        } else {
            true
        }
    }

    fn check_expiration(&self, expiration: Option<DateTime<Utc>>) -> bool {
        if let Some(expiration) = expiration {
            Utc::now() < expiration
        } else {
            true
        }
    }

    fn hex_digits(&self) -> usize {
        ((self.claim as f32) / 4.).floor() as usize
    }

    fn zeroes(&self) -> String {
        String::from_utf8(vec![b'0'; self.hex_digits()]).unwrap()
    }

    fn _check<T: Digest>(&self, hasher: &mut T) -> bool {
        debug!("{}", self.to_string());
        hasher.input_str(&self.to_string());

        debug!("{}", hasher.result_str());
        hasher.result_str()[..self.hex_digits()] == self.zeroes()
    }

    fn check(&self) -> bool {
        if cfg!(feature = "sha1") {
            let mut hasher = Sha1::new();
            self._check(&mut hasher)
        } else {
            let mut hasher = Sha3::sha3_256();
            self._check(&mut hasher)
        }
    }

    fn format(&self) -> String {
        format!(
            "{}:{}:{}:{}:{}:{}:{}",
            self.version, self.claim, self.ts, self.resource, self.ext, self.rand, self.counter
        )
    }

    /// Mint a new hashcash stamp for 'resource' with 'bits' of collision
    /// 20 bits of collision is the default.
    ///
    /// 'ext' lets you add your own extensions to a minted stamp.  Specify an
    /// extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val'
    ///
    /// 'saltchars' specifies the length of the salt used; this version defaults
    /// 8 chars, rather than the C version's 16 chars.  This still provides about
    /// 17 million salts per resource, per timestamp, before birthday paradox
    /// collisions occur.  Really paranoid users can use a larger salt though.
    ///
    /// 'stamp_seconds' lets you add the option time elements to the datestamp.
    /// If you want more than just day, you get all the way down to seconds,
    /// even though the spec also allows hours/minutes without seconds.
    pub fn mint(
        resource: Option<&str>,
        bits: Option<u32>,
        now: Option<DateTime<Utc>>,
        ext: Option<&str>,
        saltchars: Option<usize>,
        stamp_seconds: bool,
    ) -> Result<Self> {
        let version = "1";
        let now = now.unwrap_or_else(Utc::now);
        let ts = if stamp_seconds {
            now.format("%Y%M%d%H%M%S")
        } else {
            now.format("%Y%M%d")
        };
        let bits = bits.unwrap_or(20);
        let ext = ext.unwrap_or("");
        let saltchars = saltchars.unwrap_or(8);
        let rand = Alphanumeric
            .sample_iter(thread_rng())
            .take(saltchars)
            .collect();
        let resource = resource.unwrap_or("");
        let challenge = format!("{}:{}:{}:{}:{}:{}", version, bits, ts, resource, ext, rand);

        Ok(Stamp {
            version: version.to_string(),
            claim: bits,
            ts: ts.to_string(),
            resource: resource.to_string(),
            ext: ext.to_string(),
            rand,
            counter: _mint(&challenge, bits),
        })
    }

    pub fn with_secs() -> Result<Self> {
        Self::mint(None, None, None, None, None, true)
    }

    pub fn with_resource(resource: &str, stamp_seconds: bool) -> Result<Self> {
        Self::mint(Some(resource), None, None, None, None, stamp_seconds)
    }

    pub fn with_bits(bits: u32, stamp_seconds: bool) -> Result<Self> {
        Self::mint(None, Some(bits), None, None, None, stamp_seconds)
    }

    pub fn with_resource_and_bits(resource: &str, bits: u32, stamp_seconds: bool) -> Result<Self> {
        Self::mint(Some(resource), Some(bits), None, None, None, stamp_seconds)
    }
}

impl TryFrom<&str> for Stamp {
    type Error = HcError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let stamp_vec = value.split(':').collect::<Vec<&str>>();
        if stamp_vec.len() != 7 {
            return Err(HcError::from(
                format!("Malformed stamp, expected 6 parts, got {}", stamp_vec.len()).as_str(),
            ));
        }
        Ok(Stamp {
            version: stamp_vec[0].to_string(),
            claim: stamp_vec[1].parse()?,
            ts: stamp_vec[2].to_string(),
            resource: stamp_vec[3].to_string(),
            ext: stamp_vec[4].to_string(),
            rand: stamp_vec[5].to_string(),
            counter: stamp_vec[6].to_string(),
        })
    }
}

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

impl Default for Stamp {
    fn default() -> Self {
        Self::mint(None, None, None, None, None, false).unwrap()
    }
}

mod test {
    use crate::Stamp;
    use crate::check;
    #[test]
    fn test_default() {
        let stamp = Stamp::default();
        let result = check(&stamp.to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_with_secs() {
        let stamp = Stamp::with_secs();
        assert!(stamp.is_ok());
        let result = check(&stamp.unwrap().to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_with_resource() {
        let stamp = Stamp::with_resource("test", false);
        assert!(stamp.is_ok());
        let result = check(&stamp.unwrap().to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_with_resource_and_seconds() {
        let stamp = Stamp::with_resource("test", true);
        assert!(stamp.is_ok());
        let result = check(&stamp.unwrap().to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_with_bits() {
        let stamp = Stamp::with_bits(16, false);
        assert!(stamp.is_ok());
        let result = check(&stamp.unwrap().to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_with_bits_and_seconds() {
        let stamp = Stamp::with_bits(16, true);
        assert!(stamp.is_ok());
        let result = check(&stamp.unwrap().to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_with_resource_and_bits() {
        let stamp = Stamp::with_resource_and_bits("test", 16, false);
        assert!(stamp.is_ok());
        let result = check(&stamp.unwrap().to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_with_resource_and_bits_and_seconds() {
        let stamp = Stamp::with_resource_and_bits("test", 16, true);
        assert!(stamp.is_ok());
        let result = check(&stamp.unwrap().to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_mint() {
        let stamp = Stamp::mint(Some("test"), Some(15), None, Some("name1=2"), Some(12), false);
        assert!(stamp.is_ok());
        let result = check(&stamp.unwrap().to_string());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_check() {
        assert!(check("1:20:20202116:test::Z4p8WaiO:31c14").unwrap());
        assert!(!check("1:20:20202116:test1::Z4p8WaiO:31c14").unwrap());
        assert!(!check("1:20:20202116:test::z4p8WaiO:31c14").unwrap());
        assert!(!check("1:20:20202116:test::Z4p8WaiO:31C14").unwrap());
        assert!(check("0:20:20202116:test::Z4p8WaiO:31c14").is_err());
        assert!(!check("1:19:20202116:test::Z4p8WaiO:31c14").unwrap());
        assert!(!check("1:20:20202115:test::Z4p8WaiO:31c14").unwrap());
    }

}