ligo/src/utils/crypto_box.ml

50 lines
2.1 KiB
OCaml
Raw Normal View History

(**************************************************************************)
(* *)
(* Copyright (c) 2014 - 2016. *)
(* Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)
(* *)
(* All rights reserved. No warranty, explicit or implicit, provided. *)
(* *)
(**************************************************************************)
(** Tezos - X25519/XSalsa20-Poly1305 cryptography *)
type secret_key = Sodium.Box.secret_key
type public_key = Sodium.Box.public_key
type channel_key = Sodium.Box.channel_key
type nonce = Sodium.Box.nonce
2016-11-09 06:18:09 +04:00
type difficulty = int
let random_keypair = Sodium.Box.random_keypair
let random_nonce = Sodium.Box.random_nonce
let increment_nonce = Sodium.Box.increment_nonce
let box = Sodium.Box.Bigbytes.box
2016-11-08 02:38:02 +04:00
let box_open sk pk msg nonce =
try Some (Sodium.Box.Bigbytes.box_open sk pk msg nonce) with
| Sodium.Verification_failure -> None
2016-11-05 20:12:25 +04:00
let to_secret_key = Sodium.Box.Bigbytes.to_secret_key
let of_secret_key = Sodium.Box.Bigbytes.of_secret_key
let to_public_key = Sodium.Box.Bigbytes.to_public_key
let of_public_key = Sodium.Box.Bigbytes.of_public_key
let to_nonce = Sodium.Box.Bigbytes.to_nonce
let of_nonce = Sodium.Box.Bigbytes.of_nonce
2016-11-10 06:29:57 +04:00
let check_proof_of_work pk nonce difficulty =
let hash_bytes l =
let hash = Cryptokit.Hash.sha256 () in
List.iter (fun b -> hash#add_string (MBytes.to_string b)) l;
let r = hash#result in hash#wipe; r in
let hash = hash_bytes [of_public_key pk; of_nonce nonce] in
let bytes = MBytes.of_string hash in
let len = MBytes.length bytes * 8 in
try
for i = len - 1 downto (len - difficulty) do
if MBytes.get_bool bytes i then raise Exit
done;
true
with Exit -> false
2016-11-09 06:18:09 +04:00
let generate_proof_of_work pk difficulty =
let rec loop nonce =
if check_proof_of_work pk nonce difficulty then nonce
else loop (increment_nonce nonce) in
loop (random_nonce ())