text
stringlengths
12
786k
let get_history proxy ~ typ ~ timespan ~ resolution = let timespan = Int32 . of_int timespan in let resolution = Int32 . of_int resolution in let % lwt data = OBus_method . call m_GetHistory proxy ( typ , timespan , resolution ) in let data = List . map ( fun ( x1 , x2 , x3 ) -> ( Int32 . to_int x1 , x2 , Int32 . to_int x3 ) ) data in return data
let get_statistics proxy ~ typ = OBus_method . call m_GetStatistics proxy typ
let native_path proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_NativePath proxy
let vendor proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_Vendor proxy
let model proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_Model proxy
let serial proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_Serial proxy
let update_time proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_UpdateTime proxy
let typ proxy = OBus_property . map_r ( function | 0l -> ` Unknown | 1l -> ` Line_power | 2l -> ` Battery | 3l -> ` Ups | 4l -> ` Monitor | 5l -> ` Mouse | 6l -> ` Keyboard | 7l -> ` Pda | 8l -> ` Phone | n -> Printf . ksprintf failwith " invalid device type : % ld " n ) ( OBus_property . make ~ monitor : UPower_monitor . monitor p_Type proxy )
let power_supply proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_PowerSupply proxy
let has_history proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_HasHistory proxy
let has_statistics proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_HasStatistics proxy
let online proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_Online proxy
let energy proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_Energy proxy
let energy_empty proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_EnergyEmpty proxy
let energy_full proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_EnergyFull proxy
let energy_full_design proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_EnergyFullDesign proxy
let energy_rate proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_EnergyRate proxy
let voltage proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_Voltage proxy
let time_to_empty proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_TimeToEmpty proxy
let time_to_full proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_TimeToFull proxy
let percentage proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_Percentage proxy
let is_present proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_IsPresent proxy
let state proxy = OBus_property . map_r ( function | 0l -> ` Unknown | 1l -> ` Charging | 2l -> ` Discharging | 3l -> ` Empty | 4l -> ` Fully_charged | 5l -> ` Pending_charge | 6l -> ` Pending_discharge | n -> Printf . ksprintf failwith " invalid device state : % ld " n ) ( OBus_property . make ~ monitor : UPower_monitor . monitor p_State proxy )
let is_rechargeable proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_IsRechargeable proxy
let capacity proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_Capacity proxy
let technology proxy = OBus_property . map_r ( function | 0l -> ` Unknown | 1l -> ` Lithium_ion | 2l -> ` Lithium_polymer | 3l -> ` Lithium_iron_phosphate | 4l -> ` Lead_acid | 5l -> ` Nickel_cadmium | 6l -> ` Nickel_metal_hydride | n -> Printf . ksprintf failwith " invalid technolofy number : % ld " n ) ( OBus_property . make ~ monitor : UPower_monitor . monitor p_Technology proxy )
let recall_notice proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_RecallNotice proxy
let recall_vendor proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_RecallVendor proxy
let recall_url proxy = OBus_property . make ~ monitor : UPower_monitor . monitor p_RecallUrl proxy
let properties proxy = OBus_property . group ~ monitor : UPower_monitor . monitor proxy interface
type latency = [ ` Cpu_dma | ` Network ]
let string_of_latency = function | ` Cpu_dma -> " cpu_dma " | ` Network -> " network "
let latency_of_string = function | " cpu_dma " -> ` Cpu_dma | " network " -> ` Network | latency -> Printf . ksprintf failwith " unknown latency type ( % S ) " latency
type latency_request = { lr_cookie : cookie ; lr_uid : int ; lr_pid : int ; lr_exec : string ; lr_timespec : int64 ; lr_persistent : bool ; lr_typ : latency ; lr_reserved : string ; lr_value : int ; }
let proxy daemon = OBus_proxy . make ( UPower . to_peer daemon ) [ " org " ; " freedesktop " ; " UPower " ; " Policy " ]
let set_minimum_latency daemon ~ latency ~ value = OBus_method . call m_SetMinimumLatency ( proxy daemon ) ( string_of_latency latency , Int32 . of_int value )
let request_latency daemon ~ latency ~ value ~ persistent = let value = Int32 . of_int value in let % lwt cookie = OBus_method . call m_RequestLatency ( proxy daemon ) ( string_of_latency latency , value , persistent ) in let cookie = Int32 . to_int cookie in return cookie
let cancel_request daemon ~ latency ~ cookie = let cookie = Int32 . of_int cookie in OBus_method . call m_CancelRequest ( proxy daemon ) ( string_of_latency latency , cookie )
let get_latency daemon ~ latency = let % lwt value = OBus_method . call m_GetLatency ( proxy daemon ) ( string_of_latency latency ) in let value = Int32 . to_int value in return value
let latency_changed daemon = OBus_signal . map ( fun ( latency , value ) -> ( latency_of_string latency , Int32 . to_int value ) ) ( OBus_signal . make s_LatencyChanged ( proxy daemon ) )
let get_latency_requests daemon = let % lwt requests = OBus_method . call m_GetLatencyRequests ( proxy daemon ) ( ) in return ( List . map ( fun ( cookie , uid , pid , exec , timespec , persistent , typ , reserved , value ) -> { lr_cookie = Int32 . to_int cookie ; lr_uid = Int32 . to_int uid ; lr_pid = Int32 . to_int pid ; lr_exec = exec ; lr_timespec = timespec ; lr_persistent = persistent ; lr_typ = latency_of_string typ ; lr_reserved = reserved ; lr_value = Int32 . to_int value ; } ) requests )
let requests_changed daemon = OBus_signal . make s_RequestsChanged ( proxy daemon )
type data = { data_is_userspace : bool ; data_id : int ; data_value : float ; data_cmdline : string option ; data_details : string ; }
let proxy daemon = OBus_proxy . make ( UPower . to_peer daemon ) [ " org " ; " freedesktop " ; " UPower " ; " Wakeups " ]
let has_capability daemon = OBus_property . make p_HasCapability ( proxy daemon )
let get_total daemon = let % lwt value = OBus_method . call m_GetTotal ( proxy daemon ) ( ) in let value = Int32 . to_int value in return value
let total_changed daemon = OBus_signal . map ( fun value -> let value = Int32 . to_int value in value ) ( OBus_signal . make s_TotalChanged ( proxy daemon ) )
let get_data daemon = let % lwt data = OBus_method . call m_GetData ( proxy daemon ) ( ) in return ( List . map ( fun ( is_userspace , id , value , cmdline , details ) -> { data_is_userspace = is_userspace ; data_id = Int32 . to_int id ; data_value = value ; data_cmdline = if cmdline = " " then None else Some cmdline ; data_details = details ; } ) data )
let data_changed daemon = OBus_signal . make s_DataChanged ( proxy daemon )
let const_hole s fmt _ = pp fmt " % s " s
let rec qualid fmt ( q : qualid ) = match q with | Qpreid pid -> Preid . pp fmt pid | Qdot ( q , pid ) -> pp fmt " [ @% a . % a ] " @ qualid q Preid . pp pid
let labelled_arg fmt ( l : labelled_arg ) = match l with | Lunit -> pp fmt " ( ) " | Lnone pid -> Preid . pp fmt pid | Loptional pid -> pp fmt " [ @?% a ] " @ Preid . pp pid | Lnamed pid -> pp fmt " [ @~% a ] " @ Preid . pp pid | Lghost ( pid , _ ) -> pp fmt " [ [ @% a : TY ] ] " @ Preid . pp pid
let spec f fmt x = pp fmt " [ ] " @@ f x
let term fmt _ = pp fmt " [ @ TERM . . . ] " @
let invariant fmt _ = pp fmt " [ @ INVARIANT . . . ] " @
let list_keyword s fmt x = match x with | [ ] -> ( ) | _ -> pp fmt " % a @\ n " ( list ~ sep : newline ( const_hole s ) ) x
let type_spec f ts = let ephemeral f e = if e then pp f " ephemeral @\ n " else ( ) in let print_tspec _fmt ts = pp f " [ @< v >% a % a % a ] " @ ephemeral ts . ty_ephemeral ( list_keyword " model . . . " ) ts . ty_field ( list_keyword " invariant . . . " ) ( snd ts . ty_invariant ) in if ts . ty_ephemeral || ts . ty_field != [ ] || snd ts . ty_invariant != [ ] then pp f " [ @% a ] " @ ( spec print_tspec ) ts else ( )
let spec_header fmt h = pp fmt " [ @< h >% a % s % a % a ] @@\ n " ( list ~ sep : comma labelled_arg ) h . sp_hd_ret ( if h . sp_hd_ret = [ ] then " " else " " ) = Preid . pp h . sp_hd_nm ( list ~ sep : sp labelled_arg ) h . sp_hd_args
let val_spec fmt vspec = match vspec with | None -> ( ) | Some vspec -> let diverge fmt x = if x then pp fmt " diverges @\ n " else ( ) in let print_content fmt s = pp fmt " [ @% a % a % a % a % a % a % a % a ] " @ ( option spec_header ) s . sp_header ( list_keyword " requires . . . " ) s . sp_pre ( list_keyword " ensures . . . " ) s . sp_post ( list_keyword " with . . . " ) s . sp_xpost ( list_keyword " modifies . . . " ) s . sp_writes ( list_keyword " consumes . . . " ) s . sp_consumes diverge s . sp_diverge ( list_keyword " equivalent . . . " ) s . sp_equiv in spec print_content fmt vspec
let value_description f x = pp f " [ @% a % a ] " @ core_type x . vtype ( fun f x -> if x . vprim <> [ ] then pp f " @ =@ % a " ( list constant_string ) x . vprim ) x
let s_type_declaration f x = let priv f = match x . tprivate with Public -> ( ) | Private -> pp f " ; @ private " in let manifest f = match x . tmanifest with | None -> ( ) | Some y -> if x . tkind = Ptype_abstract then pp f " % t ; @% a " priv core_type y else pp f " ; @% a " core_type y in let constructor_declaration f pcd = pp f " ; " ; |@ constructor_declaration reset_ctxt f ( pcd . pcd_name . txt , pcd . pcd_vars , pcd . pcd_args , pcd . pcd_res , pcd . pcd_attributes ) in let repr f = let intro f = if x . tmanifest = None then ( ) else pp f " ; " @= in match x . tkind with | Ptype_variant xs -> let variants fmt xs = if xs = [ ] then pp fmt " " | else pp fmt " @\ n % a " ( list ~ sep : newline constructor_declaration ) xs in pp f " % t % t % a " intro priv variants xs | Ptype_abstract -> ( ) | Ptype_record l -> pp f " % t % t ; @% a " intro priv ( record_declaration reset_ctxt ) l | Ptype_open -> pp f " % t % t ; . . " @ intro priv in let constraints f = List . iter ( fun ( ct1 , ct2 , _ ) -> pp f " [ @< hov2 >@ constraint @ % a @ =@ % a ] " @ core_type ct1 core_type ct2 ) x . tcstrs in pp f " % t % t % t " manifest repr constraints
let s_type_declaration_rec_flag f ( rf , l ) = let type_decl kwd rf f x = let eq = if x . tkind = Ptype_abstract && x . tmanifest = None then " " else " " = in pp f " [ [ @@% s % a % a % s % s % a ] @% a ] @@\ n [ @@ @ % a ] " @ kwd nonrec_flag rf ( type_params reset_ctxt ) x . tparams x . tname . txt eq s_type_declaration x ( item_attributes reset_ctxt ) x . tattributes ( option type_spec ) x . tspec in match l with | [ ] -> assert false | [ x ] -> type_decl " type " rf f x | x :: xs -> pp f " [ @< v >% a , @% a ] " @ ( type_decl " type " rf ) x ( list ( type_decl " and " Asttypes . Recursive ) ) xs
let function_ f x = let keyword = match x . fun_type with None -> " predicate " | Some _ -> " function " in let sep f x = match x with | { fun_req = [ ] ; fun_ens = [ ] ; fun_variant = [ ] ; _ } -> ( ) | _ -> pp f " @\ n " in let func_spec f x = pp f " % a % a % a % a % a " ( fun f _ -> if x . fun_coer then pp f " @\ ncoercion " else ( ) ) ( ) sep x ( list_keyword " variant . . . " ) x . fun_variant ( list_keyword " requires . . . " ) x . fun_req ( list_keyword " ensures . . . " ) x . fun_ens in let func f x = pp f " [ @% s % s % a . . . % a ] " @ keyword ( if x . fun_rec then " rec " else " " ) Preid . pp x . fun_name ( option func_spec ) x . fun_spec in spec func f x
let axiom f x = let axiom f _ = pp f " [ @ axiom . . . ] " @ in spec axiom f x
let rec s_signature_item f x = let s_val_description f vd = let intro = if vd . vprim = [ ] then " val " else " external " in pp f " [ @< 2 >% s @ % a @ :@ % a ] @% a @\ n % a " intro protect_ident vd . vname . txt value_description vd ( item_attributes reset_ctxt ) vd . vattributes val_spec vd . vspec in let print_open f od = pp f " [ @< hov2 > open % s @ % a ] @% a " ( override od . popen_override ) longident_loc od . popen_expr ( item_attributes reset_ctxt ) od . popen_attributes in match x . sdesc with | Sig_type ( rf , l ) -> s_type_declaration_rec_flag f ( rf , l ) | Sig_val vd -> s_val_description f vd | Sig_typext te -> type_extension reset_ctxt f te | Sig_exception ed -> exception_declaration reset_ctxt f ed | Sig_class l -> ( let class_description kwd f ( { pci_params = ls ; pci_name = { txt ; _ } ; _ } as x ) = pp f " [ @< 2 >% s % a % a % s ; ; @:@% a ] @% a " kwd virtual_flag x . pci_virt ( class_params_def reset_ctxt ) ls txt class_type x . pci_expr ( item_attributes reset_ctxt ) x . pci_attributes in match l with | [ ] -> ( ) | [ x ] -> class_description " class " f x | x :: xs -> pp f " [ @< v >% a , @% a ] " @ ( class_description " class " ) x ( list ( class_description " and " ) ) xs ) | Sig_module ( { mdtype = { mdesc = Mod_alias alias ; mattributes = [ ] ; _ } ; _ } as pmd ) -> pp f " [ @< hov > module @ % s @ =@ % a ] @% a " ( match pmd . mdname . txt with None -> " _ " | Some s -> s ) longident_loc alias ( item_attributes reset_ctxt ) pmd . mdattributes | Sig_module pmd -> pp f " [ @< hov > module @ % s @ :@ % a ] @% a " ( match pmd . mdname . txt with None -> " _ " | Some s -> s ) s_module_type pmd . mdtype ( item_attributes reset_ctxt ) pmd . mdattributes | Sig_modsubst pms -> pp f " [ @< hov > module @ % s @ :=@ % a ] @% a " pms . pms_name . txt longident_loc pms . pms_manifest ( item_attributes reset_ctxt ) pms . pms_attributes | Sig_open od -> print_open f od | Sig_typesubst _l -> pp f " < typesubst " > | Sig_include incl -> pp f " [ @< hov2 > include @ % a ] @% a " module_type incl . pincl_mod ( item_attributes reset_ctxt ) incl . pincl_attributes | Sig_modtype { mtdname = s ; mtdtype = md ; mtdattributes = attrs ; _ } -> pp f " [ @< hov2 > module @ type @ % s % a ] @% a " s . txt ( fun f md -> match md with | None -> ( ) | Some mt -> Format . pp_print_space f ( ) ; pp f " @ =@ % a " s_module_type mt ) md ( item_attributes reset_ctxt ) attrs | Sig_modtypesubst { mtdname = s ; mtdtype = md ; mtdattributes = attrs ; _ } -> let md = match md with None -> assert false | Some mt -> mt in pp f " [ @< hov2 > module @ type @ % s @ :=@ % a ] @% a " s . txt s_module_type md ( item_attributes reset_ctxt ) attrs | Sig_class_type l -> class_type_declaration_list reset_ctxt f l | Sig_recmodule decls -> let rec string_x_module_type_list f ( ? first = true ) l = match l with | [ ] -> ( ) | pmd :: tl -> if not first then pp f " @ [ @< hov2 > and @ % s :@ % a ] @% a " ( match pmd . mdname . txt with None -> " _ " | Some s -> s ) s_module_type1 pmd . mdtype ( item_attributes reset_ctxt ) pmd . mdattributes else pp f " [ @< hov2 > module @ rec @ % s :@ % a ] @% a " ( match pmd . mdname . txt with None -> " _ " | Some s -> s ) s_module_type1 pmd . mdtype ( item_attributes reset_ctxt ) pmd . mdattributes ; string_x_module_type_list f ~ first : false tl in string_x_module_type_list f decls | Sig_attribute a -> floating_attribute reset_ctxt f a | Sig_extension ( e , a ) -> item_extension reset_ctxt f e ; item_attributes reset_ctxt f a | Sig_function x -> function_ f x | Sig_axiom x -> axiom f x | Sig_ghost_type ( rf , l ) -> pp f " [ @% a ] " @ ( spec s_type_declaration_rec_flag ) ( rf , l ) | Sig_ghost_val vd -> pp f " [ @% a ] " @ ( spec s_val_description ) vd | Sig_ghost_open od -> pp f " [ @% a ] " @ ( spec print_open ) od if x . mattributes <> [ ] then pp f " ( ( % a ) % a ) " s_module_type { x with mattributes = [ ] } ( attributes reset_ctxt ) x . mattributes else match x . mdesc with | Mod_functor ( Unit , me ) -> pp f " functor ( ) ; ; @->@% a " s_module_type me | Mod_functor ( Named ( s , mt ) , me ) -> pp f " functor @ ( % s @ :@ % a ) ; ; @->@% a " ( match s . txt with None -> " _ " | Some s -> s ) s_module_type mt s_module_type me | Mod_with ( mt , [ ] ) -> s_module_type f mt | Mod_with ( mt , l ) -> let with_constraint f = function | Wtype ( li , ( { tparams = ls ; _ } as td ) ) -> let ls = List . map fst ls in pp f " type @ % a % a =@ % a " ( list core_type ~ sep : comma ~ first : rparens ~ last : lparens ) ls longident_loc li s_type_declaration td | Wmodule ( li , li2 ) -> pp f " module % a =@ % a " longident_loc li longident_loc li2 | Wmodtype ( li , mty ) -> pp f " module type % a =@ % a " longident_loc li module_type mty | Wtypesubst ( li , ( { tparams = ls ; _ } as td ) ) -> let ls = List . map fst ls in pp f " type @ % a % a :=@ % a " ( list core_type ~ sep : comma ~ first : lparens ~ last : rparens ) ls longident_loc li s_type_declaration td | Wmodsubst ( li , li2 ) -> pp f " module % a :=@ % a " longident_loc li longident_loc li2 | Wmodtypesubst ( li , mty ) -> pp f " module type % a :=@ % a " longident_loc li module_type mty in pp f " [ @< hov2 >% a @ with @ % a ] " @ s_module_type1 mt ( list with_constraint ~ sep ( : any " and @ " ) ) l | _ -> s_module_type1 f x if x . mattributes <> [ ] then s_module_type f x else match x . mdesc with | Mod_ident li -> pp f " % a " longident_loc li | Mod_alias li -> pp f " ( module % a ) " longident_loc li | Mod_signature s -> pp f " [ @< hv0 [ >@< hv2 > sig @ % a ] @@ end ] " @ ( list s_signature_item ) s | Mod_typeof me -> pp f " [ @< hov2 > module @ type @ of @ % a ] " @ module_expr me | Mod_extension e -> extension reset_ctxt f e | _ -> paren true s_module_type f x
module Blake2 = Blake2 . Make ( )
type block_data = { block : string ; created_at : string ; peer_id : string ; snark_work : string option [ @ default None ] None }
module Proof_data = struct type t = { proof : Ledger_proof . Stable . Latest . t ; proof_time : Core_kernel . Time . Span . t ; snark_work_fee : Currency . Fee . Stable . Latest . t } [ @@ deriving bin_io_unversioned ] bin_io_unversioned end
let sign_blake2_hash ~ private_key s = let module Field = Snark_params . Tick . Field in let blake2 = Blake2 . digest_string s in let field_elements = [ ] || in let bitstrings = [ | Blake2 . to_raw_string blake2 |> Blake2 . string_to_bits |> Array . to_list ] | in let input : ( Field . t , bool ) bool Random_oracle . Legacy . Input . t = { field_elements ; bitstrings } in Schnorr . Legacy . sign private_key input
let send_uptime_data ~ logger ~ interruptor ( ~ submitter_keypair : Keypair . t ) t ~ url ~ state_hash ~ produced block_data = let open Interruptible . Let_syntax in let make_interruptible f = Interruptible . lift f interruptor in let block_data_json = block_data_to_yojson block_data in let block_data_string = Yojson . Safe . to_string block_data_json in let signature = sign_blake2_hash ~ private_key : submitter_keypair . private_key block_data_string in let json = ` Assoc [ ( " data " , block_data_json ) block_data_json ; ( " signature " , Signature . to_yojson signature ) signature ; ( " submitter " , Public_key . to_yojson submitter_keypair . public_key ) public_key ] in let headers = Cohttp . Header . of_list [ ( " Content - Type " , " application / json ) " ] in let metadata_of_body = function | ` String s -> [ ( " error " , ` String s ) s ] | ` Strings ss -> [ ( " error " , ` List ( List . map ss ~ f ( : fun s -> ` String s ) s ) s ) s ] | ` Empty | ` Pipe _ -> [ ] in let max_attempts = 8 in let attempt_pause_sec = 4 . 0 in let unrecoverable_status_codes = [ 400 ; 401 ; 411 ; 413 ] in let run_attempt attempt = let interruptible = match % map make_interruptible ( Monitor . try_with ~ here [ :% here ] here ~ extract_exn : true ( fun ( ) -> Cohttp_async . Client . post ~ headers ~ body : ( Yojson . Safe . to_string json |> Cohttp_async . Body . of_string ) of_string url ) ) with | Ok ( { status ; _ } , body ) body -> let status_code = Cohttp . Code . code_of_status status in let status_string = Cohttp . Code . string_of_status status in let unretriable = List . mem unrecoverable_status_codes status_code ~ equal : Int . equal in let succeeded = status_code = 200 in ( if succeeded then [ % log info ] info " Sent block with state hash $ state_hash to uptime service at URL \ $ url " ~ metadata : [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " includes_snark_work " , ` Bool ( Option . is_some block_data . snark_work ) snark_work ) ; ( " is_produced_block " , ` Bool produced ) produced ] else if unretriable then [ % log error ] error " Got unrecoverable response from update service backend at URL \ $ url , not retrying to send block " ~ metadata : [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " http_code " , ` Int status_code ) status_code ; ( " http_error " , ` String status_string ) status_string ; ( " payload " , json ) json ] else if attempt >= max_attempts then let base_metadata = [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " http_code " , ` Int status_code ) status_code ; ( " http_error " , ` String status_string ) status_string ; ( " payload " , json ) json ] in let extra_metadata = metadata_of_body body in let metadata = base_metadata @ extra_metadata in [ % log error ] error " After % d attempts , failed to send block with state hash \ $ state_hash to uptime service at URL $ url , no more retries " max_attempts ~ metadata else let base_metadata = [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " http_code " , ` Int status_code ) status_code ; ( " http_error " , ` String status_string ) status_string ] in let extra_metadata = metadata_of_body body in let metadata = base_metadata @ extra_metadata in [ % log info ] info " Failure when sending block with state hash $ state_hash to \ uptime service at URL $ url , attempt % d of % d , retrying " attempt max_attempts ~ metadata ) ; succeeded || unretriable | Error exn -> [ % log warn ] warn " Error when sending block with state hash $ state_hash to uptime \ service at URL $ url " ~ metadata : [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " url " , ` String ( Uri . to_string url ) url ) url ; ( " payload " , json ) json ; ( " error " , ` String ( Exn . to_string exn ) exn ) exn ] ; false in match % map . Deferred Interruptible . force interruptible with | Ok succeeded -> succeeded | Error _ -> [ % log error ] error " In uptime service , POST of block with state hash $ state_hash was \ interrupted " ~ metadata : [ ( " state_hash " , State_hash . to_yojson state_hash ) state_hash ; ( " payload " , json ) json ] ; true in let rec go attempt = let open Deferred . Let_syntax in let % bind succeeded = run_attempt attempt in if succeeded then Deferred . return ( ) else if attempt < max_attempts then ( let % bind ( ) = Async . after ( Time . Span . of_sec attempt_pause_sec ) attempt_pause_sec in [ % log info ] info " In uptime service , retrying to send block , attempt % d of % d attempts \ allowed " attempt max_attempts ; go ( attempt + 1 ) 1 ) else Deferred . unit in make_interruptible ( go 1 ) 1
let block_base64_of_breadcrumb breadcrumb = let external_transition = breadcrumb |> Transition_frontier . Breadcrumb . block |> External_transition . compose in let block_string = Binable . to_string ( module External_transition . Raw . Stable . Latest ) Latest external_transition in Base64 . encode_exn block_string
let send_produced_block_at ~ logger ~ interruptor ~ url ~ peer_id ( ~ submitter_keypair : Keypair . t ) t ~ block_produced_bvar tm = let open Interruptible . Let_syntax in let make_interruptible f = Interruptible . lift f interruptor in let timeout_min = 3 . 0 in let % bind ( ) = make_interruptible ( at tm ) tm in match % bind make_interruptible ( with_timeout ( Time . Span . of_min timeout_min ) timeout_min ( Bvar . wait block_produced_bvar ) block_produced_bvar ) with | ` Timeout -> [ % log error ] error " Uptime service did not get a produced block within % 0 . 1f minutes \ after scheduled time " timeout_min ; return ( ) | ` Result breadcrumb -> let block_base64 = block_base64_of_breadcrumb breadcrumb in let state_hash = Transition_frontier . Breadcrumb . state_hash breadcrumb in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = None } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : true block_data
let send_block_and_transaction_snark ~ logger ~ interruptor ~ url ~ snark_worker ~ transition_frontier ~ peer_id ( ~ submitter_keypair : Keypair . t ) t ~ snark_work_fee = match Broadcast_pipe . Reader . peek transition_frontier with | None -> [ % log info ] info " Transition frontier not available to send a block to uptime service " ; Interruptible . return ( ) | Some tf -> ( let make_interruptible f = Interruptible . lift f interruptor in let breadcrumb = Transition_frontier . best_tip tf in let block_base64 = block_base64_of_breadcrumb breadcrumb in let open Interruptible . Let_syntax in let message = Sok_message . create ~ fee : snark_work_fee ~ prover ( : Public_key . compress submitter_keypair . public_key ) public_key in let best_tip = Transition_frontier . best_tip tf in let best_tip_block = Transition_frontier . Breadcrumb . block best_tip in if List . is_empty ( Mina_block . transactions ~ constraint_constants : Genesis_constants . Constraint_constants . compiled best_tip_block ) then ( [ % log info ] info " No transactions in block , sending block without SNARK work to \ uptime service " ; let state_hash = Transition_frontier . Breadcrumb . state_hash best_tip in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = None } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : false block_data ) else let best_tip_staged_ledger = Transition_frontier . Breadcrumb . staged_ledger best_tip in match Staged_ledger . all_work_pairs best_tip_staged_ledger ~ get_state ( : fun state_hash -> match Transition_frontier . find_protocol_state tf state_hash with | None -> Error ( Error . createf " Could not find state_hash % s in transition frontier \ for uptime service " ( State_hash . to_base58_check state_hash ) state_hash ) | Some protocol_state -> Ok protocol_state ) with | Error e -> [ % log error ] error " Could not get SNARK work from best tip staged ledger for uptime \ service " ~ metadata [ : ( " error " , Error_json . error_to_yojson e ) e ] ; Interruptible . return ( ) | Ok [ ] -> [ % log info ] info " No SNARK jobs available for uptime service , sending just the \ block " ; let state_hash = Transition_frontier . Breadcrumb . state_hash best_tip in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = None } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : false block_data | Ok job_one_or_twos -> ( let transitions = List . concat_map job_one_or_twos ~ f : One_or_two . to_list |> List . filter ~ f ( : function | Snark_work_lib . Work . Single . Spec . Transition _ -> true | Merge _ -> false ) in let staged_ledger_hash = Mina_block . header best_tip_block |> Mina_block . Header . protocol_state |> Mina_state . Protocol_state . blockchain_state |> Mina_state . Blockchain_state . staged_ledger_hash in match List . find transitions ~ f ( : fun transition -> match transition with | Snark_work_lib . Work . Single . Spec . Transition ( { target ; _ } , _ ) _ -> Pasta_bindings . Fp . equal target . ledger ( Staged_ledger_hash . ledger_hash staged_ledger_hash ) staged_ledger_hash | Merge _ -> failwith " Expected Transition work , not Merge " ) with | None -> [ % log info ] info " No transactions in block match staged ledger hash , sending \ block without SNARK work " ; let state_hash = Transition_frontier . Breadcrumb . state_hash best_tip in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = None } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : false block_data | Some single_spec -> ( match % bind make_interruptible ( Uptime_snark_worker . perform_single snark_worker ( message , single_spec ) single_spec ) with | Error e -> [ % log error ] error " Error when running uptime service SNARK worker on a \ transaction " ~ metadata [ : ( " error " , Error_json . error_to_yojson e ) e ] ; Interruptible . return ( ) | Ok ( Error e ) e -> [ % log error ] error " Error computing SNARK work for uptime service " ~ metadata [ : ( " error " , Error_json . error_to_yojson e ) e ] ; Interruptible . return ( ) | Ok ( Ok ( proof , proof_time ) proof_time ) proof_time -> let proof_data : Proof_data . t = { proof ; proof_time ; snark_work_fee } in let proof_string = Binable . to_string ( module Proof_data ) Proof_data proof_data in let snark_work_base64 = Base64 . encode_exn proof_string in let state_hash = Transition_frontier . Breadcrumb . state_hash best_tip in let block_data = { block = block_base64 ; created_at = Rfc3339_time . get_rfc3339_time ( ) ; peer_id ; snark_work = Some snark_work_base64 } in send_uptime_data ~ logger ~ interruptor ~ submitter_keypair ~ url ~ state_hash ~ produced : false block_data ) ) )
let start ~ logger ~ uptime_url ~ snark_worker_opt ~ transition_frontier ~ time_controller ~ block_produced_bvar ~ uptime_submitter_keypair ~ get_next_producer_timing ~ get_snark_work_fee ~ get_peer = match uptime_url with | None -> [ % log info ] info " Not running uptime service , no URL given " ; ( ) | Some url -> [ % log info ] info " Starting uptime service using URL $ url " ~ metadata [ : ( " url " , ` String ( Uri . to_string url ) url ) url ] ; let snark_worker : Uptime_snark_worker . t = Option . value_exn snark_worker_opt in let slot_duration_ms = Consensus . Configuration . t ~ constraint_constants : Genesis_constants . Constraint_constants . compiled ~ protocol_constants : Genesis_constants . compiled . protocol |> Consensus . Configuration . slot_duration |> Float . of_int in let make_slots_span min = Block_time . Span . of_time_span ( Time . Span . of_ms ( slot_duration_ms . * min ) min ) min in let five_slots_span = make_slots_span 5 . 0 in let four_slots_span = make_slots_span 4 . 0 in let wait_until_iteration_start block_tm = let now = Block_time . now time_controller in if Block_time ( . < ) now block_tm then at ( Block_time . to_time block_tm ) block_tm else ( [ % log warn ] warn " In uptime service , current block time is past desired start of \ iteration " ; return ( ) ) in let register_iteration = let interrupt_ivar = ref ( Ivar . create ( ) ) in fun ( ) -> Ivar . fill_if_empty ! interrupt_ivar ( ) ; Deferred . create ( fun ivar -> interrupt_ivar := ivar ) ivar in let run_iteration next_block_tm : Block_time . t Deferred . t = let get_next_producer_time_opt ( ) = match get_next_producer_timing ( ) with | None -> [ % log trace ] trace " Next producer timing not set for uptime service " ; None | Some timing -> ( let open Daemon_rpcs . Types . Status . Next_producer_timing in match timing . timing with | Check_again _tm -> [ % log trace ] trace " Next producer timing not available for uptime service " ; None | Evaluating_vrf _ -> [ % log trace ] trace " Evaluating VRF , wait for block production status for \ uptime service " ; None | Produce prod_tm | Produce_now prod_tm -> Some ( Block_time . to_time prod_tm . time ) time ) in [ % log trace ] trace " Waiting for next 5 - slot boundary to start work in uptime service " ~ metadata : [ ( " boundary_block_time " , Block_time . to_yojson next_block_tm ) next_block_tm ; ( " boundary_time " , ` String ( Block_time . to_time next_block_tm |> Time . to_string ) to_string ) ] ; let % bind ( ) = wait_until_iteration_start next_block_tm in let interruptor = register_iteration ( ) in let open Interruptible . Let_syntax in Interruptible . don ' t_wait_for ( [ % log trace ] trace " Determining which action to take in uptime service " ; match get_peer ( ) with | None -> [ % log warn ] warn " Daemon is not yet a peer in the gossip network , uptime \ service not sending a produced block " ; Interruptible . return ( ) | Some ( { peer_id ; _ } : Network_peer . Peer . t ) t -> ( let submitter_keypair = Option . value_exn uptime_submitter_keypair in let send_just_block next_producer_time = [ % log info ] info " Uptime service will attempt to send the next produced \ block " ; send_produced_block_at ~ logger ~ interruptor ~ url ~ peer_id ~ submitter_keypair ~ block_produced_bvar next_producer_time in let send_block_and_snark_work ( ) = [ % log info ] info " Uptime service will attempt to send a block and SNARK work " ; let snark_work_fee = get_snark_work_fee ( ) in send_block_and_transaction_snark ~ logger ~ interruptor ~ url ~ snark_worker ~ transition_frontier ~ peer_id ~ submitter_keypair ~ snark_work_fee in match get_next_producer_time_opt ( ) with | None -> send_block_and_snark_work ( ) | Some next_producer_time -> let four_slots_from_start = Block_time . add next_block_tm four_slots_span |> Block_time . to_time in if Time ( . <= ) next_producer_time four_slots_from_start then let % bind ( ) = send_block_and_snark_work ( ) in send_just_block next_producer_time else send_block_and_snark_work ( ) ) ) ; Deferred . return ( Block_time . add next_block_tm five_slots_span ) five_slots_span in let next_slot_block_time = let block_time_ms_int64 = Block_time . now time_controller |> Block_time . to_int64 in let slot_duration_ms_int64 = Float . to_int64 slot_duration_ms in let next_slot_ms = if Int64 . equal Int64 . zero ( Int64 ( . rem ) rem block_time_ms_int64 slot_duration_ms_int64 ) slot_duration_ms_int64 then block_time_ms_int64 else let last_slot_no = Int64 ( . / ) block_time_ms_int64 slot_duration_ms_int64 in Int64 ( . * ) ( Int64 . succ last_slot_no ) last_slot_no slot_duration_ms_int64 in Block_time . of_int64 next_slot_ms in Async . Deferred . forever next_slot_block_time run_iteration
module Worker_state = struct module type S = sig val perform_single : Sok_message . t * Prod . single_spec -> ( Ledger_proof . t * Time . Span . t ) t Deferred . Or_error . t end type init_arg = Logger . Stable . Latest . t [ @@ deriving bin_io_unversioned ] bin_io_unversioned type t = ( module S ) S let create ~ logger : t Deferred . t = Memory_stats . log_memory_stats logger ~ process " : uptime service SNARK worker " ; Deferred . return ( let module M = struct let perform_single ( message , single_spec ) single_spec = let % bind ( worker_state : Prod . Worker_state . t ) t = Prod . Worker_state . create ~ constraint_constants : Genesis_constants . Constraint_constants . compiled ~ proof_level : Full ( ) in Prod . perform_single worker_state ~ message single_spec end in ( module M : S ) S ) let get = Fn . id end
module Worker = struct module T = struct module F = Rpc_parallel . Function type ' w functions = { perform_single : ( ' w , Sok_message . t * Prod . single_spec , ( Ledger_proof . t * Time . Span . t ) t Or_error . t ) F . t } module Worker_state = Worker_state module Connection_state = struct type init_arg = unit [ @@ deriving bin_io_unversioned ] bin_io_unversioned type t = unit end module Functions ( C : Rpc_parallel . Creator with type worker_state := Worker_state . t and type connection_state := Connection_state . t ) t = struct let perform_single ( w : Worker_state . t ) t msg_and_single_spec = let ( module M ) M = Worker_state . get w in M . perform_single msg_and_single_spec let functions = let f ( i , o , f ) f = C . create_rpc ~ f ( : fun ~ worker_state ~ conn_state : _ i -> f worker_state i ) i ~ bin_input : i ~ bin_output : o ( ) in { perform_single = f ( [ % bin_type_class : Sok_message . Stable . Latest . t * Prod . single_spec ] single_spec , [ % bin_type_class : ( Ledger_proof . Stable . Latest . t * Time . Span . t ) t Or_error . t ] t , perform_single ) } let init_worker_state logger = [ % log info ] info " Uptime SNARK worker started " ; Worker_state . create ~ logger let init_connection_state ~ connection : _ ~ worker_state : _ ( ) = Deferred . unit end end include Rpc_parallel . Make ( T ) T end
type t = { connection : Worker . Connection . t ; process : Process . t ; logger : Logger . Stable . Latest . t }
let create ~ logger ~ pids : t Deferred . t = let on_failure err = [ % log error ] error " Uptime service SNARK worker process failed with error $ err " ~ metadata [ : ( " err " , Error_json . error_to_yojson err ) err ] ; Error . raise err in [ % log info ] info " Starting a new uptime service SNARK worker process " ; let % map connection , process = Worker . spawn_in_foreground_exn ~ connection_timeout ( : Time . Span . of_min 1 ) . ~ on_failure ~ shutdown_on : Connection_closed ~ connection_state_init_arg ( ) : logger in [ % log info ] info " Daemon started process of kind $ process_kind with pid \ $ uptime_snark_worker_pid " ~ metadata : [ ( " uptime_snark_worker_pid " , ` Int ( Process . pid process |> Pid . to_int ) to_int ) to_int ; ( " process_kind " , ` String Child_processes . Termination ( . show_process_kind Uptime_snark_worker ) Uptime_snark_worker ) ] ; Child_processes . Termination . register_process pids process Child_processes . Termination . Uptime_snark_worker ; don ' t_wait_for @@ Pipe . iter ( Process . stdout process |> Reader . pipe ) pipe ~ f ( : fun stdout -> return @@ [ % log debug ] debug " Uptime SNARK worker stdout : $ stdout " ~ metadata [ : ( " stdout " , ` String stdout ) stdout ] ) ; don ' t_wait_for @@ Pipe . iter ( Process . stderr process |> Reader . pipe ) pipe ~ f ( : fun stderr -> return @@ [ % log error ] error " Uptime SNARK worker stderr : $ stderr " ~ metadata [ : ( " stderr " , ` String stderr ) stderr ] ) ; { connection ; process ; logger }
let perform_single { connection ; _ } ( ( _message , _single_spec ) _single_spec as arg ) arg = Worker . Connection . run connection ~ f : Worker . functions . perform_single ~ arg
let root_dir = ref Sundials . RootDirs . Increasing
let args = [ ( " - e " , Arg . Unit ( fun ( ) -> root_dir := Sundials . RootDirs . IncreasingOrDecreasing ) , " Use either instead of up ( ) " ) ; ]
let _ = Arg . parse args ( fun _ -> ( ) ) " upvseither : test different types of root detection "
let print_with_time t v = Printf . printf " % e " t ; Sundials . RealArray . iter ( Printf . printf " \ t % e " ) v ; print_newline ( )
let f t_s y yd = yd . { x } <- - 1 . 0 ; Printf . printf " f ( % e , [ % e ] ) = [ % e ] \ n " t_s y . { x } yd . { x }
let g t_s y gout = gout . { 0 } <- y . { x } ; Printf . printf " g ( % e , [ % e ] ) = [ % e ] \ n " t_s y . { x } gout . { 0 }
let y = Sundials . RealArray . of_array [ | x_i ] |
let s = Cvode . ( init Adams default_tolerances f ~ roots ( : 1 , g ) 0 . y_nvec )
let rootdata = Sundials . Roots . create 1
let _ = Cvode . set_all_root_directions s ! root_dir
let _ = Cvode . set_stop_time s max_sim_t
let _ = Cvode . set_max_step s 5 . 0
let _ = Printf . printf " time \ t \ t t \ n " ; Printf . printf " ------------------------------------\ n " ; print_with_time 0 . 0 y ; try let i = ref 0 in while true do let ( t ' , result ) = Cvode . solve_one_step s max_sim_t y_nvec in Printf . printf " \ nstep % 3d . \ n " ! i ; incr i ; print_with_time t ' y ; Printf . printf " \ t \ t ( step size = % e ) \ n " ( Cvode . get_last_step s ) ; match result with | Cvode . RootsFound -> print_endline " ** root found " | Cvode . StopTimeReached -> raise Done | Cvode . Success -> ( ) done with Done -> ( )
let get_file_size fd = Unix . handle_unix_error Unix . fstat fd |> fun { Unix . st_size ; _ } -> st_size
type t = { freelist : int Queue . t ; mutable insize : int ; mutable offset : Int63 . t ; mutable reads : int ; mutable writes : int ; mutable write_left : int ; mutable read_left : int ; block_size : int ; infd : Unix . file_descr ; outfd : Unix . file_descr ; }
let pp ppf { insize ; offset ; reads ; writes ; write_left ; read_left ; _ } = Fmt . pf ppf " insize % d offset % a reads % d writes % d rleft % d wleft % d " insize Int63 . pp offset reads writes read_left write_left
type req = { op : [ ` R | ` W ] ; fixed_off : int ; mutable len : int ; fileoff : Int63 . t ; mutable off : int ; t : t ; }
let pp_req ppf { op ; len ; off ; fixed_off ; fileoff ; t ; _ } = Fmt . pf ppf " [ % s fileoff % a len % d off % d fixedoff % d ] [ % a ] " ( match op with ` | R -> " r " ` | W -> " w " ) Int63 . pp fileoff len off fixed_off pp t
let queue_read uring t len = let fixed_off = Queue . pop t . freelist in let req = { op ` = R ; fixed_off ; fileoff = t . offset ; len ; off = 0 ; t } in Logs . debug ( fun l -> l " queue_read : % a " pp_req req ) ; let r = Uring . read_fixed uring ~ file_offset : t . offset t . infd ~ off : fixed_off ~ len req in assert ( r <> None ) ; t . offset <- Int63 . ( add t . offset ( of_int len ) ) ; t . read_left <- t . read_left - len ; t . reads <- t . reads + 1
let handle_read_completion uring req res = Logs . debug ( fun l -> l " read_completion : res =% d % a " res pp_req req ) ; let bytes_to_read = req . len - req . off in match res with | 0 -> Logs . debug ( fun l -> l " eof % a " pp_req req ) ; | n when n = eagain || n = eintr -> let r = Uring . read_fixed ~ file_offset : req . fileoff uring req . t . infd ~ off : req . fixed_off ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued eintr read : % a " pp_req req ) ; | n when n < 0 -> raise ( Failure ( " unix errorno " ^ ( string_of_int n ) ) ) | n when n < bytes_to_read -> req . off <- req . off + n ; req . len <- req . len - n ; let r = Uring . read_fixed ~ file_offset : req . fileoff uring req . t . infd ~ off ( : req . fixed_off + req . off ) ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued short read : % a " pp_req req ) ; | n when n = bytes_to_read -> req . t . reads <- req . t . reads - 1 ; req . t . writes <- req . t . writes + 1 ; let req = { req with op ` = W ; off = 0 ; len = req . len + req . off } in let r = Uring . write_fixed uring ~ file_offset : req . fileoff req . t . outfd ~ off : req . fixed_off ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " queued write : % a " pp_req req ) ; | n -> raise ( Failure ( Printf . sprintf " unexpected read result % d > % d " bytes_to_read n ) )
let handle_write_completion uring req res = Logs . debug ( fun l -> l " write_completion : res =% d % a " res pp_req req ) ; let bytes_to_write = req . len - req . off in match res with | 0 -> raise End_of_file | n when n = eagain || n = eintr -> let r = Uring . write_fixed ~ file_offset : req . fileoff uring req . t . outfd ~ off : req . fixed_off ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued eintr read : % a " pp_req req ) ; | n when n < 0 -> failwith ( Fmt . str " unix error % d " ( - n ) ) | n when n < bytes_to_write -> req . off <- req . off + n ; req . len <- req . len - n ; let r = Uring . write_fixed ~ file_offset : req . fileoff uring req . t . outfd ~ off ( : req . fixed_off + req . off ) ~ len : req . len req in assert ( r <> None ) ; Logs . debug ( fun l -> l " requeued short write : % a " pp_req req ) ; | n when n = bytes_to_write -> req . t . writes <- req . t . writes - 1 ; req . t . write_left <- req . t . write_left - req . len ; Queue . push req . fixed_off req . t . freelist ; Logs . debug ( fun l -> l " write done : % a " pp_req req ) ; | n -> raise ( Failure ( Printf . sprintf " unexpected writev result % d > % d " bytes_to_write n ) )