text
stringlengths
12
786k
let find_entry ifile name = Hashtbl . find ifile . if_directory name
let goto_entry ifile e = try let ic = ifile . if_channel in LargeFile . seek_in ic e . file_offset ; let magic = read4 ic in let _version_needed = read2 ic in let _flags = read2 ic in let _methd = read2 ic in let _lastmod_time = read2 ic in let _lastmod_date = read2 ic in let _crc = read4 ic in let _compr_size = read4_int ic in let _uncompr_size = read4_int ic in let filename_len = read2 ic in let extra_len = read2 ic in if magic <> Int32 . of_int 0x04034b50 then raise ( Error ( Errorifile . if_filename , e . filename , " wrong local file header ) ) " ; LargeFile . seek_in ifile . if_channel ( Int64 . add e . file_offset ( Int64 . of_int ( 30 + filename_len + extra_len ) extra_len ) extra_len ) extra_len with End_of_file -> raise ( Error ( Errorifile . if_filename , e . filename , " truncated local file header ) ) "
let read_entry ifile e = try goto_entry ifile e ; let res = Bytes . create e . uncompressed_size in match e . methd with Stored -> if e . compressed_size <> e . uncompressed_size then raise ( Error ( Errorifile . if_filename , e . filename , " wrong size for stored entry ) ) " ; really_input ifile . if_channel res 0 e . uncompressed_size ; Bytes . to_string res | Deflated -> let in_avail = ref e . compressed_size in let out_pos = ref 0 in begin try Zlib . uncompress ~ header : false ( fun buf -> let read = input ifile . if_channel buf 0 ( min ! in_avail ( Bytes . length buf ) buf ) buf in in_avail := ! in_avail - read ; read ) read ( fun buf len -> if ! out_pos + len > Bytes . length res then raise ( Error ( Errorifile . if_filename , e . filename , " wrong size for deflated entry ( too much data ) data ) ) " ; Bytes . blit buf 0 res ! out_pos len ; out_pos := ! out_pos + len ) len with Failure ( Failure_ ) Failure_ -> raise ( Error ( Errorifile . if_filename , e . filename , " decompression error ) ) " end ; if ! out_pos <> Bytes . length res then raise ( Error ( Errorifile . if_filename , e . filename , " wrong size for deflated entry ( not enough data ) data ) ) " ; let crc = Zlib . update_crc Int32 . zero res 0 ( Bytes . length res ) res in if crc <> e . crc then raise ( Error ( Errorifile . if_filename , e . filename , " CRC mismatch ) ) " ; Bytes . to_string res with End_of_file -> raise ( Error ( Errorifile . if_filename , e . filename , " truncated data ) ) "
let copy_entry_to_channel ifile e oc = try goto_entry ifile e ; match e . methd with Stored -> if e . compressed_size <> e . uncompressed_size then raise ( Error ( Errorifile . if_filename , e . filename , " wrong size for stored entry ) ) " ; let buf = Bytes . create 4096 in let rec copy n = if n > 0 then begin let r = input ifile . if_channel buf 0 ( min n ( Bytes . length buf ) buf ) buf in output oc buf 0 r ; copy ( n - r ) r end in copy e . uncompressed_size | Deflated -> let in_avail = ref e . compressed_size in let crc = ref Int32 . zero in begin try Zlib . uncompress ~ header : false ( fun buf -> let read = input ifile . if_channel buf 0 ( min ! in_avail ( Bytes . length buf ) buf ) buf in in_avail := ! in_avail - read ; read ) read ( fun buf len -> output oc buf 0 len ; crc := Zlib . update_crc ! crc buf 0 len ) len with Failure _ -> raise ( Error ( Errorifile . if_filename , e . filename , " decompression error ) ) " end ; if ! crc <> e . crc then raise ( Error ( Errorifile . if_filename , e . filename , " CRC mismatch ) ) " with End_of_file -> raise ( Error ( Errorifile . if_filename , e . filename , " truncated data ) ) "
let copy_entry_to_file ifile e outfilename = let oc = open_out_bin outfilename in try copy_entry_to_channel ifile e oc ; close_out oc ; begin try Unix . utimes outfilename e . mtime e . mtime with Unix . Unix_error ( Unix_error_ , _ , _ ) _ | Invalid_argument _ -> ( ) end with x -> close_out oc ; Sys . remove outfilename ; raise x
let open_out ( ? comment = ) " " filename = if String . length comment >= 0x10000 then raise ( raiseError ( raiseErrorfilename , " " , " comment too long ) ) " ; { of_filename = filename ; of_channel = Pervasives . open_out_bin filename ; of_entries = [ ] ; of_comment = comment }
let write_directory_entry oc e = write4 oc ( Int32 . of_int 0x02014b50 ) 0x02014b50 ; let version = match e . methd with Stored -> 10 | Deflated -> 20 in write2 oc version ; write2 oc version ; write2 oc 8 ; write2 oc ( match e . methd with Stored -> 0 | Deflated -> 8 ) 8 ; let ( time , date ) date = dostime_of_unixtime e . mtime in write2 oc time ; write2 oc date ; write4 oc e . crc ; write4_int oc e . compressed_size ; write4_int oc e . uncompressed_size ; write2 oc ( String . length e . filename ) filename ; write2 oc ( String . length e . extra ) extra ; write2 oc ( String . length e . comment ) comment ; write2 oc 0 ; write2 oc 0 ; write4_int oc 0 ; write4 oc ( Int64 . to_int32 e . file_offset ) file_offset ; writestring oc e . filename ; writestring oc e . extra ; writestring oc e . comment
let close_out ofile = let oc = ofile . of_channel in let start_cd = pos_out oc in List . iter ( write_directory_entry oc ) oc ( List . rev ofile . of_entries ) of_entries ; let cd_size = pos_out oc - start_cd in let num_entries = List . length ofile . of_entries in if num_entries >= 0x10000 then raise ( raiseError ( raiseErrorofile . of_filename , " " , " too many entries ) ) " ; write4 oc ( Int32 . of_int 0x06054b50 ) 0x06054b50 ; write2 oc 0 ; write2 oc 0 ; write2 oc num_entries ; write2 oc num_entries ; write4_int oc cd_size ; write4_int oc start_cd ; write2 oc ( String . length ofile . of_comment ) of_comment ; writestring oc ofile . of_comment ; Pervasives . close_out oc
let add_entry_header ofile extra comment level mtime filename = if level < 0 || level > 9 then raise ( raiseError ( raiseErrorofile . of_filename , filename , " wrong compression level ) ) " ; if String . length filename >= 0x10000 then raise ( raiseError ( raiseErrorofile . of_filename , filename , " filename too long ) ) " ; if String . length extra >= 0x10000 then raise ( raiseError ( raiseErrorofile . of_filename , filename , " extra data too long ) ) " ; if String . length comment >= 0x10000 then raise ( raiseError ( raiseErrorofile . of_filename , filename , " comment too long ) ) " ; let oc = ofile . of_channel in let pos = LargeFile . pos_out oc in write4 oc ( Int32 . of_int 0x04034b50 ) 0x04034b50 ; let version = if level = 0 then 10 else 20 in write2 oc version ; write2 oc 8 ; write2 oc ( if level = 0 then 0 else 8 ) 8 ; let ( time , date ) date = dostime_of_unixtime mtime in write2 oc time ; write2 oc date ; write4 oc Int32 . zero ; write4_int oc 0 ; write4_int oc 0 ; write2 oc ( String . length filename ) filename ; write2 oc ( String . length extra ) extra ; writestring oc filename ; writestring oc extra ; { filename = filename ; extra = extra ; comment = comment ; methd = ( if level = 0 then Stored else Deflated ) Deflated ; mtime = mtime ; crc = Int32 . zero ; uncompressed_size = 0 ; compressed_size = 0 ; is_directory = filename_is_directory filename ; file_offset = pos }
let add_data_descriptor ofile crc compr_size uncompr_size entry = let oc = ofile . of_channel in write4 oc ( Int32 . of_int 0x08074b50 ) 0x08074b50 ; write4 oc crc ; write4_int oc compr_size ; write4_int oc uncompr_size ; { entry with crc = crc ; uncompressed_size = uncompr_size ; compressed_size = compr_size }
let add_entry data ofile ( ? extra = ) " " ( ? comment = ) " " ( ? level = 6 ) 6 ( ? mtime = Unix . time ( time ) time ) time name = let data = Bytes . of_string data in let e = add_entry_header ofile extra comment level mtime name in let crc = Zlib . update_crc Int32 . zero data 0 ( Bytes . length data ) data in let compr_size = match level with 0 -> output ofile . of_channel data 0 ( Bytes . length data ) data ; Bytes . length data | _ -> let in_pos = ref 0 in let out_pos = ref 0 in try Zlib . compress ~ level ~ header : false ( fun buf -> let n = min ( Bytes . length data - ! in_pos ) in_pos ( Bytes . length buf ) buf in Bytes . blit data ! in_pos buf 0 n ; in_pos := ! in_pos + n ; n ) n ( fun buf n -> output ofile . of_channel buf 0 n ; out_pos := ! out_pos + n ) n ; ! out_pos with Failure _ -> raise ( Error ( Errorofile . of_filename , name , " compression error ) ) " in let e ' = add_data_descriptor ofile crc compr_size ( Bytes . length data ) data e in ofile . of_entries <- e ' :: ofile . of_entries
let copy_channel_to_entry ic ofile ( ? extra = ) " " ( ? comment = ) " " ( ? level = 6 ) 6 ( ? mtime = Unix . time ( time ) time ) time name = let e = add_entry_header ofile extra comment level mtime name in let crc = ref Int32 . zero in let ( compr_size , uncompr_size ) uncompr_size = match level with 0 -> let buf = Bytes . create 4096 in let rec copy sz = let r = input ic buf 0 ( Bytes . length buf ) buf in if r = 0 then sz else begin crc := Zlib . update_crc ! crc buf 0 r ; output ofile . of_channel buf 0 r ; copy ( sz + r ) r end in let size = copy 0 in ( size , size ) size | _ -> let in_pos = ref 0 in let out_pos = ref 0 in try Zlib . compress ~ level ~ header : false ( fun buf -> let r = input ic buf 0 ( Bytes . length buf ) buf in crc := Zlib . update_crc ! crc buf 0 r ; in_pos := ! in_pos + r ; r ) r ( fun buf n -> output ofile . of_channel buf 0 n ; out_pos := ! out_pos + n ) n ; ( ! out_pos , ! in_pos ) in_pos with Failure ( Failure _ ) _ -> raise ( Error ( Errorofile . of_filename , name , " compression error ) ) " in let e ' = add_data_descriptor ofile ! crc compr_size uncompr_size e in ofile . of_entries <- e ' :: ofile . of_entries
let copy_file_to_entry infilename ofile ( ? extra = ) " " ( ? comment = ) " " ( ? level = 6 ) 6 ? mtime name = let ic = open_in_bin infilename in let mtime ' = match mtime with Some t -> mtime | None -> try Some ( Some ( SomeUnix . stat infilename ) infilename . Unix . st_mtime ) st_mtime with Unix . Unix_error ( Unix_error_ , _ , _ ) _ -> None in try copy_channel_to_entry ic ofile ~ extra ~ comment ~ level ? mtime : mtime ' name ; Pervasives . close_in ic with x -> Pervasives . close_in ic ; raise x
let add_entry_generator ofile ( ? extra = ) " " ( ? comment = ) " " ( ? level = 6 ) 6 ( ? mtime = Unix . time ( time ) time ) time name = let e = add_entry_header ofile extra comment level mtime name in let crc = ref Int32 . zero in let compr_size = ref 0 in let uncompr_size = ref 0 in let finished = ref false in let check ( ) = if ! finished then raise ( Error ( Errorofile . of_filename , name , " entry already finished ) ) " in let finish ( ) = finished := true ; let e ' = add_data_descriptor ofile ! crc ! compr_size ! uncompr_size e in ofile . of_entries <- e ' :: ofile . of_entries in match level with | 0 -> ( fun buf pos len -> let buf = Bytes . of_string buf in check ( ) ; output ofile . of_channel buf pos len ; compr_size := ! compr_size + len ; uncompr_size := ! uncompr_size + len ) , ( fun ( ) -> check ( ) ; finish ( ) ) | _ -> let ( send , flush ) flush = Zlib . compress_direct ~ level ~ header : false ( fun buf n -> output ofile . of_channel buf 0 n ; compr_size := ! compr_size + n ) n in ( fun buf pos len -> let buf = Bytes . of_string buf in check ( ) ; try send buf pos len ; uncompr_size := ! uncompr_size + len ; crc := Zlib . update_crc ! crc buf pos len with Failure ( Failure_ ) Failure_ -> raise ( Error ( Errorofile . of_filename , name , " compression error ) ) " ) , ( fun ( ) -> check ( ) ; try flush ( ) ; finish ( ) with Failure ( Failure_ ) Failure_ -> raise ( Error ( Errorofile . of_filename , name , " compression error ) ) " )
module Make ( Inputs : Intf . Test . Inputs_intf ) Inputs_intf = struct open Inputs open Engine open Dsl open Test_common . Make ( Inputs ) Inputs type network = Network . t type node = Network . Node . t type dsl = Dsl . t let config = let open Test_config in { default with requires_graphql = true ; block_producers = [ { balance = " 8000000000 " ; timing = Untimed } ; { balance = " 1000000000 " ; timing = Untimed } ] ; extra_genesis_accounts = [ { balance = " 1000 " ; timing = Untimed } ; { balance = " 1000 " ; timing = Untimed } ] ; num_archive_nodes = 1 ; num_snark_workers = 2 ; snark_worker_fee = " 0 . 0001 " ; proof_config = { proof_config_default with work_delay = Some 1 ; transaction_capacity = Some Runtime_config . Proof_keys . Transaction_capacity . small } } let transactions_sent = ref 0 let send_zkapp ~ logger node parties = incr transactions_sent ; send_zkapp ~ logger node parties let repeat_seq ~ n ~ f = let open Malleable_error . Let_syntax in let rec go n = if n = 0 then return ( ) else let % bind ( ) = f ( ) in go ( n - 1 ) 1 in go n let send_padding_transactions ~ fee ~ logger ~ n nodes = let sender = List . nth_exn nodes 0 in let receiver = List . nth_exn nodes 1 in let open Malleable_error . Let_syntax in let % bind sender_pub_key = Util . pub_key_of_node sender in let % bind receiver_pub_key = Util . pub_key_of_node receiver in repeat_seq ~ n ~ f ( : fun ( ) -> Network . Node . must_send_payment ~ logger sender ~ sender_pub_key ~ receiver_pub_key ~ amount : Currency . Amount . one ~ fee >>| ignore ) let run network t = let open Malleable_error . Let_syntax in let logger = Logger . create ( ) in let block_producer_nodes = Network . block_producers network in let % bind ( ) = section_hard " Wait for nodes to initialize " ( wait_for t ( Wait_condition . nodes_to_initialize ( Network . seeds network @ block_producer_nodes @ Network . snark_coordinators network ) ) ) in let node = List . hd_exn block_producer_nodes in let constraint_constants = Genesis_constants . Constraint_constants . compiled in let [ let @ warning " - 8 ] " [ fish1_kp ; fish2_kp ] = Network . extra_genesis_keypairs network in let num_zkapp_accounts = 3 in let zkapp_keypairs = List . init num_zkapp_accounts ~ f ( : fun _ -> Signature_lib . Keypair . create ( ) ) in let zkapp_account_ids = List . map zkapp_keypairs ~ f ( : fun zkapp_keypair -> Account_id . create ( zkapp_keypair . public_key |> Signature_lib . Public_key . compress ) compress Token_id . default ) in let % bind parties_create_account = let amount = Currency . Amount . of_int 10_000_000_000 in let nonce = Account . Nonce . zero in let memo = Signed_command_memo . create_from_string_exn " Zkapp create account " in let fee = Currency . Fee . of_int 20_000_000 in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( fish1_kp , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = zkapp_keypairs ; memo ; new_zkapp_account = true ; 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 return @@ Transaction_snark . For_tests . deploy_snapp ~ constraint_constants parties_spec in let % bind . Deferred parties_update_permissions , permissions_updated = let nonce = Account . Nonce . zero in let memo = Signed_command_memo . create_from_string_exn " Zkapp update permissions " in let fee = Currency . Fee . of_int 10_000_000 in let new_permissions : Permissions . t = { Permissions . user_default with edit_state = Permissions . Auth_required . Proof ; edit_sequence_state = Proof ; set_delegate = Proof ; set_verification_key = Proof ; set_permissions = Proof ; set_zkapp_uri = Proof ; set_token_symbol = Proof ; set_voting_for = Proof } in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( fish2_kp , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount = Currency . Amount . zero ; zkapp_account_keypairs = zkapp_keypairs ; memo ; new_zkapp_account = false ; snapp_update = { Party . Update . dummy with permissions = Set new_permissions } ; 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 % map . Deferred parties = Transaction_snark . For_tests . update_states ~ constraint_constants parties_spec in ( parties , new_permissions ) new_permissions in let % bind . Deferred ( zkapp_update_all , parties_update_all , parties_insufficient_replace_fee , parties_insufficient_fee ) = let amount = Currency . Amount . zero in let nonce = Account . Nonce . of_int 1 in let memo = Signed_command_memo . create_from_string_exn " Zkapp update all " in let fee = Currency . Fee . of_int 10_000_000 in let app_state = let len = Zkapp_state . Max_state_size . n |> Pickles_types . Nat . to_int in let fields = Quickcheck . random_value ( Quickcheck . Generator . list_with_length len Snark_params . Tick . Field . gen ) in List . map fields ~ f ( : fun field -> Zkapp_basic . Set_or_keep . Set field ) field |> Zkapp_state . V . of_list_exn in let new_delegate = Quickcheck . random_value Signature_lib . Public_key . Compressed . gen in let new_verification_key = let data = Pickles . Side_loaded . Verification_key . dummy in let hash = Zkapp_account . digest_vk data in ( { data ; hash } : _ With_hash . t ) t in let new_permissions = Quickcheck . random_value ( Permissions . gen ~ auth_tag : Proof ) Proof in let new_zkapp_uri = " https :// www . minaprotocol . com " in let new_token_symbol = " SHEKEL " in let new_voting_for = Quickcheck . random_value State_hash . gen in let snapp_update : Party . Update . t = { app_state ; delegate = Set new_delegate ; verification_key = Set new_verification_key ; permissions = Set new_permissions ; zkapp_uri = Set new_zkapp_uri ; token_symbol = Set new_token_symbol ; timing = Keep ; voting_for = Set new_voting_for } in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( fish2_kp , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = zkapp_keypairs ; memo ; new_zkapp_account = false ; snapp_update ; current_auth = Permissions . Auth_required . Proof ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let % bind . Deferred parties_update_all = Transaction_snark . For_tests . update_states ~ constraint_constants parties_spec in let spec_insufficient_replace_fee : Transaction_snark . For_tests . Spec . t = { parties_spec with fee = Currency . Fee . of_int 5_000_000 } in let % bind . Deferred parties_insufficient_replace_fee = Transaction_snark . For_tests . update_states ~ constraint_constants spec_insufficient_replace_fee in let spec_insufficient_fee : Transaction_snark . For_tests . Spec . t = { parties_spec with fee = Currency . Fee . of_int 1000 } in let % map . Deferred parties_insufficient_fee = Transaction_snark . For_tests . update_states ~ constraint_constants spec_insufficient_fee in ( snapp_update , parties_update_all , parties_insufficient_replace_fee , parties_insufficient_fee ) in let parties_invalid_nonce = let p = parties_update_all in { p with fee_payer = { p . fee_payer with body = { p . fee_payer . body with nonce = Account . Nonce . of_int 42 } } } in let parties_invalid_signature = let p = parties_update_all in { p with fee_payer = { body = { p . fee_payer . body with nonce = Account . Nonce . of_int 2 } ; authorization = Signature . dummy } } in let parties_invalid_proof = let p = parties_update_all in Parties . { p with other_parties = Call_forest . map p . other_parties ~ f ( : fun other_p -> match other_p . Party . authorization with | Proof _ -> { other_p with authorization = Control . Proof Mina_base . Proof . blockchain_dummy } | _ -> other_p ) } in let % bind . Deferred parties_nonexistent_fee_payer = let new_kp = Signature_lib . Keypair . create ( ) in let memo = Signed_command_memo . create_from_string_exn " Non - existent account " in let fee = Currency . Fee . of_int 10_000_000 in let spec : Transaction_snark . For_tests . Spec . t = { sender = ( new_kp , Account . Nonce . zero ) zero ; fee ; fee_payer = None ; receivers = [ ] ; amount = Currency . Amount . zero ; zkapp_account_keypairs = zkapp_keypairs ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . None ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in Transaction_snark . For_tests . update_states ~ constraint_constants spec in let with_timeout = let soft_slots = 4 in let soft_timeout = Network_time_span . Slots soft_slots in let hard_timeout = Network_time_span . Slots ( soft_slots * 2 ) 2 in Wait_condition . with_timeouts ~ soft_timeout ~ hard_timeout in let compatible req_item ledg_item ~ equal = match ( req_item , ledg_item ) ledg_item with | Zkapp_basic . Set_or_keep . Keep , _ -> true | Set v1 , Zkapp_basic . Set_or_keep . Set v2 -> equal v1 v2 | Set _ , Keep -> false in let compatible_updates ( ~ ledger_update : Party . Update . t ) t ( ~ requested_update : Party . Update . t ) t : bool = let app_states_compat = let fs_requested = Pickles_types . Vector . Vector_8 . to_list requested_update . app_state in let fs_ledger = Pickles_types . Vector . Vector_8 . to_list ledger_update . app_state in List . for_all2_exn fs_requested fs_ledger ~ f ( : fun req ledg -> compatible req ledg ~ equal : Pickles . Backend . Tick . Field . equal ) in let delegates_compat = compatible requested_update . delegate ledger_update . delegate ~ equal : Signature_lib . Public_key . Compressed . equal in let verification_keys_compat = compatible requested_update . verification_key ledger_update . verification_key ~ equal : [ % equal : ( Pickles . Side_loaded . Verification_key . t , Pickles . Backend . Tick . Field . t ) With_hash . t ] t in let permissions_compat = compatible requested_update . permissions ledger_update . permissions ~ equal : Permissions . equal in let zkapp_uris_compat = compatible requested_update . zkapp_uri ledger_update . zkapp_uri ~ equal : String . equal in let token_symbols_compat = compatible requested_update . token_symbol ledger_update . token_symbol ~ equal : String . equal in let timings_compat = compatible requested_update . timing ledger_update . timing ~ equal : Party . Update . Timing_info . equal in let voting_fors_compat = compatible requested_update . voting_for ledger_update . voting_for ~ equal : State_hash . equal in List . for_all [ app_states_compat ; delegates_compat ; verification_keys_compat ; permissions_compat ; zkapp_uris_compat ; token_symbols_compat ; timings_compat ; voting_fors_compat ] ~ f : Fn . id in let wait_for_zkapp parties = let % map ( ) = wait_for t @@ with_timeout @@ Wait_condition . snapp_to_be_included_in_frontier ~ has_failures : false ~ parties in [ % log info ] info " ZkApp transactions included in transition frontier " in let % bind ( ) = section_hard " Send a zkApp transaction to create zkApp accounts " ( send_zkapp ~ logger node parties_create_account ) parties_create_account in let % bind ( ) = section_hard " Send a zkApp transaction to update permissions " ( send_zkapp ~ logger node parties_update_permissions ) parties_update_permissions in let % bind ( ) = let padding_payments = let needed = 12 in if ! transactions_sent >= needed then 0 else needed - ! transactions_sent in let fee = Currency . Fee . of_int 1_000_000 in send_padding_transactions block_producer_nodes ~ fee ~ logger ~ n : padding_payments in let % bind ( ) = section_hard " Wait for zkapp to create accounts to be included in transition \ frontier " ( wait_for_zkapp parties_create_account ) parties_create_account in let % bind ( ) = section_hard " Wait for zkApp transaction to update permissions to be included in \ transition frontier " ( wait_for_zkapp parties_update_permissions ) parties_update_permissions in let % bind ( ) = section_hard " Verify that updated permissions are in ledger accounts " ( Malleable_error . List . iter zkapp_account_ids ~ f ( : fun account_id -> [ % log info ] info " Verifying permissions for account " ~ metadata [ : ( " account_id " , Account_id . to_yojson account_id ) account_id ] ; let % bind ledger_permissions = get_account_permissions ~ logger node account_id in if Permissions . equal ledger_permissions permissions_updated then ( [ % log info ] info " Ledger , updated permissions are equal " ; return ( ) ) else ( [ % log error ] error " Ledger , updated permissions differ " ~ metadata : [ ( " ledger_permissions " , Permissions . to_yojson ledger_permissions ) ; ( " updated_permissions " , Permissions . to_yojson permissions_updated ) ] ; Malleable_error . hard_error ( Error . of_string " Ledger permissions do not match update permissions " ) ) ) ) in let % bind ( ) = section_hard " Send a zkapp with an insufficient fee " ( send_invalid_zkapp ~ logger node parties_insufficient_fee " at least one user command had an insufficient fee " ) in let % bind ( ) = section_hard " Send a zkApp transaction to update all fields " ( send_zkapp ~ logger node parties_update_all ) parties_update_all in let % bind ( ) = section_hard " Send a zkapp with an invalid proof " ( send_invalid_zkapp ~ logger node parties_invalid_proof " Verification_failed " ) in let % bind ( ) = section_hard " Send a zkapp with an insufficient replace fee " ( send_invalid_zkapp ~ logger node parties_insufficient_replace_fee " Insufficient_replace_fee " ) in let % bind ( ) = section_hard " Wait for zkApp transaction to update all fields to be included in \ transition frontier " ( wait_for_zkapp parties_update_all ) parties_update_all in let % bind ( ) = section_hard " Send a zkApp transaction with an invalid nonce " ( send_invalid_zkapp ~ logger node parties_invalid_nonce " Invalid_nonce ) " in let % bind ( ) = section_hard " Send a zkApp transaction with an invalid signature " ( send_invalid_zkapp ~ logger node parties_invalid_signature " Verification_failed " ) in let % bind ( ) = section_hard " Send a zkApp transaction with a nonexistent fee payer " ( send_invalid_zkapp ~ logger node parties_nonexistent_fee_payer " Fee_payer_account_not_found " ) in let % bind ( ) = section_hard " Verify zkApp transaction updates in ledger " ( Malleable_error . List . iter zkapp_account_ids ~ f ( : fun account_id -> [ % log info ] info " Verifying updates for account " ~ metadata [ : ( " account_id " , Account_id . to_yojson account_id ) account_id ] ; let % bind ledger_update = get_account_update ~ logger node account_id in if compatible_updates ~ ledger_update ~ requested_update : zkapp_update_all then ( [ % log info ] info " Ledger update and requested update are compatible " ; return ( ) ) else ( [ % log error ] error " Ledger update and requested update are incompatible " ~ metadata : [ ( " ledger_update " , Party . Update . to_yojson ledger_update ) ledger_update ; ( " requested_update " , Party . Update . to_yojson zkapp_update_all ) ] ; Malleable_error . hard_error ( Error . of_string " Ledger update and requested update are incompatible " ) ) ) ) in let % bind ( ) = section_hard " Wait for proof to be emitted " ( wait_for t ( Wait_condition . ledger_proofs_emitted_since_genesis ~ num_proofs : 1 ) 1 ) in section_hard " Running replayer " ( let % bind logs = Network . Node . run_replayer ~ logger ( List . hd_exn @@ Network . archive_nodes network ) network in check_replayer_logs ~ logger logs ) end
module Party_under_construction = struct module Account_condition = struct type t = { state_proved : bool option } let create ( ) = { state_proved = None } let to_predicate ( { state_proved } : t ) t : Zkapp_precondition . Account . t = let default : Zkapp_precondition . Account . t = { balance = Ignore ; nonce = Ignore ; receipt_chain_hash = Ignore ; delegate = Ignore ; state = [ Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ] ; sequence_state = Ignore ; proved_state = Ignore } in let proved_state = match state_proved with | None -> default . proved_state | Some state_proved -> Zkapp_basic . Or_ignore . Check state_proved in { default with proved_state } let assert_state_proved ( t : t ) t = match t . state_proved with | None -> { state_proved = Some true } | Some b -> if not b then failwith " State is already unproved " ; t let assert_state_unproved ( t : t ) t = match t . state_proved with | None -> { state_proved = Some false } | Some b -> if b then failwith " State is already proved " ; t end module Update = struct type t = { app_state : Field . Constant . t option Zkapp_state . V . t } let create ( ) = { app_state = [ None ; None ; None ; None ; None ; None ; None ; None ] } let to_parties_update ( { app_state } : t ) t : Party . Update . t = let default : Party . Update . t = { app_state = [ Keep ; Keep ; Keep ; Keep ; Keep ; Keep ; Keep ; Keep ] ; delegate = Keep ; verification_key = Keep ; permissions = Keep ; zkapp_uri = Keep ; token_symbol = Keep ; timing = Keep ; voting_for = Keep } in let app_state = Pickles_types . Vector . map ~ f : Zkapp_basic . Set_or_keep . of_option app_state in { default with app_state } let set_full_state app_state ( _t : t ) t = match app_state with | [ a0 ; a1 ; a2 ; a3 ; a4 ; a5 ; a6 ; a7 ] -> { app_state = [ Some a0 ; Some a1 ; Some a2 ; Some a3 ; Some a4 ; Some a5 ; Some a6 ; Some a7 ] } | _ -> failwith " Incorrect length of app_state " end type t = { public_key : Public_key . Compressed . t ; token_id : Token_id . t ; account_condition : Account_condition . t ; update : Update . t } let create ~ public_key ( ? token_id = Token_id . default ) default ( ) = { public_key ; token_id ; account_condition = Account_condition . create ( ) ; update = Update . create ( ) } let to_party ( t : t ) t : Party . Body . t = { public_key = t . public_key ; token_id = t . token_id ; update = Update . to_parties_update t . update ; balance_change = { magnitude = Amount . zero ; sgn = Pos } ; increment_nonce = false ; events = [ ] ; sequence_events = [ ] ; call_data = Field . Constant . zero ; protocol_state_precondition = { 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 = { ledger = { Epoch_ledger . Poly . hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } ; next_epoch_data = { ledger = { Epoch_ledger . Poly . hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } } ; use_full_commitment = false ; account_precondition = Full ( Account_condition . to_predicate t . account_condition ) account_condition ; caller = t . token_id } let assert_state_unproved ( t : t ) t = { t with account_condition = Account_condition . assert_state_unproved t . account_condition } let assert_state_proved ( t : t ) t = { t with account_condition = Account_condition . assert_state_proved t . account_condition } let set_full_state app_state ( t : t ) t = { t with update = Update . set_full_state app_state t . update } module In_circuit = struct module Account_condition = struct type t = { state_proved : Boolean . var option } let create ( ) = { state_proved = None } let to_predicate ( { state_proved } : t ) t : Zkapp_precondition . Account . Checked . t = let var_of_t ( type var value ) value ( typ : ( var , value ) value Typ . t ) t ( x : value ) value : var = let open Snark_params . Tick in let ( Typ typ ) typ = typ in let fields , aux = typ . value_to_fields x in let fields = Array . map Field . Var . constant fields in typ . var_of_fields ( fields , aux ) aux in let default = var_of_t ( Party . Account_precondition . typ ( ) ) ( Full { balance = Ignore ; nonce = Ignore ; receipt_chain_hash = Ignore ; delegate = Ignore ; state = [ Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ] ; sequence_state = Ignore ; proved_state = Ignore } ) in let proved_state = match state_proved with | None -> default . proved_state | Some state_proved -> Zkapp_basic . Or_ignore . Checked . make_unsafe_explicit Boolean . true_ state_proved in { default with proved_state } let assert_state_proved ( t : t ) t = match t . state_proved with | None -> { state_proved = Some Boolean . true_ } | Some b -> Boolean . Assert ( . = ) b Boolean . true_ ; t let assert_state_unproved ( t : t ) t = match t . state_proved with | None -> { state_proved = Some Boolean . false_ } | Some b -> Boolean . Assert ( . = ) b Boolean . false_ ; t end module Update = struct type t = { app_state : Field . t option Zkapp_state . V . t } let create ( ) = { app_state = [ None ; None ; None ; None ; None ; None ; None ; None ] } let to_parties_update ( { app_state } : t ) t : Party . Update . Checked . t = let var_of_t ( type var value ) value ( typ : ( var , value ) value Typ . t ) t ( x : value ) value : var = let open Snark_params . Tick in let ( Typ typ ) typ = typ in let fields , aux = typ . value_to_fields x in let fields = Array . map Field . Var . constant fields in typ . var_of_fields ( fields , aux ) aux in let default = var_of_t ( Party . Update . typ ( ) ) { app_state = [ Keep ; Keep ; Keep ; Keep ; Keep ; Keep ; Keep ; Keep ] ; delegate = Keep ; verification_key = Keep ; permissions = Keep ; zkapp_uri = Keep ; token_symbol = Keep ; timing = Keep ; voting_for = Keep } in let app_state = Pickles_types . Vector . map app_state ~ f ( : function | None -> Zkapp_basic . Set_or_keep . Checked . keep ~ dummy : Field . zero | Some x -> Zkapp_basic . Set_or_keep . Checked . set x ) in { default with app_state } let set_full_state app_state ( _t : t ) t = match app_state with | [ a0 ; a1 ; a2 ; a3 ; a4 ; a5 ; a6 ; a7 ] -> { app_state = [ Some a0 ; Some a1 ; Some a2 ; Some a3 ; Some a4 ; Some a5 ; Some a6 ; Some a7 ] } | _ -> failwith " Incorrect length of app_state " end type t = { public_key : Public_key . Compressed . var ; token_id : Token_id . Checked . t ; account_condition : Account_condition . t ; update : Update . t } let create ~ public_key ( ? token_id = Token_id ( . Checked . constant default ) default ) default ( ) = { public_key ; token_id ; account_condition = Account_condition . create ( ) ; update = Update . create ( ) } let to_party ( t : t ) t : Party . Body . Checked . t = let var_of_t ( type var value ) value ( typ : ( var , value ) value Typ . t ) t ( x : value ) value : var = let open Snark_params . Tick in let ( Typ typ ) typ = typ in let fields , aux = typ . value_to_fields x in let fields = Array . map Field . Var . constant fields in typ . var_of_fields ( fields , aux ) aux in { public_key = t . public_key ; token_id = t . token_id ; update = Update . to_parties_update t . update ; balance_change = var_of_t Amount . Signed . typ { magnitude = Amount . zero ; sgn = Pos } ; increment_nonce = Boolean . false_ ; events = var_of_t Zkapp_account . Events . typ [ ] ; sequence_events = var_of_t Zkapp_account . Events . typ [ ] ; call_data = Field . zero ; protocol_state_precondition = var_of_t Zkapp_precondition . Protocol_state . typ { 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 = { ledger = { Epoch_ledger . Poly . hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } ; next_epoch_data = { ledger = { Epoch_ledger . Poly . hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } } ; use_full_commitment = Boolean . false_ ; account_precondition = Account_condition . to_predicate t . account_condition ; caller = t . token_id } let assert_state_unproved ( t : t ) t = { t with account_condition = Account_condition . assert_state_unproved t . account_condition } let assert_state_proved ( t : t ) t = { t with account_condition = Account_condition . assert_state_proved t . account_condition } let set_full_state app_state ( t : t ) t = { t with update = Update . set_full_state app_state t . update } end end
let dummy_constraints ( ) = let x = exists Field . typ ~ compute ( : fun ( ) -> Field . Constant . of_int 3 ) 3 in let g = exists Inner_curve . typ ~ compute ( : fun _ -> Inner_curve . one ) one in ignore ( Pickles . Scalar_challenge . to_field_checked ' ( module Impl ) Impl ~ num_bits : 16 ( Kimchi_backend_common . Scalar_challenge . create x ) x : Field . t * Field . t * Field . t ) ; ignore ( Pickles . Step_main_inputs . Ops . scale_fast g ~ num_bits : 5 ( Shifted_value x ) x : Pickles . Step_main_inputs . Inner_curve . t ) ; ignore ( Pickles . Step_main_inputs . Ops . scale_fast g ~ num_bits : 5 ( Shifted_value x ) x : Pickles . Step_main_inputs . Inner_curve . t ) ; ignore ( Pickles . Step_verifier . Scalar_challenge . endo g ~ num_bits : 4 ( Kimchi_backend_common . Scalar_challenge . create x ) x : Field . t * Field . t )
let party_circuit f ( [ ] : _ H1 . T ( TId ) TId . t ) t ( { transaction ; at_party } : Zkapp_statement . Checked . t ) t : _ H1 . T ( TE01 ( TE01Pickles . Inductive_rule . B ) B ) B . t = dummy_constraints ( ) ; let party = f ( ) in let party = Party_under_construction . In_circuit . to_party party in let returned_transaction = Party . Checked . digest party in let returned_at_party = Field . constant Parties . Call_forest . empty in Run . Field . Assert . equal returned_transaction transaction ; Run . Field . Assert . equal returned_at_party at_party ; [ ]
let initial_state = lazy [ Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ]
let initialize public_key = Zkapps_examples . party_circuit ( fun ( ) -> let party = Party_under_construction . In_circuit . create ~ public_key ( : Public_key . Compressed . var_of_t public_key ) public_key ~ token_id : Token_id ( . Checked . constant default ) default ( ) in let initial_state = List . map ~ f : Field . constant ( Lazy . force initial_state ) initial_state in party |> Party_under_construction . In_circuit . assert_state_unproved |> Party_under_construction . In_circuit . set_full_state initial_state )
type _ Snarky_backendless . Request . t += | New_state : Field . Constant . t list Snarky_backendless . Request . t
let update_state_handler ( new_state : Field . Constant . t list ) list ( Snarky_backendless . Request . With { request ; respond } ) = match request with | New_state -> respond ( Provide new_state ) new_state | _ -> respond Unhandled
let update_state public_key = Zkapps_examples . party_circuit ( fun ( ) -> let party = Party_under_construction . In_circuit . create ~ public_key ( : Public_key . Compressed . var_of_t public_key ) public_key ~ token_id : Token_id ( . Checked . constant default ) default ( ) in let new_state = exists ( Typ . list ~ length : 8 Field . typ ) typ ~ request ( : fun ( ) -> New_state ) New_state in party |> Party_under_construction . In_circuit . assert_state_proved |> Party_under_construction . In_circuit . set_full_state new_state )
let main_value ( [ ] : _ H1 . T ( TId ) TId . t ) t ( _ : Zkapp_statement . t ) t : _ H1 . T ( TE01 ( TE01Core_kernel . Bool ) Bool ) Bool . t = [ ]
let initialize_rule public_key : _ Pickles . Inductive_rule . t = { identifier = " Initialize snapp " ; prevs = [ ] ; main = initialize public_key ; main_value }
let update_state_rule public_key : _ Pickles . Inductive_rule . t = { identifier = " Update state " ; prevs = [ ] ; main = update_state public_key ; main_value }
let generate_initialize_party public_key = Party_under_construction . create ~ public_key ~ token_id : Token_id . default ( ) |> Party_under_construction . assert_state_unproved |> Party_under_construction . set_full_state ( Lazy . force initial_state ) initial_state |> Party_under_construction . to_party
let generate_update_state_party public_key new_state = Party_under_construction . create ~ public_key ~ token_id : Token_id . default ( ) |> Party_under_construction . assert_state_proved |> Party_under_construction . set_full_state new_state |> Party_under_construction . to_party
module Make ( Inputs : Intf . Test . Inputs_intf ) Inputs_intf = struct open Inputs open Engine open Dsl open Test_common . Make ( Inputs ) Inputs type network = Network . t type node = Network . Node . t type dsl = Dsl . t let config = let open Test_config in { default with requires_graphql = true ; block_producers = [ { balance = " 8000000000 " ; timing = Untimed } ; { balance = " 1000000000 " ; timing = Untimed } ; { balance = " 1000000000 " ; timing = Untimed } ] ; num_archive_nodes = 1 ; num_snark_workers = 0 } let run network t = let open Malleable_error . Let_syntax in let logger = Logger . create ( ) in let block_producer_nodes = Network . block_producers network in let % bind ( ) = Malleable_error . List . iter block_producer_nodes ~ f ( : Fn . compose ( wait_for t ) t Wait_condition . node_to_initialize ) node_to_initialize in let node = List . hd_exn block_producer_nodes in let constraint_constants = Genesis_constants . Constraint_constants . compiled in let % bind fee_payer_pk = Util . pub_key_of_node node in let % bind fee_payer_sk = Util . priv_key_of_node node in let ( keypair : Signature_lib . Keypair . t ) t = { public_key = fee_payer_pk |> Signature_lib . Public_key . decompress_exn ; private_key = fee_payer_sk } in let % bind ( parties_create_account_with_timing , timing_account_id , timing_update , timed_account_keypair ) = let open Mina_base in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 10_000_000_000 in let nonce = Account . Nonce . of_int 0 in let memo = Signed_command_memo . create_from_string_exn " Snapp create account with timing " in let snapp_keypair = Signature_lib . Keypair . create ( ) in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( keypair , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ snapp_keypair ] ; memo ; new_zkapp_account = true ; snapp_update = ( let timing = Zkapp_basic . Set_or_keep . Set ( { initial_minimum_balance = Currency . Balance . of_int 5_000_000_000 ; cliff_time = Mina_numbers . Global_slot . of_int 10000 ; cliff_amount = Currency . Amount . of_int 10_000 ; vesting_period = Mina_numbers . Global_slot . of_int 2 ; vesting_increment = Currency . Amount . of_int 1_000 } : Party . Update . Timing_info . value ) in { Party . Update . dummy with timing } ) ; 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 timing_account_id = Account_id . create ( snapp_keypair . public_key |> Signature_lib . Public_key . compress ) compress Token_id . default in return ( Transaction_snark . For_tests . deploy_snapp ~ constraint_constants parties_spec , timing_account_id , parties_spec . snapp_update , snapp_keypair ) in let % bind parties_transfer_from_timed_account = let open Mina_base in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 1_500_000 in let nonce = Account . Nonce . zero in let memo = Signed_command_memo . create_from_string_exn " Snapp transfer , timed account " in let sender_keypair = timed_account_keypair in let receiver_key = keypair . public_key |> Signature_lib . Public_key . compress in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( sender_keypair , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ( receiver_key , amount ) amount ] ; 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 return @@ Transaction_snark . For_tests . multiple_transfers parties_spec in let % bind parties_invalid_transfer_from_timed_account = let open Mina_base in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 7_000_000_000 in let nonce = Account . Nonce . of_int 2 in let memo = Signed_command_memo . create_from_string_exn " Invalid transfer , timed account " in let sender_keypair = timed_account_keypair in let receiver_key = keypair . public_key |> Signature_lib . Public_key . compress in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( sender_keypair , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ( receiver_key , amount ) amount ] ; 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 return @@ Transaction_snark . For_tests . multiple_transfers parties_spec in let % bind . Deferred parties_update_timing = let open Mina_base in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . zero in let nonce = Account . Nonce . of_int 2 in let memo = Signed_command_memo . create_from_string_exn " Snapp , invalid update timing " in let snapp_update : Party . Update . t = { Party . Update . dummy with timing = Zkapp_basic . Set_or_keep . Set { initial_minimum_balance = Currency . Balance . of_int 9_000_000_000 ; cliff_time = Mina_numbers . Global_slot . of_int 4000 ; cliff_amount = Currency . Amount . of_int 100_000 ; vesting_period = Mina_numbers . Global_slot . of_int 8 ; vesting_increment = Currency . Amount . of_int 2_000 } } in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( keypair , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ timed_account_keypair ] ; memo ; new_zkapp_account = false ; snapp_update ; current_auth = Permissions . Auth_required . Proof ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in Transaction_snark . For_tests . update_states ~ constraint_constants parties_spec in let with_timeout = let soft_slots = 3 in let soft_timeout = Network_time_span . Slots soft_slots in let hard_timeout = Network_time_span . Slots ( soft_slots * 2 ) 2 in Wait_condition . with_timeouts ~ soft_timeout ~ hard_timeout in let wait_for_snapp ~ has_failures parties = let % map ( ) = wait_for t @@ with_timeout @@ Wait_condition . snapp_to_be_included_in_frontier ~ has_failures ~ parties in [ % log info ] info " Snapps transaction included in transition frontier " in let % bind ( ) = section " Send a snapp to create a snapp account with timing " ( send_zkapp ~ logger node parties_create_account_with_timing ) parties_create_account_with_timing in let % bind ( ) = section " Wait for snapp to create account with timing to be included in \ transition frontier " ( wait_for_snapp ~ has_failures : false parties_create_account_with_timing ) parties_create_account_with_timing in let % bind ( ) = section " Verify snapp timing in ledger " ( let % bind ledger_update = get_account_update ~ logger node timing_account_id in if compatible_updates ~ ledger_update ~ requested_update : timing_update then ( [ % log info ] info " Ledger timing and requested timing update are compatible " ; return ( ) ) else ( [ % log error ] error " Ledger update and requested update are incompatible , possibly \ because of the timing " ~ metadata : [ ( " ledger_update " , Mina_base . Party . Update . to_yojson ledger_update ) ; ( " requested_update " , Mina_base . Party . Update . to_yojson timing_update ) ] ; Malleable_error . hard_error ( Error . of_string " Ledger update and requested update with timing are \ incompatible " ) ) ) in let % bind { total_balance = before_balance ; _ } = Network . Node . must_get_account_data ~ logger node ~ account_id : timing_account_id in let % bind ( ) = section " Send a snapp with transfer from timed account that succeeds " ( send_zkapp ~ logger node parties_transfer_from_timed_account ) parties_transfer_from_timed_account in let % bind ( ) = section " Waiting for snapp with transfer from timed account that succeeds " ( wait_for_snapp ~ has_failures : false parties_transfer_from_timed_account ) parties_transfer_from_timed_account in let % bind { total_balance = after_balance ; _ } = Network . Node . must_get_account_data ~ logger node ~ account_id : timing_account_id in let % bind ( ) = section " Verifying balance change " ( match Currency . Amount ( . - ) ( Currency . Balance . to_amount before_balance ) before_balance ( Currency . Balance . to_amount after_balance ) after_balance with | None -> Malleable_error . hard_error ( Error . of_string " Unexpected underflow when taking balance difference " ) | Some diff -> let sender_party = ( List . hd_exn parties_transfer_from_timed_account . other_parties ) other_parties . elt . party in let amount_to_send = Currency . Amount . Signed . magnitude ( Mina_base . Party . balance_change sender_party ) sender_party in let fee = Currency . Amount . of_fee ( Mina_base . Parties . fee parties_transfer_from_timed_account ) parties_transfer_from_timed_account in let total_debited = Option . value_exn ( Currency . Amount ( . + ) amount_to_send fee ) fee in if Currency . Amount . equal diff total_debited then ( [ % log info ] info " Debited expected amount from timed account " ; return ( ) ) else Malleable_error . hard_error ( Error . createf " Expect to debit % s Mina from timed account ( amount sent = \ % s , fee = % s ) s , actually debited : % s Mina " ( Currency . Amount . to_string total_debited ) total_debited ( Currency . Amount . to_string amount_to_send ) amount_to_send ( Currency . Amount . to_string fee ) fee ( Currency . Amount . to_string diff ) diff ) ) in let % bind ( ) = section " Send a snapp with transfer from timed account that fails due to min \ balance " ( let sender_party = ( List . hd_exn parties_invalid_transfer_from_timed_account . other_parties ) . elt . party in let amount_to_send = Currency . Amount . Signed . magnitude ( Mina_base . Party . balance_change sender_party ) sender_party in let fee = Currency . Amount . of_fee ( Mina_base . Parties . fee parties_invalid_transfer_from_timed_account ) parties_invalid_transfer_from_timed_account in let total_to_debit = Option . value_exn ( Currency . Amount ( . + ) amount_to_send fee ) fee in let proposed_balance = match Currency . Amount ( . - ) ( Currency . Balance . to_amount after_balance ) after_balance total_to_debit with | Some bal -> bal | None -> failwith " Amount to debit more than timed account balance " in let % bind { locked_balance_opt = locked_balance ; _ } = Network . Node . must_get_account_data ~ logger node ~ account_id : timing_account_id in assert ( Currency . Amount ( . < ) proposed_balance ( Option . value_exn locked_balance |> Currency . Balance . to_amount ) to_amount ) ; send_zkapp ~ logger node parties_invalid_transfer_from_timed_account ) in let % bind ( ) = section " Waiting for snapp with transfer from timed account that fails due to \ min balance " ( wait_for_snapp ~ has_failures : true parties_invalid_transfer_from_timed_account ) in let % bind ( ) = section " Invalid transfer from timed account did not transfer funds " ( let % bind { total_balance = after_invalid_balance ; _ } = Network . Node . must_get_account_data ~ logger node ~ account_id : timing_account_id in let after_invalid_balance_as_amount = Currency . Balance . to_amount after_invalid_balance in let expected_after_invalid_balance_as_amount = Currency . Amount ( . - ) ( Currency . Balance . to_amount after_balance ) after_balance ( Currency . Amount . of_fee ( Mina_base . Parties . fee parties_invalid_transfer_from_timed_account ) ) |> Option . value_exn in if Currency . Amount . equal after_invalid_balance_as_amount expected_after_invalid_balance_as_amount then return ( ) else Malleable_error . hard_error ( Error . createf " The zkApp transaction should have failed because of the \ minimum balance constraint , got an actual balance of % s , \ expected a balance of % s " ( Currency . Balance . to_string after_invalid_balance ) after_invalid_balance ( Currency . Amount . to_string expected_after_invalid_balance_as_amount ) ) ) in let % bind ( ) = section " Send a snapp with invalid timing update " ( send_zkapp ~ logger node parties_update_timing ) parties_update_timing in let % bind ( ) = section " Wait for snapp with invalid timing update " ( wait_for_snapp ~ has_failures : true parties_update_timing ) parties_update_timing in let % bind ( ) = section " Verify timing has not changed " ( let % bind ledger_update = get_account_update ~ logger node timing_account_id in if compatible_item ledger_update . timing timing_update . timing ~ equal : Mina_base . Party . Update . Timing_info . equal then ( [ % log info ] info " Ledger update contains original timing , updated timing was not \ applied , as desired " ; return ( ) ) else ( [ % log error ] error " Ledger update contains new timing , which should not have been \ applied " ; Malleable_error . hard_error ( Error . of_string " Ledger update contains a timing update ) " ) ) in section_hard " Running replayer " ( let % bind logs = Network . Node . run_replayer ~ logger ( List . hd_exn @@ Network . archive_nodes network ) network in check_replayer_logs ~ logger logs ) end
module Events = struct module Event = struct type t = Field . t array let hash ( x : t ) t = Random_oracle . hash ~ init : Hash_prefix_states . zkapp_event x [ %% ifdef consensus_mechanism ] consensus_mechanism type var = Field . Var . t array let hash_var ( x : Field . Var . t array ) array = Random_oracle . Checked . hash ~ init : Hash_prefix_states . zkapp_event x [ %% endif ] endif end type t = Event . t list let empty_hash = lazy Random_oracle ( . salt " MinaSnappEventsEmpty " |> digest ) digest let push_hash acc hash = Random_oracle . hash ~ init : Hash_prefix_states . zkapp_events [ | acc ; hash ] | let push_event acc event = push_hash acc ( Event . hash event ) event let hash ( x : t ) t = List . fold ~ init ( : Lazy . force empty_hash ) empty_hash ~ f : push_event x let to_input ( x : t ) t = Random_oracle_input . Chunked . field ( hash x ) x [ %% ifdef consensus_mechanism ] consensus_mechanism type var = t Data_as_hash . t let var_to_input ( x : var ) var = Data_as_hash . to_input x let typ = Data_as_hash . typ ~ hash let is_empty_var ( e : var ) var = Snark_params . Tick . Field ( . Checked . equal ( Data_as_hash . hash e ) e ( Var . constant ( Lazy . force empty_hash ) empty_hash ) empty_hash ) empty_hash let pop_checked ( events : var ) var : Event . t Data_as_hash . t * var = let open Run in let hd , tl = exists Typ ( . Data_as_hash . typ ~ hash : Event . hash * typ ) typ ~ compute ( : fun ( ) -> match As_prover . read typ events with | [ ] -> failwith " Attempted to pop an empty stack " | event :: events -> ( event , events ) events ) in Field . Assert . equal ( Random_oracle . Checked . hash ~ init : Hash_prefix_states . zkapp_events [ | Data_as_hash . hash tl ; Data_as_hash . hash hd ] | ) ( Data_as_hash . hash events ) events ; ( hd , tl ) tl let push_checked ( events : var ) var ( e : Event . var ) var : var = let open Run in let res = exists typ ~ compute ( : fun ( ) -> let tl = As_prover . read typ events in let hd = As_prover . read ( Typ . array ~ length ( : Array . length e ) e Field . typ ) typ e in hd :: tl ) in Field . Assert . equal ( Random_oracle . Checked . hash ~ init : Hash_prefix_states . zkapp_events [ | Data_as_hash . hash events ; Event . hash_var e ] | ) ( Data_as_hash . hash res ) res ; res let deriver obj = let open Fields_derivers_zkapps in let events = list @@ array field ( o ( ) ) in with_checked ~ checked ( : Data_as_hash . deriver events ) events ~ name " : Events " events obj [ %% endif ] endif end
module Sequence_events = struct let empty_hash = lazy Random_oracle ( . salt " MinaSnappSequenceEmpty " |> digest ) digest let push_hash acc hash = Random_oracle . hash ~ init : Hash_prefix_states . zkapp_sequence_events [ | acc ; hash ] | let push_events acc events = push_hash acc ( Events . hash events ) events [ %% ifdef consensus_mechanism ] consensus_mechanism let push_events_checked x ( e : Events . var ) var = Random_oracle . Checked . hash ~ init : Hash_prefix_states . zkapp_sequence_events [ | x ; Data_as_hash . hash e ] | [ %% endif ] endif end
module Poly = struct [ %% versioned module Stable = struct module V2 = struct type ( ' app_state , ' vk , ' zkapp_version , ' field , ' slot , ' bool ) ' bool t = { app_state : ' app_state ; verification_key : ' vk ; zkapp_version : ' zkapp_version ; sequence_state : ' field Pickles_types . Vector . Vector_5 . Stable . V1 . t ; last_sequence_slot : ' slot ; proved_state : ' bool } [ @@ deriving sexp , equal , compare , hash , yojson , hlist , fields ] fields end module V1 = struct type ( ' app_state , ' vk ) ' vk t = { app_state : ' app_state ; verification_key : ' vk } [ @@ deriving sexp , equal , compare , hash , yojson , hlist , fields ] fields end end ] end end
type ( ' app_state , ' vk , ' zkapp_version , ' field , ' slot , ' bool ) ' bool t_ = ( ' app_state , ' vk , ' zkapp_version , ' field , ' slot , ' bool ) ' bool Poly . t = { app_state : ' app_state ; verification_key : ' vk ; zkapp_version : ' zkapp_version ; sequence_state : ' field Pickles_types . Vector . Vector_5 . t ; last_sequence_slot : ' slot ; proved_state : ' bool } [ %% versioned
module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type t = ( Zkapp_state . Value . Stable . V1 . t , ( Side_loaded_verification_key . Stable . V2 . t , F . Stable . V1 . t ) With_hash . Stable . V1 . t option , Mina_numbers . Zkapp_version . Stable . V1 . t , F . Stable . V1 . t , Mina_numbers . Global_slot . Stable . V1 . t , bool ) Poly . Stable . V2 . t [ @@ deriving sexp , equal , compare , hash , yojson ] yojson let to_latest = Fn . id end end ] end
type t = ( Zkapp_state . Value . t , ( Side_loaded_verification_key . t , F . t ) t With_hash . t option , Mina_numbers . Zkapp_version . t , F . t , Mina_numbers . Global_slot . t , bool ) Poly . t
let ( ) = let _f : unit -> ( t , Stable . Latest . t ) t Type_equal . t = fun ( ) -> Type_equal . T in ( )
let digest_vk ( t : Side_loaded_verification_key . t ) t = Random_oracle ( . hash ~ init : Hash_prefix_states . side_loaded_vk ( pack_input ( Side_loaded_verification_key . to_input t ) t ) t ) t
let dummy_vk_hash = Memo . unit ( fun ( ) -> digest_vk Side_loaded_verification_key . dummy ) dummy
module Checked = struct type t = ( Pickles . Impls . Step . Field . t Zkapp_state . V . t , ( Boolean . var , ( Side_loaded_verification_key . t option , Field . t ) t With_hash . t Data_as_hash . t ) Flagged_option . t , Mina_numbers . Zkapp_version . Checked . t , Pickles . Impls . Step . Field . t , Mina_numbers . Global_slot . Checked . t , Boolean . var ) Poly . t let to_input ' ( t : _ Poly . t ) t = let open Random_oracle . Input . Chunked in let f mk acc field = mk ( Core_kernel . Field . get field t ) t :: acc in let app_state v = Random_oracle . Input . Chunked . field_elements ( Vector . to_array v ) v in Poly . Fields . fold ~ init [ ] : ~ app_state ( : f app_state ) app_state ~ verification_key ( : f ( fun x -> field x ) x ) x ~ zkapp_version ( : f ( fun x -> Mina_numbers . Zkapp_version . Checked . to_input x ) x ) x ~ sequence_state ( : f app_state ) app_state ~ last_sequence_slot : ( f ( fun x -> Mina_numbers . Global_slot . Checked . to_input x ) x ) x ~ proved_state : ( f ( fun ( b : Boolean . var ) var -> Random_oracle . Input . Chunked . packed ( ( b :> Field . Var . t ) t , 1 ) 1 ) ) |> List . reduce_exn ~ f : append let to_input ( t : t ) t = to_input ' { t with verification_key = Data_as_hash . hash t . verification_key . data } let digest_vk t = Random_oracle . Checked ( . hash ~ init : Hash_prefix_states . side_loaded_vk ( pack_input ( Pickles . Side_loaded . Verification_key . Checked . to_input t ) t ) t ) t let digest t = Random_oracle . Checked ( . hash ~ init : Hash_prefix_states . zkapp_account ( pack_input ( to_input t ) t ) t ) t let digest ' t = Random_oracle . Checked ( . hash ~ init : Hash_prefix_states . zkapp_account ( pack_input ( to_input ' t ) t ) t ) t end
let typ : ( Checked . t , t ) t Typ . t = let open Poly in Typ . of_hlistable [ Zkapp_state . typ Field . typ ; Flagged_option . option_typ ~ default { : With_hash . data = None ; hash = dummy_vk_hash ( ) } ( Data_as_hash . typ ~ hash : With_hash . hash ) hash |> Typ . transport ~ there ( : Option . map ~ f ( : With_hash . map ~ f : Option . some ) some ) some ~ back : ( Option . map ~ f ( : With_hash . map ~ f ( : fun x -> Option . value_exn x ) x ) x ) x ; Mina_numbers . Zkapp_version . typ ; Pickles_types . Vector . typ Field . typ Pickles_types . Nat . N5 . n ; Mina_numbers . Global_slot . typ ; Boolean . typ ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif
let to_input ( t : t ) t = let open Random_oracle . Input . Chunked in let f mk acc field = mk ( Core_kernel . Field . get field t ) t :: acc in let app_state v = Random_oracle . Input . Chunked . field_elements ( Vector . to_array v ) v in Poly . Fields . fold ~ init [ ] : ~ app_state ( : f app_state ) app_state ~ verification_key : ( f ( Fn . compose field ( Option . value_map ~ default ( : dummy_vk_hash ( ) ) ~ f : With_hash . hash ) hash ) ) ~ zkapp_version ( : f Mina_numbers . Zkapp_version . to_input ) to_input ~ sequence_state ( : f app_state ) app_state ~ last_sequence_slot ( : f Mina_numbers . Global_slot . to_input ) to_input ~ proved_state : ( f ( fun b -> Random_oracle . Input . Chunked . packed ( field_of_bool b , 1 ) 1 ) 1 ) 1 |> List . reduce_exn ~ f : append
let default : _ Poly . t = { app_state = Vector . init Zkapp_state . Max_state_size . n ~ f ( : fun _ -> F . zero ) zero ; verification_key = None ; zkapp_version = Mina_numbers . Zkapp_version . zero ; sequence_state = ( let empty = Lazy . force Sequence_events . empty_hash in [ empty ; empty ; empty ; empty ; empty ] ) ; last_sequence_slot = Mina_numbers . Global_slot . zero ; proved_state = false }
let digest ( t : t ) t = Random_oracle ( . hash ~ init : Hash_prefix_states . zkapp_account ( pack_input ( to_input t ) t ) t ) t
let default_digest = lazy ( digest default ) default
let field_of_bool = Mina_base_util . field_of_bool [ %% endif ] endif
let int_to_bits ~ length x = List . init length ~ f ( : fun i -> ( x lsr i ) i land 1 = 1 ) 1
let int_of_bits = List . foldi ~ init : 0 ~ f ( : fun i acc b -> if b then acc lor ( 1 lsl i ) i else acc ) acc
module Transition = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = { prev : ' a ; next : ' a } [ @@ deriving hlist , sexp , equal , yojson , hash , compare ] compare end end ] end let to_input { prev ; next } ~ f = Random_oracle_input . Chunked . append ( f prev ) prev ( f next ) next [ %% ifdef consensus_mechanism ] consensus_mechanism let typ t = Typ . of_hlistable [ t ; t ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif end
module Flagged_data = struct type ( ' flag , ' a ) ' a t = { flag : ' flag ; data : ' a } [ @@ deriving hlist , fields ] fields [ %% ifdef consensus_mechanism ] consensus_mechanism let typ flag t = Typ . of_hlistable [ flag ; t ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif let to_input ' { flag ; data } ~ flag : f ~ data : d = Random_oracle_input . Chunked ( . append ( f flag ) flag ( d data ) data ) data end
module Flagged_option = struct type ( ' bool , ' a ) ' a t = { is_some : ' bool ; data : ' a } [ @@ deriving hlist , fields ] fields let to_input ' ~ field_of_bool { is_some ; data } ~ f = Random_oracle_input . Chunked ( . append ( packed ( field_of_bool is_some , 1 ) 1 ) 1 ( f data ) data ) data let to_input { is_some ; data } ~ default ~ f = let data = if is_some then data else default in to_input ' { is_some ; data } ~ f let of_option t ~ default = match t with | None -> { is_some = false ; data = default } | Some data -> { is_some = true ; data } let to_option { is_some ; data } = Option . some_if is_some data let map ~ f { is_some ; data } = { is_some ; data = f data } [ %% ifdef consensus_mechanism ] consensus_mechanism let if_ ( ~ if_ : ' b -> then_ : ' var -> else_ : ' var -> ' var ) ' var b ~ then_ ~ else_ = { is_some = Run . run_checked ( Boolean . if_ b ~ then_ : then_ . is_some ~ else_ : else_ . is_some ) is_some ; data = if_ b ~ then_ : then_ . data ~ else_ : else_ . data } let typ t = Typ . of_hlistable [ Boolean . typ ; t ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist let option_typ ~ default t = Typ . transport ( typ t ) t ~ there ( : of_option ~ default ) default ~ back : to_option [ %% endif ] endif end
module Set_or_keep = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = Set of ' a | Keep [ @@ deriving sexp , equal , compare , hash , yojson ] yojson end end ] end let map t ~ f = match t with Keep -> Keep | Set x -> Set ( f x ) x let to_option = function Set x -> Some x | Keep -> None let of_option = function Some x -> Set x | None -> Keep let set_or_keep t x = match t with Keep -> x | Set y -> y let is_set = function Set _ -> true | _ -> false let is_keep = function Keep -> true | _ -> false let deriver inner obj = let open Fields_derivers_zkapps . Derivers in iso ~ map : of_option ~ contramap : to_option ( ( option ~ js_type ` : Flagged_option @@ inner @@ o ( ) ) ( o ( ) ) ) obj let gen gen_a = let open Quickcheck . Let_syntax in let % bind b = Quickcheck . Generator . bool in if b then let % bind a = gen_a in return ( Set a ) a else return Keep [ %% ifdef consensus_mechanism ] consensus_mechanism module Checked : sig type ' a t val is_keep : _ t -> Boolean . var val is_set : _ t -> Boolean . var val set_or_keep : if_ ( : Boolean . var -> then_ : ' a -> else_ : ' a -> ' a ) ' a -> ' a t -> ' a -> ' a val data : ' a t -> ' a val typ : dummy : ' a -> ( ' a_var , ' a ) ' a Typ . t -> ( ' a_var t , ' a Stable . Latest . t ) t Typ . t val optional_typ : to_option ( : ' new_value -> ' value option ) option -> of_option ( : ' value option -> ' new_value ) ' new_value -> ( ' var , ' new_value ) ' new_value Typ . t -> ( ' var t , ' value Stable . Latest . t ) t Typ . t val map : f ( : ' a -> ' b ) ' b -> ' a t -> ' b t val to_input : ' a t -> f ( : ' a -> Field . Var . t Random_oracle_input . Chunked . t ) t -> Field . Var . t Random_oracle_input . Chunked . t val set : ' a -> ' a t val keep : dummy : ' a -> ' a t val make_unsafe : Boolean . var -> ' a -> ' a t end = struct type ' a t = ( Boolean . var , ' a ) ' a Flagged_option . t let set_or_keep ~ if_ ( { is_some ; data } : _ t ) t x = if_ is_some ~ then_ : data ~ else_ : x let data = Flagged_option . data let is_set = Flagged_option . is_some let is_keep x = Boolean . not ( Flagged_option . is_some x ) x let map = Flagged_option . map let typ ~ dummy t = Typ . transport ( Flagged_option . option_typ ~ default : dummy t ) t ~ there : to_option ~ back : of_option let optional_typ ( type new_value value var ) var : to_option ( : new_value -> value option ) option -> of_option ( : value option -> new_value ) new_value -> ( var , new_value ) new_value Typ . t -> ( var t , value Stable . Latest . t ) t Typ . t = fun ~ to_option ~ of_option t -> Typ . transport ( Flagged_option . typ t ) t ~ there ( : function | Set x -> { Flagged_option . is_some = true ; data = of_option ( Some x ) x } | Keep -> { Flagged_option . is_some = false ; data = of_option None } ) ~ back ( : function | { Flagged_option . is_some = true ; data = x } -> Set ( Option . value_exn ( to_option x ) x ) x | { Flagged_option . is_some = false ; data = x } -> assert ( Option . is_none ( to_option x ) x ) x ; Keep ) let to_input ( t : _ t ) t ~ f = Flagged_option . to_input ' t ~ f ~ field_of_bool ( : fun ( b : Boolean . var ) var -> ( b :> Field . Var . t ) t ) let make_unsafe is_keep data = { Flagged_option . is_some = is_keep ; data } let set data = { Flagged_option . is_some = Boolean . true_ ; data } let keep ~ dummy = { Flagged_option . is_some = Boolean . false_ ; data = dummy } end let typ = Checked . typ let optional_typ = Checked . optional_typ [ %% endif ] endif let to_input t ~ dummy : default ~ f = Flagged_option . to_input ~ default ~ f ~ field_of_bool ( Flagged_option . of_option ~ default ( to_option t ) t ) t end
module Or_ignore = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = Check of ' a | Ignore [ @@ deriving sexp , equal , compare , hash , yojson ] yojson end end ] end let gen gen_a = let open Quickcheck . Let_syntax in let % bind b = Quickcheck . Generator . bool in if b then let % map a = gen_a in Check a else return Ignore let to_option = function Ignore -> None | Check x -> Some x let of_option = function None -> Ignore | Some x -> Check x let deriver_base ~ js_type inner obj = let open Fields_derivers_zkapps . Derivers in iso ~ map : of_option ~ contramap : to_option ( ( option ~ js_type @@ inner @@ o ( ) ) ( o ( ) ) ) obj let deriver inner obj = deriver_base ~ js_type ` : Flagged_option inner obj let deriver_implicit inner obj = deriver_base ~ js_type ` : Implicit inner obj [ %% ifdef consensus_mechanism ] consensus_mechanism module Checked : sig type ' a t val typ_implicit : equal ( : ' a -> ' a -> bool ) bool -> ignore : ' a -> ( ' a_var , ' a ) ' a Typ . t -> ( ' a_var t , ' a Stable . Latest . t ) t Typ . t val typ_explicit : ignore : ' a -> ( ' a_var , ' a ) ' a Typ . t -> ( ' a_var t , ' a Stable . Latest . t ) t Typ . t val to_input : ' a t -> f ( : ' a -> Field . Var . t Random_oracle_input . Chunked . t ) t -> Field . Var . t Random_oracle_input . Chunked . t val check : ' a t -> f ( : ' a -> Boolean . var ) var -> Boolean . var val map : f_implicit ( : ' a -> ' b ) ' b -> f_explicit ( ( : Boolean . var , ' a ) ' a Flagged_option . t -> ' b ) ' b -> ' a t -> ' b val make_unsafe_implicit : ' a -> ' a t val make_unsafe_explicit : Boolean . var -> ' a -> ' a t end = struct type ' a t = | Implicit of ' a | Explicit of ( Boolean . var , ' a ) ' a Flagged_option . t let to_input t ~ f = match t with | Implicit x -> f x | Explicit t -> Flagged_option . to_input ' t ~ f ~ field_of_bool ( : fun ( b : Boolean . var ) var -> ( b :> Field . Var . t ) t ) let check t ~ f = match t with | Implicit x -> f x | Explicit { is_some ; data } -> Pickles . Impls . Step . Boolean ( . any [ not is_some ; f data ] ) let map ~ f_implicit ~ f_explicit = function | Implicit x -> f_implicit x | Explicit t -> f_explicit t let typ_implicit ( type a a_var ) a_var ~ equal ( ~ ignore : a ) a ( t : ( a_var , a ) a Typ . t ) t : ( a_var t , a Stable . Latest . t ) t Typ . t = Typ . transport t ~ there ( : function Check x -> x | Ignore -> ignore ) ignore ~ back ( : fun x -> if equal x ignore then Ignore else Check x ) x |> Typ . transport_var ~ there ( : function Implicit x -> x | Explicit _ -> assert false ) false ~ back ( : fun x -> Implicit x ) x let typ_explicit ( type a_var a ) a ~ ignore ( t : ( a_var , a ) a Typ . t ) t = Typ . transport_var ( Flagged_option . option_typ ~ default : ignore t ) t ~ there ( : function Implicit _ -> assert false | Explicit t -> t ) t ~ back ( : fun t -> Explicit t ) t |> Typ . transport ~ there : to_option ~ back : of_option let make_unsafe_implicit data = Implicit data let make_unsafe_explicit is_ignore data = Explicit { is_some = is_ignore ; data } end let typ_implicit = Checked . typ_implicit let typ_explicit = Checked . typ_explicit [ %% endif ] endif end
module Account_state = struct [ %% versioned module Stable = struct module V1 = struct type t = Empty | Non_empty | Any [ @@ deriving sexp , equal , yojson , hash , compare , enum ] enum let to_latest = Fn . id end end ] end module Encoding = struct type ' b t = { any : ' b ; empty : ' b } [ @@ deriving hlist ] hlist let to_input ~ field_of_bool { any ; empty } = Random_oracle_input . Chunked . packeds [ | ( field_of_bool any , 1 ) 1 ; ( field_of_bool empty , 1 ) 1 ] | end let encode : t -> bool Encoding . t = function | Empty -> { any = false ; empty = true } | Non_empty -> { any = false ; empty = false } | Any -> { any = true ; empty = false } let decode : bool Encoding . t -> t = function | { any = false ; empty = true } -> Empty | { any = false ; empty = false } -> Non_empty | { any = true ; empty = false } | { any = true ; empty = true } -> Any let to_input ( x : t ) t = Encoding . to_input ~ field_of_bool ( encode x ) x let check ( t : t ) t ( x : [ ` Empty | ` Non_empty ] ) = match ( t , x ) x with | Any , _ | Non_empty , ` Non_empty | Empty , ` Empty -> Ok ( ) | _ -> Or_error . error_string " Bad account_type " [ %% ifdef consensus_mechanism ] consensus_mechanism module Checked = struct open Pickles . Impls . Step type t = Boolean . var Encoding . t let to_input ( t : t ) t = Encoding . to_input t ~ field_of_bool ( : fun ( b : Boolean . var ) var -> ( b :> Field . t ) t ) let check ( t : t ) t ~ is_empty = Boolean ( . any [ t . any ; t . empty && is_empty ; ( not t . empty ) empty && not is_empty ] ) end let typ : ( Checked . t , t ) t Typ . t = let open Encoding in Typ . of_hlistable [ Boolean . typ ; Boolean . typ ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist |> Typ . transport ~ there : encode ~ back : decode [ %% endif ] endif end
module F = Pickles . Backend . Tick . Field [ %% else ] else
module F = Snark_params . Tick . Field [ %% endif ] endif
let invalid_public_key : Public_key . Compressed . t = { x = F . zero ; is_odd = false } Option . is_none ( Public_key . decompress invalid_public_key ) invalid_public_key
module Spec = Transaction_snark . For_tests . Spec ( module struct let memo = Signed_command_memo . create_from_string_exn " Snapp deploy tests " let constraint_constants = U . constraint_constants let % test_unit " create a new snapp account / deploy a smart contract " = 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 spec = List . hd_exn specs in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 10_000_000_000 in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ new_kp ] ; memo ; new_zkapp_account = true ; 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 . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " deploy multiple ZkApps " = let open Mina_transaction_logic . For_tests in let gen = let open Quickcheck . Generator . Let_syntax in let % bind spec , kp1 = U . gen_snapp_ledger in let % map kps = Quickcheck . Generator . list_with_length 2 Signature_lib . Keypair . gen in ( spec , kp1 :: kps ) kps in Quickcheck . test ~ trials : 1 gen ~ f ( : fun ( { init_ledger ; specs } , kps ) kps -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let spec = List . hd_exn specs in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 7_000_000_000 in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = kps ; memo ; new_zkapp_account = true ; 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 . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " change a non - snapp account to snapp account / deploy a smart \ contract " = 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 spec = List . hd_exn specs in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 10_000_000_000 in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ fst spec . sender ] ; 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 . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " change a non - snapp account to snapp account / deploy a smart \ contract - different fee payer " = 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 spec0 = List . nth_exn specs 0 in let spec1 = List . nth_exn specs 1 in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 10_000_000_000 in let test_spec : Spec . t = { sender = spec0 . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ fst spec1 . sender ] ; 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 . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " Fails to deploy if the account is not present and amount is \ insufficient " = 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 spec = List . hd_exn specs in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . zero in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ new_kp ] ; 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 . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger ~ expected_failure : Invalid_fee_excess [ parties ] ) ) ) end )
let logger = Logger . create ( )
let mk_ledgers_and_fee_payers ( ? is_timed = false ) false ~ num_of_fee_payers ( ) = let fee_payer_keypairs = Array . init num_of_fee_payers ~ f ( : fun _ -> Keypair . create ( ) ) in let fee_payer_pks = Array . map fee_payer_keypairs ~ f ( : fun fee_payer_keypair -> Public_key . compress fee_payer_keypair . public_key ) in let fee_payer_account_ids = Array . map fee_payer_pks ~ f ( : fun fee_payer_pk -> Account_id . create fee_payer_pk Token_id . default ) in let ( initial_balance : Currency . Balance . t ) t = Currency . Balance . of_int 1_000_000_000_000_000 in let ( fee_payer_accounts : Account . t array ) array = if is_timed then let initial_minimum_balance = Currency . Balance . of_int 1_000_000_000_000_000 in let cliff_time = Mina_numbers . Global_slot . of_int 1_000 in let cliff_amount = Currency . Amount . zero in let vesting_period = Mina_numbers . Global_slot . of_int 10 in let vesting_increment = Currency . Amount . of_int 100_000_000_000 in Array . map fee_payer_account_ids ~ f ( : fun fee_payer_account_id -> Account . create_timed fee_payer_account_id initial_balance ~ initial_minimum_balance ~ cliff_time ~ cliff_amount ~ vesting_period ~ vesting_increment |> Or_error . ok_exn ) else Array . map fee_payer_account_ids ~ f ( : fun fee_payer_account_id -> Account . create fee_payer_account_id initial_balance ) in let ledger = Mina_ledger . Ledger . create ~ depth : 10 ( ) in Array . iter2_exn fee_payer_accounts fee_payer_account_ids ~ f ( : fun fee_payer_account fee_payer_account_id -> Mina_ledger . Ledger . get_or_create_account ledger fee_payer_account_id fee_payer_account |> Or_error . ok_exn |> fun _ -> ( ) ) ; let keys = List . init 1000 ~ f ( : fun _ -> Keypair . create ( ) ) in let keymap = List . map ( Array . to_list fee_payer_keypairs @ keys ) keys ~ f ( : fun { public_key ; private_key } -> ( Public_key . compress public_key , private_key ) private_key ) |> Public_key . Compressed . Map . of_alist_exn in ( ledger , fee_payer_keypairs , keymap ) keymap
let ` VK vk , ` Prover prover = Lazy . force U . trivial_zkapp
let generate_parties_and_apply_them_consecutively ( ) = let num_of_fee_payers = 5 in let trials = 6 in let ledger , fee_payer_keypairs , keymap = mk_ledgers_and_fee_payers ~ num_of_fee_payers ( ) in Test_util . with_randomness 123456789 ( fun ( ) -> let test i = 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 ; ( " accounts " , ` List ( List . map ( Mina_ledger . Ledger . accounts ledger |> Set . to_list ) to_list ~ f ( : fun account_id -> Mina_ledger . Ledger . location_of_account ledger account_id |> Option . value_exn |> Mina_ledger . Ledger . get ledger |> Option . value_exn |> Account . to_yojson ) ) ) ] " generated parties " ; U . check_parties_with_merges_exn ledger [ parties ] ) ) in for i = 0 to trials - 1 do test i done )
let generate_parties_and_apply_them_freshly ( ) = let num_of_fee_payers = 5 in let trials = 6 in Test_util . with_randomness 123456789 ( fun ( ) -> let test i = let ledger , fee_payer_keypairs , keymap = mk_ledgers_and_fee_payers ~ 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 ( ) -> U . check_parties_with_merges_exn ledger [ parties ] ) ) in for i = 0 to trials - 1 do test i done )
let mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure ~ expected_failure_status = Test_util . with_randomness 123456789 ( fun ( ) -> let test i = let ledger , fee_payer_keypairs , keymap = mk_ledgers_and_fee_payers ~ num_of_fee_payers ( ) in Quickcheck . test ~ trials : 1 ( Mina_generators . Parties_generators . gen_parties_from ~ failure ( : Some type_of_failure ) type_of_failure ~ 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 : expected_failure_status ledger [ parties ] ~ state_body : U . genesis_state_body ) ) in for i = 0 to trials - 1 do test i done )
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 ) )