use bit mask to check proof of work
This commit is contained in:
Eitan Chatav 2016-11-16 17:09:01 -08:00
parent ee5aec87ad
commit 0edfae4621

View File

@ -15,7 +15,7 @@ type secret_key = Sodium.Box.secret_key
type public_key = Sodium.Box.public_key type public_key = Sodium.Box.public_key
type channel_key = Sodium.Box.channel_key type channel_key = Sodium.Box.channel_key
type nonce = Sodium.Box.nonce type nonce = Sodium.Box.nonce
type difficulty = int type difficulty = int64
let random_keypair = Sodium.Box.random_keypair let random_keypair = Sodium.Box.random_keypair
let random_nonce = Sodium.Box.random_nonce let random_nonce = Sodium.Box.random_nonce
@ -35,13 +35,9 @@ let check_proof_of_work pk nonce difficulty =
[ Sodium.Box.Bigbytes.of_public_key pk ; [ Sodium.Box.Bigbytes.of_public_key pk ;
Sodium.Box.Bigbytes.of_nonce nonce ] in Sodium.Box.Bigbytes.of_nonce nonce ] in
let bytes = MBytes.of_string hash in let bytes = MBytes.of_string hash in
let len = MBytes.length bytes * 8 in let last_int64 =
try EndianBigstring.BigEndian.get_int64 bytes (MBytes.length bytes - 8) in
for i = len - 1 downto (len - difficulty) do Int64.logand last_int64 (Int64.of_int 1) < difficulty
if MBytes.get_bool bytes i then raise Exit
done;
true
with Exit -> false
let generate_proof_of_work pk difficulty = let generate_proof_of_work pk difficulty =
let rec loop nonce = let rec loop nonce =
if check_proof_of_work pk nonce difficulty then nonce if check_proof_of_work pk nonce difficulty then nonce