text
stringlengths
0
601k
let test_timed_account ( ) = let num_of_fee_payers = 5 in let trials = 1 in Test_util . with_randomness 123456789 ( fun ( ) -> let test i = let ledger , fee_payer_keypairs , keymap = mk_ledgers_and_fee_payers ~ is_timed : true ~ num_of_fee_payers ( ) in Quickcheck . test ~ trials : 1 ( Mina_generators . Parties_generators . gen_parties_from ~ protocol_state_view : U . genesis_state_view ~ fee_payer_keypair : fee_payer_keypairs ( . i / 2 ) 2 ~ keymap ~ ledger ~ vk ~ prover ( ) ) ~ f ( : fun parties -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> [ % log info ] info ~ metadata [ : ( " parties " , Parties . to_yojson parties ) parties ] " generated parties " ; U . check_parties_with_merges_exn ~ expected_failure : Transaction_status . Failure . Source_minimum_balance_violation ledger [ parties ] ~ state_body : U . genesis_state_body ) ) in for i = 0 to trials - 1 do test i done )
let ( ) = let num_of_fee_payers = 5 in let trials = 2 in generate_parties_and_apply_them_consecutively ( ) ; generate_parties_and_apply_them_freshly ( ) ; let open Mina_generators . Parties_generators in let open Transaction_status . Failure in mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure : Invalid_protocol_state_precondition ~ expected_failure_status : Protocol_state_precondition_unsatisfied ; mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure ( : Update_not_permitted ` App_state ) App_state ~ expected_failure_status : Update_not_permitted_app_state ; mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure ( : Update_not_permitted ` Verification_key ) Verification_key ~ expected_failure_status : Update_not_permitted_verification_key ; mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure ( : Update_not_permitted ` Zkapp_uri ) Zkapp_uri ~ expected_failure_status : Update_not_permitted_zkapp_uri ; mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure ( : Update_not_permitted ` Token_symbol ) Token_symbol ~ expected_failure_status : Update_not_permitted_token_symbol ; mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure ( : Update_not_permitted ` Voting_for ) Voting_for ~ expected_failure_status : Update_not_permitted_voting_for ; mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure ( : Update_not_permitted ` Balance ) Balance ~ expected_failure_status : Update_not_permitted_balance ; test_timed_account ( )
module Spec = Transaction_snark . For_tests . Spec ( module struct let memo = Signed_command_memo . create_from_string_exn " Zkapp payments tests " let constraint_constants = U . constraint_constants let merkle_root_after_parties_exn t ~ txn_state_view txn = let hash = Ledger . merkle_root_after_parties_exn ~ constraint_constants : U . constraint_constants ~ txn_state_view t txn in Frozen_ledger_hash . of_ledger_hash hash let signed_signed ( ~ wallets : U . Wallet . t array ) array i j : Parties . t = let full_amount = 8_000_000_000 in let fee = Fee . of_int ( Random . int full_amount ) full_amount in let receiver_amount = Amount . sub ( Amount . of_int full_amount ) full_amount ( Amount . of_fee fee ) fee |> Option . value_exn in let acct1 = wallets ( . i ) i in let acct2 = wallets ( . j ) j in let new_state : _ Zkapp_state . V . t = Pickles_types . Vector . init Zkapp_state . Max_state_size . n ~ f : Field . of_int in Parties . of_simple { fee_payer = { body = { public_key = acct1 . account . public_key ; update = { app_state = Pickles_types . Vector . map new_state ~ f ( : fun x -> Zkapp_basic . Set_or_keep . Set x ) ; delegate = Keep ; verification_key = Keep ; permissions = Keep ; zkapp_uri = Keep ; token_symbol = Keep ; timing = Keep ; voting_for = Keep } ; fee = Fee . of_int full_amount ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = Zkapp_precondition . Protocol_state . accept ; nonce = acct1 . account . nonce } ; authorization = Signature . dummy } ; other_parties = [ { body = { public_key = acct1 . account . public_key ; update = Party . Update . noop ; token_id = Token_id . default ; balance_change = Amount . Signed ( . of_unsigned receiver_amount |> negate ) negate ; increment_nonce = true ; events = [ ] ; sequence_events = [ ] ; call_data = Field . zero ; call_depth = 0 ; protocol_state_precondition = Zkapp_precondition . Protocol_state . accept ; use_full_commitment = false ; account_precondition = Accept ; caller = Call } ; authorization = Signature Signature . dummy } ; { body = { public_key = acct2 . account . public_key ; update = Party . Update . noop ; token_id = Token_id . default ; balance_change = Amount . Signed ( . of_unsigned receiver_amount ) receiver_amount ; increment_nonce = false ; events = [ ] ; sequence_events = [ ] ; call_data = Field . zero ; call_depth = 0 ; protocol_state_precondition = Zkapp_precondition . Protocol_state . accept ; use_full_commitment = false ; account_precondition = Accept ; caller = Call } ; authorization = None_given } ] ; memo } let % test_unit " merkle_root_after_zkapp_command_exn_immutable " = Test_util . with_randomness 123456789 ( fun ( ) -> let wallets = U . Wallet . random_wallets ( ) in Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Array . iter ( Array . sub wallets ~ pos : 1 ~ len ( : Array . length wallets - 1 ) 1 ) 1 ~ f ( : fun { account ; private_key = _ } -> Ledger . create_new_account_exn ledger ( Account . identifier account ) account account ) ; let t1 = let i , j = ( 1 , 2 ) 2 in signed_signed ~ wallets i j in let hash_pre = Ledger . merkle_root ledger in let _target = let txn_state_view = Mina_state . Protocol_state . Body . view U . genesis_state_body in merkle_root_after_parties_exn ledger ~ txn_state_view t1 in let hash_post = Ledger . merkle_root ledger in [ % test_eq : Field . t ] t hash_pre hash_post ) ) let % test_unit " zkapps - based payment " = let open Mina_transaction_logic . For_tests in Quickcheck . test ~ trials : 2 Test_spec . gen ~ f ( : fun { init_ledger ; specs } -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> let parties = party_send ~ constraint_constants ( List . hd_exn specs ) specs in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . apply_parties ledger [ parties ] ) |> fun _ -> ( ) ) let % test_unit " Consecutive zkapps - based payments " = let open Mina_transaction_logic . For_tests in Quickcheck . test ~ trials : 2 Test_spec . gen ~ f ( : fun { init_ledger ; specs } -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> let partiess = List . map ~ f ( : fun s -> let use_full_commitment = Quickcheck . random_value Bool . quickcheck_generator in party_send ~ constraint_constants ~ use_full_commitment s ) specs in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . apply_parties ledger partiess |> fun _ -> ( ) ) ) let % test_unit " multiple transfers from one account " = let open Mina_transaction_logic . For_tests in Quickcheck . test ~ trials : 1 U . gen_snapp_ledger ~ f ( : fun ( { init_ledger ; specs } , new_kp ) new_kp -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let fee = Fee . of_int 1_000_000 in let amount = Amount . of_int 1_000_000_000 in let spec = List . hd_exn specs in let receiver_count = 3 in let total_amount = Amount . scale amount receiver_count |> Option . value_exn in let new_receiver = Signature_lib . Public_key . compress new_kp . public_key in let new_receiver_amount = Option . value_exn ( Amount . sub amount ( Amount . of_fee constraint_constants . account_creation_fee ) ) in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = ( new_receiver , new_receiver_amount ) new_receiver_amount :: ( List . take specs ( receiver_count - 1 ) 1 |> List . map ~ f ( : fun s -> ( s . receiver , amount ) amount ) amount ) ; amount = total_amount ; zkapp_account_keypairs = [ ] ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let parties = Transaction_snark . For_tests . multiple_transfers test_spec in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " zkapps payments failed due to insufficient funds " = let open Mina_transaction_logic . For_tests in Quickcheck . test ~ trials : 5 U . gen_snapp_ledger ~ f ( : fun ( { init_ledger ; specs } , new_kp ) new_kp -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; let fee = Fee . of_int 1_000_000 in let spec = List . hd_exn specs in let sender_pk = ( fst spec . sender ) sender . public_key |> Signature_lib . Public_key . compress in let sender_id : Account_id . t = Account_id . create sender_pk Token_id . default in let sender_location = Ledger . location_of_account ledger sender_id |> Option . value_exn in let sender_account = Ledger . get ledger sender_location |> Option . value_exn in let sender_balance = sender_account . balance in let amount = Amount . add Balance ( . to_amount sender_balance ) sender_balance Amount ( . of_int 1_000_000 ) 1_000_000 |> Option . value_exn in let receiver_count = 3 in let total_amount = Amount . scale amount receiver_count |> Option . value_exn in let new_receiver = Signature_lib . Public_key . compress new_kp . public_key in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = ( new_receiver , amount ) amount :: ( List . take specs ( receiver_count - 1 ) 1 |> List . map ~ f ( : fun s -> ( s . receiver , amount ) amount ) amount ) ; amount = total_amount ; zkapp_account_keypairs = [ ] ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let parties = Transaction_snark . For_tests . multiple_transfers test_spec in U . check_parties_with_merges_exn ~ expected_failure : Transaction_status . Failure . Overflow ledger [ parties ] ) ) ) end )
module Closed_interval = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = { lower : ' a ; upper : ' a } [ @@ deriving annot , sexp , equal , compare , hash , yojson , hlist , fields ] fields end end ] end let gen gen_a compare_a = let open Quickcheck . Let_syntax in let % bind a1 = gen_a in let % map a2 = gen_a in if compare_a a1 a2 <= 0 then { lower = a1 ; upper = a2 } else { lower = a2 ; upper = a1 } let to_input { lower ; upper } ~ f = Random_oracle_input . Chunked . append ( f lower ) lower ( f upper ) upper let typ x = Typ . of_hlistable [ x ; x ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist let deriver ~ name inner obj = let open Fields_derivers_zkapps . Derivers in let ( . ! ) = ( . ! ) ~ t_fields_annots in Fields . make_creator obj ~ lower . :! inner ~ upper . :! inner |> finish ( name ^ " Interval ) " ~ t_toplevel_annots let % test_module " ClosedInterval " = ( module struct module IntClosedInterval = struct type t_ = int t [ @@ deriving sexp , equal , compare ] compare type t = t_ [ @@ deriving sexp , equal , compare ] compare let v = { lower = 10 ; upper = 100 } end let % test_unit " roundtrip json " = let open Fields_derivers_zkapps . Derivers in let full = o ( ) in let _a : _ Unified_input . t = deriver ~ name " : Int " int full in [ % test_eq : IntClosedInterval . t ] t ( ( ! full # of_json ) of_json ( ( ! full # to_json ) to_json IntClosedInterval . v ) v ) v IntClosedInterval . v end ) end
let assert_ b e = if b then Ok ( ) else Or_error . error_string e
module Numeric = struct module Tc = struct type ( ' var , ' a ) ' a t = { zero : ' a ; max_value : ' a ; compare : ' a -> ' a -> int ; equal : ' a -> ' a -> bool ; typ : ( ' var , ' a ) ' a Typ . t ; to_input : ' a -> F . t Random_oracle_input . Chunked . t ; to_input_checked : ' var -> Field . Var . t Random_oracle_input . Chunked . t ; lte_checked : ' var -> ' var -> Boolean . var ; eq_checked : ' var -> ' var -> Boolean . var } let run f x y = Impl . run_checked ( f x y ) y let ( !! ) f = Fn . compose Impl . run_checked f let length = Length . { zero ; max_value ; compare ; lte_checked = run Checked ( . <= ) ; eq_checked = run Checked ( . = ) ; equal ; typ ; to_input ; to_input_checked = Checked . to_input } let amount = Currency . Amount . { zero ; max_value = max_int ; compare ; lte_checked = run Checked ( . <= ) ; eq_checked = run Checked ( . = ) ; equal ; typ ; to_input ; to_input_checked = var_to_input } let balance = Currency . Balance . { zero ; max_value = max_int ; compare ; lte_checked = run Checked ( . <= ) ; eq_checked = run Checked ( . = ) ; equal ; typ ; to_input ; to_input_checked = var_to_input } let nonce = Account_nonce . { zero ; max_value ; compare ; lte_checked = run Checked ( . <= ) ; eq_checked = run Checked ( . = ) ; equal ; typ ; to_input ; to_input_checked = Checked . to_input } let global_slot = Global_slot . { zero ; max_value ; compare ; lte_checked = run Checked ( . <= ) ; eq_checked = run Checked ( . = ) ; equal ; typ ; to_input ; to_input_checked = Checked . to_input } let time = Block_time . { equal ; compare ; lte_checked = run Checked ( . <= ) ; eq_checked = run Checked ( . = ) ; zero ; max_value ; typ = Checked . typ ; to_input ; to_input_checked = Checked . to_input } end open Tc [ %% versioned module Stable = struct module V1 = struct type ' a t = ' a Closed_interval . Stable . V1 . t Or_ignore . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare end end ] end let deriver name inner obj = let closed_interval obj ' = Closed_interval . deriver ~ name inner obj ' in Or_ignore . deriver_implicit closed_interval obj module Derivers = struct open Fields_derivers_zkapps . Derivers let block_time_inner obj = let ( ^^ ) = Fn . compose in iso_string ~ name " : BlockTime " ~ js_type : UInt64 ~ of_string ( : Block_time . of_uint64 ^^ Unsigned_extended . UInt64 . of_string ) of_string ~ to_string ( : Unsigned_extended . UInt64 . to_string ^^ Block_time . to_uint64 ) to_uint64 obj let nonce obj = deriver " Nonce " uint32 obj let balance obj = deriver " Balance " balance obj let amount obj = deriver " CurrencyAmount " amount obj let length obj = deriver " Length " uint32 obj let global_slot obj = deriver " GlobalSlot " uint32 obj let token_id obj = deriver " TokenId " Token_id . deriver obj let block_time obj = deriver " BlockTime " block_time_inner obj end let % test_module " Numeric " = ( module struct module Int_numeric = struct type t_ = int t [ @@ deriving sexp , equal , compare ] compare type t = t_ [ @@ deriving sexp , equal , compare ] compare end module T = struct type t = { foo : Int_numeric . t } [ @@ deriving annot , sexp , equal , compare , fields ] fields let v : t = { foo = Or_ignore . Check { Closed_interval . lower = 10 ; upper = 100 } } let deriver obj = let open Fields_derivers_zkapps . Derivers in let ( . ! ) = ( . ! ) ~ t_fields_annots in Fields . make_creator obj ~ foo ( . :! deriver " Int " int ) int |> finish " T " ~ t_toplevel_annots end let % test_unit " roundtrip json " = let open Fields_derivers_zkapps . Derivers in let full = o ( ) in let _a : _ Unified_input . t = T . deriver full in [ % test_eq : T . t ] t ( of_json full ( to_json full T . v ) v ) v T . v end ) let gen gen_a compare_a = Or_ignore . gen ( Closed_interval . gen gen_a compare_a ) compare_a let to_input { zero ; max_value ; to_input ; _ } ( t : ' a t ) t = Closed_interval . to_input ~ f : to_input ( match t with | Check x -> x | Ignore -> { lower = zero ; upper = max_value } ) module Checked = struct type ' a t = ' a Closed_interval . t Or_ignore . Checked . t let to_input { to_input_checked ; _ } ( t : ' a t ) t = Or_ignore . Checked . to_input t ~ f ( : Closed_interval . to_input ~ f : to_input_checked ) to_input_checked open Impl let check { lte_checked = ( <= ) ; _ } ( t : ' a t ) t ( x : ' a ) ' a = Or_ignore . Checked . check t ~ f ( : fun { lower ; upper } -> Boolean . all [ lower <= x ; x <= upper ] ) let is_constant { eq_checked = ( = ) ; _ } ( t : ' a t ) t = let is_constant ( { lower ; upper } : _ Closed_interval . t ) t = lower = upper in Or_ignore . Checked . map t ~ f_implicit : is_constant ~ f_explicit ( : fun { is_some ; data } -> Boolean ( . &&& ) is_some ( is_constant data ) data ) end let typ { equal = eq ; zero ; max_value ; typ ; _ } = Or_ignore . typ_implicit ( Closed_interval . typ typ ) typ ~ equal ( : Closed_interval . equal eq ) eq ~ ignore { : Closed_interval . lower = zero ; upper = max_value } let check ~ label { compare ; _ } ( t : ' a t ) t ( x : ' a ) ' a = match t with | Ignore -> Ok ( ) | Check { lower ; upper } -> if compare lower x <= 0 && compare x upper <= 0 then Ok ( ) else Or_error . errorf " Bounds check failed : % s " label let is_constant { equal = ( = ) ; _ } ( t : ' a t ) t = match t with Ignore -> false | Check { lower ; upper } -> lower = upper end
module Eq_data = struct include Or_ignore module Tc = struct type ( ' var , ' a ) ' a t = { equal : ' a -> ' a -> bool ; equal_checked : ' var -> ' var -> Boolean . var ; default : ' a ; typ : ( ' var , ' a ) ' a Typ . t ; to_input : ' a -> F . t Random_oracle_input . Chunked . t ; to_input_checked : ' var -> Field . Var . t Random_oracle_input . Chunked . t } let run f x y = Impl . run_checked ( f x y ) y let field = let open Random_oracle_input . Chunked in Field . { typ ; equal ; equal_checked = run Checked . equal ; default = zero ; to_input = field ; to_input_checked = field } let sequence_state = let open Random_oracle_input . Chunked in lazy Field . { typ ; equal ; equal_checked = run Checked . equal ; default = Lazy . force Zkapp_account . Sequence_events . empty_hash ; to_input = field ; to_input_checked = field } let boolean = let open Random_oracle_input . Chunked in Boolean . { typ ; equal = Bool . equal ; equal_checked = run equal ; default = false ; to_input = ( fun b -> packed ( field_of_bool b , 1 ) 1 ) 1 ; to_input_checked = ( fun ( b : Boolean . var ) var -> packed ( ( b :> Field . Var . t ) t , 1 ) 1 ) 1 } let receipt_chain_hash = Receipt . Chain_hash . { field with to_input_checked = var_to_input ; typ ; equal ; equal_checked = run equal_var } let ledger_hash = Ledger_hash . { field with to_input_checked = var_to_input ; typ ; equal ; equal_checked = run equal_var } let frozen_ledger_hash = Frozen_ledger_hash . { field with to_input_checked = var_to_input ; typ ; equal ; equal_checked = run equal_var } let state_hash = State_hash . { field with to_input_checked = var_to_input ; typ ; equal ; equal_checked = run equal_var } let token_id = Token_id . { default ; to_input_checked = Checked . to_input ; to_input ; typ ; equal ; equal_checked = Checked . equal } let epoch_seed = Epoch_seed . { field with to_input_checked = var_to_input ; typ ; equal ; equal_checked = run equal_var } let public_key ( ) = Public_key . Compressed . { default = invalid_public_key ; to_input ; to_input_checked = Checked . to_input ; equal_checked = run Checked . equal ; typ ; equal } end let to_input ~ explicit { Tc . default ; to_input ; _ } ( t : _ t ) t = if explicit then Flagged_option . to_input ' ~ f : to_input ~ field_of_bool ( match t with | Ignore -> { is_some = false ; data = default } | Check data -> { is_some = true ; data } ) else to_input ( match t with Ignore -> default | Check x -> x ) x let to_input_explicit tc = to_input ~ explicit : true tc let to_input_checked { Tc . to_input_checked ; _ } ( t : _ Checked . t ) t = Checked . to_input t ~ f : to_input_checked let check_checked { Tc . equal_checked ; _ } ( t : ' a Checked . t ) t ( x : ' a ) ' a = Checked . check t ~ f ( : equal_checked x ) x let check ( ? label = ) " " { Tc . equal ; _ } ( t : ' a t ) t ( x : ' a ) ' a = match t with | Ignore -> Ok ( ) | Check y -> if equal x y then Ok ( ) else Or_error . errorf " Equality check failed : % s " label let typ_implicit { Tc . equal ; default = ignore ; typ ; _ } = typ_implicit ~ equal ~ ignore typ let typ_explicit { Tc . default = ignore ; typ ; _ } = typ_explicit ~ ignore typ end
module Hash = struct include Eq_data let to_input tc = to_input ~ explicit : true tc let typ = typ_explicit end
module Leaf_typs = struct let public_key ( ) = Public_key . Compressed ( . Or_ignore . typ_explicit ~ ignore : invalid_public_key typ ) typ open Eq_data . Tc let field = Eq_data . typ_explicit field let receipt_chain_hash = Hash . typ receipt_chain_hash let ledger_hash = Hash . typ ledger_hash let frozen_ledger_hash = Hash . typ frozen_ledger_hash let state_hash = Hash . typ state_hash open Numeric . Tc let length = Numeric . typ length let time = Numeric . typ time let amount = Numeric . typ amount let balance = Numeric . typ balance let nonce = Numeric . typ nonce let global_slot = Numeric . typ global_slot let token_id = Hash . typ token_id end
module Account = struct module Poly = struct [ %% versioned module Stable = struct module V1 = struct type ( ' balance , ' nonce , ' receipt_chain_hash , ' pk , ' field ) ' field t = { balance : ' balance ; nonce : ' nonce ; receipt_chain_hash : ' receipt_chain_hash ; public_key : ' pk ; delegate : ' pk ; state : ' field Zkapp_state . V . Stable . V1 . t } [ @@ deriving annot , hlist , sexp , equal , yojson , hash , compare ] compare end end ] end end [ %% versioned module Stable = struct module V2 = struct type t = { balance : Balance . Stable . V1 . t Numeric . Stable . V1 . t ; nonce : Account_nonce . Stable . V1 . t Numeric . Stable . V1 . t ; receipt_chain_hash : Receipt . Chain_hash . Stable . V1 . t Hash . Stable . V1 . t ; delegate : Public_key . Compressed . Stable . V1 . t Eq_data . Stable . V1 . t ; state : F . Stable . V1 . t Eq_data . Stable . V1 . t Zkapp_state . V . Stable . V1 . t ; sequence_state : F . Stable . V1 . t Eq_data . Stable . V1 . t ; proved_state : bool Eq_data . Stable . V1 . t } [ @@ deriving annot , hlist , sexp , equal , yojson , hash , compare , fields ] fields let to_latest = Fn . id end module V1 = struct type t = ( Balance . Stable . V1 . t Numeric . Stable . V1 . t , Account_nonce . Stable . V1 . t Numeric . Stable . V1 . t , Receipt . Chain_hash . Stable . V1 . t Hash . Stable . V1 . t , Public_key . Compressed . Stable . V1 . t Eq_data . Stable . V1 . t , F . Stable . V1 . t Eq_data . Stable . V1 . t ) Poly . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest ( { balance ; nonce ; receipt_chain_hash ; public_key = _ ; delegate ; state } : t ) : V2 . t = { balance ; nonce ; receipt_chain_hash ; delegate ; state ; sequence_state = Ignore ; proved_state = Ignore } end end ] end let gen : t Quickcheck . Generator . t = let open Quickcheck . Let_syntax in let % bind balance = Numeric . gen Balance . gen Balance . compare in let % bind nonce = Numeric . gen Account_nonce . gen Account_nonce . compare in let % bind receipt_chain_hash = Or_ignore . gen Receipt . Chain_hash . gen in let % bind delegate = Eq_data . gen Public_key . Compressed . gen in let % bind state = let % bind fields = let field_gen = Snark_params . Tick . Field . gen in Quickcheck . Generator . list_with_length 8 ( Or_ignore . gen field_gen ) field_gen in Quickcheck . Generator . return ( Zkapp_state . V . of_list_exn fields ) fields in let % bind sequence_state = let % bind n = Int . gen_uniform_incl Int . min_value Int . max_value in let field_gen = Quickcheck . Generator . return ( F . of_int n ) n in Or_ignore . gen field_gen in let % map proved_state = Or_ignore . gen Quickcheck . Generator . bool in { balance ; nonce ; receipt_chain_hash ; delegate ; state ; sequence_state ; proved_state } let accept : t = { balance = Ignore ; nonce = Ignore ; receipt_chain_hash = Ignore ; delegate = Ignore ; state = Vector . init Zkapp_state . Max_state_size . n ~ f ( : fun _ -> Or_ignore . Ignore ) Ignore ; sequence_state = Ignore ; proved_state = Ignore } let is_accept : t -> bool = equal accept let deriver obj = let open Fields_derivers_zkapps in let ( . ! ) = ( . ! ) ~ t_fields_annots in Fields . make_creator obj ~ balance . :! Numeric . Derivers . balance ~ nonce . :! Numeric . Derivers . nonce ~ receipt_chain_hash ( . :! Or_ignore . deriver field ) field ~ delegate ( . :! Or_ignore . deriver public_key ) public_key ~ state ( . :! Zkapp_state . deriver @@ Or_ignore . deriver field ) field ~ sequence_state ( . :! Or_ignore . deriver_implicit field ) field ~ proved_state ( . :! Or_ignore . deriver bool ) bool |> finish " AccountPrecondition " ~ t_toplevel_annots let % test_unit " json roundtrip " = let b = Balance . of_int 1000 in let predicate : t = { accept with balance = Or_ignore . Check { Closed_interval . lower = b ; upper = b } ; sequence_state = Or_ignore . Check ( Field . of_int 99 ) 99 ; proved_state = Or_ignore . Check true } in let module Fd = Fields_derivers_zkapps . Derivers in let full = deriver ( Fd . o ( ) ) in [ % test_eq : t ] t predicate ( predicate |> Fd . to_json full |> Fd . of_json full ) full let to_input ( { balance ; nonce ; receipt_chain_hash ; delegate ; state ; sequence_state ; proved_state } : t ) = let open Random_oracle_input . Chunked in List . reduce_exn ~ f : append [ Numeric ( . to_input Tc . balance balance ) balance ; Numeric ( . to_input Tc . nonce nonce ) nonce ; Hash ( . to_input Tc . receipt_chain_hash receipt_chain_hash ) receipt_chain_hash ; Eq_data ( . to_input_explicit ( Tc . public_key ( ) ) delegate ) delegate ; Vector . reduce_exn ~ f : append ( Vector . map state ~ f : Eq_data ( . to_input_explicit Tc . field ) field ) field ; Eq_data ( . to_input ~ explicit : false ( Lazy . force Tc . sequence_state ) sequence_state ) sequence_state sequence_state ; Eq_data ( . to_input_explicit Tc . boolean ) boolean proved_state ] let digest t = Random_oracle ( . hash ~ init : Hash_prefix . zkapp_precondition_account ( pack_input ( to_input t ) t ) t ) t module Checked = struct type t = { balance : Balance . var Numeric . Checked . t ; nonce : Account_nonce . Checked . t Numeric . Checked . t ; receipt_chain_hash : Receipt . Chain_hash . var Hash . Checked . t ; delegate : Public_key . Compressed . var Eq_data . Checked . t ; state : Field . Var . t Eq_data . Checked . t Zkapp_state . V . t ; sequence_state : Field . Var . t Eq_data . Checked . t ; proved_state : Boolean . var Eq_data . Checked . t } [ @@ deriving hlist ] hlist let to_input ( { balance ; nonce ; receipt_chain_hash ; delegate ; state ; sequence_state ; proved_state } : t ) = let open Random_oracle_input . Chunked in List . reduce_exn ~ f : append [ Numeric ( . Checked . to_input Tc . balance balance ) balance ; Numeric ( . Checked . to_input Tc . nonce nonce ) nonce ; Hash ( . to_input_checked Tc . receipt_chain_hash receipt_chain_hash ) receipt_chain_hash ; Eq_data ( . to_input_checked ( Tc . public_key ( ) ) delegate ) delegate ; Vector . reduce_exn ~ f : append ( Vector . map state ~ f : Eq_data ( . to_input_checked Tc . field ) field ) field ; Eq_data ( . to_input_checked ( Lazy . force Tc . sequence_state ) sequence_state ) sequence_state sequence_state ; Eq_data ( . to_input_checked Tc . boolean ) boolean proved_state ] open Impl let checks { balance ; nonce ; receipt_chain_hash ; delegate ; state ; sequence_state ; proved_state } ( a : Account . Checked . Unhashed . t ) t = [ ( Transaction_status . Failure . Account_balance_precondition_unsatisfied , Numeric ( . Checked . check Tc . balance balance a . balance ) balance ) ; ( Transaction_status . Failure . Account_nonce_precondition_unsatisfied , Numeric ( . Checked . check Tc . nonce nonce a . nonce ) nonce ) ; ( Transaction_status . Failure . Account_receipt_chain_hash_precondition_unsatisfied , Eq_data ( . check_checked Tc . receipt_chain_hash receipt_chain_hash a . receipt_chain_hash ) receipt_chain_hash ) ; ( Transaction_status . Failure . Account_delegate_precondition_unsatisfied , Eq_data ( . check_checked ( Tc . public_key ( ) ) delegate a . delegate ) delegate ) ] @ [ ( Transaction_status . Failure . Account_sequence_state_precondition_unsatisfied , Boolean . any Vector ( . to_list ( map a . zkapp . sequence_state ~ f : Eq_data ( . check_checked ( Lazy . force Tc . sequence_state ) sequence_state sequence_state ) sequence_state ) ) ) ] @ ( Vector ( . to_list ( map2 state a . zkapp . app_state ~ f : Eq_data ( . check_checked Tc . field ) field ) field ) field |> List . mapi ~ f ( : fun i check -> let failure = Transaction_status . Failure . Account_app_state_precondition_unsatisfied i in ( failure , check ) check ) ) @ [ ( Transaction_status . Failure . Account_proved_state_precondition_unsatisfied , Eq_data ( . check_checked Tc . boolean proved_state a . zkapp . proved_state ) proved_state ) ] let check ~ check t a = List . iter ~ f ( : fun ( failure , passed ) passed -> check failure passed ) passed ( checks t a ) a let digest ( t : t ) t = Random_oracle . Checked ( . hash ~ init : Hash_prefix . zkapp_precondition_account ( pack_input ( to_input t ) t ) t ) t end let typ ( ) : ( Checked . t , Stable . Latest . t ) t Typ . t = let open Leaf_typs in Typ . of_hlistable [ balance ; nonce ; receipt_chain_hash ; public_key ( ) ; Zkapp_state . typ ( Or_ignore . typ_explicit Field . typ ~ ignore : Field . zero ) zero ; Or_ignore . typ_implicit Field . typ ~ equal : Field . equal ~ ignore ( : Lazy . force Zkapp_account . Sequence_events . empty_hash ) empty_hash ; Or_ignore . typ_explicit Boolean . typ ~ ignore : false ] ~ var_to_hlist : Checked . to_hlist ~ var_of_hlist : Checked . of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist let checks { balance ; nonce ; receipt_chain_hash ; delegate ; state ; sequence_state ; proved_state } ( a : Account . t ) t = [ ( Transaction_status . Failure . Account_balance_precondition_unsatisfied , Numeric ( . check ~ label " : balance " Tc . balance balance a . balance ) balance ) ; ( Transaction_status . Failure . Account_nonce_precondition_unsatisfied , Numeric ( . check ~ label " : nonce " Tc . nonce nonce a . nonce ) nonce ) ; ( Transaction_status . Failure . Account_receipt_chain_hash_precondition_unsatisfied , Eq_data ( . check ~ label " : receipt_chain_hash " Tc . receipt_chain_hash receipt_chain_hash a . receipt_chain_hash ) receipt_chain_hash ) ; ( Transaction_status . Failure . Account_delegate_precondition_unsatisfied , let tc = Eq_data . Tc . public_key ( ) in Eq_data ( . check ~ label " : delegate " tc delegate ( Option . value ~ default : tc . default a . delegate ) delegate ) delegate ) ] @ match a . zkapp with | None -> [ ] | Some zkapp -> [ ( Transaction_status . Failure . Account_sequence_state_precondition_unsatisfied , match List . find ( Vector . to_list zkapp . sequence_state ) sequence_state ~ f ( : fun state -> Eq_data ( . check ( Lazy . force Tc . sequence_state ) sequence_state ~ label " " : sequence_state state ) state |> Or_error . is_ok ) with | None -> Error ( Error . createf " Sequence state mismatch ) " | Some _ -> Ok ( ) ) ] @ List . mapi Vector ( . to_list ( zip state zkapp . app_state ) app_state ) app_state ~ f ( : fun i ( c , v ) v -> let failure = Transaction_status . Failure . Account_app_state_precondition_unsatisfied i in ( failure , Eq_data ( . check Tc . field ~ label ( : sprintf " state [ state % d ] d " i ) i c v ) v ) ) @ [ ( Transaction_status . Failure . Account_proved_state_precondition_unsatisfied , Eq_data ( . check ~ label " : proved_state " Tc . boolean proved_state zkapp . proved_state ) proved_state ) ] let check ~ check t a = List . iter ~ f ( : fun ( failure , res ) res -> check failure ( Result . is_ok res ) res ) res ( checks t a ) a end
module Protocol_state = struct module Epoch_data = struct module Poly = Epoch_data . Poly [ %% versioned module Stable = struct module V1 = struct type t = ( ( Frozen_ledger_hash . Stable . V1 . t Hash . Stable . V1 . t , Currency . Amount . Stable . V1 . t Numeric . Stable . V1 . t ) Epoch_ledger . Poly . Stable . V1 . t , Epoch_seed . Stable . V1 . t Hash . Stable . V1 . t , State_hash . Stable . V1 . t Hash . Stable . V1 . t , State_hash . Stable . V1 . t Hash . Stable . V1 . t , Length . Stable . V1 . t Numeric . Stable . V1 . t ) Poly . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest = Fn . id end end ] end let deriver obj = let open Fields_derivers_zkapps . Derivers in let ledger obj ' = let ( . ! ) = ( . ! ) ~ t_fields_annots : Epoch_ledger . Poly . t_fields_annots in Epoch_ledger . Poly . Fields . make_creator obj ' ~ hash ( . :! Or_ignore . deriver field ) field ~ total_currency . :! Numeric . Derivers . amount |> finish " EpochLedgerPrecondition " ~ t_toplevel_annots : Epoch_ledger . Poly . t_toplevel_annots in let ( . ! ) = ( . ! ) ~ t_fields_annots : Poly . t_fields_annots in Poly . Fields . make_creator obj ~ ledger . :! ledger ~ seed ( . :! Or_ignore . deriver field ) field ~ start_checkpoint ( . :! Or_ignore . deriver field ) field ~ lock_checkpoint ( . :! Or_ignore . deriver field ) field ~ epoch_length . :! Numeric . Derivers . length |> finish " EpochDataPrecondition " ~ t_toplevel_annots : Poly . t_toplevel_annots let % test_unit " json roundtrip " = let f = Or_ignore . Check Field . one in let u = Length . zero in let a = Amount . zero in let predicate : t = { Poly . ledger = { Epoch_ledger . Poly . hash = f ; total_currency = Or_ignore . Check { Closed_interval . lower = a ; upper = a } } ; seed = f ; start_checkpoint = f ; lock_checkpoint = f ; epoch_length = Or_ignore . Check { Closed_interval . lower = u ; upper = u } } in let module Fd = Fields_derivers_zkapps . Derivers in let full = deriver ( Fd . o ( ) ) in [ % test_eq : t ] t predicate ( predicate |> Fd . to_json full |> Fd . of_json full ) full let gen : t Quickcheck . Generator . t = let open Quickcheck . Let_syntax in let % bind ledger = let % bind hash = Hash . gen Frozen_ledger_hash0 . gen in let % map total_currency = Numeric . gen Amount . gen Amount . compare in { Epoch_ledger . Poly . hash ; total_currency } in let % bind seed = Hash . gen Epoch_seed . gen in let % bind start_checkpoint = Hash . gen State_hash . gen in let % bind lock_checkpoint = Hash . gen State_hash . gen in let min_epoch_length = 8 in let max_epoch_length = Genesis_constants . slots_per_epoch in let % map epoch_length = Numeric . gen ( Length . gen_incl ( Length . of_int min_epoch_length ) min_epoch_length ( Length . of_int max_epoch_length ) max_epoch_length ) Length . compare in { Poly . ledger ; seed ; start_checkpoint ; lock_checkpoint ; epoch_length } let to_input ( { ledger = { hash ; total_currency } ; seed ; start_checkpoint ; lock_checkpoint ; epoch_length } : t ) = let open Random_oracle . Input . Chunked in List . reduce_exn ~ f : append [ Hash ( . to_input Tc . frozen_ledger_hash hash ) hash ; Numeric ( . to_input Tc . amount total_currency ) total_currency ; Hash ( . to_input Tc . epoch_seed seed ) seed ; Hash ( . to_input Tc . state_hash start_checkpoint ) start_checkpoint ; Hash ( . to_input Tc . state_hash lock_checkpoint ) lock_checkpoint ; Numeric ( . to_input Tc . length epoch_length ) epoch_length ] module Checked = struct type t = ( ( Frozen_ledger_hash . var Hash . Checked . t , Currency . Amount . var Numeric . Checked . t ) Epoch_ledger . Poly . t , Epoch_seed . var Hash . Checked . t , State_hash . var Hash . Checked . t , State_hash . var Hash . Checked . t , Length . Checked . t Numeric . Checked . t ) Poly . t let to_input ( { ledger = { hash ; total_currency } ; seed ; start_checkpoint ; lock_checkpoint ; epoch_length } : t ) = let open Random_oracle . Input . Chunked in List . reduce_exn ~ f : append [ Hash ( . to_input_checked Tc . frozen_ledger_hash hash ) hash ; Numeric ( . Checked . to_input Tc . amount total_currency ) total_currency ; Hash ( . to_input_checked Tc . epoch_seed seed ) seed ; Hash ( . to_input_checked Tc . state_hash start_checkpoint ) start_checkpoint ; Hash ( . to_input_checked Tc . state_hash lock_checkpoint ) lock_checkpoint ; Numeric ( . Checked . to_input Tc . length epoch_length ) epoch_length ] end end module Poly = struct [ %% versioned module Stable = struct module V1 = struct type ( ' snarked_ledger_hash , ' time , ' length , ' vrf_output , ' global_slot , ' amount , ' epoch_data ) t = { snarked_ledger_hash : ' snarked_ledger_hash ; timestamp : ' time ; blockchain_length : ' length ; min_window_density : ' length ; last_vrf_output : ' vrf_output [ @ skip ] skip ; total_currency : ' amount ; global_slot_since_hard_fork : ' global_slot ; global_slot_since_genesis : ' global_slot ; staking_epoch_data : ' epoch_data ; next_epoch_data : ' epoch_data } [ @@ deriving annot , hlist , sexp , equal , yojson , hash , compare , fields ] fields end end ] end end [ %% versioned module Stable = struct module V1 = struct type t = ( Frozen_ledger_hash . Stable . V1 . t Hash . Stable . V1 . t , Block_time . Stable . V1 . t Numeric . Stable . V1 . t , Length . Stable . V1 . t Numeric . Stable . V1 . t , unit , Global_slot . Stable . V1 . t Numeric . Stable . V1 . t , Currency . Amount . Stable . V1 . t Numeric . Stable . V1 . t , Epoch_data . Stable . V1 . t ) Poly . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest = Fn . id end end ] end let deriver obj = let open Fields_derivers_zkapps . Derivers in let ( . ! ) ? skip_data = ( . ! ) ? skip_data ~ t_fields_annots : Poly . t_fields_annots in let last_vrf_output = ( . ! ) ~ skip_data ( ) : skip in Poly . Fields . make_creator obj ~ snarked_ledger_hash ( . :! Or_ignore . deriver field ) field ~ timestamp . :! Numeric . Derivers . block_time ~ blockchain_length . :! Numeric . Derivers . length ~ min_window_density . :! Numeric . Derivers . length ~ last_vrf_output ~ total_currency . :! Numeric . Derivers . amount ~ global_slot_since_hard_fork . :! Numeric . Derivers . global_slot ~ global_slot_since_genesis . :! Numeric . Derivers . global_slot ~ staking_epoch_data . :! Epoch_data . deriver ~ next_epoch_data . :! Epoch_data . deriver |> finish " ProtocolStatePrecondition " ~ t_toplevel_annots : Poly . t_toplevel_annots let gen : t Quickcheck . Generator . t = let open Quickcheck . Let_syntax in let snarked_ledger_hash = Zkapp_basic . Or_ignore . Ignore in let % bind timestamp = Numeric . gen Block_time . gen Block_time . compare in let % bind blockchain_length = Numeric . gen Length . gen Length . compare in let max_min_window_density = Genesis_constants . for_unit_tests . protocol . slots_per_sub_window * Genesis_constants . Constraint_constants . compiled . sub_windows_per_window - 1 |> Length . of_int in let % bind min_window_density = Numeric . gen ( Length . gen_incl Length . zero max_min_window_density ) max_min_window_density Length . compare in let last_vrf_output = ( ) in let % bind total_currency = Numeric . gen Currency . Amount . gen Currency . Amount . compare in let % bind global_slot_since_hard_fork = Numeric . gen Global_slot . gen Global_slot . compare in let % bind global_slot_since_genesis = Numeric . gen Global_slot . gen Global_slot . compare in let % bind staking_epoch_data = Epoch_data . gen in let % map next_epoch_data = Epoch_data . gen in { Poly . snarked_ledger_hash ; timestamp ; blockchain_length ; min_window_density ; last_vrf_output ; total_currency ; global_slot_since_hard_fork ; global_slot_since_genesis ; staking_epoch_data ; next_epoch_data } let to_input ( { snarked_ledger_hash ; timestamp ; blockchain_length ; min_window_density ; last_vrf_output ; total_currency ; global_slot_since_hard_fork ; global_slot_since_genesis ; staking_epoch_data ; next_epoch_data } : t ) = let open Random_oracle . Input . Chunked in let ( ) = last_vrf_output in let length = Numeric ( . to_input Tc . length ) length in List . reduce_exn ~ f : append [ Hash ( . to_input Tc . field snarked_ledger_hash ) snarked_ledger_hash ; Numeric ( . to_input Tc . time timestamp ) timestamp ; length blockchain_length ; length min_window_density ; Numeric ( . to_input Tc . amount total_currency ) total_currency ; Numeric ( . to_input Tc . global_slot global_slot_since_hard_fork ) global_slot_since_hard_fork ; Numeric ( . to_input Tc . global_slot global_slot_since_genesis ) global_slot_since_genesis ; Epoch_data . to_input staking_epoch_data ; Epoch_data . to_input next_epoch_data ] let digest t = Random_oracle ( . hash ~ init : Hash_prefix . zkapp_precondition_protocol_state ( pack_input ( to_input t ) t ) t ) t module View = struct [ %% versioned module Stable = struct module V1 = struct type t = ( Frozen_ledger_hash . Stable . V1 . t , Block_time . Stable . V1 . t , Length . Stable . V1 . t , unit , Global_slot . Stable . V1 . t , Currency . Amount . Stable . V1 . t , ( ( Frozen_ledger_hash . Stable . V1 . t , Currency . Amount . Stable . V1 . t ) Epoch_ledger . Poly . Stable . V1 . t , Epoch_seed . Stable . V1 . t , State_hash . Stable . V1 . t , State_hash . Stable . V1 . t , Length . Stable . V1 . t ) Epoch_data . Poly . Stable . V1 . t ) Poly . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest = Fn . id end end ] end module Checked = struct type t = ( Frozen_ledger_hash . var , Block_time . Checked . t , Length . Checked . t , unit , Global_slot . Checked . t , Currency . Amount . var , ( ( Frozen_ledger_hash . var , Currency . Amount . var ) var Epoch_ledger . Poly . t , Epoch_seed . var , State_hash . var , State_hash . var , Length . Checked . t ) Epoch_data . Poly . t ) Poly . t end end module Checked = struct type t = ( Frozen_ledger_hash . var Hash . Checked . t , Block_time . Checked . t Numeric . Checked . t , Length . Checked . t Numeric . Checked . t , unit , Global_slot . Checked . t Numeric . Checked . t , Currency . Amount . var Numeric . Checked . t , Epoch_data . Checked . t ) Poly . Stable . Latest . t let to_input ( { snarked_ledger_hash ; timestamp ; blockchain_length ; min_window_density ; last_vrf_output ; total_currency ; global_slot_since_hard_fork ; global_slot_since_genesis ; staking_epoch_data ; next_epoch_data } : t ) = let open Random_oracle . Input . Chunked in let ( ) = last_vrf_output in let length = Numeric ( . Checked . to_input Tc . length ) length in List . reduce_exn ~ f : append [ Hash ( . to_input_checked Tc . frozen_ledger_hash snarked_ledger_hash ) snarked_ledger_hash ; Numeric ( . Checked . to_input Tc . time timestamp ) timestamp ; length blockchain_length ; length min_window_density ; Numeric ( . Checked . to_input Tc . amount total_currency ) total_currency ; Numeric ( . Checked . to_input Tc . global_slot global_slot_since_hard_fork ) global_slot_since_hard_fork ; Numeric ( . Checked . to_input Tc . global_slot global_slot_since_genesis ) global_slot_since_genesis ; Epoch_data . Checked . to_input staking_epoch_data ; Epoch_data . Checked . to_input next_epoch_data ] let digest t = Random_oracle . Checked ( . hash ~ init : Hash_prefix . zkapp_precondition_protocol_state ( pack_input ( to_input t ) t ) t ) t let check ( { snarked_ledger_hash ; timestamp ; blockchain_length ; min_window_density ; last_vrf_output ; total_currency ; global_slot_since_hard_fork ; global_slot_since_genesis ; staking_epoch_data ; next_epoch_data } : t ) ( s : View . Checked . t ) t = let open Impl in let epoch_ledger ( { hash ; total_currency } : _ Epoch_ledger . Poly . t ) t ( t : Epoch_ledger . var ) var = [ Hash ( . check_checked Tc . frozen_ledger_hash ) frozen_ledger_hash hash t . hash ; Numeric ( . Checked . check Tc . amount ) amount total_currency t . total_currency ] in let epoch_data ( { ledger ; seed ; start_checkpoint ; lock_checkpoint ; epoch_length } : _ Epoch_data . Poly . t ) ( t : _ Epoch_data . Poly . t ) t = ignore seed ; epoch_ledger ledger t . ledger @ [ Hash ( . check_checked Tc . state_hash ) state_hash start_checkpoint t . start_checkpoint ; Hash ( . check_checked Tc . state_hash ) state_hash lock_checkpoint t . lock_checkpoint ; Numeric ( . Checked . check Tc . length ) length epoch_length t . epoch_length ] in ignore last_vrf_output ; Boolean . all ( [ Hash ( . check_checked Tc . ledger_hash ) ledger_hash snarked_ledger_hash s . snarked_ledger_hash ; Numeric ( . Checked . check Tc . time ) time timestamp s . timestamp ; Numeric ( . Checked . check Tc . length ) length blockchain_length s . blockchain_length ; Numeric ( . Checked . check Tc . length ) length min_window_density s . min_window_density ; Numeric ( . Checked . check Tc . amount ) amount total_currency s . total_currency ; Numeric ( . Checked . check Tc . global_slot ) global_slot global_slot_since_hard_fork s . global_slot_since_hard_fork ; Numeric ( . Checked . check Tc . global_slot ) global_slot global_slot_since_genesis s . global_slot_since_genesis ] @ epoch_data staking_epoch_data s . staking_epoch_data @ epoch_data next_epoch_data s . next_epoch_data ) end let typ : ( Checked . t , Stable . Latest . t ) t Typ . t = let open Poly . Stable . Latest in let frozen_ledger_hash = Hash ( . typ Tc . frozen_ledger_hash ) frozen_ledger_hash in let state_hash = Hash ( . typ Tc . state_hash ) state_hash in let epoch_seed = Hash ( . typ Tc . epoch_seed ) epoch_seed in let length = Numeric ( . typ Tc . length ) length in let time = Numeric ( . typ Tc . time ) time in let amount = Numeric ( . typ Tc . amount ) amount in let global_slot = Numeric ( . typ Tc . global_slot ) global_slot in let epoch_data = let epoch_ledger = let open Epoch_ledger . Poly in Typ . of_hlistable [ frozen_ledger_hash ; amount ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist in let open Epoch_data . Poly in Typ . of_hlistable [ epoch_ledger ; epoch_seed ; state_hash ; state_hash ; length ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist in Typ . of_hlistable [ frozen_ledger_hash ; time ; length ; length ; Typ . unit ; amount ; global_slot ; global_slot ; epoch_data ; epoch_data ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist let epoch_data : Epoch_data . t = { ledger = { hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } let accept : t = { snarked_ledger_hash = Ignore ; timestamp = Ignore ; blockchain_length = Ignore ; min_window_density = Ignore ; last_vrf_output = ( ) ; total_currency = Ignore ; global_slot_since_hard_fork = Ignore ; global_slot_since_genesis = Ignore ; staking_epoch_data = epoch_data ; next_epoch_data = epoch_data } let valid_until time : t = { snarked_ledger_hash = Ignore ; timestamp = Check time ; blockchain_length = Ignore ; min_window_density = Ignore ; last_vrf_output = ( ) ; total_currency = Ignore ; global_slot_since_hard_fork = Ignore ; global_slot_since_genesis = Ignore ; staking_epoch_data = epoch_data ; next_epoch_data = epoch_data } let % test_unit " json roundtrip " = let predicate : t = accept in let module Fd = Fields_derivers_zkapps . Derivers in let full = deriver ( Fd . o ( ) ) in [ % test_eq : t ] t predicate ( predicate |> Fd . to_json full |> Fd . of_json full ) full let check ( { snarked_ledger_hash ; timestamp ; blockchain_length ; min_window_density ; last_vrf_output ; total_currency ; global_slot_since_hard_fork ; global_slot_since_genesis ; staking_epoch_data ; next_epoch_data } : t ) ( s : View . t ) t = let open Or_error . Let_syntax in let epoch_ledger ( { hash ; total_currency } : _ Epoch_ledger . Poly . t ) t ( t : Epoch_ledger . Value . t ) t = let % bind ( ) = Hash ( . check ~ label " : epoch_ledger_hash " Tc . frozen_ledger_hash ) frozen_ledger_hash hash t . hash in let % map ( ) = Numeric ( . check ~ label " : epoch_ledger_total_currency " Tc . amount ) amount total_currency t . total_currency in ( ) in let epoch_data label ( { ledger ; seed ; start_checkpoint ; lock_checkpoint ; epoch_length } : _ Epoch_data . Poly . t ) ( t : _ Epoch_data . Poly . t ) t = let l s = sprintf " % s_ % s " label s in let % bind ( ) = epoch_ledger ledger t . ledger in ignore seed ; let % bind ( ) = Hash ( . check ~ label ( : l " start_check_point ) " Tc . state_hash ) state_hash start_checkpoint t . start_checkpoint in let % bind ( ) = Hash ( . check ~ label ( : l " lock_check_point ) " Tc . state_hash ) state_hash lock_checkpoint t . lock_checkpoint in let % map ( ) = Numeric ( . check ~ label " : epoch_length " Tc . length ) length epoch_length t . epoch_length in ( ) in let % bind ( ) = Hash ( . check ~ label " : snarked_ledger_hash " Tc . ledger_hash ) ledger_hash snarked_ledger_hash s . snarked_ledger_hash in let % bind ( ) = Numeric ( . check ~ label " : timestamp " Tc . time ) time timestamp s . timestamp in let % bind ( ) = Numeric ( . check ~ label " : blockchain_length " Tc . length ) length blockchain_length s . blockchain_length in let % bind ( ) = Numeric ( . check ~ label " : min_window_density " Tc . length ) length min_window_density s . min_window_density in ignore last_vrf_output ; let % bind ( ) = Numeric ( . check ~ label " : total_currency " Tc . amount ) amount total_currency s . total_currency in let % bind ( ) = Numeric ( . check ~ label " : curr_global_slot " Tc . global_slot ) global_slot global_slot_since_hard_fork s . global_slot_since_hard_fork in let % bind ( ) = Numeric ( . check ~ label " : global_slot_since_genesis " Tc . global_slot ) global_slot global_slot_since_genesis s . global_slot_since_genesis in let % bind ( ) = epoch_data " staking_epoch_data " staking_epoch_data s . staking_epoch_data in let % map ( ) = epoch_data " next_epoch_data " next_epoch_data s . next_epoch_data in ( ) end
module Account_type = struct [ %% versioned module Stable = struct module V1 = struct type t = User | Zkapp | None | Any [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest = Fn . id end end ] end let check ( t : t ) t ( a : A . t option ) option = match ( a , t ) t with | _ , Any -> Ok ( ) | None , None -> Ok ( ) | None , _ -> Or_error . error_string " expected account_type = None " | Some a , User -> assert_ ( Option . is_none a . zkapp ) zkapp " expected account_type = User " | Some a , Zkapp -> assert_ ( Option . is_some a . zkapp ) zkapp " expected account_type = Zkapp " | Some _ , None -> Or_error . error_string " no second account allowed " let to_bits = function | User -> [ true ; false ] | Zkapp -> [ false ; true ] | None -> [ false ; false ] | Any -> [ true ; true ] let of_bits = function | [ user ; zkapp ] -> ( match ( user , zkapp ) zkapp with | true , false -> User | false , true -> Zkapp | false , false -> None | true , true -> Any ) | _ -> assert false let to_input x = let open Random_oracle_input . Chunked in Array . reduce_exn ~ f : append ( Array . of_list_map ( to_bits x ) x ~ f ( : fun b -> packed ( field_of_bool b , 1 ) 1 ) 1 ) 1 module Checked = struct type t = { user : Boolean . var ; zkapp : Boolean . var } [ @@ deriving hlist ] hlist let to_input { user ; zkapp } = let open Random_oracle_input . Chunked in Array . reduce_exn ~ f : append ( Array . map [ | user ; zkapp ] | ~ f ( : fun b -> packed ( ( b :> Field . Var . t ) t , 1 ) 1 ) ) let constant = let open Boolean in function | User -> { user = true_ ; zkapp = false_ } | Zkapp -> { user = false_ ; zkapp = true_ } | None -> { user = false_ ; zkapp = false_ } | Any -> { user = true_ ; zkapp = true_ } let snapp_allowed t = t . zkapp let user_allowed t = t . user end let typ = let open Checked in Typ . of_hlistable [ Boolean . typ ; Boolean . typ ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist ( : function | User -> [ true ; false ] | Zkapp -> [ false ; true ] | None -> [ false ; false ] | Any -> [ true ; true ] ) ~ value_of_hlist ( : fun [ user ; zkapp ] -> match ( user , zkapp ) zkapp with | true , false -> User | false , true -> Zkapp | false , false -> None | true , true -> Any ) end
module Other = struct module Poly = struct [ %% versioned module Stable = struct module V1 = struct type ( ' account , ' account_transition , ' vk ) ' vk t = { predicate : ' account ; account_transition : ' account_transition ; account_vk : ' vk } [ @@ deriving hlist , sexp , equal , yojson , hash , compare ] compare end end ] end end [ %% versioned module Stable = struct module V2 = struct type t = ( Account . Stable . V2 . t , Account_state . Stable . V1 . t Transition . Stable . V1 . t , F . Stable . V1 . t Hash . Stable . V1 . t ) Poly . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest = Fn . id end module V1 = struct type t = ( Account . Stable . V1 . t , Account_state . Stable . V1 . t Transition . Stable . V1 . t , F . Stable . V1 . t Hash . Stable . V1 . t ) Poly . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest ( { predicate ; account_transition ; account_vk } : t ) t : V2 . t = { predicate = Account . Stable . V1 . to_latest predicate ; account_transition ; account_vk } end end ] end module Checked = struct type t = ( Account . Checked . t , Account_state . Checked . t Transition . t , Field . Var . t Or_ignore . Checked . t ) Poly . Stable . Latest . t let to_input ( { predicate ; account_transition ; account_vk } : t ) t = let open Random_oracle_input . Chunked in List . reduce_exn ~ f : append [ Account . Checked . to_input predicate ; Transition . to_input ~ f : Account_state . Checked . to_input account_transition ; Hash ( . to_input_checked Tc . field ) field account_vk ] end let to_input ( { predicate ; account_transition ; account_vk } : t ) t = let open Random_oracle_input . Chunked in List . reduce_exn ~ f : append [ Account . to_input predicate ; Transition . to_input ~ f : Account_state . to_input account_transition ; Hash ( . to_input Tc . field ) field account_vk ] let typ ( ) = let open Poly in Typ . of_hlistable [ Account . typ ( ) ; Transition . typ Account_state . typ ; Hash ( . typ Tc . field ) field ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist let accept : t = { predicate = Account . accept ; account_transition = { prev = Any ; next = Any } ; account_vk = Ignore } end
module Poly = struct [ %% versioned module Stable = struct module V1 = struct type ( ' account , ' protocol_state , ' other , ' pk ) ' pk t = { self_predicate : ' account ; other : ' other ; fee_payer : ' pk ; protocol_state_predicate : ' protocol_state } [ @@ deriving hlist , sexp , equal , yojson , hash , compare ] compare let to_latest = Fn . id end end ] end let typ spec = let open Stable . Latest in Typ . of_hlistable spec ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist end [ %% versioned
module Stable = struct module V2 = struct type t = ( Account . Stable . V2 . t , Protocol_state . Stable . V1 . t , Other . Stable . V2 . t , Public_key . Compressed . Stable . V1 . t Eq_data . Stable . V1 . t ) Poly . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest = Fn . id end module V1 = struct type t = ( Account . Stable . V1 . t , Protocol_state . Stable . V1 . t , Other . Stable . V1 . t , Public_key . Compressed . Stable . V1 . t Eq_data . Stable . V1 . t ) Poly . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest ( { self_predicate ; other ; fee_payer ; protocol_state_predicate } : t ) t : V2 . t = { self_predicate = Account . Stable . V1 . to_latest self_predicate ; other = Other . Stable . V1 . to_latest other ; fee_payer ; protocol_state_predicate } end end ] end
let to_input ( { self_predicate ; other ; fee_payer ; protocol_state_predicate } : t ) t = let open Random_oracle_input . Chunked in List . reduce_exn ~ f : append [ Account . to_input self_predicate ; Other . to_input other ; Eq_data ( . to_input_explicit ( Tc . public_key ( ) ) ) fee_payer ; Protocol_state . to_input protocol_state_predicate ]
let digest t = Random_oracle ( . hash ~ init : Hash_prefix . zkapp_precondition ( pack_input ( to_input t ) t ) t ) t
let accept : t = { self_predicate = Account . accept ; other = Other . accept ; fee_payer = Ignore ; protocol_state_predicate = Protocol_state . accept }
module Checked = struct type t = ( Account . Checked . t , Protocol_state . Checked . t , Other . Checked . t , Public_key . Compressed . var Or_ignore . Checked . t ) Poly . Stable . Latest . t let to_input ( { self_predicate ; other ; fee_payer ; protocol_state_predicate } : t ) t = let open Random_oracle_input . Chunked in List . reduce_exn ~ f : append [ Account . Checked . to_input self_predicate ; Other . Checked . to_input other ; Eq_data ( . to_input_checked ( Tc . public_key ( ) ) ) fee_payer ; Protocol_state . Checked . to_input protocol_state_predicate ] let digest t = Random_oracle . Checked ( . hash ~ init : Hash_prefix . zkapp_precondition ( pack_input ( to_input t ) t ) t ) t end
let typ ( ) : ( Checked . t , Stable . Latest . t ) t Typ . t = Poly . typ [ Account . typ ( ) ; Other . typ ( ) ; Eq_data ( . typ_explicit ( Tc . public_key ( ) ) ) ; Protocol_state . typ ]
module V = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V1 = struct type ' a t = ' a Vector . Vector_8 . Stable . V1 . t [ @@ deriving compare , yojson , sexp , hash , equal ] equal end end ] end type ' a t = ' a Vector . Vector_8 . t [ @@ deriving compare , yojson , sexp , hash , equal ] equal let map = Vector . map let of_list_exn = Vector . Vector_8 . of_list_exn let to_list = Vector . to_list end
let ( ) = let _f : type a . unit -> ( a V . t , a Vector . With_length ( With_lengthMax_state_size ) With_lengthMax_state_size . t ) t Type_equal . t = fun ( ) -> Type_equal . T in ( )
let typ t = Vector . typ t Max_state_size . n
module Value = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V1 = struct type t = Zkapp_basic . F . Stable . V1 . t V . Stable . V1 . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let to_latest = Fn . id end end ] end type t = Zkapp_basic . F . t V . t [ @@ deriving sexp , equal , yojson , hash , compare ] compare let ( ) = let _f : unit -> ( t , Stable . Latest . t ) t Type_equal . t = fun ( ) -> Type_equal . T in ( ) end
let to_input ( t : _ V . t ) t ~ f = Vector ( . reduce_exn ( map t ~ f ) f ~ f : Random_oracle_input . Chunked . append ) append
let deriver inner obj = let open Fields_derivers_zkapps . Derivers in iso ~ map : V . of_list_exn ~ contramap : V . to_list ( ( list @@ inner @@ o ( ) ) ( o ( ) ) ) obj
module Poly = struct [ %% versioned module Stable = struct module V1 = struct type ' comm t = { transaction : ' comm ; at_party : ' comm } [ @@ deriving hlist , sexp , yojson ] yojson end end ] end let to_field_elements ( t : ' c t ) t : ' c array = let [ x0 ; x1 ] = to_hlist t in [ | x0 ; x1 ] | end [ %% versioned
module Stable = struct module V2 = struct type t = Parties . Transaction_commitment . Stable . V1 . t Poly . Stable . V1 . t [ @@ deriving sexp , yojson ] yojson let to_latest = Fn . id end end ] end
let to_field_elements : t -> _ = Poly . to_field_elements
module Checked = struct type t = Parties . Transaction_commitment . Checked . t Poly . t let to_field_elements : t -> _ = Poly . to_field_elements open Pickles . Impls . Step module Assert = struct let equal ( t1 : t ) t ( t2 : t ) t = Array . iter2_exn ~ f : Field . Assert . equal ( to_field_elements t1 ) t1 ( to_field_elements t2 ) t2 end end
let typ = let open Poly in Typ . of_hlistable Parties . Transaction_commitment [ . typ ; typ ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif
module Flags = struct open Command let default_fee = Currency . Fee . of_formatted_string " 1 " let min_fee = Currency . Fee . of_formatted_string " 0 . 003 " let memo = Param . flag " -- memo " ~ doc " : STRING Memo accompanying the transaction " Param ( . optional string ) string let fee = Param . flag " -- fee " ~ doc : ( Printf . sprintf " FEE Amount you are willing to pay to process the transaction \ ( default : % s ) s ( minimum : % s ) s " ( Currency . Fee . to_formatted_string default_fee ) default_fee ( Currency . Fee . to_formatted_string min_fee ) min_fee ) ( Param . optional txn_fee ) txn_fee let amount = Param . flag " -- receiver - amount " ~ doc " : NN Receiver amount in Mina " ( Param . required txn_amount ) txn_amount let nonce = Param . flag " -- nonce " ~ doc " : NN Nonce of the fee payer account " Param ( . required txn_nonce ) txn_nonce let common_flags = Command ( . let open Let_syntax in let % map keyfile = Param . flag " -- fee - payer - key " ~ doc : " KEYFILE Private key file for the fee payer of the transaction \ ( should already be in the ledger ) ledger " Param ( . required string ) string and fee = fee and nonce = nonce and memo = memo and debug = Param . flag " -- debug " Param . no_arg ~ doc " : Debug mode , generates transaction snark " in ( keyfile , fee , nonce , memo , debug ) debug ) debug end
let create_zkapp_account = let create_command ~ debug ~ keyfile ~ fee ~ zkapp_keyfile ~ amount ~ nonce ~ memo ( ) = let open Deferred . Let_syntax in let % map parties = create_zkapp_account ~ debug ~ keyfile ~ fee ~ zkapp_keyfile ~ amount ~ nonce ~ memo in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary " : Generate a zkApp transaction that creates a zkApp account " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file for the zkApp account to be created " Param ( . required string ) string and amount = Flags . amount in let fee = Option . value ~ default : Flags . default_fee fee in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ zkapp_keyfile ~ amount ~ nonce ~ memo ) )
let upgrade_zkapp = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ verification_key ~ zkapp_uri ~ auth ( ) = let open Deferred . Let_syntax in let % map parties = upgrade_zkapp ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ verification_key ~ zkapp_uri ~ auth in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary " : Generate a zkApp transaction that updates the verification key " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file for the zkApp account to be upgraded " Param ( . required string ) string and verification_key = Param . flag " -- verification - key " ~ doc " : VERIFICATION_KEY the verification key for the zkApp account " Param ( . required string ) string and zkapp_uri_str = Param . flag " -- zkapp - uri " ~ doc " : URI the URI for the zkApp account " Param ( . optional string ) string and auth = Param . flag " -- auth " ~ doc : " Proof | Signature | Either | None Current authorization in the account \ to change the verification key " Param ( . required string ) string in let fee = Option . value ~ default : Flags . default_fee fee in let auth = Util . auth_of_string auth in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; let zkapp_uri = Zkapp_basic . Set_or_keep . of_option zkapp_uri_str in create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ verification_key ~ zkapp_uri ~ auth ) )
let transfer_funds = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ receivers ( ) = let open Deferred . Let_syntax in let % map parties = transfer_funds ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ receivers in Util . print_snapp_transaction parties ; ( ) in let read_key_and_amount count = let read ( ) = let open Deferred . Let_syntax in printf " Receiver Key " :%! ; match % bind Reader . read_line ( Lazy . force Reader . stdin ) stdin with | ` Ok key -> ( let pk = Signature_lib . Public_key . Compressed . of_base58_check_exn key in printf " ! Amount " :%! ; match % map Reader . read_line ( Lazy . force Reader . stdin ) stdin with | ` Ok amt -> let amount = Currency . Amount . of_formatted_string amt in ( pk , amount ) amount | ` Eof -> failwith " Invalid amount " ) | ` Eof -> failwith " Invalid key " in let rec go ( ? prompt = true ) true count keys = if count <= 0 then return keys else if prompt then ( printf " Continue ? [ N / y ] y \ n " %! ; match % bind Reader . read_line ( Lazy . force Reader . stdin ) stdin with | ` Ok r -> if String . Caseless . equal r " y " then let % bind key = read ( ) in go ( count - 1 ) 1 ( key :: keys ) keys else return keys | ` Eof -> return keys ) else let % bind key = read ( ) in go ( count - 1 ) 1 ( key :: keys ) keys in printf " Enter at most % d receivers ( Base58Check encoding ) encoding and amounts \ n " %! count ; let % bind ks = go ~ prompt : false 1 [ ] in go ( count - 1 ) 1 ks in Command ( . let open Let_syntax in Command . async ~ summary : " Generate a zkApp transaction that makes multiple transfers from one \ account " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags in let fee = Option . value ~ default : Flags . default_fee fee in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwithf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ( ) ; let max_keys = 10 in let receivers = read_key_and_amount max_keys in create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ receivers ) )
let update_state = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ app_state ( ) = let open Deferred . Let_syntax in let % map parties = update_state ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ app_state in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary " : Generate a zkApp transaction that updates zkApp state " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file of the zkApp account to be updated " Param ( . required string ) string and app_state = Param . flag " -- zkapp - state " ~ doc : " String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of 8 elements that \ represent the zkApp state ( Use empty string for no - op ) op " Param ( . listed string ) string in let fee = Option . value ~ default : Flags . default_fee fee in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ app_state ) )
let update_zkapp_uri = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ zkapp_uri ~ auth ( ) = let open Deferred . Let_syntax in let % map parties = update_zkapp_uri ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ zkapp_uri ~ auth in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary " : Generate a zkApp transaction that updates the zkApp URI " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and snapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file of the zkApp account to be updated " Param ( . required string ) string and zkapp_uri = Param . flag " -- zkapp - uri " ~ doc " : SNAPP_URI The string to be used as the updated zkApp URI " Param ( . required string ) string and auth = Param . flag " -- auth " ~ doc : " Proof | Signature | Either | None Current authorization in the account \ to change the zkApp URI " Param ( . required string ) string in let fee = Option . value ~ default : Flags . default_fee fee in let auth = Util . auth_of_string auth in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ zkapp_uri ~ auth ) )
let update_sequence_state = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ sequence_state ( ) = let open Deferred . Let_syntax in let % map parties = update_sequence_state ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ sequence_state in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary " : Generate a zkApp transaction that updates zkApp state " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file of the zkApp account to be updated " Param ( . required string ) string and sequence_state0 = Param . flag " -- sequence - state0 " ~ doc " : String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of elements " Param ( . required ( Arg_type . comma_separated ~ allow_empty : false ~ strip_whitespace : true string ) ) and sequence_state1 = Param . flag " -- sequence - state1 " ~ doc " : String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of elements " Param ( . optional_with_default [ ] ( Arg_type . comma_separated ~ allow_empty : false ~ strip_whitespace : true string ) ) and sequence_state2 = Param . flag " -- sequence - state2 " ~ doc " : String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of elements " Param ( . optional_with_default [ ] ( Arg_type . comma_separated ~ allow_empty : false ~ strip_whitespace : true string ) ) and sequence_state3 = Param . flag " -- sequence - state3 " ~ doc " : String ( Stringhash ) Stringhash | Integer ( Integerfield element ) element a list of elements " Param ( . optional_with_default [ ] ( Arg_type . comma_separated ~ allow_empty : false ~ strip_whitespace : true string ) ) in let fee = Option . value ~ default : Flags . default_fee fee in let sequence_state = List . filter_map ~ f ( : fun s -> if List . is_empty s then None else Some ( Array . of_list s ) s ) s [ sequence_state0 ; sequence_state1 ; sequence_state2 ; sequence_state3 ] in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ sequence_state ) )
let update_token_symbol = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ token_symbol ~ auth ( ) = let open Deferred . Let_syntax in let % map parties = update_token_symbol ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ token_symbol ~ auth in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary " : Generate a zkApp transaction that updates token symbol " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and snapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file of the zkApp account to be updated " Param ( . required string ) string and token_symbol = Param . flag " -- token - symbol " ~ doc " : TOKEN_SYMBOL The string to be used as the updated token symbol " Param ( . required string ) string and auth = Param . flag " -- auth " ~ doc : " Proof | Signature | Either | None Current authorization in the account \ to change the token symbol " Param ( . required string ) string in let fee = Option . value ~ default : Flags . default_fee fee in let auth = Util . auth_of_string auth in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ snapp_keyfile ~ token_symbol ~ auth ) )
let update_permissions = let create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ permissions ~ current_auth ( ) = let open Deferred . Let_syntax in let % map parties = update_permissions ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ permissions ~ current_auth in Util . print_snapp_transaction parties ; ( ) in Command ( . let open Let_syntax in Command . async ~ summary : " Generate a zkApp transaction that updates the permissions of a zkApp \ account " ( let % map keyfile , fee , nonce , memo , debug = Flags . common_flags and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file of the zkApp account to be updated " Param ( . required string ) string and edit_state = Param . flag " -- edit - state " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and send = Param . flag " -- send " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and receive = Param . flag " -- receive " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_permissions = Param . flag " -- set - permissions " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_delegate = Param . flag " -- set - delegate " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_verification_key = Param . flag " -- set - verification - key " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_zkapp_uri = Param . flag " -- set - zkapp - uri " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and edit_sequence_state = Param . flag " -- set - sequence - state " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_token_symbol = Param . flag " -- set - token - symbol " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and increment_nonce = Param . flag " -- increment - nonce " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and set_voting_for = Param . flag " -- set - voting - for " ~ doc " : Proof | Signature | Either | None " Param ( . required string ) string and current_auth = Param . flag " -- current - auth " ~ doc : " Proof | Signature | Either | None Current authorization in the account \ to change permissions " Param ( . required string ) string in let fee = Option . value ~ default : Flags . default_fee fee in let permissions : Permissions . t Zkapp_basic . Set_or_keep . t = Zkapp_basic . Set_or_keep . Set { Permissions . Poly . edit_state = Util . auth_of_string edit_state ; send = Util . auth_of_string send ; receive = Util . auth_of_string receive ; set_permissions = Util . auth_of_string set_permissions ; set_delegate = Util . auth_of_string set_delegate ; set_verification_key = Util . auth_of_string set_verification_key ; set_zkapp_uri = Util . auth_of_string set_zkapp_uri ; edit_sequence_state = Util . auth_of_string edit_sequence_state ; set_token_symbol = Util . auth_of_string set_token_symbol ; increment_nonce = Util . auth_of_string increment_nonce ; set_voting_for = Util . auth_of_string set_voting_for } in if Currency . Fee ( . fee < Flags . min_fee ) min_fee then failwith ( sprintf " Fee must at least be % s " ( Currency . Fee . to_formatted_string Flags . min_fee ) min_fee ) ; create_command ~ debug ~ keyfile ~ fee ~ nonce ~ memo ~ zkapp_keyfile ~ permissions ~ current_auth ( : Util . auth_of_string current_auth ) current_auth ) )
let test_zkapp_with_genesis_ledger = Command ( . let open Let_syntax in Command . async ~ summary : " Generate a trivial zkApp transaction and genesis ledger with \ verification key for testing " ( let % map keyfile = Param . flag " -- fee - payer - key " ~ doc : " KEYFILE Private key file for the fee payer of the transaction \ ( should be in the genesis ledger ) ledger " Param ( . required string ) string and zkapp_keyfile = Param . flag " -- zkapp - account - key " ~ doc " : KEYFILE Private key file to create a new zkApp account " Param ( . required string ) string and config_file = Param . flag " -- config - file " ~ aliases [ : " config - file " ] ~ doc : " PATH path to a configuration file consisting the genesis ledger " Param ( . required string ) string in test_zkapp_with_genesis_ledger_main keyfile zkapp_keyfile config_file ) )
let txn_commands = [ ( " create - zkapp - account " , create_zkapp_account ) create_zkapp_account ; ( " upgrade - zkapp " , upgrade_zkapp ) upgrade_zkapp ; ( " transfer - funds " , transfer_funds ) transfer_funds ; ( " update - state " , update_state ) update_state ; ( " update - zkapp - uri " , update_zkapp_uri ) update_zkapp_uri ; ( " update - sequence - state " , update_sequence_state ) update_sequence_state ; ( " update - token - symbol " , update_token_symbol ) update_token_symbol ; ( " update - permissions " , update_permissions ) update_permissions ; ( " test - zkapp - with - genesis - ledger " , test_zkapp_with_genesis_ledger ) test_zkapp_with_genesis_ledger ]
let ( ) = Command . run ( Command . group ~ summary " : ZkApp test transaction " ~ preserve_subcommand_order ( ) : txn_commands )
let crc_table = Array . init 256 ( fun n -> let crc = ref ( Int32 . of_int n ) n in for j = 0 to 7 do crc := if Int32 . to_int ( Int32 . logand ( ! crc ) crc 1l ) 1l <> 0 then Int32 . logxor ( Int32 . shift_right_logical ( ! crc ) crc 1 ) 1 polynom else Int32 . shift_right_logical ( ! crc ) crc 1 ; done ; ! crc ) crc
let compress ( ? level = 6 ) 6 ( ? header = true ) true refill flush = let inbuf = Bytes . create buffer_size and outbuf = Bytes . create buffer_size in let zs = Extc . zlib_deflate_init2 level ( if header then max_wbits else - max_wbits ) max_wbits in let rec compr inpos inavail = if inavail = 0 then begin let incount = refill inbuf in if incount = 0 then compr_finish ( compr_finish ) compr_finish else compr 0 incount end else begin let res = Extc . zlib_deflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : inpos ~ slen : inavail ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_NO_FLUSH in let used_in , used_out = res . z_read , res . z_wrote in flush outbuf used_out ; compr ( inpos + used_in ) used_in ( inavail - used_in ) used_in end and compr_finish ( ) = let ret = Extc . zlib_deflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : 0 ~ slen : 0 ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_FINISH in let ( finished , _ , used_out ) used_out = ret . z_finish , ret . z_read , ret . z_wrote in flush outbuf used_out ; if not finished then compr_finish ( compr_finish ) compr_finish in compr 0 0 ; Extc . zlib_deflate_end zs
let compress_direct ( ? level = 6 ) 6 ( ? header = true ) true flush = let outbuf = Bytes . create buffer_size in let zs = Extc . zlib_deflate_init2 level ( if header then max_wbits else - max_wbits ) max_wbits in let rec compr inbuf inpos inavail = if inavail = 0 then ( ) else begin let res = Extc . zlib_deflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : inpos ~ slen : inavail ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_NO_FLUSH in let used_in , used_out = res . z_read , res . z_wrote in flush outbuf used_out ; compr inbuf ( inpos + used_in ) used_in ( inavail - used_in ) used_in end and compr_finish ( ) = let ret = Extc . zlib_deflate zs ~ src " " : ~ spos : 0 ~ slen : 0 ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_FINISH in let ( finished , _ , used_out ) used_out = ret . z_finish , ( ) , ret . z_wrote in flush outbuf used_out ; if not finished then compr_finish ( compr_finish ) compr_finish in compr , compr_finish
let uncompress ( ? header = true ) true refill flush = let inbuf = Bytes . create buffer_size and outbuf = Bytes . create buffer_size in let zs = Extc . zlib_inflate_init2 ( if header then max_wbits else - max_wbits ) max_wbits in let rec uncompr inpos inavail = if inavail = 0 then begin let incount = refill inbuf in if incount = 0 then uncompr_finish true else uncompr 0 incount end else begin let ret = Extc . zlib_inflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : inpos ~ slen : inavail ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_SYNC_FLUSH in let ( finished , used_in , used_out ) used_out = ret . z_finish , ret . z_read , ret . z_wrote in flush outbuf used_out ; if not finished then uncompr ( inpos + used_in ) used_in ( inavail - used_in ) used_in end and uncompr_finish first_finish = let dummy_byte = if first_finish && not header then 1 else 0 in let ret = Extc . zlib_inflate zs ~ src ( : Bytes . to_string inbuf ) inbuf ~ spos : 0 ~ slen : dummy_byte ~ dst : outbuf ~ dpos : 0 ~ dlen : buffer_size Z_SYNC_FLUSH in let ( finished , _ , used_out ) used_out = ret . z_finish , ret . z_read , ret . z_wrote in flush outbuf used_out ; if not finished then uncompr_finish false in uncompr 0 0 ; Extc . zlib_inflate_end zs
let update_crc crc buf pos len = let c = ref ( Int32 . lognot crc ) crc in for i = pos to ( len + pos - 1 ) 1 do let b = Int32 . of_int ( int_of_char ( Bytes . get buf i ) i ) i in c := Int32 . logxor ( Array . get crc_table ( Int32 . to_int ( Int32 . logand ( Int32 . logxor ! c b ) b 0xFFl ) 0xFFl ) 0xFFl ) 0xFFl ( Int32 . shift_right_logical ! c 8 ) 8 ; done ; let ret = Int32 . lognot ! c in ret
type location = Loc of int * int
let input_name = ref " "
let input_chan = ref stdin
let initialize iname = input_name := iname ; input_chan := open_in iname
let output_lines ff char1 char2 charline1 line1 line2 = let n1 = char1 - charline1 and n2 = char2 - charline1 in if line2 > line1 then fprintf ff " , line % d -% d , characters % d -% d :\ n " line1 line2 n1 n2 else fprintf ff " , line % d , characters % d -% d :\ n " line1 n1 n2 ; ( )
let output_loc ff input seek line_flag ( Loc ( pos1 , pos2 ) ) = let pr_chars n c = for i = 1 to n do pp_print_char ff c done in let skip_line ( ) = try while input ( ) != ' \ n ' do ( ) done with End_of_file -> ( ) in let copy_line ( ) = let c = ref ' ' in begin try while c := input ( ) ; ! c != ' \ n ' do pp_print_char ff ! c done with End_of_file -> pp_print_string ff " < EOF " > end ; pp_print_char ff ' \ n ' in let pr_line first len ch = let c = ref ' ' and f = ref first and l = ref len in try while c := input ( ) ; ! c != ' \ n ' do if ! f > 0 then begin f := ! f - 1 ; pp_print_char ff ( if ! c == ' \ t ' then ! c else ' ' ) end else if ! l > 0 then begin l := ! l - 1 ; pp_print_char ff ( if ! c == ' \ t ' then ! c else ch ) end else ( ) done with End_of_file -> if ! f = 0 && ! l > 0 then pr_chars 5 ch in let pos = ref 0 and line1 = ref 1 and line1_pos = ref 0 and line2 = ref 1 and line2_pos = ref 0 in seek 0 ; begin try while ! pos < pos1 do incr pos ; if input ( ) == ' \ n ' then begin incr line1 ; line1_pos := ! pos ; ( ) end done with End_of_file -> ( ) end ; line2 := ! line1 ; line2_pos := ! line1_pos ; begin try while ! pos < pos2 do incr pos ; if input ( ) == ' \ n ' then begin incr line2 ; line2_pos := ! pos ; ( ) end done with End_of_file -> ( ) end ; if line_flag then output_lines ff pos1 pos2 ! line1_pos ! line1 ! line2 ; if ! line1 == ! line2 then begin seek ! line1_pos ; pp_print_string ff error_prompt ; copy_line ( ) ; seek ! line1_pos ; pp_print_string ff error_prompt ; pr_line ( pos1 - ! line1_pos ) ( pos2 - pos1 ) ' ' ; ^ pp_print_char ff ' \ n ' end else begin seek ! line1_pos ; pp_print_string ff error_prompt ; pr_line 0 ( pos1 - ! line1_pos ) ' . ' ; seek pos1 ; copy_line ( ) ; if ! line2 - ! line1 <= 8 then for i = ! line1 + 1 to ! line2 - 1 do pp_print_string ff error_prompt ; copy_line ( ) done else begin for i = ! line1 + 1 to ! line1 + 3 do pp_print_string ff error_prompt ; copy_line ( ) done ; pp_print_string ff error_prompt ; pp_print_string ff " . . . . . . . . . . \ n " ; for i = ! line1 + 4 to ! line2 - 4 do skip_line ( ) done ; for i = ! line2 - 3 to ! line2 - 1 do pp_print_string ff error_prompt ; copy_line ( ) done end ; begin try pp_print_string ff error_prompt ; for i = ! line2_pos to pos2 - 1 do pp_print_char ff ( input ( ) ) done ; pr_line 0 100 ' . ' with End_of_file -> pp_print_string ff " < EOF " > end ; pp_print_char ff ' \ n ' end
let output_location ff loc = let p = pos_in ! input_chan in fprintf ff " File " \% s " " \ ! input_name ; output_loc ff ( fun ( ) -> input_char ! input_chan ) ( seek_in ! input_chan ) true loc ; seek_in ! input_chan p
let output_input_name ff = fprintf ff " File " \% s " , \ line 1 :\ n " ! input_name
type carray = ( float , float64_elt , c_layout ) Array1 . t
type zarray = ( int32 , int32_elt , c_layout ) Array1 . t
let cmake n = let r = Array1 . create float64 c_layout n in Array1 . fill r 0 . 0 ; r
let zmake n = let r = Array1 . create int32 c_layout n in Array1 . fill r 0l ; r
let get_zin v i = Array1 . get v i <> 0l
let zzero zinvec length = for i = 0 to length - 1 do Array1 . set zinvec i 0l done
type ' s f_alloc = unit -> ' s
type ' s f_maxsize = ' s -> int * int
type ' s f_csize = ' s -> int
type ' s f_zsize = ' s -> int
type ( ' s , ' o ) f_step = ' s -> carray -> carray -> zarray -> float -> ' o
type ' s f_ders = ' s -> carray -> carray -> zarray -> carray -> float -> unit
type ' s f_zero = ' s -> carray -> zarray -> carray -> float -> unit
type ' s f_reset = ' s -> unit
type ' s f_horizon = ' s -> float
let time_eq f1 f2 = if abs_float ( f1 . - f2 ) < min_float then true else let rel_error = if abs_float f1 > abs_float f2 then abs_float ( ( f1 . - f2 ) . / f1 ) else abs_float ( ( f1 . - f2 ) . / f2 ) in ( rel_error <= 0 . 000001 )
let time_leq t1 t2 = t1 < t2 || time_eq t1 t2
let time_geq t1 t2 = t1 > t2 || time_eq t1 t2
module type STATE_SOLVER = sig type t type nvec val cmake : int -> nvec val unvec : nvec -> carray type rhsfn = float -> carray -> carray -> unit type dkyfn = nvec -> float -> int -> unit val initialize : rhsfn -> nvec -> t val reinitialize : t -> float -> nvec -> unit val step : t -> float -> nvec -> float val get_dky : t -> dkyfn val set_stop_time : t -> float -> unit val set_min_step : t -> float -> unit val set_max_step : t -> float -> unit val set_tolerances : t -> float -> float -> unit end
module type STATE_SOLVER_SENS = sig include STATE_SOLVER type sensmat val smake : int -> int -> sensmat val arrays_of_sensmat : sensmat -> float array array type rhsfn = carray -> float -> carray -> carray -> unit type dkysensfn = sensmat -> float -> int -> unit val initialize : rhsfn -> carray -> nvec -> sensmat -> t val reinitialize : t -> float -> nvec -> sensmat -> unit val get_sens_dky : t -> dkysensfn end
module type ZEROC_SOLVER = sig type t type zcfn = float -> carray -> carray -> unit val initialize : int -> zcfn -> carray -> t val initialize_only : int -> zcfn -> carray -> t val reinitialize : t -> float -> carray -> unit val step : t -> float -> carray -> unit val takeoff : t -> bool val has_roots : t -> bool val find : t -> ( ( float -> int -> unit ) * carray ) -> zarray -> float end
module type RUNTIME = sig val go : unit hsimu -> unit val check : bool hsimu -> int -> unit end
module type DISCRETE_RUNTIME = sig val go : float -> ( unit -> unit ) -> unit end
type file_kind = ZLS | ZLI ; ;
let file_dependencies_as kind source_file = try if Sys . file_exists source_file then begin match kind with | ZLS -> zls_file_dependencies source_file | ZLI -> zli_file_dependencies source_file end with x -> let report_err = function | Zlexer . Lexical_error ( err , range ) -> lexical_error err range | Zparser . Error -> ( ) | Sys_error msg -> fprintf Format . err_formatter " [ @ I / O error :@ % s ] . " @@ msg | Preprocessing_error -> fprintf Format . err_formatter " [ @ Preprocessing error on file % s ] . " @@ source_file | x -> raise x in error_occurred := true ; report_err x
let file_dependencies source_file = if Filename . check_suffix source_file " . zls " then file_dependencies_as ZLS source_file else if Filename . check_suffix source_file " . zli " then file_dependencies_as ZLI source_file else ( )
let usage = " Usage : zlsdep [ options ] < source files >\ nOptions are " :
let _ = try add_to_load_path Filename . current_dir_name ; Arg . parse [ " - I " , Arg . String add_to_load_path , " < dir > Add < dir > to the list of include directories " ; " - impl " , Arg . String ( file_dependencies_as ZLS ) , " < f > Process < f > as a . zls file " ; " - intf " , Arg . String ( file_dependencies_as ZLI ) , " < f > Process < f > as a . zli file " ; " - pp " , Arg . String ( fun s -> preprocessor := Some s ) , " < cmd > Pipe sources through preprocessor < cmd " ; > " - slash " , Arg . Set force_slash , " ( Windows ) Use forward slash / instead of backslash \\ in file paths " ; ] file_dependencies usage ; exit ( if ! error_occurred then 2 else 0 ) with | Zmisc . Error -> exit 2 ; ;
sig val enable_logging : unit -> unit val min_step_size : float option ref val max_step_size : float option ref val max_sim_time : float option ref val speedup : float ref val step : ' s Zls . f_alloc -> ' s Zls . f_csize -> ' s Zls . f_zsize -> ' s Zls . f_horizon -> ' s Zls . f_maxsize -> ' s Zls . f_ders -> ( ' s , ' o ) Zls . f_step -> ' s Zls . f_zero -> ' s Zls . f_reset -> ( unit -> ' o option * bool * float )
module Make ( SSolver : Zls . STATE_SOLVER ) ( ZSolver : Zls . ZEROC_SOLVER ) = let no_time_in_solver = - 1 . 0 let add_margin h = h . + ( 2 . 0 . * epsilon_float . * h ) let max_sim_time = ref None let min_step_size = ref None let max_step_size = ref None let always_reinit = ref true let precise_logging = ref false let color_logging = ref true let max_c_step = ref 100 . 0 let rel_tol = ref ( None : float option ) let abs_tol = ref ( None : float option ) let log = ref false let log_gcalls = ref false let log_fcalls = ref false let log_dcalls = ref false let show_stats = ref false let speedup = ref 1 . 0 let enable_logging ( ) = ( log := true ) let set_param set_fn s param = ( match ! param with Some v -> set_fn s v | _ -> ( ) ) let set_param2 set_fn s param1 param2 = ( match ! param1 , ! param2 with Some v1 , Some v2 -> set_fn s v1 v2 | _ -> ( ) ) let set_color s = if ! color_logging then print_string s let set_err_color s = if ! color_logging then prerr_string s let print_time ( s1 , s2 ) t = if ! precise_logging then Printf . printf " % s . % 15e % s " s1 t s2 else Printf . printf " % s % e % s " s1 t s2 let print_black_newline ( ) = set_color black ; print_newline ( ) ; flush stdout let print_black_endline s = print_string s ; print_black_newline ( ) let carray_log l t c = let pr = if ! precise_logging then printf " \ t % . 15e " else printf " \ t % e " in if ! precise_logging then printf " % s . % 15e " l t else printf " % s % e " l t ; for i = 0 to Bigarray . Array1 . dim c - 1 do pr c . { i } done ; print_black_newline ( ) let zarray_log l t z = if ! precise_logging then printf " % s . % 15e " l t else printf " % s % e " l t ; for i = 0 to Bigarray . Array1 . dim z - 1 do printf " \ t % s " ( Int32 . to_string z . { i } ) done ; print_black_newline ( ) let print_roots zs t rin = if ! log then ( set_color boldred ; zarray_log " Z : " t rin ) let print_states label t cs = if ! log then carray_log label t cs let print_horizon t t_horizon reinit = if ! log then begin set_color yellow ; print_time ( " H : " , " " ) t ; print_time ( " \ t horizon " , = if reinit then " ( reinit ) " else " " ) t_horizon ; print_black_newline ( ) end let print_help_key ( ) = if ! log then begin print_endline " " ; print_endline " I : initial solver state " ; print_endline " C : result of continuous solver " ; print_endline " C ' : state given to the discrete solver ( last values ) " ; set_color boldred ; print_black_endline " Z : zero - crossings triggering the discrete solver " ; print_endline " D : result of discrete solver " ; set_color yellow ; print_black_endline " H : time horizon set for a continuous phase " ; print_newline ( ) ; print_string " M : time " ; print_newline ( ) ; print_string " --+\ n " ; flush stdout end let print_terminated t = if ! log then begin print_time ( " --+ terminated at " , " \ n " ) t ; flush stdout end ; if ! show_stats then begin let stats = Gc . stat ( ) in printf " gc collections : minor =% d major =% d compact =% d \ n " stats . Gc . minor_collections stats . Gc . major_collections stats . Gc . compactions ; printf " gc words : minor . =% 0f promoted . =% 0f major . =% 0f \ n " stats . Gc . minor_words stats . Gc . promoted_words stats . Gc . major_words ; flush stdout end let args n_eq = Arg . align ( [ ( " - maxt " , Arg . Float ( fun m -> max_sim_time := Some m ) , " < float > maximum simulation time " ) ; ( " - speedup " , Arg . Float ( fun m -> speedup := m ) , " < float > relate simulation and wall clock times ( 2 . 0 = twice as fast ) " ) ; ( " - fullspeed " , Arg . Unit ( fun ( ) -> speedup := 0 . 0 ) , " Do not try to relate simulation and wall clock times " ) ; ( " - maxcstep " , Arg . Float ( fun m -> max_c_step := m ) , " < float > maximum length of a C step ( if ' too big ' the solver may behave strangely ) " ) ; ( " - maxstep " , Arg . Float ( fun m -> max_step_size := Some m ) , " < float > maximum step size ( of solver ) " ) ; ( " - minstep " , Arg . Float ( fun m -> min_step_size := Some m ) , " < float > minimum step size ( of solver ) " ) ; ( " - reltol " , Arg . Float ( fun t -> rel_tol := Some t ) , " < float > Set relative tolerance ( only effective if - abstol is also given ) . " ) ; ( " - abstol " , Arg . Float ( fun t -> abs_tol := Some t ) , " < float > Set absolute tolerance ( only effective if - reltol is also given ) . " ) ; ( " - precisetime " , Arg . Set precise_logging , " Log time values with higher precision . " ) ; ( " - nocolor " , Arg . Clear color_logging , " Disable color logging ( no ASCII escape sequences ) . " ) ; ( " - avoidreinit " , Arg . Clear always_reinit , " Only reinitialize the solver when continuous state values change . " ) ; ( " - l " , Arg . Set log , " Log state variables and zero - crossings to stdout . " ) ; ( " - lgcalls " , Arg . Set log_gcalls , " Log zero - crossing function calls to stdout . " ) ; ( " - lfcalls " , Arg . Set log_fcalls , " Log differential function calls to stdout . " ) ; ( " - ldcalls " , Arg . Set log_dcalls , " Log discrete function calls to stdout . " ) ; ( " - stats " , Arg . Set show_stats , " Show statistics on termination ( with - maxt ) . " ) ; ] ) type model_disc_next = | Continue of bool * float | Goagain of bool | EndSimulation type sim_state_i = { discrete_ready : bool ; reset_required : bool ; init_horizon : float ; } type sim_state_d = { ssolver : SSolver . t ; zsolver : ZSolver . t ; t_sim : float ; t_nextmesh : float ; t_horizon : float ; after_c : bool ; roots_valid : bool ; needs_reset : bool ; } type sim_state = | SimI of sim_state_i | SimD of sim_state_d | SimC of sim_state_d | SimF let step ( f_alloc : ' s Zls . f_alloc ) ( f_csize : ' s Zls . f_csize ) ( f_zsize : ' s Zls . f_zsize ) ( f_horizon : ' s Zls . f_horizon ) ( f_maxsize : ' s Zls . f_maxsize ) ( f_ders : ' s Zls . f_ders ) ( f_step : ( ' s , ' o ) Zls . f_step ) ( f_zero : ' s Zls . f_zero ) ( f_reset : ' s Zls . f_reset ) = let dstate = f_alloc ( ) in let n_cstates , n_zeros = f_maxsize dstate in Arg . parse ( args n_cstates ) ( fun _ -> ( ) ) " Zélus simulation loop " ; let no_roots_in = Zls . zmake n_zeros in let no_roots_out = Zls . cmake n_zeros in let roots = Zls . zmake n_zeros in let ignore_der = Zls . cmake n_cstates in let cstates_nv = SSolver . cmake n_cstates in let cstates = SSolver . unvec cstates_nv in let pre_cstates = Zls . cmake ( if ! always_reinit then 0 else n_cstates ) in let f_main t cs ds = if ! log_fcalls then begin set_color before_loggedcall ; carray_log " * FC " : t cs ; ignore ( f_ders dstate cs ds no_roots_in no_roots_out no_time_in_solver ) ; set_color after_loggedcall ; carray_log " FD " : t ds end else ignore ( f_ders dstate cs ds no_roots_in no_roots_out no_time_in_solver ) ; in let g_main t cs rs = if ! log_gcalls then begin set_color before_loggedcall ; carray_log " * ZC " : t cs ; ignore ( f_zero dstate cs no_roots_in rs no_time_in_solver ) ; set_color after_loggedcall ; carray_log " ZR " : t rs end else ignore ( f_zero dstate cs no_roots_in rs no_time_in_solver ) ; in let g_setup t cs ri = if ! log_gcalls then begin set_color before_loggedcall ; carray_log " * ZS " : t cs ; ignore ( f_zero dstate cs ri no_roots_out no_time_in_solver ) ; set_color after_loggedcall end else ignore ( f_zero dstate cs ri no_roots_out no_time_in_solver ) ; in let d_main t rin = let o = if ! log_dcalls then begin set_color before_loggedcall ; carray_log " * DC " : t cstates ; let r = f_step dstate cstates ignore_der no_roots_in t in set_color after_loggedcall ; carray_log " DR " : t cstates ; r end else f_step dstate cstates ignore_der no_roots_in t in let t_horizon = f_horizon dstate in if t_horizon <= t then o , Goagain true else o , Continue ( true , t_horizon ) in let simstate = ref ( SimI { discrete_ready = false ; reset_required = true ; init_horizon = 0 . 0 } ) in let setup_discrete_step t roots = g_setup no_time_in_solver cstates roots ; if not ! always_reinit then Bigarray . Array1 . blit cstates pre_cstates in let exists_state_reset ( ) = let rec check i = if i = n_cstates then false else if cstates . { i } <> pre_cstates . { i } then true else check ( i + 1 ) in ! always_reinit || check 0 in let step ( ) = match ! simstate with | SimI { discrete_ready = false ; reset_required } -> begin if reset_required then begin print_help_key ( ) ; f_reset dstate end ; let step_out , step_status = d_main 0 . 0 no_roots_in in let goagain , t_horizon = match step_status with | Continue ( _ , t_horizon ) -> ( false , t_horizon ) | Goagain reset -> ( true , infinity ) | EndSimulation -> failwith " End of simulation at first call " ! in print_states ( if goagain then " D . : " else " D : " ) 0 . 0 cstates ; print_horizon 0 . 0 t_horizon false ; simstate := SimI { discrete_ready = not goagain ; reset_required = false ; init_horizon = t_horizon } ; Some step_out , false , 0 . 0 end | SimI { discrete_ready = true ; init_horizon } -> begin if not ! always_reinit then Bigarray . Array1 . blit cstates pre_cstates ; let ss = SSolver . initialize f_main cstates_nv in let zs = ZSolver . initialize n_zeros g_main cstates in set_param SSolver . set_stop_time ss max_sim_time ; set_param SSolver . set_min_step ss min_step_size ; set_param SSolver . set_max_step ss max_step_size ; set_param2 SSolver . set_tolerances ss rel_tol abs_tol ; print_states " I : " 0 . 0 cstates ; print_horizon 0 . 0 init_horizon false ; let params = { ssolver = ss ; zsolver = zs ; t_sim = 0 . 0 ; t_nextmesh = 0 . 0 ; t_horizon = init_horizon ; after_c = false ; roots_valid = false ; needs_reset = false ; } in simstate := SimC params ; None , false , 0 . 0 end | SimC ( { ssolver = ss ; zsolver = zs ; t_sim = last_t ; t_nextmesh ; t_horizon ; needs_reset } as params ) -> ( try if needs_reset then ( SSolver . reinitialize ss last_t cstates_nv ; ZSolver . reinitialize zs last_t cstates ) ; let t_limit = min ( last_t . + ! max_c_step ) t_horizon in let t_nextmesh = if needs_reset || t_limit > t_nextmesh then SSolver . step ss ( add_margin t_limit ) cstates_nv else t_nextmesh in then ( SSolver . get_dky ss cstates_nv t_limit 0 ; t_limit ) else t_nextmesh in ZSolver . step zs t cstates ; let has_roots = ZSolver . has_roots zs in let t = if has_roots then ZSolver . find zs ( SSolver . get_dky ss cstates_nv , cstates ) roots else t in let event = has_roots || t >= t_horizon in let delta = if ! speedup > 0 . 0 then ( t . - last_t ) . / ! speedup else 0 . 0 in print_states ( if event then " C ' : " else " C : " ) t cstates ; let at_stop_time = match ! max_sim_time with Some tmax -> t >= tmax | _ -> false in simstate := if at_stop_time then ( print_terminated t ; SimF ) else if event then begin if has_roots then print_roots zs t roots ; setup_discrete_step t ( if has_roots then roots else no_roots_in ) ; SimD { params with t_sim = t ; t_nextmesh = t_nextmesh ; after_c = true ; roots_valid = has_roots ; needs_reset = false ; } end else SimC { params with needs_reset = false ; after_c = true ; t_sim = t ; t_nextmesh = t_nextmesh } ; None , false , delta with err -> begin flush stdout ; set_err_color boldred ; eprintf " fatal error : % s \ n " ( Printexc . to_string err ) ; if ! log then if Printexc . backtrace_status ( ) then Printexc . print_backtrace stderr else prerr_string " ( compile with - g and run with OCAMLRUNPARAM = b for a backtrace ) \ n " ; Printexc . print_backtrace stderr ; set_err_color black ; flush stderr ; simstate := SimF ; None , false , 0 . 0 end ) | SimD ( { ssolver = ss ; zsolver = zs ; t_sim ; after_c ; needs_reset ; roots_valid } as params ) -> begin let step_out , step_status = d_main t_sim no_roots_in in simstate := ( match step_status with | Continue ( reset , t_horizon ) -> begin print_states " D : " t_sim cstates ; let needs_reinit = needs_reset || reset && exists_state_reset ( ) in print_horizon t_sim t_horizon needs_reinit ; SimC { params with after_c = false ; t_horizon = t_horizon ; needs_reset = needs_reinit } end | Goagain reset -> begin print_states " D . : " t_sim cstates ; SimD { params with after_c = false ; needs_reset = needs_reset || reset } end | EndSimulation -> begin print_states " D $: " t_sim cstates ; print_terminated t_sim ; SimF end ) ; Some step_out , false , 0 . 0 end | SimF -> None , true , 0 . 0 in step
module Make ( SSolver : Zls . STATE_SOLVER ) = struct
module Solver = Zlsolve . Make ( SSolver ) ( Illinois )
let wait_next_instant = let delay = ref 0 . 0 in let rec wait_next_instant starting ending delta = let diff = ( delta . - ( ending . - starting ) ) . - ! delay in if diff > 0 . 0 then begin try delay := 0 . 0 ; ignore ( Unix . select [ ] [ ] [ ] diff ) ; false with Unix . Unix_error ( Unix . EINTR , _ , _ ) -> wait_next_instant starting ( Unix . gettimeofday ( ) ) delta end else begin delay := min ( . - diff ) delta ; true end in wait_next_instant
let go ( Ztypes . Hsim { alloc = main_alloc ; maxsize = main_maxsize ; csize = main_csize ; zsize = main_zsize ; step = main_step ; derivative = main_ders ; crossings = main_zero ; reset = main_reset ; horizon = main_horizon ; } ) = let stepfn = Solver . step main_alloc main_csize main_zsize main_horizon main_maxsize main_ders main_step main_zero main_reset in let starting = ref ( Unix . gettimeofday ( ) ) in let rec step ( ) = let _ , is_done , delta = stepfn ( ) in if is_done then ( ) else if delta = 0 . 0 then step ( ) else let ending = Unix . gettimeofday ( ) in ignore ( wait_next_instant ! starting ending delta ) ; starting := Unix . gettimeofday ( ) ; step ( ) in step ( )
let check ( Ztypes . Hsim { alloc = main_alloc ; maxsize = main_maxsize ; csize = main_csize ; zsize = main_zsize ; step = main_step ; derivative = main_ders ; crossings = main_zero ; reset = main_reset ; horizon = main_horizon ; } ) limit = let stepfn = Solver . step main_alloc main_csize main_zsize main_horizon main_maxsize main_ders main_step main_zero main_reset in let rec step n = if n == limit then ( ) else let result , is_done , delta = stepfn ( ) in match result with | Some false -> exit 1 | _ -> if is_done then ( ) else step ( n + 1 ) in ( step 0 ; exit 0 ) end
module Make ( SSolver : Zls . STATE_SOLVER ) =
module Solver = Zlsolve . Make ( SSolver ) ( Illinois )
let _ = GMain . init ( )
let start_playing = ref true
let destroy ( ) = GMain . Main . quit ( )
let low_prio = Glib . int_of_priority ` LOW -> Glib . Timeout . id = " ml_g_timeout_add " main_ders main_step main_zero main_reset = val stepfn = Solver . step main_alloc main_csize main_zsize main_horizon main_maxsize main_ders main_step main_zero main_reset val mutable last_wall_clk = Unix . gettimeofday ( ) val mutable timer_id = None val mutable step_count = 0 method private inc_step_count ( ) = step_count <- step_count + 1 method private reset_step_count ( ) = step_count <- 0 method private too_many_steps = step_count > 1000 method private clear_timer ( ) = match timer_id with None -> ( ) | Some id -> ( Glib . Timeout . remove id ; timer_id <- None ) method single_step ( ) = let _ , is_done , _ = stepfn ( ) in is_done method trigger_step ( ) = self # clear_timer ( ) ; self # inc_step_count ( ) ; let _ , is_done , delta = stepfn ( ) in let wall_clk = Unix . gettimeofday ( ) in let delta ' = delta . - ( wall_clk . - last_wall_clk ) in last_wall_clk <- wall_clk ; if is_done then true else if delta <= 0 . 0 && not self # too_many_steps then self # trigger_step ( ) else if self # too_many_steps then begin prerr_string " Zlsrungtk : too fast !\ n " ; flush stderr ; self # reset_step_count ( ) ; timer_id <- Some ( timeout_add ~ prio : low_prio ~ ms : 10 ~ callback : self # trigger_step ) ; true end else if delta ' <= 0 . 0 then self # trigger_step ( ) else ( self # reset_step_count ( ) ; timer_id <- Some ( timeout_add ~ prio : low_prio ~ ms ( : int_of_float ( delta ' . * 1000 . 0 ) ) ~ callback : self # trigger_step ) ; true ) method start ( ) = last_wall_clk <- Unix . gettimeofday ( ) ; ignore ( self # trigger_step ( ) ) method stop ( ) = self # clear_timer ( ) end
let go ( Ztypes . Hsim { alloc = main_alloc ; maxsize = main_maxsize ; csize = main_csize ; zsize = main_zsize ; step = main_step ; derivative = main_ders ; crossings = main_zero ; reset = main_reset ; horizon = main_horizon ; } ) = let w = GWindow . window ~ title " : Simulator " ~ width : 250 ~ height : 70 ~ resizable : false ( ) in let outer_box = GPack . vbox ~ packing : w # add ( ) in let top_box = GPack . button_box ` HORIZONTAL ~ packing : outer_box # pack ~ child_width : 48 ~ child_height : 48 ~ layout ` : SPREAD ( ) in let b_play = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_PLAY ( ) in let b_pause = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_PAUSE ( ) in let b_single = GButton . button ~ packing : top_box # pack ~ stock ` : MEDIA_NEXT ( ) in b_pause # misc # set_sensitive false ; let stask = new step_task main_alloc main_csize main_zsize main_horizon main_maxsize main_ders main_step main_zero main_reset in let s_speed_adj = GData . adjustment ~ lower : 1 . 0 ~ upper : 20 . 0 ~ value : 3 . 0 ~ step_incr : 0 . 2 ( ) in let original_speedup = ! Solver . speedup in let change_speedup x = let v = s_speed_adj # value in Solver . speedup := original_speedup . * ( if v <= 3 . 0 then v . / 3 . 0 else ( v . - 3 . 0 ) . * 4 . 0 ) ; ignore ( stask # trigger_step ( ) ) in ignore ( s_speed_adj # connect # value_changed change_speedup ) ; let s_speed = GRange . scale ` HORIZONTAL ~ adjustment : s_speed_adj ~ draw_value : false ~ packing : outer_box # pack ( ) in ignore ( s_speed ) ; let step_react_fun ( ) = try if Printexc . print stask # single_step ( ) then begin b_single # misc # set_sensitive false ; b_play # misc # set_sensitive false ; b_pause # misc # set_sensitive false ; ( ) end with _ -> ( destroy ( ) ) in let play_pushed ( ) = b_single # misc # set_sensitive false ; b_play # misc # set_sensitive false ; b_pause # misc # set_sensitive true ; stask # start ( ) in let pause_pushed ( ) = b_single # misc # set_sensitive true ; b_play # misc # set_sensitive true ; b_pause # misc # set_sensitive false ; stask # stop ( ) in ignore ( b_play # connect # clicked ~ callback : play_pushed ) ; ignore ( b_pause # connect # clicked ~ callback : pause_pushed ) ; ignore ( b_single # connect # clicked ~ callback : step_react_fun ) ; if ! start_playing then play_pushed ( ) ; ignore ( w # connect # destroy ~ callback : destroy ) ; w # show ( ) ; GMain . Main . main ( )
let check _ _ = assert false
let _ = GMain . init ( )