text
stringlengths
12
786k
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
module Info = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type t = { statements : Statement . Stable . V2 . t ; work_ids : int One_or_two . Stable . V1 . t ; fee : Fee . Stable . V1 . t ; prover : Public_key . Compressed . Stable . V1 . t } [ @@ deriving compare , sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end type t = Stable . Latest . t = { statements : Statement . t ; work_ids : int One_or_two . t ; fee : Fee . t ; prover : Public_key . Compressed . t } [ @@ deriving to_yojson , sexp , compare ] compare end
module T = struct [ %% versioned module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type t = { fee : Fee . Stable . V1 . t ; proofs : Ledger_proof . Stable . V2 . t One_or_two . Stable . V1 . t ; prover : Public_key . Compressed . Stable . V1 . t } [ @@ deriving compare , sexp , yojson ] yojson let to_latest = Fn . id end end ] end type t = Stable . Latest . t = { fee : Fee . t ; proofs : Ledger_proof . t One_or_two . t ; prover : Public_key . Compressed . t } [ @@ deriving compare , yojson , sexp ] sexp let statement t = One_or_two . map t . proofs ~ f : Ledger_proof . statement let info t = let statements = One_or_two . map t . proofs ~ f : Ledger_proof . statement in { Info . statements ; work_ids = One_or_two . map statements ~ f : Transaction_snark . Statement . hash ; fee = t . fee ; prover = t . prover } end
module Checked = struct include T let create_unsafe = Fn . id end
let fee { fee ; _ } = fee
module Failure = struct [ %% versioned module Stable = struct module V2 = struct type t = | Predicate [ @ value 1 ] 1 | Source_not_present | Receiver_not_present | Amount_insufficient_to_create_account | Cannot_pay_creation_fee_in_token | Source_insufficient_balance | Source_minimum_balance_violation | Receiver_already_exists | Token_owner_not_caller | Overflow | Global_excess_overflow | Local_excess_overflow | Signed_command_on_zkapp_account | Zkapp_account_not_present | Update_not_permitted_balance | Update_not_permitted_timing_existing_account | Update_not_permitted_delegate | Update_not_permitted_app_state | Update_not_permitted_verification_key | Update_not_permitted_sequence_state | Update_not_permitted_zkapp_uri | Update_not_permitted_token_symbol | Update_not_permitted_permissions | Update_not_permitted_nonce | Update_not_permitted_voting_for | Parties_replay_check_failed | Fee_payer_nonce_must_increase | Fee_payer_must_be_signed | Account_balance_precondition_unsatisfied | Account_nonce_precondition_unsatisfied | Account_receipt_chain_hash_precondition_unsatisfied | Account_delegate_precondition_unsatisfied | Account_sequence_state_precondition_unsatisfied | Account_app_state_precondition_unsatisfied of int | Account_proved_state_precondition_unsatisfied | Protocol_state_precondition_unsatisfied | Incorrect_nonce | Invalid_fee_excess [ @@ deriving sexp , yojson , equal , compare , variants , hash ] hash let to_latest = Fn . id end end ] end module Collection = struct type display = ( int * Stable . Latest . t list ) list list [ @@ deriving equal , yojson , sexp , bin_io_unversioned ] bin_io_unversioned [ %% versioned module Stable = struct module V1 = struct type t = Stable . V2 . t list list [ @@ deriving equal , compare , yojson , sexp , hash ] hash let to_latest = Fn . id end end ] end let to_display t = let _ , display = List . fold_right t ~ init ( : 0 , [ ] ) ~ f ( : fun bucket ( index , acc ) acc -> if List . is_empty bucket then ( index + 1 , acc ) acc else ( index + 1 , ( index , bucket ) bucket :: acc ) acc ) in display let empty = [ ] let of_single_failure f : t = [ [ f ] ] let is_empty : t -> bool = Fn . compose List . is_empty List . concat end type failure = t let failure_min = min let failure_max = max let all = let add acc var = var . Variantslib . Variant . constructor :: acc in Variants . fold ~ init [ ] : ~ predicate : add ~ source_not_present : add ~ receiver_not_present : add ~ amount_insufficient_to_create_account : add ~ cannot_pay_creation_fee_in_token : add ~ source_insufficient_balance : add ~ source_minimum_balance_violation : add ~ receiver_already_exists : add ~ token_owner_not_caller : add ~ overflow : add ~ global_excess_overflow : add ~ local_excess_overflow : add ~ signed_command_on_zkapp_account : add ~ zkapp_account_not_present : add ~ update_not_permitted_balance : add ~ update_not_permitted_timing_existing_account : add ~ update_not_permitted_delegate : add ~ update_not_permitted_app_state : add ~ update_not_permitted_verification_key : add ~ update_not_permitted_sequence_state : add ~ update_not_permitted_zkapp_uri : add ~ update_not_permitted_token_symbol : add ~ update_not_permitted_permissions : add ~ update_not_permitted_nonce : add ~ update_not_permitted_voting_for : add ~ parties_replay_check_failed : add ~ fee_payer_nonce_must_increase : add ~ fee_payer_must_be_signed : add ~ account_balance_precondition_unsatisfied : add ~ account_nonce_precondition_unsatisfied : add ~ account_receipt_chain_hash_precondition_unsatisfied : add ~ account_delegate_precondition_unsatisfied : add ~ account_sequence_state_precondition_unsatisfied : add ~ account_app_state_precondition_unsatisfied ( : fun acc var -> List . init 8 ~ f : var . constructor @ acc ) ~ account_proved_state_precondition_unsatisfied : add ~ protocol_state_precondition_unsatisfied : add ~ incorrect_nonce : add ~ invalid_fee_excess : add let gen = Quickcheck . Generator . of_list all let to_string = function | Predicate -> " Predicate " | Source_not_present -> " Source_not_present " | Receiver_not_present -> " Receiver_not_present " | Amount_insufficient_to_create_account -> " Amount_insufficient_to_create_account " | Cannot_pay_creation_fee_in_token -> " Cannot_pay_creation_fee_in_token " | Source_insufficient_balance -> " Source_insufficient_balance " | Source_minimum_balance_violation -> " Source_minimum_balance_violation " | Receiver_already_exists -> " Receiver_already_exists " | Token_owner_not_caller -> " Token_owner_not_caller " | Overflow -> " Overflow " | Global_excess_overflow -> " Global_excess_overflow " | Local_excess_overflow -> " Local_excess_overflow " | Signed_command_on_zkapp_account -> " Signed_command_on_zkapp_account " | Zkapp_account_not_present -> " Zkapp_account_not_present " | Update_not_permitted_balance -> " Update_not_permitted_balance " | Update_not_permitted_timing_existing_account -> " Update_not_permitted_timing_existing_account " | Update_not_permitted_delegate -> " update_not_permitted_delegate " | Update_not_permitted_app_state -> " Update_not_permitted_app_state " | Update_not_permitted_verification_key -> " Update_not_permitted_verification_key " | Update_not_permitted_sequence_state -> " Update_not_permitted_sequence_state " | Update_not_permitted_zkapp_uri -> " Update_not_permitted_zkapp_uri " | Update_not_permitted_token_symbol -> " Update_not_permitted_token_symbol " | Update_not_permitted_permissions -> " Update_not_permitted_permissions " | Update_not_permitted_nonce -> " Update_not_permitted_nonce " | Update_not_permitted_voting_for -> " Update_not_permitted_voting_for " | Parties_replay_check_failed -> " Parties_replay_check_failed " | Fee_payer_nonce_must_increase -> " Fee_payer_nonce_must_increase " | Fee_payer_must_be_signed -> " Fee_payer_must_be_signed " | Account_balance_precondition_unsatisfied -> " Account_balance_precondition_unsatisfied " | Account_nonce_precondition_unsatisfied -> " Account_nonce_precondition_unsatisfied " | Account_receipt_chain_hash_precondition_unsatisfied -> " Account_receipt_chain_hash_precondition_unsatisfied " | Account_delegate_precondition_unsatisfied -> " Account_delegate_precondition_unsatisfied " | Account_sequence_state_precondition_unsatisfied -> " Account_sequence_state_precondition_unsatisfied " | Account_app_state_precondition_unsatisfied i -> sprintf " Account_app_state_ % i_precondition_unsatisfied " i | Account_proved_state_precondition_unsatisfied -> " Account_proved_state_precondition_unsatisfied " | Protocol_state_precondition_unsatisfied -> " Protocol_state_precondition_unsatisfied " | Incorrect_nonce -> " Incorrect_nonce " | Invalid_fee_excess -> " Invalid_fee_excess " let of_string = function | " Predicate " -> Ok Predicate | " Source_not_present " -> Ok Source_not_present | " Receiver_not_present " -> Ok Receiver_not_present | " Amount_insufficient_to_create_account " -> Ok Amount_insufficient_to_create_account | " Cannot_pay_creation_fee_in_token " -> Ok Cannot_pay_creation_fee_in_token | " Source_insufficient_balance " -> Ok Source_insufficient_balance | " Source_minimum_balance_violation " -> Ok Source_minimum_balance_violation | " Receiver_already_exists " -> Ok Receiver_already_exists | " Token_owner_not_caller " -> Ok Token_owner_not_caller | " Overflow " -> Ok Overflow | " Global_excess_overflow " -> Ok Global_excess_overflow | " Local_excess_overflow " -> Ok Local_excess_overflow | " Signed_command_on_zkapp_account " -> Ok Signed_command_on_zkapp_account | " Zkapp_account_not_present " -> Ok Zkapp_account_not_present | " Update_not_permitted_balance " -> Ok Update_not_permitted_balance | " Update_not_permitted_timing_existing_account " -> Ok Update_not_permitted_timing_existing_account | " update_not_permitted_delegate " -> Ok Update_not_permitted_delegate | " Update_not_permitted_app_state " -> Ok Update_not_permitted_app_state | " Update_not_permitted_verification_key " -> Ok Update_not_permitted_verification_key | " Update_not_permitted_sequence_state " -> Ok Update_not_permitted_sequence_state | " Update_not_permitted_zkapp_uri " -> Ok Update_not_permitted_zkapp_uri | " Update_not_permitted_token_symbol " -> Ok Update_not_permitted_token_symbol | " Update_not_permitted_permissions " -> Ok Update_not_permitted_permissions | " Update_not_permitted_nonce " -> Ok Update_not_permitted_nonce | " Update_not_permitted_voting_for " -> Ok Update_not_permitted_voting_for | " Parties_replay_check_failed " -> Ok Parties_replay_check_failed | " Fee_payer_nonce_must_increase " -> Ok Fee_payer_nonce_must_increase | " Fee_payer_must_be_signed " -> Ok Fee_payer_must_be_signed | " Account_balance_precondition_unsatisfied " -> Ok Account_balance_precondition_unsatisfied | " Account_nonce_precondition_unsatisfied " -> Ok Account_nonce_precondition_unsatisfied | " Account_receipt_chain_hash_precondition_unsatisfied " -> Ok Account_receipt_chain_hash_precondition_unsatisfied | " Account_delegate_precondition_unsatisfied " -> Ok Account_delegate_precondition_unsatisfied | " Account_sequence_state_precondition_unsatisfied " -> Ok Account_sequence_state_precondition_unsatisfied | " Account_proved_state_precondition_unsatisfied " -> Ok Account_proved_state_precondition_unsatisfied | " Protocol_state_precondition_unsatisfied " -> Ok Protocol_state_precondition_unsatisfied | " Incorrect_nonce " -> Ok Incorrect_nonce | " Invalid_fee_excess " -> Ok Invalid_fee_excess | str -> ( let res = List . find_map ~ f ( : fun ( prefix , suffix , parse ) parse -> Option . try_with ( fun ( ) -> assert ( String . length str >= String . length prefix + String . length suffix ) ; for i = 0 to String . length prefix - 1 do assert ( Char . equal prefix [ . i ] i str [ . i ] i ) i done ; let offset = String . length str - String . length suffix in for i = 0 to String . length suffix - 1 do assert ( Char . equal suffix [ . i ] i str [ . offset + i ] i ) i done ; parse ( String . sub str ~ pos ( : String . length prefix ) prefix ~ len ( : offset - String . length prefix ) prefix ) ) ) [ ( " Account_app_state_ " , " _precondition_unsatisfied " , fun str -> Account_app_state_precondition_unsatisfied ( int_of_string str ) str ) ] in match res with | Some res -> Ok res | None -> Error " Transaction_status . Failure . of_string : Unknown value " ) let % test_unit " of_string ( of_stringto_string ) of_stringto_string roundtrip " = List . iter all ~ f ( : fun failure -> [ % test_eq : ( t , string ) string Result . t ] t ( of_string ( to_string failure ) failure ) failure ( Ok failure ) failure ) let describe = function | Predicate -> " A predicate failed " | Source_not_present -> " The source account does not exist " | Receiver_not_present -> " The receiver account does not exist " | Amount_insufficient_to_create_account -> " Cannot create account : transaction amount is smaller than the account \ creation fee " | Cannot_pay_creation_fee_in_token -> " Cannot create account : account creation fees cannot be paid in \ non - default tokens " | Source_insufficient_balance -> " The source account has an insufficient balance " | Source_minimum_balance_violation -> " The source account requires a minimum balance " | Receiver_already_exists -> " Attempted to create an account that already exists " | Token_owner_not_caller -> " A party used a non - default token but its caller was not the token \ owner " | Overflow -> " The resulting balance is too large to store " | Global_excess_overflow -> " The resulting global fee excess is too large to store " | Local_excess_overflow -> " The resulting local fee excess is too large to store " | Signed_command_on_zkapp_account -> " The source of a signed command cannot be a snapp account " | Zkapp_account_not_present -> " A snapp account does not exist " | Update_not_permitted_balance -> " The authentication for an account didn ' t allow the requested update \ to its balance " | Update_not_permitted_timing_existing_account -> " The timing of an existing account cannot be updated " | Update_not_permitted_delegate -> " The authentication for an account didn ' t allow the requested update \ to its delegate " | Update_not_permitted_app_state -> " The authentication for an account didn ' t allow the requested update \ to its app state " | Update_not_permitted_verification_key -> " The authentication for an account didn ' t allow the requested update \ to its verification key " | Update_not_permitted_sequence_state -> " The authentication for an account didn ' t allow the requested update \ to its sequence state " | Update_not_permitted_zkapp_uri -> " The authentication for an account didn ' t allow the requested update \ to its snapp URI " | Update_not_permitted_token_symbol -> " The authentication for an account didn ' t allow the requested update \ to its token symbol " | Update_not_permitted_permissions -> " The authentication for an account didn ' t allow the requested update \ to its permissions " | Update_not_permitted_nonce -> " The authentication for an account didn ' t allow the requested update \ to its nonce " | Update_not_permitted_voting_for -> " The authentication for an account didn ' t allow the requested update \ to its voted - for state hash " | Parties_replay_check_failed -> " Check to avoid replays failed . The party must increment nonce or use \ full commitment if the authorization is a signature " | Fee_payer_nonce_must_increase -> " Fee payer party must increment its nonce " | Fee_payer_must_be_signed -> " Fee payer party must have a valid signature " | Account_balance_precondition_unsatisfied -> " The party ' s account balance precondition was unsatisfied " | Account_nonce_precondition_unsatisfied -> " The party ' s account nonce precondition was unsatisfied " | Account_receipt_chain_hash_precondition_unsatisfied -> " The party ' s account receipt - chain hash precondition was unsatisfied " | Account_delegate_precondition_unsatisfied -> " The party ' s account delegate precondition was unsatisfied " | Account_sequence_state_precondition_unsatisfied -> " The party ' s account sequence state precondition was unsatisfied " | Account_app_state_precondition_unsatisfied i -> sprintf " The party ' s account app state ( % i ) i precondition was unsatisfied " i | Account_proved_state_precondition_unsatisfied -> " The party ' s account proved state precondition was unsatisfied " | Protocol_state_precondition_unsatisfied -> " The party ' s protocol state precondition unsatisfied " | Incorrect_nonce -> " Incorrect nonce " | Invalid_fee_excess -> " Fee excess from parties transaction more than the transaction fees " end [ %% versioned
module Stable = struct module V2 = struct type t = Applied | Failed of Failure . Collection . Stable . V1 . t [ @@ deriving sexp , yojson , equal , compare ] compare let to_latest = Fn . id end end ] end
let state_body_hash = U . genesis_state_body_hash ( module struct module Ledger = struct include Ledger let merkle_root t = Frozen_ledger_hash . of_ledger_hash @@ merkle_root t let merkle_root_after_user_command_exn t ~ txn_global_slot txn = let hash = merkle_root_after_user_command_exn ~ constraint_constants : U . constraint_constants ~ txn_global_slot t txn in Frozen_ledger_hash . of_ledger_hash hash end module Sparse_ledger = struct include Sparse_ledger let merkle_root t = Frozen_ledger_hash . of_ledger_hash @@ merkle_root t end 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 of_user_command ' ( sok_digest : Sok_message . Digest . t ) t ledger ( user_command : Signed_command . With_valid_signature . t ) t init_stack pending_coinbase_stack_state state_body handler = let source = Ledger . merkle_root ledger in let current_global_slot = Mina_state . Protocol_state . Body . consensus_state state_body |> Consensus . Data . Consensus_state . global_slot_since_genesis in let target = Ledger . merkle_root_after_user_command_exn ledger ~ txn_global_slot : current_global_slot user_command in let user_command_in_block = { Transaction_protocol_state . Poly . transaction = user_command ; block_data = state_body } in Async . Thread_safe . block_on_async_exn ( fun ( ) -> let statement = let txn = Transaction . Command ( User_command . Signed_command ( Signed_command . forget_check user_command ) user_command ) in Transaction_snark . Statement . Poly . with_empty_local_state ~ source ~ target ~ sok_digest ~ fee_excess ( : Or_error . ok_exn ( Transaction . fee_excess txn ) txn ) txn ~ supply_increase : ( Or_error . ok_exn ( Transaction . supply_increase txn ) txn ) txn ~ pending_coinbase_stack_state in U . T . of_user_command ~ init_stack ~ statement user_command_in_block handler ) let coinbase_test state_body ~ carryforward = let mk_pubkey ( ) = Public_key ( . compress ( of_private_key_exn ( Private_key . create ( ) ) ) ) in let state_body_hash = Mina_state . Protocol_state . Body . hash state_body in let producer = mk_pubkey ( ) in let producer_id = Account_id . create producer Token_id . default in let receiver = mk_pubkey ( ) in let receiver_id = Account_id . create receiver Token_id . default in let other = mk_pubkey ( ) in let other_id = Account_id . create other Token_id . default in let pending_coinbase_init = Pending_coinbase . Stack . empty in let cb = Coinbase . create ~ amount ( : Currency . Amount . of_int 10_000_000_000 ) 10_000_000_000 ~ receiver ~ fee_transfer : ( Some ( Coinbase . Fee_transfer . create ~ receiver_pk : other ~ fee : U . constraint_constants . account_creation_fee ) ) |> Or_error . ok_exn in let transaction = Mina_transaction . Transaction . Coinbase cb in let source_stack = if carryforward then Pending_coinbase . Stack ( . push_state state_body_hash pending_coinbase_init ) pending_coinbase_init else pending_coinbase_init in let pending_coinbase_stack_target = U . pending_coinbase_stack_target transaction U . genesis_state_body_hash pending_coinbase_init in let txn_in_block = { Transaction_protocol_state . Poly . transaction ; block_data = state_body } in Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Ledger . create_new_account_exn ledger producer_id ( Account . create receiver_id Balance . zero ) zero ; let sparse_ledger = Sparse_ledger . of_ledger_subset_exn ledger [ producer_id ; receiver_id ; other_id ] in let sparse_ledger_after , _ = Sparse_ledger . apply_transaction ~ constraint_constants : U . constraint_constants sparse_ledger ~ txn_state_view : ( txn_in_block . block_data |> Mina_state . Protocol_state . Body . view ) view txn_in_block . transaction |> Or_error . ok_exn in Transaction_snark . check_transaction txn_in_block ( unstage ( Sparse_ledger . handler sparse_ledger ) sparse_ledger ) sparse_ledger ~ constraint_constants : U . constraint_constants ~ sok_message : ( Mina_base . Sok_message . create ~ fee : Currency . Fee . zero ~ prover : Public_key . Compressed . empty ) ~ source ( : Sparse_ledger . merkle_root sparse_ledger ) sparse_ledger ~ target ( : Sparse_ledger . merkle_root sparse_ledger_after ) sparse_ledger_after ~ init_stack : pending_coinbase_init ~ pending_coinbase_stack_state : { source = source_stack ; target = pending_coinbase_stack_target } ~ zkapp_account1 : None ~ zkapp_account2 : None ) let % test_unit " coinbase with new state body hash " = Test_util . with_randomness 123456789 ( fun ( ) -> coinbase_test state_body ~ carryforward : false ) let % test_unit " coinbase with carry - forward state body hash " = Test_util . with_randomness 123456789 ( fun ( ) -> coinbase_test state_body ~ carryforward : true ) let % test_unit " new_account " = Test_util . with_randomness 123456789 ( fun ( ) -> let wallets = U . Wallet . random_wallets ( ) in Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> Array . iter ( Array . sub wallets ~ pos : 1 ~ len ( : Array . length wallets - 1 ) 1 ) 1 ~ f ( : fun { account ; private_key = _ } -> Ledger . create_new_account_exn ledger ( Account . identifier account ) account account ) ; let t1 = U . Wallet . user_command_with_wallet wallets ~ sender : 1 ~ receiver : 0 8_000_000_000 ( Fee . of_int ( Random . int 20 * 1_000_000_000 ) 1_000_000_000 ) 1_000_000_000 Account . Nonce . zero ( Signed_command_memo . create_by_digesting_string_exn ( Test_util . arbitrary_string ~ len : Signed_command_memo . max_digestible_string_length ) ) in let current_global_slot = Mina_state . Protocol_state . Body . consensus_state state_body |> Consensus . Data . Consensus_state . global_slot_since_genesis in let target = Ledger . merkle_root_after_user_command_exn ledger ~ txn_global_slot : current_global_slot t1 in let mentioned_keys = Signed_command . accounts_accessed ( Signed_command . forget_check t1 ) t1 in let sparse_ledger = Sparse_ledger . of_ledger_subset_exn ledger mentioned_keys in let sok_message = Sok_message . create ~ fee : Fee . zero ~ prover : wallets ( . 1 ) 1 . account . public_key in let pending_coinbase_stack = Pending_coinbase . Stack . empty in let pending_coinbase_stack_target = U . pending_coinbase_stack_target ( Command ( Signed_command t1 ) t1 ) t1 state_body_hash pending_coinbase_stack in let pending_coinbase_stack_state = { Transaction_snark . Pending_coinbase_stack_state . source = pending_coinbase_stack ; target = pending_coinbase_stack_target } in Transaction_snark . check_user_command ~ constraint_constants ~ sok_message ~ source ( : Ledger . merkle_root ledger ) ledger ~ target ~ init_stack : pending_coinbase_stack ~ pending_coinbase_stack_state { transaction = t1 ; block_data = state_body } ( unstage @@ Sparse_ledger . handler sparse_ledger ) sparse_ledger ) ) let account_fee = Fee . to_int constraint_constants . account_creation_fee let test_transaction ~ constraint_constants ? txn_global_slot ledger txn = let source = Ledger . merkle_root ledger in let pending_coinbase_stack = Pending_coinbase . Stack . empty in let state_body , state_body_hash = match txn_global_slot with | None -> ( state_body , state_body_hash ) state_body_hash | Some txn_global_slot -> let state_body = let state = Mina_state . Protocol_state . create ~ previous_state_hash : Tick0 . Field . zero ~ body : state_body in let consensus_state_at_slot = Consensus . Data . Consensus_state . Value . For_tests . with_global_slot_since_genesis ( Mina_state . Protocol_state . consensus_state state ) state txn_global_slot in Mina_state . Protocol_state ( . create_value ~ previous_state_hash ( : previous_state_hash state ) state ~ genesis_state_hash ( : genesis_state_hash state ) state ~ blockchain_state ( : blockchain_state state ) state ~ consensus_state : consensus_state_at_slot ~ constants : ( Protocol_constants_checked . value_of_t Genesis_constants . compiled . protocol ) ) . body in let state_body_hash = Mina_state . Protocol_state . Body . hash state_body in ( state_body , state_body_hash ) state_body_hash in let txn_state_view : Zkapp_precondition . Protocol_state . View . t = Mina_state . Protocol_state . Body . view state_body in let mentioned_keys , pending_coinbase_stack_target = let pending_coinbase_stack = Pending_coinbase . Stack . push_state state_body_hash pending_coinbase_stack in match ( txn : Transaction . Valid . t ) t with | Command ( Signed_command uc ) uc -> ( Signed_command . accounts_accessed ( uc :> Signed_command . t ) t , pending_coinbase_stack ) | Command ( Parties _ ) _ -> failwith " Parties commands not yet supported " | Fee_transfer ft -> ( Fee_transfer . receivers ft , pending_coinbase_stack ) pending_coinbase_stack | Coinbase cb -> ( Coinbase . accounts_accessed cb , Pending_coinbase . Stack . push_coinbase cb pending_coinbase_stack ) in let sok_signer = match to_preunion ( txn :> Transaction . t ) t with | ` Transaction t -> ( Transaction_union . of_transaction t ) t . signer |> Public_key . compress | ` Parties c -> Account_id . public_key ( Parties . fee_payer c ) c in let sparse_ledger = Sparse_ledger . of_ledger_subset_exn ledger mentioned_keys in let _applied = Or_error . ok_exn @@ Ledger . apply_transaction ledger ~ constraint_constants ~ txn_state_view ( txn :> Transaction . t ) t in let target = Ledger . merkle_root ledger in let sok_message = Sok_message . create ~ fee : Fee . zero ~ prover : sok_signer in Transaction_snark . check_transaction ~ constraint_constants ~ sok_message ~ source ~ target ~ init_stack : pending_coinbase_stack ~ pending_coinbase_stack_state : { Transaction_snark . Pending_coinbase_stack_state . source = pending_coinbase_stack ; target = pending_coinbase_stack_target } ~ zkapp_account1 : None ~ zkapp_account2 : None { transaction = txn ; block_data = state_body } ( unstage @@ Sparse_ledger . handler sparse_ledger ) sparse_ledger let % test_unit " account creation fee - user commands " = Test_util . with_randomness 123456789 ( fun ( ) -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) |> Array . to_list in let sender = List . hd_exn wallets in let receivers = List . tl_exn wallets in let txns_per_receiver = 2 in let amount = 8_000_000_000 in let txn_fee = 2_000_000_000 in let memo = Signed_command_memo . create_by_digesting_string_exn ( Test_util . arbitrary_string ~ len : Signed_command_memo . max_digestible_string_length ) in Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let _ , ucs = let receivers = List . fold ~ init : receivers ( List . init ( txns_per_receiver - 1 ) 1 ~ f : Fn . id ) id ~ f ( : fun acc _ -> receivers @ acc ) acc in List . fold receivers ~ init ( : Account . Nonce . zero , [ ] ) ~ f ( : fun ( nonce , txns ) txns receiver -> let uc = U . Wallet . user_command ~ fee_payer : sender ~ source_pk ( : Account . public_key sender . account ) account ~ receiver_pk ( : Account . public_key receiver . account ) account amount ( Fee . of_int txn_fee ) txn_fee nonce memo in ( Account . Nonce . succ nonce , txns @ [ uc ] ) ) in Ledger . create_new_account_exn ledger ( Account . identifier sender . account ) account sender . account ; let ( ) = List . iter ucs ~ f ( : fun uc -> test_transaction ~ constraint_constants ledger ( Transaction . Command ( Signed_command uc ) uc ) uc ) in List . iter receivers ~ f ( : fun receiver -> U . check_balance ( Account . identifier receiver . account ) account ( ( amount * txns_per_receiver ) txns_per_receiver - account_fee ) account_fee ledger ) ; U . check_balance ( Account . identifier sender . account ) account ( Balance . to_int sender . account . balance - ( amount + txn_fee ) txn_fee * txns_per_receiver * List . length receivers ) ledger ) ) let % test_unit " account creation fee - fee transfers " = Test_util . with_randomness 123456789 ( fun ( ) -> let receivers = U . Wallet . random_wallets ~ n : 3 ( ) |> Array . to_list in let txns_per_receiver = 3 in let fee = 8_000_000_000 in Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let fts = let receivers = List . fold ~ init : receivers ( List . init ( txns_per_receiver - 1 ) 1 ~ f : Fn . id ) id ~ f ( : fun acc _ -> receivers @ acc ) acc |> One_or_two . group_list in List . fold receivers ~ init [ ] : ~ f ( : fun txns receiver -> let ft : Fee_transfer . t = Or_error . ok_exn @@ Fee_transfer . of_singles @@ One_or_two . map receiver ~ f ( : fun receiver -> Fee_transfer . Single . create ~ receiver_pk : receiver . account . public_key ~ fee ( : Currency . Fee . of_int fee ) fee ~ fee_token : receiver . account . token_id ) in txns @ [ ft ] ) in let ( ) = List . iter fts ~ f ( : fun ft -> let txn = Mina_transaction . Transaction . Fee_transfer ft in test_transaction ~ constraint_constants ledger txn ) in List . iter receivers ~ f ( : fun receiver -> U . check_balance ( Account . identifier receiver . account ) account ( ( fee * txns_per_receiver ) txns_per_receiver - account_fee ) account_fee ledger ) ) ) let % test_unit " account creation fee - coinbase " = Test_util . with_randomness 123456789 ( fun ( ) -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let receiver = wallets ( . 0 ) 0 in let other = wallets ( . 1 ) 1 in let dummy_account = wallets ( . 2 ) 2 in let reward = 10_000_000_000 in let fee = Fee . to_int constraint_constants . account_creation_fee in let coinbase_count = 3 in let ft_count = 2 in Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let _ , cbs = let fts = List . map ( List . init ft_count ~ f : Fn . id ) id ~ f ( : fun _ -> Coinbase . Fee_transfer . create ~ receiver_pk : other . account . public_key ~ fee : constraint_constants . account_creation_fee ) in List . fold ~ init ( : fts , [ ] ) ( List . init coinbase_count ~ f : Fn . id ) id ~ f ( : fun ( fts , cbs ) cbs _ -> let cb = Coinbase . create ~ amount ( : Currency . Amount . of_int reward ) reward ~ receiver : receiver . account . public_key ~ fee_transfer ( : List . hd fts ) fts |> Or_error . ok_exn in ( Option . value ~ default [ ] : ( List . tl fts ) fts , cb :: cbs ) cbs ) in Ledger . create_new_account_exn ledger ( Account . identifier dummy_account . account ) account dummy_account . account ; let ( ) = List . iter cbs ~ f ( : fun cb -> let txn = Mina_transaction . Transaction . Coinbase cb in test_transaction ~ constraint_constants ledger txn ) in let fees = fee * ft_count in U . check_balance ( Account . identifier receiver . account ) account ( ( reward * coinbase_count ) coinbase_count - account_fee - fees ) fees ledger ; U . check_balance ( Account . identifier other . account ) account ( fees - account_fee ) account_fee ledger ) ) module Pc_with_init_stack = struct type t = { pc : Transaction_snark . Pending_coinbase_stack_state . t ; init_stack : Pending_coinbase . Stack . t } end let test_base_and_merge ~ state_hash_and_body1 ~ state_hash_and_body2 ~ carryforward1 ~ carryforward2 = Test_util . with_randomness 123456789 ( fun ( ) -> let wallets = U . Wallet . random_wallets ( ) in let state_body_hash1 , state_body1 = state_hash_and_body1 in let state_body_hash2 , state_body2 = state_hash_and_body2 in Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> Array . iter wallets ~ f ( : fun { account ; private_key = _ } -> Ledger . create_new_account_exn ledger ( Account . identifier account ) account account ) ; let memo = Signed_command_memo . create_by_digesting_string_exn ( Test_util . arbitrary_string ~ len : Signed_command_memo . max_digestible_string_length ) in let t1 = U . Wallet . user_command_with_wallet wallets ~ sender : 0 ~ receiver : 1 8_000_000_000 ( Fee . of_int ( Random . int 20 * 1_000_000_000 ) 1_000_000_000 ) 1_000_000_000 Account . Nonce . zero memo in let t2 = U . Wallet . user_command_with_wallet wallets ~ sender : 1 ~ receiver : 2 8_000_000_000 ( Fee . of_int ( Random . int 20 * 1_000_000_000 ) 1_000_000_000 ) 1_000_000_000 Account . Nonce . zero memo in let sok_digest = Sok_message . create ~ fee : Fee . zero ~ prover : wallets ( . 0 ) 0 . account . public_key |> Sok_message . digest in let sparse_ledger = Sparse_ledger . of_ledger_subset_exn ledger ( List . concat_map ~ f ( : fun t -> Signed_command . accounts_accessed ( Signed_command . forget_check t ) t ) [ t1 ; t2 ] ) in let init_stack1 = Pending_coinbase . Stack . empty in let pending_coinbase_stack_state1 = let stack_with_state = Pending_coinbase . Stack . push_state state_body_hash1 init_stack1 in let source_stack , target_stack = if carryforward1 then ( stack_with_state , stack_with_state ) stack_with_state else ( init_stack1 , stack_with_state ) stack_with_state in { Pc_with_init_stack . pc = { source = source_stack ; target = target_stack } ; init_stack = init_stack1 } in let proof12 = of_user_command ' sok_digest ledger t1 pending_coinbase_stack_state1 . init_stack pending_coinbase_stack_state1 . pc state_body1 ( unstage @@ Sparse_ledger . handler sparse_ledger ) sparse_ledger in let current_global_slot = Mina_state . Protocol_state . Body . consensus_state state_body1 |> Consensus . Data . Consensus_state . global_slot_since_genesis in let sparse_ledger , _ = Sparse_ledger . apply_user_command ~ constraint_constants ~ txn_global_slot : current_global_slot sparse_ledger t1 |> Or_error . ok_exn in let pending_coinbase_stack_state2 , state_body2 = let previous_stack = pending_coinbase_stack_state1 . pc . target in let stack_with_state2 = Pending_coinbase . Stack ( . push_state state_body_hash2 previous_stack ) previous_stack in let source_stack , target_stack , init_stack , state_body2 = if carryforward2 then ( previous_stack , previous_stack , init_stack1 , state_body1 ) state_body1 else ( previous_stack , stack_with_state2 , previous_stack , state_body2 ) in ( { Pc_with_init_stack . pc = { source = source_stack ; target = target_stack } ; init_stack } , state_body2 ) in ignore ( Ledger . apply_user_command ~ constraint_constants ledger ~ txn_global_slot : current_global_slot t1 |> Or_error . ok_exn : Ledger . Transaction_applied . Signed_command_applied . t ) ; [ % test_eq : Frozen_ledger_hash . t ] t ( Ledger . merkle_root ledger ) ledger ( Sparse_ledger . merkle_root sparse_ledger ) sparse_ledger ; let proof23 = of_user_command ' sok_digest ledger t2 pending_coinbase_stack_state2 . init_stack pending_coinbase_stack_state2 . pc state_body2 ( unstage @@ Sparse_ledger . handler sparse_ledger ) sparse_ledger in let current_global_slot = Mina_state . Protocol_state . Body . consensus_state state_body2 |> Consensus . Data . Consensus_state . global_slot_since_genesis in let sparse_ledger , _ = Sparse_ledger . apply_user_command ~ constraint_constants ~ txn_global_slot : current_global_slot sparse_ledger t2 |> Or_error . ok_exn in ignore ( Ledger . apply_user_command ledger ~ constraint_constants ~ txn_global_slot : current_global_slot t2 |> Or_error . ok_exn : Mina_transaction_logic . Transaction_applied . Signed_command_applied . t ) ; [ % test_eq : Frozen_ledger_hash . t ] t ( Ledger . merkle_root ledger ) ledger ( Sparse_ledger . merkle_root sparse_ledger ) sparse_ledger ; let proof13 = Async . Thread_safe . block_on_async_exn ( fun ( ) -> U . T . merge ~ sok_digest proof12 proof23 ) |> Or_error . ok_exn in Async . Thread_safe . block_on_async ( fun ( ) -> U . T . verify_against_digest proof13 ) |> Result . ok_exn ) ) let % test " base_and_merge : transactions in one block ( t1 , t2 in b1 ) b1 , \ carryforward the state from a previous transaction t0 in b1 " = let state_hash_and_body1 = ( state_body_hash , state_body ) state_body in test_base_and_merge ~ state_hash_and_body1 ~ state_hash_and_body2 : state_hash_and_body1 ~ carryforward1 : true ~ carryforward2 : true let % test " base_and_merge : transactions in one block ( t1 , t2 in b1 ) b1 , don ' t \ carryforward the state from a previous transaction t0 in b1 " = let state_hash_and_body1 = ( state_body_hash , state_body ) state_body in test_base_and_merge ~ state_hash_and_body1 ~ state_hash_and_body2 : state_hash_and_body1 ~ carryforward1 : false ~ carryforward2 : true let % test " base_and_merge : transactions in two different blocks ( t1 , t2 in \ b1 , b2 resp ) . , carryforward the state from a previous \ transaction t0 in b1 " = let state_hash_and_body1 = let state_body0 = Mina_state . Protocol_state . negative_one ~ genesis_ledger : Genesis_ledger ( . Packed . t for_unit_tests ) for_unit_tests ~ genesis_epoch_data : Consensus . Genesis_epoch_data . for_unit_tests ~ constraint_constants ~ consensus_constants |> Mina_state . Protocol_state . body in let state_body_hash0 = Mina_state . Protocol_state . Body . hash state_body0 in ( state_body_hash0 , state_body0 ) state_body0 in let state_hash_and_body2 = ( state_body_hash , state_body ) state_body in test_base_and_merge ~ state_hash_and_body1 ~ state_hash_and_body2 ~ carryforward1 : true ~ carryforward2 : false let % test " base_and_merge : transactions in two different blocks ( t1 , t2 in \ b1 , b2 resp ) . , don ' t carryforward the state from a previous \ transaction t0 in b1 " = let state_hash_and_body1 = let state_body0 = Mina_state . Protocol_state . negative_one ~ genesis_ledger : Genesis_ledger ( . Packed . t for_unit_tests ) for_unit_tests ~ genesis_epoch_data : Consensus . Genesis_epoch_data . for_unit_tests ~ constraint_constants ~ consensus_constants |> Mina_state . Protocol_state . body in let state_body_hash0 = Mina_state . Protocol_state . Body . hash state_body0 in ( state_body_hash0 , state_body0 ) state_body0 in let state_hash_and_body2 = ( state_body_hash , state_body ) state_body in test_base_and_merge ~ state_hash_and_body1 ~ state_hash_and_body2 ~ carryforward1 : false ~ carryforward2 : false let create_account pk token balance = Account . create ( Account_id . create pk token ) token ( Balance . of_int balance ) balance let test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ? memo ? valid_until ? nonce body = let memo = match memo with | Some memo -> memo | None -> Signed_command_memo . create_by_digesting_string_exn ( Test_util . arbitrary_string ~ len : Signed_command_memo . max_digestible_string_length ) in Array . iter accounts ~ f ( : fun account -> Ledger . create_new_account_exn ledger ( Account . identifier account ) account account ) ; let get_account aid = Option . bind ( Ledger . location_of_account ledger aid ) aid ~ f ( : Ledger . get ledger ) ledger in let nonce = match nonce with | Some nonce -> nonce | None -> ( match get_account ( Account_id . create fee_payer_pk fee_token ) fee_token with | Some { nonce ; _ } -> nonce | None -> failwith " Could not infer a valid nonce for this test . Provide one \ explicitly " ) in let payload = Signed_command . Payload . create ~ fee ~ fee_payer_pk ~ nonce ~ valid_until ~ memo ~ body in let signer = Signature_lib . Keypair . of_private_key_exn signer in let user_command = Signed_command . sign signer payload in test_transaction ~ constraint_constants ledger ( Command ( Signed_command user_command ) user_command ) user_command ; let fee_payer = Signed_command . Payload . fee_payer payload in let source = Signed_command . Payload . source payload in let receiver = Signed_command . Payload . receiver payload in let fee_payer_account = get_account fee_payer in let source_account = get_account source in let receiver_account = get_account receiver in ( ` Fee_payer_account fee_payer_account , ` Source_account source_account , ` Receiver_account receiver_account ) let random_int_incl l u = Quickcheck . random_value ( Int . gen_incl l u ) u let sub_amount amt bal = Option . value_exn ( Balance . sub_amount bal amt ) amt let sub_fee fee = sub_amount ( Amount . of_fee fee ) fee let % test_unit " delegation delegatee does not exist " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let source_pk = fee_payer_pk in let receiver_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account source_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Stake_delegation ( Set_delegate { delegator = source_pk ; new_delegate = receiver_pk } ) ) in let fee_payer_account = Option . value_exn fee_payer_account in let source_account = Option . value_exn source_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Public_key . Compressed . equal ( Option . value_exn source_account . delegate ) delegate source_pk ) ; assert ( Option . is_none receiver_account ) receiver_account ) ) let % test_unit " delegation delegator does not exist " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let source_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = wallets ( . 2 ) 2 . account . public_key in let fee_token = Token_id . default in let token_id = Token_id . default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; create_account receiver_pk token_id 30_000_000_000 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account source_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Stake_delegation ( Set_delegate { delegator = source_pk ; new_delegate = receiver_pk } ) ) in let fee_payer_account = Option . value_exn fee_payer_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Option . is_none source_account ) source_account ; assert ( Option . is_some receiver_account ) receiver_account ) ) let % test_unit " timed account - transactions " = Test_util . with_randomness 123456789 ( fun ( ) -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let sender = wallets ( . 0 ) 0 in let receivers = Array . to_list wallets |> List . tl_exn in let txns_per_receiver = 2 in let amount = 8_000_000_000 in let txn_fee = 2_000_000_000 in let memo = Signed_command_memo . create_by_digesting_string_exn ( Test_util . arbitrary_string ~ len : Signed_command_memo . max_digestible_string_length ) in let balance = Balance . of_int 100_000_000_000_000 in let initial_minimum_balance = Balance . of_int 80_000_000_000_000 in let cliff_time = Mina_numbers . Global_slot . of_int 1000 in let cliff_amount = Amount . of_int 10000 in let vesting_period = Mina_numbers . Global_slot . of_int 10 in let vesting_increment = Amount . of_int 1 in let txn_global_slot = Mina_numbers . Global_slot . of_int 1002 in let sender = { sender with account = Or_error . ok_exn @@ Account . create_timed ( Account . identifier sender . account ) account balance ~ initial_minimum_balance ~ cliff_time ~ cliff_amount ~ vesting_period ~ vesting_increment } in Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let _ , ucs = let receiver_ids = List . init ( List . length receivers ) receivers ~ f ( ( : + ) 1 ) 1 in let receivers = List . fold ~ init : receiver_ids ( List . init ( txns_per_receiver - 1 ) 1 ~ f : Fn . id ) id ~ f ( : fun acc _ -> receiver_ids @ acc ) acc in List . fold receivers ~ init ( : Account . Nonce . zero , [ ] ) ~ f ( : fun ( nonce , txns ) txns receiver -> let uc = U . Wallet . user_command_with_wallet wallets ~ sender : 0 ~ receiver amount ( Fee . of_int txn_fee ) txn_fee nonce memo in ( Account . Nonce . succ nonce , txns @ [ uc ] ) ) in Ledger . create_new_account_exn ledger ( Account . identifier sender . account ) account sender . account ; let ( ) = List . iter ucs ~ f ( : fun uc -> test_transaction ~ constraint_constants ~ txn_global_slot ledger ( Transaction . Command ( Signed_command uc ) uc ) uc ) in List . iter receivers ~ f ( : fun receiver -> U . check_balance ( Account . identifier receiver . account ) account ( ( amount * txns_per_receiver ) txns_per_receiver - account_fee ) account_fee ledger ) ; U . check_balance ( Account . identifier sender . account ) account ( Balance . to_int sender . account . balance - ( amount + txn_fee ) txn_fee * txns_per_receiver * List . length receivers ) ledger ) ) let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = fee_payer_pk in let fee_token = Token_id . default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account _also_token_owner_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_new_token { token_owner_pk ; disable_new_accounts = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee |> sub_fee constraint_constants . account_creation_fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Option . is_none token_owner_account . delegate ) delegate ; assert ( Token_permissions . equal token_owner_account . token_permissions ( Token_owned { disable_new_accounts = false } ) ) ) ) let % test_unit " create new token for a different pk " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account _also_token_owner_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_new_token { token_owner_pk ; disable_new_accounts = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee |> sub_fee constraint_constants . account_creation_fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Option . is_none token_owner_account . delegate ) delegate ; assert ( Token_permissions . equal token_owner_account . token_permissions ( Token_owned { disable_new_accounts = false } ) ) ) ) let % test_unit " create new token for a different pk new accounts disabled " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account _also_token_owner_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_new_token { token_owner_pk ; disable_new_accounts = true } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee |> sub_fee constraint_constants . account_creation_fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Option . is_none token_owner_account . delegate ) delegate ; assert ( Token_permissions . equal token_owner_account . token_permissions ( Token_owned { disable_new_accounts = true } ) ) ) ) let % test_unit " create own new token account " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = fee_payer_pk in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee |> sub_fee constraint_constants . account_creation_fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Balance ( . equal zero ) zero receiver_account . balance ) balance ; assert ( Option . is_none receiver_account . delegate ) delegate ; assert ( Token_permissions . equal receiver_account . token_permissions ( Not_owned { account_disabled = false } ) ) ) ) let % test_unit " create new token account for a different pk " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = wallets ( . 2 ) 2 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee |> sub_fee constraint_constants . account_creation_fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Balance ( . equal zero ) zero receiver_account . balance ) balance ; assert ( Option . is_none receiver_account . delegate ) delegate ; assert ( Token_permissions . equal receiver_account . token_permissions ( Not_owned { account_disabled = false } ) ) ) ) let % test_unit " create new token account for a different pk in a locked \ token " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = fee_payer_pk in let receiver_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = true } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee |> sub_fee constraint_constants . account_creation_fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Balance ( . equal zero ) zero receiver_account . balance ) balance ; assert ( Option . is_none receiver_account . delegate ) delegate ; assert ( Token_permissions . equal receiver_account . token_permissions ( Not_owned { account_disabled = false } ) ) ) ) let % test_unit " create new own locked token account in a locked token " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = fee_payer_pk in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = true } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = true } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee |> sub_fee constraint_constants . account_creation_fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Balance ( . equal zero ) zero receiver_account . balance ) balance ; assert ( Option . is_none receiver_account . delegate ) delegate ; assert ( Token_permissions . equal receiver_account . token_permissions ( Not_owned { account_disabled = true } ) ) ) ) let % test_unit " create new token account fails for locked token , non - owner \ fee - payer " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = wallets ( . 2 ) 2 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = true } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Option . is_none receiver_account ) receiver_account ) receiver_account ) receiver_account let % test_unit " create new locked token account fails for unlocked token , \ non - owner fee - payer " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = wallets ( . 2 ) 2 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = true } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Option . is_none receiver_account ) receiver_account ) receiver_account ) receiver_account let % test_unit " create new token account fails if account exists " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = wallets ( . 2 ) 2 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ; create_account receiver_pk token_id 0 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Balance ( . equal zero ) zero receiver_account . balance ) balance ) balance ) balance let % test_unit " create new token account fails if receiver is token owner " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = token_owner_pk in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Balance ( . equal zero ) zero receiver_account . balance ) balance ) balance ) balance let % test_unit " create new token account fails if claimed token owner \ doesn ' t own the token " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = wallets ( . 2 ) 2 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; create_account token_owner_pk token_id 0 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero token_owner_account . balance ) balance ; assert ( Option . is_none receiver_account ) receiver_account ) receiver_account ) receiver_account let % test_unit " create new token account fails if claimed token owner is \ also the account creation target and does not exist " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 3 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk = fee_payer_pk ; token_id ; receiver_pk = fee_payer_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Option . is_none token_owner_account ) token_owner_account ; assert ( Option . is_none receiver_account ) receiver_account ) receiver_account ) receiver_account let % test_unit " create new token account works for default token " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = fee_payer_pk in let receiver_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let token_id = Token_id . default in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account _token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Create_token_account { token_owner_pk ; token_id ; receiver_pk ; account_disabled = false } ) in let fee_payer_account = Option . value_exn fee_payer_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee |> sub_fee constraint_constants . account_creation_fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance ( . equal zero ) zero receiver_account . balance ) balance ; assert ( Public_key . Compressed . equal receiver_pk ( Option . value_exn receiver_account . delegate ) delegate ) ; assert ( Token_permissions . equal receiver_account . token_permissions ( Not_owned { account_disabled = false } ) ) ) ) let % test_unit " mint tokens in owner ' s account " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 1 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = fee_payer_pk in let receiver_pk = fee_payer_pk in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let amount = Amount . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account _token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Mint_tokens { token_owner_pk ; token_id ; receiver_pk ; amount } ) in let fee_payer_account = Option . value_exn fee_payer_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in let expected_receiver_balance = accounts ( . 1 ) 1 . balance |> add_amount amount in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance . equal expected_receiver_balance receiver_account . balance ) ) ) let % test_unit " mint tokens in another pk ' s account " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = fee_payer_pk in let receiver_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let amount = Amount . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ; create_account receiver_pk token_id 0 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Mint_tokens { token_owner_pk ; token_id ; receiver_pk ; amount } ) in let fee_payer_account = Option . value_exn fee_payer_account in let receiver_account = Option . value_exn receiver_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in let expected_receiver_balance = accounts ( . 2 ) 2 . balance |> add_amount amount in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance . equal accounts ( . 1 ) 1 . balance token_owner_account . balance ) ; assert ( Balance . equal expected_receiver_balance receiver_account . balance ) ) ) let % test_unit " mint tokens fails if the claimed token owner is not the \ token owner " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = fee_payer_pk in let receiver_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let amount = Amount . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; create_account token_owner_pk token_id 0 ; create_account receiver_pk token_id 0 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Mint_tokens { token_owner_pk ; token_id ; receiver_pk ; amount } ) in let fee_payer_account = Option . value_exn fee_payer_account in let receiver_account = Option . value_exn receiver_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance . equal accounts ( . 1 ) 1 . balance token_owner_account . balance ) ; assert ( Balance . equal accounts ( . 2 ) 2 . balance receiver_account . balance ) ) ) let % test_unit " mint tokens fails if the token owner account is not present " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = fee_payer_pk in let receiver_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let amount = Amount . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; create_account receiver_pk token_id 0 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Mint_tokens { token_owner_pk ; token_id ; receiver_pk ; amount } ) in let fee_payer_account = Option . value_exn fee_payer_account in let receiver_account = Option . value_exn receiver_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Option . is_none token_owner_account ) token_owner_account ; assert ( Balance . equal accounts ( . 1 ) 1 . balance receiver_account . balance ) ) ) let % test_unit " mint tokens fails if the fee - payer does not have permission \ to mint " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = wallets ( . 1 ) 1 . account . public_key in let receiver_pk = fee_payer_pk in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let amount = Amount . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ; create_account receiver_pk token_id 0 ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Mint_tokens { token_owner_pk ; token_id ; receiver_pk ; amount } ) in let fee_payer_account = Option . value_exn fee_payer_account in let receiver_account = Option . value_exn receiver_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance . equal accounts ( . 1 ) 1 . balance token_owner_account . balance ) ; assert ( Balance . equal accounts ( . 2 ) 2 . balance receiver_account . balance ) ) ) let % test_unit " mint tokens fails if the receiver account is not present " = Test_util . with_randomness 123456789 ( fun ( ) -> Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> let wallets = U . Wallet . random_wallets ~ n : 2 ( ) in let signer = wallets ( . 0 ) 0 . private_key in let fee_payer_pk = wallets ( . 0 ) 0 . account . public_key in let token_owner_pk = fee_payer_pk in let receiver_pk = wallets ( . 1 ) 1 . account . public_key in let fee_token = Token_id . default in let token_id = Quickcheck . random_value Token_id . gen_non_default in let amount = Amount . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let accounts = [ | create_account fee_payer_pk fee_token 20_000_000_000 ; { ( create_account token_owner_pk token_id 0 ) 0 with token_permissions = Token_owned { disable_new_accounts = false } } ] | in let fee = Fee . of_int ( random_int_incl 2 15 * 1_000_000_000 ) 1_000_000_000 in let ( ` Fee_payer_account fee_payer_account , ` Source_account token_owner_account , ` Receiver_account receiver_account ) = test_user_command_with_accounts ~ constraint_constants ~ ledger ~ accounts ~ signer ~ fee ~ fee_payer_pk ~ fee_token ( Mint_tokens { token_owner_pk ; token_id ; receiver_pk ; amount } ) in let fee_payer_account = Option . value_exn fee_payer_account in let token_owner_account = Option . value_exn token_owner_account in let expected_fee_payer_balance = accounts ( . 0 ) 0 . balance |> sub_fee fee in assert ( Balance . equal fee_payer_account . balance expected_fee_payer_balance ) ; assert ( Balance . equal accounts ( . 1 ) 1 . balance token_owner_account . balance ) ; assert ( Option . is_none receiver_account ) receiver_account ) receiver_account ) receiver_account ) * let % test_unit " unchanged timings for fee transfers and coinbase " = Test_util . with_randomness 123456789 ( fun ( ) -> let receivers = Array . init 2 ~ f ( : fun _ -> Public_key . of_private_key_exn ( Private_key . create ( ) ) |> Public_key . compress ) in let timed_account pk = let account_id = Account_id . create pk Token_id . default in let balance = Balance . of_int 100_000_000_000_000 in let initial_minimum_balance = Balance . of_int 80_000_000_000 in let cliff_time = Mina_numbers . Global_slot . of_int 2 in let cliff_amount = Amount . of_int 5_000_000_000 in let vesting_period = Mina_numbers . Global_slot . of_int 2 in let vesting_increment = Amount . of_int 40_000_000_000 in Or_error . ok_exn @@ Account . create_timed account_id balance ~ initial_minimum_balance ~ cliff_time ~ cliff_amount ~ vesting_period ~ vesting_increment in let timed_account1 = timed_account receivers ( . 0 ) 0 in let timed_account2 = timed_account receivers ( . 1 ) 1 in let fee = 8_000_000_000 in let ft1 , ft2 = let single1 = Fee_transfer . Single . create ~ receiver_pk : receivers ( . 0 ) 0 ~ fee ( : Currency . Fee . of_int fee ) fee ~ fee_token : Token_id . default in let single2 = Fee_transfer . Single . create ~ receiver_pk : receivers ( . 1 ) 1 ~ fee ( : Currency . Fee . of_int fee ) fee ~ fee_token : Token_id . default in ( Fee_transfer . create single1 ( Some single2 ) single2 |> Or_error . ok_exn , Fee_transfer . create single1 None |> Or_error . ok_exn ) in let coinbase_with_ft , coinbase_wo_ft = let ft = Coinbase . Fee_transfer . create ~ receiver_pk : receivers ( . 0 ) 0 ~ fee ( : Currency . Fee . of_int fee ) fee in ( Coinbase . create ~ amount ( : Currency . Amount . of_int 10_000_000_000 ) 10_000_000_000 ~ receiver : receivers ( . 1 ) 1 ~ fee_transfer ( : Some ft ) ft |> Or_error . ok_exn , Coinbase . create ~ amount ( : Currency . Amount . of_int 10_000_000_000 ) 10_000_000_000 ~ receiver : receivers ( . 1 ) 1 ~ fee_transfer : None |> Or_error . ok_exn ) in let transactions : Mina_transaction . Transaction . Valid . t list = [ Fee_transfer ft1 ; Fee_transfer ft2 ; Coinbase coinbase_with_ft ; Coinbase coinbase_wo_ft ] in Ledger . with_ledger ~ depth : ledger_depth ~ f ( : fun ledger -> List . iter [ timed_account1 ; timed_account2 ] ~ f ( : fun acc -> Ledger . create_new_account_exn ledger ( Account . identifier acc ) acc acc ) ; let txn_global_slot = Mina_numbers . Global_slot . of_int 100 in List . iter transactions ~ f ( : fun txn -> test_transaction ~ txn_global_slot ~ constraint_constants ledger txn ) ) ) end )
module Body = struct type ( ' tag , ' public_key , ' token_id , ' amount , ' bool ) ' bool t_ = { tag : ' tag ; source_pk : ' public_key ; receiver_pk : ' public_key ; token_id : ' token_id ; amount : ' amount ; token_locked : ' bool } [ @@ deriving sexp , hlist ] hlist type t = ( Tag . t , Public_key . Compressed . t , Token_id . t , Currency . Amount . t , bool ) bool t_ [ @@ deriving sexp ] sexp let of_user_command_payload_body = function | Signed_command_payload . Body . Payment { source_pk ; receiver_pk ; amount } -> { tag = Tag . Payment ; source_pk ; receiver_pk ; token_id = Token_id . default ; amount ; token_locked = false } | Stake_delegation ( Set_delegate { delegator ; new_delegate } ) -> { tag = Tag . Stake_delegation ; source_pk = delegator ; receiver_pk = new_delegate ; token_id = Token_id . default ; amount = Currency . Amount . zero ; token_locked = false } let gen ~ fee = let open Quickcheck . Generator . Let_syntax in let % bind tag = Tag . gen in let % map amount = let min , max = let max_amount_without_overflow = Amount ( . sub max_int ( of_fee fee ) fee ) fee |> Option . value_exn ? here : None ? message : None ? error : None in match tag with | Payment -> ( Amount . zero , max_amount_without_overflow ) max_amount_without_overflow | Stake_delegation -> ( Amount . zero , Amount . zero ) zero | Create_account -> ( Amount . zero , Amount . zero ) zero | Fee_transfer -> ( Amount . zero , max_amount_without_overflow ) max_amount_without_overflow | Coinbase -> ( Amount . of_fee fee , Amount . max_int ) max_int | Mint_tokens -> ( Amount . zero , Amount . max_int ) max_int in Amount . gen_incl min max and token_locked = match tag with | Payment -> return false | Stake_delegation -> return false | Create_account -> Quickcheck . Generator . bool | Fee_transfer -> return false | Coinbase -> return false | Mint_tokens -> return false and source_pk = Public_key . Compressed . gen and receiver_pk = Public_key . Compressed . gen and token_id = match tag with | Payment -> Token_id . gen | Stake_delegation -> return Token_id . default | Create_account -> Token_id . gen | Mint_tokens -> Token_id . gen | Fee_transfer -> return Token_id . default | Coinbase -> return Token_id . default in { tag ; source_pk ; receiver_pk ; token_id ; amount ; token_locked } [ %% ifdef consensus_mechanism ] consensus_mechanism type var = ( Tag . Unpacked . var , Public_key . Compressed . var , Token_id . Checked . t , Currency . Amount . var , Boolean . var ) t_ let spec = Data_spec . [ Tag . unpacked_typ ; Public_key . Compressed . typ ; Public_key . Compressed . typ ; Token_id . typ ; Currency . Amount . typ ; Boolean . typ ] let typ = Typ . of_hlistable spec ~ var_to_hlist : t__to_hlist ~ value_to_hlist : t__to_hlist ~ var_of_hlist : t__of_hlist ~ value_of_hlist : t__of_hlist module Checked = struct let constant ( { tag ; source_pk ; receiver_pk ; token_id ; amount ; token_locked } : t ) t : var = { tag = Tag . unpacked_of_t tag ; source_pk = Public_key . Compressed . var_of_t source_pk ; receiver_pk = Public_key . Compressed . var_of_t receiver_pk ; token_id = Token_id . Checked . constant token_id ; amount = Currency . Amount . var_of_t amount ; token_locked = Boolean . var_of_value token_locked } let to_input_legacy { tag ; source_pk ; receiver_pk ; token_id ; amount ; token_locked } = let % map amount = Currency . Amount . var_to_input_legacy amount and ( ) = make_checked ( fun ( ) -> Token_id . Checked . Assert . equal token_id ( Token_id . Checked . constant Token_id . default ) default ) in let token_id = Signed_command_payload . Legacy_token_id . default_checked in Array . reduce_exn ~ f : Random_oracle . Input . Legacy . append [ | Tag . Unpacked . to_input_legacy tag ; Public_key . Compressed . Checked . to_input_legacy source_pk ; Public_key . Compressed . Checked . to_input_legacy receiver_pk ; token_id ; amount ; Random_oracle . Input . Legacy . bitstring [ token_locked ] ] | end [ %% endif ] endif let to_input_legacy { tag ; source_pk ; receiver_pk ; token_id ; amount ; token_locked } = assert ( Token_id . equal token_id Token_id . default ) default ; Array . reduce_exn ~ f : Random_oracle . Input . Legacy . append [ | Tag . to_input_legacy tag ; Public_key . Compressed . to_input_legacy source_pk ; Public_key . Compressed . to_input_legacy receiver_pk ; Signed_command_payload . Legacy_token_id . default ; Currency . Amount . to_input_legacy amount ; Random_oracle . Input . Legacy . bitstring [ token_locked ] ] | end
module Payload_common = struct module Poly = struct type ( ' fee , ' public_key , ' token_id , ' nonce , ' global_slot , ' memo ) ' memo t = { fee : ' fee ; fee_token : ' token_id ; fee_payer_pk : ' public_key ; nonce : ' nonce ; valid_until : ' global_slot ; memo : ' memo } [ @@ deriving sexp , hlist ] hlist end let to_signed_command_payload_common { Poly . fee ; fee_payer_pk ; nonce ; valid_until ; memo ; fee_token = _ } = { Signed_command_payload . Common . Poly . fee ; fee_payer_pk ; nonce ; valid_until ; memo } type t = ( Currency . Fee . t , Public_key . Compressed . t , Token_id . t , Mina_numbers . Account_nonce . t , Mina_numbers . Global_slot . t , Signed_command_memo . t ) Poly . t [ @@ deriving sexp ] sexp [ %% ifdef consensus_mechanism ] consensus_mechanism module Checked = struct type value = t type t = ( Currency . Fee . Checked . t , Public_key . Compressed . var , Token_id . Checked . t , Mina_numbers . Account_nonce . Checked . t , Mina_numbers . Global_slot . Checked . t , Signed_command_memo . Checked . t ) Poly . t let constant ( { fee ; fee_payer_pk ; nonce ; valid_until ; memo ; fee_token } : value ) value : t = { fee = Currency . Fee . var_of_t fee ; fee_payer_pk = Public_key . Compressed . var_of_t fee_payer_pk ; fee_token = Token_id . Checked . constant fee_token ; nonce = Mina_numbers . Account_nonce . Checked . constant nonce ; memo = Signed_command_memo . Checked . constant memo ; valid_until = Mina_numbers . Global_slot . Checked . constant valid_until } end let typ : ( Checked . t , t ) t Typ . t = let open Poly in Typ . of_hlistable [ Currency . Fee . typ ; Token_id . typ ; Public_key . Compressed . typ ; Mina_numbers . Account_nonce . typ ; Mina_numbers . Global_slot . typ ; Signed_command_memo . typ ] ~ var_to_hlist : to_hlist ~ value_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif end
type t = ( Payload_common . t , Body . t ) t Signed_command_payload . Poly . t
type payload = t [ @@ deriving sexp ] sexp
let of_user_command_payload ( { common = { memo ; fee ; fee_payer_pk ; nonce ; valid_until } ; body } : Signed_command_payload . t ) : t = { common = { fee ; fee_token = Token_id . default ; fee_payer_pk ; nonce ; valid_until ; memo } ; body = Body . of_user_command_payload_body body }
let gen = let open Quickcheck . Generator . Let_syntax in let % bind common = Signed_command_payload . Common . gen in let % map body = Body . gen ~ fee : common . fee in Signed_command_payload . Poly { . common ; body }
type var = ( Payload_common . Checked . t , Body . var ) var Signed_command_payload . Poly . t
let typ : ( var , t ) t Typ . t = let to_hlist = Signed_command_payload . Poly . to_hlist in let of_hlist = Signed_command_payload . Poly . of_hlist in Typ . of_hlistable [ Payload_common . typ ; Body . typ ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist
module Checked = struct let to_input_legacy ( { common ; body } : var ) var = let % map common = Signed_command_payload . Common . Checked . to_input_legacy ( Payload_common . to_signed_command_payload_common common ) common and body = Body . Checked . to_input_legacy body in Random_oracle . Input . Legacy . append common body let constant ( { common ; body } : t ) t : var = { common = Payload_common . Checked . constant common ; body = Body . Checked . constant body } end [ %% endif ] endif
let to_input_legacy ( { common ; body } : t ) t = Random_oracle . Input . Legacy . append ( Signed_command_payload . Common . to_input_legacy ( Payload_common . to_signed_command_payload_common common ) common ) ( Body . to_input_legacy body ) body
let excess ( payload : t ) t : Amount . Signed . t = let tag = payload . body . tag in let fee = payload . common . fee in let amount = payload . body . amount in match tag with | Payment | Stake_delegation | Create_account | Mint_tokens -> Amount . Signed . of_unsigned ( Amount . of_fee fee ) fee | Fee_transfer -> Option . value_exn ( Amount . add_fee amount fee ) fee |> Amount . Signed . of_unsigned |> Amount . Signed . negate | Coinbase -> Amount . Signed . zero
let fee_excess ( { body = { tag ; amount ; _ } ; common = { fee ; _ } } : t ) t = match tag with | Payment | Stake_delegation | Create_account | Mint_tokens -> Fee_excess . of_single ( Token_id . default , Fee . Signed . of_unsigned fee ) fee | Fee_transfer -> let excess = Option . value_exn ( Amount . add_fee amount fee ) fee |> Amount . to_fee |> Fee . Signed . of_unsigned |> Fee . Signed . negate in Fee_excess . of_single ( Token_id . default , excess ) excess | Coinbase -> Fee_excess . of_single ( Token_id . default , Fee . Signed . zero ) zero
let supply_increase ( payload : payload ) payload = let tag = payload . body . tag in match tag with | Coinbase -> payload . body . amount | Payment | Stake_delegation | Create_account | Mint_tokens | Fee_transfer -> Amount . zero
type t = | Payment | Stake_delegation | Create_account | Mint_tokens | Fee_transfer | Coinbase
let to_string = function | Payment -> " payment " | Stake_delegation -> " delegation " | Create_account -> " create_account " | Mint_tokens -> " mint_tokens " | Fee_transfer -> " fee - transfer " | Coinbase -> " coinbase "
let gen = Quickcheck . Generator . map ( Int . gen_incl min max ) max ~ f ( : fun i -> Option . value_exn ( of_enum i ) i )
module Bits = struct type t = bool * bool * bool [ @@ deriving equal ] equal let of_int i : t = let test_mask mask = i land mask = mask in ( test_mask 0b100 , test_mask 0b10 , test_mask 0b1 ) 0b1 let of_t x = of_int ( to_enum x ) x let payment = of_t Payment let stake_delegation = of_t Stake_delegation let create_account = of_t Create_account let mint_tokens = of_t Mint_tokens let fee_transfer = of_t Fee_transfer let coinbase = of_t Coinbase let to_bits ( b1 , b2 , b3 ) b3 = [ b1 ; b2 ; b3 ] let to_input_legacy t = Random_oracle . Input . Legacy . bitstring ( to_bits t ) t [ %% ifdef consensus_mechanism ] consensus_mechanism type var = Boolean . var * Boolean . var * Boolean . var let typ = Typ . tuple3 Boolean . typ Boolean . typ Boolean . typ let constant ( b1 , b2 , b3 ) b3 = Boolean ( . var_of_value b1 , var_of_value b2 , var_of_value b3 ) b3 [ %% endif ] endif end
module Unpacked = struct module Poly = struct type ' bool t = { is_payment : ' bool ; is_stake_delegation : ' bool ; is_create_account : ' bool ; is_mint_tokens : ' bool ; is_fee_transfer : ' bool ; is_coinbase : ' bool ; is_user_command : ' bool } [ @@ deriving equal , hlist ] hlist [ %% ifdef consensus_mechanism ] consensus_mechanism let typ ( bool : ( ' bool_var , ' bool ) ' bool Typ . t ) t : ( ' bool_var t , ' bool t ) t Typ . t = Typ . of_hlistable [ bool ; bool ; bool ; bool ; bool ; bool ; bool ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif end type t = bool Poly . t [ @@ deriving equal ] equal let empty : t = { is_payment = false ; is_stake_delegation = false ; is_create_account = false ; is_mint_tokens = false ; is_fee_transfer = false ; is_coinbase = false ; is_user_command = false } let payment = { empty with is_payment = true ; is_user_command = true } let stake_delegation = { empty with is_stake_delegation = true ; is_user_command = true } let create_account = { empty with is_create_account = true ; is_user_command = true } let mint_tokens = { empty with is_mint_tokens = true ; is_user_command = true } let fee_transfer = { empty with is_fee_transfer = true ; is_user_command = false } let coinbase = { empty with is_coinbase = true ; is_user_command = false } let of_bits_t ( bits : Bits . t ) t : t = match List . Assoc . find ~ equal : Bits . equal [ ( Bits . payment , payment ) payment ; ( Bits . stake_delegation , stake_delegation ) stake_delegation ; ( Bits . create_account , create_account ) create_account ; ( Bits . mint_tokens , mint_tokens ) mint_tokens ; ( Bits . fee_transfer , fee_transfer ) fee_transfer ; ( Bits . coinbase , coinbase ) coinbase ] bits with | Some t -> t | None -> raise ( Invalid_argument " Transaction_union_tag . Unpacked . of_bits_t ) " let to_bits_t ( t : t ) t : Bits . t = match List . Assoc . find ~ equal [ ( payment , Bits . payment ) payment ; ( stake_delegation , Bits . stake_delegation ) stake_delegation ; ( create_account , Bits . create_account ) create_account ; ( mint_tokens , Bits . mint_tokens ) mint_tokens ; ( fee_transfer , Bits . fee_transfer ) fee_transfer ; ( coinbase , Bits . coinbase ) coinbase ] t with | Some bits -> bits | None -> raise ( Invalid_argument " Transaction_union_tag . Unpacked . to_bits_t ) " [ %% ifdef consensus_mechanism ] consensus_mechanism type var = Boolean . var Poly . t let to_bits_var ( { is_payment ; is_stake_delegation ; is_create_account ; is_mint_tokens ; is_fee_transfer ; is_coinbase ; is_user_command = _ } : var ) = let b1 , b2 , b3 = List . fold ~ init : Field ( . Var ( . constant zero , constant zero , constant zero ) zero ) zero [ ( Bits . payment , is_payment ) is_payment ; ( Bits . stake_delegation , is_stake_delegation ) is_stake_delegation ; ( Bits . create_account , is_create_account ) is_create_account ; ( Bits . mint_tokens , is_mint_tokens ) is_mint_tokens ; ( Bits . fee_transfer , is_fee_transfer ) is_fee_transfer ; ( Bits . coinbase , is_coinbase ) is_coinbase ] ~ f ( : fun ( acc1 , acc2 , acc3 ) acc3 ( ( bit1 , bit2 , bit3 ) bit3 , bool_var ) bool_var -> let add_if_true bit acc = if bit then Field . Var . add acc ( bool_var :> Field . Var . t ) t else acc in ( add_if_true bit1 acc1 , add_if_true bit2 acc2 , add_if_true bit3 acc3 ) acc3 ) in Boolean . Unsafe ( . of_cvar b1 , of_cvar b2 , of_cvar b3 ) b3 let typ : ( var , t ) t Typ . t = let ( Typ base_typ ) base_typ = Poly . typ Boolean . typ in Typ { base_typ with check = ( fun ( { is_payment ; is_stake_delegation ; is_create_account ; is_mint_tokens ; is_fee_transfer ; is_coinbase ; is_user_command } as t ) -> let open Checked . Let_syntax in let % bind ( ) = base_typ . check t in let % bind ( ) = [ % with_label " Only one tag is set ] " ( Boolean . Assert . exactly_one [ is_payment ; is_stake_delegation ; is_create_account ; is_mint_tokens ; is_fee_transfer ; is_coinbase ] ) in [ % with_label " User command flag is correctly set ] " ( Boolean . Assert . exactly_one [ is_user_command ; is_fee_transfer ; is_coinbase ] ) ) } let constant ( { is_payment ; is_stake_delegation ; is_create_account ; is_mint_tokens ; is_fee_transfer ; is_coinbase ; is_user_command } : t ) : var = { is_payment = Boolean . var_of_value is_payment ; is_stake_delegation = Boolean . var_of_value is_stake_delegation ; is_create_account = Boolean . var_of_value is_create_account ; is_mint_tokens = Boolean . var_of_value is_mint_tokens ; is_fee_transfer = Boolean . var_of_value is_fee_transfer ; is_coinbase = Boolean . var_of_value is_coinbase ; is_user_command = Boolean . var_of_value is_user_command } let is_payment ( { is_payment ; _ } : var ) var = is_payment let is_stake_delegation ( { is_stake_delegation ; _ } : var ) var = is_stake_delegation let is_create_account ( { is_create_account ; _ } : var ) var = is_create_account let is_mint_tokens ( { is_mint_tokens ; _ } : var ) var = is_mint_tokens let is_fee_transfer ( { is_fee_transfer ; _ } : var ) var = is_fee_transfer let is_coinbase ( { is_coinbase ; _ } : var ) var = is_coinbase let is_user_command ( { is_user_command ; _ } : var ) var = is_user_command let to_bits t = Bits . to_bits ( to_bits_var t ) t let to_input_legacy t = Random_oracle . Input . Legacy . bitstring ( to_bits t ) t [ %% endif ] endif end
let unpacked_t_of_t = function | Payment -> Unpacked . payment | Stake_delegation -> Unpacked . stake_delegation | Create_account -> Unpacked . create_account | Mint_tokens -> Unpacked . mint_tokens | Fee_transfer -> Unpacked . fee_transfer | Coinbase -> Unpacked . coinbase
let to_bits tag = Bits . to_bits ( Unpacked . to_bits_t ( unpacked_t_of_t tag ) tag ) tag
let to_input_legacy tag = Random_oracle . Input . Legacy . bitstring ( to_bits tag ) tag
let t_of_unpacked_t ( unpacked : Unpacked . t ) t : t = match List . Assoc . find ~ equal : Unpacked . equal [ ( Unpacked . payment , Payment ) Payment ; ( Unpacked . stake_delegation , Stake_delegation ) Stake_delegation ; ( Unpacked . create_account , Create_account ) Create_account ; ( Unpacked . mint_tokens , Mint_tokens ) Mint_tokens ; ( Unpacked . fee_transfer , Fee_transfer ) Fee_transfer ; ( Unpacked . coinbase , Coinbase ) Coinbase ] unpacked with | Some t -> t | None -> raise ( Invalid_argument " Transaction_union_tag . t_of_unpacked_t ) "
let bits_t_of_t tag = Unpacked . to_bits_t ( unpacked_t_of_t tag ) tag
let t_of_bits_t tag = t_of_unpacked_t ( Unpacked . of_bits_t tag ) tag
let unpacked_of_t tag = Unpacked . constant ( unpacked_t_of_t tag ) tag
let bits_of_t tag = Bits . constant ( bits_t_of_t tag ) tag
let unpacked_typ = Typ . transport Unpacked . typ ~ there : unpacked_t_of_t ~ back : t_of_unpacked_t
let bits_typ = Typ . transport Bits . typ ~ there : bits_t_of_t ~ back : t_of_bits_t ( module struct let test_predicate checked unchecked = let checked x = Checked . return ( checked x ) x in for i = min to max do Test_util . test_equal unpacked_typ Boolean . typ checked unchecked ( Option . value_exn ( of_enum i ) i ) i done let one_of xs t = List . mem xs ~ equal t let % test_unit " is_payment " = test_predicate Unpacked . is_payment ( equal Payment ) Payment let % test_unit " is_stake_delegation " = test_predicate Unpacked . is_stake_delegation ( equal Stake_delegation ) Stake_delegation let % test_unit " is_create_account " = test_predicate Unpacked . is_create_account ( equal Create_account ) Create_account let % test_unit " is_mint_tokens " = test_predicate Unpacked . is_mint_tokens ( equal Mint_tokens ) Mint_tokens let % test_unit " is_fee_transfer " = test_predicate Unpacked . is_fee_transfer ( equal Fee_transfer ) Fee_transfer let % test_unit " is_coinbase " = test_predicate Unpacked . is_coinbase ( equal Coinbase ) Coinbase let % test_unit " is_user_command " = test_predicate Unpacked . is_user_command ( one_of [ Payment ; Stake_delegation ; Create_account ; Mint_tokens ] ) let % test_unit " not_user_command " = test_predicate ( fun x -> Boolean . not ( Unpacked . is_user_command x ) x ) x ( one_of [ Fee_transfer ; Coinbase ] ) let % test_unit " bit_representation " = for i = min to max do Test_util . test_equal unpacked_typ Bits . typ ( Fn . compose Checked . return Unpacked . to_bits_var ) to_bits_var bits_t_of_t ( Option . value_exn ( of_enum i ) i ) i done end ) [ %% endif ] endif
module Hashless_ledger = struct type t = { base : Ledger . t ; overlay : ( Account . Identifier . t , Account . t ) t Hashtbl . t } type location = Ours of Account . Identifier . t | Theirs of Ledger . Location . t let msg s = s ^ " : somehow we got a location that isn ' t present in the underlying ledger " let get t = function | Ours key -> Hashtbl . find t . overlay key | Theirs loc -> ( match Ledger . get t . base loc with | Some a -> ( match Hashtbl . find t . overlay ( Account . identifier a ) a with | None -> Some a | s -> s ) | None -> failwith ( msg " get ) " ) let location_of_account t key = match Hashtbl . find t . overlay key with | Some _ -> Some ( Ours key ) key | None -> Option . map ~ f ( : fun d -> Theirs d ) d ( Ledger . location_of_account t . base key ) key let set t loc acct = match loc with | Ours key -> Hashtbl . set t . overlay ~ key ~ data : acct | Theirs loc -> ( match Ledger . get t . base loc with | Some a -> Hashtbl . set t . overlay ~ key ( : Account . identifier a ) a ~ data : acct | None -> failwith ( msg " set ) " ) let get_or_create_account t key account = match location_of_account t key with | None -> set t ( Ours key ) key account ; Ok ( ` Added , Ours key ) key | Some loc -> Ok ( ` Existed , loc ) loc let get_or_create_exn ledger aid = let action , loc = get_or_create_account ledger aid ( Account . initialize aid ) aid |> Or_error . ok_exn in ( action , Option . value_exn ( get ledger loc ) loc , loc ) loc let create_new_account t account_id account = let open Or_error . Let_syntax in let % bind action , _ = get_or_create_account t account_id account in if [ % equal : [ ` Existed | ` Added ] ] action ` Existed then Or_error . errorf " ! Could not create a new account with pk \ { % sexp : Signature_lib . Public_key . Compressed . t } t : Account already \ exists " ( Account_id . public_key account_id ) account_id else Ok ( ) let get_or_create t id = Or_error . try_with ( fun ( ) -> get_or_create_exn t id ) id let remove_accounts_exn _t = failwith " hashless_ledger : bug in transaction_logic " let merkle_root _t = Ledger_hash . empty_hash let create l = { base = l ; overlay = Hashtbl . create ( module Account_id ) Account_id } let with_ledger ~ depth ~ f = Ledger . with_ledger ~ depth ~ f ( : fun l -> let t = create l in f t ) let create_masked t = { base = t . base ; overlay = Hashtbl . copy t . overlay } let apply_mask t ~ masked = Hashtbl . merge_into ~ src : masked . overlay ~ dst : t . overlay ~ f ( : fun ~ key : _ src _dst -> Set_to src ) src let empty ~ depth ( ) = let ledger = Ledger . create_ephemeral ~ depth ( ) in let res = create ledger in Ledger . close ledger ; res end
let apply_user_command ~ constraint_constants ~ txn_global_slot l uc = Result . map ~ f ( : fun applied_txn -> applied_txn . Transaction_applied . Signed_command_applied . common . user_command . status ) ( apply_user_command l ~ constraint_constants ~ txn_global_slot uc ) uc