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
//! Rust implementation of hashcash anti-spam / denial of service 
//! counter-measure tool.

extern crate rand;
extern crate chrono;
extern crate base64;
extern crate crypto;
extern crate byteorder;

use base64::{encode, decode};
use crypto::digest::Digest;
use crypto::sha1::Sha1;
use rand::{thread_rng, Rng};
use rand::distributions::{Standard};
use chrono::prelude::*;
use chrono::Duration;
use byteorder::{BigEndian, WriteBytesExt};

const DATE_FMT: &str = "%y%m%d%H%M%S";

/// Stores a destructured hashcash token by its various components.
#[derive(Debug,PartialEq)]
pub struct Token {
    pub ver: u8,
    pub bits: u32,
    pub date: NaiveDateTime,
    pub resource: String,
    pub ext: String,
    pub rand: Vec<u8>,
    pub counter: Vec<u8>,
}

/// Various error types that are used during the validation of a 
/// `hashcash::Token`.
#[derive(Debug)]
pub enum CheckError {
    /// Returned when validating a `hashcash::Token` and the date is older than 
    /// two days.
    ExpiryError,
    /// Returned when validating a `hashcash::Token` and the resulting hash 
    /// does not satisfy the declared difficulty bits.
    DifficultyError,
}

/// Returned when creating a `hashcash::Token` from a `&str` fails due to
/// an invalid input.
#[derive(Debug)]
pub struct ParseError { 
    pub message: &'static str 
}

impl Token {
    /// Given a fully qualified hashcash token string, returns a parsed version 
    /// of the input.
    /// ```
    /// use hashcash::Token;
    ///
    /// let t = "1:4:180606122628:example::OfZIJujxSu6ojd08LI0hLg:AAHz1w";
    /// let token = Token::from_str(t).unwrap();
    ///
    /// println!("{:?}", token);
    /// ```
    pub fn from_str(stamp: &str) -> Result<Token, ParseError> {
        let stamp_string = stamp.to_string();
        let stamp_parts: Vec<&str> = stamp_string.split(":").collect();

        if stamp_parts.len() != 7 {
            return Err(ParseError { 
                message: "Invalid number of parameters" 
            });
        }

        let ver = match stamp_parts[0].parse::<u8>() {
            Ok(n) => n,
            Err(_) => {
                return Err(ParseError {
                    message: "Invalid version specifier" 
                });
            },
        };
        let bits = match stamp_parts[1].parse::<u32>() {
            Ok(n) => n,
            Err(_) => {
                return Err(ParseError {
                    message: "Invalid difficulty specifier"
                });
            },
        };
        let date = match NaiveDateTime::parse_from_str(stamp_parts[2], DATE_FMT) {
            Ok(d) => d,
            Err(_) => {
                return Err(ParseError {
                    message: "Invalid date specifier"
                });
            },
        };
        let rand = match decode(stamp_parts[5]) {
            Ok(v) => v,
            Err(_) => {
                return Err(ParseError {
                    message: "Invalid base64 random string" 
                });
            },
        };
        let counter = match decode(stamp_parts[6]) {
            Ok(v) => v,
            Err(_) => {
                return Err(ParseError {
                    message: "Invalid base64 counter string" 
                });
            },
        };

        Ok(Token { 
            ver, 
            bits, 
            date, 
            resource: stamp_parts[3].to_string(), 
            ext: stamp_parts[4].to_string(), 
            rand, 
            counter,
        })
    }

    /// Given a resource string and a difficulty factor, mints a new 
    /// `hashcash::Token` and returns it.
    /// 
    /// ```
    /// use hashcash::Token;
    ///
    /// let resource = String::from("test@hashcash.rs");
    /// let bits = 4; // very low difficulty - 20 is normal
    /// let token = Token::new(resource, bits);
    /// println!("Token: {}", token.to_string());
    /// ```
    pub fn new(resource: String, bits: u32) -> Token {
        let mut ctr = thread_rng().gen_range(1, 1048576);
        let ext = String::from("");
        let date = get_current_naive_date();
        let ver = 1;

        let rand: Vec<u8> = thread_rng()
            .sample_iter(&Standard)
            .take(16)
            .collect();
        
        loop {
            let mut counter = vec![];
            counter.write_u32::<BigEndian>(ctr).unwrap();

            let stamp = Token {
                ver,
                bits,
                date,
                resource: resource.clone(),
                ext: ext.clone(),
                rand: rand.clone(),
                counter,
            };

            match stamp.check() {
                Ok(_) => {
                    return Token::from_str(&stamp.to_string()).unwrap();
                },
                Err(_) => {
                    ctr += 1;
                },
            }
        }
    }

    /// Validates the `hashcash::Token`, returning any validation errors if 
    /// not valid.
    ///
    /// ```
    /// use hashcash::Token;
    ///
    /// let token = "1:4:180606122628:example::OfZIJujxSu6ojd08LI0hLg:AAHz1w";
    /// 
    /// match Token::from_str(token) {
    ///     Ok(t) => {
    ///         match t.check() {
    ///             Ok(_) => println!("OK"),
    ///             Err(e) => eprintln!("{:?}", e),
    ///         }
    ///     },
    ///     Err(e) => eprintln!("{}", e.message)
    /// }
    /// ```
    pub fn check(&self) -> Result<&Self, CheckError> {
        let mut leading_zeros = 0;
        let mut hasher = Sha1::new();
        let result: &mut [u8] = &mut [0; 20];

        hasher.input_str(&self.to_string());
        hasher.result(result);

        for byte in result {
            let front_zeros = byte.leading_zeros();
            leading_zeros += front_zeros;

            if front_zeros < 8 {
                break;
            }
        }
        
        if leading_zeros < self.bits {
            return Err(CheckError::DifficultyError);
        }

        let expires_after = Duration::days(2);
        let time_delta = get_current_naive_date() - self.date;
        
        if time_delta >= expires_after {
            return Err(CheckError::ExpiryError);
        }

        Ok(self)
    }

    /// Returns a fully qualified hashcash token string suitable for use as a 
    /// `X-Hashcash` header value or otherwise.
    pub fn to_string(&self) -> String {
        let mut rand = encode(&self.rand);
        let mut counter = encode(&self.counter);

        // Pop the base64 == off the rand and counter for "prettier" output
        rand.pop();
        rand.pop();
        counter.pop();
        counter.pop();

        format!(
            "{}:{}:{}:{}:{}:{}:{}",
            self.ver.to_string(),
            self.bits.to_string(),
            self.date.format(DATE_FMT),
            self.resource,
            self.ext,
            rand,
            counter
        )
    }
}

fn get_current_naive_date() -> NaiveDateTime {
    let date_local = Local::now().to_rfc3339();
    let date_normalized = DateTime::parse_from_rfc3339(&date_local).unwrap();
    
    date_normalized.naive_local()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_mints_a_new_valid_stamp() {
        let stamp1 = Token::new(String::from("test@hashcash.rs"), 4);
        stamp1.check().unwrap();
        println!("{}", stamp1.to_string());
        let stamp2 = Token::from_str(&stamp1.to_string()).unwrap();
        stamp2.check().unwrap();
        assert_eq!(stamp1, stamp2);
    }
}