ligo/src/client/embedded/alpha/client_proto_nonces.ml

83 lines
2.6 KiB
OCaml
Raw Normal View History

2016-09-08 21:13:10 +04:00
(**************************************************************************)
(* *)
(* Copyright (c) 2014 - 2016. *)
(* Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)
(* *)
(* All rights reserved. No warranty, explicit or implicit, provided. *)
(* *)
(**************************************************************************)
(* TODO locking... *)
type t = (Block_hash.t * Nonce.t) list
let encoding : t Data_encoding.t =
let open Data_encoding in
list
(obj2
(req "block" Block_hash.encoding)
(req "nonce" Nonce.encoding))
let filename cctxt =
Client_commands.(Filename.concat cctxt.config.base_dir "nonces")
2016-09-08 21:13:10 +04:00
let load cctxt =
let filename = filename cctxt in
2016-09-08 21:13:10 +04:00
if not (Sys.file_exists filename) then
Lwt.return []
else
Data_encoding_ezjsonm.read_file filename >>= function
| Error _ ->
cctxt.Client_commands.error "couldn't to read the nonces file"
| Ok json ->
2016-09-08 21:13:10 +04:00
match Data_encoding.Json.destruct encoding json with
| exception _ -> (* TODO print_error *)
cctxt.Client_commands.error "didn't understand the nonces file"
2016-09-08 21:13:10 +04:00
| list ->
Lwt.return list
let check_dir dirname =
if not (Sys.file_exists dirname) then
Lwt_utils.create_dir dirname
2016-09-08 21:13:10 +04:00
else
Lwt.return ()
let save cctxt list =
2016-09-08 21:13:10 +04:00
Lwt.catch
(fun () ->
let dirname = Client_commands.(cctxt.config.base_dir) in
2016-09-08 21:13:10 +04:00
check_dir dirname >>= fun () ->
let filename = filename cctxt in
2016-09-08 21:13:10 +04:00
let json = Data_encoding.Json.construct encoding list in
Data_encoding_ezjsonm.write_file filename json >>= function
| Error _ -> failwith "Json.write_file"
| Ok () -> return ())
2016-09-08 21:13:10 +04:00
(fun exn ->
cctxt.Client_commands.error
"could not write the nonces file: %s." (Printexc.to_string exn))
2016-09-08 21:13:10 +04:00
let mem cctxt block_hash =
load cctxt >|= fun data ->
2016-09-08 21:13:10 +04:00
List.mem_assoc block_hash data
let find cctxt block_hash =
load cctxt >|= fun data ->
2016-09-08 21:13:10 +04:00
try Some (List.assoc block_hash data)
with Not_found -> None
let add cctxt block_hash nonce =
load cctxt >>= fun data ->
save cctxt ((block_hash, nonce) ::
List.remove_assoc block_hash data)
2016-09-08 21:13:10 +04:00
let del cctxt block_hash =
load cctxt >>= fun data ->
save cctxt (List.remove_assoc block_hash data)
2016-09-08 21:13:10 +04:00
let dels cctxt hashes =
load cctxt >>= fun data ->
save cctxt @@
2016-09-08 21:13:10 +04:00
List.fold_left
(fun data hash -> List.remove_assoc hash data)
data hashes