-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhash.ml
49 lines (39 loc) · 1.48 KB
/
hash.ml
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
open Core.Std
let hex_of_char c =
if Char.('0' <= c && c <= '9') then Char.to_int c - Char.to_int '0'
else if Char.('a' <= c && c <= 'f') then 10 + Char.to_int c - Char.to_int 'a'
else failwithf "char %c is not hex" c ()
let char_of_hex i =
if 0 <= i && i < 10 then Char.of_int_exn (Char.to_int '0' + i)
else if 10 <= i && i < 16 then Char.of_int_exn (Char.to_int 'a' + i - 10)
else failwithf "not in hex range %d" i ()
let of_hex str =
let len = String.length str in
if len % 2 = 0 then
String.init (len / 2) ~f:(fun i ->
Char.of_int_exn
(16 * hex_of_char str.[len - 2*i - 2] + hex_of_char str.[len - 2*i - 1]))
else failwith "Input string size is odd"
let to_hex str =
let len = String.length str in
String.init (2*len) ~f:(fun i ->
let c = str.[len-1 - i / 2] |> Char.to_int in
if i % 2 = 0 then char_of_hex (c / 16) else char_of_hex (c % 16)
)
let difficulty t =
let rec loop acc index =
if index < 0 then acc
else
let c = String.get t index |> Char.to_int in
loop (256. *. acc +. float c) (index - 1)
in
(* 1.1579e77 ~ 2^256 *)
1.1579e77 /. loop 0. (String.length t - 1)
include String
let sexp_of_t t = Sexp.Atom (to_hex t)
let t_of_sexp = function
| Sexp.Atom s -> of_hex s
| _ -> failwith "Atom expected"
let consume iobuf = Iobuf.Consume.string iobuf ~len:32
let fill iobuf str = Iobuf.Fill.tail_padded_fixed_string iobuf str ~len:32 ~padding:'\000'
let zero = String.of_char_list (List.init 32 ~f:(fun _ -> '\000'))