text
stringlengths
0
601k
let create len = make len ( UChar . chr 0 )
let copy s = s # copy
let sub s start len = s # sub start len
let fill s start len u = for i = start to start + len - 1 do s # set i u done
let blit src srcoff dst dstoff len = for i = 0 to len - 1 do let u = src # get ( srcoff + i ) in dst # set ( dstoff + i ) u done
let concat s1 s2 = s1 # concat ( s2 :> uchar storage )
let iter proc s = s # iter proc end
let ( >>= ) = Result . bind
let scalar ? anchor ? tag ( ? plain_implicit = true ) true ( ? quoted_implicit = false ) false ( ? style = ` Plain ) Plain value = { anchor ; tag ; plain_implicit ; quoted_implicit ; style ; value }
let yaml_scalar_to_json t = match t with | " null " | " NULL " | " " | " Null " | " " ~ -> ` Null | " y " | " Y " | " yes " | " Yes " | " YES " | " true " | " True " | " TRUE " | " on " | " On " | " ON " -> ` Bool true | " n " | " N " | " no " | " No " | " NO " | " false " | " False " | " FALSE " | " off " | " Off " | " OFF " -> ` Bool false | " . - inf " -> ` Float neg_infinity | " . inf " -> ` Float infinity | " . nan " | " . NaN " | " . NAN " -> ` Float nan | s -> ( try ` Float ( float_of_string s ) s with _ -> ` String s ) s
let to_json v = let rec fn = function | ` Scalar { value ; quoted_implicit = true } -> ` String value | ` Scalar { value } -> yaml_scalar_to_json value | ` Alias _ -> failwith " Anchors are not supported when serialising to JSON " | ` A { s_members } -> ` A ( List . map fn s_members ) s_members | ` O { m_members } -> let simple_key_to_string = function | ` Scalar { anchor ; value } -> value | k -> failwith " non - string key is not supported " in ` O ( List . map ( fun ( k , v ) v -> ( simple_key_to_string k , fn v ) v ) v m_members ) m_members in match fn v with r -> Ok r | exception Failure msg -> Error ( ` Msg msg ) msg
let of_json ( v : value ) value = let rec fn = function | ` Null -> ` Scalar ( scalar ) " " | ` Bool b -> ` Scalar ( scalar ( string_of_bool b ) b ) b | ` Float f -> ` Scalar ( scalar ( string_of_float f ) f ) f | ` String value -> ` Scalar ( scalar value ) value | ` A l -> ` A { s_anchor = None ; s_tag = None ; s_implicit = true ; s_members = List . map fn l ; } | ` O l -> ` O { m_anchor = None ; m_tag = None ; m_implicit = true ; m_members = List . map ( fun ( k , v ) v -> ( ` Scalar ( scalar k ) k , fn v ) v ) v l ; } in match fn v with r -> Ok r | exception Failure msg -> Error ( ` Msg msg ) msg
let to_string ? len ( ? encoding = ` Utf8 ) Utf8 ? scalar_style ? layout_style ( v : value ) value = emitter ? len ( ) >>= fun t -> stream_start t encoding >>= fun ( ) -> document_start t >>= fun ( ) -> let rec iter = function | ` Null -> Stream . scalar ( scalar ) " " t | ` String s -> let style = match yaml_scalar_to_json s with | ` String s -> scalar_style | _ -> Some ` Double_quoted in Stream . scalar ( scalar ? style ~ quoted_implicit : true s ) s t | ` Float s -> Stream . scalar ( scalar ( Printf . sprintf " . % 16g " s ) s ) s t | ` Bool s -> Stream . scalar ( scalar ( string_of_bool s ) s ) s t | ` A l -> sequence_start ? style : layout_style t >>= fun ( ) -> let rec fn = function | [ ] -> sequence_end t | hd :: tl -> iter hd >>= fun ( ) -> fn tl in fn l | ` O l -> mapping_start ? style : layout_style t >>= fun ( ) -> let rec fn = function | [ ] -> mapping_end t | ( k , v ) v :: tl -> iter ( ` String k ) k >>= fun ( ) -> iter v >>= fun ( ) -> fn tl in fn l in iter v >>= fun ( ) -> document_end t >>= fun ( ) -> stream_end t >>= fun ( ) -> let r = Stream . emitter_buf t in Ok ( Bytes . to_string r ) r
let to_string_exn ? len ? encoding ? scalar_style ? layout_style s = match to_string ? len ? encoding ? scalar_style ? layout_style s with | Ok s -> s | Error ( ` Msg m ) m -> raise ( Invalid_argument m ) m
let yaml_to_string ( ? encoding = ` Utf8 ) Utf8 ? scalar_style ? layout_style v = emitter ( ) >>= fun t -> stream_start t encoding >>= fun ( ) -> document_start t >>= fun ( ) -> let rec iter = function | ` Scalar s -> Stream . scalar s t | ` Alias anchor -> alias t anchor | ` A { s_anchor = anchor ; s_tag = tag ; s_implicit = implicit ; s_members } -> sequence_start ? anchor ? tag ~ implicit ? style : layout_style t >>= fun ( ) -> let rec fn = function | [ ] -> sequence_end t | hd :: tl -> iter hd >>= fun ( ) -> fn tl in fn s_members | ` O { m_anchor = anchor ; m_tag = tag ; m_implicit = implicit ; m_members } -> mapping_start ? anchor ? tag ~ implicit ? style : layout_style t >>= fun ( ) -> let rec fn = function | [ ] -> mapping_end t | ( k , v ) v :: tl -> iter k >>= fun ( ) -> iter v >>= fun ( ) -> fn tl in fn m_members in iter v >>= fun ( ) -> document_end t >>= fun ( ) -> stream_end t >>= fun ( ) -> let r = Stream . emitter_buf t in Ok ( Bytes . to_string r ) r
let yaml_of_string s = let open Event in parser s >>= fun t -> let next ( ) = do_parse t >>= fun ( e , pos ) pos -> Ok ( e , pos ) pos in next ( ) >>= fun ( e , pos ) pos -> match e with | Stream_start _ -> ( next ( ) >>= fun ( e , pos ) pos -> match e with | Document_start _ -> let rec parse_v ( e , pos ) pos = match e with | Sequence_start { anchor ; tag ; implicit ; style = _ } -> next ( ) >>= parse_seq [ ] >>= fun s -> Ok ( ` A { s_anchor = anchor ; s_tag = tag ; s_implicit = implicit ; s_members = s ; } ) | Scalar scalar -> Ok ( ` Scalar scalar ) scalar | Alias { anchor } -> Ok ( ` Alias anchor ) anchor | Mapping_start { anchor ; tag ; implicit ; style = _ } -> next ( ) >>= parse_map [ ] >>= fun s -> Ok ( ` O { m_anchor = anchor ; m_tag = anchor ; m_implicit = implicit ; m_members = s ; } ) | e -> Error ( ` Msg " todo ) " and parse_seq acc ( e , pos ) pos = match e with | Sequence_end -> Ok ( List . rev acc ) acc | e -> parse_v ( e , pos ) pos >>= fun v -> next ( ) >>= parse_seq ( v :: acc ) acc and parse_map acc ( e , pos ) pos = match e with | Mapping_end -> Ok ( List . rev acc ) acc | e -> parse_v ( e , pos ) pos >>= fun k -> next ( ) >>= parse_v >>= fun v -> next ( ) >>= parse_map ( ( k , v ) v :: acc ) acc in next ( ) >>= parse_v | Stream_end -> Ok ( ` Scalar ( scalar ) ) " " | e -> Error ( ` Msg " Not document start ) ) " | _ -> Error ( ` Msg " Not stream start ) "
let of_string s = yaml_of_string s >>= to_json
let of_string_exn s = match of_string s with | Ok s -> s | Error ( ` Msg m ) m -> raise ( Invalid_argument m ) m
let pp ppf s = match to_string s with | Ok s -> Format . pp_print_string ppf s | Error ( ` Msg m ) m -> Format . pp_print_string ppf ( Printf . sprintf ( " error ( % s ) s ) s " m ) m
let rec equal v1 v2 = match ( v1 , v2 ) v2 with | ` Null , ` Null -> true | ` Bool x1 , ` Bool x2 -> ( ( = ) : bool -> bool -> bool ) bool x1 x2 | ` Float x1 , ` Float x2 -> ( ( = ) : float -> float -> bool ) bool x1 x2 | ` String x1 , ` String x2 -> String . equal x1 x2 | ` A xs1 , ` A xs2 -> List . for_all2 equal xs1 xs2 | ` O xs1 , ` O xs2 -> List . for_all2 ( fun ( k1 , v1 ) v1 ( k2 , v2 ) v2 -> String . equal k1 k2 && equal v1 v2 ) v2 xs1 xs2 | _ -> false
let uuid_random_state = Random . State . make_self_init ( )
module Make ( File : WitnessUtil . File ) ( Cfg : MyCFG . CfgBidir ) ( Spec : Spec ) ( EQSys : GlobConstrSys with module LVar = VarF ( Spec . C ) and module GVar = GVarF ( Spec . V ) and module D = Spec . D and module G = Spec . G ) ( LHT : BatHashtbl . S with type key = EQSys . LVar . t ) ( GHT : BatHashtbl . S with type key = EQSys . GVar . t ) = struct module NH = BatHashtbl . Make ( Node ) module WitnessInvariant = WitnessUtil . Invariant ( File ) ( Cfg ) let join_contexts ( lh : Spec . D . t LHT . t ) : Spec . D . t NH . t = let nh = NH . create 113 in LHT . iter ( fun ( n , _ ) d -> let d ' = try Spec . D . join ( NH . find nh n ) d with Not_found -> d in NH . replace nh n d ' ) lh ; nh let write lh gh = let yaml_creation_time = ` String ( TimeUtil . iso8601_now ( ) ) in let yaml_producer = ` O [ ( " name " , ` String " Goblint " ) ; ( " version " , ` String Version . goblint ) ; ( " command_line " , ` String Goblintutil . command_line ) ; ] in let files = GobConfig . get_string_list " files " in let sha256_file f = Sha256 . ( to_hex ( file f ) ) in let sha256_file_cache = BatCache . make_ht ~ gen : sha256_file ~ init_size : 5 in let sha256_file = sha256_file_cache . get in let yaml_task = ` O ( [ ( " input_files " , ` A ( List . map Yaml . Util . string files ) ) ; ( " input_file_hashes " , ` O ( List . map ( fun file -> ( file , ` String ( sha256_file file ) ) ) files ) ) ; ( " data_model " , ` String ( match GobConfig . get_string " exp . architecture " with | " 64bit " -> " LP64 " | " 32bit " -> " ILP32 " | _ -> failwith " invalid architecture " ) ) ; ( " language " , ` String " C " ) ; ] @ match ! Svcomp . task with | Some ( module Task ) -> [ ( " specification " , ` String ( Svcomp . Specification . to_string Task . specification ) ) ] | None -> [ ] ) in let nh = join_contexts lh in let yaml_entries = NH . fold ( fun n local acc -> match n with | Statement _ when WitnessInvariant . is_invariant_node n -> let context : Invariant . context = { scope = Node . find_fundec n ; i = - 1 ; lval = None ; offset = Cil . NoOffset ; deref_invariant ( = fun _ _ _ -> Invariant . none ) } in begin match Spec . D . invariant context local with | Some inv -> let loc = Node . location n in let invs = WitnessUtil . InvariantExp . process_exp inv in List . fold_left ( fun acc inv -> let uuid = Uuidm . v4_gen uuid_random_state ( ) in let entry = ` O [ ( " entry_type " , ` String " loop_invariant " ) ; ( " metadata " , ` O [ ( " format_version " , ` String " 0 . 1 " ) ; ( " uuid " , ` String ( Uuidm . to_string uuid ) ) ; ( " creation_time " , yaml_creation_time ) ; ( " producer " , yaml_producer ) ; ( " task " , yaml_task ) ; ] ) ; ( " location " , ` O [ ( " file_name " , ` String loc . file ) ; ( " file_hash " , ` String ( sha256_file loc . file ) ) ; ( " line " , ` Float ( float_of_int loc . line ) ) ; ( " column " , ` Float ( float_of_int ( loc . column - 1 ) ) ) ; ( " function " , ` String ( Node . find_fundec n ) . svar . vname ) ; ] ) ; ( " loop_invariant " , ` O [ ( " string " , ` String ( CilType . Exp . show inv ) ) ; ( " type " , ` String " assertion " ) ; ( " format " , ` String " C " ) ; ] ) ; ] in entry :: acc ) acc invs | None -> acc end | _ -> acc ) nh [ ] in let yaml = ` A yaml_entries in Yaml_unix . to_file_exn ( Fpath . v ( GobConfig . get_string " witness . yaml . path " ) ) yaml end
module M ( F : Ctypes . FOREIGN ) FOREIGN = struct let foreign = F . foreign module C = struct include Ctypes let ( @-> ) = F ( . @-> ) let returning = F . returning end let version = foreign " yaml_get_version_string " C ( . void @-> returning string ) string let get_version = foreign " yaml_get_version " C ( . ptr int @-> ptr int @-> ptr int @-> returning void ) void let token_delete = foreign " yaml_token_delete " C ( . ptr T . Token . t @-> returning void ) void let parser_init = foreign " yaml_parser_initialize " C ( . ptr T . Parser . t @-> returning int ) int let parser_delete = foreign " yaml_parser_delete " C ( . ptr T . Parser . t @-> returning void ) void let parser_set_input_string = foreign " yaml_parser_set_input_string " C ( . ptr T . Parser . t @-> ptr char @-> size_t @-> returning void ) void let parser_parse = foreign " yaml_parser_parse " C ( . ptr T . Parser . t @-> ptr T . Event . t @-> returning int ) int let emitter_init = foreign " yaml_emitter_initialize " C ( . ptr T . Emitter . t @-> returning int ) int let emitter_delete = foreign " yaml_emitter_delete " C ( . ptr T . Emitter . t @-> returning void ) void let emitter_set_output_string = foreign " yaml_emitter_set_output_string " C ( . ptr T . Emitter . t @-> ocaml_bytes @-> size_t @-> ptr size_t @-> returning void ) void let emitter_set_encoding = foreign " yaml_emitter_set_encoding " C ( . ptr T . Emitter . t @-> T . encoding_t @-> returning void ) void let emitter_set_canonical = foreign " yaml_emitter_set_canonical " C ( . ptr T . Emitter . t @-> bool @-> returning void ) void let emitter_set_indent = foreign " yaml_emitter_set_indent " C ( . ptr T . Emitter . t @-> int @-> returning void ) void let emitter_set_width = foreign " yaml_emitter_set_width " C ( . ptr T . Emitter . t @-> int @-> returning void ) void let emitter_set_unicode = foreign " yaml_emitter_set_unicode " C ( . ptr T . Emitter . t @-> bool @-> returning void ) void let emitter_flush = foreign " yaml_emitter_flush " C ( . ptr T . Emitter . t @-> returning int ) int let emitter_emit = foreign " yaml_emitter_emit " C ( . ptr T . Emitter . t @-> ptr T . Event . t @-> returning int ) int let stream_start_event_init = foreign " yaml_stream_start_event_initialize " C ( . ptr T . Event . t @-> T . encoding_t @-> returning int ) int let stream_end_event_init = foreign " yaml_stream_end_event_initialize " C ( . ptr T . Event . t @-> returning int ) int let document_start_event_init = foreign " yaml_document_start_event_initialize " C ( . ptr T . Event . t @-> ptr T . Version_directive . t @-> ptr T . Tag_directive . t @-> ptr T . Tag_directive . t @-> bool @-> returning int ) int let document_end_event_init = foreign " yaml_document_end_event_initialize " C ( . ptr T . Event . t @-> bool @-> returning int ) int let alias_event_init = foreign " yaml_alias_event_initialize " C ( . ptr T . Event . t @-> string @-> returning int ) int let scalar_event_init = foreign " yaml_scalar_event_initialize " C ( . ptr T . Event . t @-> string_opt @-> string_opt @-> string @-> int @-> bool @-> bool @-> T . scalar_style_t @-> returning int ) int let sequence_start_event_init = foreign " yaml_sequence_start_event_initialize " C ( . ptr T . Event . t @-> string_opt @-> string_opt @-> bool @-> T . sequence_style_t @-> returning int ) int let sequence_end_event_init = foreign " yaml_sequence_end_event_initialize " C ( . ptr T . Event . t @-> returning int ) int let mapping_start_event_init = foreign " yaml_mapping_start_event_initialize " C ( . ptr T . Event . t @-> string_opt @-> string_opt @-> bool @-> T . mapping_style_t @-> returning int ) int let mapping_end_event_init = foreign " yaml_mapping_end_event_initialize " C ( . ptr T . Event . t @-> returning int ) int end
module Encoding = struct type t = [ ` Any | ` E of int64 | ` Utf16be | ` Utf16le | ` Utf8 ] end
module Error = struct type t = [ ` None | ` Memory | ` Reader | ` Scanner | ` Parser | ` Composer | ` Writer | ` Emitter | ` E of int64 ] end
module Scalar_style = struct type t = [ ` Any | ` Plain | ` Single_quoted | ` Double_quoted | ` Literal | ` Folded | ` E of int64 ] end
module Sequence_style = struct type t = [ ` Any | ` Block | ` Flow | ` E of int64 ] end
module Mapping_style = struct type t = [ ` Any | ` Block | ` Flow | ` E of int64 ] end
module Token_type = struct type t = [ ` None | ` Stream_start | ` Stream_end | ` Version_directive | ` Tag_directive | ` Document_start | ` Document_end | ` Block_sequence_start | ` Block_mapping_start | ` Block_end | ` Flow_sequence_start | ` Flow_sequence_end | ` Flow_mapping_start | ` Flow_mapping_end | ` Block_entry | ` Flow_entry | ` Key | ` Value | ` Alias | ` Anchor | ` Tag | ` Scalar | ` E of int64 ] end
module Event_type = struct type t = [ ` None | ` Stream_start | ` Stream_end | ` Document_start | ` Document_end | ` Alias | ` Scalar | ` Sequence_start | ` Sequence_end | ` Mapping_start | ` Mapping_end | ` E of int64 ] end
module M ( F : Ctypes . TYPE ) TYPE = struct let yaml_char_t = F . uchar let enum label typedef vals = F . enum ~ typedef : true ~ unexpected ( : fun i -> ` E i ) i typedef ( List . map ( fun ( a , b ) b -> ( a , F . constant ( " YAML_ " ^ b ^ " _ " ^ label ) label F . int64_t ) int64_t ) int64_t vals ) vals let encoding_t : Encoding . t F . typ = enum " ENCODING " " yaml_encoding_t " [ ( ` Any , " ANY ) " ; ( ` Utf8 , " UTF8 ) " ; ( ` Utf16le , " UTF16LE ) " ; ( ` Utf16be , " UTF16BE ) " ; ] let error_t : Error . t F . typ = enum " ERROR " " yaml_error_type_t " [ ( ` None , " NO ) " ; ( ` Memory , " MEMORY ) " ; ( ` Reader , " READER ) " ; ( ` Scanner , " SCANNER ) " ; ( ` Parser , " PARSER ) " ; ( ` Composer , " COMPOSER ) " ; ( ` Writer , " WRITER ) " ; ( ` Emitter , " EMITTER ) " ; ] let scalar_style_t : Scalar_style . t F . typ = enum " SCALAR_STYLE " " yaml_scalar_style_t " [ ( ` Any , " ANY ) " ; ( ` Plain , " PLAIN ) " ; ( ` Single_quoted , " SINGLE_QUOTED ) " ; ( ` Double_quoted , " DOUBLE_QUOTED ) " ; ( ` Literal , " LITERAL ) " ; ( ` Folded , " FOLDED ) " ; ] let sequence_style_t : Sequence_style . t F . typ = enum " SEQUENCE_STYLE " " yaml_sequence_style_t " [ ( ` Any , " ANY ) " ; ( ` Block , " BLOCK ) " ; ( ` Flow , " FLOW ) " ] let mapping_style_t : Mapping_style . t F . typ = enum " MAPPING_STYLE " " yaml_mapping_style_t " [ ( ` Any , " ANY ) " ; ( ` Block , " BLOCK ) " ; ( ` Flow , " FLOW ) " ] let token_type_t : Token_type . t F . typ = enum " TOKEN " " yaml_token_type_t " [ ( ` None , " NO ) " ; ( ` Stream_start , " STREAM_START ) " ; ( ` Stream_end , " STREAM_END ) " ; ( ` Version_directive , " VERSION_DIRECTIVE ) " ; ( ` Tag_directive , " TAG_DIRECTIVE ) " ; ( ` Document_start , " DOCUMENT_START ) " ; ( ` Document_end , " DOCUMENT_END ) " ; ( ` Block_sequence_start , " BLOCK_SEQUENCE_START ) " ; ( ` Block_mapping_start , " BLOCK_MAPPING_START ) " ; ( ` Block_end , " BLOCK_END ) " ; ( ` Flow_sequence_start , " FLOW_SEQUENCE_START ) " ; ( ` Flow_sequence_end , " FLOW_SEQUENCE_END ) " ; ( ` Flow_mapping_start , " FLOW_MAPPING_START ) " ; ( ` Flow_mapping_end , " FLOW_MAPPING_END ) " ; ( ` Block_entry , " BLOCK_ENTRY ) " ; ( ` Flow_entry , " FLOW_ENTRY ) " ; ( ` Key , " KEY ) " ; ( ` Value , " VALUE ) " ; ( ` Alias , " ALIAS ) " ; ( ` Tag , " TAG ) " ; ( ` Scalar , " SCALAR ) " ; ] let event_type_t : Event_type . t F . typ = enum " EVENT " " yaml_event_type_t " [ ( ` None , " NO ) " ; ( ` Stream_start , " STREAM_START ) " ; ( ` Stream_end , " STREAM_END ) " ; ( ` Document_start , " DOCUMENT_START ) " ; ( ` Document_end , " DOCUMENT_END ) " ; ( ` Alias , " ALIAS ) " ; ( ` Scalar , " SCALAR ) " ; ( ` Sequence_start , " SEQUENCE_START ) " ; ( ` Sequence_end , " SEQUENCE_END ) " ; ( ` Mapping_start , " MAPPING_START ) " ; ( ` Mapping_end , " MAPPING_END ) " ; ] type ' a typ = ' a Ctypes . structure F . typ type ' a utyp = ' a Ctypes . union F . typ type ( ' a , ' b ) ' b field = ( ' b , ' a Ctypes . structure ) structure F . field type ( ' a , ' b ) ' b ufield = ( ' b , ' a Ctypes . union ) union F . field module Version_directive = struct type t let t : t typ = F . structure " yaml_version_directive_s " let major = F ( . field t " major " int ) int let minor = F ( . field t " minor " int ) int let ( ) = F . seal t end module Tag_directive = struct type t let t : t typ = F . structure " yaml_tag_directive_s " let handle = F ( . field t " handle " string ) string let prefix = F ( . field t " prefix " string ) string let ( ) = F . seal t end module Mark = struct type t let t : t typ = F . structure " yaml_mark_s " let index = F ( . field t " index " size_t ) size_t let line = F ( . field t " line " size_t ) size_t let column = F ( . field t " column " size_t ) size_t let ( ) = F . seal t end module Token = struct module Stream_start = struct type t let t : t typ = F ( . structure " stream_start_s ) " let encoding = F ( . field t " encoding " encoding_t ) encoding_t let ( ) = F . seal t end module Alias = struct type t let t : t typ = F . structure " alias_s " let value = F ( . field t " value " ( ptr yaml_char_t ) yaml_char_t ) yaml_char_t let ( ) = F . seal t end module Anchor = struct type t let t : t typ = F . structure " anchor_s " let value = F ( . field t " value " ( ptr yaml_char_t ) yaml_char_t ) yaml_char_t let ( ) = F . seal t end module Scalar = struct type t let t : t typ = F . structure " scalar_s " let value = F ( . field t " value " ( ptr yaml_char_t ) yaml_char_t ) yaml_char_t let length = F ( . field t " length " size_t ) size_t let style = F ( . field t " style " scalar_style_t ) scalar_style_t let ( ) = F . seal t end module Version = struct type t let t : t typ = F . structure " version_directive_s " let value = F ( . field t " major " int ) int let length = F ( . field t " minor " int ) int let ( ) = F . seal t end module Data = struct type t let t : t utyp = F . union " data_u " let stream_start = F ( . field t " stream_start " Stream_start . t ) t let alias = F ( . field t " alias " Alias . t ) t let anchor = F ( . field t " anchor " Anchor . t ) t let scalar = F ( . field t " scalar " Scalar . t ) t let version = F ( . field t " version_directive " Version_directive . t ) t let ( ) = F . seal t end type t let t : t typ = F . structure " yaml_token_s " let _type = F ( . field t " type " token_type_t ) token_type_t let data = F ( . field t " data " Data . t ) t let start_mark = F ( . field t " start_mark " Mark . t ) t let end_mark = F ( . field t " end_mark " Mark . t ) t let ( ) = F . seal t end module Event = struct module Stream_start = struct type t let t : t typ = F ( . structure " event_stream_start_s ) " let encoding = F ( . field t " encoding " encoding_t ) encoding_t let ( ) = F . seal t end module Document_start = struct module Tag_directives = struct type t let t : t typ = F ( . structure " event_tag_directives_s ) " let start = F ( . field t " start " ( ptr Tag_directive . t ) t ) t let _end = F ( . field t " end " ( ptr Tag_directive . t ) t ) t let ( ) = F . seal t end type t let t : t typ = F ( . structure " event_document_start_s ) " let version_directive = F ( . field t " version_directive " ( ptr_opt Version_directive . t ) t ) t let tag_directives = F ( . field t " tag_directives " Tag_directives . t ) t let implicit = F ( . field t " implicit " int ) int let ( ) = F . seal t end module Document_end = struct type t let t : t typ = F ( . structure " event_document_end_s ) " let implicit = F ( . field t " implicit " int ) int let ( ) = F . seal t end module Alias = struct type t let t : t typ = F ( . structure " event_alias_s ) " let anchor = F ( . field t " anchor " string_opt ) string_opt let ( ) = F . seal t end module Scalar = struct type t let t : t typ = F ( . structure " event_scalar_s ) " let anchor = F ( . field t " anchor " string_opt ) string_opt let tag = F ( . field t " tag " string_opt ) string_opt let value = F ( . field t " value " string ) string let length = F ( . field t " length " size_t ) size_t let plain_implicit = F ( . field t " plain_implicit " int ) int let quoted_implicit = F ( . field t " quoted_implicit " int ) int let style = F ( . field t " style " scalar_style_t ) scalar_style_t let ( ) = F . seal t end module Sequence_start = struct type t let t : t typ = F ( . structure " event_sequence_start_s ) " let anchor = F ( . field t " anchor " string_opt ) string_opt let tag = F ( . field t " tag " string_opt ) string_opt let implicit = F ( . field t " implicit " int ) int let style = F ( . field t " style " sequence_style_t ) sequence_style_t let ( ) = F . seal t end module Mapping_start = struct type t let t : t typ = F ( . structure " event_mapping_start_s ) " let anchor = F ( . field t " anchor " string_opt ) string_opt let tag = F ( . field t " tag " string_opt ) string_opt let implicit = F ( . field t " implicit " int ) int let style = F ( . field t " style " mapping_style_t ) mapping_style_t let ( ) = F . seal t end module Data = struct type t let t : t utyp = F . union " event_data_u " let stream_start = F ( . field t " stream_start " Stream_start . t ) t let document_start = F ( . field t " document_start " Document_start . t ) t let document_end = F ( . field t " document_end " Document_end . t ) t let alias = F ( . field t " alias " Alias . t ) t let scalar = F ( . field t " scalar " Scalar . t ) t let sequence_start = F ( . field t " sequence_start " Sequence_start . t ) t let mapping_start = F ( . field t " mapping_start " Mapping_start . t ) t let ( ) = F . seal t end type t let t : t typ = F . structure " yaml_event_s " let _type = F ( . field t " type " event_type_t ) event_type_t let data = F ( . field t " data " Data . t ) t let start_mark = F ( . field t " start_mark " Mark . t ) t let end_mark = F ( . field t " end_mark " Mark . t ) t let ( ) = F . seal t end module Parser = struct type t let t : t typ = F . structure " yaml_parser_s " let error = F ( . field t " error " error_t ) error_t let problem = F ( . field t " problem " string_opt ) string_opt let problem_offset = F ( . field t " problem_offset " size_t ) size_t let problem_value = F ( . field t " problem_value " int ) int let ( ) = F . seal t end module Emitter = struct type t let t : t typ = F . structure " yaml_emitter_s " let ( ) = F . seal t end end
type value = [ ` Null | ` Bool of bool | ` Float of float | ` String of string | ` A of value list | ` O of ( string * value ) value list ]
type yaml = [ ` Scalar of scalar | ` Alias of string | ` A of sequence | ` O of mapping ] s_anchor : string option ; s_tag : string option ; s_implicit : bool ; s_members : yaml list ; } m_anchor : string option ; m_tag : string option ; m_implicit : bool ; m_members : ( yaml * yaml ) yaml list ; } anchor : string option ; tag : string option ; value : string ; plain_implicit : bool ; quoted_implicit : bool ; style : scalar_style ; } [ ` Any | ` Plain | ` Single_quoted | ` Double_quoted | ` Literal | ` Folded ]
type version = [ ` V1_1 | ` V1_2 ] [ @@ deriving sexp ] sexp
type encoding = [ ` Any | ` Utf16be | ` Utf16le | ` Utf8 ] [ @@ deriving sexp ] sexp
type layout_style = [ ` Any | ` Block | ` Flow ] [ @@ deriving sexp ] sexp
module Stream = struct module Mark = struct type t = Yaml . Stream . Mark . t = { index : int ; line : int ; column : int } [ @@ deriving sexp ] sexp end module Event = struct type pos = Yaml . Stream . Event . pos = { start_mark : Mark . t ; end_mark : Mark . t ; } [ @@ deriving sexp ] sexp type t = Yaml . Stream . Event . t = | Stream_start of { encoding : encoding } | Document_start of { version : version option ; implicit : bool } | Document_end of { implicit : bool } | Mapping_start of { anchor : string option ; tag : string option ; implicit : bool ; style : layout_style ; } | Mapping_end | Stream_end | Scalar of scalar | Sequence_start of { anchor : string option ; tag : string option ; implicit : bool ; style : layout_style ; } | Sequence_end | Alias of { anchor : string } | Nothing [ @@ deriving sexp ] sexp end end
let license = " \ notice , this list of conditions and the following disclaimer . notice , this list of conditions and the following disclaimer in the documentation and / or other materials provided with the distribution . derived from this software without specific prior written permission . "
let polycat write_one streaming in_file out_file = let ic , fname = match in_file with | ` File s -> open_in s , s in let oc = match out_file with | ` File s -> open_out s in let finally ( ) = if oc != stdout then close_out_noerr oc ; if ic != stdin then close_in_noerr ic in try if streaming then Stream . iter ( write_one oc ) ( Yojson . Safe . stream_from_channel ~ fname ic ) else write_one oc ( Yojson . Safe . from_channel ~ fname ic ) ; finally ( ) ; true with e -> finally ( ) ; eprintf " Error :\ n " ; ( match e with | e -> ) ; false
let cat sort output_biniou std compact streaming in_file out_file = if not output_biniou then let write_one oc x = let x = if sort then Yojson . Safe . sort x else x in if compact then else output_char oc ' \ n ' in polycat write_one streaming in_file out_file else let write_one oc x = output_string oc ( Bi_io . string_of_tree ( Yojson_biniou . biniou_of_json x ) ) in polycat write_one streaming in_file out_file
let parse_cmdline ( ) = let out = ref None in let std = ref false in let compact = ref false in let streaming = ref true in let sort = ref false in let output_biniou = ref false in let options = [ " - o " , Arg . String ( fun s -> out := Some s ) , " < file > Output file " ; " - std " , Arg . Set std , " Convert tuples and variants into standard JSON , refuse to print NaN and infinities , require the root node to be either an object or an array . " ; " - c " , Arg . Set compact , " Compact output ( default : pretty - printed ) " ; " - s " , Arg . Set streaming , " Streaming mode : read and write a sequence of JSON values instead of just one ( default ) . " ; " - u " , Arg . Clear streaming , " A single JSON record is expected . ( no longer the default since 1 . 1 . 1 ) " ; " - sort " , Arg . Set sort , " Sort object fields ( default : preserve field order ) " ; " - ob " , Arg . Set output_biniou , " \ Experimental " ; " - version " , Arg . Unit ( fun ( ) -> print_endline Yojson . version ; exit 0 ) , " \ Print version of yojson and ydump and exit . " ] in let files = ref [ ] in let anon_fun s = files := s :: ! files in let msg = sprintf " \ % s license Sys . argv . ( 0 ) in Arg . parse options anon_fun msg ; let in_file = match List . rev ! files with | [ x ] -> ` File x | _ -> in let out_file = match ! out with | Some x -> ` File x in ! sort , ! output_biniou , ! std , ! compact , ! streaming , in_file , out_file
let ( ) = let sort , output_biniou , std , compact , streaming , in_file , out_file = parse_cmdline ( ) in let success = let rec aux cpt b = if cpt = 100 then b else let b = ( b && cat sort output_biniou std compact streaming in_file out_file ) in aux ( cpt + 1 ) b in aux 0 true in if success then exit 0 else exit 1
let populate_wallet yes_wallet_dir alias_pkh_pk_list = let pkh_filename = " public_key_hashs " in let pk_filename = " public_keys " in let sk_filename = " secret_keys " in if not ( Sys . file_exists yes_wallet_dir ) then Unix . mkdir yes_wallet_dir 0o750 ; Unix . chdir yes_wallet_dir ; if Sys . file_exists pkh_filename || Sys . file_exists pk_filename || Sys . file_exists sk_filename then ( Format . eprintf " Warning : cannot write wallet , at least one of the following files \ already exists : % s { /% s , % s , % s } . " @ yes_wallet_dir pkh_filename pk_filename sk_filename ; false ) else ( json_to_file ( pkh_list_json alias_pkh_pk_list ) pkh_filename ; json_to_file ( pk_list_json alias_pkh_pk_list ) pk_filename ; json_to_file ( sk_list_json alias_pkh_pk_list ) sk_filename ; true )
let usage ( ) = Format . printf " > create minimal in < yes_wallet_dir . " >@ ; Format . printf " creates a yes - wallet with the foundation baker keys in \ < yes_wallet_dir . " >@ ; Format . printf " > create from context < base_dir > in < yes_wallet_dir > [ % s ] . " @ active_bakers_only_opt_name ; Format . printf " creates a yes - wallet with all delegates in the head block of the \ context in < base_dir > and store it in < yes_wallet_dir . " >@ ; Format . printf " if % s is used the deactivated bakers are filtered out . " @ active_bakers_only_opt_name
let ( ) = let argv = Array . to_list Sys . argv in let ( options , argv ) = List . partition ( fun arg -> String . length arg > 0 && String . get arg 0 = ' ' ) - argv in let active_bakers_only = List . exists ( fun opt -> opt = active_bakers_only_opt_name ) options in let unknonw_options = List . filter ( fun opt -> opt <> active_bakers_only_opt_name ) options in if unknonw_options <> [ ] then Format . eprintf " Warning : unknown options % a . " @ ( Format . pp_print_list Format . pp_print_string ) unknonw_options ; match argv with | [ ] -> assert false | [ _ ] -> usage ( ) ; exit 0 | [ _ ; " create " ; " minimal " ; " in " ; yes_wallet_dir ] -> if active_bakers_only then Format . eprintf " Warning : option % s is ignored for create minimal . " @ active_bakers_only_opt_name ; if populate_wallet yes_wallet_dir Yes_wallet_lib . alias_pkh_pk_list then Format . printf " Created minimal wallet in % s . " @ yes_wallet_dir | [ _ ; " create " ; " from " ; " context " ; base_dir ; " in " ; yes_wallet_dir ] -> let alias_pkh_pk_list = Yes_wallet_lib . load_mainnet_bakers_public_keys base_dir active_bakers_only in if populate_wallet yes_wallet_dir alias_pkh_pk_list then Format . printf " Created wallet in % s . " @ yes_wallet_dir | _ -> Format . eprintf " Invalid command . Usage . " :@ ; usage ( ) ; exit 1
type protocol = Florence | Granada | Hangzhou | Ithaca | Alpha
let string_of_protocol = function | Florence -> " Florence " | Granada -> " Granada " | Hangzhou -> " Hangzhou " | Ithaca -> " Ithaca " | Alpha -> " Alpha "
let pp_protocol ppf protocol = Format . fprintf ppf " % s " ( string_of_protocol protocol )
let pkh_json ( alias , pkh , _pk ) = Ezjsonm . ( dict [ ( " name " , string alias ) ; ( " value " , string pkh ) ] )
let pk_json ( alias , _pkh , pk ) = Ezjsonm . ( dict [ ( " name " , string alias ) ; ( " value " , dict [ ( " locator " , string @@ " unencrypted " : ^ pk ) ; ( " key " , string pk ) ] ) ; ] )
let sk_of_pk ( pk_s : string ) : string = let open Tezos_crypto . Signature in let pk = Public_key . of_b58check_exn pk_s in let pk_b = Data_encoding . Binary . to_bytes_exn Public_key . encoding pk in let sk_b = Bytes . sub pk_b 0 33 in let sk = Data_encoding . Binary . of_bytes_exn Secret_key . encoding sk_b in let sk_s = Secret_key . to_b58check sk in sk_s
let sk_json ( alias , _pkh , pk ) = Ezjsonm . ( dict [ ( " name " , string alias ) ; ( " value " , string @@ " unencrypted " : ^ sk_of_pk pk ) ; ] )
let map_bind_to_json f list = Ezjsonm . list f list
let pkh_list_json list = map_bind_to_json pkh_json list
let pk_list_json list = map_bind_to_json pk_json list
let sk_list_json list = map_bind_to_json sk_json list
let json_to_file json file = let chan = open_out file in Ezjsonm . to_channel ~ minify : false chan json ; close_out chan
let alias_pkh_pk_list = [ ( " foundation1 " , " tz3RDC3Jdn4j15J7bBHZd29EUee9gVB1CxD9 " , " p2pk67wVncLFS1DQDm2gVR45sYCzQSXTtqn3bviNYXVCq6WRoqtxHXL " ) ; ( " foundation2 " , " tz3bvNMQ95vfAYtG8193ymshqjSvmxiCUuR5 " , " p2pk66n1NmhPDEkcf9sXEKe9kBoTwBoTYxke1hx16aTRVq8MoXuwNqo " ) ; ( " foundation3 " , " tz3RB4aoyjov4KEVRbuhvQ1CKJgBJMWhaeB8 " , " p2pk67NECc8vGK4eLbXGEgBZGhk53x1pCMbgnFEgLxZEMGDtzVcFQok " ) ; ( " foundation4 " , " tz3bTdwZinP8U1JmSweNzVKhmwafqWmFWRfk " , " p2pk6796esaR3dNr8jUx8S7xxZdRvpYSrhHMg6NagjwMRJHsERMiUKM " ) ; ( " foundation5 " , " tz3NExpXn9aPNZPorRE4SdjJ2RGrfbJgMAaV " , " p2pk66iTZwLmRPshQgUr2HE3RUzSFwAN5MNaBQ5rfduT1dGKXd25pNN " ) ; ( " foundation6 " , " tz3UoffC7FG7zfpmvmjUmUeAaHvzdcUvAj6r " , " p2pk65ffAqpYT6Et73DXdNqudthwmSNzNyzL3Wdn2EYuiiMwoPu6vFJ " ) ; ( " foundation7 " , " tz3WMqdzXqRWXwyvj5Hp2H7QEepaUuS7vd9K " , " p2pk67Cwb5Ke6oSmqeUbJxURXMe3coVnH9tqPiB2xD84CYhHbBKs4oM " ) ; ( " foundation8 " , " tz3VEZ4k6a4Wx42iyev6i2aVAptTRLEAivNN " , " p2pk67uapBxwkM1JNasGJ6J3rozzYELgrtcqxKZwZLjvsr4XcAr4FqC " ) ; ]
let get_delegates ( proto : protocol ) context ( header : Block_header . shell_header ) active_bakers_only = let open Lwt_tzresult_syntax in let level = header . Block_header . level in let predecessor_timestamp = header . timestamp in let timestamp = Time . Protocol . add predecessor_timestamp 10000L in let fitness = header . fitness in match proto with | Florence -> let open Tezos_protocol_009_PsFLoren . Protocol in let * ( ctxt , _ ) = let *! r = Alpha_context . prepare context ~ level ~ predecessor_timestamp ~ timestamp ~ fitness in Lwt . return @@ Environment . wrap_tzresult r in let * delegates = Alpha_context . Delegate . fold ctxt ~ init ( : ok [ ] ) ~ f ( : fun pkh acc -> let * pk = let *! r = Alpha_context . Roll . delegate_pubkey ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in let *? acc = acc in let * staking_balance = let *! r = Alpha_context . Delegate . staking_balance ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in if active_bakers_only then let * b = let *! r = Alpha_context . Delegate . deactivated ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in match b with | true -> return acc | false -> return ( ( pkh , pk , staking_balance ) :: acc ) else return ( ( pkh , pk , staking_balance ) :: acc ) ) in return @@ List . map ( fun ( pkh , pk , _ ) -> ( pkh , pk ) ) @@ List . sort ( fun ( _ , _ , x ) ( _ , _ , y ) -> Alpha_context . Tez . compare y x ) delegates | Granada -> let open Tezos_protocol_010_PtGRANAD . Protocol in let * ( ctxt , _ , _ ) = let *! r = Alpha_context . prepare context ~ level ~ predecessor_timestamp ~ timestamp ~ fitness in Lwt . return @@ Environment . wrap_tzresult r in let * delegates = Alpha_context . Delegate . fold ctxt ~ init ( : ok [ ] ) ~ f ( : fun pkh acc -> let * pk = let *! r = Alpha_context . Roll . delegate_pubkey ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in let *? acc = acc in let * staking_balance = let *! r = Alpha_context . Delegate . staking_balance ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in if active_bakers_only then let * b = let *! r = Alpha_context . Delegate . deactivated ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in match b with | true -> return acc | false -> return ( ( pkh , pk , staking_balance ) :: acc ) else return ( ( pkh , pk , staking_balance ) :: acc ) ) in return @@ List . map ( fun ( pkh , pk , _ ) -> ( pkh , pk ) ) @@ List . sort ( fun ( _ , _ , x ) ( _ , _ , y ) -> Alpha_context . Tez . compare y x ) delegates | Hangzhou -> let open Tezos_protocol_011_PtHangz2 . Protocol in let * ( ctxt , _ , _ ) = let *! r = Alpha_context . prepare context ~ level ~ predecessor_timestamp ~ timestamp ~ fitness in Lwt . return @@ Environment . wrap_tzresult r in let * delegates = Alpha_context . Delegate . fold ctxt ~ init ( : ok [ ] ) ~ f ( : fun pkh acc -> let * pk = let *! r = Alpha_context . Roll . delegate_pubkey ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in let *? acc = acc in let * staking_balance = let *! r = Alpha_context . Delegate . staking_balance ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in if active_bakers_only then let * b = let *! r = Alpha_context . Delegate . deactivated ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in match b with | true -> return acc | false -> return ( ( pkh , pk , staking_balance ) :: acc ) else return ( ( pkh , pk , staking_balance ) :: acc ) ) in return @@ List . map ( fun ( pkh , pk , _ ) -> ( pkh , pk ) ) @@ List . sort ( fun ( _ , _ , x ) ( _ , _ , y ) -> Alpha_context . Tez . compare y x ) delegates | Ithaca -> let open Tezos_protocol_012_Psithaca . Protocol in let * ( ctxt , _ , _ ) = let *! r = Alpha_context . prepare context ~ level ~ predecessor_timestamp ~ timestamp in Lwt . return @@ Environment . wrap_tzresult r in let * delegates = Alpha_context . Delegate . fold ctxt ~ order ` : Sorted ~ init ( : ok [ ] ) ~ f ( : fun pkh acc -> let * pk = let *! r = Alpha_context . Delegate . pubkey ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in let *? acc = acc in let * staking_balance = let *! r = Alpha_context . Delegate . staking_balance ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in if active_bakers_only then let * b = let *! r = Alpha_context . Delegate . deactivated ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in match b with | true -> return acc | false -> return ( ( pkh , pk , staking_balance ) :: acc ) else return ( ( pkh , pk , staking_balance ) :: acc ) ) in return @@ List . map ( fun ( pkh , pk , _ ) -> ( pkh , pk ) ) @@ List . sort ( fun ( _ , _ , x ) ( _ , _ , y ) -> Alpha_context . Tez . compare y x ) delegates | Alpha -> let open Tezos_protocol_alpha . Protocol in let * ( ctxt , _ , _ ) = let *! r = Alpha_context . prepare context ~ level ~ predecessor_timestamp ~ timestamp in Lwt . return @@ Environment . wrap_tzresult r in let * delegates = Alpha_context . Delegate . fold ctxt ~ order ` : Sorted ~ init ( : ok [ ] ) ~ f ( : fun pkh acc -> let * pk = let *! r = Alpha_context . Delegate . pubkey ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in let *? acc = acc in let * staking_balance = let *! r = Alpha_context . Delegate . staking_balance ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in if active_bakers_only then let * b = let *! r = Alpha_context . Delegate . deactivated ctxt pkh in Lwt . return @@ Environment . wrap_tzresult r in match b with | true -> return acc | false -> return ( ( pkh , pk , staking_balance ) :: acc ) else return ( ( pkh , pk , staking_balance ) :: acc ) ) in return @@ List . map ( fun ( pkh , pk , _ ) -> ( pkh , pk ) ) @@ List . sort ( fun ( _ , _ , x ) ( _ , _ , y ) -> Alpha_context . Tez . compare y x ) delegates
let protocol_of_hash protocol_hash = if Protocol_hash . equal protocol_hash Tezos_protocol_009_PsFLoren . Protocol . hash then Some Florence else if Protocol_hash . equal protocol_hash Tezos_protocol_010_PtGRANAD . Protocol . hash then Some Granada else if Protocol_hash . equal protocol_hash Tezos_protocol_011_PtHangz2 . Protocol . hash then Some Hangzhou else if Protocol_hash . equal protocol_hash Tezos_protocol_012_Psithaca . Protocol . hash then Some Ithaca else if Protocol_hash . equal protocol_hash Tezos_protocol_alpha . Protocol . hash then Some Alpha else None
let load_mainnet_bakers_public_keys base_dir active_bakers_only = let open Lwt_tzresult_syntax in let open Tezos_store in let mainnet_genesis = { Genesis . time = Time . Protocol . of_notation_exn " 2018 - 06 - 30T16 : 07 : 32Z " ; block = Block_hash . of_b58check_exn " BLockGenesisGenesisGenesisGenesisGenesisf79b5d1CoW2 " ; protocol = Protocol_hash . of_b58check_exn " Ps9mPmXaRzmzk35gbAYNCAw6UXdE2qoABTHbN2oEEc1qM7CwT9P " ; } in let * store = Tezos_store . Store . init ~ store_dir ( : Filename . concat base_dir " store " ) ~ context_dir ( : Filename . concat base_dir " context " ) ~ allow_testchains : true ~ readonly : true mainnet_genesis in let main_chain_store = Store . main_chain_store store in let *! block = Tezos_store . Store . Chain . current_head main_chain_store in Format . printf " Head block found and loaded ( % a ) . " @ Block_hash . pp ( Tezos_store . Store . Block . hash block ) ; let header = Store . Block . header block in let *! context = let *! r = Store . Block . context_exn main_chain_store block in Lwt . return @@ Tezos_shell_context . Shell_context . wrap_disk_context r in let *! protocol_hash = Store . Block . protocol_hash_exn main_chain_store block in let header = header . shell in let * delegates = match protocol_of_hash protocol_hash with | None -> Error_monad . failwith " unknown protocol hash " | Some protocol -> Format . printf " Protocol % a detected . " @ pp_protocol protocol ; get_delegates protocol context header active_bakers_only in let *! ( ) = Tezos_store . Store . close_store store in return @@ List . mapi ( fun i ( pkh , pk ) -> let pkh = Signature . Public_key_hash . to_b58check pkh in let pk = Signature . Public_key . to_b58check pk in let alias = List . find_map ( fun ( alias , pkh ' , _ ) -> if String . equal pkh ' pkh then Some alias else None ) alias_pkh_pk_list in let alias = Option . value ~ default ( : Format . asprintf " baker_ % d " i ) alias in ( alias , pkh , pk ) ) delegates
let load_mainnet_bakers_public_keys base_dir active_bakers_only = match Lwt_main . run ( load_mainnet_bakers_public_keys base_dir active_bakers_only ) with | Ok alias_pkh_pk_list -> alias_pkh_pk_list | Error trace -> Format . eprintf " error . :@% a . " @ Error_monad . pp_print_trace trace ; exit 1
type t = { month_count : int }
let equal ( x : t ) ( y : t ) = x . month_count = y . month_count
let lt ( x : t ) ( y : t ) = x . month_count < y . month_count
let le ( x : t ) ( y : t ) = x . month_count <= y . month_count
let gt ( x : t ) ( y : t ) = x . month_count > y . month_count
let ge ( x : t ) ( y : t ) = x . month_count >= y . month_count
let compare ( x : t ) ( y : t ) = compare x . month_count y . month_count
let month_count_of_ym ~ year ~ month = ( year * 12 ) + ( month - 1 )
let ym_of_month_count month_count = if month_count >= 0 then ( month_count / 12 , ( month_count mod 12 ) + 1 ) else ( ( month_count - 11 ) / 12 , ( ( ( month_count mod 12 ) + 12 ) mod 12 ) + 1 )
type error = [ ` Does_not_exist | ` Invalid_year of int | ` Invalid_month of int ]
let make ~ year ~ month : ( t , error ) result = if year < Constants . min_year || Constants . max_year < year then Error ( ` Invalid_year year ) else if month < 1 || 12 < month then Error ( ` Invalid_month month ) else Ok { month_count = month_count_of_ym ~ year ~ month }
let make_exn ~ year ~ month : t = match make ~ year ~ month with Error e -> raise ( Error_exn e ) | Ok x -> x
let sub_month_count ( t : t ) n : t = { month_count = t . month_count - n }
let sub ( ? years = 0 ) ( ? months = 0 ) t : t = sub_month_count t ( ( years * 12 ) + months )
let add_month_count ( t : t ) n : t = { month_count = t . month_count + n }
let add ( ? years = 0 ) ( ? months = 0 ) t : t = add_month_count t ( ( years * 12 ) + months )
let diff_months t1 t2 = t1 . month_count - t2 . month_count
let year_month ( t : t ) : int * int = ym_of_month_count t . month_count
let year ( t : t ) : int = fst @@ year_month t
let month ( t : t ) : int = snd @@ year_month t
module Alco = struct let lt_case0 ( ) = Alcotest . ( check bool ) " less than " true Timedesc . Ym . ( lt ( make_exn ~ year : 2000 ~ month : 1 ) ( make_exn ~ year : 2000 ~ month : 2 ) ) let lt_case1 ( ) = Alcotest . ( check bool ) " less than " false Timedesc . Ym . ( lt ( make_exn ~ year : 2000 ~ month : 1 ) ( make_exn ~ year : 2000 ~ month : 1 ) ) let lt_case2 ( ) = Alcotest . ( check bool ) " less than " false Timedesc . Ym . ( lt ( make_exn ~ year : 2000 ~ month : 2 ) ( make_exn ~ year : 2000 ~ month : 1 ) ) let le_case0 ( ) = Alcotest . ( check bool ) " less than or equal to " true Timedesc . Ym . ( le ( make_exn ~ year : 2000 ~ month : 1 ) ( make_exn ~ year : 2000 ~ month : 2 ) ) let le_case1 ( ) = Alcotest . ( check bool ) " less than or equal to " true Timedesc . Ym . ( le ( make_exn ~ year : 2000 ~ month : 1 ) ( make_exn ~ year : 2000 ~ month : 1 ) ) let le_case2 ( ) = Alcotest . ( check bool ) " less than or equal to " false Timedesc . Ym . ( le ( make_exn ~ year : 2000 ~ month : 2 ) ( make_exn ~ year : 2000 ~ month : 1 ) ) let gt_case0 ( ) = Alcotest . ( check bool ) " greater than or equal to " true Timedesc . Ym . ( gt ( make_exn ~ year : 2000 ~ month : 2 ) ( make_exn ~ year : 2000 ~ month : 1 ) ) let gt_case1 ( ) = Alcotest . ( check bool ) " greater than or equal to " false Timedesc . Ym . ( gt ( make_exn ~ year : 2000 ~ month : 1 ) ( make_exn ~ year : 2000 ~ month : 1 ) ) let gt_case2 ( ) = Alcotest . ( check bool ) " greater than or equal to " false Timedesc . Ym . ( gt ( make_exn ~ year : 2000 ~ month : 1 ) ( make_exn ~ year : 2000 ~ month : 2 ) ) let ge_case0 ( ) = Alcotest . ( check bool ) " greater than or equal to " true Timedesc . Ym . ( ge ( make_exn ~ year : 2000 ~ month : 2 ) ( make_exn ~ year : 2000 ~ month : 1 ) ) let ge_case1 ( ) = Alcotest . ( check bool ) " greater than or equal to " true Timedesc . Ym . ( ge ( make_exn ~ year : 2000 ~ month : 1 ) ( make_exn ~ year : 2000 ~ month : 1 ) ) let ge_case2 ( ) = Alcotest . ( check bool ) " greater than or equal to " false Timedesc . Ym . ( ge ( make_exn ~ year : 2000 ~ month : 1 ) ( make_exn ~ year : 2000 ~ month : 2 ) ) let of_iso8601_case0 ( ) = Alcotest . ( check ym_testable ) " same date " ( Timedesc . Ym . of_iso8601_exn " 1977 - 06 " ) ( Timedesc . Ym . make_exn ~ year : 1977 ~ month : 6 ) let wrap_around_case0 ( ) = let y = Timedesc . Ym . add ~ months : 1 ( Timedesc . Ym . make_exn ~ year : 1977 ~ month : 12 ) in Alcotest . ( check ym_testable ) " same date " ( Timedesc . Ym . make_exn ~ year : 1978 ~ month : 1 ) y let wrap_around_case1 ( ) = let y = Timedesc . Ym . add ~ months : 13 ( Timedesc . Ym . make_exn ~ year : 1977 ~ month : 12 ) in Alcotest . ( check ym_testable ) " same date " ( Timedesc . Ym . make_exn ~ year : 1979 ~ month : 1 ) y let wrap_around_case2 ( ) = let y = Timedesc . Ym . sub ~ months : 1 ( Timedesc . Ym . make_exn ~ year : 1977 ~ month : 1 ) in Alcotest . ( check ym_testable ) " same date " ( Timedesc . Ym . make_exn ~ year : 1976 ~ month : 12 ) y let wrap_around_case3 ( ) = let y = Timedesc . Ym . sub ~ months : 13 ( Timedesc . Ym . make_exn ~ year : 1977 ~ month : 1 ) in Alcotest . ( check ym_testable ) " same date " ( Timedesc . Ym . make_exn ~ year : 1975 ~ month : 12 ) y let suite = [ Alcotest . test_case " lt_case0 " ` Quick lt_case0 ; Alcotest . test_case " lt_case1 " ` Quick lt_case1 ; Alcotest . test_case " lt_case2 " ` Quick lt_case2 ; Alcotest . test_case " le_case0 " ` Quick le_case0 ; Alcotest . test_case " le_case1 " ` Quick le_case1 ; Alcotest . test_case " le_case2 " ` Quick le_case2 ; Alcotest . test_case " gt_case0 " ` Quick gt_case0 ; Alcotest . test_case " gt_case1 " ` Quick gt_case1 ; Alcotest . test_case " gt_case2 " ` Quick gt_case2 ; Alcotest . test_case " ge_case0 " ` Quick ge_case0 ; Alcotest . test_case " ge_case1 " ` Quick ge_case1 ; Alcotest . test_case " ge_case2 " ` Quick ge_case2 ; Alcotest . test_case " of_iso8601_case0 " ` Quick of_iso8601_case0 ; Alcotest . test_case " wrap_around_case0 " ` Quick wrap_around_case0 ; Alcotest . test_case " wrap_around_case1 " ` Quick wrap_around_case1 ; Alcotest . test_case " wrap_around_case2 " ` Quick wrap_around_case2 ; Alcotest . test_case " wrap_around_case3 " ` Quick wrap_around_case3 ; ] end
module Qc = struct let to_iso8601_of_iso8601 = QCheck . Test . make ~ count : 100_000 ~ name " : to_iso8601_of_iso8601 " ym ( fun ( year , month ) -> let d = Timedesc . Ym . make_exn ~ year ~ month in let d ' = d |> Timedesc . Ym . to_iso8601 |> Timedesc . Ym . of_iso8601 |> CCResult . get_exn in Timedesc . Ym . equal d d ' ) let add_identity = QCheck . Test . make ~ count : 100_000 ~ name " : add_identity " ym ( fun ( year , month ) -> let x = Timedesc . Ym . make_exn ~ year ~ month in Timedesc . Ym . ( equal ( add ~ months : 0 x ) x ) ) let sub_identity = QCheck . Test . make ~ count : 100_000 ~ name " : sub_identity " ym ( fun ( year , month ) -> let x = Timedesc . Ym . make_exn ~ year ~ month in Timedesc . Ym . ( equal ( sub ~ months : 0 x ) x ) ) let add_sub = QCheck . Test . make ~ count : 100_000 ~ name " : add_sub " QCheck . ( pair ym small_int ) ( fun ( ( year , month ) , y ) -> let x = Timedesc . Ym . make_exn ~ year ~ month in Timedesc . Ym . ( equal x ( sub ~ months : y ( add ~ months : y x ) ) ) ) let sub_add = QCheck . Test . make ~ count : 100_000 ~ name " : sub_add " QCheck . ( pair ym small_int ) ( fun ( ( year , month ) , y ) -> let x = Timedesc . Ym . make_exn ~ year ~ month in Timedesc . Ym . ( equal x ( add ~ months : y ( sub ~ months : y x ) ) ) ) let add_diff = QCheck . Test . make ~ count : 100_000 ~ name " : add_diff " QCheck . ( pair ym iso_week ) ( fun ( ( year_x , month_x ) , ( year_y , month_y ) ) -> let x = Timedesc . Ym . make_exn ~ year : year_x ~ month : month_x in let y = Timedesc . Ym . make_exn ~ year : year_y ~ month : month_y in let diff = Timedesc . Ym . diff_months x y in Timedesc . Ym . ( equal x ( add ~ months : diff y ) ) ) let sub_diff = QCheck . Test . make ~ count : 100_000 ~ name " : sub_diff " QCheck . ( pair ym iso_week ) ( fun ( ( year_x , month_x ) , ( year_y , month_y ) ) -> let x = Timedesc . Ym . make_exn ~ year : year_x ~ month : month_x in let y = Timedesc . Ym . make_exn ~ year : year_y ~ month : month_y in let diff = Timedesc . Ym . diff_months x y in Timedesc . Ym . ( equal y ( sub ~ months : diff x ) ) ) let suite = [ to_iso8601_of_iso8601 ; add_identity ; sub_identity ; add_sub ; sub_add ; add_diff ; sub_diff ; ] end
module Pretty = struct end
module Util = struct # include " util . ml " end end
module Util = struct # include " util . ml " end end
module Raw = struct end
let rec biniou_of_json = function ` Null -> ` Unit | ` Bool b -> ` Bool b | ` Int i -> ` Svint i | ` Intlit i -> failwith " Cannot convert big int to biniou " | ` Float f -> ` Float64 f | ` String s -> ` String s | ` Assoc l -> let a = Array . map ( fun ( s , x ) -> ( Some s , Bi_io . hash_name s , biniou_of_json x ) ) ( Array . of_list l ) in ` Record a | ` List l -> ( match l with [ ] -> ` Array None | l -> let a = Array . map biniou_of_json ( Array . of_list l ) in let tag = Bi_io . tag_of_tree a . ( 0 ) in try for i = 1 to Array . length a - 1 do if Bi_io . tag_of_tree a . ( i ) <> tag then raise Exit done ; ` Array ( Some ( tag , a ) ) with Exit -> failwith " Cannot convert heterogenous array to biniou " ) | ` Tuple l -> ` Tuple ( Array . map biniou_of_json ( Array . of_list l ) ) | ` Variant ( s , o ) -> let o = match o with None -> None | Some x -> Some ( biniou_of_json x ) in ` Variant ( Some s , Bi_io . hash_name s , o )
let rec json_of_biniou ( x : Bi_io . tree ) = match x with ` Unit -> ` Null | ` Bool b -> ` Bool b | ` Int8 _ -> failwith " Cannot convert int8 to JSON " | ` Int16 _ -> failwith " Cannot convert int16 to JSON " | ` Int32 _ -> failwith " Cannot convert int32 to JSON " | ` Int64 _ -> failwith " Cannot convert int64 to JSON " | ` Float32 f | ` Float64 f -> ` Float f | ` Uvint i -> failwith " Cannot convert uvint to JSON " | ` Svint i -> ` Int i | ` String s -> ` String s | ` Array None -> ` List [ ] | ` Array ( Some ( _ , a ) ) -> ` List ( Array . to_list ( Array . map json_of_biniou a ) ) | ` Tuple a -> ` Tuple ( Array . to_list ( Array . map json_of_biniou a ) ) | ` Record a -> ` Assoc ( Array . to_list ( Array . map ( function ( Some s , _ , x ) -> ( s , json_of_biniou x ) | ( None , _ , _ ) -> failwith " Cannot convert hashed field name to JSON " ) a ) ) | ` Num_variant _ -> failwith " Cannot convert num_variant to JSON " | ` Variant ( Some s , _ , Some x ) -> ` Variant ( s , Some ( json_of_biniou x ) ) | ` Variant ( Some s , _ , None ) -> ` Variant ( s , None ) | ` Variant ( None , _ , _ ) -> failwith " Cannot convert hashed variant name to JSON " | ` Table None -> ` List [ ] | ` Table ( Some ( header , rows ) ) -> ` List ( Array . to_list ( Array . map ( json_of_row header ) rows ) ) | ` Shared _ -> failwith " Cannot convert shared node to JSON " let n = Array . length header in if Array . length a <> n then failwith " Malformed biniou table " ; let l = ref [ ] in for i = n - 1 downto 0 do let o , _ , _ = header . ( i ) in let x = a . ( i ) in match o with None -> failwith " Cannot convert hashed field name to JSON " | Some s -> l := ( s , json_of_biniou x ) :: ! l done ; ` Assoc ! l
let test = let open Yojson_unittest_types in let all_basic_types = { field01 = 1 . 2000001 ; field02 = 1 . 2 ; field03 = 0xEFFFFFFFl ; field04 = 0xEBABABABABABABABL ; field05 = 0x7FFFFFFFl ; field06 = 0x7BABABABABABABABL ; field07 = 0xEFFFFFFFl ; field08 = 0xEBABABABABABABABL ; field09 = 0xEFFFFFFFl ; field10 = 0xEBABABABABABABABL ; field13 = true ; field14 = " This is a test " \ string " " ; \ repeated01 = [ 1 . 2000001 ; ] ; repeated02 = [ 1 . 2 ; ] ; repeated03 = [ 0xEFFFFFFFl ; ] ; repeated04 = [ 0xEBABABABABABABABL ; ] ; repeated05 = [ 0x7FFFFFFFl ; ] ; repeated06 = [ 0x7BABABABABABABABL ; ] ; repeated07 = [ 0xEFFFFFFFl ; ] ; repeated08 = [ 0xEBABABABABABABABL ; ] ; repeated09 = [ 0xEFFFFFFFl ; ] ; repeated10 = [ 0xEBABABABABABABABL ; ] ; repeated13 = [ true ; ] ; repeated14 = [ " This is a test " \ string ] " " ; ; \ } in let small_message = { sm_string = " This " \ IS " \ a small string " ; } in let test_enum0 = Value0 in let test_enum1 = Value1 in let test_enum2 = Value_two in let single_one_of_string : single_one_of = String_value " This is the single one " \ string " " \ in let single_one_of_int : single_one_of = Int_value 0xEFABABABl in let single_one_of_enum : single_one_of = Enum_value test_enum0 in let single_one_of_small_message : single_one_of = Small_message small_message in let single_one_of_recursive : single_one_of = Recursive_value single_one_of_small_message in { all_basic_types = Some all_basic_types ; test_enum0 ; test_enum1 ; test_enum2 ; single_one_of_string = Some single_one_of_string ; single_one_of_int = Some single_one_of_int ; single_one_of_enum = Some single_one_of_enum ; single_one_of_small_message = Some single_one_of_small_message ; single_one_of_recursive = Some single_one_of_recursive ; repeated_enum = [ test_enum0 ; test_enum1 ; test_enum2 ] test_enum2 ; }
let ( ) = let json_str = Yojson_unittest_yojson . encode_test test |> Yojson . Basic . to_string in print_endline json_str ; let test ' = json_str |> Yojson . Basic . from_string |> Yojson_unittest_yojson . decode_test in assert ( asserttest = test ' ) test ' ; ( )
let ( ) = print_endline " \ nConsistency tests . . . Ok "
let ( ) = let ic = let filename = " yojson . data " in open_in filename in let buffer_len = 1024 * 1024 in let buffer = Bytes . create buffer_len in let buffer_len = match input ic buffer 0 buffer_len with | i when i < buffer_len -> i | _ -> assert ( assertfalse ) assertfalse in let test ' = Bytes . sub_string buffer 0 buffer_len |> Yojson . Basic . from_string |> Yojson_unittest_yojson . decode_test in let open Yojson_unittest_types in assert ( asserttest ' . all_basic_types = test . all_basic_types ) all_basic_types ; assert ( asserttest ' . test_enum0 = test . test_enum0 ) test_enum0 ; assert ( asserttest ' . test_enum1 = test . test_enum1 ) test_enum1 ; assert ( asserttest ' . test_enum2 = test . test_enum2 ) test_enum2 ; assert ( asserttest ' . single_one_of_string = test . single_one_of_string ) single_one_of_string ; assert ( asserttest ' . single_one_of_int = test . single_one_of_int ) single_one_of_int ; assert ( asserttest ' . single_one_of_enum = test . single_one_of_enum ) single_one_of_enum ; assert ( asserttest ' . single_one_of_small_message = test . single_one_of_small_message ) single_one_of_small_message ; assert ( asserttest ' . single_one_of_recursive = test . single_one_of_recursive ) single_one_of_recursive ; print_endline " \ nConformance tests . . . Ok " ; ( )
type bbox = { xmin : float ; ymin : float ; xmax : float ; ymax : float ; confidence : float ; class_index : int ; class_confidence : float }
let iou b1 b2 = let b1_area = ( b1 . xmax . - b1 . xmin . + 1 . ) . * ( b1 . ymax . - b1 . ymin . + 1 . ) in let b2_area = ( b2 . xmax . - b2 . xmin . + 1 . ) . * ( b2 . ymax . - b2 . ymin . + 1 . ) in let i_xmin = Float . max b1 . xmin b2 . xmin in let i_xmax = Float . min b1 . xmax b2 . xmax in let i_ymin = Float . max b1 . ymin b2 . ymin in let i_ymax = Float . min b1 . ymax b2 . ymax in let i_area = Float . max 0 . ( i_xmax . - i_xmin . + 1 . ) . * Float . max 0 . ( i_ymax . - i_ymin . + 1 . ) in i_area . / ( b1_area . + b2_area . - i_area )
let colors = [ | [ | 0 . 5 ; 0 . 0 ; 0 . 5 ] | ; [ | 0 . 0 ; 0 . 5 ; 0 . 5 ] | ; [ | 0 . 5 ; 0 . 5 ; 0 . 0 ] | ; [ | 0 . 7 ; 0 . 3 ; 0 . 0 ] | ; [ | 0 . 7 ; 0 . 0 ; 0 . 3 ] | ; [ | 0 . 0 ; 0 . 7 ; 0 . 3 ] | ; [ | 0 . 3 ; 0 . 7 ; 0 . 0 ] | ; [ | 0 . 3 ; 0 . 0 ; 0 . 7 ] | ; [ | 0 . 0 ; 0 . 3 ; 0 . 7 ] | ] |
let report predictions ~ image ~ width ~ height = Tensor . print_shape ~ name " : predictions " predictions ; let bboxes = List . init ( Tensor . shape2_exn predictions |> fst ) ~ f ( : fun index -> let predictions = Tensor . get predictions index |> Tensor . to_float1_exn in let confidence = predictions . ( 4 ) in if Float . ( > ) confidence confidence_threshold then ( let xmin = predictions . ( 0 ) . - ( predictions . ( 2 ) . / 2 . ) in let ymin = predictions . ( 1 ) . - ( predictions . ( 3 ) . / 2 . ) in let xmax = predictions . ( 0 ) . + ( predictions . ( 2 ) . / 2 . ) in let ymax = predictions . ( 1 ) . + ( predictions . ( 3 ) . / 2 . ) in let best_class_index = Array . foldi predictions ~ init : 5 ~ f ( : fun index max_index v -> if index > 5 && Float . ( < ) predictions . ( max_index ) v then index else max_index ) in let class_confidence = predictions . ( best_class_index ) in let class_index = best_class_index - 5 in if Float . ( > ) class_confidence 0 . then Some { confidence ; xmin ; ymin ; xmax ; ymax ; class_index ; class_confidence } else None ) else None ) |> List . filter_opt in let bboxes = List . map bboxes ~ f ( : fun bbox -> bbox . class_index , ( bbox . confidence , bbox ) ) |> Map . of_alist_multi ( module Int ) |> Map . to_alist |> List . concat_map ~ f ( : fun ( _ , bboxes ) -> let bboxes = List . sort bboxes ~ compare : Caml . compare |> List . rev_map ~ f : snd in List . fold bboxes ~ init [ ] : ~ f ( : fun acc_bboxes bbox -> let drop = List . exists acc_bboxes ~ f ( : fun b -> Float . ( > ) ( iou b bbox ) nms_threshold ) in if drop then acc_bboxes else bbox :: acc_bboxes ) ) in let image = Tensor . ( to_type image ~ type_ ( : T Float ) / f 255 . ) in let _ , _ , initial_height , initial_width = Tensor . shape4_exn image in let resize_and_clamp v ~ initial_max ~ max = Int . of_float ( v . * Float . of_int initial_max . / Float . of_int max ) |> Int . max 0 |> Int . min ( initial_max - 1 ) in List . iter bboxes ~ f ( : fun b -> let xmin = resize_and_clamp b . xmin ~ initial_max : initial_width ~ max : width in let xmax = resize_and_clamp b . xmax ~ initial_max : initial_width ~ max : width in let ymin = resize_and_clamp b . ymin ~ initial_max : initial_height ~ max : height in let ymax = resize_and_clamp b . ymax ~ initial_max : initial_height ~ max : height in let color = colors . ( b . class_index % Array . length colors ) in let color = Tensor . ( of_float1 color |> reshape ~ shape [ : 1 ; 3 ; 1 ; 1 ] ) in let draw_rect xmin xmax ymin ymax = Tensor . narrow image ~ dim : 3 ~ start : xmin ~ length ( : xmax - xmin ) |> Tensor . narrow ~ dim : 2 ~ start : ymin ~ length ( : ymax - ymin ) |> Tensor . copy_ ~ src : color in draw_rect xmin xmax ymin ( Int . min ( ymin + 2 ) ymax ) ; draw_rect xmin xmax ( Int . max ymin ( ymax - 2 ) ) ymax ; draw_rect ( Int . max xmin ( xmax - 2 ) ) xmax ymin ymax ; draw_rect xmin ( Int . min ( xmin + 2 ) xmax ) ymin ymax ; Stdio . printf " % s . % 2f . % 2f ( % d % d % d % d ) \ n " %! classes . ( b . class_index ) b . confidence b . class_confidence xmin xmax ymin ymax ) ; Image . write_image Tensor . ( image * f 255 . ) ~ filename " : output . jpg "
let ( ) = let module Sys = Caml . Sys in if Array . length Sys . argv <> 3 then Printf . failwithf " usage : % s yolo - v3 . ot input . png " Sys . argv . ( 0 ) ( ) ; let vs = Var_store . create ~ name " : rn " ~ device : Cpu ( ) in let darknet = Darknet . parse_config config_filename in let model = Darknet . build_model vs darknet in Stdio . printf " Loading weights from % s \ n " %! Sys . argv . ( 1 ) ; Serialize . load_multi_ ~ named_tensors ( : Var_store . all_vars vs ) ~ filename : Sys . argv . ( 1 ) ; let width , height = Darknet . width darknet , Darknet . height darknet in let image = Image . load_image Sys . argv . ( 2 ) |> Or_error . ok_exn in let resized_image = Image . resize image ~ width ~ height in let resized_image = Tensor . ( to_type resized_image ~ type_ ( : T Float ) / f 255 . ) in let predictions = Layer . forward_ model resized_image ~ is_training : false in Tensor . squeeze predictions |> report ~ image ~ width ~ height
type ( ' a , ' b ) ' b exec = ( ' a , unit , string , ' b ) ' b format4 -> ' a