text
stringlengths
0
601k
module Make ( A : T0 ) T0 ( A_value : T0 ) T0 = struct module I = Inductive_rule . T ( A ) A ( A_value ) A_value let prev ( type xs ys ws hs ) hs ~ self ( ~ choices : ( xs , ys , ws , hs ) hs H4 . T ( TI ) TI . t ) t = let module M_inner = H4 . Map ( Tag ) Tag ( E04 ( Domains ) Domains ) Domains ( struct let f : type a b c d . ( a , b , c , d ) d Tag . t -> Domains . t = fun t -> Types_map . lookup_map t ~ self : self . Tag . id ~ default ( : fun ( ) -> assert false ) false ~ f ( : function | ` Side_loaded d -> fun ( ) -> Common . wrap_domains ~ proofs_verified : ( Nat . to_int ( Nat . Add . n d . permanent . max_proofs_verified ) max_proofs_verified ) | ` Compiled d -> fun ( ) -> d . wrap_domains ) ( ) end ) end in let module M = H4 . Map ( I ) I ( H4 . T ( E04 ( Domains ) Domains ) Domains ) Domains ( struct let f : type vars values env widths heights . ( vars , values , widths , heights ) heights I . t -> ( vars , values , widths , heights ) heights H4 . T ( TE04 ( TE04Domains ) TE04Domains ) TE04Domains . t = fun rule -> M_inner . f rule . prevs end ) end in M . f choices let f_debug full_signature num_choices choices_length ~ self ~ choices ~ max_proofs_verified = let num_choices = Hlist . Length . to_nat choices_length in let dummy_step_domains = Vector . init num_choices ~ f ( : fun _ -> Fix_domains . rough_domains ) rough_domains in let dummy_step_widths = Vector . init num_choices ~ f ( : fun _ -> Nat . to_int ( Nat . Add . n max_proofs_verified ) max_proofs_verified ) in let dummy_step_keys = lazy ( Vector . init num_choices ~ f ( : fun _ -> let g = Backend . Tock . Inner_curve ( . to_affine_exn one ) one in Verification_key . dummy_commitments g ) ) in let prev_domains = prev ~ self ~ choices in Timer . clock __LOC__ ; let _ , main = Wrap_main . wrap_main full_signature choices_length dummy_step_keys dummy_step_widths dummy_step_domains prev_domains max_proofs_verified in Timer . clock __LOC__ ; let t = Fix_domains . domains ( module Impls . Wrap ) Wrap ( Impls . Wrap . input ( ) ) ( T ( Snarky_backendless . Typ . unit ( ) , Fn . id , Fn . id ) id ) id main in Timer . clock __LOC__ ; t let f full_signature num_choices choices_length ~ self ~ choices ~ max_proofs_verified = let res = Common . wrap_domains ~ proofs_verified ( : Nat . to_int ( Nat . Add . n max_proofs_verified ) max_proofs_verified ) max_proofs_verified in ( if debug then let res ' = f_debug full_signature num_choices choices_length ~ self ~ choices ~ max_proofs_verified in [ % test_eq : Domains . t ] t res res ' ) ; res end
let wrap ident exn_args global_idx = let open JavaAST in let name = Ident . name ident in Output . verbose ( Printf . sprintf " wrapping exception % S . . . " name ) name ; let exn_args = List . mapi ( fun i arg -> let info = TypeMap . find false arg in let name = Printf . sprintf " p % d " i in info , name ) name exn_args in let formal_params = List . map ( fun ( info , name ) name -> let typ = info . TypeInfo . java_type in typ , name ) name exn_args in let identifiers = List . map ( fun ( _ , x ) x -> Identifier x ) x formal_params in let cstr = constructor [ Public ] Public name ~ parameters : formal_params [ Super_constructor [ Static_call ( name , " create " , identifiers ) identifiers ] identifiers ] identifiers in let global_tag = get_global global_idx in let create_meth = let elems = List . map ( fun ( info , name ) name -> info . TypeInfo . ocaml_of_java ( Identifier name ) name ) name exn_args in let elems = global_tag :: elems in method_ [ Private ; Static ] Static ~ return ( : Some type_Value ) type_Value " create " ~ parameters : formal_params [ return ( create_block 0 elems ) elems ] elems in let global_id = Call ( get global_tag 0 , " asString " , [ ] ) in let register = Static_call ( " OCamlException " , " register " , [ global_id ; Identifier ( name ^ " . class ) ] ) " in add_static_block [ Expression register ] ; class_ [ Public ; Static ; Final ] Final name ~ extends ( : Some " OCamlException ) " ~ methods [ : cstr ; create_meth ] create_meth ( )
let wrap modname name res params eqs module_types approx approx_idx = let fname = Ident . name name in Output . verbose ( Printf . sprintf " wrapping functor % S . . . " fname ) fname ; let open JavaAST in let links = ref [ ] in let meth_parameters = List . mapi ( fun i ( mn , mt ) mt -> let id = Printf . sprintf " p % d " i in let t = Path . name mt in let _ , _ , l = List . find ( fun ( id , _ , _ ) _ -> ( Ident . name id ) id = t ) t module_types in let mn = Ident . name mn in let l = List . mapi ( fun i x -> try let idx_type = ref ( - 1 ) 1 in let link , _ , _ = List . find ( fun ( _ , parameter , typ ) typ -> incr idx_type ; ( parameter = mn ) mn && ( typ = x ) x ) x eqs in links := ( link , ( i , ! idx_type ) idx_type ) idx_type :: ! links ; Reference ( link , [ ] ) with Not_found -> Reference ( x , [ ] ) ) l in let t = Reference ( t , l ) l in let formal = t , id in let effective = Identifier id in let effective = Call ( effective , " value " , [ ] ) in formal , effective ) effective params in let formal_meth_parameters , effective_meth_parameters = List . split meth_parameters in let class_name , func_name , closed = match approx with | Some ( Jlambda . Value_closure ( fundesc , _ ) _ ) _ -> fundesc . Jlambda . fun_label . Jlambda . fl_class , fundesc . Jlambda . fun_label . Jlambda . fl_method , fundesc . Jlambda . fun_closed | _ -> fail ( Cannot_determine_function name ) name in let effective_meth_parameters = if closed then effective_meth_parameters else effective_meth_parameters @ [ get_global approx_idx ] approx_idx in let call = Static_call ( class_name , func_name , effective_meth_parameters ) effective_meth_parameters in let _ , _ , res_type_params = List . find ( fun ( id , _ , _ ) _ -> ( Ident . name id ) id = ( Path . name res ) res ) res module_types in let res_type_params , quantif , wrappers = List . fold_left ( fun ( acc , quantif , wrappers ) wrappers elem -> if List . mem_assoc elem ! links then let p_id , w_id = List . assoc elem ! links in let wrapper = Identifier ( Printf . sprintf " p % d " p_id ) p_id in let wrapper = Call ( wrapper , " getWrapper " , [ Int_literal ( Int32 . of_int w_id ) w_id ] w_id ) w_id in elem :: acc , elem :: quantif , wrapper :: wrappers else let wrapper = Identifier " OCamlValue . WRAPPER " in " OCamlValue " :: acc , quantif , wrapper :: wrappers ) wrappers ( [ ] , [ ] , [ ] ) res_type_params in let res_type_params = List . rev res_type_params in let quantif = List . rev quantif in let wrappers = List . rev wrappers in let res_type_params = List . map ( fun x -> Reference ( x , [ ] ) ) res_type_params in let res_type = Reference ( Path . name res , res_type_params ) res_type_params in let res_conv e = Static_call ( Path . name res , " wrap " , wrappers @ [ e ] e ) e in let meth_return_type = Some ( res_type , res_conv , false ) false in let type_parameters = TypeParametersTable . empty in let body = Wrap_arrow . make_body meth_return_type type_parameters call in let body = Wrap_arrow . make_try_catch body in let javadoc = [ Printf . sprintf " Applies functor { @ code % s . % s } s . " modname fname ] in method_ ~ javadoc ~ annotations [ " :@ SuppressWarnings ( SuppressWarnings " \ unchecked ) ] " " \ ~ generics ( : List . map ( Printf . sprintf " % s extends OCamlValue ) " quantif ) quantif [ Public ; Static ] ~ return ( : match meth_return_type with None -> None | Some ( x , _ , _ ) _ -> Some x ) x fname ~ parameters ( : formal_meth_parameters ) ~ throws : Wrap_arrow . throws_list body
let pad_domains ( type prev_varss prev_valuess branches max_proofs_verified ) max_proofs_verified ( module Max_proofs_verified : Nat . Intf with type n = max_proofs_verified ) max_proofs_verified ( pi_branches : ( prev_varss , branches ) branches Length . t ) t ( prev_wrap_domains : ( prev_varss , prev_valuess , _ , _ ) _ H4 . T ( TH4 . T ( TE04 ( TE04Domains ) TE04Domains ) TE04Domains ) TE04Domains . t ) : ( ( Domains . t , branches ) branches Vector . t , max_proofs_verified ) max_proofs_verified Vector . t = let module Ds = struct type t = ( Domains . t , Max_proofs_verified . n ) n Vector . t end in let ds : ( prev_varss , prev_valuess , _ , _ ) _ H4 . T ( TE04 ( TE04Ds ) TE04Ds ) TE04Ds . t = let dummy_domains = let d = Domain . Pow_2_roots_of_unity 1 in { Domains . h = d } in let module M = H4 . Map ( H4 . T ( E04 ( Domains ) Domains ) Domains ) Domains ( E04 ( Ds ) Ds ) Ds ( struct module H = H4 . T ( E04 ( Domains ) Domains ) Domains let f : type a b c d . ( a , b , c , d ) d H4 . T ( TE04 ( TE04Domains ) TE04Domains ) TE04Domains . t -> Ds . t = fun domains -> let ( T ( len , pi ) pi ) pi = H . length domains in let module V = H4 . To_vector ( Domains ) Domains in Vector . extend_exn ( V . f pi domains ) domains Max_proofs_verified . n dummy_domains end ) end in M . f prev_wrap_domains in let ds = let module V = H4 . To_vector ( Ds ) Ds in V . f pi_branches ds in Vector . transpose ds
module Old_bulletproof_chals = struct type t = | T : ' max_local_max_proofs_verified Nat . t * ' max_local_max_proofs_verified Challenges_vector . t -> t end
let pack_statement max_proofs_verified t = with_label __LOC__ ( fun ( ) -> Spec . pack ( module Impl ) Impl ( Types . Step . Statement . spec max_proofs_verified Backend . Tock . Rounds . n ) n ( Types . Step . Statement . to_data t ) t )
let shifts ~ log2_size = Common . tock_shifts ~ log2_size |> Plonk_types . Shifts . map ~ f : Impl . Field . constant
let domain_generator ~ log2_size = Backend . Tock . Field . domain_generator ~ log2_size |> Impl . Field . constant
let split_field_typ : ( Field . t * Boolean . var , Field . Constant . t ) t Typ . t = Typ . transport Typ ( . field * Boolean . typ ) typ ~ there ( : fun ( x : Field . Constant . t ) t -> let n = Bigint . of_field x in let is_odd = Bigint . test_bit n 0 in let y = Field . Constant ( ( . if is_odd then x - one else x ) x / of_int 2 ) 2 in ( y , is_odd ) is_odd ) ~ back ( : fun ( hi , is_odd ) is_odd -> let open Field . Constant in let x = hi + hi in if is_odd then x + one else x )
let split_field ( x : Field . t ) t : Field . t * Boolean . var = let ( ( y , is_odd ) is_odd as res ) res = exists Typ ( . field * Boolean . typ ) typ ~ compute ( : fun ( ) -> let x = As_prover . read_var x in let n = Bigint . of_field x in let is_odd = Bigint . test_bit n 0 in let y = Field . Constant ( ( . if is_odd then x - one else x ) x / of_int 2 ) 2 in ( y , is_odd ) is_odd ) in Field ( . Assert . equal ( ( of_int 2 * y ) y + ( is_odd :> t ) t ) t x ) x ; res
let wrap_main ( type max_proofs_verified branches prev_varss prev_valuess env max_local_max_proofs_verifieds ) ( full_signature : ( max_proofs_verified , branches , max_local_max_proofs_verifieds ) Full_signature . t ) ( pi_branches : ( prev_varss , branches ) branches Hlist . Length . t ) t ( step_keys : ( Wrap_main_inputs . Inner_curve . Constant . t index , branches ) branches Vector . t Lazy . t ) ( step_widths : ( int , branches ) branches Vector . t ) t ( step_domains : ( Domains . t , branches ) branches Vector . t ) t ( prev_wrap_domains : ( prev_varss , prev_valuess , _ , _ ) _ H4 . T ( TH4 . T ( TE04 ( TE04Domains ) TE04Domains ) TE04Domains ) TE04Domains . t ) ( module Max_proofs_verified : Nat . Add . Intf with type n = max_proofs_verified ) max_proofs_verified : ( max_proofs_verified , max_local_max_proofs_verifieds ) max_local_max_proofs_verifieds Requests . Wrap . t * ( ( _ , _ , _ Shifted_value . Type1 . t , _ , _ , _ , _ , _ , _ ) Types . Wrap . Statement . In_circuit . t -> unit ) = Timer . clock __LOC__ ; let T = Max_proofs_verified . eq in let branches = Hlist . Length . to_nat pi_branches in Timer . clock __LOC__ ; let ( module Req ) Req = Requests . Wrap ( . ( create ( ) : ( max_proofs_verified , max_local_max_proofs_verifieds ) max_local_max_proofs_verifieds t ) t ) t in Timer . clock __LOC__ ; let { Full_signature . padded ; maxes = ( module Max_widths_by_slot ) Max_widths_by_slot } = full_signature in Timer . clock __LOC__ ; let main ( { proof_state = { deferred_values = { plonk ; xi ; combined_inner_product ; b ; which_branch ; bulletproof_challenges } ; sponge_digest_before_evaluations ; me_only = me_only_digest } ; pass_through } : ( _ , _ , _ Shifted_value . Type1 . t , _ , _ , _ , _ , _ , _ ) Types . Wrap . Statement . In_circuit . t ) = with_label __LOC__ ( fun ( ) -> let which_branch = One_hot_vector . of_index which_branch ~ length : branches in let prev_proof_state = with_label __LOC__ ( fun ( ) -> let open Types . Step . Proof_state in let typ = typ ( module Impl ) Impl Max_proofs_verified . n ( Shifted_value . Type2 . typ Field . typ ) typ in exists typ ~ request ( : fun ( ) -> Req . Proof_state ) Proof_state ) in let step_plonk_index = with_label __LOC__ ( fun ( ) -> choose_key which_branch ( Vector . map ( Lazy . force step_keys ) step_keys ~ f ( : Plonk_verification_key_evals . map ~ f : Inner_curve . constant ) constant ) ) in let prev_step_accs = with_label __LOC__ ( fun ( ) -> exists ( Vector . typ Inner_curve . typ Max_proofs_verified . n ) n ~ request ( : fun ( ) -> Req . Step_accs ) Step_accs ) in let old_bp_chals = with_label __LOC__ ( fun ( ) -> let typ = let module T = H1 . Typ ( Impls . Wrap ) Wrap ( Nat ) Nat ( Challenges_vector ) Challenges_vector ( Challenges_vector . Constant ) Constant ( struct let f ( type n ) n ( n : n Nat . t ) t = Vector . typ ( Vector . typ Field . typ Backend . Tock . Rounds . n ) n n end ) end in T . f Max_widths_by_slot . maxes in let module Z = H1 . Zip ( Nat ) Nat ( Challenges_vector ) Challenges_vector in let module M = H1 . Map ( H1 . Tuple2 ( Nat ) Nat ( Challenges_vector ) Challenges_vector ) Challenges_vector ( E01 ( Old_bulletproof_chals ) Old_bulletproof_chals ) Old_bulletproof_chals ( struct let f ( type n ) n ( ( n , v ) v : n H1 . Tuple2 ( Tuple2Nat ) Tuple2Nat ( Tuple2NatChallenges_vector ) Tuple2NatChallenges_vector . t ) t = Old_bulletproof_chals . T ( n , v ) v end ) end in let module V = H1 . To_vector ( Old_bulletproof_chals ) Old_bulletproof_chals in Z . f Max_widths_by_slot . maxes ( exists typ ~ request ( : fun ( ) -> Req . Old_bulletproof_challenges ) Old_bulletproof_challenges ) Old_bulletproof_challenges |> M . f |> V . f Max_widths_by_slot . length ) in let domainses = with_label __LOC__ ( fun ( ) -> pad_domains ( module Max_proofs_verified ) Max_proofs_verified pi_branches prev_wrap_domains ) in let new_bulletproof_challenges = with_label __LOC__ ( fun ( ) -> let evals = let ty = let ty = Plonk_types . All_evals . typ ( Evaluation_lengths . create ~ of_int : Fn . id ) id Field . typ ~ default : Field . Constant . zero in Vector . typ ty Max_proofs_verified . n in exists ty ~ request ( : fun ( ) -> Req . Evals ) Evals in let chals = let wrap_domains : ( _ Plonk_checks . plonk_domain , Max_proofs_verified . n ) Vector . t = Vector . map domainses ~ f ( : fun possible_wrap_domains -> Pseudo . Domain . to_domain ~ shifts ~ domain_generator ( which_branch , Vector . map ~ f ( : fun ds -> ds . h ) h possible_wrap_domains ) ) in let max_quot_sizes = Vector . map domainses ~ f ( : fun ds -> ( which_branch , Vector . map ds ~ f ( : fun d -> Common . max_quot_size_int ( Domain . size d . h ) h ) ) ) in let actual_proofs_verifieds = padded |> Vector . map ~ f ( : fun proofs_verifieds_in_slot -> Pseudo . choose ( which_branch , proofs_verifieds_in_slot ) proofs_verifieds_in_slot ~ f : Field . of_int ) in Vector . mapn [ prev_proof_state . unfinalized_proofs ; old_bp_chals ; actual_proofs_verifieds ; evals ; wrap_domains ; max_quot_sizes ] ~ f ( : fun [ { deferred_values ; sponge_digest_before_evaluations ; should_finalize } ; old_bulletproof_challenges ; actual_proofs_verified ; evals ; wrap_domain ; max_quot_size ] -> let sponge = let s = Sponge . create sponge_params in Sponge . absorb s sponge_digest_before_evaluations ; s in let ( T ( max_local_max_proofs_verified , old_bulletproof_challenges ) ) = old_bulletproof_challenges in let finalized , chals = with_label __LOC__ ( fun ( ) -> finalize_other_proof ( Nat . Add . create max_local_max_proofs_verified ) max_local_max_proofs_verified ~ max_quot_size ~ actual_proofs_verified ~ domain ( : wrap_domain :> _ Plonk_checks . plonk_domain ) plonk_domain ~ sponge ~ old_bulletproof_challenges deferred_values evals ) in Boolean ( . Assert . any [ finalized ; not should_finalize ] ) ; chals ) in chals ) in let prev_statement = let prev_me_onlys = Vector . map2 prev_step_accs old_bp_chals ~ f ( : fun sacc ( T ( max_local_max_proofs_verified , chals ) chals ) chals -> hash_me_only max_local_max_proofs_verified { challenge_polynomial_commitment = sacc ; old_bulletproof_challenges = chals } ) in { Types . Step . Statement . pass_through = prev_me_onlys ; proof_state = prev_proof_state } in let openings_proof = let shift = Shifts . tick1 in exists ( Plonk_types . Openings . Bulletproof . typ ( Typ . transport Other_field . Packed . typ ~ there ( : fun x -> match Shifted_value . Type1 . of_field ( module Backend . Tick . Field ) Field ~ shift x with | Shifted_value x -> x ) ~ back ( : fun x -> Shifted_value . Type1 . to_field ( module Backend . Tick . Field ) Field ~ shift ( Shifted_value x ) x ) |> Typ . transport_var ~ there ( : fun ( Shifted_value . Type1 . Shifted_value x ) x -> x ) x ~ back ( : fun x -> Shifted_value x ) x ) Inner_curve . typ ~ length ( : Nat . to_int Backend . Tick . Rounds . n ) n ) ~ request ( : fun ( ) -> Req . Openings_proof ) Openings_proof in let ( sponge_digest_before_evaluations_actual , ( ` Success bulletproof_success , bulletproof_challenges_actual ) bulletproof_challenges_actual ) = let messages = with_label __LOC__ ( fun ( ) -> exists ( Plonk_types . Messages . typ ~ dummy : Inner_curve . Params . one Inner_curve . typ ~ bool : Boolean . typ ~ commitment_lengths : ( Commitment_lengths . create ~ of_int : Fn . id ) id ) ~ request ( : fun ( ) -> Req . Messages ) Messages ) in let sponge = Opt . create sponge_params in with_label __LOC__ ( fun ( ) -> incrementally_verify_proof ( module Max_proofs_verified ) Max_proofs_verified ~ step_widths ~ step_domains ~ verification_key : step_plonk_index ~ xi ~ sponge ~ public_input : ( Array . map ( pack_statement Max_proofs_verified . n prev_statement ) prev_statement ~ f ( : function | ` Field ( Shifted_value x ) x -> ` Field ( split_field x ) x | ` Packed_bits ( x , n ) n -> ` Packed_bits ( x , n ) n ) ) ~ sg_old : prev_step_accs ~ advice { : b ; combined_inner_product } ~ messages ~ which_branch ~ openings_proof ~ plonk ) in with_label __LOC__ ( fun ( ) -> Boolean . Assert . is_true bulletproof_success ) ; with_label __LOC__ ( fun ( ) -> Field . Assert . equal me_only_digest ( hash_me_only Max_proofs_verified . n { Types . Wrap . Proof_state . Me_only . challenge_polynomial_commitment = openings_proof . challenge_polynomial_commitment ; old_bulletproof_challenges = new_bulletproof_challenges } ) ) ; with_label __LOC__ ( fun ( ) -> Field . Assert . equal sponge_digest_before_evaluations sponge_digest_before_evaluations_actual ) ; Array . iter2_exn bulletproof_challenges_actual ( Vector . to_array bulletproof_challenges ) bulletproof_challenges ~ f ( : fun { prechallenge = { inner = x1 } } ( { prechallenge = { inner = x2 } } : _ SC . t Bulletproof_challenge . t ) -> with_label __LOC__ ( fun ( ) -> Field . Assert . equal x1 x2 ) x2 ) ; ( ) ) in Timer . clock __LOC__ ; ( ( module Req ) Req , main ) main
let sponge_params_constant = Sponge . Params ( . map pasta_q_kimchi ~ f : Impl . Field . Constant . of_string ) of_string
let field_random_oracle ( ? length = Me . Field . size_in_bits - 1 ) 1 s = Me . Field . of_bits ( bits_random_oracle ~ length s ) s
let unrelated_g = let group_map = unstage ( group_map ( module Me . Field ) Field ~ a : Me . Inner_curve . Params . a ~ b : Me . Inner_curve . Params . b ) and str = Fn . compose bits_to_bytes Me . Field . to_bits in fun ( x , y ) y -> group_map ( field_random_oracle ( str x ^ str y ) y ) y
module Other_field = struct type t = Impls . Step . Field . Constant . t [ @@ deriving sexp ] sexp include ( Tick . Field : module type of Tick . Field with type t := t ) t let size = Impls . Step . Bigint . to_bignum_bigint size end
let sponge_params = Sponge . Params ( . map sponge_params_constant ~ f : Impl . Field . constant ) constant
module Unsafe = struct let unpack_unboolean ( ? length = Field . size_in_bits ) size_in_bits x = let res = exists ( Typ . list Boolean . typ_unchecked ~ length ) length ~ compute : As_prover ( . fun ( ) -> List . take ( Field . Constant . unpack ( read_var x ) x ) x length ) length in Field . Assert . equal x ( Field . project res ) res ; res end
module Sponge = struct module Permutation = Sponge_inputs . Make ( Impl ) Impl ( struct include Tock_field_sponge . Inputs let params = Tock_field_sponge . params end ) end module S = Sponge . Make_sponge ( Permutation ) Permutation include S let squeeze_field = squeeze let squeeze = squeeze end let module T = Make_sponge . Test ( Impl ) Impl ( Tock_field_sponge . Field ) Field ( Sponge . S ) S in T . test Tock_field_sponge . params
module Input_domain = struct let lagrange_commitments domain : Me . Inner_curve . Affine . t array = let domain_size = Domain . size domain in time " lagrange " ( fun ( ) -> Array . init domain_size ~ f ( : fun i -> ( Kimchi_bindings . Protocol . SRS . Fp . lagrange_commitment ( Tick . Keypair . load_urs ( ) ) domain_size i ) . unshifted ( . 0 ) 0 |> Common . finite_exn ) ) let domain = Domain . Pow_2_roots_of_unity 7 end
module Inner_curve = struct module C = Kimchi_pasta . Pasta . Vesta module Inputs = struct module Impl = Impl module Params = struct include C . Params let one = C . to_affine_exn C . one let group_size_in_bits = Field . size_in_bits end module F = struct include struct open Impl . Field type nonrec t = t let ( * ) , ( + ) , ( - ) , inv_exn , square , scale , if_ , typ , constant = ( ( * ) , ( + ) , ( - ) , inv , square , scale , if_ , typ , constant ) constant let negate x = scale x Constant ( . negate one ) one end module Constant = struct open Impl . Field . Constant type nonrec t = t let ( * ) , ( + ) , ( - ) , inv_exn , square , negate = ( ( * ) , ( + ) , ( - ) , inv , square , negate ) negate end let assert_square x y = Impl . assert_square x y let assert_r1cs x y z = Impl . assert_r1cs x y z end module Constant = struct include C . Affine module Scalar = Impls . Step . Field . Constant let scale ( t : t ) t ( x : Scalar . t ) t : t = C ( . to_affine_exn ( scale ( of_affine t ) t x ) x ) x let random ( ) : t = C ( . to_affine_exn ( random ( ) ) ) let zero = Impl . Field . Constant ( . zero , zero ) zero let ( + ) t1 t2 : t = let is_zero ( x , _ ) _ = Impl . Field . Constant ( . equal zero x ) x in if is_zero t1 then t2 else if is_zero t2 then t1 else let r = C ( . of_affine t1 + of_affine t2 ) t2 in try C . to_affine_exn r with _ -> zero let negate x : t = C ( . to_affine_exn ( negate ( of_affine x ) x ) x ) x let to_affine_exn = Fn . id let of_affine = Fn . id end end module Params = Inputs . Params module Constant = Inputs . Constant module T = Snarky_curve . For_native_base_field ( Inputs ) Inputs include ( T : module type of T with module Scaling_precomputation := T . Scaling_precomputation ) module Scaling_precomputation = T . Scaling_precomputation let ( + ) t1 t2 = Plonk_curve_ops . add_fast ( module Impl ) Impl t1 t2 let double t = t + t let scale t bs = with_label __LOC__ ( fun ( ) -> T . scale t ( Bitstring_lib . Bitstring . Lsb_first . of_list bs ) bs ) let to_field_elements ( x , y ) y = [ x ; y ] let assert_equal ( x1 , y1 ) y1 ( x2 , y2 ) y2 = Field . Assert . equal x1 x2 ; Field . Assert . equal y1 y2 let scale_inv t bs = let res = exists typ ~ compute : As_prover ( . fun ( ) -> C . scale ( C . of_affine ( read typ t ) t ) t ( Other . Field . inv ( Other . Field . of_bits ( List . map ~ f ( : read Boolean . typ ) typ bs ) bs ) bs ) |> C . to_affine_exn ) to_affine_exn in assert_equal t ( scale res bs ) bs ; res let negate = T . negate let one = T . one let if_ = T . if_ end
module Generators = struct let h = lazy ( Kimchi_bindings . Protocol . SRS . Fp . urs_h ( Backend . Tick . Keypair . load_urs ( ) ) |> Common . finite_exn ) end
let elements_of_signature signature = let open Types in let types , functions , _ = List . fold_left ( fun ( acc_types , acc_functions , idx ) idx elem -> match elem with | Sig_type ( id , { type_params = [ ] ; type_arity = 0 ; type_kind = Type_abstract ; type_manifest = None ; _ } , _ ) _ -> ( Ident . name id , List . length acc_types ) acc_types :: acc_types , acc_functions , idx | Sig_value ( id , { val_type = { desc = ( Tarrow _ ) _ ; _ } as type_expr ; val_kind = Val_reg ; _ } ) -> acc_types , ( Ident . name id , type_expr , Some idx ) idx :: acc_functions , succ idx | Sig_value _ | Sig_type _ | Sig_exception _ | Sig_module _ | Sig_modtype _ | Sig_class _ | Sig_class_type _ -> fail Only_asbtract_types_and_functions ) Only_asbtract_types_and_functions ( [ ] , [ ] , 0 ) 0 signature in List . rev types , List . rev functions
let rec patch_function types type_expr = let open Types in let desc = match type_expr . desc with | Tarrow ( x , te1 , te2 , c ) c -> let te1 = patch_function types te1 in let te2 = patch_function types te2 in Tarrow ( x , te1 , te2 , c ) c | Ttuple l -> Ttuple ( patch_function_list types l ) l | Tconstr ( path , _ , _ ) _ when List . mem_assoc ( Path . name path ) path types -> Tvar ( Some ( Path . name path ) path ) path | Tconstr ( path , l , a ) a -> Tconstr ( path , patch_function_list types l , a ) a | Tlink te -> Tlink ( patch_function types te ) te | x -> x in { type_expr with desc } List . map ( patch_function types ) types type_expr_list
let wrap name signature = let class_name = Ident . name name in Output . verbose ( Printf . sprintf " wrapping module type % S . . . " class_name ) class_name ; TypeMap . add_local name true ; let open JavaAST in let type_parameters , functions = elements_of_signature signature in let wrapper_fields , get_wrapper_meth , get_wrapper_idx_meth , wrapper_meth , wrap_meth = Wrap_common . make_wrapper_elements ( Ident . name name ) name ~ suffix " :$ impl " type_parameters in let cstr , cstrc , cstr2 = let wrapper_parameters , inits = Wrap_common . make_wrapper_cstr_elements wrapper_fields type_parameters in let c1 = constructor [ Public ] Public ( Ident . name name ) name ~ parameters : wrapper_parameters ( [ Super_constructor [ Identifier " Value . UNIT ] ] " @ inits ) inits in let cc = constructor [ Protected ] Protected ( Ident . name name ) name ~ parameters ( : wrapper_parameters @ [ type_Value , " v ] ) " ( [ Super_constructor [ Identifier " v ] ] " @ inits ) inits in let effective_parameters = List . map ( fun ( _ , id ) id -> Identifier id ) id wrapper_parameters in let c2 = constructor ~ annotations ( : if effective_parameters = [ ] then [ ] else [ " @ SuppressWarnings ( SuppressWarnings " \ unchecked ) ] ) " " \ [ Public ] Public ( ( Ident . name name ) name ^ " $ impl ) " ~ parameters ( : wrapper_parameters @ [ type_Value , " v ] ) " [ Super_constructor ( effective_parameters @ [ Identifier " v ] ) ] " in c1 , cc , c2 in let functions = List . map ( fun ( id , type_expr , idx ) idx -> id , patch_function type_parameters type_expr , idx ) idx functions in let implementations , callers , closures = Wrap_structure . make_methods false functions in let value_meth = let cached_id = Identifier " this . cached " in let sz = Int32 . of_int ( List . length implementations ) implementations in let build_cached = [ Assign ( " this . cached " , Static_call ( " Value " , " createBlock " , [ Int_literal 0l ; Int_literal sz ] sz ) sz ) sz ] sz @ ( List . mapi ( fun i m -> let arity = List . length m . meth_parameters in let close = Static_call ( " OCamlWrappers " , " createClosure " , [ Identifier ( class_name ^ " . class ) " ; String_literal m . meth_name ; Identifier " this " ; Int_literal ( Int32 . of_int arity ) arity ] ) in let s = set cached_id i close in Expression s ) s closures ) closures in method_ ~ annotations [ " :@ Override ] " [ Public ] Public ~ return ( : Some type_Value ) type_Value " value " [ If ( Infix ( " " , == cached_id , Null_literal ) Null_literal , Block build_cached ) build_cached ; JavaAST . return cached_id ] cached_id in let name = Ident . name name in let full_name name = if type_parameters = [ ] then name else let tmp = List . map ( fun ( id , _ ) _ -> Printf . sprintf " % s extends OCamlValue " id ) id type_parameters in name ^ " " < ^ ( String . concat " , " tmp ) tmp ^ " " > in let full_name ' name = if type_parameters = [ ] then name else let tmp = List . map ( fun ( id , _ ) _ -> Printf . sprintf " % s " id ) id type_parameters in name ^ " " < ^ ( String . concat " , " tmp ) tmp ^ " " > in let cached_field = [ Private ] Private , type_Value , " cached " , None in let hash_code , equals , to_string = make_basic_object_methods name " " false in let abstract = class_ [ Public ; Static ; Abstract ] Abstract ( full_name name ) name ~ extends ( : Some " OCamlValue ) " ~ fields ( [ : cached_field ] cached_field @ wrapper_fields ) wrapper_fields ~ methods ( [ : cstr ; cstrc ; value_meth ] value_meth @ implementations @ closures @ [ hash_code ; equals ; to_string ] to_string @ [ get_wrapper_meth ; get_wrapper_idx_meth ; wrap_meth ; wrapper_meth ] wrapper_meth ) wrapper_meth ( ) in let orig_value_meth = method_ ~ annotations [ " :@ Override ] " [ Public ; Final ] Final ~ return ( : Some type_Value ) type_Value " value " [ return ( Identifier " this . value ) ] " in let final = class_ [ Private ; Static ; Final ] Final ( full_name ( name ^ " $ impl ) ) " ~ extends ( : Some ( full_name ' name ) name ) name ~ methods ( [ : cstr2 ] cstr2 @ callers @ [ orig_value_meth ] orig_value_meth ) orig_value_meth ( ) in abstract , final , List . map fst type_parameters
type dlog_opening = ( Tock . Curve . Affine . t , Tock . Field . t ) t Types . Step . Bulletproof . t
module Constant = struct type t = { messages : Tock . Curve . Affine . t Plonk_types . Messages . t ; opening : dlog_opening } [ @@ deriving hlist ] hlist end
module Checked = struct type t = { messages : Inner_curve . t Plonk_types . Messages . t ; opening : ( Inner_curve . t , Impls . Step . Other_field . t Shifted_value . Type2 . t ) Types . Step . Bulletproof . t } [ @@ deriving hlist ] hlist end
let typ : ( Checked . t , Constant . t ) t Typ . t = let shift = Shifted_value . Type2 . Shift . create ( module Tock . Field ) Field in Typ . of_hlistable ~ var_to_hlist : Checked . to_hlist ~ var_of_hlist : Checked . of_hlist ~ value_to_hlist : Constant . to_hlist ~ value_of_hlist : Constant . of_hlist [ Plonk_types . Messages . typ ~ bool : Boolean . typ ~ dummy : Inner_curve . Params . one ~ commitment_lengths ( : Commitment_lengths . create ~ of_int ( : fun x -> x ) x ) x Inner_curve . typ ; Types . Step . Bulletproof . typ ~ length ( : Nat . to_int Tock . Rounds . n ) n ( Typ . transport Other_field . typ ~ there ( : fun x -> match Shifted_value . Type2 . of_field ( module Tock . Field ) Field ~ shift x with | Shifted_value x -> x ) ~ back ( : fun x -> Shifted_value . Type2 . to_field ( module Tock . Field ) Field ~ shift ( Shifted_value x ) x ) |> Typ . transport_var ~ there ( : fun ( Shifted_value . Type2 . Shifted_value x ) x -> x ) x ~ back ( : fun x -> Shifted_value x ) x ) Inner_curve . typ ]
let wrap name fields record_repr type_parameters = let open JavaAST in let open Types in TypeMap . add_local name false ; let generics = TypeParametersTable . make type_parameters in let infos = List . mapi ( fun i ( _ , _ , type_expr ) type_expr -> i , TypeMap . find ~ generics false type_expr ) type_expr fields in let wrapper_fields , get_wrapper_meth , get_wrapper_idx_meth , wrapper_meth , wrap_meth = Wrap_common . make_wrapper_elements ( Ident . name name ) name type_parameters in let cstr = let wrapper_parameters , inits = Wrap_common . make_wrapper_cstr_elements wrapper_fields type_parameters in constructor [ Private ] Private ( Ident . name name ) name ~ parameters ( : wrapper_parameters @ [ type_Value , " v ] ) " ( [ Super_constructor [ Identifier " v ] ] " @ inits ) inits in let accessors = List . map2 ( fun ( id , mut , _ ) _ ( pos , info ) info -> let get = let res = if record_repr = Record_regular then let tmp = get ( Identifier " this . value ) " pos in info . TypeInfo . java_of_ocaml tmp else get_double ( Identifier " this . value ) " pos in method_ [ Public ] Public ~ return ( : Some ( info . TypeInfo . java_type ) java_type ) java_type ( " get " ^ ( String . capitalize ( Ident . name id ) id ) id ) id [ Return ( Some ( cast_if_needed info . TypeInfo . java_type res ) res ) res ] res in if mut = Asttypes . Immutable then [ get ] get else begin let x = Identifier " x " in let call = if record_repr = Record_regular then let x = info . TypeInfo . ocaml_of_java x in set ( Identifier " this . value ) " pos x else set_double ( Identifier " this . value ) " pos x in let set = method_ [ Public ] Public ( " set " ^ ( String . capitalize ( Ident . name id ) id ) id ) id ~ parameters [ : info . TypeInfo . java_type , " x ] " [ Expression ( call ) call ] call in [ get ; set ] set end ) end fields infos in let create = let quantif = List . map ( fun ( id , _ ) _ -> Printf . sprintf " % s extends OCamlValue " id ) id type_parameters in let wrappers = List . map ( fun ( _ , idx ) idx -> let id = Identifier ( Printf . sprintf " v % d " idx ) idx in Call ( id , " getWrapper " , [ ] ) ) type_parameters in method_ ~ generics : quantif ~ annotations ( : if type_parameters = [ ] then [ ] else [ " @ SuppressWarnings ( SuppressWarnings " \ unchecked ) ] ) " " \ [ Public ; Static ] Static ~ return ( : Some ( Reference ( Ident . name name , [ ] ) ) ) " create " ~ parameters ( : List . map2 ( fun ( _ , _ , _ ) _ ( pos , info ) info -> ( info . TypeInfo . java_type , Printf . sprintf " v % d " pos ) pos ) pos fields infos ) infos ( let l = List . map2 ( fun ( _ , _ , _ ) _ ( pos , _info ) _info -> Identifier ( Printf . sprintf " v % d " pos ) pos ) pos fields infos in let l ' = List . map2 ( fun e ( _ , info ) info -> let e : JavaAST . expression = e in let info : TypeInfo . t = info in let conv : TypeInfo . conversion_function = info . TypeInfo . ocaml_of_java in if record_repr = Record_regular then conv e else e ) e l infos in let wrap = if record_repr = Record_regular then create_block 0 l ' else create_double_array l ' in let res = New ( Ident . name name , ( wrappers @ [ wrap ] wrap ) wrap ) wrap in [ Return ( Some res ) res ] ) in let accessors = List . flatten accessors in let hash_code = method_ ~ annotations [ " :@ Override ] " [ Public ] Public ~ return ( : Some Int ) Int " hashCode " ( let call = Call ( Identifier " this . value " , " hashCode " , [ ] ) in [ Return ( Some call ) call ] call ) call in let equals = method_ ~ annotations [ " :@ Override ] " [ Public ] Public ~ return ( : Some Boolean ) Boolean " equals " ~ parameters [ : type_Object , " obj ] " ( let cond = Instance_of ( Identifier " obj " , Reference ( Ident . name name , [ ] ) ) in let if_branch = let t = Reference ( Ident . name name , [ ] ) in let l = List . map ( fun ( pos , info ) info -> let this = if record_repr = Record_regular then let tmp = get ( Identifier " this . value ) " pos in info . TypeInfo . java_of_ocaml tmp else get_double ( Identifier " this . value ) " pos in let that = if record_repr = Record_regular then let tmp = get ( Identifier " that . value ) " pos in info . TypeInfo . java_of_ocaml tmp else get_double ( Identifier " that . value ) " pos in if primitive_type info . TypeInfo . java_type then Infix ( " " , == this , that ) that else Call ( this , " equals " , [ that ] that ) that ) that infos in Block [ Variable_declaration ( t , " that " , Cast ( t , Identifier " obj ) ) " ; Return ( Some ( JavaAST . and_list l ) l ) l ] in let else_branch = Return ( Some ( Identifier " false ) ) " in [ If_else ( cond , if_branch , else_branch ) else_branch ] else_branch ) else_branch in let to_string = method_ ~ annotations [ " :@ Override ] " [ Public ] Public ~ return ( : Some type_String ) type_String " toString " ( let string_builder = Reference ( " StringBuilder " , [ ] ) in let append e = Expression ( Call ( Identifier " sb " , " append " , [ e ] e ) e ) e in [ Variable_declaration ( string_builder , " sb " , New ( " StringBuilder " , [ ] ) ) ; append ( String_literal ( ( Ident . name name ) name ^ ( ) ) ] " " @ ( List . flatten ( List . map2 ( fun ( id , _ , _ ) _ ( pos , info ) info -> let elem = if record_repr = Record_regular then let tmp = get ( Identifier " this . value ) " pos in info . TypeInfo . java_of_ocaml tmp else get_double ( Identifier " this . value ) " pos in let pref = Printf . sprintf " % s % s " = ( if pos > 0 then " , " else ) " " ( Ident . name id ) id in [ append ( String_literal pref ) pref ; append elem ] elem ) elem fields infos ) infos ) infos @ [ append ( String_literal ) ) " " ; Return ( Some ( Call ( Identifier " sb " , " toString " , [ ] ) ) ) ] ) in let name = Ident . name name in let full_name = if type_parameters = [ ] then name else let tmp = List . map ( fun ( id , _ ) _ -> Printf . sprintf " % s extends OCamlValue " id ) id type_parameters in name ^ " " < ^ ( String . concat " , " tmp ) tmp ^ " " > in class_ [ Public ; Static ; Final ] Final full_name ~ extends ( : Some " OCamlValue ) " ~ fields : wrapper_fields ~ methods ( [ : cstr ] cstr @ [ get_wrapper_meth ; get_wrapper_idx_meth ] get_wrapper_idx_meth @ accessors @ [ hash_code ; equals ; to_string ] to_string @ [ create ] create @ [ wrap_meth ; wrapper_meth ] wrapper_meth ) wrapper_meth ( )
let make_try_catch body = let open JavaAST in let handlers = [ " OCamlException " , " oe " , [ Throw ( Call ( Identifier " oe " , " getFailException " , [ ] ) ) ] ; ] in let body = [ Try_catch ( body , handlers ) handlers ] handlers in body
let make_body meth_return_type call = let open JavaAST in match meth_return_type with | Some ( t , conv , _gen ) _gen -> let ret = return ( cast_if_needed t ( conv ( Identifier " res ) ) ) " in [ Variable_declaration ( t , " res " , call ) call ; ret ] | None -> [ Expression call ; return ( Identifier " Value . UNIT ) " ]
let rec split3 = function | ( x , y , z ) z :: tl -> let x ' , y ' , z ' = split3 tl in x :: x ' , y :: y ' , z :: z ' | [ ] -> [ ] , [ ] , [ ]
let make_methods is_object methods = let open JavaAST in let name_hash = List . map ( fun ( name , _ , _ ) _ -> Btype . hash_variant name , name ) name methods in let name_hash = List . sort Pervasives . compare name_hash in let name_hash = List . mapi ( fun i ( _ , x ) x -> x , i ) i name_hash in let all_methods = List . map ( fun ( name , type_expr , index ) index -> let meth_return_type , meth_parameters = Wrap_common . flatten_arrow type_expr in let type_parameters = Wrap_arrow . get_type_parameters meth_parameters meth_return_type in let meth_return_type = Wrap_arrow . return_type_of_type_expr ~ reverse : true type_parameters meth_return_type and meth_return_type ' = Wrap_arrow . return_type_of_type_expr ~ reverse : false type_parameters meth_return_type in let return = match meth_return_type with | Some ( x , _ , _ ) _ -> Some x | None -> None in let both_parameters = List . mapi ( fun i te -> if is_unit te then None , Identifier " Value . UNIT " else let id = Printf . sprintf " p % d " i in let tt = TypeMap . find ~ generics : type_parameters false te in let t = tt . TypeInfo . java_type in let x = tt . TypeInfo . ocaml_of_java ( Identifier id ) id in Some ( t , id ) id , x ) x meth_parameters in let parameters , parameters2 = List . split both_parameters in let parameters = map_option parameters in let meth = method_ [ Public ; Abstract ] Abstract ~ return name ~ parameters [ ] in let meth2 = let this_value = Identifier " this . value " in let target = match index with | Some x -> ( get this_value x ) x | None -> let idx = List . assoc name name_hash in get ( get this_value 0 ) 0 ( 2 + ( 2 * idx ) idx ) idx in let apply_params = if is_object then target :: this_value :: parameters2 else target :: parameters2 in let call = Static_call ( " NativeApply " , " apply " , apply_params ) apply_params in let body = Wrap_arrow . make_body meth_return_type ' type_parameters call in let body = Wrap_arrow . make_try_catch ~ catch_all : true body in method_ ~ annotations [ " :@ Override ] " [ Public ; Final ] Final ~ return name ~ parameters body in let parameters = List . mapi ( fun i te -> let id = Printf . sprintf " p % d " i in if is_unit te then Some ( type_Value , id ) id , None else let tt = TypeMap . find ~ generics : type_parameters false te in let t = type_Value in let conv = tt . TypeInfo . java_of_ocaml in let formal = t , id in let effective = conv ( Identifier id ) id in Some formal , Some effective ) effective meth_parameters in let formal_meth_parameters , effective_meth_parameters = List . split parameters in let formal_meth_parameters = map_option formal_meth_parameters in let effective_meth_parameters = map_option effective_meth_parameters in let call = Call ( Identifier " this " , name , effective_meth_parameters ) effective_meth_parameters in let body = make_body meth_return_type call in let body = make_try_catch body in let formal_meth_parameters = if is_object then let dummy_self = type_Value , " self " in dummy_self :: formal_meth_parameters else formal_meth_parameters in let closure = method_ [ Public ; Final ] Final ~ return ( : Some type_Value ) type_Value ( name ^ " $ impl ) " ~ parameters : formal_meth_parameters ~ throws [ " : FailException ] " body in ( meth , meth2 , closure ) closure ) closure methods in split3 all_methods
type variant_kind = | Simple_variant | Polymorphic_variant
let get_element variant_kind x fields idx = if variant_kind = Simple_variant then get x idx else if ( List . length fields ) fields = 1 then get x 1 else get ( get x 1 ) 1 idx
let wrap ident constructors variant_kind type_parameters = let open JavaAST in let name = Ident . name ident in TypeMap . add_local ident ( variant_kind = Polymorphic_variant ) Polymorphic_variant ; let generics = TypeParametersTable . make type_parameters in let wrapper_fields , get_wrapper_meth , get_wrapper_idx_meth , wrapper_meth , wrap_meth = Wrap_common . make_wrapper_elements name type_parameters in let class_type = Reference ( name , [ ] ) in let type_T = Reference ( " T " , [ ] ) in let type_Visitor_T = Reference ( " Visitor " , type_T :: ( List . map ( fun ( id , _ ) _ -> Reference ( id , [ ] ) ) type_parameters ) type_parameters ) type_parameters in let ident_v = Identifier " v " in let ident_this = Identifier " this " in let ident_this_value = Identifier " this . value " in let ident_that_value = Identifier " that . value " in let type_TAG = Reference ( " TAG " , [ ] ) in let cstr = let wrapper_parameters , inits = Wrap_common . make_wrapper_cstr_elements wrapper_fields type_parameters in constructor [ Private ] Private name ~ parameters ( : wrapper_parameters @ [ type_Value , " v ] ) " ( [ Super_constructor [ ident_v ] ident_v ] ident_v @ inits ) inits in let make_switch_block long_block mk_block def_block = let _ , block_cases = List . fold_left ( fun ( idx_block , block_cases ) block_cases ( id , fields ) fields -> if fields = [ ] then begin idx_block , block_cases end else begin let case = ( idx_block , mk_block idx_block id fields ) fields in Int32 . succ idx_block , case :: block_cases end ) end ( 0l , [ ] ) constructors in let if_block = Switch ( Call ( ident_this_value , " getTag " , [ ] ) , List . rev block_cases , def_block ) def_block in If_else ( Call ( ident_this_value , " isBlock " , [ ] ) , if_block , long_block ) long_block in let make_switch_simple mk_long mk_block def_long def_block = let _ , block_cases , _ , long_cases = List . fold_left ( fun ( idx_block , block_cases , idx_long , long_cases ) long_cases ( id , fields ) fields -> if fields = [ ] then begin let case = ( idx_long , mk_long idx_long id ) id in idx_block , block_cases , Int32 . succ idx_long , case :: long_cases end else begin let case = ( idx_block , mk_block idx_block id fields ) fields in Int32 . succ idx_block , case :: block_cases , idx_long , long_cases end ) end ( 0l , [ ] , 0l , [ ] ) constructors in let if_block = Switch ( Call ( ident_this_value , " getTag " , [ ] ) , List . rev block_cases , def_block ) def_block in let else_block = Switch ( Call ( ident_this_value , " asCastedInt " , [ ] ) , List . rev long_cases , def_long ) def_long in If_else ( Call ( ident_this_value , " isBlock " , [ ] ) , if_block , else_block ) else_block in let make_switch_poly mk_long mk_block def_long def_block = let block_cases , long_cases = List . fold_left ( fun ( block_cases , long_cases ) long_cases ( id , fields ) fields -> let tag = Btype . hash_variant id in let tag = Int32 . of_int tag in if fields = [ ] then begin let case = ( tag , mk_long id ) id in block_cases , case :: long_cases end else begin let case = ( tag , mk_block id fields ) fields in case :: block_cases , long_cases end ) end ( [ ] , [ ] ) constructors in let if_block = Switch ( Call ( get ident_this_value 0 , " asCastedInt " , [ ] ) , List . rev block_cases , def_block ) def_block in let else_block = Switch ( Call ( ident_this_value , " asCastedInt " , [ ] ) , List . rev long_cases , def_long ) def_long in If_else ( Call ( ident_this_value , " isBlock " , [ ] ) , if_block , else_block ) else_block in let tag_meth = let default = Some ( return Null_literal ) Null_literal in let ident id = return ( Identifier ( Printf . sprintf " TAG . % s " id ) id ) id in if variant_kind = Simple_variant then method_ [ Public ] Public ~ return ( : Some type_TAG ) type_TAG " tag " [ make_switch_simple ( fun _ id -> ident id ) id ( fun _ id _ -> ident id ) id default default ] default else method_ [ Public ] Public ~ return ( : Some type_TAG ) type_TAG " tag " [ make_switch_poly ( fun id -> ident id ) id ( fun id _ -> ident id ) id default default ] default in let accessor_meths = List . map ( fun ( id , fields ) fields -> List . mapi ( fun idx field -> let info = TypeMap . find ~ generics false field in let res = get_element variant_kind ident_this_value fields idx in let res = info . TypeInfo . java_of_ocaml res in let name = Printf . sprintf " get % s % d " id idx in method_ [ Public ] Public ~ return ( : Some info . TypeInfo . java_type ) java_type name [ return ( cast_if_needed info . TypeInfo . java_type res ) res ] res ) res fields ) fields constructors in let visit_meth = let default = Some ( return Null_literal ) Null_literal in let ident_visitor = Identifier " visitor " in if variant_kind = Simple_variant then method_ ~ generics [ " : T ] " [ Public ] Public ~ return ( : Some type_T ) type_T " visit " ~ parameters [ : type_Visitor_T , " visitor ] " [ make_switch_simple ( fun _ id -> return ( Call ( ident_visitor , " visit " ^ id , [ ] ) ) ) ( fun _ id fields -> let l = List . mapi ( fun i field -> let info = TypeMap . find ~ generics false field in let v = get ident_this_value i in let v = info . TypeInfo . java_of_ocaml v in cast_if_needed info . TypeInfo . java_type v ) v fields in return ( Call ( ident_visitor , " visit " ^ id , l ) l ) l ) l default default ] default else method_ ~ generics [ " : T ] " [ Public ] Public ~ return ( : Some type_T ) type_T " visit " ~ parameters [ : type_Visitor_T , " visitor ] " [ make_switch_poly ( fun id -> return ( Call ( ident_visitor , " visit " ^ id , [ ] ) ) ) ( fun id fields -> let l = List . mapi ( fun i field -> let info = TypeMap . find ~ generics false field in let v = get_element variant_kind ident_this_value fields i in let v = info . TypeInfo . java_of_ocaml v in cast_if_needed info . TypeInfo . java_type v ) v fields in return ( Call ( ident_visitor , " visit " ^ id , l ) l ) l ) l default default ] default in let hash_code_meth = let call = Call ( ident_this , " tag " , [ ] ) in let call = Call ( call , " hashCode " , [ ] ) in method_ ~ annotations [ " :@ Override ] " [ Public ] Public ~ return ( : Some Int ) Int " hashCode " [ return call ] call in let equals_meth = let default = Some ( return ( Boolean_literal false ) false ) false in let body = if variant_kind = Simple_variant then make_switch_block ( return ( Infix ( " " , == Call ( ident_that_value , " asLong " , [ ] ) , Call ( ident_that_value , " asLong " , [ ] ) ) ) ) ( fun _ _ fields -> let l = List . mapi ( fun idx field -> let info = TypeMap . find ~ generics false field in let x = get ident_this_value idx in let x = info . TypeInfo . java_of_ocaml x in let y = get ident_that_value idx in let y = info . TypeInfo . java_of_ocaml y in if primitive_type info . TypeInfo . java_type then Infix ( " " , == x , y ) y else Call ( x , " equals " , [ y ] y ) y ) y fields in return ( and_list l ) l ) l default else make_switch_block ( return ( Infix ( " " , == Call ( ident_that_value , " asLong " , [ ] ) , Call ( ident_that_value , " asLong " , [ ] ) ) ) ) ( fun _ _ fields -> let l = List . mapi ( fun idx field -> let info = TypeMap . find ~ generics false field in let x = get_element variant_kind ident_this_value fields idx in let x = info . TypeInfo . java_of_ocaml x in let y = get_element variant_kind ident_that_value fields idx in let y = info . TypeInfo . java_of_ocaml y in if primitive_type info . TypeInfo . java_type then Infix ( " " , == x , y ) y else Call ( x , " equals " , [ y ] y ) y ) y fields in return ( and_list l ) l ) l default in method_ ~ annotations [ " :@ Override ] " [ Public ] Public ~ return ( : Some Boolean ) Boolean " equals " ~ parameters [ : type_Object , " obj ] " ( make_equals_body name " obj " [ body ] body ) body in let to_string_meth = let type_string_builder = Reference ( " StringBuilder " , [ ] ) in let append e = Expression ( Call ( Identifier " sb " , " append " , [ e ] e ) e ) e in let append_string s = append ( String_literal s ) s in let default = Some ( return Null_literal ) Null_literal in let long_case id = return ( String_literal ( Printf . sprintf " % s . % s ( s ) s " name id ) id ) id in let block_case id fields = Block ( [ Variable_declaration ( type_string_builder , " sb " , New ( " StringBuilder " , [ ] ) ) ; append_string ( Printf . sprintf " % s . % s ( s " name id ) id ] @ ( List . flatten ( List . mapi ( fun idx field -> let info = TypeMap . find ~ generics false field in let v = get_element variant_kind ident_this_value fields idx in let v = info . TypeInfo . java_of_ocaml v in if idx > 0 then [ append_string " , " ; append v ] v else [ append v ] v ) v fields ) fields ) fields @ [ append_string ) " " ; return ( Call ( Identifier " sb " , " toString " , [ ] ) ) ] ) in let body = if variant_kind = Simple_variant then make_switch_simple ( fun _ id -> long_case id ) id ( fun _ id fields -> block_case id fields ) fields default default else make_switch_poly ( fun id -> long_case id ) id ( fun id fields -> block_case id fields ) fields default default in method_ ~ annotations [ " :@ Override ] " [ Public ] Public ~ return ( : Some type_String ) type_String " toString " [ body ] body in let _ , _ , create_meths = List . fold_left ( fun ( idx_block , idx_long , acc ) acc ( id , fields ) fields -> if fields <> [ ] then begin let l = List . mapi ( fun i field -> let p = Identifier ( Printf . sprintf " p % d " i ) i in let info = TypeMap . find ~ generics false field in info . TypeInfo . ocaml_of_java p ) p fields in let old_name = name in let name = Printf . sprintf " create % s " id in let used = ref [ ] in let parameters = List . mapi ( fun i field -> let info = TypeMap . find ~ generics false field in ( match field . Types . desc with | Types . Tvar ( Some id ) id -> if not ( List . mem_assoc id ! used ) used then begin used := ( id , i ) i :: ! used end | _ -> ( ) ) ; info . TypeInfo . java_type , Printf . sprintf " p % d " i ) i fields in let meth = let additional_parameters = ref [ ] in let quantif = List . map ( fun ( id , _ ) _ -> if not ( List . mem_assoc id ! used ) used then begin let ap = Reference ( " Wrapper " , [ Reference ( id , [ ] ) ] ) , " w " ^ id in additional_parameters := ap :: ! additional_parameters ; end ; Printf . sprintf " % s extends OCamlValue " id ) id type_parameters in let parameters = parameters @ ! additional_parameters in let wrappers = List . map ( fun ( id , _ ) _ -> if List . mem_assoc id ! used then begin let p = Identifier ( " p " ^ ( string_of_int ( List . assoc id ! used ) used ) used ) used in Call ( p , " getWrapper " , [ ] ) end else begin Identifier ( " w " ^ id ) id end ) end type_parameters in let res = if variant_kind = Simple_variant then New ( old_name , wrappers @ [ create_block idx_block l ] l ) l else if ( List . length fields ) fields = 1 then let tag = Btype . hash_variant id in New ( old_name , wrappers @ [ create_block 0 ( ( create_long tag ) tag :: l ) l ] l ) l else let tag = Btype . hash_variant id in let params = create_block 0 l in New ( old_name , wrappers @ [ create_block 0 ( ( create_long tag ) tag :: [ params ] params ) params ] params ) params in method_ ~ generics : quantif ~ annotations ( : if quantif = [ ] then [ ] else [ " @ SuppressWarnings ( SuppressWarnings " \ unchecked ) ] ) " " \ [ Public ; Static ] Static ~ return ( : Some class_type ) class_type name ~ parameters [ return res ] res in ( succ idx_block , idx_long , meth :: acc ) acc end else begin let res = if variant_kind = Simple_variant then New ( name , [ create_long idx_long ] idx_long ) idx_long else New ( name , [ create_long ( Btype . hash_variant id ) id ] id ) id in let name = Printf . sprintf " create % s " id in let meth = method_ [ Public ; Static ] Static ~ return ( : Some class_type ) class_type name [ return res ] res in ( idx_block , succ idx_long , meth :: acc ) acc end ) end ( 0 , 0 , [ ] ) constructors in let tag_class = { enum_modifiers = [ Public ; Static ] Static ; enum_name = " TAG " ; enum_values = ( List . map fst constructors ) constructors ; } in let visitor_itf = let meths = List . map ( fun ( id , fields ) fields -> let l = List . map ( fun field -> let info = TypeMap . find ~ generics false field in info . TypeInfo . java_type ) java_type fields in type_T , " visit " ^ id , l ) l constructors in let l = List . map fst type_parameters in let l = String . concat " , " l in let l = if l = " " then l else " , " ^ l in { interf_modifiers = [ Public ] Public ; interf_name = " Visitor < T " ^ l ^ " " ; > interf_methods = meths ; } in let full_name = if type_parameters = [ ] then name else let tmp = List . map ( fun ( id , _ ) _ -> Printf . sprintf " % s extends OCamlValue " id ) id type_parameters in name ^ " " < ^ ( String . concat " , " tmp ) tmp ^ " " > in class_ [ Public ; Static ; Final ] Final full_name ~ extends ( : Some " OCamlValue ) " ~ fields : wrapper_fields ~ methods ( [ : cstr ; get_wrapper_meth ; get_wrapper_idx_meth ; tag_meth ] tag_meth @ ( List . flatten accessor_meths ) accessor_meths @ [ visit_meth ; hash_code_meth ; equals_meth ; to_string_meth ] to_string_meth @ ( List . rev create_meths ) create_meths @ [ wrap_meth ; wrapper_meth ] wrapper_meth ) wrapper_meth ~ inner [ : Enum tag_class ; Interface visitor_itf ] visitor_itf ( )
module type Inputs = Intf . Wrap_main_inputs . S
let challenge_polynomial ~ one ~ add ~ mul chals = let ( + ) = add and ( * ) = mul in stage ( fun pt -> let k = Array . length chals in let pow_two_pows = let res = Array . init k ~ f ( : fun _ -> pt ) pt in for i = 1 to k - 1 do let y = res ( . i - 1 ) 1 in res ( . i ) i <- y * y done ; res in let prod f = let r = ref ( f 0 ) 0 in for i = 1 to k - 1 do r := f i * ! r done ; ! r in prod ( fun i -> one + ( chals ( . i ) i * pow_two_pows ( . k - 1 - i ) i ) i ) i )
module Make ( Inputs : Inputs with type Impl . field = Tock . Field . t and type Impl . Bigint . t = Tock . Bigint . R . t and type Inner_curve . Constant . Scalar . t = Tick . Field . t ) t = struct open Inputs open Impl module Other_field = struct module Packed = struct module Constant = Other_field type t = Impls . Wrap . Other_field . t let typ = Impls . Wrap . Other_field . typ let to_bits_unsafe ( x : t ) t = Wrap_main_inputs . Unsafe . unpack_unboolean x let absorb_shifted sponge ( x : t Shifted_value . Type1 . t ) t = match x with Shifted_value x -> Sponge . absorb sponge x end module With_top_bit0 = struct module Constant = Other_field type t = Impls . Wrap . Other_field . t let typ = Impls . Wrap . Other_field . typ_unchecked let absorb_shifted sponge ( x : t Shifted_value . Type1 . t ) t = match x with Shifted_value x -> Sponge . absorb sponge x end end let print_g lab ( x , y ) y = if debug then as_prover As_prover ( . fun ( ) -> printf " !% s : { % sexp : Backend . Tock . Field . t } t , { % sexp : Backend . Tock . Field . t } t \ n \ " %! lab ( read_var x ) x ( read_var y ) y ) y let print_w lab gs = if debug then Array . iteri gs ~ f ( : fun i ( fin , g ) g -> as_prover As_prover ( . fun ( ) -> printf " fin =% b " %! ( read Boolean . typ fin ) fin ) fin ; ksprintf print_g " % s [ s % d ] d " lab i g ) let print_chal lab x = if debug then as_prover As_prover ( . fun ( ) -> printf " in - snark % s " :%! lab ; Field . Constant . print ( Field . Constant . project ( List . map ~ f ( : read Boolean . typ ) typ x ) x ) x ; printf " \ n ) " %! let print_bool lab x = if debug then as_prover ( fun ( ) -> printf " % s : % b \ n " %! lab ( As_prover . read Boolean . typ x ) x ) module Challenge = Challenge . Make ( Impl ) Impl module Digest = Digest . Make ( Impl ) Impl module Scalar_challenge = SC . Make ( Impl ) Impl ( Inner_curve ) Inner_curve ( Challenge ) Challenge ( Endo . Wrap_inner_curve ) Wrap_inner_curve module Ops = Plonk_curve_ops . Make ( Impl ) Impl ( Inner_curve ) Inner_curve let product m f = List . reduce_exn ( List . init m ~ f ) f ~ f : Field ( . * ) let absorb sponge ty t = absorb ~ mask_g1_opt ( : fun ( ) -> assert false ) false ~ absorb_field ( : Sponge . absorb sponge ) sponge ~ g1_to_field_elements : Inner_curve . to_field_elements ~ absorb_scalar ( : Sponge . absorb sponge ) sponge ty t let scalar_to_field s = SC . to_field_checked ( module Impl ) Impl s ~ endo : Endo . Step_inner_curve . scalar let lowest_128_bits ~ constrain_low_bits x = let assert_128_bits a = ignore ( scalar_to_field ( SC . SC . create a ) a : Field . t ) t in Util . lowest_128_bits ~ constrain_low_bits ~ assert_128_bits ( module Impl ) Impl x let squeeze_challenge sponge : Field . t = lowest_128_bits ~ constrain_low_bits : true ( Sponge . squeeze sponge ) sponge let squeeze_scalar sponge : Field . t SC . SC . t = SC . SC . create ( lowest_128_bits ~ constrain_low_bits : false ( Sponge . squeeze sponge ) sponge ) sponge let bullet_reduce sponge gammas = let absorb t = absorb sponge t in let prechallenges = Array . map gammas ~ f ( : fun gammas_i -> absorb ( PC :: PC ) PC gammas_i ; squeeze_scalar sponge ) in let term_and_challenge ( l , r ) r pre = let left_term = Scalar_challenge . endo_inv l pre in let right_term = Scalar_challenge . endo r pre in ( Ops . add_fast left_term right_term , { Bulletproof_challenge . prechallenge = pre } ) in let terms , challenges = Array . map2_exn gammas prechallenges ~ f : term_and_challenge |> Array . unzip in ( Array . reduce_exn terms ~ f : Ops . add_fast , challenges ) challenges let equal_g g1 g2 = List . map2_exn ~ f : Field . equal ( Inner_curve . to_field_elements g1 ) g1 ( Inner_curve . to_field_elements g2 ) g2 |> Boolean . all module One_hot_vector = One_hot_vector . Make ( Impl ) Impl type ' a index ' = ' a Plonk_verification_key_evals . t type ' a index = ' a Plonk_verification_key_evals . t let choose_key : type n . n One_hot_vector . t -> ( Inner_curve . t index ' , n ) n Vector . t -> Inner_curve . t index ' = let open Tuple_lib in let map = Plonk_verification_key_evals . map in let map2 = Plonk_verification_key_evals . map2 in fun bs keys -> let open Field in Vector . map2 ( bs :> ( Boolean . var , n ) n Vector . t ) t keys ~ f ( : fun b key -> map key ~ f ( : fun g -> Double . map g ~ f ( ( : * ) ( b :> t ) t ) t ) t ) t |> Vector . reduce_exn ~ f ( : map2 ~ f ( : Double . map2 ~ f ( : + ) ) ) |> map ~ f ( : fun g -> Double . map ~ f ( : Util . seal ( module Impl ) Impl ) Impl g ) g let lagrange ( type n ) n ~ domain : ( ( which_branch : n One_hot_vector . t ) t , ( domains : ( Domains . t , n ) n Vector . t ) t ) i = Vector . map domains ~ f ( : fun d -> let d = Precomputed . Lagrange_precomputations . index_of_domain_log2 ( Domain . log2_size d . h ) h in match Precomputed . Lagrange_precomputations . vesta ( . d ) d ( . i ) i with | [ | g ] | -> let g = Inner_curve . Constant . of_affine g in Inner_curve . constant g | _ -> assert false ) |> Vector . map2 ( which_branch :> ( Boolean . var , n ) n Vector . t ) t ~ f ( : fun b ( x , y ) y -> Field ( ( . b :> t ) t * x , ( b :> t ) t * y ) y ) y |> Vector . reduce_exn ~ f ( : Double . map2 ~ f : Field ( . + ) ) let lagrange_with_correction ( type n ) n ~ input_length ~ domain : ( ( which_branch : n One_hot_vector . t ) t , ( domains : ( Domains . t , n ) n Vector . t ) t ) i : Inner_curve . t Double . t = with_label __LOC__ ( fun ( ) -> let actual_shift = Ops . bits_per_chunk * Ops . chunks_needed ~ num_bits : input_length in let rec pow2pow x i = if i = 0 then x else pow2pow Inner_curve . Constant ( . x + x ) x ( i - 1 ) 1 in let base_and_correction ( h : Domain . t ) t = let d = Precomputed . Lagrange_precomputations . index_of_domain_log2 ( Domain . log2_size h ) h in match Precomputed . Lagrange_precomputations . vesta ( . d ) d ( . i ) i with | [ | g ] | -> let open Inner_curve . Constant in let g = of_affine g in ( Inner_curve . constant g , Inner_curve . constant ( negate ( pow2pow g actual_shift ) actual_shift ) actual_shift ) | xs -> failwithf " expected commitment to have length 1 . got % d " ( Array . length xs ) xs ( ) in match domains with | [ ] -> assert false | d :: ds -> if Vector . for_all ds ~ f ( : fun d ' -> Domain . equal d . h d ' . h ) h then base_and_correction d . h else Vector . map domains ~ f ( : fun ( ds : Domains . t ) t -> base_and_correction ds . h ) |> Vector . map2 ( which_branch :> ( Boolean . var , n ) n Vector . t ) t ~ f ( : fun b pr -> Double . map pr ~ f ( : fun ( x , y ) y -> Field ( ( . b :> t ) t * x , ( b :> t ) t * y ) y ) ) |> Vector . reduce_exn ~ f ( : Double . map2 ~ f ( : Double . map2 ~ f : Field ( . + ) ) ) |> Double . map ~ f ( : Double . map ~ f ( : Util . seal ( module Impl ) Impl ) Impl ) Impl ) let h_precomp = Lazy . map ~ f : Inner_curve . Scaling_precomputation . create Generators . h let group_map = let f = lazy ( let module M = Group_map . Bw19 . Make ( Field . Constant ) Constant ( Field ) Field ( struct let params = Group_map . Bw19 . Params . create ( module Field . Constant ) Constant { b = Inner_curve . Params . b } end ) end in let open M in Snarky_group_map . Checked . wrap ( module Impl ) Impl ~ potential_xs ~ y_squared ( : fun ~ x -> Field ( . ( x * x * x ) x + ( constant Inner_curve . Params . a * x ) x + constant Inner_curve . Params . b ) b ) |> unstage ) in fun x -> Lazy . force f x module Split_commitments = struct module Point = struct type t = [ ` Finite of Inner_curve . t | ` Maybe_finite of Boolean . var * Inner_curve . t ] let finite : t -> Boolean . var = function | ` Finite _ -> Boolean . true_ | ` Maybe_finite ( b , _ ) _ -> b let add ( p : t ) t ( q : Inner_curve . t ) t = match p with | ` Finite p -> Ops . add_fast p q | ` Maybe_finite ( finite , p ) p -> Inner_curve . if_ finite ~ then_ ( : Ops . add_fast p q ) q ~ else_ : q let underlying = function ` Finite p -> p | ` Maybe_finite ( _ , p ) p -> p end module Curve_opt = struct type t = { point : Inner_curve . t ; non_zero : Boolean . var } end let combine batch ~ xi without_bound with_bound = let { Curve_opt . non_zero ; point } = Pcs_batch . combine_split_commitments batch ~ scale_and_add ( : fun ( ~ acc : Curve_opt . t ) t ~ xi ( keep , ( p : Point . t ) t ) t -> let point = Inner_curve ( . if_ keep ~ then_ : ( if_ acc . non_zero ~ then_ ( : Point . add p ( Scalar_challenge . endo acc . point xi ) xi ) xi ~ else_ : ( Point . underlying p ) ) ~ else_ : acc . point ) point in let non_zero = Boolean ( . keep &&& Point . finite p ||| acc . non_zero ) non_zero in { Curve_opt . non_zero ; point } ) ~ xi ~ init ( : fun ( keep , p ) p -> { non_zero = Boolean ( . keep &&& Point . finite p ) p ; point = Point . underlying p } ) without_bound with_bound in Boolean . Assert . is_true non_zero ; point end let scale_fast = Ops . scale_fast let check_bulletproof ~ pcs_batch ( ~ sponge : Sponge . t ) t ( ~ xi : Scalar_challenge . t ) t ( ~ advice : Other_field . Packed . t Shifted_value . Type1 . t Types . Step . Bulletproof . Advice . t ) ~ polynomials ( : without_degree_bound , with_degree_bound ) with_degree_bound ~ openings_proof : ( { lr ; delta ; z_1 ; z_2 ; challenge_polynomial_commitment } : ( Inner_curve . t , Other_field . Packed . t Shifted_value . Type1 . t ) Openings . Bulletproof . t ) = with_label __LOC__ ( fun ( ) -> Other_field . Packed . absorb_shifted sponge advice . combined_inner_product ; let u = let t = Sponge . squeeze_field sponge in group_map t in let open Inner_curve in let combined_polynomial = Split_commitments . combine pcs_batch ~ xi without_degree_bound with_degree_bound in let scale_fast = scale_fast ~ num_bits : Other_field . Packed . Constant . size_in_bits in let lr_prod , challenges = bullet_reduce sponge lr in let p_prime = let uc = scale_fast u advice . combined_inner_product in combined_polynomial + uc in let q = p_prime + lr_prod in absorb sponge PC delta ; let c = squeeze_scalar sponge in let lhs = let cq = Scalar_challenge . endo q c in cq + delta in let rhs = let b_u = scale_fast u advice . b in let z_1_g_plus_b_u = scale_fast ( challenge_polynomial_commitment + b_u ) b_u z_1 in let z2_h = scale_fast ( Inner_curve . constant ( Lazy . force Generators . h ) h ) h z_2 in z_1_g_plus_b_u + z2_h in ( ` Success ( equal_g lhs rhs ) rhs , challenges ) challenges ) module Opt = struct include Opt_sponge . Make ( Impl ) Impl ( Wrap_main_inputs . Sponge . Permutation ) Permutation let challenge ( s : t ) t : Field . t = lowest_128_bits ( squeeze s ) s ~ constrain_low_bits : true let scalar_challenge ( s : t ) t : Scalar_challenge . t = SC . SC . create ( lowest_128_bits ( squeeze s ) s ~ constrain_low_bits : false ) false end let absorb sponge ty t = Util . absorb ~ absorb_field ( : Opt . absorb sponge ) sponge ~ g1_to_field_elements ( : fun ( b , ( x , y ) y ) y -> [ ( b , x ) x ; ( b , y ) y ] ) ~ absorb_scalar ( : fun x -> Opt . absorb sponge ( Boolean . true_ , x ) x ) x ~ mask_g1_opt ( : fun ( ( finite : Boolean . var ) var , ( x , y ) y ) y -> ( Boolean . true_ , Field ( ( . finite :> t ) t * x , ( finite :> t ) t * y ) y ) y ) ty t module Pseudo = Pseudo . Make ( Impl ) Impl let mask ( type n ) n ( lengths : ( int , n ) n Vector . t ) t ( choice : n One_hot_vector . t ) t : Boolean . var array = let max = Option . value_exn ( List . max_elt ~ compare : Int . compare ( Vector . to_list lengths ) lengths ) lengths in let length = Pseudo . choose ( choice , lengths ) lengths ~ f : Field . of_int in let ( T max ) max = Nat . of_int max in Vector . to_array ( ones_vector ( module Impl ) Impl ~ first_zero : length max ) max module Plonk = Types . Wrap . Proof_state . Deferred_values . Plonk let iter2 ~ chal ~ scalar_chal { Plonk . Minimal . alpha = alpha_0 ; beta = beta_0 ; gamma = gamma_0 ; zeta = zeta_0 } { Plonk . Minimal . alpha = alpha_1 ; beta = beta_1 ; gamma = gamma_1 ; zeta = zeta_1 } = chal beta_0 beta_1 ; chal gamma_0 gamma_1 ; scalar_chal alpha_0 alpha_1 ; scalar_chal zeta_0 zeta_1 let assert_eq_marlin ( m1 : ( _ , Field . t Import . Scalar_challenge . t ) t Plonk . Minimal . t ) t ( m2 : ( _ , Scalar_challenge . t ) t Plonk . Minimal . t ) t = iter2 m1 m2 ~ chal ( : fun c1 c2 -> Field . Assert . equal c1 c2 ) c2 ~ scalar_chal ( : fun ( { inner = t1 } : _ Import . Scalar_challenge . t ) t ( { inner = t2 } : Scalar_challenge . t ) t -> Field . Assert . equal t1 t2 ) let incrementally_verify_proof ( type b ) b ( module Max_proofs_verified : Nat . Add . Intf with type n = b ) b ~ step_widths ~ step_domains ~ verification_key ( : m : _ Plonk_verification_key_evals . t ) t ~ xi ~ sponge ( ~ public_input : [ ` Field of Field . t * Boolean . var | ` Packed_bits of Field . t * int ] array ) ( ~ sg_old : ( _ , Max_proofs_verified . n ) n Vector . t ) t ~ advice ( ~ messages : _ Messages . t ) t ~ which_branch ~ openings_proof ( ~ plonk : _ Types . Wrap . Proof_state . Deferred_values . Plonk . In_circuit . t ) t = let T = Max_proofs_verified . eq in let public_input = Array . concat_map public_input ~ f ( : function | ` Field ( x , b ) b -> [ | ( x , Field . size_in_bits ) size_in_bits ; ( ( b :> Field . t ) t , 1 ) 1 ] | | ` Packed_bits ( x , n ) n -> [ | ( x , n ) n ] | ) in let sg_old = with_label __LOC__ ( fun ( ) -> let actual_width = Pseudo . choose ( which_branch , step_widths ) step_widths ~ f : Field . of_int in Vector . map2 ( ones_vector ( module Impl ) Impl ~ first_zero : actual_width Max_proofs_verified . n ) sg_old ~ f ( : fun keep sg -> [ | ( keep , sg ) sg ] ) | ) in with_label __LOC__ ( fun ( ) -> let sample ( ) = Opt . challenge sponge in let sample_scalar ( ) : Scalar_challenge . t = Opt . scalar_challenge sponge in let open Plonk_types . Messages in let x_hat = with_label __LOC__ ( fun ( ) -> let domain = ( which_branch , step_domains ) step_domains in let terms = with_label __LOC__ ( fun ( ) -> Array . mapi public_input ~ f ( : fun i x -> match x with | b , 1 -> assert_ ( Constraint . boolean ( b :> Field . t ) t ) t ; ` Cond_add ( Boolean . Unsafe . of_cvar b , lagrange ~ domain i ) i | x , n -> ` Add_with_correction ( ( x , n ) n , lagrange_with_correction ~ input_length : n ~ domain i ) ) ) in let correction = with_label __LOC__ ( fun ( ) -> Array . reduce_exn ( Array . filter_map terms ~ f ( : function | ` Cond_add _ -> None | ` Add_with_correction ( _ , ( _ , corr ) corr ) corr -> Some corr ) ) ~ f : Ops . add_fast ) in with_label __LOC__ ( fun ( ) -> Array . foldi terms ~ init : correction ~ f ( : fun i acc term -> match term with | ` Cond_add ( b , g ) g -> with_label __LOC__ ( fun ( ) -> Inner_curve . if_ b ~ then_ ( : Ops . add_fast g acc ) acc ~ else_ : acc ) | ` Add_with_correction ( ( x , num_bits ) num_bits , ( g , _ ) _ ) _ -> Ops . add_fast acc ( Ops . scale_fast2 ' ( module Other_field . With_top_bit0 ) With_top_bit0 g x ~ num_bits ) ) ) ) |> Inner_curve . negate in let without = Type . Without_degree_bound in let absorb_g gs = absorb sponge without ( Array . map gs ~ f ( : fun g -> ( Boolean . true_ , g ) g ) g ) g in absorb sponge PC ( Boolean . true_ , x_hat ) x_hat ; let w_comm = messages . w_comm in Vector . iter ~ f : absorb_g w_comm ; let beta = sample ( ) in let gamma = sample ( ) in let z_comm = messages . z_comm in absorb_g z_comm ; let alpha = sample_scalar ( ) in let t_comm : ( Inputs . Impl . Field . t * Inputs . Impl . Field . t ) t Pickles_types__Plonk_types . Poly_comm . Without_degree_bound . t = messages . t_comm in absorb_g t_comm ; let zeta = sample_scalar ( ) in let sponge = match sponge with | { state ; sponge_state ; params } -> ( match sponge_state with | Squeezed n -> S . make ~ state ~ sponge_state ( : Squeezed n ) n ~ params | _ -> assert false ) in let sponge_before_evaluations = Sponge . copy sponge in let sponge_digest_before_evaluations = Sponge . squeeze_field sponge in let sigma_comm_init , [ _ ] = Vector . split m . sigma_comm ( snd ( Permuts_minus_1 . add Nat . N1 . n ) n ) n in let scale_fast = scale_fast ~ num_bits : Other_field . Packed . Constant . size_in_bits in let ft_comm = with_label __LOC__ ( fun ( ) -> Common . ft_comm ~ add : Ops . add_fast ~ scale : scale_fast ~ negate : Inner_curve . negate ~ endoscale : Scalar_challenge . endo ~ verification_key : m ~ plonk ~ alpha ~ t_comm ) in let bulletproof_challenges = let num_commitments_without_degree_bound = Nat . N26 . n in let without_degree_bound = Vector . append sg_old ( [ | x_hat ] | :: [ | ft_comm ] | :: z_comm :: [ | m . generic_comm ] | :: [ | m . psm_comm ] | :: Vector . append w_comm ( Vector . map sigma_comm_init ~ f ( : fun g -> [ | g ] ) ) | ( snd ( Columns . add Permuts_minus_1 . n ) n ) n |> Vector . map ~ f ( : Array . map ~ f ( : fun g -> ( Boolean . true_ , g ) g ) g ) g ) ( snd ( Max_proofs_verified . add num_commitments_without_degree_bound ) num_commitments_without_degree_bound ) in check_bulletproof ~ pcs_batch : ( Common . dlog_pcs_batch ( Max_proofs_verified . add num_commitments_without_degree_bound ) num_commitments_without_degree_bound ) ~ sponge : sponge_before_evaluations ~ xi ~ advice ~ openings_proof ~ polynomials : ( Vector . map without_degree_bound ~ f ( : Array . map ~ f ( : fun ( keep , x ) x -> ( keep , ` Finite x ) x ) x ) x , [ ] ) in assert_eq_marlin { alpha = plonk . alpha ; beta = plonk . beta ; gamma = plonk . gamma ; zeta = plonk . zeta } { alpha ; beta ; gamma ; zeta } ; ( sponge_digest_before_evaluations , bulletproof_challenges ) bulletproof_challenges ) module Split_evaluations = struct let combine_split_evaluations ' s = Pcs_batch . combine_split_evaluations s ~ mul ( : fun ( keep , x ) x ( y : Field . t ) t -> ( keep , Field ( . y * x ) x ) x ) x ~ mul_and_add ( : fun ~ acc ~ xi ( keep , fx ) fx -> Field . if_ keep ~ then_ : Field ( . fx + ( xi * acc ) acc ) acc ~ else_ : acc ) ~ init ( : fun ( _ , fx ) fx -> fx ) fx ~ shifted_pow : ( Pseudo . Degree_bound . shifted_pow ~ crs_max_degree : Common . Max_degree . wrap ) end let mask_evals ( type n ) n ( ~ lengths : ( int , n ) n Vector . t Evals . t ) t ( choice : n One_hot_vector . t ) t ( e : Field . t array Evals . t ) t : ( Boolean . var * Field . t ) t array Evals . t = Evals . map2 lengths e ~ f ( : fun lengths e -> Array . zip_exn ( mask lengths choice ) choice e ) let combined_evaluation ( type b b_plus_26 ) b_plus_26 b_plus_26 ~ xi ~ evaluation_point ( ( without_degree_bound : ( _ , b_plus_26 ) b_plus_26 Vector . t ) t , with_degree_bound ) with_degree_bound ~ max_quot_size = let open Field in with_label __LOC__ ( fun ( ) -> Pcs_batch . combine_split_evaluations ~ mul ~ last : Array . last ~ mul_and_add ( : fun ~ acc ~ xi fx -> fx + ( xi * acc ) acc ) acc ~ shifted_pow : ( Pseudo . Degree_bound . shifted_pow ~ crs_max_degree : Common . Max_degree . wrap ) ~ init : Fn . id ~ evaluation_point ~ xi ( Common . dlog_pcs_batch b_plus_26 ) b_plus_26 without_degree_bound with_degree_bound ) let compute_challenges ~ scalar chals = Vector . map chals ~ f ( : fun { Bulletproof_challenge . prechallenge } -> scalar prechallenge ) let challenge_polynomial = Field ( . challenge_polynomial ~ add ~ mul ~ one ) one let pow2pow ( pt : Field . t ) t ( n : int ) int : Field . t = with_label __LOC__ ( fun ( ) -> let rec go acc i = if i = 0 then acc else go ( Field . square acc ) acc ( i - 1 ) 1 in go pt n ) let actual_evaluation ( e : Field . t array ) array ( ~ pt_to_n : Field . t ) t : Field . t = with_label __LOC__ ( fun ( ) -> match List . rev ( Array . to_list e ) e with | e :: es -> List . fold ~ init : e es ~ f ( : fun acc y -> let acc ' = exists Field . typ ~ compute ( : fun ( ) -> As_prover . read_var Field ( . y + ( pt_to_n * acc ) acc ) acc ) in let pt_n_acc = Field ( . pt_to_n * acc ) acc in let open Kimchi_backend_common . Plonk_constraint_system . Plonk_constraint in let open Field . Constant in assert_ [ { annotation = None ; basic = T ( Basic { l = ( one , y ) y ; r = ( one , pt_n_acc ) pt_n_acc ; o = ( negate one , acc ' ) acc ' ; m = zero ; c = zero } ) } ] ; acc ' ) | [ ] -> failwith " empty list " ) let shift1 = Shifted_value . Type1 . Shift ( . map ~ f : Field . constant ( create ( module Field . Constant ) Constant ) Constant ) Constant let shift2 = Shifted_value . Type2 . Shift ( . map ~ f : Field . constant ( create ( module Field . Constant ) Constant ) Constant ) Constant let % test_unit " endo scalar " = SC . test ( module Impl ) Impl ~ endo : Endo . Step_inner_curve . scalar let map_plonk_to_field plonk = Types . Step . Proof_state . Deferred_values . Plonk . In_circuit . map_challenges ~ f ( : Util . seal ( module Impl ) Impl ) Impl ~ scalar : scalar_to_field plonk |> Types . Step . Proof_state . Deferred_values . Plonk . In_circuit . map_fields ~ f ( : Shifted_value . Type2 . map ~ f ( : Util . seal ( module Impl ) Impl ) Impl ) Impl module Plonk_checks = struct include Plonk_checks include Plonk_checks . Make ( Shifted_value . Type2 ) Type2 ( Plonk_checks . Scalars . Tock ) Tock end let finalize_other_proof ( type b ) b ( module Proofs_verified : Nat . Add . Intf with type n = b ) b ? actual_proofs_verified ~ domain ~ max_quot_size ~ sponge ( ~ old_bulletproof_challenges : ( _ , b ) b Vector . t ) t ( { xi ; combined_inner_product ; bulletproof_challenges ; b ; plonk } : ( _ , _ , _ Shifted_value . Type2 . t , _ ) Types . Step . Proof_state . Deferred_values . In_circuit . t ) { Plonk_types . All_evals . ft_eval1 ; evals = ( { evals = evals1 ; public_input = x_hat1 } , { evals = evals2 ; public_input = x_hat2 } ) } = let T = Proofs_verified . eq in let open Vector in let open Field in let absorb_evals x_hat e = with_label __LOC__ ( fun ( ) -> let xs , ys = Evals . to_vectors e in List . iter Vector ( [ . | x_hat ] | :: ( to_list xs @ to_list ys ) ys ) ys ~ f ( : Array . iter ~ f ( : Sponge . absorb sponge ) sponge ) sponge ) in absorb_evals x_hat1 evals1 ; absorb_evals x_hat2 evals2 ; Sponge . absorb sponge ft_eval1 ; let xi_actual = squeeze_scalar sponge in let r_actual = squeeze_challenge sponge in let xi_correct = with_label __LOC__ ( fun ( ) -> let { SC . SC . inner = xi_actual } = xi_actual in let { SC . SC . inner = xi } = xi in Field . equal xi_actual xi ) in let xi = scalar_to_field xi in let r = scalar_to_field ( SC . SC . create r_actual ) r_actual in let plonk = map_plonk_to_field plonk in let zetaw = Field . mul domain # generator plonk . zeta in let plonk_minimal = Plonk . to_minimal plonk in let combined_evals = let n = Common . Max_degree . wrap_log2 in let zeta_n = pow2pow plonk . zeta n in let zetaw_n = pow2pow zetaw n in ( Plonk_types . Evals . map ~ f ( : actual_evaluation ~ pt_to_n : zeta_n ) zeta_n evals1 , Plonk_types . Evals . map ~ f ( : actual_evaluation ~ pt_to_n : zetaw_n ) zetaw_n evals2 ) in let env = Plonk_checks . scalars_env ( module Field ) Field ~ srs_length_log2 : Common . Max_degree . wrap_log2 ~ endo ( : Impl . Field . constant Endo . Wrap_inner_curve . base ) base ~ mds : sponge_params . mds ~ field_of_hex ( : fun s -> Kimchi_pasta . Pasta . Bigint256 . of_hex_string s |> Kimchi_pasta . Pasta . Fq . of_bigint |> Field . constant ) ~ domain ( Plonk . to_minimal plonk ) plonk combined_evals in let combined_inner_product_correct = with_label __LOC__ ( fun ( ) -> let ft_eval0 : Field . t = with_label __LOC__ ( fun ( ) -> Plonk_checks . ft_eval0 ( module Field ) Field ~ env ~ domain plonk_minimal combined_evals x_hat1 ) in let actual_combined_inner_product = let sg_olds = Vector . map old_bulletproof_challenges ~ f ( : fun chals -> unstage ( challenge_polynomial ( Vector . to_array chals ) chals ) chals ) in let combine ~ ft pt x_hat e = let pi = Proofs_verified . add Nat . N26 . n in let a , b = Evals . to_vectors ( e : Field . t array Evals . t ) t in let sg_evals = match actual_proofs_verified with | None -> Vector . map sg_olds ~ f ( : fun f -> [ | f pt ] ) | | Some proofs_verified -> let mask = ones_vector ( module Impl ) Impl ~ first_zero : proofs_verified ( Vector . length sg_olds ) sg_olds in with_label __LOC__ ( fun ( ) -> Vector . map2 mask sg_olds ~ f ( : fun b f -> [ | Field ( ( . b :> t ) t * f pt ) pt ] | ) ) in let v = Vector . append sg_evals ( [ | x_hat ] | :: [ | ft ] | :: a ) a ( snd pi ) pi in combined_evaluation pi ~ xi ~ evaluation_point : pt ( v , b ) b ~ max_quot_size in combine ~ ft : ft_eval0 plonk . zeta x_hat1 evals1 + ( r * combine ~ ft : ft_eval1 zetaw x_hat2 evals2 ) evals2 in with_label __LOC__ ( fun ( ) -> equal ( Shifted_value . Type2 . to_field ( module Field ) Field ~ shift : shift2 combined_inner_product ) actual_combined_inner_product ) ) in let bulletproof_challenges = with_label __LOC__ ( fun ( ) -> compute_challenges ~ scalar : scalar_to_field bulletproof_challenges ) in let b_correct = with_label __LOC__ ( fun ( ) -> let challenge_poly = unstage ( challenge_polynomial ( Vector . to_array bulletproof_challenges ) bulletproof_challenges ) bulletproof_challenges in let b_actual = challenge_poly plonk . zeta + ( r * challenge_poly zetaw ) zetaw in equal ( Shifted_value . Type2 . to_field ( module Field ) Field ~ shift : shift2 b ) b b_actual ) in let plonk_checks_passed = with_label __LOC__ ( fun ( ) -> Plonk_checks . checked ( module Impl ) Impl ~ env ~ shift : shift2 plonk combined_evals ) in print_bool " xi_correct " xi_correct ; print_bool " combined_inner_product_correct " combined_inner_product_correct ; print_bool " plonk_checks_passed " plonk_checks_passed ; print_bool " b_correct " b_correct ; ( Boolean . all [ xi_correct ; b_correct ; combined_inner_product_correct ; plonk_checks_passed ] , bulletproof_challenges ) let map_challenges { Types . Step . Proof_state . Deferred_values . plonk ; combined_inner_product ; xi ; bulletproof_challenges ; b } ~ f ~ scalar = { Types . Step . Proof_state . Deferred_values . plonk = Types . Step . Proof_state . Deferred_values . Plonk . In_circuit . map_challenges plonk ~ f ~ scalar ; combined_inner_product ; bulletproof_challenges = Vector . map bulletproof_challenges ~ f ( : fun ( r : _ Bulletproof_challenge . t ) t -> { Bulletproof_challenge . prechallenge = scalar r . prechallenge } ) ; xi = scalar xi ; b } let hash_me_only ( type n ) n ( _max_proofs_verified : n Nat . t ) t ( t : ( _ , ( _ , n ) n Vector . t ) t Types . Wrap . Proof_state . Me_only . t ) t = let sponge = Sponge . create sponge_params in Array . iter ~ f ( : Sponge . absorb sponge ) sponge ( Types . Wrap . Proof_state . Me_only . to_field_elements ~ g1 : Inner_curve . to_field_elements t ) ; Sponge . squeeze_field sponge end
let merge ( { dv = dv1 } as def1 , s1 ) ( { dv = dv2 } as def2 , s2 ) = Total . union def1 def2 , S . union dv1 ( S . union dv2 ( S . union s1 s2 ) )
let union ( { dv = dv1 } as def1 , s1 ) ( { dv = dv2 } as def2 , s2 ) = Total . union def1 def2 , S . union ( S . inter dv1 dv2 ) ( S . union s1 s2 )
let filter_env shared_set b_env = let filter n ( { t_sort = sort } as entry ) ( bounded , env ) = let entry = match sort with S . add n bounded , Env . add n entry env in Env . fold filter b_env ( S . empty , Env . empty )
let rec equation ( { eq_desc = desc } as eq ) = let eq , defnames , shared_set = match desc with | EQeq ( pat , e ) -> { eq with eq_desc = EQeq ( pat , expression e ) } , { Deftypes . empty with dv = Vars . fv_pat S . empty S . empty pat } , S . empty | EQpluseq ( n , e ) -> { eq with eq_desc = EQpluseq ( n , expression e ) } , { Deftypes . empty with dv = S . singleton n } , S . empty | EQder ( n , e , None , [ ] ) -> { eq with eq_desc = EQder ( n , expression e , None , [ ] ) } , { Deftypes . empty with der = S . singleton n } , S . empty | EQinit ( n , e ) -> { eq with eq_desc = EQinit ( n , expression e ) } , { Deftypes . empty with di = S . singleton n } , S . empty | EQmatch ( total , e , m_h_list ) -> let m_h_list , ( defnames , shared_set ) = { eq with eq_desc = EQmatch ( total , expression e , m_h_list ) } , defnames , shared_set | EQreset ( eq_list , e ) -> let eq_list , ( defnames , shared_set ) = let defnames , shared_set = { eq with eq_desc = EQreset ( eq_list , expression e ) } , defnames , shared_set | EQand ( and_eq_list ) -> let and_eq_list , ( defnames , shared_set ) = { eq with eq_desc = EQand ( and_eq_list ) } , defnames , shared_set | EQbefore ( before_eq_list ) -> let before_eq_list , ( defnames , shared_set ) = { eq with eq_desc = EQbefore ( before_eq_list ) } , defnames , shared_set | EQblock ( b ) -> let b , defnames , shared_set = block b in { eq with eq_desc = EQblock ( b ) } , defnames , shared_set | EQforall ( { for_index = i_list ; for_init = init_list ; let index xi_out_x ( { desc = desc } as ind ) = let init acc ( { desc = desc } as ini ) = let i_list , xi_out_x = Zmisc . map_fold index Env . empty i_list in let init_list , i_set = Zmisc . map_fold init S . empty init_list in let b_eq_list , { dv = dv ; di = di ; der = der ; nv = nv ; mv = mv } , shared_set = block b_eq_list in let x_of_xi xi = try Env . find xi xi_out_x with Not_found -> xi in let defnames = mv = S . map x_of_xi mv } in let shared_set = S . map x_of_xi shared_set in let defnames , shared_set = { eq with eq_desc = defnames , shared_set | EQpresent _ | EQautomaton _ | EQder _ | EQnext _ | EQemit _ -> assert false in { eq with eq_write = defnames } , defnames , shared_set Zmisc . map_fold ( fun acc eq -> let eq , defnames , shared_set = equation eq in let l_list = List . map local l_list in let eq_list , ( { dv = dv ; der = der ; di = di ; nv = nv ; mv = mv } , shared_set ) = equation_list ( Deftypes . empty , S . empty ) eq_list in let bounded , b_env = filter_env shared_set b_env in let dv = S . diff dv bounded in let di = S . diff di bounded in let der = S . diff der bounded in let nv = S . diff nv bounded in let mv = S . diff mv bounded in let shared_set = S . diff shared_set bounded in let local_defnames = { dv = dv ; der = der ; di = di ; nv = nv ; mv = mv } in { b with b_write = local_defnames ; b_locals = l_list ; local_defnames , shared_set let eq_list , ( _ , shared_set ) = equation_list ( Deftypes . empty , S . empty ) eq_list in let _ , l_env = filter_env shared_set l_env in { l with l_eq = eq_list ; l_env = l_env } let desc = match desc with | Elocal _ | Eglobal _ | Econst _ | Econstr0 _ | Elast _ -> desc | Eop ( op , e_list ) -> Eop ( op , List . map expression e_list ) | Eapp ( app , op , e_list ) -> Eapp ( app , op , List . map expression e_list ) | Etuple ( e_list ) -> Etuple ( List . map expression e_list ) | Econstr1 ( c , e_list ) -> Econstr1 ( c , List . map expression e_list ) | Erecord_access ( e_record , ln ) -> Erecord_access ( expression e_record , ln ) | Erecord ( l_e_list ) -> Erecord ( List . map ( fun ( l , e ) -> ( l , expression e ) ) l_e_list ) | Erecord_with ( e_record , l_e_list ) -> Erecord_with ( expression e_record , | Etypeconstraint ( e , ty ) -> Etypeconstraint ( expression e , ty ) | Elet ( l , e ) -> Elet ( local l , expression e ) | Eblock ( b , e ) -> let b , _ , _ = block b in Eblock ( b , expression e ) | Eseq ( e1 , e2 ) -> Eseq ( expression e1 , expression e2 ) | Eperiod { p_phase = p1 ; p_period = p2 } -> Eperiod | Epresent _ | Ematch _ -> assert false in { e with e_desc = desc }
let implementation impl = match impl . desc with | Econstdecl ( n , is_static , e ) -> { impl with desc = Econstdecl ( n , is_static , expression e ) } | Efundecl ( n , ( { f_body = e } as body ) ) -> { impl with desc = Efundecl ( n , { body with f_body = expression e } ) } | _ -> impl
let implementation_list impl_list = Zmisc . iter implementation impl_list
module Core_over_monad ( Monad : Preface_specs . MONAD ) ( Tape : Preface_specs . MONOID ) = struct type tape = Tape . t type ' a monad = ' a Monad . t type ' a t = ( ' a * tape ) monad let upper m = Monad . bind ( fun a -> Monad . return ( a , Tape . neutral ) ) m let writer ( x , t ) = Monad . return ( x , t ) let run writer_m = writer_m let exec x = Monad . map snd x let tell s = writer ( ( ) , s ) let listen m = Monad . map ( fun ( x , b ) -> ( ( x , b ) , b ) ) m let listens f m = Monad . map ( fun ( x , b ) -> ( ( x , f b ) , b ) ) m let pass m = Monad . map ( fun ( ( x , f ) , b ) -> ( x , f b ) ) m let censor f m = Monad . map ( fun ( x , b ) -> ( x , f b ) ) m end
module Functor ( F : Preface_specs . FUNCTOR ) ( Tape : Preface_specs . MONOID ) = type ' a t = ( ' a * Tape . t ) F . t let map f x = F . map ( fun ( y , t ) -> ( f y , t ) ) x end )
module Applicative ( A : Preface_specs . APPLICATIVE ) ( Tape : Preface_specs . MONOID ) = type ' a t = ( ' a * Tape . t ) A . t let pure x = A . pure ( x , Tape . neutral ) let apply f v = let g ( x , t ) ( y , u ) = ( x y , Tape . combine t u ) in A . lift2 g f v ; ; end )
module Alternative ( A : Preface_specs . ALTERNATIVE ) ( Tape : Preface_specs . MONOID ) = Alternative . Over_applicative ( Applicative ( A ) ( Tape ) ) ( struct type ' a t = ( ' a * Tape . t ) A . t let neutral = A . neutral let combine writer_l writer_r = A . combine writer_l writer_r end )
module Monad ( M : Preface_specs . MONAD ) ( Tape : Preface_specs . MONOID ) = type ' a t = ( ' a * Tape . t ) M . t let return x = M . return ( x , Tape . neutral ) let bind f m = M . ( m >>= fun ( x , t ) -> f x >|= fun ( y , u ) -> ( y , Tape . combine t u ) ) ; ; end )
module Monad_plus ( M : Preface_specs . MONAD_PLUS ) ( Tape : Preface_specs . MONOID ) = Monad_plus . Over_monad ( Monad ( M ) ( Tape ) ) ( struct type ' a t = ( ' a * Tape . t ) M . t let neutral = M . neutral let combine writer_l writer_r = M . combine writer_l writer_r end )
module Over_monad ( M : Preface_specs . MONAD ) ( Tape : Preface_specs . MONOID ) = struct include Core_over_monad ( M ) ( Tape ) module Monad = Monad ( M ) ( Tape ) include Monad end
module Id = Unique_id . Int63 ( )
let io_stats = Io_stats . create ( )
module Time_ns_suppress_sexp_in_test = struct type t = Time_ns . t let sexp_of_t t = if am_running_inline_test then Sexp . List [ ] else Time_ns . sexp_of_t t end
module Flush_result = struct type t = | Error | Consumer_left | Flushed of Time_ns_suppress_sexp_in_test . t [ @@ deriving sexp_of ] end
module Line_ending = struct type t = | Dos | Unix [ @@ deriving sexp_of ] end
module Check_buffer_age ' = struct type ' a t = { writer : ' a ; maximum_age : Time_ns . Span . t ; mutable bytes_received_at_now_minus_maximum_age : Int63 . t ; bytes_received_queue : Int63 . t Queue . t ; times_received_queue : Time_ns . t Queue . t ; mutable bytes_seen : Int63 . t ; mutable too_old : unit Ivar . t ; for_this_time_source : ' a per_time_source } and ' a per_time_source = { active_checks : ( ' a t [ @ sexp . opaque ] ) Bag . t ; closed : unit Ivar . t } [ @@ deriving fields , sexp_of ] end
type open_flags = ( Open_flags . t , exn ) Result . t [ @@ deriving sexp_of ]
module Destroy_or_keep = struct type t = | Destroy | Keep [ @@ deriving sexp_of ] end
module Scheduled = struct type t = ( Bigstring . t IOVec . t * Destroy_or_keep . t ) Deque . t let length ( t : t ) = Deque . fold t ~ init : 0 ~ f ( : fun n ( iovec , _ ) -> n + iovec . len ) end
module Stop_reason = struct type t = | Error | Consumer_left [ @@ deriving sexp_of ] end
type t = { id : Id . t ; mutable fd : Fd . t ; monitor : Monitor . t ; inner_monitor : Monitor . t ; mutable background_writer_state : [ ` Running | ` Not_running | ` Stopped_permanently of Stop_reason . t ] ; background_writer_stopped : unit Ivar . t ; syscall : [ ` Per_cycle | ` Periodic of Time . Span . t ] ; mutable bytes_received : Int63 . t ; mutable bytes_written : Int63 . t ; scheduled : Scheduled . t ; mutable scheduled_bytes : int ; mutable buf : Bigstring . t ; mutable scheduled_back : int ; mutable back : int ; time_source : Time_source . t ; flushes : ( Flush_result . t Ivar . t * Int63 . t ) Queue . t ; mutable close_state : [ ` Open | ` Closed_and_flushing | ` Closed ] ; close_finished : unit Ivar . t ; close_started : unit Ivar . t ; producers_to_flush_at_close : ( unit -> unit Deferred . t ) Bag . t ; mutable flush_at_shutdown_elt : t Bag . Elt . t option ; mutable check_buffer_age : t Check_buffer_age ' . t Bag . Elt . t option ; consumer_left : unit Ivar . t ; mutable raise_when_consumer_leaves : bool ; open_flags : open_flags Deferred . t ; line_ending : Line_ending . t ; mutable backing_out_channel : Backing_out_channel . t option }
let sexp_of_t t = [ % sexp ( t . fd : Fd . t_hum ) ]
let sexp_of_t_internals { id ; fd ; monitor ; inner_monitor ; background_writer_state ; background_writer_stopped ; syscall ; bytes_received ; bytes_written ; scheduled = _ ; scheduled_bytes ; buf = _ ; scheduled_back ; back ; time_source ; flushes = _ ; close_state ; close_finished ; close_started ; producers_to_flush_at_close ; flush_at_shutdown_elt ; check_buffer_age ; consumer_left ; raise_when_consumer_leaves ; open_flags ; line_ending ; backing_out_channel } = let suppress_in_test x = if am_running_inline_test then None else Some x in let monitor_name_in_test monitor = if am_running_inline_test then [ % sexp ( Monitor . name monitor : Info . t ) ] else [ % sexp ( monitor : Monitor . t ) ] in let time_source = if phys_equal time_source ( Time_source . wall_clock ( ) ) then None else Some time_source in [ % sexp { id = ( suppress_in_test id : ( Id . t option [ @ sexp . option ] ) ) ; fd = ( suppress_in_test fd : ( Fd . t option [ @ sexp . option ] ) ) ; monitor = ( monitor_name_in_test monitor : Sexp . t ) ; inner_monitor = ( monitor_name_in_test inner_monitor : Sexp . t ) ; background_writer_state : [ ` Running | ` Not_running | ` Stopped_permanently of Stop_reason . t ] ; background_writer_stopped : unit Ivar . t ; syscall : [ ` Per_cycle | ` Periodic of Time . Span . t ] ; bytes_received : Int63 . t ; bytes_written : Int63 . t ; scheduled_bytes : int ; scheduled_back : int ; back : int ; time_source : ( Time_source . t option [ @ sexp . option ] ) ; close_state : [ ` Open | ` Closed_and_flushing | ` Closed ] ; close_finished : unit Ivar . t ; close_started : unit Ivar . t ; num_producers_to_flush_at_close = ( Bag . length producers_to_flush_at_close : int ) ; flush_at_shutdown_elt = ( suppress_in_test flush_at_shutdown_elt : ( ( t [ @ sexp . opaque ] ) Bag . Elt . t option option [ @ sexp . option ] ) ) ; check_buffer_age = ( suppress_in_test check_buffer_age : ( ( t [ @ sexp . opaque ] ) Check_buffer_age ' . t Bag . Elt . t option option [ @ sexp . option ] ) ) ; consumer_left : unit Ivar . t ; raise_when_consumer_leaves : bool ; open_flags = ( suppress_in_test open_flags : ( open_flags Deferred . t option [ @ sexp . option ] ) ) ; line_ending : Line_ending . t ; backing_out_channel : ( Backing_out_channel . t option [ @ sexp . option ] ) } ] ; ;
type writer = t [ @@ deriving sexp_of ]
let set_raise_when_consumer_leaves t bool = t . raise_when_consumer_leaves <- bool
let bytes_to_write t = t . scheduled_bytes + t . back - t . scheduled_back
let is_stopped_permanently t = match t . background_writer_state with | ` Stopped_permanently _ -> true | ` Running | ` Not_running -> false ; ;
let invariant t : unit = try let check f field = f ( Field . get field t ) in Fields . iter ~ id : ignore ~ fd : ignore ~ monitor : ignore ~ inner_monitor : ignore ~ buf : ignore ~ background_writer_state : ( check ( function | ` Stopped_permanently _ -> assert ( bytes_to_write t = 0 ) ; assert ( Ivar . is_full t . background_writer_stopped ) | ` Running | ` Not_running -> assert ( Bigstring . length t . buf > 0 ) ; assert ( Int63 . ( t . bytes_received - t . bytes_written = of_int ( bytes_to_write t ) ) ) ; assert ( Ivar . is_empty t . background_writer_stopped ) ) ) ~ background_writer_stopped : ignore ~ syscall : ignore ~ bytes_written : ( check ( fun bytes_written -> assert ( Int63 . ( zero <= bytes_written && bytes_written <= t . bytes_received ) ) ) ) ~ bytes_received : ignore ~ scheduled : ( check ( fun ( scheduled : Scheduled . t ) -> Deque . iter scheduled ~ f ( : fun ( iovec , kind ) -> if phys_equal t . buf iovec . buf then assert ( match kind with | Keep -> true | Destroy -> false ) ) ) ) ~ scheduled_bytes : ( check ( fun scheduled_bytes -> assert ( scheduled_bytes = Scheduled . length t . scheduled ) ) ) ~ scheduled_back : ( check ( fun scheduled_back -> assert ( 0 <= scheduled_back && scheduled_back <= t . back ) ) ) ~ back ( : check ( fun back -> assert ( back <= Bigstring . length t . buf ) ) ) ~ time_source : ignore ~ flushes : ignore ~ close_state : ignore ~ close_finished : ( check ( fun close_finished -> match t . close_state with | ` Open | ` Closed_and_flushing -> assert ( Ivar . is_empty close_finished ) | ` Closed -> ( ) ) ) ~ close_started : ( check ( fun close_started -> [ % test_result : bool ] ( Ivar . is_empty close_started ) ~ expect : ( match t . close_state with | ` Open -> true | ` Closed | ` Closed_and_flushing -> false ) ) ) ~ producers_to_flush_at_close : ignore ~ flush_at_shutdown_elt : ( check ( fun o -> assert ( Bool . equal ( is_none o ) ( Ivar . is_full t . close_finished ) ) ; Option . iter o ~ f ( : fun elt -> assert ( phys_equal t ( Bag . Elt . value elt ) ) ) ) ) ~ check_buffer_age : ignore ~ consumer_left : ( check ( fun consumer_left -> if Ivar . is_full consumer_left then assert ( is_stopped_permanently t ) ) ) ~ raise_when_consumer_leaves : ignore ~ open_flags : ignore ~ line_ending : ignore ~ backing_out_channel ( : check ( Option . invariant Backing_out_channel . invariant ) ) with | exn -> raise_s [ % message " writer invariant failed " ( exn : exn ) ~ writer ( : t : t_internals ) ] ; ;
module Check_buffer_age : sig type t = writer Check_buffer_age ' . t Bag . Elt . t option val dummy : t val create : writer -> maximum_age [ : ` At_most of Time . Span . t | ` Unlimited ] -> t val destroy : t -> unit val too_old : t -> unit Deferred . t module Internal_for_unit_test : sig val check_now : check_invariants : bool -> time_source : Time_source . t -> unit val num_active_checks_for : Time_source . t -> int option end open Check_buffer_age ' type t = writer Check_buffer_age ' . t Bag . Elt . t option let elt_invariant t : unit = Invariant . invariant [ % here ] t [ % sexp_of : _ t ] ( fun ( ) -> let check f field = f ( Field . get field t ) in assert ( Queue . length t . bytes_received_queue = Queue . length t . times_received_queue ) ; Fields . iter ~ writer : ignore ~ maximum_age : ignore ~ too_old : ( check ( fun ivar -> let imply a b = ( not a ) || b in assert ( imply Int63 . O . ( t . bytes_received_at_now_minus_maximum_age > t . writer . bytes_written ) ( Ivar . is_full ivar ) ) ) ) ~ bytes_received_queue : ( check ( fun q -> let n = Queue . fold q ~ init : t . bytes_received_at_now_minus_maximum_age ~ f ( : fun prev count -> assert ( Int63 . ( < ) prev count ) ; count ) in assert ( Int63 . ( <= ) n t . writer . bytes_received ) ; assert ( Int63 . ( = ) n t . bytes_seen ) ) ) ~ times_received_queue : ( check ( fun q -> match Queue . to_list q with | [ ] -> ( ) | times -> [ % test_result : Time_ns . t list ] ~ expect : times ( List . sort times ~ compare : Time_ns . compare ) ; assert ( Time_ns . Span . ( <= ) ( Time_ns . diff ( List . last_exn times ) ( List . hd_exn times ) ) t . maximum_age ) ) ) ~ bytes_received_at_now_minus_maximum_age : ignore ~ bytes_seen : ignore ~ for_this_time_source : ignore ) ; ; let dummy = None let rec sync e ~ now = if not ( Queue . is_empty e . bytes_received_queue ) then ( let bytes_received = Queue . peek_exn e . bytes_received_queue in let time_received = Queue . peek_exn e . times_received_queue in let bytes_are_written = Int63 . ( <= ) bytes_received e . writer . bytes_written in let bytes_are_too_old = Time_ns . Span . ( > ) ( Time_ns . diff now time_received ) e . maximum_age in if bytes_are_too_old then e . bytes_received_at_now_minus_maximum_age <- bytes_received ; if bytes_are_written || bytes_are_too_old then ( ignore ( Queue . dequeue_exn e . bytes_received_queue : Int63 . t ) ; ignore ( Queue . dequeue_exn e . times_received_queue : Time_ns . t ) ; sync e ~ now ) ) ; ; module Per_time_source = struct type t = writer Check_buffer_age ' . per_time_source let process_active_check e = let now = Time_source . now e . writer . time_source in sync e ~ now ; let bytes_received = e . writer . bytes_received in let bytes_written = e . writer . bytes_written in if Int63 . O . ( bytes_received > e . bytes_seen ) then ( e . bytes_seen <- bytes_received ; if Int63 . O . ( bytes_received > bytes_written ) then ( Queue . enqueue e . bytes_received_queue e . writer . bytes_received ; Queue . enqueue e . times_received_queue now ) ) ; let too_old = Int63 . O . ( e . bytes_received_at_now_minus_maximum_age > bytes_written ) in match Ivar . is_full e . too_old , too_old with | true , true | false , false -> ( ) | true , false -> e . too_old <- Ivar . create ( ) | false , true -> Ivar . fill e . too_old ( ) ; let writer = e . writer in Monitor . send_exn e . writer . monitor ( Exn . create_s [ % message " writer buffer has data older than " ~ maximum_age ( : e . maximum_age : Time_ns . Span . t ) ~ beginning_of_buffer : ( Bigstring . to_string writer . buf ~ pos : 0 ~ len ( : Int . min 1024 ( Bigstring . length writer . buf ) ) : string ) ( writer : writer ) ] ) ; ; let create ( ) = { active_checks = Bag . create ( ) ; closed = Ivar . create ( ) } let check t = Bag . iter t . active_checks ~ f : process_active_check let internal_check_now_for_unit_test t ~ check_invariants = if check_invariants then Bag . iter t . active_checks ~ f : elt_invariant ; check t ; ; end module Time_source_key = Hashable . Make_plain ( struct type t = Time_source . t [ @@ deriving sexp_of ] let hash_fold_t state t = Time_source . Id . hash_fold_t state ( Time_source . id t ) let hash t = Time_source . Id . hash ( Time_source . id t ) let compare t1 t2 = Time_source . Id . compare ( Time_source . id t1 ) ( Time_source . id t2 ) end ) let by_time_source : Per_time_source . t Time_source_key . Table . t = Time_source_key . Table . create ( ) ; ; module Internal_for_unit_test = struct let num_active_checks_for time_source = Option . map ( Hashtbl . find by_time_source time_source ) ~ f ( : fun pt -> Bag . length pt . active_checks ) ; ; let check_now ~ check_invariants ~ time_source = Per_time_source . internal_check_now_for_unit_test ( Hashtbl . find_exn by_time_source time_source ) ~ check_invariants ; ; end let create writer ~ maximum_age = match maximum_age with | ` Unlimited -> None | ` At_most maximum_age -> let time_source = writer . time_source in let for_this_time_source = Hashtbl . find_or_add by_time_source time_source ~ default ( : fun ( ) -> let pt = Per_time_source . create ( ) in Time_source . every time_source Time_ns . Span . second ~ stop ( : Ivar . read pt . closed ) ~ continue_on_error : false ( fun ( ) -> Per_time_source . check pt ) ; pt ) in Some ( Bag . add for_this_time_source . active_checks { writer ; bytes_received_queue = Queue . create ( ) ; times_received_queue = Queue . create ( ) ; maximum_age = Time_ns . Span . of_span_float_round_nearest maximum_age ; bytes_seen = Int63 . zero ; bytes_received_at_now_minus_maximum_age = Int63 . zero ; too_old = Ivar . create ( ) ; for_this_time_source } ) ; ; let destroy t = match t with | None -> ( ) | Some elt -> let t = Bag . Elt . value elt in let per_time_source = t . for_this_time_source in Bag . remove per_time_source . active_checks elt ; if Bag . is_empty per_time_source . active_checks then ( Hashtbl . remove by_time_source t . writer . time_source ; Ivar . fill_if_empty per_time_source . closed ( ) ) ; ; let too_old t = match t with | None -> Deferred . never ( ) | Some elt -> Ivar . read ( Bag . Elt . value elt ) . too_old ; ; end
let flushed_or_failed_with_result t = match t . backing_out_channel with | Some backing_out_channel -> Backing_out_channel . flush backing_out_channel ; return ( Flush_result . Flushed ( Time_source . now t . time_source ) ) | None -> if Int63 . O . ( t . bytes_written = t . bytes_received ) then return ( Flush_result . Flushed ( Time_source . now t . time_source ) ) else ( match t . background_writer_state with | ` Stopped_permanently Error -> return Flush_result . Error | ` Stopped_permanently Consumer_left -> return Flush_result . Consumer_left | ` Running | ` Not_running -> if Ivar . is_full t . close_finished then Deferred . return Flush_result . Error else Deferred . create ( fun ivar -> Queue . enqueue t . flushes ( ivar , t . bytes_received ) ) ) ; ;
let eager_map t ~ f = if Deferred . is_determined t then return ( f ( Deferred . value_exn t ) ) else Deferred . map t ~ f ; ;
let eager_bind t ~ f = if Deferred . is_determined t then f ( Deferred . value_exn t ) else Deferred . bind t ~ f ; ;
let flushed_or_failed_unit t = eager_map ( flushed_or_failed_with_result t ) ~ f : ignore
let flushed_time_ns t = eager_bind ( flushed_or_failed_with_result t ) ~ f ( : function | Flushed t -> Deferred . return t | Error | Consumer_left -> Deferred . never ( ) ) ; ;
let flushed_time t = eager_map ( flushed_time_ns t ) ~ f : Time_ns . to_time_float_round_nearest
let flushed t = eager_map ( flushed_time_ns t ) ~ f ( : ignore : Time_ns . t -> unit ) ; ;
let set_backing_out_channel t backing_out_channel = t . backing_out_channel <- Some backing_out_channel ; ;
let set_synchronous_backing_out_channel t backing_out_channel = let rec wait_until_no_bytes_to_write ( ) = if bytes_to_write t = 0 then ( set_backing_out_channel t backing_out_channel ; return ( ) ) else ( let % bind ( ) = flushed t in wait_until_no_bytes_to_write ( ) ) in wait_until_no_bytes_to_write ( ) ; ;
let set_synchronous_out_channel t out_channel = set_synchronous_backing_out_channel t ( Backing_out_channel . of_out_channel out_channel ) ; ;
let using_synchronous_backing_out_channel t = Option . is_some t . backing_out_channel
let clear_synchronous_out_channel t = if is_some t . backing_out_channel then ( assert ( bytes_to_write t = 0 ) ; t . backing_out_channel <- None ) ; ;
let with_synchronous_backing_out_channel t backing_out_channel ~ f = let saved_backing_out_channel = t . backing_out_channel in Monitor . protect ( fun ( ) -> let % bind ( ) = set_synchronous_backing_out_channel t backing_out_channel in f ( ) ) ~ finally ( : fun ( ) -> t . backing_out_channel <- saved_backing_out_channel ; return ( ) ) ; ;
let with_synchronous_out_channel t out_channel ~ f = with_synchronous_backing_out_channel t ~ f ( Backing_out_channel . of_out_channel out_channel ) ; ;
let set_fd t fd = let % map ( ) = flushed t in t . fd <- fd ; ;
let consumer_left t = Ivar . read t . consumer_left
let close_finished t = Ivar . read t . close_finished
let close_started t = Ivar . read t . close_started
let is_closed t = match t . close_state with | ` Open -> false | ` Closed | ` Closed_and_flushing -> true ; ;
let is_open t = not ( is_closed t )
let writers_to_flush_at_shutdown : t Bag . t = Bag . create ( )
let final_flush ? force t = let producers_flushed = Deferred . List . iter ~ how ` : Parallel ~ f ( : fun f -> f ( ) ) ( Bag . to_list t . producers_to_flush_at_close ) in let force = match force with | Some fc -> fc | None -> ( match Fd . kind t . fd with | File -> Deferred . never ( ) | Char | Fifo | Socket _ -> Time_source . after t . time_source ( Time_ns . Span . of_sec 5 . ) ) in Deferred . any_unit [ consumer_left t ; Deferred . all_unit [ producers_flushed ; flushed t ] ; force ; Check_buffer_age . too_old t . check_buffer_age ] ; ;
let close ? force_close t = if debug then Debug . log " Writer . close " t [ % sexp_of : t ] ; ( match t . close_state with | ` Closed_and_flushing | ` Closed -> ( ) | ` Open -> t . close_state <- ` Closed_and_flushing ; Ivar . fill t . close_started ( ) ; final_flush t ? force : force_close >>> fun ( ) -> t . close_state <- ` Closed ; Check_buffer_age . destroy t . check_buffer_age ; ( match t . flush_at_shutdown_elt with | None -> assert false | Some elt -> Bag . remove writers_to_flush_at_shutdown elt ) ; Unix . close t . fd >>> fun ( ) -> Ivar . fill t . close_finished ( ) ) ; close_finished t ; ;
let ( ) = Shutdown . at_shutdown ( fun ( ) -> if debug then Debug . log_string " Writer . at_shutdown " ; Deferred . List . iter ~ how ` : Parallel ( Bag . to_list writers_to_flush_at_shutdown ) ~ f ( : fun t -> Deferred . any_unit [ final_flush t ; close_finished t ] ) ) ; ;
let fill_flushes { bytes_written ; flushes ; time_source ; _ } = if not ( Queue . is_empty flushes ) then ( let now = Time_source . now time_source in let rec loop ( ) = match Queue . peek flushes with | None -> ( ) | Some ( ivar , z ) -> if Int63 . ( z <= bytes_written ) then ( Ivar . fill ivar ( Flush_result . Flushed now ) ; ignore ( Queue . dequeue flushes : ( Flush_result . t Ivar . t * Int63 . t ) option ) ; loop ( ) ) in loop ( ) ) ; ;
let stop_permanently t ( outcome : Stop_reason . t ) = t . background_writer_state <- ` Stopped_permanently outcome ; Deque . clear t . scheduled ; t . scheduled_bytes <- 0 ; t . buf <- Bigstring . create 0 ; t . scheduled_back <- 0 ; t . back <- 0 ; Ivar . fill_if_empty t . background_writer_stopped ( ) ; Queue . iter t . flushes ~ f ( : fun ( ivar , _ ) -> Ivar . fill ivar ( match outcome with | Error -> Flush_result . Error | Consumer_left -> Flush_result . Consumer_left ) ) ; Queue . clear t . flushes ; ;
let stopped_permanently t = Ivar . read t . background_writer_stopped
let die t sexp = stop_permanently t Error ; raise_s sexp ; ;
type buffer_age_limit = [ ` At_most of Time . Span . t | ` Unlimited ]