text
stringlengths
0
601k
let of_yojson = function | ` String str -> Result . map_error ( of_base58_check str ) str ~ f ( : fun _ -> " Transaction_hash . of_yojson : Error decoding string from base58_check \ format " ) | _ -> Error " Transaction_hash . of_yojson : Expected a string "
let hash_signed_command = Fn . compose digest_string Signed_command . to_base58_check
let hash_command = Fn . compose digest_string User_command . to_base58_check
let hash_fee_transfer = Fn . compose digest_string Fee_transfer . Single . to_base58_check
let hash_coinbase = Fn . compose digest_string Coinbase . to_base58_check
module User_command_with_valid_signature = struct type hash = T . t [ @@ deriving sexp , compare , hash ] hash let hash_to_yojson = to_yojson let hash_of_yojson = of_yojson [ %% versioned module Stable = struct module V2 = struct type t = ( ( User_command . Valid . Stable . V2 . t [ t @ hash . ignore ] ignore ) ignore , ( T . Stable . V1 . t [ t @ to_yojson hash_to_yojson ] hash_to_yojson ) hash_to_yojson ) With_hash . Stable . V1 . t [ @@ deriving sexp , hash , to_yojson ] to_yojson let to_latest = Fn . id let compare ( x : t ) t ( y : t ) t = T . compare x . hash y . hash end end ] end let create ( c : User_command . Valid . t ) t : t = { data = c ; hash = hash_command ( User_command . forget_check c ) c } let data ( { data ; _ } : t ) t = data let command ( { data ; _ } : t ) t = User_command . forget_check data let hash ( { hash ; _ } : t ) t = hash let forget_check ( { data ; hash } : t ) t = { With_hash . data = User_command . forget_check data ; hash } include Comparable . Make ( Stable . Latest ) Latest let make data hash : t = { data ; hash } end
module User_command = struct type hash = T . t [ @@ deriving sexp , compare , hash ] hash let hash_to_yojson = to_yojson let hash_of_yojson = of_yojson [ %% versioned module Stable = struct module V2 = struct type t = ( ( User_command . Stable . V2 . t [ t @ hash . ignore ] ignore ) ignore , ( T . Stable . V1 . t [ t @ to_yojson hash_to_yojson ] hash_to_yojson ) hash_to_yojson ) With_hash . Stable . V1 . t [ @@ deriving sexp , hash , to_yojson ] to_yojson let to_latest = Fn . id let compare ( x : t ) t ( y : t ) t = T . compare x . hash y . hash end end ] end let create ( c : User_command . t ) t : t = { data = c ; hash = hash_command c } let data ( { data ; _ } : t ) t = data let command ( { data ; _ } : t ) t = data let hash ( { hash ; _ } : t ) t = hash let of_checked ( { data ; hash } : User_command_with_valid_signature . t ) t : t = { With_hash . data = User_command . forget_check data ; hash } include Comparable . Make ( Stable . Latest ) Latest end [ %% endif ] endif
module State = struct [ %% versioned module Stable = struct module V1 = struct type t = Pending | Included | Unknown [ @@ deriving equal , sexp , compare ] compare let to_latest = Fn . id end end ] end let to_string = function | Pending -> " PENDING " | Included -> " INCLUDED " | Unknown -> " UNKOWN " end
let get_status ~ frontier_broadcast_pipe ~ transaction_pool cmd = let open Or_error . Let_syntax in let % map check_cmd = Result . of_option ( User_command . check cmd ) cmd ~ error ( : Error . of_string " Invalid signature ) " |> Result . map ~ f ( : fun x -> Transaction_hash . User_command_with_valid_signature . create x ) in let resource_pool = Transaction_pool . resource_pool transaction_pool in match Broadcast_pipe . Reader . peek frontier_broadcast_pipe with | None -> State . Unknown | Some transition_frontier -> with_return ( fun { return } -> let best_tip_path = Transition_frontier . best_tip_path transition_frontier in let in_breadcrumb breadcrumb = breadcrumb |> Transition_frontier . Breadcrumb . validated_transition |> Mina_block . Validated . valid_commands |> List . exists ~ f ( : fun { data = cmd ' ; _ } -> User_command . equal cmd ( User_command . forget_check cmd ' ) cmd ' ) in if List . exists ~ f : in_breadcrumb best_tip_path then return State . Included ; if List . exists ~ f : in_breadcrumb ( Transition_frontier . all_breadcrumbs transition_frontier ) transition_frontier then return State . Pending ; if Transaction_pool . Resource_pool . member resource_pool check_cmd then return State . Pending ; State . Unknown ) ( module struct open Async open Mina_numbers let max_length = 10 let frontier_size = 1 let logger = Logger . null ( ) let time_controller = Block_time . Controller . basic ~ logger let precomputed_values = Lazy . force Precomputed_values . for_unit_tests let proof_level = precomputed_values . proof_level let constraint_constants = precomputed_values . constraint_constants module Genesis_ledger = ( val precomputed_values . genesis_ledger ) genesis_ledger let trust_system = Trust_system . null ( ) let pool_max_size = precomputed_values . genesis_constants . txpool_max_size let verifier = Async . Thread_safe . block_on_async_exn ( fun ( ) -> Verifier . create ~ logger ~ proof_level ~ constraint_constants ~ conf_dir : None ~ pids ( : Child_processes . Termination . create_pid_table ( ) ) ) let key_gen = let open Quickcheck . Generator in let open Quickcheck . Generator . Let_syntax in let keypairs = List . map ( Lazy . force Genesis_ledger . accounts ) accounts ~ f : fst in let % map random_key_opt = of_list keypairs in ( Genesis_ledger . largest_account_keypair_exn ( ) , Signature_lib . Keypair . of_private_key_exn ( Option . value_exn random_key_opt ) random_key_opt ) let gen_frontier = Transition_frontier . For_tests . gen ~ logger ~ precomputed_values ~ verifier ~ trust_system ~ max_length ~ size : frontier_size ( ) let gen_user_command = Signed_command . Gen . payment ~ sign_type ` : Real ~ max_amount : 100 ~ fee_range : 10 ~ key_gen ~ nonce ( : Account_nonce . of_int 1 ) 1 ( ) let create_pool ~ frontier_broadcast_pipe = let config = Transaction_pool . Resource_pool . make_config ~ trust_system ~ pool_max_size ~ verifier in let transaction_pool , _ , local_sink = Transaction_pool . create ~ config ~ constraint_constants : precomputed_values . constraint_constants ~ consensus_constants : precomputed_values . consensus_constants ~ time_controller ~ logger ~ frontier_broadcast_pipe ~ expiry_ns : ( Time_ns . Span . of_hr ( Float . of_int precomputed_values . genesis_constants . transaction_expiry_hr ) ) ~ log_gossip_heard : false ~ on_remote_push ( : Fn . const Deferred . unit ) unit in don ' t_wait_for @@ Linear_pipe . iter ( Transaction_pool . broadcasts transaction_pool ) transaction_pool ~ f ( : fun transactions -> [ % log trace ] trace " Transactions have been applied successfully and is propagated \ throughout the ' network ' " ~ metadata : [ ( " transactions " , Transaction_pool . Resource_pool . Diff . to_yojson transactions ) ] ; Deferred . unit ) ; let % map ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in ( transaction_pool , local_sink ) local_sink let % test_unit " If the transition frontier currently doesn ' t exist , the \ status of a sent transaction will be unknown " = Quickcheck . test ~ trials : 1 gen_user_command ~ f ( : fun user_command -> Backtrace . elide := false ; Async . Thread_safe . block_on_async_exn ( fun ( ) -> let frontier_broadcast_pipe , _ = Broadcast_pipe . create None in let % bind transaction_pool , local_diffs_writer = create_pool ~ frontier_broadcast_pipe in let % bind ( ) = Transaction_pool . Local_sink . push local_diffs_writer ( [ Signed_command user_command ] , Fn . const ( ) ) in let % map ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in [ % log info ] info " Checking status " ; [ % test_eq : State . t ] t ~ equal : State . equal State . Unknown ( Or_error . ok_exn @@ get_status ~ frontier_broadcast_pipe ~ transaction_pool ( Signed_command user_command ) user_command ) ) ) let % test_unit " A pending transaction is either in the transition frontier \ or transaction pool , but not in the best path of the \ transition frontier " = Quickcheck . test ~ trials : 1 ( Quickcheck . Generator . tuple2 gen_frontier gen_user_command ) gen_user_command ~ f ( : fun ( frontier , user_command ) user_command -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let frontier_broadcast_pipe , _ = Broadcast_pipe . create ( Some frontier ) frontier in let % bind transaction_pool , local_diffs_writer = create_pool ~ frontier_broadcast_pipe in let % bind ( ) = Transaction_pool . Local_sink . push local_diffs_writer ( [ Signed_command user_command ] , Fn . const ( ) ) in let % map ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in let status = Or_error . ok_exn @@ get_status ~ frontier_broadcast_pipe ~ transaction_pool ( Signed_command user_command ) user_command in [ % log info ] info " Computing status " ; [ % test_eq : State . t ] t ~ equal : State . equal State . Pending status ) ) let % test_unit " An unknown transaction does not appear in the transition \ frontier or transaction pool " = let user_commands_generator = let open Quickcheck . Generator in let open Let_syntax in let % bind head_user_command = gen_user_command in let % map tail_user_commands = Quickcheck . Generator . list_with_length 10 gen_user_command in Non_empty_list . init head_user_command tail_user_commands in Quickcheck . test ~ trials : 1 ( Quickcheck . Generator . tuple2 gen_frontier user_commands_generator ) user_commands_generator ~ f ( : fun ( frontier , user_commands ) user_commands -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let frontier_broadcast_pipe , _ = Broadcast_pipe . create ( Some frontier ) frontier in let % bind transaction_pool , local_diffs_writer = create_pool ~ frontier_broadcast_pipe in let unknown_user_command , pool_user_commands = Non_empty_list . uncons user_commands in let % bind ( ) = Transaction_pool . Local_sink . push local_diffs_writer ( List . map pool_user_commands ~ f ( : fun x -> User_command . Signed_command x ) , Fn . const ( ) ) in let % map ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in [ % log info ] info " Computing status " ; [ % test_eq : State . t ] t ~ equal : State . equal State . Unknown ( Or_error . ok_exn @@ get_status ~ frontier_broadcast_pipe ~ transaction_pool ( Signed_command unknown_user_command ) unknown_user_command ) ) ) end )
module type Transition_frontier_intf = sig type t type staged_ledger module Breadcrumb : sig type t val staged_ledger : t -> staged_ledger end type best_tip_diff = { new_commands : User_command . Valid . t With_status . t list ; removed_commands : User_command . Valid . t With_status . t list ; reorg_best_tip : bool } val best_tip : t -> Breadcrumb . t val best_tip_diff_pipe : t -> best_tip_diff Broadcast_pipe . Reader . t end
module Diff_versioned = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type t = User_command . Stable . V2 . t list [ @@ deriving sexp , yojson , hash ] hash let to_latest = Fn . id end end ] end type t = User_command . t list [ @@ deriving sexp , yojson ] yojson module Diff_error = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type t = | Insufficient_replace_fee | Verification_failed | Duplicate | Sender_account_does_not_exist | Invalid_nonce | Insufficient_funds | Insufficient_fee | Overflow | Bad_token | Unwanted_fee_token | Expired | Overloaded | Fee_payer_account_not_found [ @@ deriving sexp , yojson , compare ] compare let to_latest = Fn . id end end ] end type t = Stable . Latest . t = | Insufficient_replace_fee | Verification_failed | Duplicate | Sender_account_does_not_exist | Invalid_nonce | Insufficient_funds | Insufficient_fee | Overflow | Bad_token | Unwanted_fee_token | Expired | Overloaded | Fee_payer_account_not_found [ @@ deriving sexp , yojson ] yojson let to_string_name = function | Insufficient_replace_fee -> " insufficient_replace_fee " | Verification_failed -> " verification_failed " | Duplicate -> " duplicate " | Sender_account_does_not_exist -> " sender_account_does_not_exist " | Invalid_nonce -> " invalid_nonce " | Insufficient_funds -> " insufficient_funds " | Insufficient_fee -> " insufficient_fee " | Overflow -> " overflow " | Bad_token -> " bad_token " | Unwanted_fee_token -> " unwanted_fee_token " | Expired -> " expired " | Overloaded -> " overloaded " | Fee_payer_account_not_found -> " fee_payer_account_not_found " let to_string_hum = function | Insufficient_replace_fee -> " This transaction would have replaced an existing transaction in the \ pool , but the fee was too low " | Verification_failed -> " This transaction had an invalid proof / signature " | Duplicate -> " This transaction is a duplicate of one already in the pool " | Sender_account_does_not_exist -> " The fee - payer ' s account for this transaction could not be found in \ the ledger " | Invalid_nonce -> " This transaction had an invalid nonce " | Insufficient_funds -> " There are not enough funds in the fee - payer ' s account to execute \ this transaction " | Insufficient_fee -> " The fee for this transaction is too low " | Overflow -> " Executing this transaction would result in an integer overflow " | Bad_token -> " This transaction uses non - default tokens where they are not \ permitted " | Unwanted_fee_token -> " This transaction pays fees in a non - default token that this pool \ does not accept " | Expired -> " This transaction has expired " | Overloaded -> " The diff containing this transaction was too large " | Fee_payer_account_not_found -> " Fee payer account was not found in the best tip ledger " end module Rejected = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V3 = struct type t = ( User_command . Stable . V2 . t * Diff_error . Stable . V2 . t ) t list [ @@ deriving sexp , yojson , compare ] compare let to_latest = Fn . id end end ] end type t = Stable . Latest . t [ @@ deriving sexp , yojson , compare ] compare end type rejected = Rejected . t [ @@ deriving sexp , yojson , compare ] compare type verified = { accepted : ( ( Transaction_hash . User_command_with_valid_signature . t * Transaction_hash . User_command_with_valid_signature . t list ) list * Indexed_pool . Sender_local_state . t * Indexed_pool . Update . t ) list ; rejected : Rejected . t } [ @@ deriving sexp , to_yojson ] to_yojson let summary t = Printf . sprintf " Transaction diff of length % d " ( List . length t ) t let is_empty t = List . is_empty t end
type Structured_log_events . t += | Rejecting_command_for_reason of { command : User_command . t ; reason : Diff_versioned . Diff_error . t ; error_extra : ( string * Yojson . Safe . t ) t list } [ @@ deriving register_event { msg = " Rejecting command because : $ reason " } ]
module type S = sig open Intf type transition_frontier module Resource_pool : sig include Transaction_resource_pool_intf with type transition_frontier := transition_frontier module Diff : Transaction_pool_diff_intf with type resource_pool := t and type Diff_error . t = Diff_versioned . Diff_error . t and type Rejected . t = Diff_versioned . Rejected . t end include Network_pool_base_intf with type resource_pool := Resource_pool . t and type transition_frontier := transition_frontier and type resource_pool_diff := Diff_versioned . t and type resource_pool_diff_verified := Diff_versioned . verified and type config := Resource_pool . Config . t and type transition_frontier_diff := Resource_pool . transition_frontier_diff and type rejected_diff := Diff_versioned . rejected end
module Make0 ( Base_ledger : Intf . Base_ledger_intf ) Base_ledger_intf ( Staged_ledger : sig type t val ledger : t -> Base_ledger . t end ) end ( Transition_frontier : Transition_frontier_intf with type staged_ledger := Staged_ledger . t ) t = struct type verification_failure = | Command_failure of Diff_versioned . Diff_error . t | Invalid_failure of Verifier . invalid [ @@ deriving to_yojson ] to_yojson module Breadcrumb = Transition_frontier . Breadcrumb module Resource_pool = struct type transition_frontier_diff = Transition_frontier . best_tip_diff * Base_ledger . t let label = " transaction_pool " module Config = struct type t = { trust_system : ( Trust_system . t [ t @ sexp . opaque ] opaque ) opaque ; pool_max_size : int ; verifier : ( Verifier . t [ t @ sexp . opaque ] opaque ) opaque } [ @@ deriving sexp_of , make ] make end let make_config = Config . make module Batcher = Batcher . Transaction_pool module Lru_cache = struct let max_size = 2048 module T = struct type t = User_command . t list [ @@ deriving hash ] hash end module Q = Hash_queue . Make ( Int ) Int type t = unit Q . t let add t h = if not ( Q . mem t h ) h then ( if Q . length t >= max_size then ignore ( Q . dequeue_front t : ' a option ) option ; Q . enqueue_back_exn t h ( ) ; ` Already_mem false ) else ( ignore ( Q . lookup_and_move_to_back t h : unit option ) option ; ` Already_mem true ) end module Mutex = struct open Async type t = unit Mvar . Read_write . t let acquire ( t : t ) t = Mvar . take t let release ( t : t ) t = assert ( Mvar . is_empty t ) t ; don ' t_wait_for ( Mvar . put t ( ) ) let with_ t ~ f = let % bind ( ) = acquire t in let % map x = f ( ) in release t ; x let create ( ) = let t = Mvar . create ( ) in don ' t_wait_for ( Mvar . put t ( ) ) ; t end type t = { mutable pool : Indexed_pool . t ; sender_mutex : ( Mutex . t Account_id . Table . t [ t @ sexp . opaque ] opaque ) opaque ; recently_seen : ( Lru_cache . t [ t @ sexp . opaque ] opaque ) opaque ; locally_generated_uncommitted : ( Transaction_hash . User_command_with_valid_signature . t , Time . t * [ ` Batch of int ] ) Hashtbl . t ; locally_generated_committed : ( Transaction_hash . User_command_with_valid_signature . t , Time . t * [ ` Batch of int ] ) Hashtbl . t ; mutable current_batch : int ; mutable remaining_in_batch : int ; config : Config . t ; logger : ( Logger . t [ t @ sexp . opaque ] opaque ) opaque ; batcher : Batcher . t ; mutable best_tip_diff_relay : ( unit Deferred . t [ t @ sexp . opaque ] opaque ) opaque Option . t ; mutable best_tip_ledger : ( Base_ledger . t [ t @ sexp . opaque ] opaque ) opaque Option . t } [ @@ deriving sexp_of ] sexp_of let member t x = Indexed_pool . member t . pool ( Transaction_hash . User_command . of_checked x ) x let transactions ' ~ logger p = Sequence . unfold ~ init : p ~ f ( : fun pool -> match Indexed_pool . get_highest_fee pool with | Some cmd -> ( match Indexed_pool . handle_committed_txn pool cmd ~ fee_payer_balance : Currency . Amount . max_int ~ fee_payer_nonce : ( Transaction_hash . User_command_with_valid_signature . command cmd |> User_command . nonce_exn ) with | Ok ( t , _ ) _ -> Some ( cmd , t ) t | Error ( ` Queued_txns_by_sender ( error_str , queued_cmds ) queued_cmds ) queued_cmds -> [ % log error ] error " Error handling committed transaction $ cmd : $ error " ~ metadata : [ ( " cmd " , Transaction_hash . User_command_with_valid_signature . to_yojson cmd ) ; ( " error " , ` String error_str ) error_str ; ( " queue " , ` List ( List . map ( Sequence . to_list queued_cmds ) queued_cmds ~ f ( : fun c -> Transaction_hash . User_command_with_valid_signature . to_yojson c ) ) ) ] ; failwith error_str ) | None -> None ) let transactions ~ logger t = transactions ' ~ logger t . pool let all_from_account { pool ; _ } = Indexed_pool . all_from_account pool let get_all { pool ; _ } = Indexed_pool . get_all pool let find_by_hash { pool ; _ } hash = Indexed_pool . find_by_hash pool hash let get_best_tip_ledger frontier = Transition_frontier . best_tip frontier |> Breadcrumb . staged_ledger |> Staged_ledger . ledger let drop_until_below_max_size : pool_max_size : int -> Indexed_pool . t -> Indexed_pool . t * Transaction_hash . User_command_with_valid_signature . t Sequence . t = fun ~ pool_max_size pool -> let rec go pool ' dropped = if Indexed_pool . size pool ' > pool_max_size then ( let dropped ' , pool ' ' = Indexed_pool . remove_lowest_fee pool ' in assert ( not ( Sequence . is_empty dropped ' ) dropped ' ) dropped ' ; go pool ' ' @@ Sequence . append dropped dropped ' ) else ( pool ' , dropped ) dropped in go pool @@ Sequence . empty let has_sufficient_fee ~ pool_max_size pool cmd : bool = match Indexed_pool . min_fee pool with | None -> true | Some min_fee -> if Indexed_pool . size pool >= pool_max_size then Currency . Fee_rate ( . User_command . fee_per_wu cmd > min_fee ) min_fee else true let diff_error_of_indexed_pool_error : Indexed_pool . Command_error . t -> Diff_versioned . Diff_error . t = function | Invalid_nonce _ -> Invalid_nonce | Insufficient_funds _ -> Insufficient_funds | Insufficient_replace_fee _ -> Insufficient_replace_fee | Overflow -> Overflow | Bad_token -> Bad_token | Verification_failed -> Verification_failed | Unwanted_fee_token _ -> Unwanted_fee_token | Expired _ -> Expired let indexed_pool_error_metadata = function | Indexed_pool . Command_error . Invalid_nonce ( ` Between ( low , hi ) hi , nonce ) nonce -> let nonce_json = Account . Nonce . to_yojson in [ ( " between " , ` Assoc [ ( " low " , nonce_json low ) low ; ( " hi " , nonce_json hi ) hi ] ) ; ( " nonce " , nonce_json nonce ) nonce ] | Invalid_nonce ( ` Expected enonce , nonce ) nonce -> let nonce_json = Account . Nonce . to_yojson in [ ( " expected_nonce " , nonce_json enonce ) enonce ; ( " nonce " , nonce_json nonce ) nonce ] | Insufficient_funds ( ` Balance bal , amt ) amt -> let amt_json = Currency . Amount . to_yojson in [ ( " balance " , amt_json bal ) bal ; ( " amount " , amt_json amt ) amt ] | Insufficient_replace_fee ( ` Replace_fee rfee , fee ) fee -> let fee_json = Currency . Fee . to_yojson in [ ( " replace_fee " , fee_json rfee ) rfee ; ( " fee " , fee_json fee ) fee ] | Overflow -> [ ] | Bad_token -> [ ] | Verification_failed -> [ ] | Unwanted_fee_token fee_token -> [ ( " fee_token " , Token_id . to_yojson fee_token ) fee_token ] | Expired ( ` Valid_until valid_until , ` Global_slot_since_genesis global_slot_since_genesis ) -> [ ( " valid_until " , Mina_numbers . Global_slot . to_yojson valid_until ) valid_until ; ( " current_global_slot " , Mina_numbers . Global_slot . to_yojson global_slot_since_genesis ) ] | Expired ( ` Timestamp_predicate expiry_ns , ` Global_slot_since_genesis global_slot_since_genesis ) -> [ ( " expiry_ns " , ` String expiry_ns ) expiry_ns ; ( " current_global_slot " , Mina_numbers . Global_slot . to_yojson global_slot_since_genesis ) ] let indexed_pool_error_log_info e = ( Diff_versioned . Diff_error . to_string_name ( diff_error_of_indexed_pool_error e ) e , indexed_pool_error_metadata e ) let balance_of_account ~ global_slot ( account : Account . t ) t = match account . timing with | Untimed -> account . balance | Timed { initial_minimum_balance ; cliff_time ; cliff_amount ; vesting_period ; vesting_increment } -> Currency . Balance . sub_amount account . balance ( Currency . Balance . to_amount ( Account . min_balance_at_slot ~ global_slot ~ cliff_time ~ cliff_amount ~ vesting_period ~ vesting_increment ~ initial_minimum_balance ) ) |> Option . value ~ default : Currency . Balance . zero let handle_transition_frontier_diff ( ( { new_commands ; removed_commands ; reorg_best_tip = _ } : Transition_frontier . best_tip_diff ) , best_tip_ledger ) t = let global_slot = Indexed_pool . global_slot_since_genesis t . pool in t . best_tip_ledger <- Some best_tip_ledger ; let pool_max_size = t . config . pool_max_size in let log_indexed_pool_error error_str ~ metadata cmd = [ % log ' debug t . logger ] logger " Couldn ' t re - add locally generated command $ cmd , not valid against \ new ledger . Error : $ error " ~ metadata : ( [ ( " cmd " , Transaction_hash . User_command_with_valid_signature . to_yojson cmd ) ; ( " error " , ` String error_str ) error_str ] @ metadata ) in [ % log ' trace t . logger ] logger ~ metadata : [ ( " removed " , ` List ( List . map removed_commands ~ f ( : With_status . to_yojson User_command . Valid . to_yojson ) to_yojson ) ) ; ( " added " , ` List ( List . map new_commands ~ f ( : With_status . to_yojson User_command . Valid . to_yojson ) to_yojson ) ) ] " Diff : removed : $ removed added : $ added from best tip " ; let pool ' , dropped_backtrack = Sequence . fold ( removed_commands |> List . rev |> Sequence . of_list |> Sequence . map ~ f ( : fun unchecked -> unchecked . data |> Transaction_hash . User_command_with_valid_signature . create ) ) ~ init ( : t . pool , Sequence . empty ) empty ~ f ( : fun ( pool , dropped_so_far ) dropped_so_far cmd -> ( match Hashtbl . find_and_remove t . locally_generated_committed cmd with | None -> ( ) | Some time_added -> Hashtbl . add_exn t . locally_generated_uncommitted ~ key : cmd ~ data : time_added ) ; let pool ' , dropped_seq = match cmd |> Indexed_pool . add_from_backtrack pool with | Error e -> let error_str , metadata = indexed_pool_error_log_info e in log_indexed_pool_error error_str ~ metadata cmd ; ( pool , Sequence . empty ) empty | Ok indexed_pool -> drop_until_below_max_size ~ pool_max_size indexed_pool in ( pool ' , Sequence . append dropped_so_far dropped_seq ) dropped_seq ) in let locally_generated_dropped = Sequence . filter dropped_backtrack ~ f ( : Hashtbl . mem t . locally_generated_uncommitted ) locally_generated_uncommitted |> Sequence . to_list_rev in if not ( List . is_empty locally_generated_dropped ) locally_generated_dropped then [ % log ' debug t . logger ] logger " Dropped locally generated commands $ cmds during backtracking to \ maintain max size . Will attempt to re - add after forwardtracking . " ~ metadata : [ ( " cmds " , ` List ( List . map ~ f : Transaction_hash . User_command_with_valid_signature . to_yojson locally_generated_dropped ) ) ] ; let pool ' ' , dropped_commit_conflicts = List . fold new_commands ~ init ( : pool ' , Sequence . empty ) empty ~ f ( : fun ( p , dropped_so_far ) dropped_so_far cmd -> let balance account_id = match Base_ledger . location_of_account best_tip_ledger account_id with | None -> ( Currency . Amount . zero , Mina_base . Account . Nonce . zero ) zero | Some loc -> let acc = Option . value_exn ~ message " : public key has location but no account " ( Base_ledger . get best_tip_ledger loc ) loc in ( Currency . Balance . to_amount ( balance_of_account ~ global_slot acc ) acc , acc . nonce ) in let fee_payer = User_command ( . fee_payer ( forget_check cmd . data ) data ) data in let fee_payer_balance , fee_payer_nonce = balance fee_payer in let cmd ' = Transaction_hash . User_command_with_valid_signature . create cmd . data in ( match Hashtbl . find_and_remove t . locally_generated_uncommitted cmd ' with | None -> ( ) | Some time_added -> [ % log ' info t . logger ] logger " Locally generated command $ cmd committed in a block " ! ~ metadata : [ ( " cmd " , With_status . to_yojson User_command . Valid . to_yojson cmd ) ] ; Hashtbl . add_exn t . locally_generated_committed ~ key : cmd ' ~ data : time_added ) ; let p ' , dropped = match Indexed_pool . handle_committed_txn p cmd ' ~ fee_payer_balance ~ fee_payer_nonce with | Ok res -> res | Error ( ` Queued_txns_by_sender ( error_str , queued_cmds ) queued_cmds ) queued_cmds -> [ % log ' error t . logger ] logger " Error handling committed transaction $ cmd : $ error " ~ metadata : [ ( " cmd " , With_status . to_yojson User_command . Valid . to_yojson cmd ) ; ( " error " , ` String error_str ) error_str ; ( " queue " , ` List ( List . map ( Sequence . to_list queued_cmds ) queued_cmds ~ f ( : fun c -> Transaction_hash . User_command_with_valid_signature . to_yojson c ) ) ) ] ; failwith error_str in ( p ' , Sequence . append dropped_so_far dropped ) dropped ) in let commit_conflicts_locally_generated = Sequence . filter dropped_commit_conflicts ~ f ( : fun cmd -> Hashtbl . find_and_remove t . locally_generated_uncommitted cmd |> Option . is_some ) in if not @@ Sequence . is_empty commit_conflicts_locally_generated then [ % log ' info t . logger ] logger " Locally generated commands $ cmds dropped because they conflicted \ with a committed command . " ~ metadata : [ ( " cmds " , ` List ( Sequence . to_list ( Sequence . map commit_conflicts_locally_generated ~ f : Transaction_hash . User_command_with_valid_signature . to_yojson ) ) ) ] ; [ % log ' debug t . logger ] logger " ! Finished handling diff . Old pool size % i , new pool size % i . Dropped \ % i commands during backtracking to maintain max size . " ( Indexed_pool . size t . pool ) pool ( Indexed_pool . size pool ' ' ) pool ' ' ( Sequence . length dropped_backtrack ) dropped_backtrack ; Mina_metrics ( . Gauge . set Transaction_pool . pool_size ( Float . of_int ( Indexed_pool . size pool ' ' ) pool ' ' ) pool ' ' ) pool ' ' ; t . pool <- pool ' ' ; List . iter locally_generated_dropped ~ f ( : fun cmd -> let remove_cmd ( ) = assert ( Option . is_some @@ Hashtbl . find_and_remove t . locally_generated_uncommitted cmd ) in let log_and_remove ( ? metadata = [ ] ) error_str = log_indexed_pool_error error_str ~ metadata cmd ; remove_cmd ( ) in if not ( Hashtbl . mem t . locally_generated_committed cmd ) cmd then if not ( has_sufficient_fee t . pool ( Transaction_hash . User_command_with_valid_signature . command cmd ) ~ pool_max_size ) then ( [ % log ' info t . logger ] logger " Not re - adding locally generated command $ cmd to pool , \ insufficient fee " ~ metadata : [ ( " cmd " , Transaction_hash . User_command_with_valid_signature . to_yojson cmd ) ] ; remove_cmd ( ) ) else let unchecked = Transaction_hash . User_command_with_valid_signature . command cmd in match Option . bind ( Base_ledger . location_of_account best_tip_ledger ( User_command . fee_payer unchecked ) unchecked ) ~ f ( : Base_ledger . get best_tip_ledger ) best_tip_ledger with | Some acct -> ( match Indexed_pool . add_from_gossip_exn t . pool ( ` Checked cmd ) cmd acct . nonce ~ verify ( : fun _ -> assert false ) false ( balance_of_account ~ global_slot acct |> Currency . Balance . to_amount ) with | Error e -> let error_str , metadata = indexed_pool_error_log_info e in log_and_remove error_str ~ metadata : ( ( " user_command " , User_command . to_yojson unchecked ) unchecked :: metadata ) | Ok ( _ , pool ' ' ' , _ ) _ -> [ % log ' debug t . logger ] logger " re - added locally generated command $ cmd to \ transaction pool after reorg " ~ metadata : [ ( " cmd " , Transaction_hash . User_command_with_valid_signature . to_yojson cmd ) ] ; Mina_metrics ( . Gauge . set Transaction_pool . pool_size ( Float . of_int ( Indexed_pool . size pool ' ' ' ) pool ' ' ' ) pool ' ' ' ) pool ' ' ' ; t . pool <- pool ' ' ' ) | None -> log_and_remove " Fee_payer_account not found " ~ metadata : [ ( " user_command " , User_command . to_yojson unchecked ) unchecked ] ) ; let expired_commands , pool = Indexed_pool . remove_expired t . pool in Sequence . iter expired_commands ~ f ( : fun cmd -> [ % log ' debug t . logger ] logger " Dropping expired user command from the pool $ cmd " ~ metadata : [ ( " cmd " , Transaction_hash . User_command_with_valid_signature . to_yojson cmd ) ] ; ignore ( Hashtbl . find_and_remove t . locally_generated_uncommitted cmd : ( Time . t * [ ` Batch of int ] ) option ) ) ; Mina_metrics ( . Gauge . set Transaction_pool . pool_size ( Float . of_int ( Indexed_pool . size pool ) pool ) pool ) pool ; t . pool <- pool ; Deferred . unit let create ~ constraint_constants ~ consensus_constants ~ time_controller ~ expiry_ns ~ frontier_broadcast_pipe ~ config ~ logger ~ tf_diff_writer = let t = { pool = Indexed_pool . empty ~ constraint_constants ~ consensus_constants ~ time_controller ~ expiry_ns ; sender_mutex = Account_id . Table . create ( ) ; locally_generated_uncommitted = Hashtbl . create ( module Transaction_hash . User_command_with_valid_signature . Stable . Latest ) ; locally_generated_committed = Hashtbl . create ( module Transaction_hash . User_command_with_valid_signature . Stable . Latest ) ; current_batch = 0 ; remaining_in_batch = max_per_15_seconds ; config ; logger ; batcher = Batcher . create config . verifier ; best_tip_diff_relay = None ; recently_seen = Lru_cache . Q . create ( ) ; best_tip_ledger = None } in don ' t_wait_for ( Broadcast_pipe . Reader . iter frontier_broadcast_pipe ~ f ( : fun frontier_opt -> match frontier_opt with | None -> ( [ % log debug ] debug " no frontier " ; t . best_tip_ledger <- None ; match t . best_tip_diff_relay with | None -> Deferred . unit | Some hdl -> let is_finished = ref false in Deferred . any_unit [ ( let % map ( ) = hdl in t . best_tip_diff_relay <- None ; is_finished := true ) ; ( let % map ( ) = Async . after ( Time . Span . of_sec 5 ) . in if not ! is_finished then ( [ % log fatal ] fatal " Transition frontier closed without first \ closing best tip view pipe " ; assert false ) else ( ) ) ] ) | Some frontier -> [ % log debug ] debug " Got frontier " ! ; let validation_ledger = get_best_tip_ledger frontier in t . best_tip_ledger <- Some validation_ledger ; let global_slot = Indexed_pool . global_slot_since_genesis t . pool in let new_pool , dropped = Indexed_pool . revalidate t . pool ( fun sender -> match Base_ledger . location_of_account validation_ledger sender with | None -> ( Account . Nonce . zero , Currency . Amount . zero ) zero | Some loc -> let acc = Option . value_exn ~ message : " Somehow a public key has a location but no \ account " ( Base_ledger . get validation_ledger loc ) loc in ( acc . nonce , balance_of_account ~ global_slot acc |> Currency . Balance . to_amount ) ) in let dropped_locally_generated = Sequence . filter dropped ~ f ( : fun cmd -> let find_remove_bool tbl = Hashtbl . find_and_remove tbl cmd |> Option . is_some in let dropped_committed = find_remove_bool t . locally_generated_committed in let dropped_uncommitted = find_remove_bool t . locally_generated_uncommitted in assert ( not ( dropped_committed && dropped_uncommitted ) dropped_uncommitted ) dropped_uncommitted ; dropped_committed || dropped_uncommitted ) in if not ( Sequence . is_empty dropped_locally_generated ) dropped_locally_generated then [ % log info ] info " Dropped locally generated commands $ cmds from pool when \ transition frontier was recreated . " ~ metadata : [ ( " cmds " , ` List ( List . map ( Sequence . to_list dropped_locally_generated ) dropped_locally_generated ~ f : Transaction_hash . User_command_with_valid_signature . to_yojson ) ) ] ; [ % log debug ] debug " ! Re - validated transaction pool after restart : dropped % i \ of % i previously in pool " ( Sequence . length dropped ) dropped ( Indexed_pool . size t . pool ) pool ; Mina_metrics ( . Gauge . set Transaction_pool . pool_size ( Float . of_int ( Indexed_pool . size new_pool ) new_pool ) new_pool ) new_pool ; t . pool <- new_pool ; t . best_tip_diff_relay <- Some ( Broadcast_pipe . Reader . iter ( Transition_frontier . best_tip_diff_pipe frontier ) frontier ~ f ( : fun diff -> Strict_pipe . Writer . write tf_diff_writer ( diff , get_best_tip_ledger frontier ) frontier |> Deferred . don ' t_wait_for ; Deferred . unit ) ) ; Deferred . unit ) ) ; t type pool = t module Diff = struct type t = User_command . t list [ @@ deriving sexp , yojson ] yojson type _unused = unit constraint t = Diff_versioned . t module Diff_error = struct type t = Diff_versioned . Diff_error . t = | Insufficient_replace_fee | Verification_failed | Duplicate | Sender_account_does_not_exist | Invalid_nonce | Insufficient_funds | Insufficient_fee | Overflow | Bad_token | Unwanted_fee_token | Expired | Overloaded | Fee_payer_account_not_found [ @@ deriving sexp , yojson , compare ] compare let to_string_hum = Diff_versioned . Diff_error . to_string_hum end module Rejected = struct type t = ( User_command . t * Diff_error . t ) t list [ @@ deriving sexp , yojson , compare ] compare type _unused = unit constraint t = Diff_versioned . Rejected . t end type rejected = Rejected . t [ @@ deriving sexp , yojson , compare ] compare type verified = Diff_versioned . verified = { accepted : ( ( Transaction_hash . User_command_with_valid_signature . t * Transaction_hash . User_command_with_valid_signature . t list ) list * Indexed_pool . Sender_local_state . t * Indexed_pool . Update . t ) list ; rejected : Rejected . t } [ @@ deriving sexp , to_yojson ] to_yojson let reject_overloaded_diff ( diffs : verified ) verified : rejected = diffs . rejected @ List . concat_map diffs . accepted ~ f ( : fun ( cmds , _ , _ ) _ -> List . map cmds ~ f ( : fun ( c , _ ) _ -> ( Transaction_hash . User_command_with_valid_signature . command c , Diff_error . Overloaded ) ) ) let verified_accepted ( { accepted ; _ } : verified ) verified = List . concat_map accepted ~ f ( : fun ( cs , _ , _ ) _ -> List . map cs ~ f ( : fun ( c , _ ) _ -> Transaction_hash . User_command_with_valid_signature . command c ) ) let verified_rejected ( { rejected ; _ } : verified ) verified : rejected = rejected let empty = [ ] let size = List . length let score x = Int . max 1 ( List . length x ) x let max_per_15_seconds = max_per_15_seconds let summary t = Printf . sprintf " Transaction diff of length % d " ( List . length t ) t let is_empty t = List . is_empty t let log_and_punish ( ? punish = true ) true t d e = let sender = Envelope . Incoming . sender d in let trust_record = Trust_system . record_envelope_sender t . config . trust_system t . logger sender in let is_local = Envelope . Sender ( . equal Local sender ) sender in let metadata = [ ( " error " , Error_json . error_to_yojson e ) e ; ( " sender " , Envelope . Sender . to_yojson sender ) sender ] in [ % log ' error t . logger ] logger ~ metadata " Error verifying transaction pool diff from $ sender : $ error " ; if punish && not is_local then trust_record ( Trust_system . Actions . Sent_invalid_proof , Some ( " Error verifying transaction pool diff : $ error " , metadata ) metadata ) else Deferred . return ( ) let of_indexed_pool_error e = ( diff_error_of_indexed_pool_error e , indexed_pool_error_metadata e ) e let handle_command_error t ~ trust_record ~ is_sender_local tx ( e : Indexed_pool . Command_error . t ) t = let yojson_fail_reason = Fn . compose ( fun s -> ` String s ) s ( function | Indexed_pool . Command_error . Invalid_nonce _ -> " invalid nonce " | Insufficient_funds _ -> " insufficient funds " | Verification_failed -> " transaction had bad proof / signature or was malformed " | Insufficient_replace_fee _ -> " insufficient replace fee " | Overflow -> " overflow " | Bad_token -> " bad token " | Unwanted_fee_token _ -> " unwanted fee token " | Expired _ -> " expired " ) in let open Async in let % map ( ) = match e with | Insufficient_replace_fee ( ` Replace_fee rfee , fee ) fee -> let f_log = if is_sender_local then [ % log ' error t . logger ] logger else [ % log ' debug t . logger ] logger in f_log " rejecting $ cmd because of insufficient replace fee ( $ rfee > \ $ fee ) fee " ~ metadata : [ ( " cmd " , User_command . to_yojson tx ) tx ; ( " rfee " , Currency . Fee . to_yojson rfee ) rfee ; ( " fee " , Currency . Fee . to_yojson fee ) fee ] ; Deferred . unit | Unwanted_fee_token fee_token -> let f_log = if is_sender_local then [ % log ' error t . logger ] logger else [ % log ' debug t . logger ] logger in f_log " rejecting $ cmd because we don ' t accept fees in $ token " ~ metadata : [ ( " cmd " , User_command . to_yojson tx ) tx ; ( " token " , Token_id . to_yojson fee_token ) fee_token ] ; Deferred . unit | Verification_failed -> trust_record ( Trust_system . Actions . Sent_useless_gossip , Some ( " rejecting command because had invalid signature or was \ malformed " , [ ] ) ) | err -> let diff_err , error_extra = of_indexed_pool_error err in if is_sender_local then [ % str_log ' error t . logger ] logger ( Rejecting_command_for_reason { command = tx ; reason = diff_err ; error_extra } ) ; trust_record ( Trust_system . Actions . Sent_useless_gossip , Some ( " rejecting $ cmd because of $ reason . ( $ error_extra ) error_extra " , [ ( " cmd " , User_command . to_yojson tx ) tx ; ( " reason " , yojson_fail_reason err ) err ; ( " error_extra " , ` Assoc error_extra ) error_extra ] ) ) in if Indexed_pool . Command_error . grounds_for_diff_rejection e then ` Reject else ` Ignore let verify ' ~ allow_failures_for_tests ( t : pool ) pool ( diffs : t Envelope . Incoming . t ) t : verified Envelope . Incoming . t Deferred . Or_error . t = let open Deferred . Let_syntax in let trust_record = Trust_system . record_envelope_sender t . config . trust_system t . logger diffs . sender in let config = Indexed_pool . config t . pool in let global_slot = Indexed_pool . global_slot_since_genesis t . pool in let pool_max_size = t . config . pool_max_size in let sender = Envelope . Incoming . sender diffs in let is_sender_local = Envelope . Sender ( . equal sender Local ) Local in let diffs_are_valid ( ) = List . for_all ( Envelope . Incoming . data diffs ) diffs ~ f ( : fun cmd -> let is_valid = not ( User_command . has_insufficient_fee cmd ) cmd in if not is_valid then [ % log ' debug t . logger ] logger " Filtering user command with insufficient fee from \ transaction - pool diff $ cmd from $ sender " ~ metadata : [ ( " cmd " , User_command . to_yojson cmd ) cmd ; ( " sender " , Envelope ( . Sender . to_yojson ( Incoming . sender diffs ) diffs ) diffs ) ] ; is_valid ) in let h = Lru_cache . T . hash diffs . data in let ( ` Already_mem already_mem ) already_mem = Lru_cache . add t . recently_seen h in if ( not allow_failures_for_tests ) allow_failures_for_tests && already_mem && not is_sender_local then Deferred . Or_error . error_string " already saw this " else if ( not allow_failures_for_tests ) allow_failures_for_tests && not ( diffs_are_valid ( ) ) then Deferred . Or_error . error_string " at least one user command had an insufficient fee " else match t . best_tip_ledger with | None -> Deferred . Or_error . error_string " We don ' t have a transition frontier at the moment , so we ' re \ unable to verify any transactions . " | Some ledger -> ( let data ' = List . map diffs . data ~ f : ( User_command . to_verifiable ~ ledger ~ get : Base_ledger . get ~ location_of_account : Base_ledger . location_of_account ) in let by_sender = List . fold data ' ~ init : Account_id . Map . empty ~ f ( : fun by_sender c -> Map . add_multi by_sender ~ key ( : User_command . Verifiable . fee_payer c ) c ~ data : c ) |> Map . map ~ f : List . rev |> Map . to_alist in let failures = ref ( Ok ( ) ) in let add_failure err = match ! failures with | Ok ( ) -> failures := Error [ err ] | Error errs -> failures := Error ( err :: errs ) errs in let % map diffs ' = Deferred . List . map by_sender ~ how ` : Parallel ~ f ( : fun ( signer , cs ) cs -> let account = Option . bind ( Base_ledger . location_of_account ledger signer ) signer ~ f ( : Base_ledger . get ledger ) ledger in match account with | None -> let % map _ = trust_record ( Trust_system . Actions . Sent_useless_gossip , Some ( " account does not exist for id : $ account_id " , [ ( " account_id " , Account_id . to_yojson signer ) signer ] ) ) in add_failure ( Command_failure Diff_error . Fee_payer_account_not_found ) ; Error ` Invalid_command | Some account -> let signer_lock = Hashtbl . find_or_add t . sender_mutex signer ~ default : Mutex . create in let % bind ( ) = Mutex . acquire signer_lock in let rec go sender_local_state u_acc acc ( rejected : Rejected . t ) t = function | [ ] -> return ( Ok ( List . rev acc , List . rev rejected , sender_local_state , u_acc ) ) | c :: cs -> let uc = User_command . of_verifiable c in if Result . is_error ! failures then ( Mutex . release signer_lock ; return ( Error ` Other_command_failed ) Other_command_failed ) else let tx ' = Transaction_hash . User_command . create uc in if Indexed_pool . member t . pool tx ' then if is_sender_local then ( [ % log ' info t . logger ] logger " Received local $ cmd already present in \ the pool " ~ metadata : [ ( " cmd " , User_command . to_yojson uc ) uc ] ; match Indexed_pool . find_by_hash t . pool ( Transaction_hash . User_command . hash tx ' ) tx ' with | Some validated_uc -> go sender_local_state Indexed_pool . Update . empty ( ( validated_uc , [ ] ) :: acc ) acc rejected cs | None -> go sender_local_state u_acc acc ( ( uc , Diff_versioned . Diff_error . Duplicate ) :: rejected ) cs ) else let % bind _ = trust_record ( Trust_system . Actions . Sent_old_gossip , None ) in go sender_local_state u_acc acc ( ( uc , Diff_versioned . Diff_error . Duplicate ) Duplicate :: rejected ) cs else if has_sufficient_fee t . pool ~ pool_max_size uc then match % bind Indexed_pool . add_from_gossip_exn_async ~ config ~ sender_local_state ~ verify ( : fun c -> match % map Batcher . verify t . batcher { diffs with data = [ c ] } with | Error e -> [ % log ' error t . logger ] logger " Transaction verification error : \ $ error " ~ metadata : [ ( " error " , ` String ( Error . to_string_hum e ) e ) ] ; None | Ok ( Error invalid ) invalid -> [ % log ' error t . logger ] logger " Batch verification failed when \ adding from gossip " ~ metadata : [ ( " error " , ` String ( Verifier . invalid_to_string invalid ) ) ] ; add_failure ( Invalid_failure invalid ) invalid ; None | Ok ( Ok [ c ] ) -> Some c | Ok ( Ok _ ) _ -> assert false ) ( ` Unchecked ( Transaction_hash . User_command . create uc , c ) ) account . nonce ( Currency . Balance . to_amount ( balance_of_account ~ global_slot account ) ) with | Error e -> ( match % bind handle_command_error t ~ trust_record ~ is_sender_local uc e with | ` Reject -> add_failure ( Command_failure ( diff_error_of_indexed_pool_error e ) ) ; Mutex . release signer_lock ; return ( Error ` Invalid_command ) Invalid_command | ` Ignore -> go sender_local_state u_acc acc ( ( uc , diff_error_of_indexed_pool_error e ) :: rejected ) cs ) | Ok ( res , sender_local_state , u ) u -> let % bind _ = trust_record ( Trust_system . Actions . Sent_useful_gossip , Some ( " $ cmd " , [ ( " cmd " , User_command . to_yojson uc ) ] ) ) in go sender_local_state ( Indexed_pool . Update . merge u_acc u ) u ( res :: acc ) acc rejected cs else let % bind ( ) = trust_record ( Trust_system . Actions . Sent_useless_gossip , Some ( sprintf " rejecting command $ cmd due to \ insufficient fee . " , [ ( " cmd " , User_command . to_yojson uc ) uc ] ) ) in go sender_local_state u_acc acc ( ( uc , Insufficient_fee ) Insufficient_fee :: rejected ) rejected cs in go ( Indexed_pool . get_sender_local_state t . pool signer ) signer Indexed_pool . Update . empty [ ] [ ] cs ) in match ! failures with | Error errs when not allow_failures_for_tests -> let errs_string = List . map errs ~ f ( : fun err -> match err with | Command_failure cmd_err -> Yojson . Safe . to_string ( Diff_error . to_yojson cmd_err ) cmd_err | Invalid_failure invalid -> Verifier . invalid_to_string invalid ) |> String . concat ~ sep " , : " in Or_error . errorf " Diff failed with verification failure ( failures ) failures : % s " errs_string | Error _ | Ok ( ) -> let data = List . filter_map diffs ' ~ f ( : function | Error ( ` Invalid_command | ` Other_command_failed ) Other_command_failed -> assert false | Error ` Account_not_found -> None | Ok t -> Some t ) in let data : verified = { accepted = List . map data ~ f ( : fun ( cs , _rej , local_state , u ) u -> ( cs , local_state , u ) u ) ; rejected = List . concat_map data ~ f ( : fun ( _ , rej , _ , _ ) _ -> rej ) rej } in Ok { diffs with data } ) let verify ( t : pool ) pool ( diffs : t Envelope . Incoming . t ) t : verified Envelope . Incoming . t Deferred . Or_error . t = verify ' ~ allow_failures_for_tests : false t diffs let register_locally_generated t txn = Hashtbl . update t . locally_generated_uncommitted txn ~ f ( : function | Some ( _ , ` Batch batch_num ) batch_num -> ( Time . now ( ) , ` Batch batch_num ) batch_num | None -> let batch_num = if t . remaining_in_batch > 0 then ( t . remaining_in_batch <- t . remaining_in_batch - 1 ; t . current_batch ) else ( t . remaining_in_batch <- max_per_15_seconds - 1 ; t . current_batch <- t . current_batch + 1 ; t . current_batch ) in ( Time . now ( ) , ` Batch batch_num ) batch_num ) let apply t ( env : verified Envelope . Incoming . t ) t = let module Cs = struct type t = Transaction_hash . User_command_with_valid_signature . t list [ @@ deriving to_yojson ] to_yojson end in let sender = Envelope . Incoming . sender env in let is_sender_local = Envelope . Sender ( . equal sender Local ) Local in let pool_max_size = t . config . pool_max_size in let check_dropped dropped = let locally_generated_dropped = Sequence . filter dropped ~ f ( : fun tx_dropped -> Hashtbl . find_and_remove t . locally_generated_uncommitted tx_dropped |> Option . is_some ) |> Sequence . to_list in if not ( List . is_empty locally_generated_dropped ) locally_generated_dropped then [ % log ' info t . logger ] logger " Dropped locally generated commands $ cmds from transaction pool \ due to replacement or max size " ~ metadata : [ ( " cmds " , ` List ( List . map ~ f : Transaction_hash . User_command_with_valid_signature . to_yojson locally_generated_dropped ) ) ] in let pool , add_results = let open Indexed_pool in List . fold_map ~ init : t . pool env . data . accepted ~ f ( : fun acc ( cs , local_state , u ) u -> let sender = Sender_local_state . sender local_state in Option . iter ( Hashtbl . find t . sender_mutex sender ) sender ~ f : Mutex . release ; if Sender_local_state . is_remove local_state then Hashtbl . remove t . sender_mutex sender ; ( set_sender_local_state acc local_state |> Update . apply u , cs ) cs ) in let add_results = List . concat add_results in let pool , dropped_for_size = drop_until_below_max_size pool ~ pool_max_size in if not ( Sequence . is_empty dropped_for_size ) dropped_for_size then [ % log ' debug t . logger ] logger " dropped commands to maintain max size : $ cmds " ~ metadata : [ ( " cmds " , Cs . to_yojson ( Sequence . to_list dropped_for_size ) dropped_for_size ) dropped_for_size ] ; check_dropped dropped_for_size ; t . pool <- pool ; Mina_metrics ( . Gauge . set Transaction_pool . pool_size ( Float . of_int ( Indexed_pool . size pool ) pool ) pool ; Counter . inc_one Transaction_pool . transactions_added_to_pool ) transactions_added_to_pool ; let trust_record = Trust_system . record_envelope_sender t . config . trust_system t . logger sender in let rec go txs = let open Interruptible . Deferred_let_syntax in match txs with | [ ] -> Interruptible . Or_error . return ( ) | ( verified , dropped ) dropped :: txs -> let tx = Transaction_hash . User_command_with_valid_signature . command verified in let tx ' = Transaction_hash . User_command . of_checked verified in if Indexed_pool . member t . pool tx ' then if is_sender_local then ( [ % log ' info t . logger ] logger " Rebroadcasting $ cmd already present in the pool " ~ metadata [ : ( " cmd " , User_command . to_yojson tx ) tx ] ; register_locally_generated t verified ; go txs ) else let % bind _ = trust_record ( Trust_system . Actions . Sent_old_gossip , None ) None in go txs else ( if is_sender_local then register_locally_generated t verified ; if not ( List . is_empty dropped ) dropped then [ % log ' debug t . logger ] logger " dropped commands due to transaction replacement : $ dropped " ~ metadata [ : ( " dropped " , Cs . to_yojson dropped ) dropped ] ; check_dropped ( Sequence . of_list dropped ) dropped ; go txs ) in match t . best_tip_ledger with | None -> Deferred . Or_error . error_string " Got transaction pool diff when transition frontier is \ unavailable , ignoring . " | Some ledger -> ( match % map Interruptible . force @@ let open Interruptible . Let_syntax in let signal = Deferred . map ( Base_ledger . detached_signal ledger ) ledger ~ f ( : fun ( ) -> Error . createf " Ledger was detached " |> Error . tag ~ tag " : Transaction_pool . apply " ) in let % bind ( ) = Interruptible . lift Deferred . unit signal in go add_results with | Ok res -> res | Error err -> Error err ) let unsafe_apply ( t : pool ) pool ( diff : verified Envelope . Incoming . t ) t : ( t * rejected , _ ) _ Deferred . Result . t = match % map apply t diff with | Ok ( ) -> let accepted = verified_accepted diff . data in let rejected = verified_rejected diff . data in ( if not ( List . is_empty accepted ) accepted then Mina_metrics ( . Gauge . set Transaction_pool . useful_transactions_received_time_sec ( let x = Time ( . now ( ) |> to_span_since_epoch |> Span . to_sec ) to_sec in x . - Mina_metrics . time_offset_sec ) ) ) ; Ok ( accepted , rejected ) rejected | Error e -> Error ( ` Other e ) e type Structured_log_events . t += | Transactions_received of { txns : t ; sender : Envelope . Sender . t } [ @@ deriving register_event { msg = " Received transaction - pool diff $ txns from $ sender " } ] let update_metrics envelope valid_cb gossip_heard_logger_option = Mina_metrics ( . Counter . inc_one Network . gossip_messages_received ) gossip_messages_received ; Mina_metrics ( . Gauge . inc_one Network . transaction_pool_diff_received ) transaction_pool_diff_received ; let diff = Envelope . Incoming . data envelope in Option . iter gossip_heard_logger_option ~ f ( : fun logger -> [ % str_log debug ] debug ( Transactions_received { txns = diff ; sender = Envelope . Incoming . sender envelope } ) ) ; Mina_net2 . Validation_callback . set_message_type valid_cb ` Transaction ; Mina_metrics ( . Counter . inc_one Network . Transaction . received ) received end let get_rebroadcastable ( t : t ) t ~ has_timed_out = let metadata ~ key ~ time = [ ( " cmd " , Transaction_hash . User_command_with_valid_signature . to_yojson key ) ; ( " time " , ` String ( Time . to_string_abs ~ zone : Time . Zone . utc time ) time ) time ] in let added_str = " it was added at $ time and its rebroadcast period is now expired . " in let logger = t . logger in Hashtbl . filteri_inplace t . locally_generated_uncommitted ~ f ( : fun ~ key ~ data ( : time , ` Batch _ ) _ -> match has_timed_out time with | ` Timed_out -> [ % log info ] info " No longer rebroadcasting uncommitted command $ cmd , % s " added_str ~ metadata ( : metadata ~ key ~ time ) time ; false | ` Ok -> true ) ; Hashtbl . filteri_inplace t . locally_generated_committed ~ f ( : fun ~ key ~ data ( : time , ` Batch _ ) _ -> match has_timed_out time with | ` Timed_out -> [ % log debug ] debug " Removing committed locally generated command $ cmd from \ possible rebroadcast pool , % s " added_str ~ metadata ( : metadata ~ key ~ time ) time ; false | ` Ok -> true ) ; let rebroadcastable_txs = Hashtbl . to_alist t . locally_generated_uncommitted |> List . sort ~ compare ( : fun ( txn1 , ( _ , ` Batch batch1 ) batch1 ) batch1 ( txn2 , ( _ , ` Batch batch2 ) batch2 ) batch2 -> let cmp = compare batch1 batch2 in let get_hash = Transaction_hash . User_command_with_valid_signature . hash in let get_nonce txn = Transaction_hash . User_command_with_valid_signature . command txn |> User_command . nonce_exn in if cmp <> 0 then cmp else let cmp = Mina_numbers . Account_nonce . compare ( get_nonce txn1 ) txn1 ( get_nonce txn2 ) txn2 in if cmp <> 0 then cmp else Transaction_hash . compare ( get_hash txn1 ) txn1 ( get_hash txn2 ) txn2 ) |> List . group ~ break ( : fun ( _ , ( _ , ` Batch batch1 ) batch1 ) batch1 ( _ , ( _ , ` Batch batch2 ) batch2 ) batch2 -> batch1 <> batch2 ) |> List . map ~ f : ( List . map ~ f ( : fun ( txn , _ ) _ -> Transaction_hash . User_command_with_valid_signature . command txn ) ) in rebroadcastable_txs end include Network_pool_base . Make ( Transition_frontier ) Transition_frontier ( Resource_pool ) Resource_pool end
module Make ( Staged_ledger : sig type t val ledger : t -> Mina_ledger . Ledger . t end ) end with type staged_ledger := Staged_ledger . t ) t : S with type transition_frontier := Transition_frontier . t = Make0 ( Mina_ledger . Ledger ) Ledger ( Staged_ledger ) Staged_ledger ( Transition_frontier ) Transition_frontier include Make ( Staged_ledger ) Staged_ledger ( struct include Transition_frontier type best_tip_diff = Extensions . Best_tip_diff . view = { new_commands : User_command . Valid . t With_status . t list ; removed_commands : User_command . Valid . t With_status . t list ; reorg_best_tip : bool } let best_tip_diff_pipe t = Extensions ( . get_view_pipe ( extensions t ) t Best_tip_diff ) Best_tip_diff end ) end ( module struct module Mock_base_ledger = Mocks . Base_ledger module Mock_staged_ledger = Mocks . Staged_ledger let num_test_keys = 10 let test_keys = Array . init num_test_keys ~ f ( : fun _ -> Signature_lib . Keypair . create ( ) ) let num_extra_keys = 30 let extra_keys = Array . init num_extra_keys ~ f ( : fun _ -> Signature_lib . Keypair . create ( ) ) let precomputed_values = Lazy . force Precomputed_values . for_unit_tests let constraint_constants = precomputed_values . constraint_constants let consensus_constants = precomputed_values . consensus_constants let proof_level = precomputed_values . proof_level let logger = Logger . null ( ) let time_controller = Block_time . Controller . basic ~ logger let expiry_ns = Time_ns . Span . of_hr ( Float . of_int precomputed_values . genesis_constants . transaction_expiry_hr ) transaction_expiry_hr let verifier = Async . Thread_safe . block_on_async_exn ( fun ( ) -> Verifier . create ~ logger ~ proof_level ~ constraint_constants ~ conf_dir : None ~ pids ( : Child_processes . Termination . create_pid_table ( ) ) ) module Mock_transition_frontier = struct module Breadcrumb = struct type t = Mock_staged_ledger . t let staged_ledger = Fn . id end type best_tip_diff = { new_commands : User_command . Valid . t With_status . t list ; removed_commands : User_command . Valid . t With_status . t list ; reorg_best_tip : bool } type t = best_tip_diff Broadcast_pipe . Reader . t * Breadcrumb . t ref let create : unit -> t * best_tip_diff Broadcast_pipe . Writer . t = fun ( ) -> let pipe_r , pipe_w = Broadcast_pipe . create { new_commands = [ ] ; removed_commands = [ ] ; reorg_best_tip = false } in let accounts = List . map ( Array . to_list test_keys ) test_keys ~ f ( : fun kp -> let compressed = Public_key . compress kp . public_key in let account_id = Account_id . create compressed Token_id . default in ( account_id , Account . create account_id @@ Currency . Balance . of_int 1_000_000_000_000 ) ) in let ledger = Account_id . Table . of_alist_exn accounts in ( ( pipe_r , ref ledger ) ledger , pipe_w ) pipe_w let best_tip ( _ , best_tip_ref ) best_tip_ref = ! best_tip_ref let best_tip_diff_pipe ( pipe , _ ) _ = pipe end module Test = Make0 ( Mock_base_ledger ) Mock_base_ledger ( Mock_staged_ledger ) Mock_staged_ledger ( Mock_transition_frontier ) Mock_transition_frontier let pool_max_size = 25 let ( ) = Core . Backtrace . elide := false ; Async . Scheduler . set_record_backtraces true let assert_locally_generated ( pool : Test . Resource_pool . t ) t = ignore ( Hashtbl . merge pool . locally_generated_committed pool . locally_generated_uncommitted ~ f ( : fun ~ key -> function | ` Both ( ( committed , _ ) _ , ( uncommitted , _ ) _ ) _ -> failwithf " ! Command \ { % sexp : Transaction_hash . User_command_with_valid_signature . t } t \ in both locally generated committed and uncommitted with \ times % s and % s " key ( Time . to_string committed ) committed ( Time . to_string uncommitted ) uncommitted ( ) | ` Left cmd -> Some cmd | ` Right cmd -> assert ( Indexed_pool . member pool . pool ( Transaction_hash . User_command . of_checked key ) key ) ; Some cmd ) : ( Transaction_hash . User_command_with_valid_signature . t , Time . t * [ ` Batch of int ] ) Hashtbl . t ) let assert_fee_wu_ordering ( pool : Test . Resource_pool . t ) t = let txns = Test . Resource_pool . transactions pool ~ logger |> Sequence . to_list in let compare txn1 txn2 = let open Transaction_hash . User_command_with_valid_signature in let cmd1 = command txn1 in let cmd2 = command txn2 in if Account_id . equal ( User_command . fee_payer cmd1 ) cmd1 ( User_command . fee_payer cmd2 ) cmd2 then Account . Nonce . compare ( User_command . nonce_exn cmd1 ) cmd1 ( User_command . nonce_exn cmd2 ) cmd2 else let get_fee_wu cmd = User_command . fee_per_wu cmd in Currency . Fee_rate . compare ( get_fee_wu cmd2 ) cmd2 ( get_fee_wu cmd1 ) cmd1 in assert ( List . is_sorted txns ~ compare ) compare let setup_test ? expiry ( ) = let tf , best_tip_diff_w = Mock_transition_frontier . create ( ) in let tf_pipe_r , _tf_pipe_w = Broadcast_pipe . create @@ Some tf in let trust_system = Trust_system . null ( ) in let config = Test . Resource_pool . make_config ~ trust_system ~ pool_max_size ~ verifier in let expiry_ns = match expiry with None -> expiry_ns | Some t -> t in let pool_ , _ , _ = Test . create ~ config ~ logger ~ constraint_constants ~ consensus_constants ~ time_controller ~ expiry_ns ~ frontier_broadcast_pipe : tf_pipe_r ~ log_gossip_heard : false ~ on_remote_push ( : Fn . const Deferred . unit ) unit in let pool = Test . resource_pool pool_ in let % map ( ) = Async . Scheduler . yield ( ) in ( ( fun txs -> Indexed_pool . For_tests . assert_invariants pool . pool ; assert_locally_generated pool ; assert_fee_wu_ordering pool ; [ % test_eq : User_command . t List . t ] t ( Test . Resource_pool . transactions ~ logger pool |> Sequence . map ~ f : Transaction_hash . User_command_with_valid_signature . command |> Sequence . to_list |> List . sort ~ compare : User_command . compare ) ( List . sort ~ compare : User_command . compare txs ) txs ) , pool , best_tip_diff_w , tf ) let independent_cmds : User_command . Valid . t list = let rec go n cmds = let open Quickcheck . Generator . Let_syntax in if n < Array . length test_keys then let % bind cmd = let sender = test_keys ( . n ) n in User_command . Valid . Gen . payment ~ sign_type ` : Real ~ key_gen : ( Quickcheck . Generator . tuple2 ( return sender ) sender ( Quickcheck_lib . of_array test_keys ) test_keys ) ~ max_amount : 100_000_000_000 ~ fee_range : 10_000_000_000 ( ) in go ( n + 1 ) 1 ( cmd :: cmds ) cmds else Quickcheck . Generator . return @@ List . rev cmds in Quickcheck . random_value ~ seed ( ` : Deterministic " constant ) " ( go 0 [ ] ) let independent_cmds ' : User_command . t list = List . map independent_cmds ~ f : User_command . forget_check let mk_parties_cmds ( pool : Test . Resource_pool . t ) t : User_command . Valid . t list = let best_tip_ledger = Option . value_exn pool . best_tip_ledger in let mk_ledger ( ) = let ledger = Mina_ledger . Ledger . create ~ depth : precomputed_values . constraint_constants . ledger_depth ( ) in Account_id . Table . iteri best_tip_ledger ~ f ( : fun ~ key : acct_id ~ data : acct -> match Mina_ledger . Ledger . get_or_create_account ledger acct_id acct with | Error err -> failwithf " mk_parties_cmds : error adding account for account id : % s , \ error : % s . " @ ( Account_id . to_yojson acct_id |> Yojson . Safe . to_string ) to_string ( Error . to_string_hum err ) err ( ) | Ok ( ` Existed , _ ) _ -> failwithf " mk_parties_cmds : account for account id already exists : % s . " @ ( Account_id . to_yojson acct_id |> Yojson . Safe . to_string ) to_string ( ) | Ok ( ` Added , _ ) _ -> ( ) ) ; ledger in let keymap = Array . fold ( Array . append test_keys extra_keys ) extra_keys ~ init : Public_key . Compressed . Map . empty ~ f ( : fun map { public_key ; private_key } -> let key = Public_key . compress public_key in Public_key . Compressed . Map . add_exn map ~ key ~ data : private_key ) in let ledger = mk_ledger ( ) in let rec go n cmds = let open Quickcheck . Generator . Let_syntax in if n < Array . length test_keys then let % bind cmd = let fee_payer_keypair = test_keys ( . n ) n in let % map ( parties : Parties . t ) t = Mina_generators . Parties_generators . gen_parties_from ~ keymap ~ fee_payer_keypair ~ ledger ( ) in User_command . Parties parties in go ( n + 1 ) 1 ( cmd :: cmds ) cmds else Quickcheck . Generator . return @@ List . rev cmds in let result = Quickcheck . random_value ~ seed ( ` : Deterministic " parties ) " ( go 0 [ ] ) in let ledger_accounts = Mina_ledger . Ledger . to_list ledger |> List . filter ~ f ( : fun acct -> Option . is_some acct . zkapp ) zkapp in List . iter ledger_accounts ~ f ( : fun account -> let account_id = Account_id . create account . public_key account . token_id in ignore ( Mock_base_ledger . add best_tip_ledger ~ account_id ~ account : [ ` Duplicate | ` Ok ] ) ) ; result let mk_parties_cmds ' ( pool : Test . Resource_pool . t ) t : User_command . t list = List . map ( mk_parties_cmds pool ) pool ~ f : User_command . forget_check type pool_apply = ( User_command . t list , [ ` Other of Error . t ] ) Result . t [ @@ deriving sexp , compare ] compare let canonicalize t = Result . map t ~ f ( : List . sort ~ compare : User_command . compare ) compare let compare_pool_apply ( t1 : pool_apply ) pool_apply ( t2 : pool_apply ) pool_apply = compare_pool_apply ( canonicalize t1 ) t1 ( canonicalize t2 ) t2 let accepted_commands = Result . map ~ f : fst let mk_with_status ( cmd : User_command . Valid . t ) t = { With_status . data = cmd ; status = Applied } let verify_and_apply ( pool : Test . Resource_pool . t ) t cs = let tm0 = Time . now ( ) in let % bind verified = Test . Resource_pool . Diff . verify ' ~ allow_failures_for_tests : true pool ( Envelope . Incoming . local cs ) cs >>| Or_error . ok_exn in let result = Test . Resource_pool . Diff . unsafe_apply pool verified in let tm1 = Time . now ( ) in [ % log ' info pool . logger ] logger " Time for verify_and_apply : % 0 . 04f sec " ( Time . diff tm1 tm0 |> Time . Span . to_sec ) to_sec ; result let mk_linear_case_test assert_pool_txs pool best_tip_diff_w cmds = assert_pool_txs [ ] ; let % bind apply_res = verify_and_apply pool cmds in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res ) apply_res ( Ok cmds ) cmds ; assert_pool_txs cmds ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = [ mk_with_status ( List . hd_exn independent_cmds ) independent_cmds ] ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in let % bind ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in assert_pool_txs ( List . tl_exn cmds ) cmds ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w { new_commands = List . map ~ f : mk_with_status ( List . take ( List . tl_exn independent_cmds ) independent_cmds 2 ) 2 ; removed_commands = [ ] ; reorg_best_tip = false } in let % bind ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in assert_pool_txs ( List . drop cmds 3 ) 3 ; Deferred . unit let % test_unit " transactions are removed in linear case ( user cmds ) cmds " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , _frontier = setup_test ( ) in mk_linear_case_test assert_pool_txs pool best_tip_diff_w independent_cmds ' ) let % test_unit " transactions are removed in linear case ( zkapps ) zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , _frontier = setup_test ( ) in mk_linear_case_test assert_pool_txs pool best_tip_diff_w ( mk_parties_cmds ' pool ) pool ) let map_set_multi map pairs = let rec go pairs = match pairs with | ( k , v ) v :: pairs ' -> let pk = Public_key . compress test_keys ( . k ) k . public_key in let key = Account_id . create pk Token_id . default in Account_id . Table . set map ~ key ~ data : v ; go pairs ' | [ ] -> ( ) in go pairs let mk_account ~ idx ~ balance ~ nonce = let public_key = Public_key . compress @@ test_keys ( . idx ) idx . public_key in ( idx , { Account . Poly . Stable . Latest . public_key ; token_id = Token_id . default ; token_permissions = Token_permissions . Not_owned { account_disabled = false } ; token_symbol = Account . Token_symbol . default ; balance = Currency . Balance . of_int balance ; nonce = Account . Nonce . of_int nonce ; receipt_chain_hash = Receipt . Chain_hash . empty ; delegate = Some public_key ; voting_for = Quickcheck . random_value ~ seed ( ` : Deterministic " constant ) " State_hash . gen ; timing = Account . Timing . Untimed ; permissions = Permissions . user_default ; zkapp = None ; zkapp_uri = " " } ) let mk_remove_and_add_test assert_pool_txs pool best_tip_diff_w best_tip_ref valid_cmds = let cmds ' = List . map valid_cmds ~ f : User_command . forget_check in assert_pool_txs [ ] ; let cmds_to_apply = List . hd_exn cmds ' :: List . drop cmds ' 2 in let % bind apply_res = verify_and_apply pool cmds_to_apply in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res ) apply_res ( Ok cmds_to_apply ) cmds_to_apply ; map_set_multi ! best_tip_ref [ mk_account ~ idx : 1 ~ balance : 1_000_000_000_000 ~ nonce : 1 ] ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status @@ List . take valid_cmds 1 ; removed_commands = List . map ~ f : mk_with_status @@ [ List . nth_exn valid_cmds 1 ] ; reorg_best_tip = true } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs ( List . tl_exn cmds ' ) cmds ' ; Deferred . unit let % test_unit " Transactions are removed and added back in fork changes \ ( user cmds ) cmds " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in mk_remove_and_add_test assert_pool_txs pool best_tip_diff_w best_tip_ref independent_cmds ) let % test_unit " Transactions are removed and added back in fork changes \ ( zkapps ) zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in mk_remove_and_add_test assert_pool_txs pool best_tip_diff_w best_tip_ref ( mk_parties_cmds pool ) pool ) let mk_invalid_test assert_pool_txs pool best_tip_diff_w best_tip_ref cmds ' = assert_pool_txs [ ] ; map_set_multi ! best_tip_ref [ mk_account ~ idx : 0 ~ balance : 0 ~ nonce : 0 ; mk_account ~ idx : 1 ~ balance : 1_000_000_000_000 ~ nonce : 1 ] ; let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = [ ] ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in let % bind apply_res = verify_and_apply pool cmds ' in [ % test_eq : pool_apply ] pool_apply ( Ok ( List . drop cmds ' 2 ) 2 ) 2 ( accepted_commands apply_res ) apply_res ; assert_pool_txs ( List . drop cmds ' 2 ) 2 ; Deferred . unit let % test_unit " invalid transactions are not accepted ( user cmds ) cmds " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in mk_invalid_test assert_pool_txs pool best_tip_diff_w best_tip_ref independent_cmds ' ) let % test_unit " invalid transactions are not accepted ( zkapps ) zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in mk_invalid_test assert_pool_txs pool best_tip_diff_w best_tip_ref ( mk_parties_cmds ' pool ) pool ) let mk_payment ' ? valid_until ~ sender_idx ~ receiver_idx ~ fee ~ nonce ~ amount ( ) = let get_pk idx = Public_key . compress test_keys ( . idx ) idx . public_key in Signed_command . sign test_keys ( . sender_idx ) sender_idx ( Signed_command_payload . create ~ fee ( : Currency . Fee . of_int fee ) fee ~ fee_payer_pk ( : get_pk sender_idx ) sender_idx ~ valid_until ~ nonce ( : Account . Nonce . of_int nonce ) nonce ~ memo ( : Signed_command_memo . create_by_digesting_string_exn " foo ) " ~ body : ( Signed_command_payload . Body . Payment { source_pk = get_pk sender_idx ; receiver_pk = get_pk receiver_idx ; amount = Currency . Amount . of_int amount } ) ) let mk_parties ? valid_period ? fee_payer_idx ~ sender_idx ~ receiver_idx ~ fee ~ nonce ~ amount ( ) = let sender_kp = test_keys ( . sender_idx ) sender_idx in let sender_nonce = Account . Nonce . of_int nonce in let sender = ( sender_kp , sender_nonce ) sender_nonce in let amount = Currency . Amount . of_int amount in let receiver_kp = test_keys ( . receiver_idx ) receiver_idx in let receiver = receiver_kp . public_key |> Signature_lib . Public_key . compress in let fee_payer = match fee_payer_idx with | None -> None | Some ( idx , nonce ) nonce -> let fee_payer_kp = test_keys ( . idx ) idx in let fee_payer_nonce = Account . Nonce . of_int nonce in Some ( fee_payer_kp , fee_payer_nonce ) fee_payer_nonce in let fee = Currency . Fee . of_int fee in let protocol_state_precondition = match valid_period with | None -> Zkapp_precondition . Protocol_state . accept | Some time -> Zkapp_precondition . Protocol_state . valid_until time in let test_spec : Transaction_snark . For_tests . Spec . t = { sender ; fee_payer ; fee ; receivers = [ ( receiver , amount ) amount ] ; amount ; zkapp_account_keypairs = [ ] ; memo = Signed_command_memo . create_from_string_exn " expiry tests " ; 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 = Some protocol_state_precondition ; account_precondition = None } in let parties = Transaction_snark . For_tests . multiple_transfers test_spec in User_command . Parties parties let mk_payment ? valid_until ~ sender_idx ~ receiver_idx ~ fee ~ nonce ~ amount ( ) = User_command . Signed_command ( mk_payment ' ? valid_until ~ sender_idx ~ fee ~ nonce ~ receiver_idx ~ amount ( ) ) let current_global_slot ( ) = let current_time = Block_time . now time_controller in Consensus . Data . Consensus_time ( . of_time_exn ~ constants : consensus_constants current_time |> to_global_slot ) to_global_slot let mk_now_invalid_test assert_pool_txs pool best_tip_diff_w best_tip_ref cmds = let cmds ' = List . map cmds ~ f : User_command . forget_check in assert_pool_txs [ ] ; map_set_multi ! best_tip_ref [ mk_account ~ idx : 0 ~ balance : 1_000_000_000_000 ~ nonce : 1 ] ; let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status @@ List . take cmds 2 ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs [ ] ; let cmd1 = let sender = test_keys ( . 0 ) 0 in Quickcheck . random_value ( User_command . Valid . Gen . payment ~ sign_type ` : Real ~ key_gen : Quickcheck . Generator ( . tuple2 ( return sender ) sender ( Quickcheck_lib . of_array test_keys ) test_keys ) test_keys ~ nonce ( : Account . Nonce . of_int 1 ) 1 ~ max_amount : 100_000_000_000 ~ fee_range : 10_000_000_000 ( ) ) in let % bind apply_res = verify_and_apply pool [ User_command . forget_check cmd1 ] in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res ) apply_res ( Ok [ User_command . forget_check cmd1 ] ) ; assert_pool_txs [ User_command . forget_check cmd1 ] ; let cmd2 = mk_payment ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 0 ~ receiver_idx : 5 ~ amount : 999_000_000_000 ( ) in map_set_multi ! best_tip_ref [ mk_account ~ idx : 0 ~ balance : 0 ~ nonce : 1 ] ; let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status @@ ( cmd2 :: List . drop cmds 2 ) 2 ; removed_commands = List . map ~ f : mk_with_status @@ List . take cmds 2 ; reorg_best_tip = true } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs [ List . nth_exn cmds ' 1 ] ; Deferred . unit let % test_unit " Now - invalid transactions are removed from the pool on fork \ changes ( user cmds ) cmds " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in mk_now_invalid_test assert_pool_txs pool best_tip_diff_w best_tip_ref independent_cmds ) let % test_unit " Now - invalid transactions are removed from the pool on fork \ changes ( zkapps ) zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in mk_now_invalid_test assert_pool_txs pool best_tip_diff_w best_tip_ref ( mk_parties_cmds pool ) pool ) let mk_expired_not_accepted_test assert_pool_txs pool ~ padding cmds = assert_pool_txs [ ] ; let curr_slot = current_global_slot ( ) in let slot_padding = Mina_numbers . Global_slot . of_int padding in let curr_slot_plus_padding = Mina_numbers . Global_slot . add curr_slot slot_padding in let valid_command = mk_payment ~ valid_until : curr_slot_plus_padding ~ sender_idx : 1 ~ fee : 1_000_000_000 ~ nonce : 1 ~ receiver_idx : 9 ~ amount : 1_000_000_000 ( ) in let expired_commands = [ mk_payment ~ valid_until : curr_slot ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 1 ~ receiver_idx : 9 ~ amount : 1_000_000_000 ( ) ; mk_payment ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 2 ~ receiver_idx : 9 ~ amount : 1_000_000_000 ( ) ] in let % bind ( ) = after ( Block_time . Span . to_time_span consensus_constants . block_window_duration_ms ) in let all_valid_commands = cmds @ [ valid_command ] in let % bind apply_res = verify_and_apply pool ( List . map ( all_valid_commands @ expired_commands ) expired_commands ~ f : User_command . forget_check ) in let cmds_wo_check = List . map all_valid_commands ~ f : User_command . forget_check in [ % test_eq : pool_apply ] pool_apply ( Ok cmds_wo_check ) cmds_wo_check ( accepted_commands apply_res ) apply_res ; assert_pool_txs cmds_wo_check ; Deferred . unit let % test_unit " expired transactions are not accepted ( user cmds ) cmds " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , _best_tip_diff_w , ( _ , _best_tip_ref ) _best_tip_ref = setup_test ( ) in mk_expired_not_accepted_test assert_pool_txs pool ~ padding : 10 independent_cmds ) let % test_unit " expired transactions are not accepted ( zkapps ) zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , _best_tip_diff_w , ( _ , _best_tip_ref ) _best_tip_ref = setup_test ( ) in mk_expired_not_accepted_test assert_pool_txs pool ~ padding : 25 ( mk_parties_cmds pool ) pool ) let % test_unit " Expired transactions that are already in the pool are \ removed from the pool when best tip changes ( user commands ) commands " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in assert_pool_txs [ ] ; let curr_slot = current_global_slot ( ) in let curr_slot_plus_three = Mina_numbers . Global_slot ( . add curr_slot ( of_int 3 ) 3 ) 3 in let curr_slot_plus_seven = Mina_numbers . Global_slot ( . add curr_slot ( of_int 7 ) 7 ) 7 in let few_now = List . take independent_cmds ( List . length independent_cmds / 2 ) 2 in let expires_later1 = mk_payment ~ valid_until : curr_slot_plus_three ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 1 ~ receiver_idx : 9 ~ amount : 10_000_000_000 ( ) in let expires_later2 = mk_payment ~ valid_until : curr_slot_plus_seven ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 2 ~ receiver_idx : 9 ~ amount : 10_000_000_000 ( ) in let valid_commands = few_now @ [ expires_later1 ; expires_later2 ] in let cmds_wo_check = List . map valid_commands ~ f : User_command . forget_check in let % bind apply_res = verify_and_apply pool cmds_wo_check in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res ) apply_res ( Ok cmds_wo_check ) cmds_wo_check ; assert_pool_txs cmds_wo_check ; map_set_multi ! best_tip_ref [ mk_account ~ idx : 0 ~ balance : 1_000_000_000_000_000 ~ nonce : 2 ] ; let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status [ List . nth_exn few_now 0 ; expires_later1 ] ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in let cmds_wo_check = List . map ~ f : User_command . forget_check ( expires_later2 :: List . drop few_now 1 ) 1 in let % bind ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in assert_pool_txs cmds_wo_check ; let expired_command = mk_payment ~ valid_until : curr_slot ~ sender_idx : 9 ~ fee : 1_000_000_000 ~ nonce : 0 ~ receiver_idx : 5 ~ amount : 1_000_000_000 ( ) in let unexpired_command = mk_payment ~ valid_until : curr_slot_plus_seven ~ sender_idx : 8 ~ fee : 1_000_000_000 ~ nonce : 0 ~ receiver_idx : 9 ~ amount : 1_000_000_000 ( ) in let valid_forever = List . nth_exn few_now 0 in let removed_commands = [ valid_forever ; expires_later1 ; expired_command ; unexpired_command ] |> List . map ~ f : mk_with_status in let n_block_times n = Int64 ( . Block_time . Span . to_ms consensus_constants . block_window_duration_ms * n ) n |> Block_time . Span . of_ms in let % bind ( ) = after ( Block_time . Span . to_time_span ( n_block_times 3L ) 3L ) 3L in let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = [ mk_with_status valid_forever ] ; removed_commands ; reorg_best_tip = true } : Mock_transition_frontier . best_tip_diff ) in let cmds_wo_check = List . map ~ f : User_command . forget_check ( expires_later1 :: expires_later2 :: unexpired_command :: List . drop few_now 1 ) in let % bind ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in assert_pool_txs cmds_wo_check ; let % bind ( ) = after ( Block_time . Span . to_time_span ( n_block_times 5L ) 5L ) 5L in let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = [ ] ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in let cmds_wo_check = List . map ~ f : User_command . forget_check ( List . drop few_now 1 ) 1 in let % bind ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in assert_pool_txs cmds_wo_check ; Deferred . unit ) let % test_unit " Expired transactions that are already in the pool are \ removed from the pool when best tip changes ( zkapps ) zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let eight_block_time = Int64 ( . Block_time . Span . to_ms consensus_constants . block_window_duration_ms * 8L ) 8L |> Int64 . to_int |> Option . value_exn |> Time_ns . Span . of_int_ms in let expiry = Time_ns . Span ( . eight_block_time + of_sec 1 ) . in let eight_block = Block_time . Span . of_time_span @@ Time_ns . Span . to_span_float_round_nearest eight_block_time in let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ~ expiry ( ) in assert_pool_txs [ ] ; let curr_time = Block_time . sub ( Block_time . of_time ( Time . now ( ) ) ) eight_block in let n_block_times n = Int64 ( . Block_time . Span . to_ms consensus_constants . block_window_duration_ms * n ) n |> Block_time . Span . of_ms in let three_slot = n_block_times 3L in let seven_slot = n_block_times 7L in let curr_time_plus_three = Block_time . add curr_time three_slot in let curr_time_plus_seven = Block_time . add curr_time seven_slot in let few_now = List . take independent_cmds ( List . length independent_cmds / 2 ) 2 in let expires_later1 = mk_parties ~ valid_period { : lower = curr_time ; upper = curr_time_plus_three } ~ fee_payer_idx ( : 0 , 1 ) 1 ~ sender_idx : 1 ~ receiver_idx : 9 ~ fee : 1_000_000_000 ~ amount : 10_000_000_000 ~ nonce : 1 ( ) in let expires_later2 = mk_parties ~ valid_period { : lower = curr_time ; upper = curr_time_plus_seven } ~ fee_payer_idx ( : 0 , 2 ) 2 ~ sender_idx : 1 ~ receiver_idx : 9 ~ fee : 1_000_000_000 ~ amount : 10_000_000_000 ~ nonce : 2 ( ) in let valid_commands = few_now @ [ expires_later1 ; expires_later2 ] in let cmds_wo_check = List . map valid_commands ~ f : User_command . forget_check in let % bind apply_res = verify_and_apply pool cmds_wo_check in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res ) apply_res ( Ok cmds_wo_check ) cmds_wo_check ; assert_pool_txs cmds_wo_check ; map_set_multi ! best_tip_ref [ mk_account ~ idx : 0 ~ balance : 1_000_000_000_000_000 ~ nonce : 2 ; mk_account ~ idx : 1 ~ balance : 1_000_000_000_000_000 ~ nonce : 2 ] ; let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status [ List . nth_exn few_now 0 ; expires_later1 ] ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in let cmds_wo_check = List . map ~ f : User_command . forget_check ( expires_later2 :: List . drop few_now 1 ) 1 in let % bind ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in assert_pool_txs cmds_wo_check ; let expired_zkapp = mk_parties ~ valid_period { : lower = curr_time ; upper = curr_time } ~ fee_payer_idx ( : 9 , 0 ) 0 ~ sender_idx : 1 ~ fee : 1_000_000_000 ~ nonce : 3 ~ receiver_idx : 5 ~ amount : 1_000_000_000 ( ) in let unexpired_zkapp = mk_parties ~ valid_period { : lower = curr_time ; upper = curr_time_plus_seven } ~ fee_payer_idx ( : 8 , 0 ) 0 ~ sender_idx : 1 ~ fee : 1_000_000_000 ~ nonce : 4 ~ receiver_idx : 9 ~ amount : 1_000_000_000 ( ) in let valid_forever = List . nth_exn few_now 0 in let removed_commands = [ valid_forever ; expires_later1 ; expired_zkapp ; unexpired_zkapp ] |> List . map ~ f : mk_with_status in let n_block_times n = Int64 ( . Block_time . Span . to_ms consensus_constants . block_window_duration_ms * n ) n |> Block_time . Span . of_ms in let % bind ( ) = after ( Block_time . Span . to_time_span ( n_block_times 3L ) 3L ) 3L in let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = [ mk_with_status valid_forever ] ; removed_commands ; reorg_best_tip = true } : Mock_transition_frontier . best_tip_diff ) in let cmds_wo_check = List . map ~ f : User_command . forget_check ( expires_later1 :: expires_later2 :: unexpired_zkapp :: List . drop few_now 1 ) in let % bind ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in assert_pool_txs cmds_wo_check ; let % bind ( ) = after ( Block_time . Span . to_time_span ( n_block_times 5L ) 5L ) 5L in let % bind _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = [ ] ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in let cmds_wo_check = List . map ~ f : User_command . forget_check ( List . drop few_now 1 ) 1 in let % bind ( ) = Async . Scheduler . yield_until_no_jobs_remain ( ) in assert_pool_txs cmds_wo_check ; Deferred . unit ) let % test_unit " Aged - based expiry ( zkapps ) zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let expiry = Time_ns . Span . of_sec 1 . in let % bind assert_pool_txs , pool , best_tip_diff_w , _ = setup_test ~ expiry ( ) in assert_pool_txs [ ] ; let party_transfer = mk_parties ~ fee_payer_idx ( : 0 , 0 ) 0 ~ sender_idx : 1 ~ receiver_idx : 9 ~ fee : 1_000_000_000 ~ amount : 10_000_000_000 ~ nonce : 0 ( ) in let valid_commands = [ party_transfer ] in let cmds_wo_check = List . map valid_commands ~ f : User_command . forget_check in let % bind apply_res = verify_and_apply pool cmds_wo_check in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res ) apply_res ( Ok cmds_wo_check ) cmds_wo_check ; assert_pool_txs cmds_wo_check ; let % bind ( ) = after ( Time . Span . of_sec 2 ) . in let % map _ = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = [ ] ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs [ ] ) let % test_unit " Now - invalid transactions are removed from the pool when the \ transition frontier is recreated ( user cmds ) cmds " = Thread_safe . block_on_async_exn ( fun ( ) -> let frontier_pipe_r , frontier_pipe_w = Broadcast_pipe . create None in let trust_system = Trust_system . null ( ) in let config = Test . Resource_pool . make_config ~ trust_system ~ pool_max_size ~ verifier in let pool_ , _ , _ = Test . create ~ config ~ logger ~ constraint_constants ~ consensus_constants ~ time_controller ~ expiry_ns ~ frontier_broadcast_pipe : frontier_pipe_r ~ log_gossip_heard : false ~ on_remote_push ( : Fn . const Deferred . unit ) unit in let pool = Test . resource_pool pool_ in let assert_pool_txs txs = [ % test_eq : User_command . t List . t ] t ( Test . Resource_pool . transactions ~ logger pool |> Sequence . map ~ f : Transaction_hash . User_command_with_valid_signature . command |> Sequence . to_list |> List . sort ~ compare : User_command . compare ) @@ List . sort ~ compare : User_command . compare txs in assert_pool_txs [ ] ; let frontier1 , best_tip_diff_w1 = Mock_transition_frontier . create ( ) in let % bind _ = Broadcast_pipe . Writer . write frontier_pipe_w ( Some frontier1 ) frontier1 in let % bind _ = verify_and_apply pool independent_cmds ' in assert_pool_txs independent_cmds ' ; Broadcast_pipe . Writer . close best_tip_diff_w1 ; let % bind _ = Broadcast_pipe . Writer . write frontier_pipe_w None in let ( ( _ , ledger_ref2 ) ledger_ref2 as frontier2 ) frontier2 , _best_tip_diff_w2 = Mock_transition_frontier . create ( ) in map_set_multi ! ledger_ref2 [ mk_account ~ idx : 0 ~ balance : 20_000_000_000_000 ~ nonce : 5 ; mk_account ~ idx : 1 ~ balance : 0 ~ nonce : 0 ; mk_account ~ idx : 2 ~ balance : 0 ~ nonce : 1 ] ; let % bind _ = Broadcast_pipe . Writer . write frontier_pipe_w ( Some frontier2 ) frontier2 in assert_pool_txs @@ List . drop independent_cmds ' 3 ; Deferred . unit ) let % test_unit " transaction replacement works " = Thread_safe . block_on_async_exn @@ fun ( ) -> let % bind assert_pool_txs , pool , _best_tip_diff_w , frontier = setup_test ( ) in let set_sender idx ( tx : Signed_command . t ) t = let sender_kp = test_keys ( . idx ) idx in let sender_pk = Public_key . compress sender_kp . public_key in let payload : Signed_command . Payload . t = match tx . payload with | { common ; body = Payment payload } -> { common = { common with fee_payer_pk = sender_pk } ; body = Payment { payload with source_pk = sender_pk } } | { common ; body = Stake_delegation ( Set_delegate payload ) payload } -> { common = { common with fee_payer_pk = sender_pk } ; body = Stake_delegation ( Set_delegate { payload with delegator = sender_pk } ) } in User_command . Signed_command ( Signed_command . sign sender_kp payload ) payload in let txs0 = [ mk_payment ' ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 0 ~ receiver_idx : 9 ~ amount : 20_000_000_000 ( ) ; mk_payment ' ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 1 ~ receiver_idx : 9 ~ amount : 12_000_000_000 ( ) ; mk_payment ' ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 2 ~ receiver_idx : 9 ~ amount : 500_000_000_000 ( ) ] in let txs0 ' = List . map txs0 ~ f : Signed_command . forget_check in let txs1 = List . map ~ f ( : set_sender 1 ) 1 txs0 ' in let txs2 = List . map ~ f ( : set_sender 2 ) 2 txs0 ' in let txs3 = List . map ~ f ( : set_sender 3 ) 3 txs0 ' in let txs_all = List . map ~ f ( : fun x -> User_command . Signed_command x ) x txs0 @ txs1 @ txs2 @ txs3 in let txs_all = List . map txs_all ~ f : User_command . forget_check in let % bind apply_res = verify_and_apply pool txs_all in [ % test_eq : pool_apply ] pool_apply ( Ok txs_all ) txs_all ( accepted_commands apply_res ) apply_res ; assert_pool_txs @@ txs_all ; let replace_txs = [ mk_payment ~ sender_idx : 0 ~ fee : 16_000_000_000 ~ nonce : 0 ~ receiver_idx : 1 ~ amount : 440_000_000_000 ( ) ; mk_payment ~ sender_idx : 1 ~ fee : 4_000_000_000 ~ nonce : 0 ~ receiver_idx : 1 ~ amount : 788_000_000_000 ( ) ; mk_payment ~ sender_idx : 2 ~ fee : 20_000_000_000 ~ nonce : 1 ~ receiver_idx : 4 ~ amount : 721_000_000_000 ( ) ; ( let amount = 927_000_000_000 in let fee = let ledger = Mock_transition_frontier . best_tip frontier in let sender_kp = test_keys ( . 3 ) 3 in let sender_pk = Public_key . compress sender_kp . public_key in let sender_aid = Account_id . create sender_pk Token_id . default in let location = Mock_base_ledger . location_of_account ledger sender_aid |> Option . value_exn in let account = Mock_base_ledger . get ledger location |> Option . value_exn in Currency . Balance . to_int account . balance - amount in mk_payment ~ sender_idx : 3 ~ fee ~ nonce : 1 ~ receiver_idx : 4 ~ amount ( ) ) ] in let replace_txs = List . map replace_txs ~ f : User_command . forget_check in let % bind apply_res_2 = verify_and_apply pool replace_txs in [ % test_eq : pool_apply ] pool_apply ( Ok [ List . nth_exn replace_txs 0 ; List . nth_exn replace_txs 2 ] ) ( accepted_commands apply_res_2 ) apply_res_2 ; Deferred . unit let % test_unit " it drops queued transactions if a committed one makes there \ be insufficient funds " = Thread_safe . block_on_async_exn @@ fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in let txs = [ mk_payment ~ sender_idx : 0 ~ fee : 5_000_000_000 ~ nonce : 0 ~ receiver_idx : 9 ~ amount : 20_000_000_000 ( ) ; mk_payment ~ sender_idx : 0 ~ fee : 6_000_000_000 ~ nonce : 1 ~ receiver_idx : 5 ~ amount : 77_000_000_000 ( ) ; mk_payment ~ sender_idx : 0 ~ fee : 1_000_000_000 ~ nonce : 2 ~ receiver_idx : 3 ~ amount : 891_000_000_000 ( ) ] in let committed_tx = mk_payment ~ sender_idx : 0 ~ fee : 5_000_000_000 ~ nonce : 0 ~ receiver_idx : 2 ~ amount : 25_000_000_000 ( ) in let txs = txs |> List . map ~ f : User_command . forget_check in let % bind apply_res = verify_and_apply pool txs in [ % test_eq : pool_apply ] pool_apply ( Ok txs ) txs ( accepted_commands apply_res ) apply_res ; assert_pool_txs @@ txs ; map_set_multi ! best_tip_ref [ mk_account ~ idx : 0 ~ balance : 970_000_000_000 ~ nonce : 1 ] ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w { new_commands = List . map ~ f : mk_with_status @@ [ committed_tx ] ; removed_commands = [ ] ; reorg_best_tip = false } in assert_pool_txs [ List . nth_exn txs 1 ] ; Deferred . unit let % test_unit " max size is maintained " = Quickcheck . test ~ trials : 500 ( let open Quickcheck . Generator . Let_syntax in let % bind init_ledger_state = Mina_ledger . Ledger . gen_initial_ledger_state in let % bind cmds_count = Int . gen_incl pool_max_size ( pool_max_size * 2 ) 2 in let % bind cmds = User_command . Valid . Gen . sequence ~ sign_type ` : Real ~ length : cmds_count init_ledger_state in return ( init_ledger_state , cmds ) cmds ) cmds ~ f ( : fun ( init_ledger_state , cmds ) cmds -> Thread_safe . block_on_async_exn ( fun ( ) -> let % bind _assert_pool_txs , pool , best_tip_diff_w , ( _ , best_tip_ref ) best_tip_ref = setup_test ( ) in let mock_ledger = Account_id . Table . of_alist_exn ( init_ledger_state |> Array . to_sequence |> Sequence . map ~ f ( : fun ( kp , balance , nonce , timing ) timing -> let public_key = Public_key . compress kp . public_key in let account_id = Account_id . create public_key Token_id . default in ( account_id , { ( Account . initialize account_id ) account_id with balance = Currency . Balance . of_uint64 ( Currency . Amount . to_uint64 balance ) balance ; nonce ; timing } ) ) |> Sequence . to_list ) in best_tip_ref := mock_ledger ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w { new_commands = [ ] ; removed_commands = [ ] ; reorg_best_tip = true } in let cmds1 , cmds2 = List . split_n cmds pool_max_size in let % bind apply_res1 = verify_and_apply pool ( List . map cmds1 ~ f : User_command . forget_check ) forget_check in assert ( Result . is_ok apply_res1 ) apply_res1 ; [ % test_eq : int ] int pool_max_size ( Indexed_pool . size pool . pool ) pool ; let % map _apply_res2 = verify_and_apply pool ( List . map cmds2 ~ f : User_command . forget_check ) forget_check in assert ( Indexed_pool . size pool . pool <= pool_max_size ) pool_max_size ) ) let assert_rebroadcastable pool cmds = let normalize = List . sort ~ compare : User_command . compare in let expected = match normalize cmds with [ ] -> [ ] | normalized -> [ normalized ] in [ % test_eq : User_command . t list list ] list ( List . map ~ f : normalize @@ Test . Resource_pool . get_rebroadcastable pool ~ has_timed_out ( : Fn . const ` Ok ) Ok ) expected let mock_sender = Envelope . Sender . Remote ( Peer . create ( Unix . Inet_addr . of_string " 1 . 2 . 3 . 4 ) " ~ peer_id ( : Peer . Id . unsafe_of_string " contents should be irrelevant ) " ~ libp2p_port : 8302 ) let mk_rebroadcastable_test assert_pool_txs pool best_tip_diff_w cmds = assert_pool_txs [ ] ; let local_cmds = List . take cmds 5 in let local_cmds ' = List . map local_cmds ~ f : User_command . forget_check in let remote_cmds = List . drop cmds 5 in let remote_cmds ' = List . map remote_cmds ~ f : User_command . forget_check in let % bind apply_res_1 = verify_and_apply pool local_cmds ' in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res_1 ) apply_res_1 ( Ok local_cmds ' ) local_cmds ' ; assert_pool_txs local_cmds ' ; assert_rebroadcastable pool local_cmds ' ; let % bind apply_res_2 = let % bind verified = Test . Resource_pool . Diff . verify pool ( Envelope . Incoming . wrap ~ data : remote_cmds ' ~ sender : mock_sender ) mock_sender >>| Or_error . ok_exn in Test . Resource_pool . Diff . unsafe_apply pool verified in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res_2 ) apply_res_2 ( Ok remote_cmds ' ) remote_cmds ' ; assert_pool_txs ( local_cmds ' @ remote_cmds ' ) remote_cmds ' ; assert_rebroadcastable pool local_cmds ' ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status @@ List . take local_cmds 2 @ List . take remote_cmds 3 ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs ( List . drop local_cmds ' 2 @ List . drop remote_cmds ' 3 ) 3 ; assert_rebroadcastable pool ( List . drop local_cmds ' 2 ) 2 ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status @@ List . take local_cmds 1 ; removed_commands = List . map ~ f : mk_with_status @@ List . take local_cmds 2 ; reorg_best_tip = true } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs ( List . tl_exn local_cmds ' @ List . drop remote_cmds ' 3 ) 3 ; assert_rebroadcastable pool ( List . tl_exn local_cmds ' ) local_cmds ' ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status @@ List . tl_exn local_cmds @ List . drop remote_cmds 3 ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs [ ] ; assert_rebroadcastable pool [ ] ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = [ ] ; removed_commands = List . map ~ f : mk_with_status @@ List . drop local_cmds 3 @ remote_cmds ; reorg_best_tip = true } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs ( List . drop local_cmds ' 3 @ remote_cmds ' ) remote_cmds ' ; assert_rebroadcastable pool ( List . drop local_cmds ' 3 ) 3 ; let % bind ( ) = Broadcast_pipe . Writer . write best_tip_diff_w ( { new_commands = List . map ~ f : mk_with_status @@ [ List . nth_exn local_cmds 3 ] ; removed_commands = [ ] ; reorg_best_tip = false } : Mock_transition_frontier . best_tip_diff ) in assert_pool_txs ( List . drop local_cmds ' 4 @ remote_cmds ' ) remote_cmds ' ; assert_rebroadcastable pool ( List . drop local_cmds ' 4 ) 4 ; ignore ( Test . Resource_pool . get_rebroadcastable pool ~ has_timed_out ( : Fn . const ` Timed_out ) Timed_out : User_command . t list list ) ; assert_pool_txs ( List . drop local_cmds ' 4 @ remote_cmds ' ) remote_cmds ' ; assert_rebroadcastable pool [ ] ; Deferred . unit let % test_unit " rebroadcastable transaction behavior ( user cmds ) cmds " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , _frontier = setup_test ( ) in mk_rebroadcastable_test assert_pool_txs pool best_tip_diff_w independent_cmds ) let % test_unit " rebroadcastable transaction behavior ( zkapps ) zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , best_tip_diff_w , _frontier = setup_test ( ) in mk_rebroadcastable_test assert_pool_txs pool best_tip_diff_w ( mk_parties_cmds pool ) pool ) let % test_unit " apply user cmds and zkapps " = Thread_safe . block_on_async_exn ( fun ( ) -> let % bind assert_pool_txs , pool , _best_tip_diff_w , _frontier = setup_test ( ) in let num_cmds = Array . length test_keys in let take_len = num_cmds / 2 in let snapp_cmds = List . take ( mk_parties_cmds ' pool ) pool take_len in let user_cmds = List . drop independent_cmds ' take_len in let all_cmds = snapp_cmds @ user_cmds in assert_pool_txs [ ] ; let % bind apply_res = verify_and_apply pool all_cmds in [ % test_eq : pool_apply ] pool_apply ( accepted_commands apply_res ) apply_res ( Ok all_cmds ) all_cmds ; assert_pool_txs all_cmds ; Deferred . unit ) end )
let top_hash_logging_enabled = ref false
let to_preunion ( t : Transaction . t ) t = match t with | Command ( Signed_command x ) x -> ` Transaction ( Transaction . Command x ) x | Fee_transfer x -> ` Transaction ( Fee_transfer x ) x | Coinbase x -> ` Transaction ( Coinbase x ) x | Command ( Parties x ) x -> ` Parties x
let with_top_hash_logging f = let old = ! top_hash_logging_enabled in top_hash_logging_enabled := true ; try let ret = f ( ) in top_hash_logging_enabled := old ; ret with err -> top_hash_logging_enabled := old ; raise err
module Proof_type = struct [ %% versioned module Stable = struct module V1 = struct type t = [ ` Base | ` Merge ] [ @@ deriving compare , equal , hash , sexp , yojson ] yojson let to_latest = Fn . id end end ] end end
module Pending_coinbase_stack_state = struct module Init_stack = struct [ %% versioned module Stable = struct module V1 = struct type t = Base of Pending_coinbase . Stack_versioned . Stable . V1 . t | Merge [ @@ deriving sexp , hash , compare , equal , yojson ] yojson let to_latest = Fn . id end end ] end end module Poly = struct [ %% versioned module Stable = struct module V1 = struct type ' pending_coinbase t = { source : ' pending_coinbase ; target : ' pending_coinbase } [ @@ deriving sexp , hash , compare , equal , fields , yojson , hlist ] hlist let to_latest pending_coinbase { source ; target } = { source = pending_coinbase source ; target = pending_coinbase target } end end ] end let typ pending_coinbase = Tick . Typ . of_hlistable [ pending_coinbase ; pending_coinbase ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist end type ' pending_coinbase poly = ' pending_coinbase Poly . t = { source : ' pending_coinbase ; target : ' pending_coinbase } [ @@ deriving sexp , hash , compare , equal , fields , yojson ] yojson [ %% versioned module Stable = struct module V1 = struct type t = Pending_coinbase . Stack_versioned . Stable . V1 . t Poly . Stable . V1 . t [ @@ deriving sexp , hash , compare , equal , yojson ] yojson let to_latest = Fn . id end end ] end type var = Pending_coinbase . Stack . var Poly . t let typ = Poly . typ Pending_coinbase . Stack . typ let to_input ( { source ; target } : t ) t = Random_oracle . Input . Chunked . append ( Pending_coinbase . Stack . to_input source ) source ( Pending_coinbase . Stack . to_input target ) target let var_to_input ( { source ; target } : var ) var = Random_oracle . Input . Chunked . append ( Pending_coinbase . Stack . var_to_input source ) source ( Pending_coinbase . Stack . var_to_input target ) target include Hashable . Make_binable ( Stable . Latest ) Latest include Comparable . Make ( Stable . Latest ) Latest end
module Statement = struct module Poly = struct [ %% versioned module Stable = struct module V2 = struct type ( ' ledger_hash , ' amount , ' pending_coinbase , ' fee_excess , ' sok_digest , ' local_state ) t = { source : ( ' ledger_hash , ' pending_coinbase , ' local_state ) Registers . Stable . V1 . t ; target : ( ' ledger_hash , ' pending_coinbase , ' local_state ) Registers . Stable . V1 . t ; supply_increase : ' amount ; fee_excess : ' fee_excess ; sok_digest : ' sok_digest } [ @@ deriving compare , equal , hash , sexp , yojson , hlist ] hlist end end ] end let with_empty_local_state ~ supply_increase ~ fee_excess ~ sok_digest ~ source ~ target ~ pending_coinbase_stack_state : _ t = { supply_increase ; fee_excess ; sok_digest ; source = { ledger = source ; pending_coinbase_stack = pending_coinbase_stack_state . Pending_coinbase_stack_state . source ; local_state = Local_state . empty ( ) } ; target = { ledger = target ; pending_coinbase_stack = pending_coinbase_stack_state . target ; local_state = Local_state . empty ( ) } } let typ ledger_hash amount pending_coinbase fee_excess sok_digest local_state_typ = let registers = let open Registers in Tick . Typ . of_hlistable [ ledger_hash ; pending_coinbase ; local_state_typ ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist in Tick . Typ . of_hlistable [ registers ; registers ; amount ; fee_excess ; sok_digest ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist end type ( ' ledger_hash , ' amount , ' pending_coinbase , ' fee_excess , ' sok_digest , ' local_state ) poly = ( ' ledger_hash , ' amount , ' pending_coinbase , ' fee_excess , ' sok_digest , ' local_state ) Poly . t = { source : ( ' ledger_hash , ' pending_coinbase , ' local_state ) ' local_state Registers . t ; target : ( ' ledger_hash , ' pending_coinbase , ' local_state ) ' local_state Registers . t ; supply_increase : ' amount ; fee_excess : ' fee_excess ; sok_digest : ' sok_digest } [ @@ deriving compare , equal , hash , sexp , yojson ] yojson [ %% versioned module Stable = struct module V2 = struct type t = ( Frozen_ledger_hash . Stable . V1 . t , Currency . Amount . Stable . V1 . t , Pending_coinbase . Stack_versioned . Stable . V1 . t , Fee_excess . Stable . V1 . t , unit , Local_state . Stable . V1 . t ) Poly . Stable . V2 . t [ @@ deriving compare , equal , hash , sexp , yojson ] yojson let to_latest = Fn . id end end ] end module With_sok = struct [ %% versioned module Stable = struct module V2 = struct type t = ( Frozen_ledger_hash . Stable . V1 . t , Currency . Amount . Stable . V1 . t , Pending_coinbase . Stack_versioned . Stable . V1 . t , Fee_excess . Stable . V1 . t , Sok_message . Digest . Stable . V1 . t , Local_state . Stable . V1 . t ) Poly . Stable . V2 . t [ @@ deriving compare , equal , hash , sexp , yojson ] yojson let to_latest = Fn . id end end ] end type var = ( Frozen_ledger_hash . var , Currency . Amount . var , Pending_coinbase . Stack . var , Fee_excess . var , Sok_message . Digest . Checked . t , Local_state . Checked . t ) Poly . t let typ : ( var , t ) t Tick . Typ . t = Poly . typ Frozen_ledger_hash . typ Currency . Amount . typ Pending_coinbase . Stack . typ Fee_excess . typ Sok_message . Digest . typ Local_state . typ let to_input { source ; target ; supply_increase ; fee_excess ; sok_digest } = let input = Array . reduce_exn ~ f : Random_oracle . Input . Chunked . append [ | Sok_message . Digest . to_input sok_digest ; Registers . to_input source ; Registers . to_input target ; Amount . to_input supply_increase ; Fee_excess . to_input fee_excess ] | in if ! top_hash_logging_enabled then Format . eprintf " ! Generating unchecked top hash from { . :@% sexp : Tick . Field . t \ Random_oracle . Input . Chunked . t } t . " @ input ; input let to_field_elements t = Random_oracle . pack_input ( to_input t ) t module Checked = struct type t = var let to_input { source ; target ; supply_increase ; fee_excess ; sok_digest } = let open Tick in let open Checked . Let_syntax in let % bind fee_excess = Fee_excess . to_input_checked fee_excess in let source = Registers . Checked . to_input source and target = Registers . Checked . to_input target in let input = Array . reduce_exn ~ f : Random_oracle . Input . Chunked . append [ | Sok_message . Digest . Checked . to_input sok_digest ; source ; target ; Amount . var_to_input supply_increase ; fee_excess ] | in let % map ( ) = as_prover As_prover ( . if ! top_hash_logging_enabled then let % map input = Random_oracle . read_typ ' input in Format . eprintf " ! Generating checked top hash from { . :@% sexp : Field . t \ Random_oracle . Input . Chunked . t } t . " @ input else return ( ) ) in input let to_field_elements t = let open Tick . Checked . Let_syntax in Tick . Run . run_checked ( to_input t >>| Random_oracle . Checked . pack_input ) pack_input end end let option lab = Option . value_map ~ default ( : Or_error . error_string lab ) lab ~ f ( : fun x -> Ok x ) x let merge ( s1 : _ Poly . t ) t ( s2 : _ Poly . t ) t = let open Or_error . Let_syntax in let registers_check_equal ( t1 : _ Registers . t ) t ( t2 : _ Registers . t ) t = let check ' k f = let x1 = Field . get f t1 and x2 = Field . get f t2 in k x1 x2 in let module S = struct module type S = sig type t [ @@ deriving eq , sexp_of ] sexp_of end end in let check ( type t ) t ( module T : S . S with type t = t ) t f = let open T in check ' ( fun x1 x2 -> if equal x1 x2 then return ( ) else Or_error . errorf " !% s is inconsistent between transitions ( { % sexp : t } t vs \ { % sexp : t } t ) t " ( Field . name f ) f x1 x2 ) f in let module PC = struct type t = Pending_coinbase . Stack . t [ @@ deriving sexp_of ] sexp_of let equal t1 t2 = Pending_coinbase . Stack . connected ~ first : t1 ~ second : t2 ( ) end in Registers . Fields . to_list ~ ledger ( : check ( module Ledger_hash ) Ledger_hash ) Ledger_hash ~ pending_coinbase_stack ( : check ( module PC ) PC ) PC ~ local_state ( : check ( module Local_state ) Local_state ) Local_state |> Or_error . combine_errors_unit in let % map fee_excess = Fee_excess . combine s1 . fee_excess s2 . fee_excess and supply_increase = Currency . Amount . add s1 . supply_increase s2 . supply_increase |> option " Error adding supply_increase " and ( ) = registers_check_equal s1 . target s2 . source in ( { source = s1 . source ; target = s2 . target ; fee_excess ; supply_increase ; sok_digest = ( ) } : t ) include Hashable . Make_binable ( Stable . Latest ) Latest include Comparable . Make ( Stable . Latest ) Latest let gen = let open Quickcheck . Generator . Let_syntax in let % map source = Registers . gen and target = Registers . gen and fee_excess = Fee_excess . gen and supply_increase = Currency . Amount . gen in ( { source ; target ; fee_excess ; supply_increase ; sok_digest = ( ) } : t ) t end
module Proof = struct [ %% versioned module Stable = struct module V2 = struct type t = Pickles . Proof . Proofs_verified_2 . Stable . V2 . t [ @@ deriving version { asserted } , yojson , bin_io , compare , equal , sexp , hash ] hash let to_latest = Fn . id end end ] end end [ %% versioned
module Stable = struct module V2 = struct type t = { statement : Statement . With_sok . Stable . V2 . t ; proof : Proof . Stable . V2 . t } [ @@ deriving compare , equal , fields , sexp , version , yojson , hash ] hash let to_latest = Fn . id end end ] end
let proof t = t . proof
let statement t = { t . statement with sok_digest = ( ) }
let sok_digest t = t . statement . sok_digest
let create ~ statement ~ proof = { statement ; proof }
let chain if_ b ~ then_ ~ else_ = let % bind then_ = then_ and else_ = else_ in if_ b ~ then_ ~ else_
module Parties_segment = struct module Spec = struct type single = { auth_type : Control . Tag . t ; is_start : [ ` Yes | ` No | ` Compute_in_circuit ] } type t = single list end module Basic = struct module N = Side_loaded_verification_key . Max_branches [ %% versioned module Stable = struct module V1 = struct type t = Opt_signed_opt_signed | Opt_signed | Proved [ @@ deriving sexp , yojson ] yojson let to_latest = Fn . id end end ] end let of_controls = function | [ Control . Proof _ ] -> Proved | [ ( Control . Signature _ | Control . None_given ) None_given ] -> Opt_signed | [ Control ( . Signature _ | None_given ) None_given ; Control ( . Signature _ | None_given ) None_given ] -> Opt_signed_opt_signed | _ -> failwith " Parties_segment . Basic . of_controls : Unsupported combination " let opt_signed ~ is_start : Spec . single = { auth_type = Signature ; is_start } let opt_signed = opt_signed ~ is_start ` : Compute_in_circuit let to_single_list : t -> Spec . single list = fun t -> match t with | Opt_signed_opt_signed -> [ opt_signed ; opt_signed ] | Opt_signed -> [ opt_signed ] | Proved -> [ { auth_type = Proof ; is_start = ` No } ] type ( _ , _ , _ , _ ) _ t_typed = | Opt_signed_opt_signed : ( unit , unit , unit , unit ) unit t_typed | Opt_signed : ( unit , unit , unit , unit ) unit t_typed | Proved : ( Zkapp_statement . Checked . t * unit , Zkapp_statement . t * unit , Nat . N2 . n * unit , N . n * unit ) t_typed let spec : type a b c d . ( a , b , c , d ) d t_typed -> Spec . single list = fun t -> match t with | Opt_signed_opt_signed -> [ opt_signed ; opt_signed ] | Opt_signed -> [ opt_signed ] | Proved -> [ { auth_type = Proof ; is_start = ` No } ] end module Witness = Transaction_witness . Parties_segment_witness end
let dummy_constraints ( ) = make_checked Impl ( . fun ( ) -> 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 ) )
module Base = struct module User_command_failure = struct type ' bool t = { predicate_failed : ' bool ; source_not_present : ' bool ; receiver_not_present : ' bool ; amount_insufficient_to_create : ' bool ; token_cannot_create : ' bool ; source_insufficient_balance : ' bool ; source_minimum_balance_violation : ' bool ; source_bad_timing : ' bool } let num_fields = 8 let to_list { predicate_failed ; source_not_present ; receiver_not_present ; amount_insufficient_to_create ; token_cannot_create ; source_insufficient_balance ; source_minimum_balance_violation ; source_bad_timing } = [ predicate_failed ; source_not_present ; receiver_not_present ; amount_insufficient_to_create ; token_cannot_create ; source_insufficient_balance ; source_minimum_balance_violation ; source_bad_timing ] let of_list = function | [ predicate_failed ; source_not_present ; receiver_not_present ; amount_insufficient_to_create ; token_cannot_create ; source_insufficient_balance ; source_minimum_balance_violation ; source_bad_timing ] -> { predicate_failed ; source_not_present ; receiver_not_present ; amount_insufficient_to_create ; token_cannot_create ; source_insufficient_balance ; source_minimum_balance_violation ; source_bad_timing } | _ -> failwith " Transaction_snark . Base . User_command_failure . to_list : bad length " let typ : ( Boolean . var t , bool t ) t Typ . t = let open Typ in list ~ length : num_fields Boolean . typ |> transport ~ there : to_list ~ back : of_list |> transport_var ~ there : to_list ~ back : of_list let any t = Boolean . any ( to_list t ) t let compute_unchecked ( ~ constraint_constants : Genesis_constants . Constraint_constants . t ) t ~ txn_global_slot ( ~ fee_payer_account : Account . t ) t ( ~ receiver_account : Account . t ) t ( ~ source_account : Account . t ) t ( { payload ; signature = _ ; signer = _ } : Transaction_union . t ) t = match payload . body . tag with | Fee_transfer | Coinbase -> of_list ( List . init num_fields ~ f ( : fun _ -> false ) false ) false | _ -> ( let fail s = failwithf " Transaction_snark . Base . User_command_failure . compute_unchecked : \ % s " s ( ) in let fee_token = payload . common . fee_token in let token = payload . body . token_id in let fee_payer = Account_id . create payload . common . fee_payer_pk fee_token in let source = Account_id . create payload . body . source_pk token in let receiver = Account_id . create payload . body . receiver_pk token in let fee_payer_account = { fee_payer_account with balance = Option . value_exn ? here : None ? error : None ? message : None @@ Balance . sub_amount fee_payer_account . balance ( Amount . of_fee payload . common . fee ) fee } in let predicate_failed = if Public_key . Compressed . equal payload . common . fee_payer_pk payload . body . source_pk then false else match payload . body . tag with | Create_account | Mint_tokens -> assert false | Payment | Stake_delegation -> true | Fee_transfer | Coinbase -> assert false in match payload . body . tag with | Fee_transfer | Coinbase -> assert false | Stake_delegation -> let receiver_account = if Account_id . equal receiver fee_payer then fee_payer_account else receiver_account in let receiver_not_present = let id = Account . identifier receiver_account in if Account_id . equal Account_id . empty id then true else if Account_id . equal receiver id then false else fail " bad receiver account ID " in let source_account = if Account_id . equal source fee_payer then fee_payer_account else source_account in let source_not_present = let id = Account . identifier source_account in if Account_id . equal Account_id . empty id then true else if Account_id . equal source id then false else fail " bad source account ID " in { predicate_failed ; source_not_present ; receiver_not_present ; amount_insufficient_to_create = false ; token_cannot_create = false ; source_insufficient_balance = false ; source_minimum_balance_violation = false ; source_bad_timing = false } | Payment -> let receiver_account = if Account_id . equal receiver fee_payer then fee_payer_account else receiver_account in let receiver_needs_creating = let id = Account . identifier receiver_account in if Account_id . equal Account_id . empty id then true else if Account_id . equal receiver id then false else fail " bad receiver account ID " in let token_is_default = true in let token_cannot_create = receiver_needs_creating && not token_is_default in let amount_insufficient_to_create = let creation_amount = Amount . of_fee constraint_constants . account_creation_fee in receiver_needs_creating && Option . is_none ( Amount . sub payload . body . amount creation_amount ) creation_amount in let fee_payer_is_source = Account_id . equal fee_payer source in let source_account = if fee_payer_is_source then fee_payer_account else source_account in let source_not_present = let id = Account . identifier source_account in if Account_id . equal Account_id . empty id then true else if Account_id . equal source id then false else fail " bad source account ID " in let source_insufficient_balance = ( not fee_payer_is_source ) fee_payer_is_source && if Account_id . equal source receiver then receiver_needs_creating else Amount ( . Balance . to_amount source_account . balance < payload . body . amount ) amount in let timing_or_error = Mina_transaction_logic . validate_timing ~ txn_amount : payload . body . amount ~ txn_global_slot ~ account : source_account in let source_minimum_balance_violation = match timing_or_error with | Ok _ -> false | Error err -> let open Mina_base in Transaction_status . Failure . equal ( Mina_transaction_logic . timing_error_to_user_command_status err ) Transaction_status . Failure . Source_minimum_balance_violation in let source_bad_timing = ( not fee_payer_is_source ) fee_payer_is_source && ( not source_insufficient_balance ) source_insufficient_balance && Or_error . is_error timing_or_error in { predicate_failed ; source_not_present ; receiver_not_present = false ; amount_insufficient_to_create ; token_cannot_create ; source_insufficient_balance ; source_minimum_balance_violation ; source_bad_timing } | Mint_tokens | Create_account -> assert false ) let % snarkydef compute_as_prover ~ constraint_constants ~ txn_global_slot ( txn : Transaction_union . var ) var = let % bind data = exists ( Typ . Internal . ref ( ) ) ~ compute : As_prover ( . let % map txn = read Transaction_union . typ txn in let fee_token = txn . payload . common . fee_token in let token = txn . payload . body . token_id in let fee_payer = Account_id . create txn . payload . common . fee_payer_pk fee_token in let source = Account_id . create txn . payload . body . source_pk token in let receiver = Account_id . create txn . payload . body . receiver_pk token in ( txn , fee_payer , source , receiver ) receiver ) receiver in let % bind fee_payer_idx = exists ( Typ . Internal . ref ( ) ) ~ request : As_prover ( . let % map _txn , fee_payer , _source , _receiver = read ( Typ . Internal . ref ( ) ) data in Ledger_hash . Find_index fee_payer ) fee_payer in let % bind fee_payer_account = exists ( Typ . Internal . ref ( ) ) ~ request : As_prover ( . let % map fee_payer_idx = read ( Typ . Internal . ref ( ) ) fee_payer_idx in Ledger_hash . Get_element fee_payer_idx ) fee_payer_idx in let % bind source_idx = exists ( Typ . Internal . ref ( ) ) ~ request : As_prover ( . let % map _txn , _fee_payer , source , _receiver = read ( Typ . Internal . ref ( ) ) data in Ledger_hash . Find_index source ) source in let % bind source_account = exists ( Typ . Internal . ref ( ) ) ~ request : As_prover ( . let % map source_idx = read ( Typ . Internal . ref ( ) ) source_idx in Ledger_hash . Get_element source_idx ) source_idx in let % bind receiver_idx = exists ( Typ . Internal . ref ( ) ) ~ request : As_prover ( . let % map _txn , _fee_payer , _source , receiver = read ( Typ . Internal . ref ( ) ) data in Ledger_hash . Find_index receiver ) receiver in let % bind receiver_account = exists ( Typ . Internal . ref ( ) ) ~ request : As_prover ( . let % map receiver_idx = read ( Typ . Internal . ref ( ) ) receiver_idx in Ledger_hash . Get_element receiver_idx ) receiver_idx in exists typ ~ compute : As_prover ( . let % bind txn , _fee_payer , _source , _receiver = read ( Typ . Internal . ref ( ) ) data in let % bind fee_payer_account , _path = read ( Typ . Internal . ref ( ) ) fee_payer_account in let % bind source_account , _path = read ( Typ . Internal . ref ( ) ) source_account in let % bind receiver_account , _path = read ( Typ . Internal . ref ( ) ) receiver_account in let % map txn_global_slot = read Global_slot . typ txn_global_slot in compute_unchecked ~ constraint_constants ~ txn_global_slot ~ fee_payer_account ~ source_account ~ receiver_account txn ) txn end let % snarkydef check_signature shifted ~ payload ~ is_user_command ~ signer ~ signature = let % bind input = Transaction_union_payload . Checked . to_input_legacy payload in let % bind verifies = Schnorr . Legacy . Checked . verifies shifted signature signer input in [ % with_label " check signature ] " ( Boolean . Assert . any [ Boolean . not is_user_command ; verifies ] ) let check_timing ~ balance_check ~ timed_balance_check ~ account ~ txn_amount ~ txn_global_slot = let open Account . Poly in let open Account . Timing . As_record in let { is_timed ; initial_minimum_balance ; cliff_time ; cliff_amount ; vesting_period ; vesting_increment } = account . timing in let % bind curr_min_balance = Account . Checked . min_balance_at_slot ~ global_slot : txn_global_slot ~ cliff_time ~ cliff_amount ~ vesting_period ~ vesting_increment ~ initial_minimum_balance in let % bind proposed_balance = match txn_amount with | Some txn_amount -> let % bind proposed_balance , ` Underflow underflow = Balance . Checked . sub_amount_flagged account . balance txn_amount in let % map ( ) = balance_check ( Boolean . not underflow ) underflow in proposed_balance | None -> return account . balance in let % bind sufficient_timed_balance = Balance . Checked ( . >= ) proposed_balance curr_min_balance in let % bind ( ) = let % bind ok = Boolean ( . any [ not is_timed ; sufficient_timed_balance ] ) in timed_balance_check ok in let % bind is_timed_balance_zero = Balance . Checked . equal curr_min_balance ( Balance . Checked . Unsafe . of_field Field ( . Var . constant zero ) zero ) zero in let % bind is_untimed = Boolean ( ( . not is_timed ) is_timed ||| is_timed_balance_zero ) is_timed_balance_zero in let % map timing = Account . Timing . if_ is_untimed ~ then_ : Account . Timing . untimed_var ~ else_ : account . timing in ( ` Min_balance curr_min_balance , timing ) timing let side_loaded = Memo . of_comparable ( module Int ) Int ( fun i -> let open Zkapp_statement in Pickles . Side_loaded . create ~ typ ~ name ( : sprintf " zkapp_ % d " i ) i ~ max_proofs_verified : ( module Pickles . Side_loaded . Verification_key . Max_width ) Max_width ~ value_to_field_elements : to_field_elements ~ var_to_field_elements : Checked . to_field_elements ) let signature_verifies ~ shifted ~ payload_digest signature pk = let % bind pk = Public_key . decompress_var pk in Schnorr . Chunked . Checked . verifies shifted signature pk ( Random_oracle . Input . Chunked . field payload_digest ) payload_digest module Parties_snark = struct open Parties_segment open Spec module Prover_value : sig type ' a t val get : ' a t -> ' a val create : ( unit -> ' a ) ' a -> ' a t val map : ' a t -> f ( : ' a -> ' b ) ' b -> ' b t val if_ : Boolean . var -> then_ : ' a t -> else_ : ' a t -> ' a t end = struct open Impl type ' a t = ' a As_prover . Ref . t let get = As_prover . Ref . get let create = As_prover . Ref . create let if_ b ~ then_ ~ else_ = create ( fun ( ) -> get ( if Impl . As_prover . read Boolean . typ b then then_ else else_ ) else_ ) let map t ~ f = create ( fun ( ) -> f ( get t ) t ) t end module Global_state = struct type t = { ledger : Ledger_hash . var * Sparse_ledger . t Prover_value . t ; fee_excess : Amount . Signed . var ; protocol_state : Zkapp_precondition . Protocol_state . View . Checked . t } end let implied_root account incl = let open Impl in List . foldi incl ~ init ( : Lazy . force ( With_hash . hash account ) account ) account ~ f ( : fun height acc ( b , h ) h -> let l = Field . if_ b ~ then_ : h ~ else_ : acc and r = Field . if_ b ~ then_ : acc ~ else_ : h in let acc ' = Ledger_hash . merge_var ~ height l r in acc ' ) module type Single_inputs = sig val constraint_constants : Genesis_constants . Constraint_constants . t val spec : single val snapp_statement : ( int * Zkapp_statement . Checked . t ) t option end type party = { party : ( Party . Body . Checked . t , Parties . Digest . Party . Checked . t ) t With_hash . t ; control : Control . t Prover_value . t } module Inputs = struct module V = Prover_value open Impl module Transaction_commitment = struct type t = Field . t let if_ = Field . if_ let empty = Field . constant Parties . Transaction_commitment . empty let commitment ~ other_parties { : With_hash . hash = other_parties ; _ } = Parties . Transaction_commitment . Checked . create ~ other_parties_hash : other_parties let full_commitment ~ party { : party ; _ } ~ memo_hash ~ commitment = Parties . Transaction_commitment . Checked . create_complete commitment ~ memo_hash ~ fee_payer_hash : party . hash end module Bool = struct include Boolean type t = var let display _b ~ label : _ = " " type failure_status = unit type failure_status_tbl = unit let assert_with_failure_status_tbl b _failure_status_tbl = Assert . is_true b end module Account_id = struct type t = Account_id . var let if_ b ~ then_ ~ else_ = run_checked ( Account_id . Checked . if_ b ~ then_ ~ else_ ) else_ let derive_token_id = Account_id . Checked . derive_token_id let constant id = Account_id ( . Checked . create ( Public_key . Compressed . var_of_t ( public_key id ) id ) id ( Token_id . Checked . constant ( token_id id ) id ) id ) id let invalid = constant Account_id . invalid let equal x y = Account_id . Checked . equal x y |> run_checked let create = Account_id . Checked . create end module Global_slot = struct include Global_slot . Checked let ( > ) x y = run_checked ( x > y ) y let if_ b ~ then_ ~ else_ = run_checked ( if_ b ~ then_ ~ else_ ) else_ let equal x y = run_checked ( equal x y ) y end module Nonce = struct type t = Account . Nonce . Checked . t let if_ b ~ then_ ~ else_ = run_checked ( Account . Nonce . Checked . if_ b ~ then_ ~ else_ ) else_ let succ t = run_checked ( Account . Nonce . Checked . succ t ) t end module State_hash = struct type t = State_hash . var let if_ b ~ then_ ~ else_ = run_checked ( State_hash . if_ b ~ then_ ~ else_ ) else_ end module Timing = struct type t = Account_timing . var let if_ b ~ then_ ~ else_ = run_checked ( Account_timing . if_ b ~ then_ ~ else_ ) else_ let vesting_period ( t : t ) t = t . vesting_period end module Balance = struct include Balance . Checked let if_ b ~ then_ ~ else_ = run_checked ( if_ b ~ then_ ~ else_ ) else_ let sub_amount_flagged x y = run_checked ( sub_amount_flagged x y ) y let add_signed_amount_flagged x y = run_checked ( add_signed_amount_flagged x y ) y end module Verification_key = struct type t = ( Boolean . var , ( Side_loaded_verification_key . t option , Field . Constant . t ) With_hash . t Data_as_hash . t ) Zkapp_basic . Flagged_option . t let if_ b ( ~ then_ : t ) t ( ~ else_ : t ) t : t = Zkapp_basic . Flagged_option . if_ ~ if_ : Data_as_hash . if_ b ~ then_ ~ else_ end module Events = struct type t = Zkapp_account . Events . var let is_empty x = run_checked ( Party . Events . is_empty_var x ) x let push_events = Party . Sequence_events . push_events_checked end module Zkapp_uri = struct type t = string Data_as_hash . t let if_ = Data_as_hash . if_ end module Token_symbol = struct type t = Account . Token_symbol . var let if_ = Account . Token_symbol . if_ end module Account = struct type t = ( Account . Checked . Unhashed . t , Field . t Lazy . t ) t With_hash . t module Permissions = struct type controller = Permissions . Auth_required . Checked . t let edit_state : t -> controller = fun a -> a . data . permissions . edit_state let send : t -> controller = fun a -> a . data . permissions . send let receive : t -> controller = fun a -> a . data . permissions . receive let set_delegate : t -> controller = fun a -> a . data . permissions . set_delegate let set_permissions : t -> controller = fun a -> a . data . permissions . set_permissions let set_verification_key : t -> controller = fun a -> a . data . permissions . set_verification_key let set_zkapp_uri : t -> controller = fun a -> a . data . permissions . set_zkapp_uri let edit_sequence_state : t -> controller = fun a -> a . data . permissions . edit_sequence_state let set_token_symbol : t -> controller = fun a -> a . data . permissions . set_token_symbol let increment_nonce : t -> controller = fun a -> a . data . permissions . increment_nonce let set_voting_for : t -> controller = fun a -> a . data . permissions . set_voting_for type t = Permissions . Checked . t let if_ b ~ then_ ~ else_ = Permissions . Checked . if_ b ~ then_ ~ else_ end let account_with_hash ( account : Account . Checked . Unhashed . t ) t : t = With_hash . of_data account ~ hash_data ( : fun a -> lazy ( let a = { a with zkapp = ( Zkapp_account . Checked . digest a . zkapp , As_prover . Ref . create ( fun ( ) -> None ) None ) } in run_checked ( Account . Checked . digest a ) a ) ) type timing = Account_timing . var let timing ( account : t ) t : timing = account . data . timing let set_timing ( account : t ) t ( timing : timing ) timing : t = { account with data = { account . data with timing } } let is_timed ( { data = account ; _ } : t ) t = let open Account . Poly in let open Account . Timing . As_record in let { is_timed ; _ } = account . timing in is_timed let set_token_id ( account : t ) t ( token_id : Token_id . Checked . t ) t : t = account_with_hash { account . data with token_id } let balance ( a : t ) t : Balance . t = a . data . balance let set_balance ( balance : Balance . t ) t ( { data = a ; hash } : t ) t : t = { data = { a with balance } ; hash } let check_timing ~ txn_global_slot ( { data = account ; _ } : t ) t = let invalid_timing = ref None in let balance_check _ = failwith " Should not be called " in let timed_balance_check b = invalid_timing := Some ( Boolean . not b ) b ; return ( ) in let ` Min_balance _ , timing = run_checked @@ [ % with_label " Check zkapp timing ] " ( check_timing ~ balance_check ~ timed_balance_check ~ account ~ txn_amount : None ~ txn_global_slot ) in ( ` Invalid_timing ( Option . value_exn ! invalid_timing ) invalid_timing , timing ) timing let make_zkapp ( a : t ) t = a let unmake_zkapp ( a : t ) t = a let proved_state ( a : t ) t = a . data . zkapp . proved_state let set_proved_state proved_state ( { data = a ; hash } : t ) t : t = { data = { a with zkapp = { a . zkapp with proved_state } } ; hash } let app_state ( a : t ) t = a . data . zkapp . app_state let set_app_state app_state ( { data = a ; hash } : t ) t : t = { data = { a with zkapp = { a . zkapp with app_state } } ; hash } let verification_key ( a : t ) t : Verification_key . t = a . data . zkapp . verification_key let set_verification_key ( verification_key : Verification_key . t ) t ( { data = a ; hash } : t ) t : t = { data = { a with zkapp = { a . zkapp with verification_key } } ; hash } let last_sequence_slot ( a : t ) t = a . data . zkapp . last_sequence_slot let set_last_sequence_slot last_sequence_slot ( { data = a ; hash } : t ) t : t = { data = { a with zkapp = { a . zkapp with last_sequence_slot } } ; hash } let sequence_state ( a : t ) t = a . data . zkapp . sequence_state let set_sequence_state sequence_state ( { data = a ; hash } : t ) t : t = { data = { a with zkapp = { a . zkapp with sequence_state } } ; hash } let zkapp_uri ( a : t ) t = a . data . zkapp_uri let set_zkapp_uri zkapp_uri ( { data = a ; hash } : t ) t : t = { data = { a with zkapp_uri } ; hash } let token_symbol ( a : t ) t = a . data . token_symbol let set_token_symbol token_symbol ( { data = a ; hash } : t ) t : t = { data = { a with token_symbol } ; hash } let public_key ( a : t ) t = a . data . public_key let set_public_key public_key ( { data = a ; hash } : t ) t : t = { data = { a with public_key } ; hash } let delegate ( a : t ) t = a . data . delegate let set_delegate delegate ( { data = a ; hash } : t ) t : t = { data = { a with delegate } ; hash } let nonce ( a : t ) t = a . data . nonce let set_nonce nonce ( { data = a ; hash } : t ) t : t = { data = { a with nonce } ; hash } let voting_for ( a : t ) t = a . data . voting_for let set_voting_for voting_for ( { data = a ; hash } : t ) t : t = { data = { a with voting_for } ; hash } let permissions ( a : t ) t = a . data . permissions let set_permissions permissions ( { data = a ; hash } : t ) t : t = { data = { a with permissions } ; hash } end module Opt = struct open Zkapp_basic type ' a t = ( Bool . t , ' a ) ' a Flagged_option . t let is_some = Flagged_option . is_some let map x ~ f = Flagged_option . map ~ f x let or_default ~ if_ x ~ default = if_ ( is_some x ) x ~ then_ ( : Flagged_option . data x ) x ~ else_ : default let or_exn x = with_label " or_exn is_some " ( fun ( ) -> Bool . Assert . is_true ( is_some x ) x ) ; Flagged_option . data x end module Parties = struct module F = Parties . Digest . Forest . Checked type t = ( ( Party . t * unit , Parties . Digest . Party . t , Parties . Digest . Forest . t ) Parties . Call_forest . t V . t , F . t ) With_hash . t let if_ b ~ then_ ( : t : t ) t ~ else_ ( : e : t ) t : t = { hash = F . if_ b ~ then_ : t . hash ~ else_ : e . hash ; data = V . if_ b ~ then_ : t . data ~ else_ : e . data } let empty = Parties . Digest . Forest . constant Parties . Call_forest . With_hashes . empty let is_empty ( { hash = x ; _ } : t ) t = F . equal empty x let empty ( ) : t = { hash = empty ; data = V . create ( fun ( ) -> [ ] ) } let pop_exn ( { hash = h ; data = r } : t ) t : ( party * t ) t * t = with_label " Parties . pop_exn " ( fun ( ) -> let hd_r = V . create ( fun ( ) -> V . get r |> List . hd_exn |> With_stack_hash . elt ) in let party = V . create ( fun ( ) -> ( V . get hd_r ) hd_r . party |> fst ) fst in let auth = V ( . create ( fun ( ) -> ( V . get party ) party . authorization ) authorization ) authorization in let party = exists ( Party . Body . typ ( ) ) ~ compute ( : fun ( ) -> ( V . get party ) party . body ) in let party = With_hash . of_data party ~ hash_data : Parties . Digest . Party . Checked . create in let subforest : t = let subforest = V . create ( fun ( ) -> ( V . get hd_r ) hd_r . calls ) calls in let subforest_hash = exists Parties . Digest . Forest . typ ~ compute ( : fun ( ) -> Parties . Call_forest . hash ( V . get subforest ) subforest ) in { hash = subforest_hash ; data = subforest } in let tl_hash = exists Parties . Digest . Forest . typ ~ compute ( : fun ( ) -> V . get r |> List . tl_exn |> Parties . Call_forest . hash ) in let tree_hash = Parties . Digest . Tree . Checked . create ~ party : party . hash ~ calls : subforest . hash in let hash_cons = Parties . Digest . Forest . Checked . cons tree_hash tl_hash in F . Assert . equal hash_cons h ; ( ( ( { party ; control = auth } , subforest ) subforest , { hash = tl_hash ; data = V ( . create ( fun ( ) -> List . tl_exn ( get r ) r ) r ) r } ) : ( party * t ) t * t ) ) end module Stack_frame = struct type frame = ( Token_id . Checked . t , Parties . t ) t Stack_frame . t type t = ( frame , Stack_frame . Digest . Checked . t Lazy . t ) t With_hash . t let if_ b ~ then_ ( : t1 : t ) t ~ else_ ( : t2 : t ) t : t = { With_hash . hash = lazy ( Stack_frame . Digest . Checked . if_ b ~ then_ ( : Lazy . force t1 . hash ) hash ~ else_ ( : Lazy . force t2 . hash ) hash ) ; data = Stack_frame . Checked . if_ Parties . if_ b ~ then_ : t1 . data ~ else_ : t2 . data } let caller ( t : t ) t = t . data . caller let caller_caller ( t : t ) t = t . data . caller_caller let calls ( t : t ) t = t . data . calls let of_frame ( frame : frame ) frame : t = { data = frame ; hash = lazy ( Stack_frame . Digest . Checked . create ~ hash_parties ( : fun ( calls : Parties . t ) t -> calls . hash ) hash frame ) } let make ~ caller ~ caller_caller ~ calls : t = Stack_frame . make ~ caller ~ caller_caller ~ calls |> of_frame let hash ( t : t ) t : Stack_frame . Digest . Checked . t = Lazy . force t . hash let unhash ( h : Stack_frame . Digest . Checked . t ) t ( frame : ( Mina_base . Token_id . Stable . V1 . t , unit Mina_base . Parties . Call_forest . With_hashes . Stable . V1 . t ) Stack_frame . Stable . V1 . t V . t ) : t = with_label " unhash " ( fun ( ) -> let frame : frame = { caller = exists Token_id . typ ~ compute ( : fun ( ) -> ( V . get frame ) frame . caller ) ; caller_caller = exists Token_id . typ ~ compute ( : fun ( ) -> ( V . get frame ) frame . caller_caller ) ; calls = { hash = exists Mina_base . Parties . Digest . Forest . typ ~ compute ( : fun ( ) -> ( V . get frame ) frame . calls |> Mina_base . Parties . Call_forest . hash ) ; data = V . map frame ~ f ( : fun frame -> frame . calls ) calls } } in let t = of_frame frame in Stack_frame . Digest . Checked . Assert . equal ( hash ( of_frame frame ) frame ) frame h ; t ) end module Call_stack = struct module Value = struct open Mina_base type caller = Token_id . t type frame = ( caller , ( Party . t * unit , Parties . Digest . Party . t , Parties . Digest . Forest . t ) Parties . Call_forest . t ) Stack_frame . t end type elt = Stack_frame . t module Elt = struct type t = ( Value . frame , Mina_base . Stack_frame . Digest . t ) t With_hash . t let default : unit -> t = Memo . unit ( fun ( ) : t -> With_hash . of_data ~ hash_data : Mina_base . Stack_frame . Digest . create ( { caller = Mina_base . Token_id . default ; caller_caller = Mina_base . Token_id . default ; calls = [ ] } : Value . frame ) ) end let hash ( type a ) a ( xs : ( a , Call_stack_digest . t ) t With_stack_hash . t list ) list : Call_stack_digest . t = match xs with [ ] -> Call_stack_digest . empty | x :: _ -> x . stack_hash type t = ( ( Elt . t , Call_stack_digest . t ) t With_stack_hash . t list V . t , Call_stack_digest . Checked . t ) With_hash . t let if_ b ~ then_ ( : t : t ) t ~ else_ ( : e : t ) t : t = { hash = Call_stack_digest . Checked . if_ b ~ then_ : t . hash ~ else_ : e . hash ; data = V . if_ b ~ then_ : t . data ~ else_ : e . data } let empty = Call_stack_digest ( . constant empty ) empty let is_empty ( { hash = x ; _ } : t ) t = Call_stack_digest . Checked . equal empty x let empty ( ) : t = { hash = empty ; data = V . create ( fun ( ) -> [ ] ) } let exists_elt ( elt_ref : ( Value . frame , _ ) _ With_hash . t V . t ) t : Stack_frame . t = let elt : Stack_frame . frame = let calls : Parties . t = { hash = exists Mina_base . Parties . Digest . Forest . typ ~ compute ( : fun ( ) -> ( V . get elt_ref ) elt_ref . data . calls |> Mina_base . Parties . Call_forest . hash ) ; data = V . map elt_ref ~ f ( : fun frame -> frame . data . calls ) calls } and caller = exists Mina_base . Token_id . typ ~ compute ( : fun ( ) -> ( V . get elt_ref ) elt_ref . data . caller ) and caller_caller = exists Mina_base . Token_id . typ ~ compute ( : fun ( ) -> ( V . get elt_ref ) elt_ref . data . caller_caller ) in { caller ; caller_caller ; calls } in Stack_frame . of_frame elt let pop_exn ( { hash = h ; data = r } : t ) t : elt * t = let hd_r = V . create ( fun ( ) -> ( V . get r |> List . hd_exn ) hd_exn . elt ) elt in let tl_r = V . create ( fun ( ) -> V . get r |> List . tl_exn ) tl_exn in let elt : Stack_frame . t = exists_elt hd_r in let stack = exists Call_stack_digest . typ ~ compute ( : fun ( ) -> hash ( V . get tl_r ) tl_r ) tl_r in let h ' = Call_stack_digest . Checked . cons ( Stack_frame . hash elt ) elt stack in with_label __LOC__ ( fun ( ) -> Call_stack_digest . Checked . Assert . equal h h ' ) ; ( elt , { hash = stack ; data = tl_r } ) let pop ( { hash = h ; data = r } as t : t ) t : ( elt * t ) t Opt . t = let input_is_empty = is_empty t in let hd_r = V . create ( fun ( ) -> match V . get r |> List . hd with | None -> Elt . default ( ) | Some x -> x . elt ) in let tl_r = V . create ( fun ( ) -> V . get r |> List . tl |> Option . value ~ default [ ] ) : in let elt = exists_elt hd_r in let stack = exists Call_stack_digest . typ ~ compute ( : fun ( ) -> hash ( V . get tl_r ) tl_r ) tl_r in let stack_frame_hash = Stack_frame . hash elt in let h ' = Call_stack_digest . Checked . cons stack_frame_hash stack in with_label __LOC__ ( fun ( ) -> Boolean . Assert . any [ input_is_empty ; Call_stack_digest . Checked . equal h h ' ] ) ; { is_some = Boolean . not input_is_empty ; data = ( elt , { hash = stack ; data = tl_r } ) } let read_elt ( frame : elt ) elt : Elt . t = { hash = As_prover . read Mina_base . Stack_frame . Digest . typ ( Stack_frame . hash frame ) frame ; data = { calls = V . get frame . data . calls . data ; caller = As_prover . read Token_id . typ frame . data . caller ; caller_caller = As_prover . read Token_id . typ frame . data . caller_caller } } let push ( elt : elt ) elt ~ onto ( { : hash = h_tl ; data = r_tl } : t ) t : t = let h = Call_stack_digest . Checked . cons ( Stack_frame . hash elt ) elt h_tl in let r = V . create ( fun ( ) : ( Elt . t , Call_stack_digest . t ) t With_stack_hash . t list -> let hd = read_elt elt in let tl = V . get r_tl in { With_stack_hash . stack_hash = As_prover . read Call_stack_digest . typ h ; elt = hd } :: tl ) in { hash = h ; data = r } end module Amount = struct type t = Amount . Checked . t type unsigned = t module Signed = struct type t = Amount . Signed . Checked . t let equal t t ' = run_checked ( Amount . Signed . Checked . equal t t ' ) t ' let if_ b ~ then_ ~ else_ = run_checked ( Amount . Signed . Checked . if_ b ~ then_ ~ else_ ) else_ let is_pos ( t : t ) t = Sgn . Checked . is_pos ( run_checked ( Currency . Amount . Signed . Checked . sgn t ) t ) t let negate = Amount . Signed . Checked . negate let of_unsigned = Amount . Signed . Checked . of_unsigned let add_flagged x y = run_checked ( Amount . Signed . Checked . add_flagged x y ) y end let if_ b ~ then_ ~ else_ = run_checked ( Amount . Checked . if_ b ~ then_ ~ else_ ) else_ let equal t t ' = run_checked ( Amount . Checked . equal t t ' ) t ' let zero = Amount ( . var_of_t zero ) zero let add_flagged x y = run_checked ( Amount . Checked . add_flagged x y ) y let add_signed_flagged ( x : t ) t ( y : Signed . t ) t = run_checked ( Amount . Checked . add_signed_flagged x y ) y let of_constant_fee fee = Amount . var_of_t ( Amount . of_fee fee ) fee end module Token_id = struct type t = Token_id . Checked . t let if_ = Token_id . Checked . if_ let equal x y = Token_id . Checked . equal x y let default = Token_id ( . Checked . constant default ) default end module Public_key = struct type t = Public_key . Compressed . var let if_ b ~ then_ ~ else_ = run_checked ( Public_key . Compressed . Checked . if_ b ~ then_ ~ else_ ) else_ end module Protocol_state_precondition = struct type t = Zkapp_precondition . Protocol_state . Checked . t end module Field = Impl . Field module Local_state = struct type t = ( Stack_frame . t , Call_stack . t , Token_id . t , Amount . Signed . t , Ledger_hash . var * Sparse_ledger . t V . t , Bool . t , Transaction_commitment . t , Bool . failure_status_tbl ) Mina_transaction_logic . Parties_logic . Local_state . t let add_check ( t : t ) t _failure b = { t with success = Bool ( . t . success &&& b ) b } let update_failure_status_tbl ( t : t ) t _failure_status b = add_check ( t : t ) t Transaction_status . Failure . Update_not_permitted_voting_for b let add_new_failure_status_bucket t = t end end module Single ( I : Single_inputs ) Single_inputs = struct open I let { auth_type ; is_start = _ } = spec module V = Prover_value open Impl module Inputs = struct include Inputs module Account = struct include Account let register_verification_key ( { data = a ; _ } : t ) t = Option . iter snapp_statement ~ f ( : fun ( tag , _ ) _ -> let vk = exists Side_loaded_verification_key . typ ~ compute ( : fun ( ) -> Option . value_exn ( As_prover . Ref . get ( Data_as_hash . ref a . zkapp . verification_key . data ) data ) . data ) in let expected_hash = Data_as_hash . hash a . zkapp . verification_key . data in let actual_hash = Zkapp_account . Checked . digest_vk vk in Field . Assert . equal expected_hash actual_hash ; Pickles . Side_loaded . in_circuit ( side_loaded tag ) tag vk ) end module Controller = struct type t = Permissions . Auth_required . Checked . t let if_ = Permissions . Auth_required . Checked . if_ let check = match auth_type with | Proof -> fun ~ proof_verifies : _ ~ signature_verifies : _ perm -> Permissions . Auth_required . Checked . eval_proof perm | Signature | None_given -> fun ~ proof_verifies : _ ~ signature_verifies perm -> Permissions . Auth_required . Checked . eval_no_proof ~ signature_verifies perm end module Ledger = struct type t = Ledger_hash . var * Sparse_ledger . t V . t type inclusion_proof = ( Boolean . var * Field . t ) t list let if_ b ~ then_ ( ( : xt , rt ) rt : t ) t ~ else_ ( ( : xe , re ) re : t ) t = ( run_checked ( Ledger_hash . if_ b ~ then_ : xt ~ else_ : xe ) xe , V . if_ b ~ then_ : rt ~ else_ : re ) let empty ~ depth ( ) : t = let t = Sparse_ledger . empty ~ depth ( ) in ( Ledger_hash . var_of_t ( Sparse_ledger . merkle_root t ) t , V . create ( fun ( ) -> t ) t ) let idx ledger id = Sparse_ledger . find_index_exn ledger id let body_id ( body : Party . Body . Checked . t ) t = let open As_prover in Mina_base . Account_id . create ( read Signature_lib . Public_key . Compressed . typ body . public_key ) public_key ( read Mina_base . Token_id . typ body . token_id ) token_id let get_account { party ; _ } ( ( _root , ledger ) ledger : t ) t = let idx = V . map ledger ~ f ( : fun l -> idx l ( body_id party . data ) data ) data in let account = exists Mina_base . Account . Checked . Unhashed . typ ~ compute ( : fun ( ) -> Sparse_ledger . get_exn ( V . get ledger ) ledger ( V . get idx ) idx ) in let account = Account . account_with_hash account in let incl = exists Typ ( . list ~ length : constraint_constants . ledger_depth ( Boolean . typ * field ) field ) field ~ compute ( : fun ( ) -> List . map ( Sparse_ledger . path_exn ( V . get ledger ) ledger ( V . get idx ) idx ) idx ~ f ( : fun x -> match x with | ` Left h -> ( false , h ) h | ` Right h -> ( true , h ) h ) ) in ( account , incl ) incl let set_account ( ( _root , ledger ) ledger : t ) t ( ( a , incl ) incl : Account . t * _ ) _ : t = ( implied_root a incl |> Ledger_hash . var_of_hash_packed , V . map ledger ~ f : As_prover ( . fun ledger -> let a : Mina_base . Account . t = read Mina_base . Account . Checked . Unhashed . typ a . data in let idx = idx ledger ( Mina_base . Account . identifier a ) a in Sparse_ledger . set_exn ledger idx a ) a ) let check_inclusion ( ( root , _ ) _ : t ) t ( account , incl ) incl = with_label __LOC__ ( fun ( ) -> Field . Assert . equal ( implied_root account incl ) incl ( Ledger_hash . var_to_hash_packed root ) root ) let check_account public_key token_id ( ( { data = account ; _ } , _ ) _ : Account . t * _ ) _ = let is_new = run_checked ( Signature_lib . Public_key . Compressed . Checked . equal account . public_key Signature_lib . Public_key . Compressed ( . var_of_t empty ) empty ) in with_label __LOC__ ( fun ( ) -> Boolean . Assert . any [ is_new ; run_checked ( Signature_lib . Public_key . Compressed . Checked . equal public_key account . public_key ) ] ) ; with_label __LOC__ ( fun ( ) -> Boolean . Assert . any [ is_new ; Token_id . equal token_id account . token_id ] ) ; ` Is_new is_new end module Party = struct type t = party type parties = Parties . t type ' a or_ignore = ' a Zkapp_basic . Or_ignore . Checked . t type transaction_commitment = Transaction_commitment . t let balance_change ( t : t ) t = t . party . data . balance_change let protocol_state_precondition ( t : t ) t = t . party . data . protocol_state_precondition let token_id ( t : t ) t = t . party . data . token_id let public_key ( t : t ) t = t . party . data . public_key let caller ( t : t ) t = t . party . data . caller let account_id ( t : t ) t = Account_id . create ( public_key t ) t ( token_id t ) t let use_full_commitment ( t : t ) t = t . party . data . use_full_commitment let increment_nonce ( t : t ) t = t . party . data . increment_nonce let check_authorization ~ commitment ~ at_party ( { : hash = at_party ; _ } : Parties . t ) t ( { party ; control ; _ } : t ) t = let proof_verifies = match ( auth_type , snapp_statement ) snapp_statement with | Proof , Some ( _i , s ) s -> with_label __LOC__ ( fun ( ) -> Zkapp_statement . Checked . Assert . equal { transaction = commitment ; at_party = ( at_party :> Field . t ) t } s ) ; Boolean . true_ | ( Signature | None_given ) None_given , None -> Boolean . false_ | Proof , None | ( Signature | None_given ) None_given , Some _ -> assert false in let signature_verifies = match auth_type with | None_given | Proof -> Boolean . false_ | Signature -> let signature = exists Signature_lib . Schnorr . Chunked . Signature . typ ~ compute ( : fun ( ) -> match V . get control with | Signature s -> s | None_given -> Signature . dummy | Proof _ -> assert false ) in run_checked ( let % bind ( module S ) S = Tick . Inner_curve . Checked . Shifted . create ( ) in signature_verifies ~ shifted ( : module S ) S ~ payload_digest : commitment signature party . data . public_key ) in ( ` Proof_verifies proof_verifies , ` Signature_verifies signature_verifies ) module Update = struct open Zkapp_basic type ' a set_or_keep = ' a Set_or_keep . Checked . t let timing ( { party ; _ } : t ) t : Account . timing set_or_keep = Set_or_keep . Checked . map ~ f : Party . Update . Timing_info . Checked . to_account_timing party . data . update . timing let app_state ( { party ; _ } : t ) t = party . data . update . app_state let verification_key ( { party ; _ } : t ) t = party . data . update . verification_key let sequence_events ( { party ; _ } : t ) t = party . data . sequence_events let zkapp_uri ( { party ; _ } : t ) t = party . data . update . zkapp_uri let token_symbol ( { party ; _ } : t ) t = party . data . update . token_symbol let delegate ( { party ; _ } : t ) t = party . data . update . delegate let voting_for ( { party ; _ } : t ) t = party . data . update . voting_for let permissions ( { party ; _ } : t ) t = party . data . update . permissions end module Account_precondition = struct let nonce ( { party ; _ } : t ) t = party . data . account_precondition . nonce end end module Set_or_keep = struct include Zkapp_basic . Set_or_keep . Checked end module Global_state = struct include Global_state let fee_excess { fee_excess ; _ } = fee_excess let set_fee_excess t fee_excess = { t with fee_excess } let ledger { ledger ; _ } = ledger let set_ledger ~ should_update t ledger = { t with ledger = Ledger . if_ should_update ~ then_ : ledger ~ else_ : t . ledger } let global_slot_since_genesis { protocol_state ; _ } = protocol_state . global_slot_since_genesis end module Nonce_precondition = struct let is_constant = Zkapp_precondition . Numeric . Checked . is_constant Zkapp_precondition . Numeric . Tc . nonce end let with_label ~ label f = with_label label f end module Env = struct open Inputs type t = < party : Party . t ; account : Account . t ; ledger : Ledger . t ; amount : Amount . t ; signed_amount : Amount . Signed . t ; bool : Bool . t ; token_id : Token_id . t ; global_state : Global_state . t ; inclusion_proof : ( Bool . t * Field . t ) t list ; parties : Parties . t ; local_state : ( Stack_frame . t , Call_stack . t , Token_id . t , Amount . Signed . t , Ledger . t , Bool . t , Transaction_commitment . t , unit ) Mina_transaction_logic . Parties_logic . Local_state . t ; protocol_state_precondition : Zkapp_precondition . Protocol_state . Checked . t ; transaction_commitment : Transaction_commitment . t ; full_transaction_commitment : Transaction_commitment . t ; field : Field . t ; failure : unit > end include Mina_transaction_logic . Parties_logic . Make ( Inputs ) Inputs let perform ( type r ) r ( eff : ( r , Env . t ) t Mina_transaction_logic . Parties_logic . Eff . t ) t : r = match eff with | Check_protocol_state_precondition ( protocol_state_predicate , global_state ) global_state -> Zkapp_precondition . Protocol_state . Checked . check protocol_state_predicate global_state . protocol_state | Check_account_precondition ( { party ; _ } , account , local_state ) local_state -> let local_state = ref local_state in let check failure b = local_state := Inputs . Local_state . add_check ! local_state failure b in Zkapp_precondition . Account . Checked . check ~ check party . data . account_precondition account . data ; ! local_state | Init_account { party = { party ; _ } ; account } -> let account ' : Account . Checked . Unhashed . t = { account . data with public_key = party . data . public_key ; token_id = party . data . token_id } in Inputs . Account . account_with_hash account ' end let check_protocol_state ~ pending_coinbase_stack_init ~ pending_coinbase_stack_before ~ pending_coinbase_stack_after state_body = [ % with_label " Compute pending coinbase stack ] " ( let % bind state_body_hash = Mina_state . Protocol_state . Body . hash_checked state_body in let % bind computed_pending_coinbase_stack_after = Pending_coinbase . Stack . Checked . push_state state_body_hash pending_coinbase_stack_init in [ % with_label " Check pending coinbase stack ] " ( let % bind correct_coinbase_target_stack = Pending_coinbase . Stack . equal_var computed_pending_coinbase_stack_after pending_coinbase_stack_after in let % bind valid_init_state = let % bind equal_source = Pending_coinbase . Stack . equal_var pending_coinbase_stack_init pending_coinbase_stack_before in let % bind equal_source_with_state = Pending_coinbase . Stack . equal_var computed_pending_coinbase_stack_after pending_coinbase_stack_before in Boolean ( . equal_source ||| equal_source_with_state ) equal_source_with_state in Boolean . Assert . all [ correct_coinbase_target_stack ; valid_init_state ] ) ) let main ( ? witness : Witness . t option ) option ( spec : Spec . t ) t ~ constraint_constants snapp_statements ( statement : Statement . With_sok . Checked . t ) t = let open Impl in run_checked ( dummy_constraints ( ) ) ; let ( ! ) x = Option . value_exn x in let state_body = exists ( Mina_state . Protocol_state . Body . typ ~ constraint_constants ) constraint_constants ~ compute ( : fun ( ) -> ! witness . state_body ) state_body in let pending_coinbase_stack_init = exists Pending_coinbase . Stack . typ ~ compute ( : fun ( ) -> ! witness . init_stack ) in let module V = Prover_value in run_checked ( check_protocol_state ~ pending_coinbase_stack_init ~ pending_coinbase_stack_before : statement . source . pending_coinbase_stack ~ pending_coinbase_stack_after : statement . target . pending_coinbase_stack state_body ) ; let init : Global_state . t * _ Mina_transaction_logic . Parties_logic . Local_state . t = let g : Global_state . t = { ledger = ( statement . source . ledger , V . create ( fun ( ) -> ! witness . global_ledger ) global_ledger ) ; fee_excess = Amount . Signed ( . Checked . constant zero ) zero ; protocol_state = Mina_state . Protocol_state . Body . view_checked state_body } in let l : _ Mina_transaction_logic . Parties_logic . Local_state . t = { stack_frame = Inputs . Stack_frame . unhash statement . source . local_state . stack_frame ( V . create ( fun ( ) -> ! witness . local_state_init . stack_frame ) stack_frame ) stack_frame ; call_stack = { With_hash . hash = statement . source . local_state . call_stack ; data = V . create ( fun ( ) -> ! witness . local_state_init . call_stack ) call_stack } ; transaction_commitment = statement . source . local_state . transaction_commitment ; full_transaction_commitment = statement . source . local_state . full_transaction_commitment ; token_id = statement . source . local_state . token_id ; excess = statement . source . local_state . excess ; ledger = ( statement . source . local_state . ledger , V . create ( fun ( ) -> ! witness . local_state_init . ledger ) ledger ) ; success = statement . source . local_state . success ; failure_status_tbl = ( ) } in ( g , l ) l in let start_parties = As_prover . Ref . create ( fun ( ) -> ! witness . start_parties ) start_parties in let ( global , local ) local , snapp_statements = List . fold_left spec ~ init ( : init , snapp_statements ) snapp_statements ~ f ( : fun ( ( ( _ , local ) local as acc ) acc , statements ) statements party_spec -> let snapp_statement , statements = match party_spec . auth_type with | Signature | None_given -> ( None , statements ) statements | Proof -> ( match statements with | [ ] -> assert false | s :: ss -> ( Some s , ss ) ss ) in let module S = Single ( struct let constraint_constants = constraint_constants let spec = party_spec let snapp_statement = snapp_statement end ) end in let finish v = let open Mina_transaction_logic . Parties_logic . Start_data in let ps = V . map v ~ f ( : function | ` Skip -> [ ] | ` Start p -> Parties . parties p . parties |> Parties . Call_forest . map ~ f ( : fun party -> ( party , ( ) ) ) ) in let h = exists Parties . Digest . Forest . typ ~ compute ( : fun ( ) -> Parties . Call_forest . hash ( V . get ps ) ps ) in let start_data = { Mina_transaction_logic . Parties_logic . Start_data . parties = { With_hash . hash = h ; data = ps } ; memo_hash = exists Field . typ ~ compute ( : fun ( ) -> match V . get v with | ` Skip -> Field . Constant . zero | ` Start p -> p . memo_hash ) } in let global_state , local_state = with_label " apply " ( fun ( ) -> S . apply ~ constraint_constants ~ is_start : ( match party_spec . is_start with | ` No -> ` No | ` Yes -> ` Yes start_data | ` Compute_in_circuit -> ` Compute start_data ) S { . perform } acc ) in ( global_state , { local_state with failure_status_tbl = ( ) } ) in let acc ' = match party_spec . is_start with | ` No -> let global_state , local_state = S . apply ~ constraint_constants ~ is_start ` : No S { . perform } acc in ( global_state , { local_state with failure_status_tbl = ( ) } ) | ` Compute_in_circuit -> V . create ( fun ( ) -> match As_prover . Ref . get start_parties with | [ ] -> ` Skip | p :: ps -> let should_pop = Mina_base . Parties . Call_forest . is_empty ( V . get local . stack_frame . data . calls . data ) data in if should_pop then ( As_prover . Ref . set start_parties ps ; ` Start p ) else ` Skip ) |> finish | ` Yes -> as_prover ( fun ( ) -> assert ( Mina_base . Parties . Call_forest . is_empty ( V . get local . stack_frame . data . calls . data ) data ) ) ; V . create ( fun ( ) -> match As_prover . Ref . get start_parties with | [ ] -> assert false | p :: ps -> As_prover . Ref . set start_parties ps ; ` Start p ) |> finish in ( acc ' , statements ) statements ) in with_label __LOC__ ( fun ( ) -> assert ( List . is_empty snapp_statements ) snapp_statements ) snapp_statements ; let local_state_ledger = Stack_frame . Digest . Checked . if_ local . success ~ then_ ( : Inputs . Stack_frame . hash local . stack_frame ) stack_frame ~ else_ : statement . target . local_state . stack_frame in with_label __LOC__ ( fun ( ) -> Local_state . Checked . assert_equal statement . target . local_state { local with stack_frame = local_state_ledger ; call_stack = local . call_stack . hash ; ledger = fst local . ledger } ) ; with_label __LOC__ ( fun ( ) -> run_checked ( Frozen_ledger_hash . assert_equal ( fst global . ledger ) ledger statement . target . ledger ) ) ; with_label __LOC__ ( fun ( ) -> run_checked ( Amount . Checked . assert_equal statement . supply_increase Amount ( . var_of_t zero ) zero ) ) ; with_label __LOC__ ( fun ( ) -> run_checked ( let expected = statement . fee_excess in let got = { fee_token_l = Token_id ( . Checked . constant default ) default ; fee_excess_l = Amount . Signed . Checked . to_fee global . fee_excess ; Fee_excess . fee_token_r = Token_id ( . Checked . constant default ) default ; fee_excess_r = Amount . Signed . Checked . to_fee ( fst init ) init . fee_excess } in Fee_excess . assert_equal_checked expected got ) ) ; let ` Needs_some_work_for_zkapps_on_mainnet = Mina_base . Util . todo_zkapps in ( ) let witness : Witness . t option ref = ref None let rule ( type a b c d ) d ~ constraint_constants ~ proof_level ( t : ( a , b , c , d ) d Basic . t_typed ) t_typed : ( a , b , c , d , Statement . With_sok . var , Statement . With_sok . t ) Pickles . Inductive_rule . t = let open Hlist in let open Basic in let module M = H4 . T ( Pickles . Tag ) Tag in let s = Basic . spec t in let prev_should_verify = match proof_level with | Genesis_constants . Proof_level . Full -> true | _ -> false in let b = Boolean . var_of_value prev_should_verify in match t with | Proved -> { identifier = " proved " ; prevs = M [ . side_loaded 0 ] ; main_value = ( fun [ _ ] _ -> [ prev_should_verify ] ) ; main = ( fun [ snapp_statement ] stmt -> main ? witness :! witness s ~ constraint_constants ( List . mapi [ snapp_statement ] ~ f ( : fun i x -> ( i , x ) x ) x ) x stmt ; [ b ] ) } | Opt_signed_opt_signed -> { identifier = " opt_signed - opt_signed " ; prevs = M [ ] . ; main_value = ( fun [ ] _ -> [ ] ) ; main = ( fun [ ] stmt -> main ? witness :! witness s ~ constraint_constants [ ] stmt ; [ ] ) } | Opt_signed -> { identifier = " opt_signed " ; prevs = M [ ] . ; main_value = ( fun [ ] _ -> [ ] ) ; main = ( fun [ ] stmt -> main ? witness :! witness s ~ constraint_constants [ ] stmt ; [ ] ) } end type _ Snarky_backendless . Request . t += | Transaction : Transaction_union . t Snarky_backendless . Request . t | State_body : Mina_state . Protocol_state . Body . Value . t Snarky_backendless . Request . t | Init_stack : Pending_coinbase . Stack . t Snarky_backendless . Request . t let % snarkydef apply_tagged_transaction ( ~ constraint_constants : Genesis_constants . Constraint_constants . t ) t ( type shifted ) shifted ( shifted : ( module Inner_curve . Checked . Shifted . S with type t = shifted ) shifted ) shifted root pending_coinbase_stack_init pending_coinbase_stack_before pending_coinbase_after state_body ( { signer ; signature ; payload } as txn : Transaction_union . var ) var = let tag = payload . body . tag in let is_user_command = Transaction_union . Tag . Unpacked . is_user_command tag in let % bind ( ) = [ % with_label " Check transaction signature ] " ( check_signature shifted ~ payload ~ is_user_command ~ signer ~ signature ) signature in let % bind signer_pk = Public_key . compress_var signer in let % bind ( ) = [ % with_label " Fee - payer must sign the transaction ] " ( Public_key . Compressed . Checked . Assert . equal signer_pk payload . common . fee_payer_pk ) in let is_payment = Transaction_union . Tag . Unpacked . is_payment tag in let is_mint_tokens = Transaction_union . Tag . Unpacked . is_mint_tokens tag in let is_stake_delegation = Transaction_union . Tag . Unpacked . is_stake_delegation tag in let is_create_account = Transaction_union . Tag . Unpacked . is_create_account tag in let is_fee_transfer = Transaction_union . Tag . Unpacked . is_fee_transfer tag in let is_coinbase = Transaction_union . Tag . Unpacked . is_coinbase tag in let fee_token = payload . common . fee_token in let % bind fee_token_default = make_checked ( fun ( ) -> Token_id ( . Checked . equal fee_token ( Checked . constant default ) default ) default ) in let token = payload . body . token_id in let % bind token_default = make_checked ( fun ( ) -> Token_id ( . Checked . equal token ( Checked . constant default ) default ) default ) in let % bind ( ) = Checked . all_unit [ [ % with_label " Token_locked value is compatible with the transaction kind ] " ( Boolean . Assert . any [ Boolean . not payload . body . token_locked ; is_create_account ] ) ; [ % with_label " Token_locked cannot be used with the default token ] " ( Boolean . Assert . any [ Boolean . not payload . body . token_locked ; Boolean . not token_default ] ) ] in let % bind ( ) = Boolean . Assert . is_true token_default in let % bind ( ) = [ % with_label " Validate tokens ] " ( Checked . all_unit [ [ % with_label " Fee token is default or command allows non - default fee ] " ( Boolean . Assert . any [ fee_token_default ; is_payment ; is_stake_delegation ; is_fee_transfer ] ) ; [ % with_label " Fees in tokens disabled ] " ( Boolean . Assert . is_true fee_token_default ) fee_token_default ; [ % with_label " Command allows default token ] " Boolean ( . Assert . any [ is_payment ; is_stake_delegation ; is_create_account ; is_fee_transfer ; is_coinbase ] ) ] ) in let current_global_slot = Mina_state . Protocol_state . Body . consensus_state state_body |> Consensus . Data . Consensus_state . global_slot_since_genesis_var in let % bind user_command_failure = User_command_failure . compute_as_prover ~ constraint_constants ~ txn_global_slot : current_global_slot txn in let % bind user_command_fails = User_command_failure . any user_command_failure in let fee = payload . common . fee in let receiver = Account_id . Checked . create payload . body . receiver_pk token in let source = Account_id . Checked . create payload . body . source_pk token in let nonce = payload . common . nonce in let fee_payer = Account_id . Checked . create payload . common . fee_payer_pk fee_token in let % bind ( ) = [ % with_label " Check slot validity ] " ( Global_slot . Checked ( . current_global_slot <= payload . common . valid_until ) valid_until >>= Boolean . Assert . is_true ) in let % bind ( ) = [ % with_label " Compute coinbase stack ] " ( let % bind state_body_hash = Mina_state . Protocol_state . Body . hash_checked state_body in let % bind pending_coinbase_stack_with_state = Pending_coinbase . Stack . Checked . push_state state_body_hash pending_coinbase_stack_init in let % bind computed_pending_coinbase_stack_after = let coinbase = ( Account_id . Checked . public_key receiver , payload . body . amount ) amount in let % bind stack ' = Pending_coinbase . Stack . Checked . push_coinbase coinbase pending_coinbase_stack_with_state in Pending_coinbase . Stack . Checked . if_ is_coinbase ~ then_ : stack ' ~ else_ : pending_coinbase_stack_with_state in [ % with_label " Check coinbase stack ] " ( let % bind correct_coinbase_target_stack = Pending_coinbase . Stack . equal_var computed_pending_coinbase_stack_after pending_coinbase_after in let % bind valid_init_state = let % bind equal_source = Pending_coinbase . Stack . equal_var pending_coinbase_stack_init pending_coinbase_stack_before in let % bind equal_source_with_state = Pending_coinbase . Stack . equal_var pending_coinbase_stack_with_state pending_coinbase_stack_before in Boolean ( . equal_source ||| equal_source_with_state ) equal_source_with_state in [ % with_label " target stack and valid init state ] " ( Boolean . Assert . all [ correct_coinbase_target_stack ; valid_init_state ] ) ) ) in let % bind ( ) = [ % with_label " A failing user command is a user command ] " Boolean ( . Assert . any [ is_user_command ; not user_command_fails ] ) in let predicate_deferred = is_create_account in let % bind predicate_result = let % bind is_own_account = Public_key . Compressed . Checked . equal payload . common . fee_payer_pk payload . body . source_pk in let predicate_result = Boolean . false_ in Boolean ( . is_own_account ||| predicate_result ) predicate_result in let % bind ( ) = [ % with_label " Check account_precondition failure against predicted ] " ( let % bind predicate_failed = Boolean ( ( . not predicate_result ) predicate_result &&& not predicate_deferred ) predicate_deferred in assert_r1cs ( predicate_failed :> Field . Var . t ) t ( is_user_command :> Field . Var . t ) t ( user_command_failure . predicate_failed :> Field . Var . t ) t ) in let account_creation_amount = Amount . Checked . of_fee Fee ( . var_of_t constraint_constants . account_creation_fee ) account_creation_fee in let % bind is_zero_fee = Fee ( . equal_var fee ( var_of_t zero ) zero ) zero in let is_coinbase_or_fee_transfer = Boolean . not is_user_command in let % bind can_create_fee_payer_account = let % bind fee_may_be_charged = Boolean ( . token_default ||| is_zero_fee ) is_zero_fee in Boolean ( . is_coinbase_or_fee_transfer &&& fee_may_be_charged ) fee_may_be_charged in let % bind root_after_fee_payer_update = [ % with_label " Update fee payer ] " ( Frozen_ledger_hash . modify_account_send ~ depth : constraint_constants . ledger_depth root ~ is_writeable : can_create_fee_payer_account fee_payer ~ f ( : fun ~ is_empty_and_writeable account -> let % bind next_nonce = Account . Nonce . Checked . succ_if account . nonce is_user_command in let % bind ( ) = [ % with_label " Check fee nonce ] " ( let % bind nonce_matches = Account . Nonce . Checked . equal nonce account . nonce in Boolean . Assert . any [ Boolean . not is_user_command ; nonce_matches ] ) in let % bind receipt_chain_hash = let current = account . receipt_chain_hash in let % bind r = Receipt . Chain_hash . Checked . cons ( Signed_command payload ) payload current in Receipt . Chain_hash . Checked . if_ is_user_command ~ then_ : r ~ else_ : current in let % bind is_empty_and_writeable = Boolean ( . is_empty_and_writeable &&& not is_zero_fee ) is_zero_fee in let % bind should_pay_to_create = let % bind is_create_account = Boolean ( . is_create_account &&& not user_command_fails ) user_command_fails in Boolean ( . is_empty_and_writeable ||| is_create_account ) is_create_account in let % bind amount = [ % with_label " Compute fee payer amount ] " ( let fee_payer_amount = let sgn = Sgn . Checked . neg_if_true is_user_command in Amount . Signed . create_var ~ magnitude ( : Amount . Checked . of_fee fee ) fee ~ sgn in let % bind account_creation_fee = let % map magnitude = Amount . Checked . if_ should_pay_to_create ~ then_ : account_creation_amount ~ else_ : Amount ( . var_of_t zero ) zero in Amount . Signed . create_var ~ magnitude ~ sgn : Sgn . Checked . neg in Amount . Signed . Checked ( . add fee_payer_amount account_creation_fee ) account_creation_fee ) in let txn_global_slot = current_global_slot in let % bind ` Min_balance _ , timing = [ % with_label " Check fee payer timing ] " ( let % bind txn_amount = let % bind sgn = Amount . Signed . Checked . sgn amount in let % bind magnitude = Amount . Signed . Checked . magnitude amount in Amount . Checked . if_ ( Sgn . Checked . is_neg sgn ) sgn ~ then_ : magnitude ~ else_ : Amount ( . var_of_t zero ) zero in let balance_check ok = [ % with_label " Check fee payer balance ] " ( Boolean . Assert . is_true ok ) ok in let timed_balance_check ok = [ % with_label " Check fee payer timed balance ] " ( Boolean . Assert . is_true ok ) ok in check_timing ~ balance_check ~ timed_balance_check ~ account ~ txn_amount ( : Some txn_amount ) txn_amount ~ txn_global_slot ) in let % bind balance = [ % with_label " Check payer balance ] " ( Balance . Checked . add_signed_amount account . balance amount ) amount in let % map public_key = Public_key . Compressed . Checked . if_ is_empty_and_writeable ~ then_ ( : Account_id . Checked . public_key fee_payer ) fee_payer ~ else_ : account . public_key and token_id = make_checked ( fun ( ) -> Token_id . Checked . if_ is_empty_and_writeable ~ then_ ( : Account_id . Checked . token_id fee_payer ) fee_payer ~ else_ : account . token_id ) and delegate = Public_key . Compressed . Checked . if_ is_empty_and_writeable ~ then_ ( : Account_id . Checked . public_key fee_payer ) fee_payer ~ else_ : account . delegate in { Account . Poly . balance ; public_key ; token_id ; token_permissions = account . token_permissions ; token_symbol = account . token_symbol ; nonce = next_nonce ; receipt_chain_hash ; delegate ; voting_for = account . voting_for ; timing ; permissions = account . permissions ; zkapp = account . zkapp ; zkapp_uri = account . zkapp_uri } ) ) in let % bind receiver_increase = [ % with_label " Compute receiver increase ] " ( let % bind base_amount = let % bind zero_transfer = Boolean . any [ is_stake_delegation ; is_create_account ] in Amount . Checked . if_ zero_transfer ~ then_ ( : Amount . var_of_t Amount . zero ) zero ~ else_ : payload . body . amount in let % bind coinbase_receiver_fee = Amount . Checked . if_ is_coinbase ~ then_ ( : Amount . Checked . of_fee fee ) fee ~ else_ ( : Amount . var_of_t Amount . zero ) zero in Amount . Checked . sub base_amount coinbase_receiver_fee ) in let receiver_overflow = ref Boolean . false_ in let % bind root_after_receiver_update = [ % with_label " Update receiver ] " ( Frozen_ledger_hash . modify_account_recv ~ depth : constraint_constants . ledger_depth root_after_fee_payer_update receiver ~ f ( : fun ~ is_empty_and_writeable account -> let % bind is_empty_failure = let % bind must_not_be_empty = Boolean ( . is_stake_delegation ||| is_mint_tokens ) is_mint_tokens in Boolean ( . is_empty_and_writeable &&& must_not_be_empty ) must_not_be_empty in let % bind ( ) = [ % with_label " Receiver existence failure matches predicted ] " ( Boolean . Assert ( . = ) is_empty_failure user_command_failure . receiver_not_present ) in let is_empty_and_writeable = Boolean . Unsafe . of_cvar @@ Field . Var ( . sub ( is_empty_and_writeable :> t ) t ( is_empty_failure :> t ) t ) t in let % bind should_pay_to_create = Boolean ( . is_empty_and_writeable &&& not is_create_account ) is_create_account in let % bind ( ) = [ % with_label " Check whether creation fails due to a non - default token ] " ( let % bind token_should_not_create = Boolean ( . should_pay_to_create &&& Boolean . not token_default ) token_default in let % bind token_cannot_create = Boolean ( . token_should_not_create &&& is_user_command ) is_user_command in let % bind ( ) = [ % with_label " Check that account creation is paid in the default \ token for non - user - commands ] " ( Boolean . Assert ( . = ) token_should_not_create token_cannot_create ) in [ % with_label " equal token_cannot_create ] " ( Boolean . Assert ( . = ) token_cannot_create user_command_failure . token_cannot_create ) ) in let % bind balance = let % bind receiver_amount = let % bind account_creation_amount = Amount . Checked . if_ should_pay_to_create ~ then_ : account_creation_amount ~ else_ : Amount ( . var_of_t zero ) zero in let % bind amount_for_new_account , ` Underflow underflow = Amount . Checked . sub_flagged receiver_increase account_creation_amount in let % bind ( ) = [ % with_label " Receiver creation fee failure matches predicted ] " ( Boolean . Assert ( . = ) underflow user_command_failure . amount_insufficient_to_create ) in Currency . Amount . Checked . if_ user_command_fails ~ then_ : Amount ( . var_of_t zero ) zero ~ else_ : amount_for_new_account in let % bind balance , ` Overflow overflow = Balance . Checked . add_amount_flagged account . balance receiver_amount in let % bind ( ) = [ % with_label " Overflow error only occurs in user commands ] " Boolean ( . Assert . any [ is_user_command ; not overflow ] ) in receiver_overflow := overflow ; Balance . Checked . if_ overflow ~ then_ : account . balance ~ else_ : balance in let % bind user_command_fails = Boolean ( . ! receiver_overflow ||| user_command_fails ) user_command_fails in let % bind is_empty_and_writeable = Boolean ( . is_empty_and_writeable &&& not user_command_fails ) user_command_fails in let % bind may_delegate = Boolean ( . is_empty_and_writeable &&& token_default ) token_default in let % map delegate = Public_key . Compressed . Checked . if_ may_delegate ~ then_ ( : Account_id . Checked . public_key receiver ) receiver ~ else_ : account . delegate and public_key = Public_key . Compressed . Checked . if_ is_empty_and_writeable ~ then_ ( : Account_id . Checked . public_key receiver ) receiver ~ else_ : account . public_key and token_id = make_checked ( fun ( ) -> Token_id . Checked . if_ is_empty_and_writeable ~ then_ : token ~ else_ : account . token_id ) and token_owner = Boolean . if_ is_empty_and_writeable ~ then_ : Boolean . false_ ~ else_ : account . token_permissions . token_owner and token_locked = Boolean . if_ is_empty_and_writeable ~ then_ : payload . body . token_locked ~ else_ : account . token_permissions . token_locked in { Account . Poly . balance ; public_key ; token_id ; token_permissions = { Token_permissions . token_owner ; token_locked } ; token_symbol = account . token_symbol ; nonce = account . nonce ; receipt_chain_hash = account . receipt_chain_hash ; delegate ; voting_for = account . voting_for ; timing = account . timing ; permissions = account . permissions ; zkapp = account . zkapp ; zkapp_uri = account . zkapp_uri } ) ) in let % bind user_command_fails = Boolean ( . ! receiver_overflow ||| user_command_fails ) user_command_fails in let % bind fee_payer_is_source = Account_id . Checked . equal fee_payer source in let % bind root_after_source_update = [ % with_label " Update source ] " ( Frozen_ledger_hash . modify_account_send ~ depth : constraint_constants . ledger_depth ~ is_writeable : user_command_failure . source_not_present root_after_receiver_update source ~ f ( : fun ~ is_empty_and_writeable account -> let % bind ( ) = [ % with_label " Check source presence failure matches predicted ] " ( Boolean . Assert ( . = ) is_empty_and_writeable user_command_failure . source_not_present ) in let % bind ( ) = [ % with_label " Check source failure cases do not apply when fee - payer is \ source ] " ( let num_failures = let open Field . Var in add ( user_command_failure . source_insufficient_balance :> t ) t ( user_command_failure . source_bad_timing :> t ) t in let not_fee_payer_is_source = ( Boolean . not fee_payer_is_source :> Field . Var . t ) t in [ % with_label " Check num_failures ] " ( assert_r1cs not_fee_payer_is_source num_failures num_failures ) ) in let % bind amount = if_ is_payment ~ typ : Amount . typ ~ then_ : payload . body . amount ~ else_ : Amount ( . var_of_t zero ) zero in let txn_global_slot = current_global_slot in let % bind ` Min_balance _ , timing = [ % with_label " Check source timing ] " ( let balance_check ok = [ % with_label " Check source balance failure matches predicted ] " ( Boolean . Assert ( . = ) ok ( Boolean . not user_command_failure . source_insufficient_balance ) ) in let timed_balance_check ok = [ % with_label " Check source timed balance failure matches predicted ] " ( let % bind not_ok = Boolean ( . ( not ok ) ok &&& not user_command_failure . source_insufficient_balance ) source_insufficient_balance in Boolean . Assert ( . = ) not_ok user_command_failure . source_bad_timing ) in check_timing ~ balance_check ~ timed_balance_check ~ account ~ txn_amount ( : Some amount ) amount ~ txn_global_slot ) in let % bind balance , ` Underflow underflow = Balance . Checked . sub_amount_flagged account . balance amount in let % bind ( ) = [ % with_label " Check source balance failure matches predicted ] " ( Boolean . Assert ( . = ) underflow user_command_failure . source_insufficient_balance ) in let % map delegate = Public_key . Compressed . Checked . if_ is_stake_delegation ~ then_ ( : Account_id . Checked . public_key receiver ) receiver ~ else_ : account . delegate in { Account . Poly . balance ; public_key = account . public_key ; token_id = account . token_id ; token_permissions = account . token_permissions ; token_symbol = account . token_symbol ; nonce = account . nonce ; receipt_chain_hash = account . receipt_chain_hash ; delegate ; voting_for = account . voting_for ; timing ; permissions = account . permissions ; zkapp = account . zkapp ; zkapp_uri = account . zkapp_uri } ) ) in let % bind fee_excess = let open Amount in chain Signed . Checked . if_ is_coinbase ~ then_ ( : return ( Signed . Checked . of_unsigned ( var_of_t zero ) zero ) zero ) zero ~ else_ : ( let user_command_excess = Signed . Checked . of_unsigned ( Checked . of_fee payload . common . fee ) fee in let % bind fee_transfer_excess , fee_transfer_excess_overflowed = let % map magnitude , ` Overflow overflowed = Checked ( . add_flagged payload . body . amount ( of_fee payload . common . fee ) fee ) fee in ( Signed . create_var ~ magnitude ~ sgn : Sgn . Checked . neg , overflowed ) overflowed in let % bind ( ) = [ % with_label " Fee excess does not overflow ] " Boolean ( . Assert . any [ not is_fee_transfer ; not fee_transfer_excess_overflowed ] ) in Signed . Checked . if_ is_fee_transfer ~ then_ : fee_transfer_excess ~ else_ : user_command_excess ) in let % bind supply_increase = Amount . Checked . if_ is_coinbase ~ then_ : payload . body . amount ~ else_ : Amount ( . var_of_t zero ) zero in let % map final_root = Frozen_ledger_hash . if_ user_command_fails ~ then_ : root_after_fee_payer_update ~ else_ : root_after_source_update in ( final_root , fee_excess , supply_increase ) supply_increase let % snarkydef main ~ constraint_constants ( statement : Statement . With_sok . Checked . t ) t = let % bind ( ) = dummy_constraints ( ) in let % bind ( module Shifted ) Shifted = Tick . Inner_curve . Checked . Shifted . create ( ) in let % bind t = with_label __LOC__ ( exists Transaction_union . typ ~ request ( : As_prover . return Transaction ) Transaction ) Transaction in let % bind pending_coinbase_init = exists Pending_coinbase . Stack . typ ~ request ( : As_prover . return Init_stack ) Init_stack in let % bind state_body = exists ( Mina_state . Protocol_state . Body . typ ~ constraint_constants ) constraint_constants ~ request ( : As_prover . return State_body ) State_body in let % bind root_after , fee_excess , supply_increase = apply_tagged_transaction ~ constraint_constants ( module Shifted ) Shifted statement . source . ledger pending_coinbase_init statement . source . pending_coinbase_stack statement . target . pending_coinbase_stack state_body t in let % bind fee_excess = let % bind fee_excess_zero = Amount . Signed . Checked . equal fee_excess Amount . Signed ( . Checked . constant zero ) zero in let % map fee_token_l = make_checked ( fun ( ) -> Token_id . Checked . if_ fee_excess_zero ~ then_ : Token_id ( . Checked . constant default ) default ~ else_ : t . payload . common . fee_token ) in { Fee_excess . fee_token_l ; fee_excess_l = Amount . Signed . Checked . to_fee fee_excess ; fee_token_r = Token_id ( . Checked . constant default ) default ; fee_excess_r = Fee . Signed ( . Checked . constant zero ) zero } in let % bind ( ) = [ % with_label " local state check ] " ( make_checked ( fun ( ) -> Local_state . Checked . assert_equal statement . source . local_state statement . target . local_state ) ) in Checked . all_unit [ [ % with_label " equal roots ] " ( Frozen_ledger_hash . assert_equal root_after statement . target . ledger ) ledger ; [ % with_label " equal supply_increases ] " ( Currency . Amount . Checked . assert_equal supply_increase statement . supply_increase ) ; [ % with_label " equal fee excesses ] " ( Fee_excess . assert_equal_checked fee_excess statement . fee_excess ) fee_excess ] let rule ~ constraint_constants : _ Pickles . Inductive_rule . t = { identifier = " transaction " ; prevs = [ ] ; main = ( fun [ ] x -> Run . run_checked ( main ~ constraint_constants x ) x ; [ ] ) ; main_value = ( fun [ ] _ -> [ ] ) } let transaction_union_handler handler ( transaction : Transaction_union . t ) t ( state_body : Mina_state . Protocol_state . Body . Value . t ) t ( init_stack : Pending_coinbase . Stack . t ) t : Snarky_backendless . Request . request -> _ = fun ( With { request ; respond } as r ) r -> match request with | Transaction -> respond ( Provide transaction ) transaction | State_body -> respond ( Provide state_body ) state_body | Init_stack -> respond ( Provide init_stack ) init_stack | _ -> handler r end
module Transition_data = struct type t = { proof : Proof_type . t ; supply_increase : Amount . t ; fee_excess : Fee_excess . t ; sok_digest : Sok_message . Digest . t ; pending_coinbase_stack_state : Pending_coinbase_stack_state . t } [ @@ deriving fields ] fields end
module Merge = struct open Tick let % snarkydef main ( [ s1 ; s2 ] : ( Statement . With_sok . var * ( Statement . With_sok . var * _ ) _ ) _ Pickles_types . Hlist . HlistId . t ) ( s : Statement . With_sok . Checked . t ) t = let % bind fee_excess = Fee_excess . combine_checked s1 . Statement . fee_excess s2 . Statement . fee_excess in let % bind ( ) = with_label __LOC__ ( let % bind valid_pending_coinbase_stack_transition = Pending_coinbase . Stack . Checked . check_merge ~ transition1 : ( s1 . source . pending_coinbase_stack , s1 . target . pending_coinbase_stack ) ~ transition2 : ( s2 . source . pending_coinbase_stack , s2 . target . pending_coinbase_stack ) in Boolean . Assert . is_true valid_pending_coinbase_stack_transition ) in let % bind supply_increase = Amount . Checked . add s1 . supply_increase s2 . supply_increase in let % bind ( ) = make_checked ( fun ( ) -> Local_state . Checked . assert_equal s . source . local_state s1 . source . local_state ; Local_state . Checked . assert_equal s . target . local_state s2 . target . local_state ) in Checked . all_unit [ [ % with_label " equal fee excesses ] " ( Fee_excess . assert_equal_checked fee_excess s . fee_excess ) fee_excess ; [ % with_label " equal supply increases ] " ( Amount . Checked . assert_equal supply_increase s . supply_increase ) supply_increase ; [ % with_label " equal source ledger hashes ] " ( Frozen_ledger_hash . assert_equal s . source . ledger s1 . source . ledger ) ledger ; [ % with_label " equal target , source ledger hashes ] " ( Frozen_ledger_hash . assert_equal s1 . target . ledger s2 . source . ledger ) ledger ; [ % with_label " equal target ledger hashes ] " ( Frozen_ledger_hash . assert_equal s2 . target . ledger s . target . ledger ) ledger ] let rule ~ proof_level self : _ Pickles . Inductive_rule . t = let prev_should_verify = match proof_level with | Genesis_constants . Proof_level . Full -> true | _ -> false in let b = Boolean . var_of_value prev_should_verify in { identifier = " merge " ; prevs = [ self ; self ] ; main = ( fun ps x -> Run . run_checked ( main ps x ) x ; [ b ; b ] ) ; main_value = ( fun _ _ -> [ prev_should_verify ; prev_should_verify ] ) } end
type tag = ( Statement . With_sok . Checked . t , Statement . With_sok . t , Nat . N2 . n , Nat . N5 . n ) Pickles . Tag . t
let time lab f = let start = Time . now ( ) in let x = f ( ) in let stop = Time . now ( ) in printf " % s : % s \ n " %! lab ( Time . Span . to_string_hum ( Time . diff stop start ) start ) start ; x
let system ~ proof_level ~ constraint_constants = time " Transaction_snark . system " ( fun ( ) -> Pickles . compile ~ cache : Cache_dir . cache ( module Statement . With_sok . Checked ) Checked ( module Statement . With_sok ) With_sok ~ typ : Statement . With_sok . typ ~ branches ( : module Nat . N5 ) N5 ~ max_proofs_verified ( : module Nat . N2 ) N2 ~ name " : transaction - snark " ~ constraint_constants : ( Genesis_constants . Constraint_constants . to_snark_keys_header constraint_constants ) ~ choices ( : fun ~ self -> let parties x = Base . Parties_snark . rule ~ constraint_constants ~ proof_level x in [ Base . rule ~ constraint_constants ; Merge . rule ~ proof_level self ; parties Opt_signed_opt_signed ; parties Opt_signed ; parties Proved ] ) )
module Verification = struct module type S = sig val tag : tag val verify : ( t * Sok_message . t ) t list -> bool Async . Deferred . t val id : Pickles . Verification_key . Id . t Lazy . t val verification_key : Pickles . Verification_key . t Lazy . t val verify_against_digest : t -> bool Async . Deferred . t val constraint_system_digests : ( string * Md5_lib . t ) t list Lazy . t end end
module type S = sig include Verification . S val constraint_constants : Genesis_constants . Constraint_constants . t val cache_handle : Pickles . Cache_handle . t val of_non_parties_transaction : statement : Statement . With_sok . t -> init_stack : Pending_coinbase . Stack . t -> Transaction . Valid . t Transaction_protocol_state . t -> Tick . Handler . t -> t Async . Deferred . t val of_user_command : statement : Statement . With_sok . t -> init_stack : Pending_coinbase . Stack . t -> Signed_command . With_valid_signature . t Transaction_protocol_state . t -> Tick . Handler . t -> t Async . Deferred . t val of_fee_transfer : statement : Statement . With_sok . t -> init_stack : Pending_coinbase . Stack . t -> Fee_transfer . t Transaction_protocol_state . t -> Tick . Handler . t -> t Async . Deferred . t val of_parties_segment_exn : statement : Statement . With_sok . t -> snapp_statement ( : int * Zkapp_statement . t ) t option -> witness : Parties_segment . Witness . t -> spec : Parties_segment . Basic . t -> t Async . Deferred . t val merge : t -> t -> sok_digest : Sok_message . Digest . t -> t Async . Deferred . Or_error . t end
let check_transaction_union ( ? preeval = false ) false ~ constraint_constants sok_message source target init_stack pending_coinbase_stack_state transaction state_body handler = if preeval then failwith " preeval currently disabled " ; let sok_digest = Sok_message . digest sok_message in let handler = Base . transaction_union_handler handler transaction state_body init_stack in let statement : Statement . With_sok . t = Statement . Poly . with_empty_local_state ~ source ~ target ~ supply_increase ( : Transaction_union . supply_increase transaction ) transaction ~ pending_coinbase_stack_state ~ fee_excess ( : Transaction_union . fee_excess transaction ) transaction ~ sok_digest in let open Tick in ignore ( Or_error . ok_exn ( run_and_check ( handle ( Checked . map ~ f : As_prover . return ( let open Checked in exists Statement . With_sok . typ ~ compute ( : As_prover . return statement ) statement >>= Base . main ~ constraint_constants ) constraint_constants ) handler ) ) : unit )
let check_transaction ? preeval ~ constraint_constants ~ sok_message ~ source ~ target ~ init_stack ~ pending_coinbase_stack_state ~ zkapp_account1 : _ ~ zkapp_account2 : _ ( transaction_in_block : Transaction . Valid . t Transaction_protocol_state . t ) t handler = let transaction = Transaction_protocol_state . transaction transaction_in_block in let state_body = Transaction_protocol_state . block_data transaction_in_block in match to_preunion ( transaction :> Transaction . t ) t with | ` Parties _ -> failwith " Called non - party transaction with parties transaction " | ` Transaction t -> check_transaction_union ? preeval ~ constraint_constants sok_message source target init_stack pending_coinbase_stack_state ( Transaction_union . of_transaction t ) t state_body handler
let check_user_command ~ constraint_constants ~ sok_message ~ source ~ target ~ init_stack ~ pending_coinbase_stack_state t_in_block handler = let user_command = Transaction_protocol_state . transaction t_in_block in check_transaction ~ constraint_constants ~ sok_message ~ source ~ target ~ init_stack ~ pending_coinbase_stack_state ~ zkapp_account1 : None ~ zkapp_account2 : None { t_in_block with transaction = Command ( Signed_command user_command ) user_command } handler
let generate_transaction_union_witness ( ? preeval = false ) false ~ constraint_constants sok_message source target transaction_in_block init_stack pending_coinbase_stack_state handler = if preeval then failwith " preeval currently disabled " ; let transaction = Transaction_protocol_state . transaction transaction_in_block in let state_body = Transaction_protocol_state . block_data transaction_in_block in let sok_digest = Sok_message . digest sok_message in let handler = Base . transaction_union_handler handler transaction state_body init_stack in let statement : Statement . With_sok . t = Statement . Poly . with_empty_local_state ~ source ~ target ~ supply_increase ( : Transaction_union . supply_increase transaction ) transaction ~ pending_coinbase_stack_state ~ fee_excess ( : Transaction_union . fee_excess transaction ) transaction ~ sok_digest in let open Tick in let main x = handle ( Base . main ~ constraint_constants x ) x handler in generate_auxiliary_input [ Statement . With_sok . typ ] ~ return_typ ( : Snarky_backendless . Typ . unit ( ) ) main statement
let generate_transaction_witness ? preeval ~ constraint_constants ~ sok_message ~ source ~ target ~ init_stack ~ pending_coinbase_stack_state ~ zkapp_account1 : _ ~ zkapp_account2 : _ ( transaction_in_block : Transaction . Valid . t Transaction_protocol_state . t ) t handler = match to_preunion ( Transaction_protocol_state . transaction transaction_in_block :> Transaction . t ) with | ` Parties _ -> failwith " Called non - party transaction with parties transaction " | ` Transaction t -> generate_transaction_union_witness ? preeval ~ constraint_constants sok_message source target { transaction_in_block with transaction = Transaction_union . of_transaction t } init_stack pending_coinbase_stack_state handler
let verify ( ts : ( t * _ ) _ list ) list ~ key = if List . for_all ts ~ f ( : fun ( { statement ; _ } , message ) message -> Sok_message . Digest . equal ( Sok_message . digest message ) message statement . sok_digest ) then Pickles . verify ( module Nat . N2 ) N2 ( module Statement . With_sok ) With_sok key ( List . map ts ~ f ( : fun ( { statement ; proof } , _ ) _ -> ( statement , proof ) proof ) proof ) proof else Async . return false
let constraint_system_digests ~ constraint_constants ( ) = let digest = Tick . R1CS_constraint_system . digest in [ ( " transaction - merge " , digest Merge ( . Tick . constraint_system ~ exposing [ : Statement . With_sok . typ ] ~ return_typ ( : Snarky_backendless . Typ . unit ( ) ) ( fun x -> let open Tick in let % bind x1 = exists Statement . With_sok . typ in let % bind x2 = exists Statement . With_sok . typ in main [ x1 ; x2 ] x ) ) ) ; ( " transaction - base " , digest Base ( . Tick . constraint_system ~ exposing [ : Statement . With_sok . typ ] ~ return_typ ( : Snarky_backendless . Typ . unit ( ) ) ( main ~ constraint_constants ) constraint_constants ) constraint_constants ) ]
type local_state = ( Stack_frame . value , Stack_frame . value list , Token_id . t , Currency . Amount . Signed . t , Sparse_ledger . t , bool , unit , Transaction_status . Failure . Collection . t ) Mina_transaction_logic . Parties_logic . Local_state . t
module Parties_intermediate_state = struct type state = { global : global_state ; local : local_state } type t = { kind : [ ` Same | ` New | ` Two_new ] ; spec : Parties_segment . Basic . t ; state_before : state ; state_after : state ; use_full_commitment : [ ` Others | ` Proved_use_full_commitment of bool ] } end
let group_by_parties_rev ( partiess : Party . t list list ) list ( stmtss : ( global_state * local_state ) local_state list list ) list : Parties_intermediate_state . t list = let use_full_commitment ( p : Party . t ) t = match p . authorization with | Proof _ -> ` Proved_use_full_commitment p . body . use_full_commitment | _ -> ` Others in let intermediate_state p ~ kind ~ spec ~ before ~ after = { Parties_intermediate_state . kind ; spec ; state_before = { global = fst before ; local = snd before } ; state_after = { global = fst after ; local = snd after } ; use_full_commitment = use_full_commitment p } in let rec group_by_parties_rev ( partiess : Party . t list list ) list stmtss acc = match ( partiess , stmtss ) stmtss with | ( [ ] | [ [ ] ] ) , [ _ ] -> acc | [ [ ( { authorization = a1 ; _ } as p ) p ] ] , [ [ before ; after ] ] -> intermediate_state p ~ kind ` : Same ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc | [ [ ] ; [ ( { authorization = a1 ; _ } as p ) p ] ] , [ [ _ ] ; [ before ; after ] ] -> intermediate_state p ~ kind ` : New ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc | ( ( ( { authorization = Proof _ as a1 ; _ } as p ) p :: parties ) parties :: partiess , ( before :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : Same ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc ) | ( [ ] :: ( ( { authorization = Proof _ as a1 ; _ } as p ) p :: parties ) parties :: partiess , [ _ ] :: ( before :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : New ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc ) | ( ( ( { authorization = a1 ; _ } as p ) p :: ( { authorization = Proof _ ; _ } :: _ as parties ) parties ) :: partiess , ( before :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : Same ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc ) | ( ( ( { authorization = a1 ; _ } as p ) p :: ( [ ] as parties ) parties ) parties :: ( ( { authorization = Proof _ ; _ } :: _ ) _ :: _ as partiess ) partiess , ( before :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : Same ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc ) | ( ( ( { authorization = ( Signature _ | None_given ) None_given as a1 ; _ } as p ) p :: { authorization = ( Signature _ | None_given ) None_given as a2 ; _ } :: parties ) :: partiess , ( before :: _ :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : Same ~ spec ( : Parties_segment . Basic . of_controls [ a1 ; a2 ] ) ~ before ~ after :: acc ) | ( [ ] :: ( ( { authorization = a1 ; _ } as p ) p :: ( { authorization = Proof _ ; _ } :: _ as parties ) parties ) :: partiess , [ _ ] :: ( before :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : New ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc ) | ( [ ] :: ( ( { authorization = ( Signature _ | None_given ) None_given as a1 ; _ } as p ) p :: { authorization = ( Signature _ | None_given ) None_given as a2 ; _ } :: parties ) :: partiess , [ _ ] :: ( before :: _ :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : New ~ spec ( : Parties_segment . Basic . of_controls [ a1 ; a2 ] ) ~ before ~ after :: acc ) | ( [ ( { authorization = ( Signature _ | None_given ) None_given as a1 ; _ } as p ) p ] :: ( { authorization = ( Signature _ | None_given ) None_given as a2 ; _ } :: parties ) parties :: partiess , ( before :: _after1 ) _after1 :: ( _before2 :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : New ~ spec ( : Parties_segment . Basic . of_controls [ a1 ; a2 ] ) ~ before ~ after :: acc ) | ( [ ] :: ( ( { authorization = a1 ; _ } as p ) p :: parties ) parties :: ( ( { authorization = Proof _ ; _ } :: _ ) _ :: _ as partiess ) partiess , [ _ ] :: ( before :: ( [ after ] as stmts ) stmts ) stmts :: ( _ :: _ as stmtss ) stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : New ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc ) | ( [ ] :: [ ( { authorization = ( Signature _ | None_given ) None_given as a1 ; _ } as p ) p ] :: ( { authorization = ( Signature _ | None_given ) None_given as a2 ; _ } :: parties ) :: partiess , [ _ ] :: [ before ; _after1 ] :: ( _before2 :: ( after :: _ as stmts ) stmts ) stmts :: stmtss ) -> group_by_parties_rev ( parties :: partiess ) partiess ( stmts :: stmtss ) stmtss ( intermediate_state p ~ kind ` : Two_new ~ spec ( : Parties_segment . Basic . of_controls [ a1 ; a2 ] ) ~ before ~ after :: acc ) | [ [ ( { authorization = a1 ; _ } as p ) p ] ] , ( before :: after :: _ ) _ :: _ -> intermediate_state p ~ kind ` : Same ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc | ( [ ] :: [ ( { authorization = a1 ; _ } as p ) p ] :: [ ] :: _ , [ _ ] :: ( before :: after :: _ ) _ :: _ ) -> intermediate_state p ~ kind ` : New ~ spec ( : Parties_segment . Basic . of_controls [ a1 ] ) ~ before ~ after :: acc | _ , [ ] -> failwith " group_by_parties_rev : No statements remaining " | ( [ ] | [ [ ] ] ) , _ -> failwith " group_by_parties_rev : Unmatched statements remaining " | [ ] :: _ , [ ] :: _ -> failwith " group_by_parties_rev : No final statement for current transaction " | [ ] :: _ , ( _ :: _ :: _ ) _ :: _ -> failwith " group_by_parties_rev : Unmatched statements for current transaction " | [ ] :: [ _ ] :: _ , [ _ ] :: ( _ :: _ :: _ :: _ ) _ :: _ -> failwith " group_by_parties_rev : Unmatched statements for next transaction " | [ [ ] ; [ _ ] ] , [ _ ] :: [ _ ; _ ] :: _ :: _ -> failwith " group_by_parties_rev : Unmatched statements after next transaction " | ( _ :: _ ) _ :: _ , ( [ ] | [ _ ] ) :: _ | ( _ :: _ :: _ ) _ :: _ , [ _ ; _ ] :: _ -> failwith " group_by_parties_rev : Too few statements remaining for the current \ transaction " | ( [ ] | [ _ ] ) :: [ ] :: _ , _ -> failwith " group_by_parties_rev : The next transaction has no parties " | [ ] :: ( _ :: _ ) _ :: _ , _ :: ( [ ] | [ _ ] ) :: _ | [ ] :: ( _ :: _ :: _ ) _ :: _ , _ :: [ _ ; _ ] :: _ -> failwith " group_by_parties_rev : Too few statements remaining for the next \ transaction " | [ _ ] :: ( _ :: _ ) _ :: _ , _ :: ( [ ] | [ _ ] ) :: _ -> failwith " group_by_parties_rev : Too few statements remaining for the next \ transaction " | [ ] :: [ _ ] :: ( _ :: _ ) _ :: _ , _ :: _ :: ( [ ] | [ _ ] ) :: _ -> failwith " group_by_parties_rev : Too few statements remaining for the \ transaction after next " | ( [ ] | [ _ ] ) :: ( _ :: _ ) _ :: _ , [ _ ] -> failwith " group_by_parties_rev : No statements given for the next transaction " | [ ] :: [ _ ] :: ( _ :: _ ) _ :: _ , [ _ ; _ :: _ :: _ ] -> failwith " group_by_parties_rev : No statements given for transaction after next " in group_by_parties_rev partiess stmtss [ ]
let rec accumulate_call_stack_hashes ( ~ hash_frame : ' frame -> Stack_frame . Digest . t ) t ( frames : ' frame list ) list : ( ' frame , Call_stack_digest . t ) t With_stack_hash . t list = match frames with | [ ] -> [ ] | f :: fs -> let h_f = hash_frame f in let tl = accumulate_call_stack_hashes ~ hash_frame fs in let h_tl = match tl with [ ] -> Call_stack_digest . empty | t :: _ -> t . stack_hash in { stack_hash = Call_stack_digest . cons h_f h_tl ; elt = f } :: tl
let parties_witnesses_exn ~ constraint_constants ~ state_body ~ fee_excess ledger ( partiess : ( [ ` Pending_coinbase_init_stack of Pending_coinbase . Stack . t ] * [ ` Pending_coinbase_of_statement of Pending_coinbase_stack_state . t ] * Parties . t ) list ) = let sparse_ledger = match ledger with | ` Ledger ledger -> Sparse_ledger . of_ledger_subset_exn ledger ( List . concat_map ~ f ( : fun ( _ , _ , parties ) parties -> Parties . accounts_accessed parties ) parties partiess ) | ` Sparse_ledger sparse_ledger -> sparse_ledger in let state_view = Mina_state . Protocol_state . Body . view state_body in let _ , _ , states_rev = List . fold_left ~ init ( : fee_excess , sparse_ledger , [ ] ) partiess ~ f ( : fun ( fee_excess , sparse_ledger , statess_rev ) statess_rev ( _ , _ , parties ) parties -> let _ , states = Sparse_ledger . apply_parties_unchecked_with_states sparse_ledger ~ constraint_constants ~ state_view ~ fee_excess parties |> Or_error . ok_exn in let final_state = fst ( List . last_exn states ) states in ( final_state . fee_excess , final_state . ledger , states :: statess_rev ) statess_rev ) in let states = List . rev states_rev in let states_rev = group_by_parties_rev ( [ ] :: List . map ~ f ( : fun ( _ , _ , parties ) parties -> Parties . parties_list parties ) parties partiess ) ( [ List . hd_exn ( List . hd_exn states ) states ] :: states ) states in let tx_statement commitment full_commitment use_full_commitment ( remaining_parties : ( Party . t , _ , _ ) _ Parties . Call_forest . t ) t : Zkapp_statement . t = let at_party = Parties . Call_forest ( . hash ( accumulate_hashes ' remaining_parties ) remaining_parties ) remaining_parties in let transaction = match use_full_commitment with | ` Proved_use_full_commitment b -> if b then full_commitment else commitment | _ -> failwith " Expected ` Proof for party that has a proof " in { transaction ; at_party = ( at_party :> Field . t ) t } in let commitment = ref ( Local_state . dummy ( ) ) . transaction_commitment in let full_commitment = ref ( Local_state . dummy ( ) ) . full_transaction_commitment in let remaining_parties = let partiess = List . map partiess ~ f ( : fun ( pending_coinbase_init_stack , pending_coinbase_stack_state , parties ) parties -> ( pending_coinbase_init_stack , pending_coinbase_stack_state , { Mina_transaction_logic . Parties_logic . Start_data . parties ; memo_hash = Signed_command_memo . hash parties . memo } ) ) in ref partiess in let pending_coinbase_init_stack = ref Pending_coinbase . Stack . empty in let pending_coinbase_stack_state = ref { Pending_coinbase_stack_state . source = Pending_coinbase . Stack . empty ; target = Pending_coinbase . Stack . empty } in let final_ledger = match states_rev with | [ ] -> sparse_ledger | { Parties_intermediate_state . state_after = { global = { ledger ; _ } ; _ } ; _ } :: _ -> ledger in ( List . fold_right states_rev ~ init [ ] : ~ f ( : fun { Parties_intermediate_state . kind ; spec ; state_before = { global = source_global ; local = source_local } ; state_after = { global = target_global ; local = target_local } ; use_full_commitment } witnesses -> let source_local = { source_local with failure_status_tbl = [ ] } in let target_local = { target_local with failure_status_tbl = [ ] } in let current_commitment = ! commitment in let current_full_commitment = ! full_commitment in let snapp_stmt = match spec with | Proved -> Some ( 0 , tx_statement current_commitment current_full_commitment use_full_commitment source_local . stack_frame . calls ) | _ -> None in let ( start_parties , next_commitment , next_full_commitment , pending_coinbase_init_stack , pending_coinbase_stack_state ) = let empty_if_last ( mk : unit -> field * field ) field : field * field = match ( target_local . stack_frame . calls , target_local . call_stack ) call_stack with | [ ] , [ ] -> Parties . Transaction_commitment ( . empty , empty ) empty | _ -> mk ( ) in let mk_next_commitments ( parties : Parties . t ) t = empty_if_last ( fun ( ) -> let next_commitment = Parties . commitment parties in let memo_hash = Signed_command_memo . hash parties . memo in let fee_payer_hash = Parties . Digest . Party . create ( Party . of_fee_payer parties . fee_payer ) fee_payer in let next_full_commitment = Parties . Transaction_commitment . create_complete next_commitment ~ memo_hash ~ fee_payer_hash in ( next_commitment , next_full_commitment ) next_full_commitment ) in match kind with | ` Same -> let next_commitment , next_full_commitment = empty_if_last ( fun ( ) -> ( current_commitment , current_full_commitment ) current_full_commitment ) in ( [ ] , next_commitment , next_full_commitment , ! pending_coinbase_init_stack , ! pending_coinbase_stack_state ) | ` New -> ( match ! remaining_parties with | ( ` Pending_coinbase_init_stack pending_coinbase_init_stack1 , ` Pending_coinbase_of_statement pending_coinbase_stack_state1 , parties ) :: rest -> let commitment ' , full_commitment ' = mk_next_commitments parties . parties in remaining_parties := rest ; commitment := commitment ' ; full_commitment := full_commitment ' ; pending_coinbase_init_stack := pending_coinbase_init_stack1 ; pending_coinbase_stack_state := pending_coinbase_stack_state1 ; ( [ parties ] , commitment ' , full_commitment ' , ! pending_coinbase_init_stack , ! pending_coinbase_stack_state ) | _ -> failwith " Not enough remaining parties " ) | ` Two_new -> ( match ! remaining_parties with | ( ` Pending_coinbase_init_stack pending_coinbase_init_stack1 , ` Pending_coinbase_of_statement pending_coinbase_stack_state1 , parties1 ) :: ( ` Pending_coinbase_init_stack _pending_coinbase_init_stack2 , ` Pending_coinbase_of_statement pending_coinbase_stack_state2 , parties2 ) :: rest -> let commitment ' , full_commitment ' = mk_next_commitments parties2 . parties in remaining_parties := rest ; commitment := commitment ' ; full_commitment := full_commitment ' ; pending_coinbase_init_stack := pending_coinbase_init_stack1 ; pending_coinbase_stack_state := { pending_coinbase_stack_state1 with Pending_coinbase_stack_state . target = pending_coinbase_stack_state2 . Pending_coinbase_stack_state . target } ; ( [ parties1 ; parties2 ] , commitment ' , full_commitment ' , ! pending_coinbase_init_stack , ! pending_coinbase_stack_state ) | _ -> failwith " Not enough remaining parties " ) in let hash_local_state ( local : ( Stack_frame . value , Stack_frame . value list , _ , _ , _ , _ , _ , _ ) Mina_transaction_logic . Parties_logic . Local_state . t ) = let stack_frame ( stack_frame : Stack_frame . value ) value = { stack_frame with calls = Parties . Call_forest . map stack_frame . calls ~ f ( : fun p -> ( p , ( ) ) ) } in { local with stack_frame = stack_frame local . stack_frame ; call_stack = List . map local . call_stack ~ f ( : fun f -> With_hash . of_data ( stack_frame f ) f ~ hash_data : Stack_frame . Digest . create ) |> accumulate_call_stack_hashes ~ hash_frame ( : fun x -> x . With_hash . hash ) } in let source_local = { ( hash_local_state source_local ) source_local with transaction_commitment = current_commitment ; full_transaction_commitment = current_full_commitment } in let target_local = { ( hash_local_state target_local ) target_local with transaction_commitment = next_commitment ; full_transaction_commitment = next_full_commitment } in let w : Parties_segment . Witness . t = { global_ledger = source_global . ledger ; local_state_init = source_local ; start_parties ; state_body ; init_stack = pending_coinbase_init_stack } in let fee_excess = let fee_excess = match Amount . Signed ( . add target_global . fee_excess ( negate source_global . fee_excess ) fee_excess ) fee_excess with | None -> failwith ( sprintf " ! unexpected fee excess . source { % sexp : Amount . Signed . t } t \ target { % sexp : Amount . Signed . t } t " target_global . fee_excess source_global . fee_excess ) | Some balance_change -> balance_change in { fee_token_l = Token_id . default ; fee_excess_l = Amount . Signed . to_fee fee_excess ; Mina_base . Fee_excess . fee_token_r = Token_id . default ; fee_excess_r = Fee . Signed . zero } in let call_stack_hash s = List . hd s |> Option . value_map ~ default : Call_stack_digest . empty ~ f : With_stack_hash . stack_hash in let statement : Statement . With_sok . t = let source_local_ledger = if Parties . Call_forest . is_empty source_local . stack_frame . calls then Frozen_ledger_hash . empty_hash else Sparse_ledger . merkle_root source_local . ledger in { source = { ledger = Sparse_ledger . merkle_root source_global . ledger ; pending_coinbase_stack = pending_coinbase_stack_state . source ; local_state = { source_local with stack_frame = Stack_frame . Digest . create source_local . stack_frame ; call_stack = call_stack_hash source_local . call_stack ; ledger = source_local_ledger } } ; target = { ledger = Sparse_ledger . merkle_root target_global . ledger ; pending_coinbase_stack = pending_coinbase_stack_state . target ; local_state = { target_local with stack_frame = Stack_frame . Digest . create target_local . stack_frame ; call_stack = call_stack_hash target_local . call_stack ; ledger = Sparse_ledger . merkle_root target_local . ledger } } ; supply_increase = Amount . zero ; fee_excess ; sok_digest = Sok_message . Digest . default } in ( w , spec , statement , snapp_stmt ) snapp_stmt :: witnesses ) , final_ledger )
module Make ( Inputs : sig val constraint_constants : Genesis_constants . Constraint_constants . t val proof_level : Genesis_constants . Proof_level . t struct open Inputs let constraint_constants = constraint_constants let ( tag , cache_handle , p , Pickles . Provers . [ base ; merge ; opt_signed_opt_signed ; opt_signed ; proved ] ) = system ~ proof_level ~ constraint_constants module Proof = ( val p ) p let id = Proof . id let verification_key = Proof . verification_key let verify_against_digest { statement ; proof } = Proof . verify [ ( statement , proof ) proof ] let verify ts = if List . for_all ts ~ f ( : fun ( p , m ) m -> Sok_message . Digest . equal ( Sok_message . digest m ) m p . statement . sok_digest ) then Proof . verify ( List . map ts ~ f ( : fun ( { statement ; proof } , _ ) _ -> ( statement , proof ) proof ) proof ) proof else Async . return false let first_party ( witness : Transaction_witness . Parties_segment_witness . t ) t = match witness . local_state_init . stack_frame . calls with | [ ] -> with_return ( fun { return } -> List . iter witness . start_parties ~ f ( : fun s -> Parties . Call_forest . iteri ~ f ( : fun _i x -> return ( Some x ) x ) x s . parties . other_parties ) ; None ) | xs -> Parties . Call_forest . hd_party xs |> Option . map ~ f : fst let party_proof ( p : Party . t ) t = match p . authorization with | Proof p -> Some p | Signature _ | None_given -> None let snapp_proof_data ( ~ snapp_statement : ( int * Zkapp_statement . t ) t option ) option ( ~ witness : Transaction_witness . Parties_segment_witness . t ) t = let open Option . Let_syntax in let % bind p = first_party witness in let % bind tag , snapp_statement = snapp_statement in let % map pi = party_proof p in let vk = let account_id = Account_id . create p . body . public_key p . body . token_id in let account : Account . t = Sparse_ledger ( . get_exn witness . local_state_init . ledger ( find_index_exn witness . local_state_init . ledger account_id ) account_id ) account_id in match Option . value_map ~ default : None account . zkapp ~ f ( : fun s -> s . verification_key ) with | None -> failwith " No verification key found in the account " | Some s -> s in ( snapp_statement , pi , vk , tag ) tag let of_parties_segment_exn ~ statement ~ snapp_statement ~ witness ( ~ spec : Parties_segment . Basic . t ) t : t Async . Deferred . t = Base . Parties_snark . witness := Some witness ; let res = match spec with | Opt_signed -> opt_signed [ ] statement | Opt_signed_opt_signed -> opt_signed_opt_signed [ ] statement | Proved -> ( match snapp_proof_data ~ snapp_statement ~ witness with | None -> failwith " of_parties_segment : Expected exactly one proof " | Some ( s , p , v , tag ) tag -> proved ( Pickles . Side_loaded . in_prover ( Base . side_loaded tag ) tag v . data ; [ ( s , p ) p ] ) statement ) in let open Async in let % map proof = res in Base . Parties_snark . witness := None ; { proof ; statement } let of_transaction_union ~ statement ~ init_stack transaction state_body handler = let open Async in let % map proof = base [ ] ~ handler : ( Base . transaction_union_handler handler transaction state_body init_stack ) statement in { statement ; proof } let of_non_parties_transaction ~ statement ~ init_stack transaction_in_block handler = let transaction : Transaction . t = Transaction . forget ( Transaction_protocol_state . transaction transaction_in_block ) transaction_in_block in let state_body = Transaction_protocol_state . block_data transaction_in_block in match to_preunion transaction with | ` Parties _ -> failwith " Called Non - parties transaction with parties transaction " | ` Transaction t -> of_transaction_union ~ statement ~ init_stack ( Transaction_union . of_transaction t ) t state_body handler let of_user_command ~ statement ~ init_stack user_command_in_block handler = of_non_parties_transaction ~ statement ~ init_stack { user_command_in_block with transaction = Command ( Signed_command ( Transaction_protocol_state . transaction user_command_in_block ) user_command_in_block ) } handler let of_fee_transfer ~ statement ~ init_stack transfer_in_block handler = of_non_parties_transaction ~ statement ~ init_stack { transfer_in_block with transaction = Fee_transfer ( Transaction_protocol_state . transaction transfer_in_block ) transfer_in_block } handler let merge ( { statement = t12 ; _ } as x12 ) x12 ( { statement = t23 ; _ } as x23 ) x23 ~ sok_digest = let open Async . Deferred . Or_error . Let_syntax in let % bind s = Async . return ( Statement . merge t12 t23 ) t23 in let s = { s with sok_digest } in let open Async in let % map proof = merge [ ( x12 . statement , x12 . proof ) proof ; ( x23 . statement , x23 . proof ) proof ] s in Ok { statement = s ; proof } let constraint_system_digests = lazy ( constraint_system_digests ~ constraint_constants ( ) ) end
module For_tests = struct module Spec = struct type t = { fee : Currency . Fee . t ; sender : Signature_lib . Keypair . t * Mina_base . Account . Nonce . t ; fee_payer : ( Signature_lib . Keypair . t * Mina_base . Account . Nonce . t ) t option ; receivers : ( Signature_lib . Public_key . Compressed . t * Currency . Amount . t ) t list ; amount : Currency . Amount . t ; zkapp_account_keypairs : Signature_lib . Keypair . t list ; memo : Signed_command_memo . t ; new_zkapp_account : bool ; snapp_update : Party . Update . t ; current_auth : Permissions . Auth_required . t ; sequence_events : Tick . Field . t array list ; events : Tick . Field . t array list ; call_data : Tick . Field . t ; protocol_state_precondition : Zkapp_precondition . Protocol_state . t option ; account_precondition : Party . Account_precondition . t option } [ @@ deriving sexp ] sexp end let create_trivial_snapp ~ constraint_constants ( ) = let tag , _ , ( module P ) P , Pickles . Provers [ . trivial_prover ; _ ] = let trivial_rule : _ Pickles . Inductive_rule . t = let trivial_main ( tx_commitment : Zkapp_statement . Checked . t ) t : unit Checked . t = Impl . run_checked ( dummy_constraints ( ) ) |> fun ( ) -> Zkapp_statement . Checked . Assert . equal tx_commitment tx_commitment |> return in { identifier = " trivial - rule " ; prevs = [ ] ; main = ( fun [ ] x -> trivial_main x |> Run . run_checked |> fun _ : unit Pickles_types . Hlist0 . H1 ( Pickles_types . Hlist . E01 ( E01Pickles . Inductive_rule . B ) B ) B . t -> [ ] ) ; main_value = ( fun [ ] _ -> [ ] ) } in Pickles . compile ~ cache : Cache_dir . cache ( module Zkapp_statement . Checked ) Checked ( module Zkapp_statement ) Zkapp_statement ~ typ : Zkapp_statement . typ ~ branches ( : module Nat . N2 ) N2 ~ max_proofs_verified ( : module Nat . N2 ) N2 ~ name " : trivial " ~ constraint_constants : ( Genesis_constants . Constraint_constants . to_snark_keys_header constraint_constants ) ~ choices ( : fun ~ self -> [ trivial_rule ; { identifier = " dummy " ; prevs = [ self ; self ] ; main_value = ( fun [ _ ; _ ] _ -> [ true ; true ] ) ; main = ( fun [ _ ; _ ] _ -> Impl . run_checked ( dummy_constraints ( ) ) |> fun ( ) -> Run . exists Field . typ ~ compute ( : fun ( ) -> Run . Field . Constant . zero ) |> fun s -> Run . Field ( . Assert . equal s ( s + one ) one ) one |> fun ( ) : ( Zkapp_statement . Checked . t * ( Zkapp_statement . Checked . t * unit ) unit ) Pickles_types . Hlist0 . H1 ( Pickles_types . Hlist . E01 ( E01Pickles . Inductive_rule . B ) B ) B . t -> [ Boolean . true_ ; Boolean . true_ ] ) } ] ) in let vk = Pickles . Side_loaded . Verification_key . of_compiled tag in ( ` VK ( With_hash . of_data ~ hash_data : Zkapp_account . digest_vk vk ) vk , ` Prover trivial_prover ) let create_parties ( ~ constraint_constants : Genesis_constants . Constraint_constants . t ) t spec ~ update = let { Spec . fee ; sender = sender , sender_nonce ; fee_payer = fee_payer_opt ; receivers ; amount ; new_zkapp_account ; zkapp_account_keypairs ; memo ; sequence_events ; events ; call_data ; protocol_state_precondition ; account_precondition ; _ } = spec in let protocol_state_precondition = Option . value protocol_state_precondition ~ default : Zkapp_precondition . Protocol_state . accept in let sender_pk = sender . public_key |> Public_key . compress in let fee_payer : Party . Fee_payer . t = let public_key , nonce = match fee_payer_opt with | None -> ( sender_pk , sender_nonce ) sender_nonce | Some ( fee_payer_kp , fee_payer_nonce ) fee_payer_nonce -> ( fee_payer_kp . public_key |> Public_key . compress , fee_payer_nonce ) fee_payer_nonce in { body = { public_key ; update = Party . Update . noop ; fee ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition ; nonce } ; authorization = Signature . dummy } in let sender_party : Party . Simple . t option = let sender_party_body : Party . Body . Simple . t = { public_key = sender_pk ; update = Party . Update . noop ; token_id = Token_id . default ; balance_change = Amount ( . Signed ( . negate ( of_unsigned amount ) amount ) amount ) amount ; increment_nonce = true ; events = [ ] ; sequence_events = [ ] ; call_data = Field . zero ; call_depth = 0 ; protocol_state_precondition ; account_precondition = ( if Option . is_none fee_payer_opt then Nonce ( Account . Nonce . succ sender_nonce ) sender_nonce else Nonce sender_nonce ) ; use_full_commitment = false ; caller = Call } in Option . some_if ( ( not ( List . is_empty receivers ) receivers ) receivers || new_zkapp_account ) new_zkapp_account ( { body = sender_party_body ; authorization = Control . Signature Signature . dummy } : Party . Simple . t ) in let snapp_parties : Party . Simple . t list = let num_keypairs = List . length zkapp_account_keypairs in let account_creation_fee = Amount . of_fee constraint_constants . account_creation_fee in assert ( ( not new_zkapp_account ) new_zkapp_account || num_keypairs = 0 || match Currency . Amount . scale account_creation_fee num_keypairs with | None -> false | Some product -> Currency . Amount ( . >= ) amount product ) ; let zeroing_allotment = if new_zkapp_account then if num_keypairs = 0 then amount else let otherwise_allotted = Option . value_exn ( Currency . Amount . scale account_creation_fee num_keypairs ) num_keypairs in Option . value_exn ( Currency . Amount . sub amount otherwise_allotted ) otherwise_allotted else Currency . Amount . zero in List . mapi zkapp_account_keypairs ~ f ( : fun ndx zkapp_account_keypair -> let public_key = Signature_lib . Public_key . compress zkapp_account_keypair . public_key in let delta = if new_zkapp_account && ndx = 0 then Amount . Signed ( . of_unsigned zeroing_allotment ) zeroing_allotment else Amount . Signed . zero in ( { body = { public_key ; update ; token_id = Token_id . default ; balance_change = delta ; increment_nonce = false ; events ; sequence_events ; call_data ; call_depth = 0 ; protocol_state_precondition ; account_precondition = Option . value ~ default : Accept account_precondition ; use_full_commitment = true ; caller = Call } ; authorization = Control . Signature Signature . dummy } : Party . Simple . t ) ) in let other_receivers = List . map receivers ~ f ( : fun ( receiver , amt ) amt : Party . Simple . t -> { body = { public_key = receiver ; update ; token_id = Token_id . default ; balance_change = Amount . Signed . of_unsigned amt ; increment_nonce = false ; events = [ ] ; sequence_events = [ ] ; call_data = Field . zero ; call_depth = 0 ; protocol_state_precondition ; account_precondition = Accept ; use_full_commitment = false ; caller = Call } ; authorization = Control . None_given } ) in let other_parties_data = Option . value_map ~ default [ ] : sender_party ~ f ( : fun p -> [ p ] ) @ snapp_parties @ other_receivers in let ps = Parties . Call_forest . With_hashes . of_parties_simple_list ( List . map ~ f ( : fun p -> ( p , ( ) ) ) other_parties_data ) other_parties_data in let other_parties_hash = Parties . Call_forest . hash ps in let commitment : Parties . Transaction_commitment . t = Parties . Transaction_commitment . create ~ other_parties_hash in let full_commitment = Parties . Transaction_commitment . create_complete commitment ~ memo_hash ( : Signed_command_memo . hash memo ) memo ~ fee_payer_hash : ( Parties . Digest . Party . create ( Party . of_fee_payer fee_payer ) fee_payer ) fee_payer in let fee_payer = let fee_payer_signature_auth = match fee_payer_opt with | None -> Signature_lib . Schnorr . Chunked . sign sender . private_key ( Random_oracle . Input . Chunked . field full_commitment ) full_commitment | Some ( fee_payer_kp , _ ) _ -> Signature_lib . Schnorr . Chunked . sign fee_payer_kp . private_key ( Random_oracle . Input . Chunked . field full_commitment ) full_commitment in { fee_payer with authorization = fee_payer_signature_auth } in let sender_party = Option . map sender_party ~ f ( : fun s : Party . Simple . t -> let commitment = if s . body . use_full_commitment then full_commitment else commitment in let sender_signature_auth = Signature_lib . Schnorr . Chunked . sign sender . private_key ( Random_oracle . Input . Chunked . field commitment ) commitment in { body = s . body ; authorization = Signature sender_signature_auth } ) in ( ` Parties ( Parties . of_simple { fee_payer ; other_parties = other_receivers ; memo } ) , ` Sender_party sender_party , ` Proof_parties snapp_parties , ` Txn_commitment commitment , ` Full_txn_commitment full_commitment ) let deploy_snapp ( ? no_auth = false ) false ~ constraint_constants ( spec : Spec . t ) t = let ` VK vk , ` Prover _trivial_prover = create_trivial_snapp ~ constraint_constants ( ) in assert ( Zkapp_basic . Set_or_keep . is_keep spec . snapp_update . timing || ( spec . new_zkapp_account && List . length spec . zkapp_account_keypairs = 1 ) 1 ) ; let update_vk = let update = spec . snapp_update in if no_auth then update else { update with verification_key = Zkapp_basic . Set_or_keep . Set vk ; permissions = Zkapp_basic . Set_or_keep . Set { Permissions . user_default with edit_state = Permissions . Auth_required . Proof ; edit_sequence_state = Proof } } in let ( ` Parties { Parties . fee_payer ; other_parties ; memo } , ` Sender_party sender_party , ` Proof_parties snapp_parties , ` Txn_commitment commitment , ` Full_txn_commitment full_commitment ) = create_parties ~ constraint_constants spec ~ update : update_vk in assert ( List . is_empty other_parties ) other_parties ; let snapp_parties_keypairs = List . zip_exn snapp_parties spec . zkapp_account_keypairs in let snapp_parties = List . map snapp_parties_keypairs ~ f ( : fun ( snapp_party , keypair ) keypair -> if no_auth then ( { body = snapp_party . body ; authorization = None_given } : Party . Simple . t ) else let commitment = if snapp_party . body . use_full_commitment then full_commitment else commitment in let signature = Signature_lib . Schnorr . Chunked . sign keypair . private_key ( Random_oracle . Input . Chunked . field commitment ) commitment in ( { body = snapp_party . body ; authorization = Signature signature } : Party . Simple . t ) ) in let other_parties = Option . to_list sender_party @ snapp_parties in let parties : Parties . t = Parties . of_simple { fee_payer ; other_parties ; memo } in parties let update_states ? snapp_prover ~ constraint_constants ( spec : Spec . t ) t = let ( ` Parties { Parties . fee_payer ; other_parties ; memo } , ` Sender_party sender_party , ` Proof_parties snapp_parties , ` Txn_commitment commitment , ` Full_txn_commitment full_commitment ) = create_parties ~ constraint_constants spec ~ update : spec . snapp_update in assert ( List . is_empty other_parties ) other_parties ; assert ( Option . is_none sender_party ) sender_party ; assert ( not @@ List . is_empty snapp_parties ) snapp_parties ; let snapp_parties_keypairs = List . zip_exn snapp_parties spec . zkapp_account_keypairs in let % map . Async . Deferred snapp_parties = Async . Deferred . List . mapi snapp_parties_keypairs ~ f ( : fun ndx ( snapp_party , snapp_keypair ) snapp_keypair -> match spec . current_auth with | Permissions . Auth_required . Proof -> let proof_party = let ps = Parties . Call_forest . With_hashes . of_parties_simple_list ( List . map ~ f ( : fun p -> ( p , ( ) ) ) ( List . drop snapp_parties ndx ) ndx ) in Parties . Call_forest . hash ps in let tx_statement : Zkapp_statement . t = let commitment = if snapp_party . body . use_full_commitment then full_commitment else commitment in { transaction = commitment ; at_party = ( proof_party :> Field . t ) t } in let handler ( Snarky_backendless . Request . With { request ; respond } ) = match request with _ -> respond Unhandled in let prover = match snapp_prover with | Some prover -> prover | None -> let _ , ` Prover p = create_trivial_snapp ~ constraint_constants ( ) in p in let % map . Async . Deferred ( pi : Pickles . Side_loaded . Proof . t ) t = prover ~ handler [ ] tx_statement in ( { body = snapp_party . body ; authorization = Proof pi } : Party . Simple . t ) | Signature -> let commitment = if snapp_party . body . use_full_commitment then full_commitment else commitment in let signature = Signature_lib . Schnorr . Chunked . sign snapp_keypair . private_key ( Random_oracle . Input . Chunked . field commitment ) commitment in Async . Deferred . return ( { body = snapp_party . body ; authorization = Signature signature } : Party . Simple . t ) | None -> Async . Deferred . return ( { body = snapp_party . body ; authorization = None_given } : Party . Simple . t ) | _ -> failwith " Current authorization not Proof or Signature or None_given " ) in let other_parties = snapp_parties in let parties : Parties . t = Parties . of_simple { fee_payer ; other_parties ; memo } in parties let multiple_transfers ( spec : Spec . t ) t = let ( ` Parties parties , ` Sender_party sender_party , ` Proof_parties snapp_parties , ` Txn_commitment _commitment , ` Full_txn_commitment _full_commitment ) = create_parties ~ constraint_constants : Genesis_constants . Constraint_constants . compiled spec ~ update : spec . snapp_update in assert ( Option . is_some sender_party ) sender_party ; assert ( List . is_empty snapp_parties ) snapp_parties ; let other_parties = let sender_party = Option . value_exn sender_party in Parties . Call_forest . cons ( Parties . add_caller_simple sender_party Token_id . default ) default parties . other_parties in { parties with other_parties } let trivial_zkapp_account ( ? permissions = Permissions . user_default ) user_default ~ vk pk = let id = Account_id . create pk Token_id . default in { ( Account . create id Balance ( . of_int 1_000_000_000_000_000 ) 1_000_000_000_000_000 ) 1_000_000_000_000_000 with permissions ; zkapp = Some { Zkapp_account . default with verification_key = Some vk } } let create_trivial_zkapp_account ( ? permissions = Permissions . user_default ) user_default ~ vk ~ ledger pk = let create ledger id account = match Ledger . location_of_account ledger id with | Some _loc -> failwith " Account already present " | None -> let _loc , _new = Ledger . get_or_create_account ledger id account |> Or_error . ok_exn in ( ) in let id = Account_id . create pk Token_id . default in let account : Account . t = trivial_zkapp_account ~ permissions ~ vk pk in create ledger id account let create_trivial_predicate_snapp ~ constraint_constants ( ? protocol_state_predicate = Zkapp_precondition . Protocol_state . accept ) accept ( ~ snapp_kp : Signature_lib . Keypair . t ) t spec ledger = let { Mina_transaction_logic . For_tests . Transaction_spec . fee ; sender = sender , sender_nonce ; receiver = _ ; receiver_is_new = _ ; amount } = spec in let trivial_account_pk = Signature_lib . Public_key . compress snapp_kp . public_key in let ` VK vk , ` Prover trivial_prover = create_trivial_snapp ~ constraint_constants ( ) in let _v = let id = Public_key . compress sender . public_key |> fun pk -> Account_id . create pk Token_id . default in Ledger . get_or_create_account ledger id ( Account . create id Balance ( . of_int 888_888 ) 888_888 ) 888_888 |> Or_error . ok_exn in let ( ) = create_trivial_zkapp_account trivial_account_pk ~ ledger ~ vk ~ permissions { : Permissions . user_default with set_permissions = Proof } in let update_empty_permissions = let permissions = { Permissions . user_default with send = Permissions . Auth_required . Proof } |> Zkapp_basic . Set_or_keep . Set in { Party . Update . dummy with permissions } in let sender_pk = sender . public_key |> Public_key . compress in let fee_payer : Party . Fee_payer . t = { body = { public_key = sender_pk ; update = Party . Update . noop ; fee ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = protocol_state_predicate ; nonce = sender_nonce } ; authorization = Signature . dummy } in let sender_party_data : Party . Simple . t = { body = { public_key = sender_pk ; update = Party . Update . noop ; token_id = Token_id . default ; balance_change = Amount ( . Signed ( . negate ( of_unsigned amount ) amount ) amount ) amount ; increment_nonce = true ; events = [ ] ; sequence_events = [ ] ; call_data = Field . zero ; call_depth = 0 ; protocol_state_precondition = protocol_state_predicate ; account_precondition = Nonce ( Account . Nonce . succ sender_nonce ) sender_nonce ; use_full_commitment = false ; caller = Call } ; authorization = Signature Signature . dummy } in let snapp_party_data : Party . Simple . t = { body = { public_key = trivial_account_pk ; update = update_empty_permissions ; token_id = Token_id . default ; balance_change = Amount . Signed ( . of_unsigned amount ) amount ; increment_nonce = false ; events = [ ] ; sequence_events = [ ] ; call_data = Field . zero ; call_depth = 0 ; protocol_state_precondition = protocol_state_predicate ; use_full_commitment = false ; caller = Call ; account_precondition = Full Zkapp_precondition . Account . accept } ; authorization = Proof Mina_base . Proof . blockchain_dummy } in let memo = Signed_command_memo . empty in let ps = Parties . Call_forest . With_hashes . of_parties_simple_list [ ( sender_party_data , ( ) ) ; ( snapp_party_data , ( ) ) ] in let other_parties_hash = Parties . Call_forest . hash ps in let transaction : Parties . Transaction_commitment . t = Parties . Transaction_commitment . create ~ other_parties_hash in let proof_party = let ps = Parties . Call_forest . With_hashes . of_parties_simple_list [ ( snapp_party_data , ( ) ) ] in Parties . Call_forest . hash ps in let tx_statement : Zkapp_statement . t = { transaction ; at_party = ( proof_party :> Field . t ) t } in let handler ( Snarky_backendless . Request . With { request ; respond } ) = match request with _ -> respond Unhandled in let % map . Async . Deferred ( pi : Pickles . Side_loaded . Proof . t ) t = trivial_prover ~ handler [ ] tx_statement in let fee_payer_signature_auth = let txn_comm = Parties . Transaction_commitment . create_complete transaction ~ memo_hash ( : Signed_command_memo . hash memo ) memo ~ fee_payer_hash : ( Parties . Digest . Party . create ( Party . of_fee_payer fee_payer ) fee_payer ) fee_payer in Signature_lib . Schnorr . Chunked . sign sender . private_key ( Random_oracle . Input . Chunked . field txn_comm ) txn_comm in let fee_payer = { fee_payer with authorization = fee_payer_signature_auth } in let sender_signature_auth = Signature_lib . Schnorr . Chunked . sign sender . private_key ( Random_oracle . Input . Chunked . field transaction ) transaction in let sender : Party . Simple . t = { sender_party_data with authorization = Signature sender_signature_auth } in let other_parties = [ sender ; { body = snapp_party_data . body ; authorization = Proof pi } ] in let parties : Parties . t = Parties . of_simple { fee_payer ; other_parties ; memo } in parties end
module Sparse_ledger = struct include Mina_ledger . Sparse_ledger let merkle_root t = Frozen_ledger_hash . of_ledger_hash @@ merkle_root t end
let create_ledger_and_transactions num_transitions = let num_accounts = 4 in let constraint_constants = Genesis_constants . Constraint_constants . compiled in let ledger = Mina_ledger . Ledger . create ~ depth : constraint_constants . ledger_depth ( ) in let keys = Array . init num_accounts ~ f ( : fun _ -> Signature_lib . Keypair . create ( ) ) in Array . iter keys ~ f ( : fun k -> let public_key = Public_key . compress k . public_key in let account_id = Account_id . create public_key Token_id . default in Mina_ledger . Ledger . create_new_account_exn ledger account_id ( Account . create account_id ( Currency . Balance . of_int 10_000 ) 10_000 ) 10_000 ) ; let txn ( from_kp : Signature_lib . Keypair . t ) t ( to_kp : Signature_lib . Keypair . t ) t amount fee nonce = let to_pk = Public_key . compress to_kp . public_key in let from_pk = Public_key . compress from_kp . public_key in let payload : Signed_command . Payload . t = Signed_command . Payload . create ~ fee ~ fee_payer_pk : from_pk ~ nonce ~ memo : Signed_command_memo . dummy ~ valid_until : None ~ body ( : Payment { source_pk = from_pk ; receiver_pk = to_pk ; amount } ) in Signed_command . sign from_kp payload in let nonces = Public_key . Compressed . Table . of_alist_exn ( List . map ( Array . to_list keys ) keys ~ f ( : fun k -> ( Public_key . compress k . public_key , Account . Nonce . zero ) zero ) ) in let random_transaction ( ) : Signed_command . With_valid_signature . t = let sender_idx = Random . int num_accounts in let sender = keys ( . sender_idx ) sender_idx in let receiver = keys ( . Random . int num_accounts ) num_accounts in let sender_pk = Public_key . compress sender . public_key in let nonce = Hashtbl . find_exn nonces sender_pk in Hashtbl . change nonces sender_pk ~ f ( : Option . map ~ f : Account . Nonce . succ ) succ ; let fee = Currency . Fee . of_int ( 1 + Random . int 100 ) 100 in let amount = Currency . Amount . of_int ( 1 + Random . int 100 ) 100 in txn sender receiver amount fee nonce in match num_transitions with | ` Count n -> let num_transactions = n - 2 in let transactions = List . rev ( List . init num_transactions ~ f ( : fun _ -> random_transaction ( ) ) ) in let fee_transfer = let open Currency . Fee in let total_fee = List . fold transactions ~ init : zero ~ f ( : fun acc t -> Option . value_exn ( add acc ( Signed_command . Payload . fee ( t :> Signed_command . t ) t . payload ) payload ) ) in Fee_transfer . create_single ~ receiver_pk ( : Public_key . compress keys ( . 0 ) 0 . public_key ) public_key ~ fee : total_fee ~ fee_token : Token_id . default in let coinbase = Coinbase . create ~ amount : constraint_constants . coinbase_amount ~ receiver ( : Public_key . compress keys ( . 0 ) 0 . public_key ) public_key ~ fee_transfer : None |> Or_error . ok_exn in let transitions = List . map transactions ~ f ( : fun t -> Transaction . Command ( User_command . Signed_command t ) t ) @ [ Coinbase coinbase ; Fee_transfer fee_transfer ] in ( ledger , transitions ) transitions | ` Two_from_same -> let a = txn keys ( . 0 ) 0 keys ( . 1 ) 1 ( Currency . Amount . of_int 10 ) 10 Currency . Fee . zero Account . Nonce . zero in let b = txn keys ( . 0 ) 0 keys ( . 1 ) 1 ( Currency . Amount . of_int 10 ) 10 Currency . Fee . zero ( Account . Nonce . succ Account . Nonce . zero ) zero in ( ledger , [ Command ( Signed_command a ) a ; Command ( Signed_command b ) b ] )
let time thunk = let start = Time . now ( ) in let x = thunk ( ) in let stop = Time . now ( ) in ( Time . diff stop start , x ) x
let rec pair_up = function | [ ] -> [ ] | x :: y :: xs -> ( x , y ) y :: pair_up xs | _ -> failwith " Expected even length list "
let state_body = Mina_state ( . Lazy . map precomputed_values ~ f ( : fun values -> values . protocol_state_with_hashes . data |> Protocol_state . body ) )
let curr_state_view = Lazy . map state_body ~ f : Mina_state . Protocol_state . Body . view
let state_body_hash = Lazy . map ~ f : Mina_state . Protocol_state . Body . hash state_body
let pending_coinbase_stack_target ( t : Transaction . t ) t stack = let stack_with_state = Pending_coinbase . Stack ( . push_state ( Lazy . force state_body_hash ) state_body_hash stack ) stack in let target = match t with | Coinbase c -> Pending_coinbase ( . Stack . push_coinbase c stack_with_state ) stack_with_state | _ -> stack_with_state in target
let profile ( module T : Transaction_snark . S ) S sparse_ledger0 ( transitions : Transaction . Valid . t list ) list _ = let constraint_constants = Genesis_constants . Constraint_constants . compiled in let txn_state_view = Lazy . force curr_state_view in let ( base_proof_time , _ , _ ) _ , base_proofs = List . fold_map transitions ~ init ( : Time . Span . zero , sparse_ledger0 , Pending_coinbase . Stack . empty ) empty ~ f ( : fun ( max_span , sparse_ledger , coinbase_stack_source ) coinbase_stack_source t -> let sparse_ledger ' , _ = Sparse_ledger . apply_transaction ~ constraint_constants ~ txn_state_view sparse_ledger ( Transaction . forget t ) t |> Or_error . ok_exn in let coinbase_stack_target = pending_coinbase_stack_target ( Transaction . forget t ) t coinbase_stack_source in let span , proof = time ( fun ( ) -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> T . of_non_parties_transaction ~ statement : { sok_digest = Sok_message . Digest . default ; source = { ledger = Sparse_ledger . merkle_root sparse_ledger ; pending_coinbase_stack = coinbase_stack_source ; local_state = Mina_state . Local_state . empty ( ) } ; target = { ledger = Sparse_ledger . merkle_root sparse_ledger ' ; pending_coinbase_stack = coinbase_stack_target ; local_state = Mina_state . Local_state . empty ( ) } ; supply_increase = Transaction . supply_increase t |> Or_error . ok_exn ; fee_excess = Transaction . fee_excess ( Transaction . forget t ) t |> Or_error . ok_exn } ~ init_stack : coinbase_stack_source { Transaction_protocol_state . Poly . transaction = t ; block_data = Lazy . force state_body } ( unstage ( Sparse_ledger . handler sparse_ledger ) sparse_ledger ) sparse_ledger ) ) in ( ( Time . Span . max span max_span , sparse_ledger ' , coinbase_stack_target ) coinbase_stack_target , proof ) ) in let rec merge_all serial_time proofs = match proofs with | [ _ ] -> serial_time | _ -> let layer_time , new_proofs = List . fold_map ( pair_up proofs ) proofs ~ init : Time . Span . zero ~ f ( : fun max_time ( x , y ) y -> let pair_time , proof = time ( fun ( ) -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> T . merge ~ sok_digest : Sok_message . Digest . default x y ) |> Or_error . ok_exn ) in ( Time . Span . max max_time pair_time , proof ) proof ) in merge_all ( Time . Span ( . + ) serial_time layer_time ) layer_time new_proofs in let total_time = merge_all base_proof_time base_proofs in Printf . sprintf " ! Total time was : { % Time . Span } Span " total_time
let check_base_snarks sparse_ledger0 ( transitions : Transaction . Valid . t list ) list preeval = let constraint_constants = Genesis_constants . Constraint_constants . compiled in ignore ( let sok_message = Sok_message . create ~ fee : Currency . Fee . zero ~ prover : Public_key ( . compress ( of_private_key_exn ( Private_key . create ( ) ) ) ) in let txn_state_view = Lazy . force curr_state_view in List . fold transitions ~ init : sparse_ledger0 ~ f ( : fun sparse_ledger t -> let sparse_ledger ' , _ = Sparse_ledger . apply_transaction ~ constraint_constants ~ txn_state_view sparse_ledger ( Transaction . forget t ) t |> Or_error . ok_exn in let coinbase_stack_target = pending_coinbase_stack_target ( Transaction . forget t ) t Pending_coinbase . Stack . empty in let ( ) = Transaction_snark . check_transaction ? preeval ~ constraint_constants ~ sok_message ~ source ( : Sparse_ledger . merkle_root sparse_ledger ) sparse_ledger ~ target ( : Sparse_ledger . merkle_root sparse_ledger ' ) sparse_ledger ' ~ init_stack : Pending_coinbase . Stack . empty ~ pending_coinbase_stack_state : { source = Pending_coinbase . Stack . empty ; target = coinbase_stack_target } ~ zkapp_account1 : None ~ zkapp_account2 : None { Transaction_protocol_state . Poly . block_data = Lazy . force state_body ; transaction = t } ( unstage ( Sparse_ledger . handler sparse_ledger ) sparse_ledger ) sparse_ledger in sparse_ledger ' ) : Sparse_ledger . t ) ; " Base constraint system satisfied "
let generate_base_snarks_witness sparse_ledger0 ( transitions : Transaction . Valid . t list ) list preeval = let constraint_constants = Genesis_constants . Constraint_constants . compiled in ignore ( let sok_message = Sok_message . create ~ fee : Currency . Fee . zero ~ prover : Public_key ( . compress ( of_private_key_exn ( Private_key . create ( ) ) ) ) in let txn_state_view = Lazy . force curr_state_view in List . fold transitions ~ init : sparse_ledger0 ~ f ( : fun sparse_ledger t -> let sparse_ledger ' , _ = Sparse_ledger . apply_transaction ~ constraint_constants ~ txn_state_view sparse_ledger ( Transaction . forget t ) t |> Or_error . ok_exn in let coinbase_stack_target = pending_coinbase_stack_target ( Transaction . forget t ) t Pending_coinbase . Stack . empty in let ( ) = Transaction_snark . generate_transaction_witness ? preeval ~ constraint_constants ~ sok_message ~ source ( : Sparse_ledger . merkle_root sparse_ledger ) sparse_ledger ~ target ( : Sparse_ledger . merkle_root sparse_ledger ' ) sparse_ledger ' ~ init_stack : Pending_coinbase . Stack . empty ~ pending_coinbase_stack_state : { Transaction_snark . Pending_coinbase_stack_state . source = Pending_coinbase . Stack . empty ; target = coinbase_stack_target } ~ zkapp_account1 : None ~ zkapp_account2 : None { Transaction_protocol_state . Poly . transaction = t ; block_data = Lazy . force state_body } ( unstage ( Sparse_ledger . handler sparse_ledger ) sparse_ledger ) sparse_ledger in sparse_ledger ' ) : Sparse_ledger . t ) ; " Base constraint system satisfied "
let run profiler num_transactions repeats preeval = let ledger , transactions = create_ledger_and_transactions num_transactions in let sparse_ledger = Mina_ledger . Sparse_ledger . of_ledger_subset_exn ledger ( List . fold ~ init [ ] : transactions ~ f ( : fun participants t -> List . rev_append ( Transaction . accounts_accessed ( Transaction . forget t ) t ) t participants ) ) in for i = 1 to repeats do let message = profiler sparse_ledger transactions preeval in Core . printf [ " !% i ] i % s \ n " %! i message done ; exit 0
let main num_transactions repeats preeval ( ) = Test_util . with_randomness 123456789 ( fun ( ) -> let module T = Transaction_snark . Make ( struct let constraint_constants = Genesis_constants . Constraint_constants . compiled let proof_level = Genesis_constants . Proof_level . Full end ) end in run ( profile ( module T ) T ) T num_transactions repeats preeval )
let dry num_transactions repeats preeval ( ) = Test_util . with_randomness 123456789 ( fun ( ) -> run check_base_snarks num_transactions repeats preeval )
let witness num_transactions repeats preeval ( ) = Test_util . with_randomness 123456789 ( fun ( ) -> run generate_base_snarks_witness num_transactions repeats preeval )
let command = let open Command . Let_syntax in Command . basic ~ summary " : transaction snark profiler " ( let % map_open n = flag " - k " ~ doc : " count count = log_2 ( log_2number of transactions to snark ) snark or none for \ the mocked ones " ( optional int ) int and repeats = flag " -- repeat " ~ aliases [ : " repeat " ] ~ doc " : count number of times to repeat the profile " ( optional int ) int and preeval = flag " -- preeval " ~ aliases [ : " preeval " ] ~ doc : " true / false whether to pre - evaluate the checked computation to \ cache interpreter and computation state " ( optional bool ) bool and check_only = flag " -- check - only " ~ aliases [ : " check - only " ] ~ doc " : Just check base snarks , don ' t keys or time anything " no_arg and witness_only = flag " -- witness - only " ~ aliases [ : " witness - only " ] ~ doc " : Just generate the witnesses for the base snarks " no_arg in let num_transactions = Option . map n ~ f ( : fun n -> ` Count ( Int . pow 2 n ) n ) n |> Option . value ~ default ` : Two_from_same in let repeats = Option . value repeats ~ default : 1 in if witness_only then witness num_transactions repeats preeval else if check_only then dry num_transactions repeats preeval else main num_transactions repeats preeval )
let map2_or_error xs ys ~ f = let rec go xs ys acc = match ( xs , ys ) ys with | [ ] , [ ] -> Ok ( List . rev acc ) acc | x :: xs , y :: ys -> ( match f x y with Error e -> Error e | Ok z -> go xs ys ( z :: acc ) acc ) | _ , _ -> Or_error . error_string " Length mismatch " in go xs ys [ ]
module type Monad_with_Or_error_intf = sig type ' a t include Monad . S with type ' a t := ' a t module Or_error : sig type nonrec ' a t = ' a Or_error . t t include Monad . S with type ' a t := ' a t end end
module Transaction_with_witness = struct [ %% versioned module Stable = struct module V2 = struct type t = { transaction_with_info : Mina_transaction_logic . Transaction_applied . Stable . V2 . t ; state_hash : State_hash . Stable . V1 . t * State_body_hash . Stable . V1 . t ; statement : Transaction_snark . Statement . Stable . V2 . t ; init_stack : Transaction_snark . Pending_coinbase_stack_state . Init_stack . Stable . V1 . t ; ledger_witness : Mina_ledger . Sparse_ledger . Stable . V2 . t [ @ sexp . opaque ] opaque } [ @@ deriving sexp ] sexp let to_latest = Fn . id end end ] end end
module Ledger_proof_with_sok_message = struct [ %% versioned module Stable = struct module V2 = struct type t = Ledger_proof . Stable . V2 . t * Sok_message . Stable . V1 . t [ @@ deriving sexp ] sexp let to_latest = Fn . id end end ] end end
module Available_job = struct type t = ( Ledger_proof_with_sok_message . t , Transaction_with_witness . t ) Parallel_scan . Available_job . t [ @@ deriving sexp ] sexp end
module Job_view = struct type t = Transaction_snark . Statement . t Parallel_scan . Job_view . t [ @@ deriving sexp ] sexp let to_yojson ( { value ; position } : t ) t : Yojson . Safe . t = let module R = struct type t = ( Frozen_ledger_hash . t , Pending_coinbase . Stack_versioned . t , Mina_state . Local_state . t ) Mina_state . Registers . t [ @@ deriving to_yojson ] to_yojson end in let statement_to_yojson ( s : Transaction_snark . Statement . t ) t = ` Assoc [ ( " Work_id " , ` Int ( Transaction_snark . Statement . hash s ) s ) s ; ( " Source " , R . to_yojson s . source ) source ; ( " Target " , R . to_yojson s . target ) target ; ( " Fee Excess " , ` List [ ` Assoc [ ( " token " , Token_id . to_yojson s . fee_excess . fee_token_l ) fee_token_l ; ( " amount " , Fee . Signed . to_yojson s . fee_excess . fee_excess_l ) fee_excess_l ] ; ` Assoc [ ( " token " , Token_id . to_yojson s . fee_excess . fee_token_r ) fee_token_r ; ( " amount " , Fee . Signed . to_yojson s . fee_excess . fee_excess_r ) fee_excess_r ] ] ) ; ( " Supply Increase " , Currency . Amount . to_yojson s . supply_increase ) supply_increase ] in let job_to_yojson = match value with | BEmpty -> ` Assoc [ ( " B " , ` List [ ] ) ] | MEmpty -> ` Assoc [ ( " M " , ` List [ ] ) ] | MPart x -> ` Assoc [ ( " M " , ` List [ statement_to_yojson x ] ) ] | MFull ( x , y , { seq_no ; status } ) -> ` Assoc [ ( " M " , ` List [ statement_to_yojson x ; statement_to_yojson y ; ` Int seq_no ; ` Assoc [ ( " Status " , ` String ( Parallel_scan . Job_status . to_string status ) status ) ] ] ) ] | BFull ( x , { seq_no ; status } ) -> ` Assoc [ ( " B " , ` List [ statement_to_yojson x ; ` Int seq_no ; ` Assoc [ ( " Status " , ` String ( Parallel_scan . Job_status . to_string status ) status ) ] ] ) ] in ` List [ ` Int position ; job_to_yojson ] end
type job = Available_job . t [ @@ deriving sexp ] sexp [ %% versioned
module Stable = struct module V2 = struct type t = ( Ledger_proof_with_sok_message . Stable . V2 . t , Transaction_with_witness . Stable . V2 . t ) Parallel_scan . State . Stable . V1 . t [ @@ deriving sexp ] sexp let to_latest = Fn . id let hash ( t : t ) t = let state_hash = Parallel_scan . State . hash t ( Binable . to_string ( module Ledger_proof_with_sok_message . Stable . V2 ) V2 ) V2 ( Binable . to_string ( module Transaction_with_witness . Stable . V2 ) V2 ) V2 in Staged_ledger_hash . Aux_hash . of_bytes ( state_hash |> Digestif . SHA256 . to_raw_string ) to_raw_string end end ] end
let create_expected_statement ~ constraint_constants ( ~ get_state : State_hash . t -> Mina_state . Protocol_state . value Or_error . t ) t { Transaction_with_witness . transaction_with_info ; state_hash ; ledger_witness ; init_stack ; statement } = let open Or_error . Let_syntax in let source_merkle_root = Frozen_ledger_hash . of_ledger_hash @@ Sparse_ledger . merkle_root ledger_witness in let { With_status . data = transaction ; status = _ } = Ledger . Transaction_applied . transaction transaction_with_info in let % bind protocol_state = get_state ( fst state_hash ) state_hash in let state_view = Mina_state . Protocol_state . Body . view protocol_state . body in let empty_local_state = Mina_state . Local_state . empty ( ) in let % bind after , _ = Or_error . try_with ( fun ( ) -> Sparse_ledger . apply_transaction ~ constraint_constants ~ txn_state_view : state_view ledger_witness transaction ) |> Or_error . join in let target_merkle_root = Sparse_ledger . merkle_root after |> Frozen_ledger_hash . of_ledger_hash in let % bind pending_coinbase_before = match init_stack with | Base source -> Ok source | Merge -> Or_error . errorf " ! Invalid init stack in Pending coinbase stack state . Expected Base \ found Merge " in let pending_coinbase_after = let state_body_hash = snd state_hash in let pending_coinbase_with_state = Pending_coinbase . Stack . push_state state_body_hash pending_coinbase_before in match transaction with | Coinbase c -> Pending_coinbase . Stack . push_coinbase c pending_coinbase_with_state | _ -> pending_coinbase_with_state in let % bind fee_excess = Transaction . fee_excess transaction in let % map supply_increase = Transaction . supply_increase transaction in { Transaction_snark . Statement . source = { ledger = source_merkle_root ; pending_coinbase_stack = statement . source . pending_coinbase_stack ; local_state = empty_local_state } ; target = { ledger = target_merkle_root ; pending_coinbase_stack = pending_coinbase_after ; local_state = empty_local_state } ; fee_excess ; supply_increase ; sok_digest = ( ) }
let completed_work_to_scanable_work ( job : job ) job ( fee , current_proof , prover ) prover : Ledger_proof_with_sok_message . t Or_error . t = let sok_digest = Ledger_proof . sok_digest current_proof and proof = Ledger_proof . underlying_proof current_proof in match job with | Base { statement ; _ } -> let ledger_proof = Ledger_proof . create ~ statement ~ sok_digest ~ proof in Ok ( ledger_proof , Sok_message . create ~ fee ~ prover ) prover | Merge ( ( p , _ ) _ , ( p ' , _ ) _ ) _ -> let open Or_error . Let_syntax in let s = Ledger_proof . statement p and s ' = Ledger_proof . statement p ' in let option lab = Option . value_map ~ default ( : Or_error . error_string lab ) lab ~ f ( : fun x -> Ok x ) x in let % map fee_excess = Fee_excess . combine s . fee_excess s ' . fee_excess and supply_increase = Amount . add s . supply_increase s ' . supply_increase |> option " Error adding supply_increases " and _valid_pending_coinbase_stack = if Pending_coinbase . Stack . equal s . target . pending_coinbase_stack s ' . source . pending_coinbase_stack then Ok ( ) else Or_error . error_string " Invalid pending coinbase stack state " in let statement : Transaction_snark . Statement . t = { source = s . source ; target = s ' . target ; supply_increase ; fee_excess ; sok_digest = ( ) } in ( Ledger_proof . create ~ statement ~ sok_digest ~ proof , Sok_message . create ~ fee ~ prover )
let total_proofs ( works : Transaction_snark_work . t list ) list = List . sum ( module Int ) Int works ~ f ( : fun w -> One_or_two . length w . proofs ) proofs
module P = struct type t = Ledger_proof_with_sok_message . t end
module Make_statement_scanner ( Verifier : sig type t val verify : verifier : t -> P . t list -> bool Deferred . Or_error . t struct module Fold = Parallel_scan . State . Make_foldable ( Deferred ) Deferred let logger = lazy ( Logger . create ( ) ) module Timer = struct module Info = struct module Time_span = struct type t = Time . Span . t let to_yojson t = ` Float ( Time . Span . to_ms t ) t end type t = { total : Time_span . t ; count : int ; min : Time_span . t ; max : Time_span . t } [ @@ deriving to_yojson ] to_yojson let singleton time = { total = time ; count = 1 ; max = time ; min = time } let update ( t : t ) t time = { total = Time . Span ( . + ) t . total time ; count = t . count + 1 ; min = Time . Span . min t . min time ; max = Time . Span . max t . max time } end type t = Info . t String . Table . t let create ( ) : t = String . Table . create ( ) let time ( t : t ) t label f = let start = Time . now ( ) in let x = f ( ) in let elapsed = Time ( . diff ( now ( ) ) start ) start in Hashtbl . update t label ~ f ( : function | None -> Info . singleton elapsed | Some acc -> Info . update acc elapsed ) ; x let log label ( t : t ) t = let logger = Lazy . force logger in [ % log debug ] debug ~ metadata : ( List . map ( Hashtbl . to_alist t ) t ~ f ( : fun ( k , info ) info -> ( k , Info . to_yojson info ) info ) ) " % s timing " label end let scan_statement ~ constraint_constants tree ~ statement_check ~ verifier : ( Transaction_snark . Statement . t , [ ` Error of Error . t | ` Empty ] ) Deferred . Result . t = let open Deferred . Or_error . Let_syntax in let timer = Timer . create ( ) in let yield_occasionally = let f = Staged . unstage ( Async . Scheduler . yield_every ~ n : 50 ) 50 in fun ( ) -> f ( ) |> Deferred . map ~ f : Or_error . return in let yield_always ( ) = Async . Scheduler . yield ( ) |> Deferred . map ~ f : Or_error . return in let module Acc = struct type t = ( Transaction_snark . Statement . t * P . t list ) list option end in let write_error description = sprintf " ! Staged_ledger . scan_statement : % s \ n " description in let with_error ~ f message = let result = f ( ) in Deferred . Result . map_error result ~ f ( : fun e -> Error . createf " !% s : { % sexp : Error . t } t " ( write_error message ) message e ) in let merge_acc ~ proofs ( acc : Acc . t ) t s2 : Acc . t Deferred . Or_error . t = Timer . time timer ( sprintf " merge_acc :% s " __LOC__ ) __LOC__ ( fun ( ) -> with_error " Bad merge proof " ~ f ( : fun ( ) -> match acc with | None -> return ( Some ( s2 , proofs ) proofs ) proofs | Some ( s1 , ps ) ps -> let % bind merged_statement = Deferred . return ( Transaction_snark . Statement . merge s1 s2 ) s2 in let % map ( ) = yield_occasionally ( ) in Some ( merged_statement , proofs @ ps ) ps ) ) in let merge_pc ( acc : Transaction_snark . Statement . t option ) option s2 : Transaction_snark . Statement . t option Or_error . t = let open Or_error . Let_syntax in match acc with | None -> Ok ( Some s2 ) s2 | Some s1 -> let % map ( ) = if Pending_coinbase . Stack . connected ~ prev ( : Some s1 . source . pending_coinbase_stack ) pending_coinbase_stack ~ first : s1 . target . pending_coinbase_stack ~ second : s2 . source . pending_coinbase_stack ( ) then return ( ) else Or_error . errorf " ! Base merge proof : invalid pending coinbase transition s1 : \ { % sexp : Transaction_snark . Statement . t } t s2 : { % sexp : \ Transaction_snark . Statement . t } t " s1 s2 in Some s2 in let fold_step_a ( acc_statement , acc_pc ) acc_pc job = match job with | Parallel_scan . Merge . Job . Part ( proof , message ) message -> let statement = Ledger_proof . statement proof in let % map acc_stmt = merge_acc ~ proofs [ : ( proof , message ) message ] acc_statement statement in ( acc_stmt , acc_pc ) acc_pc | Empty | Full { status = Parallel_scan . Job_status . Done ; _ } -> return ( acc_statement , acc_pc ) acc_pc | Full { left = proof_1 , message_1 ; right = proof_2 , message_2 ; _ } -> let stmt1 = Ledger_proof . statement proof_1 in let stmt2 = Ledger_proof . statement proof_2 in let % bind merged_statement = Timer . time timer ( sprintf " merge :% s " __LOC__ ) __LOC__ ( fun ( ) -> Deferred . return ( Transaction_snark . Statement . merge stmt1 stmt2 ) stmt2 ) in let % map acc_stmt = merge_acc acc_statement merged_statement ~ proofs [ : ( proof_1 , message_1 ) message_1 ; ( proof_2 , message_2 ) message_2 ] in ( acc_stmt , acc_pc ) acc_pc in let fold_step_d ( acc_statement , acc_pc ) acc_pc job = match job with | Parallel_scan . Base . Job . Empty -> return ( acc_statement , acc_pc ) acc_pc | Full { status = Parallel_scan . Job_status . Done ; job = ( transaction : Transaction_with_witness . t ) t ; _ } -> let % map acc_pc = Deferred . return ( merge_pc acc_pc transaction . statement ) statement in ( acc_statement , acc_pc ) acc_pc | Full { job = transaction ; _ } -> with_error " Bad base statement " ~ f ( : fun ( ) -> let % bind expected_statement = match statement_check with | ` Full get_state -> let % bind result = Timer . time timer ( sprintf " create_expected_statement :% s " __LOC__ ) __LOC__ ( fun ( ) -> Deferred . return ( create_expected_statement ~ constraint_constants ~ get_state transaction ) ) in let % map ( ) = yield_always ( ) in result | ` Partial -> return transaction . statement in let % bind ( ) = yield_always ( ) in if Transaction_snark . Statement . equal transaction . statement expected_statement then let % bind acc_stmt = merge_acc ~ proofs [ ] : acc_statement transaction . statement in let % map acc_pc = merge_pc acc_pc transaction . statement |> Deferred . return in ( acc_stmt , acc_pc ) acc_pc else Deferred . Or_error . error_string ( sprintf " ! Bad base statement expected : \ { % sexp : Transaction_snark . Statement . t } t got : \ { % sexp : Transaction_snark . Statement . t } t " transaction . statement expected_statement ) ) in let % bind . Deferred res = Fold . fold_chronological_until tree ~ init ( : None , None ) None ~ f_merge ( : fun acc ( _weight , job ) job -> let open Container . Continue_or_stop in match % map . Deferred fold_step_a acc job with | Ok next -> Continue next | e -> Stop e ) ~ f_base ( : fun acc ( _weight , job ) job -> let open Container . Continue_or_stop in match % map . Deferred fold_step_d acc job with | Ok next -> Continue next | e -> Stop e ) ~ finish : return in Timer . log " scan_statement " timer ; match res with | Ok ( None , _ ) _ -> Deferred . return ( Error ` Empty ) Empty | Ok ( Some ( res , proofs ) proofs , _ ) _ -> ( match % map . Deferred Verifier . verify ~ verifier proofs with | Ok true -> Ok res | Ok false -> Error ( ` Error ( Error . of_string " Bad proofs ) ) " | Error e -> Error ( ` Error e ) e ) | Error e -> Deferred . return ( Error ( ` Error e ) e ) e let check_invariants t ~ constraint_constants ~ statement_check ~ verifier ~ error_prefix ( ~ registers_begin : ( Frozen_ledger_hash . t , Pending_coinbase . Stack . t , Mina_state . Local_state . t ) Mina_state . Registers . t option ) ( ~ registers_end : ( Frozen_ledger_hash . t , Pending_coinbase . Stack . t , Mina_state . Local_state . t ) Mina_state . Registers . t ) = let clarify_error cond err = if not cond then Or_error . errorf " % s : % s " error_prefix err else Ok ( ) in let check_registers ( reg1 : _ Mina_state . Registers . t ) t ( reg2 : _ Mina_state . Registers . t ) t = let open Or_error . Let_syntax in let % map ( ) = clarify_error ( Frozen_ledger_hash . equal reg1 . ledger reg2 . ledger ) ledger " did not connect with snarked ledger hash " and ( ) = clarify_error ( Pending_coinbase . Stack . connected ~ first : reg1 . pending_coinbase_stack ~ second : reg2 . pending_coinbase_stack ( ) ) " did not connect with pending - coinbase stack " and ( ) = clarify_error ( Mina_transaction_logic . Parties_logic . Local_state . Value . equal reg1 . local_state reg2 . local_state ) " did not connect with local state " in ( ) in match % map O1trace . sync_thread " validate_transaction_snark_scan_state " ( fun ( ) -> scan_statement t ~ constraint_constants ~ statement_check ~ verifier ) with | Error ( ` Error e ) e -> Error e | Error ` Empty -> Option . value_map ~ default ( : Ok ( ) ) registers_begin ~ f ( : fun registers_begin -> check_registers registers_begin registers_end ) | Ok { fee_excess = { fee_token_l ; fee_excess_l ; fee_token_r ; fee_excess_r } ; source ; target ; supply_increase = _ ; sok_digest = ( ) } -> let open Or_error . Let_syntax in let % map ( ) = Option . value_map ~ default ( : Ok ( ) ) registers_begin ~ f ( : fun registers_begin -> check_registers registers_begin source ) source and ( ) = check_registers registers_end target and ( ) = clarify_error ( Fee . Signed . equal Fee . Signed . zero fee_excess_l ) fee_excess_l " nonzero fee excess " and ( ) = clarify_error ( Fee . Signed . equal Fee . Signed . zero fee_excess_r ) fee_excess_r " nonzero fee excess " and ( ) = clarify_error ( Token_id . equal Token_id . default fee_token_l ) fee_token_l " nondefault fee token " and ( ) = clarify_error ( Token_id . equal Token_id . default fee_token_r ) fee_token_r " nondefault fee token " in ( ) end
let statement_of_job : job -> Transaction_snark . Statement . t option = function | Base { statement ; _ } -> Some statement | Merge ( ( p1 , _ ) _ , ( p2 , _ ) _ ) _ -> Transaction_snark . Statement . merge ( Ledger_proof . statement p1 ) p1 ( Ledger_proof . statement p2 ) p2 |> Result . ok
let create ~ work_delay ~ transaction_capacity_log_2 = let k = Int . pow 2 transaction_capacity_log_2 in Parallel_scan . empty ~ delay : work_delay ~ max_base_jobs : k
let empty ( ~ constraint_constants : Genesis_constants . Constraint_constants . t ) t ( ) = create ~ work_delay : constraint_constants . work_delay ~ transaction_capacity_log_2 : constraint_constants . transaction_capacity_log_2
let extract_txns txns_with_witnesses = List . map txns_with_witnesses ~ f ( : fun ( txn_with_witness : Transaction_with_witness . t ) t -> let txn = Ledger . Transaction_applied . transaction txn_with_witness . transaction_with_info in let state_hash = fst txn_with_witness . state_hash in ( txn , state_hash ) state_hash )
let latest_ledger_proof t = let open Option . Let_syntax in let % map proof , txns_with_witnesses = Parallel_scan . last_emitted_value t in ( proof , extract_txns txns_with_witnesses ) txns_with_witnesses
let staged_transactions t = List . map ~ f ( : fun ( t : Transaction_with_witness . t ) t -> t . transaction_with_info |> Ledger . Transaction_applied . transaction ) @@ Parallel_scan . pending_data t
let staged_transactions_with_protocol_states t ( ~ get_state : State_hash . t -> Mina_state . Protocol_state . value Or_error . t ) t = let open Or_error . Let_syntax in List . map ~ f ( : fun ( t : Transaction_with_witness . t ) t -> let txn = t . transaction_with_info |> Ledger . Transaction_applied . transaction in let % map protocol_state = get_state ( fst t . state_hash ) state_hash in ( txn , protocol_state ) protocol_state ) @@ Parallel_scan . pending_data t |> Or_error . all
let partition_if_overflowing t = let bundle_count work_count = ( work_count + 1 ) 1 / 2 in let { Space_partition . first = slots , job_count ; second } = Parallel_scan . partition_if_overflowing t in { Space_partition . first = ( slots , bundle_count job_count ) job_count ; second = Option . map second ~ f ( : fun ( slots , job_count ) job_count -> ( slots , bundle_count job_count ) job_count ) }
let extract_from_job ( job : job ) job = match job with | Parallel_scan . Available_job . Base d -> First ( d . transaction_with_info , d . statement , d . state_hash , d . ledger_witness , d . init_stack ) | Merge ( ( p1 , _ ) _ , ( p2 , _ ) _ ) _ -> Second ( p1 , p2 ) p2
let snark_job_list_json t = let all_jobs : Job_view . t list list = let fa ( a : Ledger_proof_with_sok_message . t ) t = Ledger_proof . statement ( fst a ) a in let fd ( d : Transaction_with_witness . t ) t = d . statement in Parallel_scan . view_jobs_with_position t fa fd in Yojson . Safe . to_string ( ` List ( List . map all_jobs ~ f ( : fun tree -> ` List ( List . map tree ~ f : Job_view . to_yojson ) to_yojson ) ) )
let all_work_statements_exn t : Transaction_snark_work . Statement . t list = let work_seqs = all_jobs t in List . concat_map work_seqs ~ f ( : fun work_seq -> One_or_two . group_list ( List . map work_seq ~ f ( : fun job -> match statement_of_job job with | None -> assert false | Some stmt -> stmt ) ) )
let required_work_pairs t ~ slots = let work_list = Parallel_scan . jobs_for_slots t ~ slots in List . concat_map work_list ~ f ( : fun works -> One_or_two . group_list works ) works
let k_work_pairs_for_new_diff t ~ k = let work_list = Parallel_scan . jobs_for_next_update t in List ( . take ( concat_map work_list ~ f ( : fun works -> One_or_two . group_list works ) works ) works k ) k
let work_statements_for_new_diff t : Transaction_snark_work . Statement . t list = let work_list = Parallel_scan . jobs_for_next_update t in List . concat_map work_list ~ f ( : fun work_seq -> One_or_two . group_list ( List . map work_seq ~ f ( : fun job -> match statement_of_job job with | None -> assert false | Some stmt -> stmt ) ) )
let all_work_pairs t ( ~ get_state : State_hash . t -> Mina_state . Protocol_state . value Or_error . t ) t : ( Transaction_witness . t , Ledger_proof . t ) t Snark_work_lib . Work . Single . Spec . t One_or_two . t list Or_error . t = let all_jobs = all_jobs t in let module A = Available_job in let open Or_error . Let_syntax in let single_spec ( job : job ) job = match extract_from_job job with | First ( transaction_with_info , statement , state_hash , ledger_witness , init_stack ) -> let % map witness = let { With_status . data = transaction ; status } = Mina_transaction_logic . Transaction_applied . transaction_with_status transaction_with_info in let % bind protocol_state_body = let % map state = get_state ( fst state_hash ) state_hash in Mina_state . Protocol_state . body state in let % map init_stack = match init_stack with | Base x -> Ok x | Merge -> Or_error . error_string " init_stack was Merge " in { Transaction_witness . ledger = ledger_witness ; transaction ; protocol_state_body ; init_stack ; status } in Snark_work_lib . Work . Single . Spec . Transition ( statement , witness ) witness | Second ( p1 , p2 ) p2 -> let % map merged = Transaction_snark . Statement . merge ( Ledger_proof . statement p1 ) p1 ( Ledger_proof . statement p2 ) p2 in Snark_work_lib . Work . Single . Spec . Merge ( merged , p1 , p2 ) p2 in List . fold_until all_jobs ~ init [ ] : ~ finish ( : fun lst -> Ok lst ) lst ~ f ( : fun acc jobs -> let specs_list : ' a One_or_two . t list Or_error . t = List . fold ~ init ( : Ok [ ] ) ( One_or_two . group_list jobs ) jobs ~ f ( : fun acc ' pair -> let % bind acc ' = acc ' in let % map spec = One_or_two . Or_error . map ~ f : single_spec pair in spec :: acc ' ) in match specs_list with | Ok list -> Continue ( acc @ List . rev list ) list | Error e -> Stop ( Error e ) e )
let fill_work_and_enqueue_transactions t transactions work = let open Or_error . Let_syntax in let fill_in_transaction_snark_work t ( works : Transaction_snark_work . t list ) list : ( Ledger_proof . t * Sok_message . t ) t list Or_error . t = let next_jobs = List ( . take ( concat @@ Parallel_scan . jobs_for_next_update t ) t ( total_proofs works ) works ) works in map2_or_error next_jobs ( List . concat_map works ~ f ( : fun { Transaction_snark_work . fee ; proofs ; prover } -> One_or_two . map proofs ~ f ( : fun proof -> ( fee , proof , prover ) prover ) prover |> One_or_two . to_list ) ) ~ f : completed_work_to_scanable_work in let old_proof = Parallel_scan . last_emitted_value t in let % bind work_list = fill_in_transaction_snark_work t work in let % bind proof_opt , updated_scan_state = Parallel_scan . update t ~ completed_jobs : work_list ~ data : transactions in let % map result_opt = Option . value_map ~ default ( : Ok None ) None proof_opt ~ f ( : fun ( ( proof , _ ) _ , txns_with_witnesses ) txns_with_witnesses -> let curr_source = ( Ledger_proof . statement proof ) proof . source in let prev_target = Option . value_map ~ default : curr_source old_proof ~ f ( : fun ( ( p ' , _ ) _ , _ ) _ -> ( Ledger_proof . statement p ' ) p ' . target ) target in if Mina_state . Registers . Value . connected prev_target curr_source then Ok ( Some ( proof , extract_txns txns_with_witnesses ) txns_with_witnesses ) txns_with_witnesses else Or_error . error_string " Unexpected ledger proof emitted " ) in ( result_opt , updated_scan_state ) updated_scan_state
let required_state_hashes t = List . fold ~ init : State_hash . Set . empty ~ f ( : fun acc ( t : Transaction_with_witness . t ) t -> Set . add acc ( fst t . state_hash ) state_hash ) ( Parallel_scan . pending_data t ) t
let check_required_protocol_states t ~ protocol_states = let open Or_error . Let_syntax in let required_state_hashes = required_state_hashes t in let check_length states = let required = State_hash . Set . length required_state_hashes in let received = List . length states in if required = received then Or_error . return ( ) else Or_error . errorf " ! Required % d protocol states but received % d " required received in let % bind ( ) = check_length protocol_states in let received_state_map = List . fold protocol_states ~ init : Mina_base . State_hash . Map . empty ~ f ( : fun m ps -> State_hash . Map . set m ~ key ( : State_hash . With_state_hashes . state_hash ps ) ps ~ data : ps ) in let protocol_states_assoc = List . filter_map ( State_hash . Set . to_list required_state_hashes ) required_state_hashes ~ f ( : State_hash . Map . find received_state_map ) received_state_map in let % map ( ) = check_length protocol_states_assoc in protocol_states_assoc
module Statement = struct module Arg = struct [ %% versioned module Stable = struct module V2 = struct type t = Transaction_snark . Statement . Stable . V2 . t One_or_two . Stable . V1 . t [ @@ deriving hash , sexp , compare ] compare let to_latest = Fn . id end end ] end end [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type t = Transaction_snark . Statement . Stable . V2 . t One_or_two . Stable . V1 . t [ @@ deriving equal , compare , hash , sexp , yojson ] yojson let to_latest = Fn . id type _unused = unit constraint t = Arg . Stable . V2 . t include Hashable . Make_binable ( Arg . Stable . V2 ) V2 end end ] end type t = Stable . Latest . t [ @@ deriving sexp , hash , compare , yojson , equal ] equal include Hashable . Make ( Stable . Latest ) Latest let gen = One_or_two . gen Transaction_snark . Statement . gen let compact_json t = ` List ( One_or_two . map ~ f ( : fun s -> ` Int ( Transaction_snark . Statement . hash s ) s ) s t |> One_or_two . to_list ) let work_ids t : int One_or_two . t = One_or_two . map t ~ f : Transaction_snark . Statement . hash end