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
// #![feature(proc_macro)]

extern crate blake2;
extern crate rand;
extern crate hex;

#[cfg(not(target_arch = "wasm32"))]
extern crate crossbeam_utils;
#[cfg(not(target_arch = "wasm32"))]
extern crate crossbeam_channel;
#[cfg(not(target_arch = "wasm32"))]
extern crate num_cpus;

#[cfg(target_arch = "wasm32")]
#[macro_use]
extern crate stdweb;

#[cfg(target_arch = "wasm32")]
use stdweb::js_export;

use blake2::{Blake2b};
use blake2::digest::{Input, VariableOutput};

use hex::{FromHex, ToHex};

#[cfg(not(target_arch = "wasm32"))]
use rand::{XorShiftRng, Rng, SeedableRng};

#[cfg(target_arch = "wasm32")]
use rand::{IsaacRng, Rng};

fn check_result_threshold(hash: &[u8]) -> bool {
    let len = hash.len();
    let first = (&hash[len-3..len]).iter().fold(true, |acc, &byte| {
        acc && byte == 255
    });
    hash[len-4] >= 192 && first
}

fn hash_work_internal(work: &[u8], input: &[u8]) -> [u8;8] {
    let mut hasher = Blake2b::new(8).unwrap();
    hasher.process(&work[..]);
    hasher.process(&input[..]);
    let mut output = [0u8; 8];
    hasher.variable_result(&mut output).unwrap();
    output
}

/// Takes an input block hash or public key in the form of a 32-character hexadecimal encoded
/// string and returns an 16-character hex-encoded string of the generated work. Runs a
/// maximum of 100 million iterations, after which it will return 0000000000000000 if it
/// did not find matching work.
#[cfg(not(target_arch = "wasm32"))]
pub fn generate_work(input_hash: &str) -> String {
    let bytes = Vec::from_hex(input_hash).unwrap();
    generate_work_internal(&bytes[..], 8)
}

#[cfg(not(target_arch = "wasm32"))]
fn generate_work_internal(input: &[u8], max_iters_pow: u32) -> String {
    let numcpus = num_cpus::get();
    let (tx,rx) = crossbeam_channel::bounded::<String>(numcpus);
    let (donetx, donerx) = crossbeam_channel::bounded::<bool>(numcpus);
    crossbeam_utils::scoped::scope(|scope| {
        for _ in 0..numcpus {
            scope.spawn(|| {
                let mut rng: XorShiftRng = SeedableRng::from_seed(rand::random::<[u32; 4]>());
                let mut work = [0u8; 8];
                let mut iters = 0u64;
                let mut result_valid = false;
                let mut done = donerx.try_recv().unwrap_or(false);
                let max_iters = 10u64.pow(max_iters_pow);
                while !result_valid && !done && iters < max_iters/numcpus as u64 {
                    work = rng.gen::<[u8; 8]>();
                    let output = hash_work_internal(&work[..], input);
                    result_valid = check_result_threshold(&output[..]);
                    iters += 1;
                    done = donerx.try_recv().unwrap_or(false);
                }
                if done {
                    return;
                }
                if result_valid {
                    work.reverse();
                    let mut work_str = String::with_capacity(16);
                    work.write_hex(&mut work_str).unwrap();
                    for _ in 0..(16-work_str.len()) {
                        work_str = format!("0{}", work_str);
                    }
                    let _ = tx.send(work_str).is_ok();
                } else {
                    let _ = tx.send(String::from("0000000000000000")).is_ok();
                }
            });
        }
    });
    let mut res = rx.recv().unwrap();
    let mut msgs_resvd = 0;
    while res == "0000000000000000" && msgs_resvd < numcpus-1 {
        res = rx.recv().unwrap();
        msgs_resvd += 1;
    }
    for _ in 0..numcpus {
        donetx.send(true).unwrap();
    }
    res
}

/// Takes an input block hash or public key in the form of a 32-character hexadecimal encoded
/// string and returns an 16-character hex-encoded string of the generated work. Runs until
/// it finds valid work.
#[cfg(not(target_arch = "wasm32"))]
pub fn generate_work_no_limit(input: &String) -> String {
    loop {
        let work = generate_work(input);
        if work != "0000000000000000" {
            return work;
        }
    }
}

/// Take an input block hash or public key in the form of a 32-character hexadecimal encoded
/// string and a 16-character hex encoded string of a work value and returns a boolean of
/// whether the work is valid for the input hash.
pub fn check_work(input: &str, work: &str) -> bool {
    let input_bytes = Vec::from_hex(input).unwrap();
    let mut work_bytes = Vec::from_hex(work).unwrap();
    work_bytes.reverse();
    let mut hasher = Blake2b::new(8).unwrap();
    hasher.process(&work_bytes[..]);
    hasher.process(&input_bytes[..]);
    let mut output = [0u8; 8];
    {
        let result = hasher.variable_result(&mut output);
        if result.is_err() {
            return false;
        }
    }
    check_result_threshold(&output[..])
}

/// WASM-compatible version of `generate_work()`
/// 
/// Take an input block hash or public key in the form of a 32-character hexadecimal encoded
/// string and a 16-character hex encoded string of a work value and returns a boolean of
/// whether the work is valid for the input hash.
#[cfg(target_arch = "wasm32")]
#[js_export]
fn check_work_wasm(input: &str, work: &str) -> bool {
    check_work(input, work)
}

/// WASM-compatible version of `generate_work()`
/// 
/// Takes an input block hash or public key in the form of a 32-character hexadecimal encoded
/// string and returns an 16-character hex-encoded string of the generated work. Runs a
/// maximum of 100 million iterations, after which it will return 0000000000000000 if it
/// did not find matching work.
#[cfg(target_arch = "wasm32")]
#[js_export]
fn generate_work_wasm(input: &str, seed: i32) -> String {
    let bytes = Vec::from_hex(input).unwrap();
    generate_work_internal(&bytes[..], 8, seed as u64)
}

#[cfg(target_arch = "wasm32")]
fn generate_work_internal(input: &[u8], max_iters_pow: u32, seed: u64) -> String {
    let mut work = [0u8; 8];
    let mut iters = 0u64;
    let mut result_valid = false;
    let max_iters = 10u64.pow(max_iters_pow);
    let mut rng = IsaacRng::new_from_u64(seed);
    while !result_valid && iters < max_iters {
        work = rng.gen::<[u8; 8]>();
        let output = hash_work_internal(&work[..], input);
        result_valid = check_result_threshold(&output[..]);
        iters += 1;
    }
    if result_valid {
        work.reverse();
        let mut work_str = String::with_capacity(16);
        work.write_hex(&mut work_str).unwrap();
        for _ in 0..(16-work_str.len()) {
            work_str = format!("0{}", work_str);
        }
        work_str
    } else {
        String::from("0000000000000000")
    }
}

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

    #[test]
    fn validates_good_work() {
        let hex = String::from("8D3E5F07BFF7B7484CDCB392F47009F62997253D28BD98B94BCED95F03C4DA09");
        let work = String::from("4effb6b0cd5625e2");
        let valid = check_work(&hex, &work);
        assert!(valid);
    }

    #[test]
    fn does_not_validate_bad_work() {
        let hex = String::from("8D3E5F07BFF7B7484CDCB392F47009F62997253D28BD98B94BCED95F03C4DA09");
        let work = String::from("4effc680cd5625e2");
        let valid = check_work(&hex, &work);
        assert!(valid == false);
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn generates_valid_work() {
        let gen_hex = String::from("47F694A96653EB497709490776E492EFBB88EBC5C4E95CC0B2C9DCAB1930C36B");
        let gen_work = generate_work_no_limit(&gen_hex);
        println!("generated work: {}", gen_work);
        let valid = check_work(&gen_hex, &gen_work);
        assert!(valid);
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn has_80_percent_success_rate() {
        let mut valid_generations = 0;
        for i in 0..15 {
            let gen_hex = String::from("47F694A96653EB497709490776E492EFBB88EBC5C4E95CC0B2C9DCAB1930C36B");
            let gen_work = generate_work(&gen_hex);
            println!("generated work: {}", gen_work);
            let valid = check_work(&gen_hex, &gen_work);
            if valid {
                valid_generations += 1;
                println!("generated valid work on iter {}, total valid: {}", i, valid_generations);
            } else {
                println!("did not generate valid work on iter {}", i);
            }
        }
        assert!(valid_generations >= 12);
    }
}