forked from LaurentMazare/btc-ocaml
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash.ml
More file actions
51 lines (41 loc) · 1.49 KB
/
Copy pathhash.ml
File metadata and controls
51 lines (41 loc) · 1.49 KB
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
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 =
if String.is_prefix str ~prefix:"0x" then
let len = String.length str in
if len % 2 = 0 then
String.init (len / 2 - 1) ~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"
else
failwith "Incorrect prefix"
let to_hex str =
let len = String.length str in
let hex =
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)
)
in
"0x" ^ hex
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 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'))