text
stringlengths 0
601k
|
---|
module All_annotations_correctly_used = struct type ' a t = | N of ' a | Graft of int | Tau of ' a t | C of ' a t * ' a t let [ @ inline never ] rec graft n = graft n let [ @ tail_mod_cons ] rec map f l = match l with | N v -> N ( f v ) | Graft n -> if n >= 0 then ( graft [ @ tailcall false ] ) n else Tau ( ( graft [ @ tailcall false ] ) n ) | Tau t -> ( map [ @ tailcall ] ) f t | C ( a , b ) -> let [ @ tail_mod_cons ] map ' l = map f l in C ( map ' a , ( map ' [ @ tailcall ] ) b ) end |
module All_annotations_correctly_used : sig type ' a t = N of ' a | Graft of int | Tau of ' a t | C of ' a t * ' a t val graft : ' a -> ' b val map : ( ' a -> ' b ) -> ' a t -> ' b t end } ] | |
module All_annotations_flipped = struct type ' a t = | N of ' a | Graft of int | Tau of ' a t | C of ' a t * ' a t let [ @ inline never ] rec graft n = graft n let [ @ tail_mod_cons ] rec map_wrong f l = match l with | N v -> N ( f v ) | Graft n -> if n >= 0 then ( graft [ @ tailcall ] ) n else Tau ( ( graft [ @ tailcall ] ) n ) | Tau t -> ( map_wrong [ @ tailcall false ] ) f t | C ( a , b ) -> let [ @ tail_mod_cons ] map ' l = map_wrong f l in C ( map ' a , ( map ' [ @ tailcall false ] ) b ) end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
module All_annotations_flipped : sig type ' a t = N of ' a | Graft of int | Tau of ' a t | C of ' a t * ' a t val graft : ' a -> ' b val map_wrong : ( ' a -> ' b ) -> ' a t -> ' b t end } ] | |
module Uint8 = struct type t = int let pp ppf t = Format . fprintf ppf " 0x % 02X " t let of_int i = if i < 0 then invalid_arg " out of range " else if i > 255 then invalid_arg " out of range " else i external add : t -> t -> t * bool = " caml__uint8_add_overflow " external mul : t -> t -> t * bool = " caml__uint8_mul_overflow " external sub : t -> t -> t * bool = " caml__uint8_sub_overflow " let pred t = sub t 1 let succ t = add t 1 let ( + ) = add let ( - ) = sub let ( * ) = mul let compare a b = match sub a b with | _ , true -> - 1 | 0 , _ -> 0 | _ , false -> 1 let ( < ) a b = compare a b < 0 let ( <= ) a b = compare a b <= 0 let ( > ) a b = compare a b > 0 let ( >= ) a b = compare a b >= 0 end |
module Uint16 = struct type t = int let pp ppf t = Format . fprintf ppf " 0x % 04X " t let of_int i = if i < 0 then invalid_arg " out of range " else if i > 65535 then invalid_arg " out of range " else i external add : t -> t -> t * bool = " caml__uint16_add_overflow " external mul : t -> t -> t * bool = " caml__uint16_mul_overflow " external sub : t -> t -> t * bool = " caml__uint16_sub_overflow " let pred t = sub t 1 let succ t = add t 1 let ( + ) = add let ( - ) = sub let ( * ) = mul let compare a b = match sub a b with | _ , true -> - 1 | 0 , _ -> 0 | _ , false -> 1 let ( < ) a b = compare a b < 0 let ( <= ) a b = compare a b <= 0 let ( > ) a b = compare a b > 0 let ( >= ) a b = compare a b >= 0 end |
module Uint32 = struct type t = int32 let pp ppf t = Format . fprintf ppf " 0x % 08lX " t let of_int i = if i < 0 then invalid_arg " out of range " else if i > 2 * Int32 . ( to_int max_int ) + 1 then invalid_arg " out of range " else Int32 . of_int i let to_int t = if Sys . word_size <= 32 && t < 0l then None else if t < 0l then Some Int32 . ( to_int ( add t min_int ) + to_int max_int + 1 ) else Some ( Int32 . to_int t ) external add : t -> t -> t * bool = " caml_uint32_add_overflow " external mul : t -> t -> t * bool = " caml_uint32_mul_overflow " external sub : t -> t -> t * bool = " caml_uint32_sub_overflow " let pred t = sub t 1l let succ t = add t 1l let ( + ) = add let ( - ) = sub let ( * ) = mul let compare a b = match sub a b with | _ , true -> - 1 | 0l , _ -> 0 | _ , false -> 1 let ( < ) a b = compare a b < 0 let ( <= ) a b = compare a b <= 0 let ( > ) a b = compare a b > 0 let ( >= ) a b = compare a b >= 0 end |
module Uint64 = struct type t = int64 let pp ppf t = Format . fprintf ppf " 0x % 016LX " t let of_int i = if i < 0 then invalid_arg " out of range " else Int64 . of_int i let to_int t = if Sys . word_size <= 64 && t < 0L then None else if t < 0L then Some Int64 . ( to_int ( add t min_int ) + to_int max_int + 1 ) else Some ( Int64 . to_int t ) external add : t -> t -> t * bool = " caml_uint64_add_overflow " external mul : t -> t -> t * bool = " caml_uint64_mul_overflow " external sub : t -> t -> t * bool = " caml_uint64_sub_overflow " let pred t = sub t 1L let succ t = add t 1L let ( + ) = add let ( - ) = sub let ( * ) = mul let compare a b = match sub a b with | _ , true -> - 1 | 0L , _ -> 0 | _ , false -> 1 let ( < ) a b = compare a b < 0 let ( <= ) a b = compare a b <= 0 let ( > ) a b = compare a b > 0 let ( >= ) a b = compare a b >= 0 end |
module Logging = struct type log_opts = { log_conns : bool ; log_async_exn : bool ; log_plugged_inout : bool ; log_everything_else : bool } bool let ( conn_section , async_exn , plugged_inout , everything_else ) everything_else = Lwt_log . Section . make " connections " , Lwt_log . Section . make " async_exceptions " , Lwt_log . Section . make " plugged_inout " , Lwt_log . Section . make " everything_else " let logging_opts = ref { log_conns = false ; log_async_exn = false ; log_plugged_inout = false ; log_everything_else = false } false let ( ) = Lwt_log . add_rule " " * Lwt_log . Info let log ( event : [ ` exn of exn | ` misc | ` plugged_inout | ` tunnel ] tunnel ) tunnel message = Lwt_log ( . match event with | ` exn exn -> if ! logging_opts . log_async_exn then ign_info ~ exn ~ section : async_exn message | ` misc -> if ! logging_opts . log_everything_else then ign_info ~ section : everything_else message | ` plugged_inout -> if ! logging_opts . log_plugged_inout then ign_info ~ section : plugged_inout message | ` tunnel -> if ! logging_opts . log_conns then ign_info ~ section : conn_section message ) end |
let byte_swap_16 value = ( ( value land 0xFF ) 0xFF lsl 8 ) 8 lor ( ( value lsr 8 ) 8 land 0xFF ) 0xFF |
module Protocol = struct type msg_version_t = Binary | Plist type conn_code = Success | Device_requested_not_connected | Port_requested_not_available | Malformed_request type event = Attached of device_t | Detached of int and device_t = { serial_number : string ; connection_speed : int ; connection_type : string ; product_id : int ; location_id : int ; device_id : int ; } type msg_t = Result of conn_code | Event of event type exn += Unknown_reply of string let ( header_length , usbmuxd_address ) usbmuxd_address = 16 , Unix . ADDR_UNIX " / var / run / usbmuxd " let listen_message = Plist ( . Dict [ ( " MessageType " , String " Listen ) " ; ( " ClientVersionString " , String " ocaml - usbmux ) " ; ( " ProgName " , String " ocaml - usbmux ) ] " |> make ) make let connect_message ~ device_id ~ device_port = Plist ( ( . Dict [ ( " MessageType " , String " Connect ) " ; ( " ClientVersionString " , String " ocaml - usbmux ) " ; ( " ProgName " , String " ocaml - usbmux ) " ; ( " DeviceID " , Integer device_id ) device_id ; ( " PortNumber " , Integer ( byte_swap_16 device_port ) device_port ) device_port ] device_port ) device_port |> make ) make let msg_length msg = String . length msg + header_length let listen_msg_len = msg_length listen_message let read_header i_chan = i_chan |> Lwt_io . atomic begin fun ic -> Lwt_io . LE ( . read_int32 ic >>= fun raw_count -> read_int32 ic >>= fun raw_version -> read_int32 ic >>= fun raw_request -> read_int32 ic >|= fun raw_tag -> Int32 ( . to_int raw_count , to_int raw_version , to_int raw_request , to_int raw_tag ) raw_tag ) raw_tag end let write_header ( ? version = Plist ) Plist ( ? request = 8 ) 8 ( ? tag = 1 ) 1 ~ total_len o_chan = o_chan |> Lwt_io . atomic begin fun oc -> ( [ total_len ; if version = Plist then 1 else 0 ; request ; tag ] tag |> List . map ~ f : Int32 . of_int ) |> Lwt_list . iter_s ( Lwt_io . LE . write_int32 oc ) oc end let parse_reply raw_reply = let handle = Plist . parse_dict raw_reply in U ( . match member " MessageType " handle |> to_string with | " Result " -> ( match member " Number " handle |> to_int with | 0 -> Result Success | 2 -> Result Device_requested_not_connected | 3 -> Result Port_requested_not_available | 5 -> Result Malformed_request | n -> raise ( Unknown_reply ( P . sprintf " Unknown result code : % d " n ) n ) n ) n | " Attached " -> Event ( Attached { serial_number = member " SerialNumber " handle |> to_string ; connection_speed = member " ConnectionSpeed " handle |> to_int ; connection_type = member " ConnectionType " handle |> to_string ; product_id = member " ProductID " handle |> to_int ; location_id = member " LocationID " handle |> to_int ; device_id = member " DeviceID " handle |> to_int } ) ; | " Detached " -> Event ( Detached ( member " DeviceID " handle |> to_int ) to_int ) to_int | otherwise -> raise ( Unknown_reply otherwise ) otherwise ) otherwise let create_listener ? event_cb ( ) = Lwt_io . with_connection usbmuxd_address begin fun ( mux_ic , mux_oc ) mux_oc -> write_header ~ total_len : listen_msg_len mux_oc >> ( ( String . length listen_message ) listen_message |> Lwt_io . write_from_string_exactly mux_oc listen_message 0 ) 0 >> read_header mux_ic >>= fun ( msg_len , _ , _ , _ ) _ -> let buffer = Bytes . create ( msg_len - header_length ) header_length in let rec start_listening ( ) = read_header mux_ic >>= fun ( msg_len , _ , _ , _ ) _ -> let buffer = Bytes . create ( msg_len - header_length ) header_length in Lwt_io . read_into_exactly mux_ic buffer 0 ( msg_len - header_length ) header_length >> match event_cb with | None -> start_listening ( ) | Some g -> g ( parse_reply buffer ) buffer >>= start_listening in Lwt_io . read_into_exactly mux_ic buffer 0 ( msg_len - header_length ) header_length >> match event_cb with | None -> start_listening ( ) | Some g -> g ( parse_reply buffer ) buffer >>= start_listening end end |
module Relay = struct type action = Shutdown | Reload type tunnel = { udid : string ; name : string option ; forwarding : forward list ; } [ @@ deriving of_yojson ] of_yojson and forward = { local_port : int ; device_port : int ; } type exn += Client_closed | Mapping_file_error of string let relay_lock = Lwt_mutex . create ( ) let ( running_servers , mapping_file , relay_timeout , lazy_exceptions , tunnels_created , tunnel_timeouts , unix_exn_exit_program ) unix_exn_exit_program = Hashtbl . create 24 , ref " " , ref None , ref 0 , ref 0 , ref 0 , ref false let status_server port = P . sprintf " http :// 127 . 0 . 0 . 1 :% d " port |> Uri . of_string let relay_pid ( ) = let open_pid_file = open_in pid_file in let target_pid = input_line open_pid_file |> int_of_string in close_in open_pid_file ; target_pid let close_chans ( ic , oc ) oc ( ) = Lwt_io . close ic >> Lwt_io . close oc let timeout_task ~ after_timeout n = let t = fst ( Lwt . task ( ) ) in let timeout = ( fun ( ) -> Lwt . cancel t ; after_timeout ( ) |> Lwt . ignore_result ) ignore_result |> Lwt_timeout . create n in Lwt_timeout . start timeout ; Lwt . on_cancel t ( fun ( ) -> Lwt_timeout . stop timeout ) timeout ; t let timeout_stream ~ after_timeout ~ read_timeout stream = ( fun ( ) -> Lwt . pick [ Lwt_stream . get stream ; timeout_task ~ after_timeout read_timeout ] read_timeout ) read_timeout |> Lwt_stream . from let echo ic oc = Lwt_io . read_chars ic |> fun hook_in -> Lwt_stream . peek hook_in >>= function | None -> Lwt . fail Client_closed | _ -> hook_in |> ( match ! relay_timeout with | None -> id | Some read_timeout -> timeout_stream ~ after_timeout ( : close_chans ( ic , oc ) oc ) oc ~ read_timeout ) read_timeout |> Lwt_io . write_chars oc let load_mappings file_name = Lwt_io . lines_of_file file_name |> Lwt_stream . to_list >|= fun lines -> lines |> List . map ~ f : String . trim |> List . filter ~ f ( : fun line -> if line <> " " && line [ . 0 ] 0 <> ' # ' then true else false ) false |> String . concat ~ sep " :\ n " |> fun data -> Yojson ( . ( try Safe . from_string data with Json_error s -> raise ( Mapping_file_error s ) s ) s |> fun should_be_array -> ( try Safe . Util . to_list should_be_array with | Safe . Util . Type_error ( e , _ ) _ -> let msg = P . sprintf " Error : % s HINT : Be sure mapping file consists of \ a single JSON array of objects , see man page for examples " e in raise ( Mapping_file_error msg ) msg ) msg |> List . map ~ f ( : fun record -> ( lazy record , tunnel_of_yojson record ) record ) record |> List . map ~ f ( : function | ( _ , Result . Ok tunnel ) tunnel -> tunnel | ( need_it , Result . Error r ) r -> let error_msg = ( ( Lazy . force need_it ) need_it |> Safe . pretty_to_string ) pretty_to_string |> P . sprintf " Check this needed field : % s , Original Json : % s " r in raise ( Mapping_file_error error_msg ) error_msg ) error_msg |> fun tunnels -> let t = Hashtbl . create ( List . length tunnels ) tunnels in tunnels |> List . iter ~ f ( : fun tunnel -> Hashtbl . add t ~ key : tunnel . udid ~ data : tunnel ) tunnel ; t ) t let do_tunnel ( udid , ( device_id , tunnels ) tunnels ) tunnels = begin tunnels . forwarding |> Lwt_list . map_p ( fun { local_port ; device_port } device_port -> let open Protocol in let server_address = Unix ( . ADDR_INET ( inet_addr_loopback , local_port ) local_port ) local_port in Lwt_io . establish_server server_address begin fun ( tcp_ic , tcp_oc ) tcp_oc -> Lwt_io . with_connection usbmuxd_address begin fun ( mux_ic , mux_oc ) mux_oc -> let msg = connect_message ~ device_id ~ device_port in write_header ~ total_len ( : msg_length msg ) msg mux_oc >> Lwt_io . write_from_string_exactly mux_oc msg 0 ( String . length msg ) msg >> read_header mux_ic >>= fun ( msg_len , _ , _ , _ ) _ -> let buffer = Bytes . create ( msg_len - header_length ) header_length in Lwt_io . read_into_exactly mux_ic buffer 0 ( msg_len - header_length ) header_length >> match parse_reply buffer with | Result Success -> tunnels_created := ! tunnels_created + 1 ; P . sprintf " Tunneling . Udid : % s Local Port : % d Device Port : % d \ Device_id : % d " udid local_port device_port device_id |> Logging . log ` tunnel ; Lwt . catch ( fun ( ) -> echo tcp_ic mux_oc <&> echo mux_ic tcp_oc >> Lwt . return ( P . sprintf " Finished Tunneling . Udid : % s Port : % d Device Port : % d \ Device_id : % d " udid local_port device_port device_id |> Logging . log ` tunnel ) tunnel ) tunnel ( function | Client_closed -> Logging . log ` tunnel " Client closed with an exception " |> close_chans ( mux_ic , mux_oc ) mux_oc >>= close_chans ( tcp_ic , tcp_oc ) tcp_oc | otherwise -> Lwt . fail otherwise ) otherwise | Result Device_requested_not_connected -> P . sprintf " Tunneling : Device requested was not connected . \ Udid : % s Device_id : % d " udid device_id |> Logging . log ` misc |> Lwt . return | Result Port_requested_not_available -> P . sprintf " Tunneling . Port requested , % d , wasn ' t available . \ Udid : % s Port : % d Device_id : % d " device_port udid local_port device_id |> Logging . log ` misc |> Lwt . return | _ -> Lwt . return_unit end >>= close_chans ( tcp_ic , tcp_oc ) tcp_oc |> Lwt . ignore_result end |> Lwt . return ) return >>= fun servers -> ( fun ( ) -> Lwt . return ( Hashtbl . add running_servers ~ key : device_id ~ data : servers ) servers ) servers |> Lwt_mutex . with_lock relay_lock end |> Lwt . ignore_result let complete_shutdown ( ) = running_servers |> Hashtbl . iter ~ f ( : fun ~ key : _ ~ data -> List . iter ~ f : Lwt_io . shutdown_server data ) data ; P . sprintf " Completed shutting down % d servers " ( Hashtbl . length running_servers ) running_servers |> Logging . log ` misc ; Hashtbl . reset running_servers let ( ) = Logging ( . Unix ( . Lwt . async_exception_hook := function | Lwt . Canceled -> tunnel_timeouts := ! tunnel_timeouts + 1 ; log ` misc " A tunnel connection timed out " | Unix_error ( ENOTCONN , _ , _ ) _ -> log ` misc " Connection refused " | Unix_error ( EADDRINUSE , _ , _ ) _ -> log ` misc " Check if already running tunneling relay , probably are " | CamlinternalLazy . Undefined -> lazy_exceptions := ! lazy_exceptions + 1 ; ( " Safe to ignore ) ignore OCaml lazy value exception from TCP tunneling " |> log ` misc | Unix_error ( Unix_errore , _ , _ ) _ -> error_message e |> P . sprintf " Unix based error : % s " |> log ` misc ; if not ! unix_exn_exit_program then exit 9 | exn -> " Please report , this is an unhandled async exception ( A bug ) bug " |> log ( ` exn exn ) exn ; exit 1 ) ) let device_alist_of_hashtable ~ device_mapping ~ devices = devices |> Hashtbl . fold ~ init [ ] : ~ f ( : fun ~ key : device_id ~ data : udid_value accum -> try ( udid_value , ( device_id , Hashtbl . find device_mapping udid_value ) udid_value ) udid_value :: accum with Not_found -> P . sprintf " Device with udid : % s expected but wasn ' t connected " udid_value |> Logging . log ` misc ; accum ) accum let start_status_server ~ device_mapping ~ devices ~ port init = let device_list = ref init in let start_time = Unix . gettimeofday ( ) in let callback _ _ _ = let uptime = Unix . gettimeofday ( ) . - start_time in let body = let tunnels_data = List . map ~ f ( : fun ( udid , ( device_id , { name ; forwarding ; _ } _ ) _ ) _ -> ( ` Assoc [ ( " Nickname " , ` String ( match name with None -> " < Unnamed " > | Some s -> s ) s ) s ; ( " Usbmuxd assigned iDevice ID " , ` Int device_id ) device_id ; ( " iDevice UDID " , ` String udid ) udid ; ( " Tunnels " , ( ` List ( forwarding |> List . map ~ f ( : fun tunnel -> ( ` Assoc [ ( " Local Port " , ` Int tunnel . local_port ) local_port ; ( " Device Port " , ` Int tunnel . device_port ) device_port ] device_port : B . json ) json ) json ) json ) json ) json ] json : B . json ) json ) json ! device_list in ` Assoc [ ( " uptime " , ` Float uptime ) uptime ; ( " async_exceptions_count " , ` Int ! lazy_exceptions ) lazy_exceptions ; ( " tunnels_created_count " , ` Int ! tunnels_created ) tunnels_created ; ( " tunnel_timeouts " , ` Int ! tunnel_timeouts ) tunnel_timeouts ; ( " mappings_file " , ` String ! mapping_file ) mapping_file ; ( " status_data " , ` List tunnels_data ) tunnels_data ] |> B . to_string in Cohttp_lwt_unix . Server . respond_string ~ status ` : OK ~ body ( ) in let server = Cohttp_lwt_unix . Server . make ~ callback ( ) in Lwt . async begin fun ( ) -> let shutdown_and_prune d = try ( Hashtbl . find running_servers d ) d |> List . iter ~ f : Lwt_io . shutdown_server ; Hashtbl . remove running_servers d with Not_found -> ( ) in let spin_up_tunnel device_udid new_id = try let ( _ , tunnels ) tunnels = List . assoc device_udid ! device_list in ( device_udid , ( new_id , tunnels ) tunnels ) tunnels |> do_tunnel with Not_found -> P . sprintf " relay can ' t create tunnel for device udid : % s " device_udid |> Logging . log ` misc in Protocol ( . create_listener ~ event_cb : begin function | Event Attached { serial_number = s ; connection_speed = _ ; connection_type = _ ; product_id = _ ; location_id = _ ; device_id = d ; } -> P . sprintf " Device % d with serial number : % s connected " d s |> Logging . log ` plugged_inout ; if not ( Hashtbl . mem devices d ) d then ( Hashtbl . add devices ~ key : d ~ data : s ; device_list := device_alist_of_hashtable ~ device_mapping ~ devices ; spin_up_tunnel s d |> Lwt . return ) return else Lwt . return ( ) | Event Detached d -> P . sprintf " Device % d disconnected " d |> Logging . log ` plugged_inout ; ( shutdown_and_prune d ; Hashtbl . remove devices d ; device_list := device_alist_of_hashtable ~ device_mapping ~ devices ) devices |> Lwt . return | _ -> Lwt . return_unit end ( ) ) end ; ( fun ( ) -> Cohttp_lwt_unix . Server . create ~ mode ( ` : TCP ( ` Port port ) port ) port server ) server |> Lwt . async let rec make_tunnels ( ? ignore_unix_exn = false ) false ( ? log_opts ( =! Logging . logging_opts ) logging_opts ) logging_opts ? stats_server ? tunnel_timeout ~ device_map = ( fun ( ) -> if Hashtbl . length running_servers <> 0 then Hashtbl . length running_servers |> Lwt_io . printlf " Exited with % d still running ; this is a bug . " else Lwt . return_unit ) return_unit |> Lwt_main . at_exit ; unix_exn_exit_program := ignore_unix_exn ; Logging . logging_opts := log_opts ; Lwt_io . set_default_buffer_size 32768 ; relay_timeout := tunnel_timeout ; ( mapping_file := device_map ) device_map |> handle_signals ; load_mappings ! mapping_file >>= fun device_mapping -> let devices = Hashtbl . create 24 in try % lwt Lwt . pick [ Lwt_unix . timeout 1 . 0 ; Protocol ( . create_listener ~ event_cb : begin function | Event Attached { serial_number = s ; connection_speed = _ ; connection_type = _ ; product_id = _ ; location_id = _ ; device_id = d ; } -> Hashtbl . add devices ~ key : d ~ data : s |> Lwt . return | Event Detached d -> Hashtbl . remove devices d |> Lwt . return | _ -> Lwt . return_unit end ( ) ) ] with Lwt_unix . Timeout -> let device_alist = device_alist_of_hashtable ~ device_mapping ~ devices in begin match stats_server with | None -> Logging . log ` misc " Did not create a status server " | Some port -> start_status_server ~ device_mapping ~ devices ~ port device_alist ; end ; let rec forever ( ) = fst ( Lwt . wait ( ) ) >>= forever in device_alist |> Lwt_list . iter_p ( Lwt_preemptive . detach do_tunnel ) do_tunnel >> forever ( ) and do_restart ( ) = if Sys . file_exists ! mapping_file then begin complete_shutdown ( ) ; Logging . log ` misc " Restarting relay with reloaded mappings " ; make_tunnels ~ ignore_unix_exn :! unix_exn_exit_program ~ log_opts :! Logging . logging_opts ? stats_server : None ? tunnel_timeout : None ~ device_map :! mapping_file |> Lwt . ignore_result end else P . sprintf " Original mapping file % s does not exist \ anymore , not reloading " ! mapping_file |> Logging . log ` misc and handle_signals ( ) = Sys ( [ . signal sigpipe Signal_ignore ; signal sigusr1 ( Signal_handle ( fun _ -> do_restart ( ) ) ) ; signal sigusr2 ( Signal_handle begin fun _ -> let relay_count = Hashtbl . length running_servers in complete_shutdown ( ) ; P . sprintf " Shutdown % d relays , exiting now " relay_count |> Logging . log ` misc ; exit 0 end ) end ; signal sigterm ( Signal_handle ( fun _ -> complete_shutdown ( ) ; exit 0 ) 0 ) 0 ] ) |> List . iter ~ f : ignore let perform action = Unix ( . try let target_pid = relay_pid ( ) in Sys ( . match action with Reload -> sigusr1 | Shutdown -> sigusr2 ) sigusr2 |> kill target_pid ; exit 0 with Unix_error ( Unix_errorEPERM , _ , _ ) _ -> ( match action with Reload -> " Couldn ' t reload mapping , permissions error " | Shutdown -> " Couldn ' t shutdown cleanly , \ permissions error ) " |> Logging . log ` misc ; exit 2 | Unix_error ( Unix_errorESRCH , _ , _ ) _ -> P . sprintf " Are you sure relay was running already ? \ Pid in % s did not match running relay " pid_file |> Logging . log ` misc ; exit 3 ) let status ~ port = Cohttp_lwt_unix . Client . get ( status_server port ) port >>= fun ( _ , body ) body -> Cohttp_lwt_body . to_string body >|= Yojson . Basic . from_string end |
type t = { id : Common . id ; bio : string mc_option ; birthday : Common . calendar_us_date mc_option ; email : string mc_option ; first_name : string mc_option ; gender : string mc_option ; is_verified : bool mc_option ; last_name : string mc_option ; link : Common . uri mc_option ; locale : string mc_option ; name : string ; name_format : string mc_option ; third_party_id : Common . id mc_option ; username : string mc_option ; verified : bool mc_option ; website : Common . uri mc_option ; |
module Home = struct end end end type t = { id : Common . id ; name : string ; category : string mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end | Application [ @ conv . as " application " ] | Event [ @ conv . as " event " ] end end let err type ' = let msg = Printf . sprintf " Expected object , found % s " type ' in ` Error ( ` Primitive_decoding_failure msg , j , trace ) in let t_of_json_exn ? trace j = match t_of_json ? trace j with | ` Ok t -> t | ` Error e -> raise ( Common . Meta_conv_error e ) let json_of_t t = Json . Object ( t |> List . map ( fun ( k , v ) -> string_of_int k , MessageTag . json_of_t v ) ) end end module Comments after : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end end end end after : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end after : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end | Event [ @ conv . as " event " ] | Note [ @ conv . as " note " ] end end module StructuredLocation = struct type t = { country : string mc_option ; city : string mc_option ; longitude : float ; zip : string mc_option ; state : string mc_option ; street : string mc_option ; located_in : Common . id mc_option ; latitude : float ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end type t = | Simple of string | Structured of StructuredLocation . t let t_of_json ? trace = function | Json . String s -> ` Ok ( Simple ( s ) ) | Json . Number n -> ` Ok ( Simple ( n ) ) | Json . Array _ -> ` Ok ( Simple ( " " ) ) | Json . Bool b -> ` Ok ( Simple ( string_of_bool b ) ) | Json . Null -> ` Ok ( Simple ( " " ) ) | o -> ( match StructuredLocation . t_of_json ? trace o with | ` Ok t -> ` Ok ( Structured ( t ) ) | ` Error e -> ` Error e ) let t_of_json_exn ? trace = function | Json . String s -> Simple ( s ) | Json . Number n -> Simple ( n ) | Json . Array _ -> Simple ( " " ) | Json . Bool b -> Simple ( string_of_bool b ) | Json . Null -> Simple ( " " ) | o -> Structured ( StructuredLocation . t_of_json_exn ? trace o ) let json_of_t = function | Simple l -> Json . String ( l ) | Structured l -> ( StructuredLocation . json_of_t l ) end end module Post = struct type t = { created_time : Common . calendar_iso8601 ; from : Profile . t ; id : Common . id ; message : string mc_option ; updated_time : Common . calendar_iso8601 ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end module ReadResponse : Common . PagedResponse with type data = Post . t = struct type data = Post . t [ @@ deriving conv { json } ] after : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end end |
module Feed = struct module ReadResponse : Common . PagedResponse with type data = Home . Post . t = struct type data = Home . Post . t [ @@ deriving conv { json } ] type cursors = { after : string ; before : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; cursors : cursors mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end } end end end |
module Posts = struct let read_permissions = [ " read_stream " ; ] module ReadResponse : Common . PagedResponse with type data = Home . Post . t = struct type data = Home . Post . t [ @@ deriving conv { json } ] type cursors = { after : string ; before : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; cursors : cursors mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end end |
module Friends = struct let read_permissions = [ " user_friends " ] module ReadResponse : Common . PagedResponse with type data = t = struct type data = t [ @@ deriving conv { json } ] type cursors = { after : string ; before : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; cursors : cursors mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end end |
let section = Lwt_log . Section . make " ocsigen : ext : userconf " |
let err_500 = Ocsigen_extensions . Ext_stop_site ( Ocsigen_cookie_map . empty , ` Internal_server_error ) Internal_server_error |
let handle_parsing_error { Ocsigen_extensions . request_info ; _ } _ = function | Ocsigen_extensions . Error_in_config_file s -> Lwt_log . ign_error_f ~ section " Syntax error in userconf configuration file for url % s : % s " ( Uri . to_string ( Ocsigen_request . uri request_info ) request_info ) request_info s ; Lwt . return err_500 | Ocsigen_extensions . Error_in_user_config_file s -> Lwt_log . ign_error_f ~ section " Unauthorized option in user configuration for url % s : % s " ( Uri . to_string ( Ocsigen_request . uri request_info ) request_info ) request_info s ; Lwt . return err_500 | e -> Lwt . fail e |
let subresult new_req user_parse_site conf previous_err req req_state = Ocsigen_extensions . Ext_sub_result ( fun cookies_to_set _rs -> Lwt . catch ( fun ( ) -> user_parse_site conf cookies_to_set ( Ocsigen_extensions . Req_not_found ( previous_err , new_req ) new_req ) new_req >>= fun ( answer , cookies ) cookies -> let rec aux ( ( answer , cts ) cts as r ) r = match answer with | Ocsigen_extensions . Ext_sub_result sr -> sr cookies_to_set req_state >>= aux | Ocsigen_extensions . Ext_continue_with ( { Ocsigen_extensions . request_config ; _ } _ , cookies , err ) err -> Lwt . return ( Ocsigen_extensions . Ext_continue_with ( { req with Ocsigen_extensions . request_config } request_config , cookies , err ) , cts ) | Ocsigen_extensions . Ext_found_continue_with r -> Lwt . return ( Ocsigen_extensions . Ext_found_continue_with ( fun ( ) -> r ( ) >|= fun ( r , { Ocsigen_extensions . request_config ; _ } _ ) _ -> r , { req with Ocsigen_extensions . request_config } request_config ) request_config , cts ) | _ -> Lwt . return r in aux ( answer , cookies ) cookies ) cookies ( fun e -> handle_parsing_error req e >>= fun answer -> Lwt . return ( answer , Ocsigen_cookie_map . empty ) empty ) empty ) empty |
let conf_to_xml conf = try [ Xml . parse_file conf ] conf with | Sys_error _ -> raise NoConfFile | Xml . Error ( s , loc ) loc -> let begin_char , end_char = Xml . range loc and line = Xml . line loc in raise ( Ocsigen_extensions . Error_in_config_file ( Printf . sprintf " % s , line % d , characters % d -% d " ( Xml . error_msg s ) s line begin_char end_char ) end_char ) end_char |
let gen hostpattern sitepath ( regexp , conf , url , prefix , localpath ) localpath = function | Ocsigen_extensions . Req_found _ -> Lwt . return Ocsigen_extensions . Ext_do_nothing | Ocsigen_extensions . Req_not_found ( previous_err , ( { Ocsigen_extensions . request_info ; request_config } request_config as req ) req ) req as req_state -> ( let path = Ocsigen_request . sub_path_string request_info in match Ocsigen_lib . Netstring_pcre . string_match regexp path 0 with | None -> Lwt . return ( Ocsigen_extensions . Ext_next previous_err ) previous_err | Some _ -> ( try Lwt_log . ign_info ~ section " Using user configuration " ; let conf0 = Ocsigen_extensions . replace_user_dir regexp conf path in let uri = Uri . of_string ( Ocsigen_lib . Netstring_pcre . global_replace regexp url path ) path and prefix = Ocsigen_lib . Netstring_pcre . global_replace regexp prefix path and userconf_options = { Ocsigen_extensions . localfiles_root = Ocsigen_extensions . replace_user_dir regexp localpath path } and conf = conf_to_xml conf0 in let user_parse_host = Ocsigen_extensions . parse_config_item ( Some userconf_options ) userconf_options hostpattern request_config in let user_parse_site = Ocsigen_extensions . make_parse_config ( sitepath @ [ prefix ] prefix ) prefix user_parse_host and req = { req with Ocsigen_extensions . request_info = Ocsigen_request . update ~ uri request_info } in Lwt . return ( subresult req user_parse_site conf previous_err req req_state ) req_state with | Ocsigen_extensions . NoSuchUser | NoConfFile | Unix . Unix_error ( Unix . EACCES , _ , _ ) _ | Unix . Unix_error ( Unix . ENOENT , _ , _ ) _ -> Lwt . return ( Ocsigen_extensions . Ext_next previous_err ) previous_err | e -> handle_parsing_error req e ) e ) e |
let parse_config _ hostpattern _ path _ _ config_elem = let regexp = ref None in let conf = ref None in let url = ref None in let prefix = ref None in let localpath = ref None in Ocsigen_extensions ( . Configuration . process_element ~ in_tag " : host " ~ other_elements ( : fun t _ _ -> raise ( Bad_config_tag_for_extension t ) t ) t ~ elements : [ Configuration . element ~ name " : userconf " ~ attributes : [ Configuration . attribute ~ name " : regexp " ~ obligatory : true ( fun s -> let s = Ocsigen_lib . Netstring_pcre . regexp ( " " ^ ^ s ^ ) " " $ in regexp := Some s ) s ; Configuration . attribute ~ name " : conf " ~ obligatory : true ( fun s -> let s = Ocsigen_extensions . parse_user_dir s in conf := Some s ) s ; Configuration . attribute ~ name " : url " ~ obligatory : true ( fun s -> url := Some s ) s ; Configuration . attribute ~ name " : prefix " ~ obligatory : true ( fun s -> prefix := Some s ) s ; Configuration . attribute ~ name " : localpath " ~ obligatory : true ( fun s -> let s = Ocsigen_extensions . parse_user_dir s in localpath := Some s ) s ] ( ) ] config_elem ) config_elem ; let info = match ! regexp , ! conf , ! url , ! prefix , ! localpath with | Some r , Some t , Some u , Some p , Some p ' -> r , t , u , p , p ' | _ -> Ocsigen_extensions . badconfig " Missing attributes for < userconf " > in gen hostpattern path info |
let ( ) = Ocsigen_extensions . register ~ name " : userconf " ~ fun_site : parse_config ( ) |
let ( ) |> x f = f x ; ; |
let allocate how_many str_len = let l = ref [ ] in for _i = 1 to how_many do let s = Bytes . create str_len in l := s ( ::! l ) ; done ; ! l |
let allocate_a_lot ( ) = allocate 499 99991 |
let allocate_many_small ( ) = allocate 99991 499 |
module LuaBookDir = struct let readdir ls = let handle : Unix . dir_handle = let w = Lua . touserdata ls 1 in match w with | Some ` Userdata h -> h | _ -> failwith " Dir handle expected " ! in try Lua . pushstring ls ( Unix . readdir handle ) ; 1 with End_of_file -> 0 let dir_gc ls = let handle : Unix . dir_handle = let w = Lua . touserdata ls 1 in match w with | Some ` Userdata h -> h | _ -> failwith " Dir handle expected " ! in Unix . closedir handle ; 0 let ocaml_handle_gc h = Unix . closedir h let opendir ls = let path = LuaL . checkstring ls 1 in let handle = try Unix . opendir path with Unix . Unix_error ( err , _ , _ ) -> LuaL . error ls " cannot open % s : % s " path ( Unix . error_message err ) in Lua . newuserdata ls handle ; LuaL . getmetatable ls " LuaBook . dir " ; Lua . setmetatable ls ( - 2 ) |> ignore ; 1 let allocate_ocaml_data ls = let data1 = allocate_many_small ( ) in let data2 = allocate_a_lot ( ) in Lua . newuserdata ls data1 ; Lua . newuserdata ls data2 ; 1 let gc_compact _ls = Printf . printf " Calling Gc . compact 2 times from Lua . . . " ; %! Gc . compact ( ) ; Gc . compact ( ) ; Printf . printf " done !\ n " ; %! 0 let luaopen_dir ls = LuaL . newmetatable ls " LuaBook . dir " |> ignore ; Lua . pushstring ls " __gc " ; Lua . pushocamlfunction ls ( Lua . make_gc_function dir_gc ) ; Lua . settable ls ( - 3 ) |> ignore ; Lua . pushocamlfunction ls opendir ; Lua . setglobal ls " opendir " ; Lua . pushocamlfunction ls readdir ; Lua . setglobal ls " readdir " ; Lua . pushocamlfunction ls gc_compact ; Lua . setglobal ls " gc_compact " ; Lua . pushocamlfunction ls allocate_ocaml_data ; Lua . setglobal ls " allocate_ocaml_data " ; end ; ; |
let closure ( ) = let l1 = LuaL . newstate ( ) in LuaL . openlibs l1 ; LuaBookDir . luaopen_dir l1 ; LuaL . loadbuffer l1 " handle = opendir ( " " ) \/\ d = readdir ( handle ) end match Lua . pcall l1 0 0 0 with | Lua . LUA_OK -> ( ) | _err -> begin Printf . printf " % s \ n " %! ( Lua . tostring l1 ( - 1 ) |> Option . value ~ default " " ) ; : Lua . pop l1 1 ; failwith " FATAL ERROR " end ; ; |
let print_timings start_space start_wtime start_ptime = let end_ptime = Unix . times ( ) in let self_u = end_ptime . Unix . tms_utime . - start_ptime . Unix . tms_utime in let self_s = end_ptime . Unix . tms_stime . - start_ptime . Unix . tms_stime in let self = self_u . + self_s in let child_u = end_ptime . Unix . tms_cutime . - start_ptime . Unix . tms_cutime in let child_s = end_ptime . Unix . tms_cstime . - start_ptime . Unix . tms_cstime in let child = child_u . + child_s in let run_time = self . + child in let real_time = Unix . time ( ) . - start_wtime in let real_time_sec = int_of_float real_time in let real_time_min = real_time_sec / 60 in let real_time_sec = real_time_sec mod 60 in let real_time_hrs = real_time_min / 60 in let real_time_min = real_time_min mod 60 in let end_space = Gc . quick_stat ( ) in Printf . printf " Run time : % f sec \ n " %! run_time ; Printf . printf " Self : % f sec \ n " %! self ; Printf . printf " sys : % f sec \ n " %! self_u ; Printf . printf " user : % f sec \ n " %! self_s ; Printf . printf " Children : % f sec \ n " %! child ; Printf . printf " sys : % f sec \ n " %! child_u ; Printf . printf " user : % f sec \ n " %! child_s ; Printf . printf " GC : minor : % d \ n " %! ( end_space . Gc . minor_collections - start_space . Gc . minor_collections ) ; Printf . printf " major : % d \ n " %! ( end_space . Gc . major_collections - start_space . Gc . major_collections ) ; Printf . printf " compactions : % d \ n " %! ( end_space . Gc . compactions - start_space . Gc . compactions ) ; Printf . printf " Allocated : . % 1f words \ n " %! ( end_space . Gc . minor_words . + end_space . Gc . major_words . - start_space . Gc . minor_words . - start_space . Gc . major_words . - end_space . Gc . promoted_words . + start_space . Gc . promoted_words ) ; Printf . printf " Wall clock : . % 0f sec ( % 02d :% 02d :% 02d ) \ n " %! real_time real_time_hrs real_time_min real_time_sec ; if real_time > 0 . then Printf . printf " Load : . % 2f %%\ n " %! ( run_time . * 100 . 0 . / real_time ) ; ; |
let run func args = Gc . compact ( ) ; let start_space = Gc . quick_stat ( ) in let start_wtime = Unix . time ( ) in let start_ptime = Unix . times ( ) in let ret = try func args with e -> print_timings start_space start_wtime start_ptime ; raise e in print_timings start_space start_wtime start_ptime ; ret ; ; |
let test_duration = 60 . 0 . * 10 . 0 ; ; |
let time_start = Unix . gettimeofday ( ) ; ; |
let main ( ) = while Unix . gettimeofday ( ) < time_start . + test_duration do closure ( ) |> ignore ; Printf . printf " Calling Gc . compact from OCaml . . . " ; %! Gc . compact ( ) ; Printf . printf " done !\ n " ; %! done ; Gc . compact ( ) ; ; ; |
type upgrades = ( Int32 . t * Protocol_hash . t ) list |
let upgrades_encoding = let open Data_encoding in def " user_activated . upgrades " ~ title " : User activated upgrades " ~ description : " User activated upgrades : at given level , switch to given protocol . " ( list ( obj2 ( req " level " int32 ) ( req " replacement_protocol " Protocol_hash . encoding ) ) ) |
type protocol_overrides = ( Protocol_hash . t * Protocol_hash . t ) list |
let protocol_overrides_encoding = let open Data_encoding in def " user_activated . protocol_overrides " ~ title " : User activated protocol overrides " ~ description : " User activated protocol overrides : activate a protocol instead of \ another . " @@ list ( obj2 ( req " replaced_protocol " Protocol_hash . encoding ) ( req " replacement_protocol " Protocol_hash . encoding ) ) |
let ( ) = Data_encoding . Registration . register upgrades_encoding ; Data_encoding . Registration . register protocol_overrides_encoding |
let test_metadata_consistency ~ migrate_from ~ migrate_to = Test . register ~ __FILE__ ~ title " : metadata consistency " ~ tags [ " : rpc " ; " metadata " ; " migration " ] @@ fun ( ) -> let node = Node . create [ ] in let * ( ) = Node . config_init node [ ] in let migration_level = 3 in Node . Config_file . ( update node ( set_sandbox_network_with_user_activated_upgrades [ ( migration_level , migrate_to ) ] ) ) ; let * ( ) = Node . run node [ ] in let * ( ) = Node . wait_for_ready node in let * client = Client . ( init ~ endpoint ( : Node node ) ( ) ) in let * ( ) = Client . activate_protocol ~ protocol : migrate_from client in let * ( ) = repeat ( migration_level - 1 ) ( fun ( ) -> Client . bake_for client ) in let * non_migration_block = RPC . get_block_metadata ~ block ( : string_of_int ( migration_level - 1 ) ) client in let protocol = JSON . ( non_migration_block |-> " protocol " |> as_string ) in Log . info " checking consistency of block at level % d " ( migration_level - 1 ) ; Check . ( ( protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected protocol = % R , got % L " ) ; let next_protocol = JSON . ( non_migration_block |-> " next_protocol " |> as_string ) in Check . ( ( next_protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected next_protocol = % R , got % L " ) ; Log . info " checking consistency of block at level % d " migration_level ; let * migration_block = RPC . get_block_metadata ~ block ( : string_of_int migration_level ) client in let protocol = JSON . ( migration_block |-> " protocol " |> as_string ) in Check . ( ( protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected protocol = % R , got % L " ) ; let next_protocol = JSON . ( migration_block |-> " next_protocol " |> as_string ) in Check . ( ( next_protocol = Protocol . hash migrate_to ) string ~ error_msg " : expected next_protocol = % R , got % L " ) ; Log . info " checking consistency of block at level % d ( again ) " ( migration_level - 1 ) ; let * non_migration_block = RPC . get_block_metadata ~ block ( : string_of_int ( migration_level - 1 ) ) client in let protocol = JSON . ( non_migration_block |-> " protocol " |> as_string ) in Check . ( ( protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected protocol = % R , got % L " ) ; let next_protocol = JSON . ( non_migration_block |-> " next_protocol " |> as_string ) in Check . ( ( next_protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected next_protocol = % R , got % L " ) ; unit |
let register ~ migrate_from ~ migrate_to = test_metadata_consistency ~ migrate_from ~ migrate_to |
type t = { ua_family : string ; ua_major : string option ; ua_minor : string option ; ua_patch : string option ; os_family : string ; os_major : string option ; os_minor : string option ; os_patch : string option ; os_patch_minor : string option ; device_family : string ; device_brand : string option ; device_model : string option ; } |
let uaparser = User_agent_parser . init ( ) |
let parse s = let parsed = User_agent_parser . parse uaparser s in let open User_agent_parser in let open User_agent_parser . UAParser in let open User_agent_parser . OSParser in let open User_agent_parser . DeviceParser in { ua_family = parsed . ua . family ; ua_major = parsed . ua . major ; ua_minor = parsed . ua . minor ; ua_patch = parsed . ua . patch ; os_family = parsed . os . family ; os_major = parsed . os . major ; os_minor = parsed . os . minor ; os_patch = parsed . os . patch ; os_patch_minor = parsed . os . patch_minor ; device_family = parsed . device . family ; device_brand = parsed . device . brand ; device_model = parsed . device . model ; } |
let is_bot t = let is_google_bot ( ) = let regex = Str . regexp " Googlebot ( \\- Mobile \\|- Image \\|- Video \\|- News ) \\?\\| Feedfetcher - Google \\| Google - Test \\| Google - Site - Verification \\| Google \ Web \ Preview \\| AdsBot - Google ( \\- Mobile ) \\?\\| Mediapartners - Google \\| Google . */\\+/ web / snippet \\| GoogleProducer " in Str . string_match regex t . ua_family 0 in let is_generic_bot ( ) = let regex = Str . regexp [ " a - z0 - 9 \\- _ ] _ ( *\\ bot \\| crawler \\| archiver \\| transcoder \\| spider ) " \\ in Str . string_match regex t . ua_family 0 in if is_google_bot ( ) then true else if is_generic_bot ( ) then true else false |
module Poly = struct [ %% versioned module Stable = struct module V2 = struct type ( ' u , ' s ) ' s t = Signed_command of ' u | Parties of ' s [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest = Fn . id end module V1 = struct type ( ' u , ' s ) ' s t = Signed_command of ' u | Snapp_command of ' s [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest : _ t -> _ V2 . t = function | Signed_command x -> Signed_command x | Snapp_command _ -> failwith " Snapp_command " end end ] end end |
type ( ' u , ' s ) ' s t_ = ( ' u , ' s ) ' s Poly . Stable . Latest . t = | Signed_command of ' u | Parties of ' s |
module Gen_make ( C : Signed_command_intf . Gen_intf ) Gen_intf = struct let to_signed_command f = Quickcheck . Generator . map f ~ f ( : fun c -> Signed_command c ) c open C . Gen let payment ? sign_type ~ key_gen ? nonce ~ max_amount ~ fee_range ( ) = to_signed_command ( payment ? sign_type ~ key_gen ? nonce ~ max_amount ~ fee_range ( ) ) let payment_with_random_participants ? sign_type ~ keys ? nonce ~ max_amount ~ fee_range ( ) = to_signed_command ( payment_with_random_participants ? sign_type ~ keys ? nonce ~ max_amount ~ fee_range ( ) ) let stake_delegation ~ key_gen ? nonce ~ fee_range ( ) = to_signed_command ( stake_delegation ~ key_gen ? nonce ~ fee_range ( ) ) let stake_delegation_with_random_participants ~ keys ? nonce ~ fee_range ( ) = to_signed_command ( stake_delegation_with_random_participants ~ keys ? nonce ~ fee_range ( ) ) let sequence ? length ? sign_type a = Quickcheck . Generator . map ( sequence ? length ? sign_type a ) a ~ f ( : List . map ~ f ( : fun c -> Signed_command c ) c ) c end |
module Gen = Gen_make ( Signed_command ) Signed_command |
module Valid = struct [ %% versioned module Stable = struct module V2 = struct type t = ( Signed_command . With_valid_signature . Stable . V2 . t , Parties . Valid . Stable . V1 . t ) Poly . Stable . V2 . t [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest = Fn . id end end ] end module Gen = Gen_make ( Signed_command . With_valid_signature ) With_valid_signature end [ %% versioned |
module Stable = struct module V2 = struct type t = ( Signed_command . Stable . V2 . t , Parties . Stable . V1 . t ) t Poly . Stable . V2 . t [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest = Fn . id end end ] end |
module Zero_one_or_two = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = [ ` Zero | ` One of ' a | ` Two of ' a * ' a ] [ @@ deriving sexp , compare , equal , hash , yojson ] yojson end end ] end end |
module Verifiable = struct [ %% versioned module Stable = struct module V2 = struct type t = ( Signed_command . Stable . V2 . t , Parties . Verifiable . Stable . V1 . t ) Poly . Stable . V2 . t [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest = Fn . id end end ] end let fee_payer ( t : t ) t = match t with | Signed_command x -> Signed_command . fee_payer x | Parties p -> Party . Fee_payer . account_id p . fee_payer end |
let to_verifiable ( t : t ) t ~ ledger ~ get ~ location_of_account : Verifiable . t = let find_vk ( p : Party . t ) t = let ( ! ) x = Option . value_exn x in let id = Party . account_id p in Option . try_with ( fun ( ) -> let account : Account . t = ( ! get ledger ( ! location_of_account ledger id ) id ) id in ( ( !! account . zkapp ) zkapp . verification_key ) verification_key . data ) in match t with | Signed_command c -> Signed_command c | Parties { fee_payer ; other_parties ; memo } -> Parties { fee_payer ; other_parties = other_parties |> Parties . Call_forest . map ~ f ( : fun party -> ( party , find_vk party ) party ) party ; memo } |
let of_verifiable ( t : Verifiable . t ) t : t = match t with | Signed_command x -> Signed_command x | Parties p -> Parties ( Parties . of_verifiable p ) p |
let fee : t -> Currency . Fee . t = function | Signed_command x -> Signed_command . fee x | Parties p -> Parties . fee p |
let has_insufficient_fee t = Currency . Fee ( . fee t < minimum_fee ) minimum_fee |
let accounts_accessed ( t : t ) t = match t with | Signed_command x -> Signed_command . accounts_accessed x | Parties ps -> Parties . accounts_accessed ps |
let to_base58_check ( t : t ) t = match t with | Signed_command x -> Signed_command . to_base58_check x | Parties ps -> Parties . to_base58_check ps |
let fee_payer ( t : t ) t = match t with | Signed_command x -> Signed_command . fee_payer x | Parties p -> Parties . fee_payer p |
let nonce_exn ( t : t ) t = match t with | Signed_command x -> Signed_command . nonce x | Parties p -> Parties . nonce p |
let check ( t : t ) t : Valid . t option = match t with | Signed_command x -> Option . map ( Signed_command . check x ) x ~ f ( : fun c -> Signed_command c ) c | Parties p -> Some ( Parties ( p :> Parties . Valid . t ) t ) t |
let fee_token ( t : t ) t = match t with | Signed_command x -> Signed_command . fee_token x | Parties x -> Parties . fee_token x |
let valid_until ( t : t ) t = match t with | Signed_command x -> Signed_command . valid_until x | Parties _ -> Mina_numbers . Global_slot . max_value |
let forget_check ( t : Valid . t ) t : t = ( t :> t ) t |
let to_valid_unsafe ( t : t ) t = ` If_this_is_used_it_should_have_a_comment_justifying_it ( match t with | Parties x -> Parties x | Signed_command x -> let ( ` If_this_is_used_it_should_have_a_comment_justifying_it x ) x = Signed_command . to_valid_unsafe x in Signed_command x ) |
let filter_by_participant ( commands : t list ) list public_key = List . filter commands ~ f ( : fun user_command -> Core_kernel . List . exists ( accounts_accessed user_command ) user_command ~ f : ( Fn . compose ( Signature_lib . Public_key . Compressed . equal public_key ) public_key Account_id . public_key ) ) |
let weight : Stable . Latest . t -> int = function | Signed_command signed_command -> Signed_command . payload signed_command |> Signed_command_payload . weight | Parties parties -> Parties . weight parties |
let fee_per_wu ( user_command : Stable . Latest . t ) t : Currency . Fee_rate . t = Currency . Fee_rate . make_exn ( fee user_command ) user_command ( weight user_command ) user_command |
module Query_first_seen = [ % graphql { | query query ( $ hashes : [ String ] ) !! { user_commands ( user_commandswhere : { hash : { _in : $ hashes } hashes } hashes ) { hash @ bsDecoder ( bsDecoderfn : " Transaction_hash . of_base58_check_exn ) " first_seen @ bsDecoder ( bsDecoderfn : " Base_types . deserialize_optional_block_time ) " } } } ] | |
module Query_participants = [ % graphql { | query query ( $ hashes : [ String ] ) !! { user_commands ( user_commandswhere : { hash : { _in : $ hashes } hashes } hashes ) { receiver { id value @ bsDecoder ( fn : " Public_key . Compressed . of_base58_check_exn ) " } sender { id value @ bsDecoder ( fn : " Public_key . Compressed . of_base58_check_exn ) " } } } } ] | |
module Query = [ % graphql { | query query ( $ hash : String ) ! { user_commands ( user_commandswhere : { hash : { _eq : $ hash } hash } hash ) { fee @ bsDecoder ( fn : " Base_types . Fee . deserialize ) " hash @ bsDecoder ( bsDecoderfn : " Transaction_hash . of_base58_check_exn ) " memo @ bsDecoder ( bsDecoderfn : " Signed_command_memo . of_base58_check_exn ) " nonce @ bsDecoder ( fn : " Base_types . Nonce . deserialize ) " sender { value @ bsDecoder ( fn : " Public_key . Compressed . of_base58_check_exn ) " } receiver { value @ bsDecoder ( fn : " Public_key . Compressed . of_base58_check_exn ) " } typ @ bsDecoder ( fn : " Base_types . User_command_type . decode ) " amount @ bsDecoder ( fn : " Base_types . Amount . deserialize ) " first_seen @ bsDecoder ( bsDecoderfn : " Base_types . deserialize_optional_block_time ) " } } } ] | |
module Insert = [ % graphql { | mutation insert ( $ user_commands : [ user_commands_insert_input ] ) !! { insert_user_commands ( insert_user_commandsobjects : $ user_commands , on_conflict : { constraint : user_commands_hash_key , update_columns : first_seen } first_seen ) { returning { hash @ bsDecoder ( bsDecoderfn : " Transaction_hash . of_base58_check_exn ) " first_seen @ bsDecoder ( bsDecoderfn : " Base_types . deserialize_optional_block_time ) " } } } } ] | |
let parties_with_ledger ( ) = let open Quickcheck . Let_syntax in let open Signature_lib in let num_keypairs = ( Parties_generators . max_other_parties * 2 ) 2 + 2 in let keypairs = List . init num_keypairs ~ f ( : fun _ -> Keypair . create ( ) ) in let keymap = List . fold keypairs ~ init : Public_key . Compressed . Map . empty ~ f ( : fun map { public_key ; private_key } -> let key = Public_key . compress public_key in Public_key . Compressed . Map . add_exn map ~ key ~ data : private_key ) in let num_keypairs_in_ledger = Parties_generators . max_other_parties + 1 in let keypairs_in_ledger = List . take keypairs num_keypairs_in_ledger in let account_ids = List . map keypairs_in_ledger ~ f ( : fun { public_key ; _ } -> Account_id . create ( Public_key . compress public_key ) public_key Token_id . default ) in let % bind balances = let min_cmd_fee = Mina_compile_config . minimum_user_command_fee in let min_balance = Currency . Fee . to_int min_cmd_fee |> Int ( . + ) 500_000_000_000 |> Currency . Balance . of_int in let max_balance = match Currency . Balance . add_amount min_balance ( Currency . Amount . of_int 20_000_000_000_000 ) 20_000_000_000_000 with | None -> failwith " parties_with_ledger : overflow for max_balance " | Some bal -> bal in Quickcheck . Generator . list_with_length num_keypairs_in_ledger ( Currency . Balance . gen_incl min_balance max_balance ) max_balance in let account_ids_and_balances = List . zip_exn account_ids balances in let snappify_account ( account : Account . t ) t : Account . t = let permissions = { Permissions . user_default with edit_state = Permissions . Auth_required . Either ; send = Either ; set_delegate = Either ; set_permissions = Either ; set_verification_key = Either ; set_zkapp_uri = Either ; edit_sequence_state = Either ; set_token_symbol = Either ; increment_nonce = Either ; set_voting_for = Either } in let verification_key = Some With_hash . { data = Side_loaded_verification_key . dummy ; hash = Zkapp_account . dummy_vk_hash ( ) } in let zkapp = Some { Zkapp_account . default with verification_key } in { account with permissions ; zkapp } in let accounts = List . mapi account_ids_and_balances ~ f ( : fun ndx ( account_id , balance ) balance -> let account = Account . create account_id balance in if ndx mod 2 = 0 then account else snappify_account account ) in let fee_payer_keypair = List . hd_exn keypairs in let ledger = Ledger . create ~ depth : ledger_depth ( ) in List . iter2_exn account_ids accounts ~ f ( : fun acct_id acct -> match Ledger . get_or_create_account ledger acct_id acct with | Error err -> failwithf " parties : error adding account for account id : % s , error : % s . " @ ( Account_id . to_yojson acct_id |> Yojson . Safe . to_string ) to_string ( Error . to_string_hum err ) err ( ) | Ok ( ` Existed , _ ) _ -> failwithf " parties : account for account id already exists : % s . " @ ( Account_id . to_yojson acct_id |> Yojson . Safe . to_string ) to_string ( ) | Ok ( ` Added , _ ) _ -> ( ) ) ; let % bind parties = Parties_generators . gen_parties_from ~ fee_payer_keypair ~ keymap ~ ledger ( ) in return ( User_command . Parties parties , fee_payer_keypair , keymap , ledger ) ledger |
let sequence_parties_with_ledger ? length ( ) = let open Quickcheck . Let_syntax in let % bind length = match length with | Some n -> return n | None -> Quickcheck . Generator . small_non_negative_int in let merge_ledger source_ledger target_ledger = Ledger . iteri source_ledger ~ f ( : fun _ndx acct -> let acct_id = Account_id . create acct . public_key acct . token_id in match Ledger . get_or_create_account target_ledger acct_id acct with | Ok ( ` Added , _ ) _ -> ( ) | Ok ( ` Existed , _ ) _ -> failwith " Account already existed in target ledger " | Error err -> failwithf " Could not add account to target ledger : % s " ( Error . to_string_hum err ) err ( ) ) in let init_ledger = Ledger . create ~ depth : ledger_depth ( ) in let rec go parties_and_fee_payer_keypairs n = if n <= 0 then return ( List . rev parties_and_fee_payer_keypairs , init_ledger ) init_ledger else let % bind parties , fee_payer_keypair , keymap , ledger = parties_with_ledger ( ) in let parties_and_fee_payer_keypairs ' = ( parties , fee_payer_keypair , keymap ) keymap :: parties_and_fee_payer_keypairs in merge_ledger ledger init_ledger ; go parties_and_fee_payer_keypairs ' ( n - 1 ) 1 in go [ ] length |
let pk_to_public_key ~ context ( ` Pk pk ) pk = Public_key . Compressed . of_base58_check pk |> Result . map_error ~ f ( : fun _ -> Errors . create ~ context ` Public_key_format_not_valid ) |
let account_id ( ` Pk pk ) pk ( ` Token_id token_id ) token_id = { Account_identifier . address = pk ; sub_account = None ; metadata = Some ( Amount_of . Token_id . encode token_id ) token_id } |
let token_id_of_account ( account : Account_identifier . t ) t = let module Decoder = Amount_of . Token_id . T ( Result ) Result in Decoder . decode account . metadata |> Result . map ~ f ( : Option . value ~ default : Amount_of . Token_id . default ) default |> Result . ok |
module Op = struct type ' a t = { label : ' a ; related_to : ' a option } [ @@ deriving equal ] equal module T ( M : Monad . S2 ) S2 = struct let build ~ a_eq ~ plan ~ f = let open M . Let_syntax in let % map _ , rev_data = List . fold plan ~ init ( : M . return ( 0 , [ ] ) ) ~ f ( : fun macc op -> let open M . Let_syntax in let % bind i , acc = macc in let operation_identifier i = { Operation_identifier . index = Int64 . of_int_exn i ; network_index = None } in let related_operations = op . related_to |> Option . bind ~ f ( : fun relate -> List . findi plan ~ f ( : fun _ a -> a_eq relate a . label ) label ) |> Option . map ~ f ( : fun ( i , _ ) _ -> [ operation_identifier i ] ) in let % map a = f ~ related_operations ~ operation_identifier ( : operation_identifier i ) i op in ( i + 1 , a :: acc ) acc ) in List . rev rev_data end module Ident2 = struct type ( ' a , ' e ) ' e t = ' a module T = struct type ( ' a , ' e ) ' e t = ' a let map = ` Define_using_bind let return a = a let bind a ~ f = f a end include Monad . Make2 ( T ) T end include T ( Ident2 ) Ident2 end |
module Kind = struct type t = [ ` Payment | ` Delegation ] [ @@ deriving yojson , equal , sexp , compare ] compare end |
module Account_creation_fees_paid = struct type t = | By_no_one | By_fee_payer of Unsigned_extended . UInt64 . t | By_receiver of Unsigned_extended . UInt64 . t [ @@ deriving equal , to_yojson , sexp , compare ] compare end |
module Failure_status = struct type t = [ ` Applied of Account_creation_fees_paid . t | ` Failed of string ] [ @@ deriving equal , to_yojson , sexp , compare ] compare end |
type t = { kind : Kind . t ; fee_payer : [ ` Pk of string ] ; source : [ ` Pk of string ] ; receiver : [ ` Pk of string ] ; fee_token : [ ` Token_id of string ] ; token : [ ` Token_id of string ] ; fee : Unsigned_extended . UInt64 . t ; nonce : Unsigned_extended . UInt32 . t ; amount : Unsigned_extended . UInt64 . t option ; valid_until : Unsigned_extended . UInt32 . t option ; memo : string option ; hash : string ; failure_status : Failure_status . t option } |
module Partial = struct type t = { kind : Kind . t ; fee_payer : [ ` Pk of string ] ; source : [ ` Pk of string ] ; receiver : [ ` Pk of string ] ; fee_token : [ ` Token_id of string ] ; token : [ ` Token_id of string ] ; fee : Unsigned_extended . UInt64 . t ; amount : Unsigned_extended . UInt64 . t option ; valid_until : Unsigned_extended . UInt32 . t option ; memo : string option } [ @@ deriving to_yojson , sexp , compare , equal ] equal module Reason = Errors . Partial_reason let to_user_command_payload : t -> nonce : Unsigned_extended . UInt32 . t -> ( Signed_command . Payload . t , Errors . t ) t Result . t = fun t ~ nonce -> let open Result . Let_syntax in let % bind fee_payer_pk = pk_to_public_key ~ context " : Fee payer " t . fee_payer in let % bind source_pk = pk_to_public_key ~ context " : Source " t . source in let % bind receiver_pk = pk_to_public_key ~ context " : Receiver " t . receiver in let % bind memo = match t . memo with | Some memo -> ( try Ok ( Signed_command_memo . create_from_string_exn memo ) memo with _ -> Error ( Errors . create ` Memo_invalid ) Memo_invalid ) | None -> Ok Signed_command_memo . empty in let % map body = match t . kind with | ` Payment -> let % map amount = Result . of_option t . amount ~ error : ( Errors . create ( ` Operations_not_valid [ Errors . Partial_reason . Amount_not_some ] ) ) in let payload = { Payment_payload . Poly . source_pk ; receiver_pk ; amount = Amount_currency . of_uint64 amount } in Signed_command . Payload . Body . Payment payload | ` Delegation -> let payload = Stake_delegation . Set_delegate { delegator = source_pk ; new_delegate = receiver_pk } in Result . return @@ Signed_command . Payload . Body . Stake_delegation payload in Signed_command . Payload . create ~ fee ( : Fee_currency . of_uint64 t . fee ) fee ~ fee_payer_pk ~ nonce ~ body ~ memo ~ valid_until : ( Option . map ~ f : Mina_numbers . Global_slot . of_uint32 t . valid_until ) valid_until end |
let forget ( t : t ) t : Partial . t = { kind = t . kind ; fee_payer = t . fee_payer ; source = t . source ; receiver = t . receiver ; fee_token = t . fee_token ; token = t . token ; fee = t . fee ; amount = t . amount ; valid_until = t . valid_until ; memo = t . memo } |
let remember ~ nonce ~ hash t = { kind = t . kind ; fee_payer = t . fee_payer ; source = t . source ; receiver = t . receiver ; fee_token = t . fee_token ; token = t . token ; fee = t . fee ; amount = t . amount ; valid_until = t . valid_until ; memo = t . memo ; hash ; nonce ; failure_status = None } |
let of_operations ? memo ? valid_until ( ops : Operation . t list ) list : ( Partial . t , Partial . Reason . t ) t Validation . t = let find_kind k ( ops : Operation . t list ) list = let name = Operation_types . name k in List . find ops ~ f ( : fun op -> String . equal op . Operation . _type name ) name |> Result . of_option ~ error [ : Partial . Reason . Can ' t_find_kind name ] in let module V = Validation in let open V . Let_syntax in let open Partial . Reason in let payment = let % map ( ) = if Int . equal ( List . length ops ) ops 3 then V . return ( ) else V . fail Length_mismatch and account_a = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Payment_source_dec ops and { account = account ' ; _ } = find_kind ` Fee_payment ops in match ( account , account ' ) account ' with | Some x , Some y when Account_identifier . equal x y -> V . return x | Some _ , Some _ -> V . fail Fee_payer_and_source_mismatch | None , _ | _ , None -> V . fail Account_not_some and token = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Payment_source_dec ops in match account with | Some account -> ( match token_id_of_account account with | None -> V . fail Incorrect_token_id | Some token -> V . return ( ` Token_id token ) token ) | None -> V . fail Account_not_some and fee_token = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Fee_payment ops in match account with | Some account -> ( match token_id_of_account account with | Some token_id -> V . return ( ` Token_id token_id ) token_id | None -> V . fail Incorrect_token_id ) | None -> V . fail Account_not_some and account_b = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Payment_receiver_inc ops in Result . of_option account ~ error [ : Account_not_some ] and ( ) = if List . for_all ops ~ f ( : fun op -> let p = Option . equal String . equal op . status in p None || p ( Some ) " " ) then V . return ( ) else V . fail Status_not_pending and payment_amount_x = let open Result . Let_syntax in let % bind { amount ; _ } = find_kind ` Payment_source_dec ops and { amount = amount ' ; _ } = find_kind ` Payment_receiver_inc ops in match ( amount , amount ' ) amount ' with | Some x , Some y when Amount . equal ( Amount_of . negated x ) x y -> V . return y | Some _ , Some _ -> V . fail Amount_inc_dec_mismatch | None , _ | _ , None -> V . fail Amount_not_some and payment_amount_y = let open Result . Let_syntax in let % bind { amount ; _ } = find_kind ` Fee_payment ops in match amount with | Some x -> V . return ( Amount_of . negated x ) x | None -> V . fail Amount_not_some in { Partial . kind = ` Payment ; fee_payer = ` Pk account_a . address ; source = ` Pk account_a . address ; receiver = ` Pk account_b . address ; fee_token ; token ; fee = Unsigned . UInt64 . of_string payment_amount_y . Amount . value ; amount = Some ( Unsigned . UInt64 . of_string payment_amount_x . Amount . value ) value ; valid_until ; memo } in let delegation = let % map ( ) = if Int . equal ( List . length ops ) ops 2 then V . return ( ) else V . fail Length_mismatch and account_a = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Fee_payment ops in Option . value_map account ~ default ( : V . fail Account_not_some ) Account_not_some ~ f : V . return and fee_token = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Fee_payment ops in match account with | Some account -> ( match token_id_of_account account with | Some token_id -> V . return ( ` Token_id token_id ) token_id | None -> V . fail Incorrect_token_id ) | None -> V . fail Account_not_some and account_b = let open Result . Let_syntax in let % bind { metadata ; _ } = find_kind ` Delegate_change ops in match metadata with | Some metadata -> ( match metadata with | ` Assoc [ ( " delegate_change_target " , ` String s ) s ] -> return s | _ -> V . fail Invalid_metadata ) | None -> V . fail Account_not_some and ( ) = if List . for_all ops ~ f ( : fun op -> let p = Option . equal String . equal op . status in p None || p ( Some ) " " ) then V . return ( ) else V . fail Status_not_pending and payment_amount_y = let open Result . Let_syntax in let % bind { amount ; _ } = find_kind ` Fee_payment ops in match amount with | Some x -> V . return ( Amount_of . negated x ) x | None -> V . fail Amount_not_some in { Partial . kind = ` Delegation ; fee_payer = ` Pk account_a . address ; source = ` Pk account_a . address ; receiver = ` Pk account_b ; fee_token ; token = ` Token_id Token_id ( . default |> to_string ) to_string ; fee = Unsigned . UInt64 . of_string payment_amount_y . Amount . value ; amount = None ; valid_until ; memo } in let partials = [ payment ; delegation ] in let oks , errs = List . partition_map partials ~ f : Result . to_either in match ( oks , errs ) errs with | [ ] , errs -> Error ( List . concat errs ) errs | [ partial ] , _ -> Ok partial | _ , _ -> failwith " A sequence of operations must represent exactly one user command " |
let to_operations ~ failure_status ( t : Partial . t ) t : Operation . t list = let plan : ' a Op . t list = ( if not Unsigned . UInt64 ( . equal t . fee zero ) zero then [ { Op . label = ` Fee_payment ; related_to = None } ] else [ ] ) @ ( match failure_status with | Some ( ` Applied ( Account_creation_fees_paid . By_receiver amount ) amount ) amount -> [ { Op . label = ` Account_creation_fee_via_payment amount ; related_to = None } ] | Some ( ` Applied ( Account_creation_fees_paid . By_fee_payer amount ) amount ) amount -> [ { Op . label = ` Account_creation_fee_via_fee_payer amount ; related_to = None } ] | _ -> [ ] ) @ match t . kind with | ` Payment -> ( match t . amount with | Some amount -> [ { Op . label = ` Payment_source_dec amount ; related_to = None } ; { Op . label = ` Payment_receiver_inc amount ; related_to = Some ( ` Payment_source_dec amount ) amount } ] | None -> [ ] ) | ` Delegation -> [ { Op . label = ` Delegate_change ; related_to = None } ] in Op . build ~ a_eq : [ % eq : [ ` Fee_payment | ` Payment_source_dec of Unsigned . UInt64 . t | ` Payment_receiver_inc of Unsigned . UInt64 . t ] ] ~ plan ~ f ( : fun ~ related_operations ~ operation_identifier op -> let status , metadata , did_fail = match ( op . label , failure_status ) failure_status with | _ , None -> ( None , None , false ) false | _ , Some ( ` Applied _ ) _ -> ( Some ` Success , None , false ) false | _ , Some ( ` Failed reason ) reason -> ( Some ` Failed , Some ( ` Assoc [ ( " reason " , ` String reason ) reason ] ) , true ) true in let pending_or_success_only = function | None -> None | Some ( ` Success | ` Failed ) Failed -> Some ` Success in let merge_metadata m1 m2 = match ( m1 , m2 ) m2 with | None , None -> None | Some x , None | None , Some x -> Some x | Some ( ` Assoc xs ) xs , Some ( ` Assoc ys ) ys -> Some ( ` Assoc ( xs @ ys ) ys ) ys | _ -> failwith " Unexpected pattern " in match op . label with | ` Fee_payment -> { Operation . operation_identifier ; related_operations ; status = status |> pending_or_success_only |> Option . map ~ f : Operation_statuses . name ; account = Some ( account_id t . fee_payer t . fee_token ) fee_token ; _type = Operation_types . name ` Fee_payment ; amount = Some Amount_of ( . negated @@ token t . fee_token t . fee ) fee ; coin_change = None ; metadata } | ` Payment_source_dec amount -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . source t . token ) token ; _type = Operation_types . name ` Payment_source_dec ; amount = ( if did_fail then None else Some Amount_of ( . negated @@ token t . token amount ) amount ) ; coin_change = None ; metadata } | ` Payment_receiver_inc amount -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . receiver t . token ) token ; _type = Operation_types . name ` Payment_receiver_inc ; amount = ( if did_fail then None else Some ( Amount_of . token t . token amount ) amount ) amount ; coin_change = None ; metadata } | ` Account_creation_fee_via_payment account_creation_fee -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . receiver t . token ) token ; _type = Operation_types . name ` Account_creation_fee_via_payment ; amount = Some Amount_of ( . negated @@ mina account_creation_fee ) account_creation_fee ; coin_change = None ; metadata } | ` Account_creation_fee_via_fee_payer account_creation_fee -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . fee_payer t . fee_token ) fee_token ; _type = Operation_types . name ` Account_creation_fee_via_fee_payer ; amount = Some Amount_of ( . negated @@ mina account_creation_fee ) account_creation_fee ; coin_change = None ; metadata } | ` Delegate_change -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . source ( ` Token_id Amount_of . Token_id . default ) default ) default ; _type = Operation_types . name ` Delegate_change ; amount = None ; coin_change = None ; metadata = merge_metadata metadata ( Some ( ` Assoc [ ( " delegate_change_target " , ` String ( let ( ` Pk r ) r = t . receiver in r ) ) ] ) ) } ) |
let to_operations ' ( t : t ) t : Operation . t list = to_operations ~ failure_status : t . failure_status ( forget t ) t let start = { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; fee_token = ` Token_id Amount_of . Token_id . default ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = None ; hash = " TXN_1_HASH " ; valid_until = Some ( Unsigned . UInt32 . of_int 10_000 ) 10_000 ; memo = Some " hello " } in let ops = to_operations ' start in match of_operations ? valid_until : start . valid_until ? memo : start . memo ops with | Ok partial -> [ % test_eq : Partial . t ] t partial ( forget start ) start | Error e -> failwithf " ! Mismatch because { % sexp : Partial . Reason . t list } list " e ( ) let start = { kind = ` Delegation ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 1_000_000_000 ; receiver = ` Pk " Bob " ; fee_token = ` Token_id Amount_of . Token_id . default ; nonce = Unsigned . UInt32 . of_int 42 ; amount = None ; failure_status = None ; hash = " TXN_2_HASH " ; valid_until = Some ( Unsigned . UInt32 . of_int 867888 ) 867888 ; memo = Some " hello " } in let ops = to_operations ' start in match of_operations ops ? valid_until : start . valid_until ? memo : start . memo with | Ok partial -> [ % test_eq : Partial . t ] t partial ( forget start ) start | Error e -> failwithf " ! Mismatch because { % sexp : Partial . Reason . t list } list " e ( ) |
let non_default_token = ` Token_id ( Token_id . to_string ( Quickcheck . random_value Token_id . gen_non_default ) gen_non_default ) gen_non_default |
let dummies = [ { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee_token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Applied Account_creation_fees_paid . By_no_one ) By_no_one ; hash = " TXN_1_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee_token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Applied ( Account_creation_fees_paid . By_receiver ( Unsigned . UInt64 . of_int 1_000_000 ) 1_000_000 ) ) ; hash = " TXN_1new_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee_token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Failed " Failure ) " ; hash = " TXN_1fail_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = non_default_token ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; fee_token = ` Token_id Amount_of . Token_id . default ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Applied Account_creation_fees_paid . By_no_one ) By_no_one ; hash = " TXN_1a_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; fee_token = non_default_token ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Applied Account_creation_fees_paid . By_no_one ) By_no_one ; hash = " TXN_1b_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Delegation ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee_token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; nonce = Unsigned . UInt32 . of_int 3 ; amount = None ; failure_status = Some ( ` Applied Account_creation_fees_paid . By_no_one ) By_no_one ; hash = " TXN_2_HASH " ; valid_until = None ; memo = Some " hello " } ] |
module Payload = struct module Common = struct [ %% versioned module Stable = struct module V2 = struct type t = ( Currency . Fee . Stable . V1 . t , Public_key . Compressed . Stable . V1 . t , Account_nonce . Stable . V1 . t option , Global_slot . Stable . V1 . t , Signed_command_memo . Stable . V1 . t ) Signed_command_payload . Common . Poly . Stable . V2 . t [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end let create ~ fee ~ fee_payer_pk ? nonce ~ valid_until ~ memo : t = { fee ; fee_payer_pk ; nonce ; valid_until ; memo } let to_user_command_common ( t : t ) t ~ minimum_nonce ~ inferred_nonce : ( Signed_command_payload . Common . t , string ) string Result . t = let open Result . Let_syntax in let % map nonce = match t . nonce with | None -> Ok inferred_nonce | Some nonce -> if Account_nonce ( . minimum_nonce <= nonce && nonce <= inferred_nonce ) inferred_nonce then Ok nonce else Error ( sprintf " ! Input nonce % s either different from inferred nonce % s or \ below minimum_nonce % s " ( Account_nonce . to_string nonce ) nonce ( Account_nonce . to_string inferred_nonce ) inferred_nonce ( Account_nonce . to_string minimum_nonce ) minimum_nonce ) in { Signed_command_payload . Common . Poly . fee = t . fee ; fee_payer_pk = t . fee_payer_pk ; nonce ; valid_until = t . valid_until ; memo = t . memo } let fee_payer ( { fee_payer_pk ; _ } : t ) t = Account_id . create fee_payer_pk Mina_base . Token_id . default end [ %% versioned module Stable = struct module V2 = struct type t = ( Common . Stable . V2 . t , Signed_command_payload . Body . Stable . V2 . t ) Signed_command_payload . Poly . Stable . V1 . t [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end let create ~ fee ~ fee_payer_pk ? nonce ~ valid_until ~ memo ~ body : t = { common = Common . create ~ fee ~ fee_payer_pk ? nonce ~ valid_until ~ memo ; body } let to_user_command_payload ( t : t ) t ~ minimum_nonce ~ inferred_nonce : ( Signed_command_payload . t , string ) string Result . t = let open Result . Let_syntax in let % map common = Common . to_user_command_common t . common ~ minimum_nonce ~ inferred_nonce in { Signed_command_payload . Poly . common ; body = t . body } let fee_payer ( { common ; _ } : t ) t = Common . fee_payer common end |
module Sign_choice = struct [ %% versioned module Stable = struct module V1 = struct type t = | Signature of Signature . Stable . V1 . t | Hd_index of Unsigned_extended . UInt32 . Stable . V1 . t | Keypair of Keypair . Stable . V1 . t [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end end [ %% versioned |
module Stable = struct module V2 = struct type t = ( Payload . Stable . V2 . t , Public_key . Compressed . Stable . V1 . t , Sign_choice . Stable . V1 . t ) Signed_command . Poly . Stable . V1 . t [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end |
let fee_payer ( { payload ; _ } : t ) t = Payload . fee_payer payload |
let create ? nonce ~ fee ~ fee_payer_pk ~ valid_until ~ memo ~ body ~ signer ~ sign_choice ( ) : t = let valid_until = Option . value valid_until ~ default : Global_slot . max_value in let payload = Payload . create ~ fee ~ fee_payer_pk ? nonce ~ valid_until ~ memo ~ body in { payload ; signer ; signature = sign_choice } |
let sign ~ signer ( ~ user_command_payload : Signed_command_payload . t ) t = function | Sign_choice . Signature signature -> Option . value_map ~ default ( : Deferred . return ( Error " Invalid_signature ) ) " ( Signed_command . create_with_signature_checked signature signer user_command_payload ) ~ f : Deferred . Result . return | Keypair signer_kp -> Deferred . Result . return ( Signed_command . sign signer_kp user_command_payload ) user_command_payload | Hd_index hd_index -> Secrets . Hardware_wallets . sign ~ hd_index ~ public_key ( : Public_key . decompress_exn signer ) signer ~ user_command_payload |
let inferred_nonce ~ get_current_nonce ( ~ fee_payer : Account_id . t ) t ~ nonce_map = let open Result . Let_syntax in let update_map = Map . set nonce_map ~ key : fee_payer in match Map . find nonce_map fee_payer with | Some ( min_nonce , nonce ) nonce -> let next_nonce = Account_nonce . succ nonce in let updated_map = update_map ~ data ( : min_nonce , next_nonce ) next_nonce in Ok ( min_nonce , next_nonce , updated_map ) updated_map | None -> let % map ` Min min_nonce , txn_pool_or_account_nonce = get_current_nonce fee_payer in let updated_map = update_map ~ data ( : min_nonce , txn_pool_or_account_nonce ) txn_pool_or_account_nonce in ( min_nonce , txn_pool_or_account_nonce , updated_map ) updated_map |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.