text
stringlengths
0
601k
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
let apply_transaction ' ~ constraint_constants ~ txn_state_view l t = O1trace . sync_thread " apply_transaction " ( fun ( ) -> apply_transaction ~ constraint_constants ~ txn_state_view l t )
let apply_transaction ~ constraint_constants ~ txn_state_view l txn = Result . map ~ f : Transaction_applied . user_command_status ( apply_transaction ' l ~ constraint_constants ~ txn_state_view txn ) txn
module Parties_segment_witness = struct open Mina_base open Mina_ledger open Currency [ %% versioned module Stable = struct module V1 = struct type t = { global_ledger : Sparse_ledger . Stable . V2 . t ; local_state_init : ( ( Token_id . Stable . V1 . t , unit Parties . Call_forest . With_hashes . Stable . V1 . t ) Stack_frame . Stable . V1 . t , ( ( ( Token_id . Stable . V1 . t , unit Parties . Call_forest . With_hashes . Stable . V1 . t ) Stack_frame . Stable . V1 . t , Stack_frame . Digest . Stable . V1 . t ) With_hash . Stable . V1 . t , Call_stack_digest . Stable . V1 . t ) With_stack_hash . Stable . V1 . t list , Token_id . Stable . V1 . t , ( Amount . Stable . V1 . t , Sgn . Stable . V1 . t ) t Signed_poly . Stable . V1 . t , Sparse_ledger . Stable . V2 . t , bool , Kimchi_backend . Pasta . Basic . Fp . Stable . V1 . t , Transaction_status . Failure . Collection . Stable . V1 . t ) Mina_transaction_logic . Parties_logic . Local_state . Stable . V1 . t ; start_parties : ( Parties . Stable . V1 . t , Kimchi_backend . Pasta . Basic . Fp . Stable . V1 . t ) Mina_transaction_logic . Parties_logic . Start_data . Stable . V1 . t list ; state_body : Mina_state . Protocol_state . Body . Value . Stable . V2 . t ; init_stack : Mina_base . Pending_coinbase . Stack_versioned . Stable . V1 . t } [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end end [ %% versioned
module Stable = struct module V2 = struct type t = { transaction : Mina_transaction . Transaction . Stable . V2 . t ; ledger : Mina_ledger . Sparse_ledger . Stable . V2 . t ; protocol_state_body : Mina_state . Protocol_state . Body . Value . Stable . V2 . t ; init_stack : Mina_base . Pending_coinbase . Stack_versioned . Stable . V1 . t ; status : Mina_base . Transaction_status . Stable . V2 . t } [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end
let transfer_and_check_balances ( ? with_burn = false ) ~ loc b ( ? fee = Tez . zero ) ? expect_failure src dst amount = let open Lwt_tzresult_syntax in let *? amount_fee = fee +? amount in let * bal_src = Context . Contract . balance ( I b ) src in let * bal_dst = Context . Contract . balance ( I b ) dst in let * op = Op . transaction ~ gas_limit ( : Alpha_context . Gas . Arith . integral_of_int_exn 3000 ) ( I b ) ~ fee src dst amount in let * b = Incremental . add_operation ? expect_failure b op in let * { parametric = { origination_size ; cost_per_byte ; _ } ; _ } = Context . get_constants ( I b ) in let *? origination_burn = cost_per_byte *? Int64 . of_int origination_size in let *? amount_fee_burn = amount_fee +? origination_burn in let amount_fee_maybe_burn = if with_burn then amount_fee_burn else amount_fee in let * ( ) = Assert . balance_was_debited ~ loc ( I b ) src bal_src amount_fee_maybe_burn in let + ( ) = Assert . balance_was_credited ~ loc ( I b ) dst bal_dst amount in ( b , op )
let n_transactions n b ? fee source dest amount = List . fold_left_es ( fun b _ -> transfer_and_check_balances ~ loc : __LOC__ b ? fee source dest amount >|=? fun ( b , _ ) -> b ) b ( 1 -- n )
module Make ( IO : S . IO ) = struct open IO type reader = unit -> Transfer . chunk IO . t type writer = string -> unit IO . t module Chunked = struct let remaining_length chunk remaining = let read_len = Int64 . of_int ( String . length chunk ) in Int64 . sub remaining read_len let read_chunk ic size = let max_read_len = Int64 . of_int 0x8000 in let len = min size max_read_len in read ic ( Int64 . to_int len ) let parse_chunksize chunk_size_hex = let hex = try String . sub chunk_size_hex 0 ( String . index chunk_size_hex ' ; ' ) with _ -> chunk_size_hex in try Some ( Int64 . of_string ( " 0x " ^ hex ) ) with _ -> None let rec junk_until_empty_line ic = read_line ic >>= function | None | Some " " -> return Done | Some _trailer -> junk_until_empty_line ic let read ~ remaining ic ( ) = let read_chunk_fragment ( ) = read_chunk ic ! remaining >>= fun chunk -> remaining := remaining_length chunk ! remaining ; ( if ! remaining = 0L then read_line ic else return None ) >>= fun _ -> return chunk in if ! remaining = 0L then read_line ic >>= function | None -> return Done | Some chunk_size_hex -> ( match parse_chunksize chunk_size_hex with | None -> return Done | Some 0L -> junk_until_empty_line ic | Some count -> ( remaining := count ; read_chunk_fragment ( ) >>= function | " " -> return Done | buf -> return ( Chunk buf ) ) ) else read_chunk_fragment ( ) >>= function | " " -> return Done | buf -> return ( Chunk buf ) let write oc buf = let len = String . length buf in if len <> 0 then write oc ( Printf . sprintf " % x \ r \ n " len ) >>= fun ( ) -> write oc buf >>= fun ( ) -> write oc " \ r \ n " else return ( ) end module Fixed = struct let read ~ remaining ic ( ) = match ! remaining with | 0L -> return Done | len -> ( let max_read_len = Int64 . of_int 0x8000 in let read_len = Int64 . to_int ( min len max_read_len ) in read ic read_len >>= function | " " -> return Done | buf -> remaining := Int64 . sub ! remaining ( Int64 . of_int ( String . length buf ) ) ; return ( match ! remaining with 0L -> Final_chunk buf | _ -> Chunk buf ) ) let write = write end module Unknown = struct let read ic ( ) = read ic 4096 >>= fun buf -> if buf = " " then return Done else return ( Chunk buf ) let write = write end let write_and_flush fn oc buf = fn oc buf >>= fun ( ) -> IO . flush oc let make_reader = function | Chunked -> Chunked . read ~ remaining ( : ref 0L ) | Fixed len -> Fixed . read ~ remaining ( : ref len ) | Unknown -> Unknown . read let write_ignore_blank writer io s = if String . length s = 0 then return ( ) else writer io s let make_writer ( ? flush = false ) mode = match flush with | false -> ( match mode with | Chunked -> Chunked . write | Fixed _ -> Fixed . write | Unknown -> Unknown . write ) | true -> ( match mode with | Chunked -> write_and_flush Chunked . write | Fixed _ -> write_and_flush Fixed . write | Unknown -> write_and_flush Unknown . write ) |> write_ignore_blank let read reader = reader ( ) let write writer buf = writer buf end
module type Transformer = sig type t val transform_expression_children : t -> Expression . t -> bool val expression : t -> Expression . t -> Expression . t val transform_children : t -> Statement . t -> t * bool val statement : t -> Statement . t -> t * Statement . t list end
module type StatementTransformer = sig type t val statement : t -> Statement . t -> t * Statement . t list end
module Identity : sig val transform_expression_children : ' t -> Expression . t -> bool val expression : ' t -> Expression . t -> Expression . t val transform_children : ' t -> Statement . t -> ' t * bool val statement : ' t -> Statement . t -> ' t * Statement . t list let transform_expression_children _ _ = true let expression _ expression = expression let transform_children state _ = state , true let statement state statement = state , [ statement ] end
module Make ( Transformer : Transformer ) = struct type result = { state : Transformer . t ; source : Source . t ; } let source { source ; _ } = source let transform state source = let state = ref state in let transform_list list ~ f = let accumulate list element = f element :: list in List . fold_left list ~ f : accumulate ~ init [ ] : |> List . rev in let transform_argument { Call . Argument . name ; value } ~ transform_expression = { Call . Argument . name ; value = transform_expression value } in let transform_parameter ( { Node . value = { Parameter . name ; value ; annotation } ; _ } as node ) ~ transform_expression = { node with Node . value = { Parameter . name ; value = value >>| transform_expression ; annotation = annotation >>| transform_expression ; } ; } in let transform_generator { Comprehension . Generator . target ; iterator ; conditions ; async } ~ transform_expression = { Comprehension . Generator . target = transform_expression target ; iterator = transform_expression iterator ; conditions = transform_list conditions ~ f : transform_expression ; async ; } in let transform_entry { Dictionary . Entry . key ; value } ~ transform_expression = { Dictionary . Entry . key = transform_expression key ; value = transform_expression value } in let transform_substring substring ~ transform_expression = match substring with | Substring . Format expression -> Substring . Format ( transform_expression expression ) | Substring . Literal _ -> substring in let rec transform_expression expression = let transform_children value = match value with | Expression . Await expression -> Expression . Await ( transform_expression expression ) | BooleanOperator { BooleanOperator . left ; operator ; right } -> BooleanOperator { BooleanOperator . left = transform_expression left ; operator ; right = transform_expression right ; } | Call { callee ; arguments } -> Call { callee = transform_expression callee ; arguments = transform_arguments arguments } | ComparisonOperator { ComparisonOperator . left ; operator ; right } -> ComparisonOperator { ComparisonOperator . left = transform_expression left ; operator ; right = transform_expression right ; } | Constant _ -> value | Dictionary { Dictionary . entries ; keywords } -> Dictionary { Dictionary . entries = transform_list entries ~ f ( : transform_entry ~ transform_expression ) ; keywords = transform_list keywords ~ f : transform_expression ; } | DictionaryComprehension { Comprehension . element ; generators } -> DictionaryComprehension { Comprehension . element = transform_entry element ~ transform_expression ; generators = transform_list generators ~ f ( : transform_generator ~ transform_expression ) ; } | Generator { Comprehension . element ; generators } -> Generator { Comprehension . element = transform_expression element ; generators = transform_list generators ~ f ( : transform_generator ~ transform_expression ) ; } | FormatString substrings -> FormatString ( transform_list substrings ~ f ( : transform_substring ~ transform_expression ) ) | Lambda { Lambda . parameters ; body } -> Lambda { Lambda . parameters = transform_list parameters ~ f ( : transform_parameter ~ transform_expression ) ; body = transform_expression body ; } | List elements -> List ( transform_list elements ~ f : transform_expression ) | ListComprehension { Comprehension . element ; generators } -> ListComprehension { Comprehension . element = transform_expression element ; generators = transform_list generators ~ f ( : transform_generator ~ transform_expression ) ; } | Name ( Name . Identifier _ ) -> value | Name ( Name . Attribute ( { base ; _ } as name ) ) -> Name ( Name . Attribute { name with base = transform_expression base } ) | Set elements -> Set ( transform_list elements ~ f : transform_expression ) | SetComprehension { Comprehension . element ; generators } -> SetComprehension { Comprehension . element = transform_expression element ; generators = transform_list generators ~ f ( : transform_generator ~ transform_expression ) ; } | Starred starred -> let starred = match starred with | Starred . Once expression -> Starred . Once ( transform_expression expression ) | Starred . Twice expression -> Starred . Twice ( transform_expression expression ) in Starred starred | Ternary { Ternary . target ; test ; alternative } -> Ternary { Ternary . target = transform_expression target ; test = transform_expression test ; alternative = transform_expression alternative ; } | Tuple elements -> Tuple ( transform_list elements ~ f : transform_expression ) | UnaryOperator { UnaryOperator . operator ; operand } -> UnaryOperator { UnaryOperator . operator ; operand = transform_expression operand } | WalrusOperator { target ; value } -> WalrusOperator { target = transform_expression target ; value = transform_expression value } | Expression . Yield expression -> Expression . Yield ( expression >>| transform_expression ) | Expression . YieldFrom expression -> Expression . YieldFrom ( expression |> transform_expression ) in let initial_state = ! state in let expression = if Transformer . transform_expression_children ! state expression then { expression with Node . value = transform_children ( Node . value expression ) } else expression in let expression = Transformer . expression ! state expression in state := initial_state ; expression and transform_arguments arguments = let transform_argument { Call . Argument . name ; value } = { Call . Argument . name ; value = transform_expression value } in transform_list arguments ~ f : transform_argument in let rec transform_statement statement = let transform_children value = match value with | Statement . Assign { Assign . target ; annotation ; value } -> Statement . Assign { Assign . target = transform_expression target ; annotation = annotation >>| transform_expression ; value = transform_expression value ; } | Assert { Assert . test ; message ; origin } -> Assert { Assert . test = transform_expression test ; message = message >>| transform_expression ; origin ; } | Break -> value | Class { Class . name ; base_arguments ; body ; decorators ; top_level_unbound_names } -> Class { Class . name ; base_arguments = transform_list base_arguments ~ f ( : transform_argument ~ transform_expression ) ; body = transform_list body ~ f : transform_statement |> List . concat ; decorators = transform_list decorators ~ f : transform_expression ; top_level_unbound_names ; } | Continue -> value | Define { signature ; captures ; unbound_names ; body } -> let transform_signature { Define . Signature . name ; parameters ; decorators ; return_annotation ; async ; parent ; nesting_define ; generator ; } = { Define . Signature . name ; parameters = transform_list parameters ~ f ( : transform_parameter ~ transform_expression ) ; decorators = transform_list decorators ~ f : transform_expression ; return_annotation = return_annotation >>| transform_expression ; async ; parent ; nesting_define ; generator ; } in let transform_capture { Define . Capture . name ; kind } = let transform_kind = function | Define . Capture . Kind . Annotation annotation -> let annotation = Option . map annotation ~ f : transform_expression in Define . Capture . Kind . Annotation annotation | Define . Capture . Kind . DefineSignature value -> let value = transform_signature value in Define . Capture . Kind . DefineSignature value | Define . Capture . Kind . ( Self _ | ClassSelf _ ) as kind -> kind in { Define . Capture . name ; kind = transform_kind kind } in Define { signature = transform_signature signature ; captures = List . map captures ~ f : transform_capture ; unbound_names ; body = transform_list body ~ f : transform_statement |> List . concat ; } | Delete expressions -> Delete ( List . map expressions ~ f : transform_expression ) | Expression expression -> Expression ( transform_expression expression ) | For { For . target ; iterator ; body ; orelse ; async } -> For { For . target = transform_expression target ; iterator = transform_expression iterator ; body = transform_list body ~ f : transform_statement |> List . concat ; orelse = transform_list orelse ~ f : transform_statement |> List . concat ; async ; } | Global _ -> value | If { If . test ; body ; orelse } -> If { If . test = transform_expression test ; body = transform_list body ~ f : transform_statement |> List . concat ; orelse = transform_list orelse ~ f : transform_statement |> List . concat ; } | Import _ -> value | Match { Match . subject ; cases } -> let rec transform_pattern { Node . value ; location } = let value = match value with | Match . Pattern . MatchAs { pattern ; name } -> Match . Pattern . MatchAs { pattern = pattern >>| transform_pattern ; name } | MatchClass { class_name ; patterns ; keyword_attributes ; keyword_patterns } -> MatchClass { class_name ; patterns = transform_list patterns ~ f : transform_pattern ; keyword_attributes ; keyword_patterns = transform_list keyword_patterns ~ f : transform_pattern ; } | MatchMapping { keys ; patterns ; rest } -> MatchMapping { keys = transform_list keys ~ f : transform_expression ; patterns = transform_list patterns ~ f : transform_pattern ; rest ; } | MatchOr patterns -> MatchOr ( transform_list patterns ~ f : transform_pattern ) | MatchSequence patterns -> MatchSequence ( transform_list patterns ~ f : transform_pattern ) | MatchSingleton constant -> ( let expression = transform_expression { Node . value = Expression . Constant constant ; location } in match expression . value with | Expression . Constant constant -> MatchSingleton constant | _ -> MatchValue expression ) | MatchStar maybe_identifier -> MatchStar maybe_identifier | MatchValue expression -> MatchValue expression | MatchWildcard -> MatchWildcard in { Node . value ; location } in let transform_case { Match . Case . pattern ; guard ; body } = { Match . Case . pattern = transform_pattern pattern ; guard = guard >>| transform_expression ; body = transform_list body ~ f : transform_statement |> List . concat ; } in Match { Match . subject = transform_expression subject ; cases = transform_list cases ~ f : transform_case ; } | Nonlocal _ -> value | Pass -> value | Raise { Raise . expression ; from } -> Raise { Raise . expression = expression >>| transform_expression ; from = from >>| transform_expression ; } | Return ( { Return . expression ; _ } as return ) -> Return { return with Return . expression = expression >>| transform_expression } | Try { Try . body ; handlers ; orelse ; finally } -> let transform_handler { Try . Handler . kind ; name ; body } = { Try . Handler . kind = kind >>| transform_expression ; name ; body = transform_list body ~ f : transform_statement |> List . concat ; } in let body = transform_list body ~ f : transform_statement |> List . concat in let handlers = transform_list handlers ~ f : transform_handler in let orelse = transform_list orelse ~ f : transform_statement |> List . concat in let finally = transform_list finally ~ f : transform_statement |> List . concat in Try { Try . body ; handlers ; orelse ; finally } | With { With . items ; body ; async } -> let transform_item ( item , alias ) = transform_expression item , alias >>| transform_expression in With { With . items = transform_list items ~ f : transform_item ; body = transform_list body ~ f : transform_statement |> List . concat ; async ; } | While { While . test ; body ; orelse } -> While { While . test = transform_expression test ; body = transform_list body ~ f : transform_statement |> List . concat ; orelse = transform_list orelse ~ f : transform_statement |> List . concat ; } in let statement = let parent_state , should_transform_children = Transformer . transform_children ! state statement in if should_transform_children then ( state := parent_state ; { statement with Node . value = transform_children ( Node . value statement ) } ) else statement in let new_state , statements = Transformer . statement ! state statement in state := new_state ; statements in let statements = transform_list source . Source . statements ~ f : transform_statement |> List . concat in { state = ! state ; source = { source with Source . statements } } end
module MakeStatementTransformer ( Transformer : StatementTransformer ) = struct type result = { state : Transformer . t ; source : Source . t ; } let source { source ; _ } = source let transform state source = let state = ref state in let open Statement in let rec transform_statement { Node . location ; value } = let value = match value with | Assign _ | Assert _ | Break | Continue | Delete _ | Expression _ | Global _ | Import _ | Pass | Raise _ | Return _ | Nonlocal _ -> value | Class ( { Class . body ; _ } as value ) -> Class { value with Class . body = List . concat_map ~ f : transform_statement body } | Define ( { Define . body ; _ } as value ) -> Define { value with Define . body = List . concat_map ~ f : transform_statement body } | With ( { With . body ; _ } as value ) -> With { value with With . body = List . concat_map ~ f : transform_statement body } | For ( { For . body ; orelse ; _ } as value ) -> let body = List . concat_map ~ f : transform_statement body in let orelse = List . concat_map ~ f : transform_statement orelse in For { value with For . body ; orelse } | If ( { If . body ; orelse ; _ } as value ) -> let body = List . concat_map ~ f : transform_statement body in let orelse = List . concat_map ~ f : transform_statement orelse in If { value with If . body ; orelse } | Match ( { Match . cases ; _ } as value ) -> let transform_case ( { Match . Case . body ; _ } as value ) = { value with Match . Case . body = List . concat_map ~ f : transform_statement body } in Match { value with Match . cases = List . map ~ f : transform_case cases } | While ( { While . body ; orelse ; _ } as value ) -> let body = List . concat_map ~ f : transform_statement body in let orelse = List . concat_map ~ f : transform_statement orelse in While { value with While . body ; orelse } | Try { Try . body ; handlers ; orelse ; finally } -> let transform_handler ( { Try . Handler . body ; _ } as value ) = { value with Try . Handler . body = List . concat_map ~ f : transform_statement body } in let body = List . concat_map ~ f : transform_statement body in let handlers = List . map ~ f : transform_handler handlers in let orelse = List . concat_map ~ f : transform_statement orelse in let finally = List . concat_map ~ f : transform_statement finally in Try { Try . body ; handlers ; orelse ; finally } in let new_state , statements = Transformer . statement ! state { Node . location ; value } in state := new_state ; statements in let statements = List . concat_map ~ f : transform_statement source . Source . statements in { state = ! state ; source = { source with Source . statements } } end
let transform_expressions ~ transform statement = let module TransformExpressions = Make ( struct type t = unit let transform_expression_children _ _ = true let expression _ { Node . value ; location } = { Node . value = transform value ; location } let transform_children state _ = state , true let statement state statement = state , [ statement ] end ) in TransformExpressions . transform ( ) ( Source . create [ Node . create_with_default_location statement ] ) |> ( fun { TransformExpressions . source ; _ } -> source ) |> Source . statements |> function | [ { Node . value = statement ; _ } ] -> statement | _ -> failwith " expected single statement "
let sanitize_expression expression = let transform = function | Expression . Name ( Name . Identifier identifier ) -> Expression . Name ( Name . Identifier ( Identifier . sanitized identifier ) ) | Name ( Name . Attribute ( { attribute ; _ } as attribute_expression ) ) -> Name ( Name . Attribute { attribute_expression with attribute = Identifier . sanitized attribute } ) | expression -> expression in match transform_expressions ~ transform ( Statement . Expression expression ) with | Statement . Expression expression -> expression | _ -> expression
let sanitize_statement statement = let module SanitizeSignatures = MakeStatementTransformer ( struct type t = unit let statement state = function | { Node . value = Statement . Define ( { Define . signature = { Define . Signature . name ; parameters ; _ } as signature ; _ } as define ) ; _ ; } as statement -> let transform_parameter ( { Node . value = { Parameter . name ; _ } as parameter ; _ } as parameter_node ) = { parameter_node with value = { parameter with name = Identifier . sanitized name } } in ( state , [ { statement with value = Statement . Define { define with signature = { signature with name = Reference . sanitized name ; parameters = List . map parameters ~ f : transform_parameter ; } ; } ; } ; ] ) | statement -> state , [ statement ] end ) in let sanitized_statement = let sanitize_expression expression = Node . create_with_default_location expression |> sanitize_expression |> Node . value in let sanitize_signatures statement = SanitizeSignatures . transform ( ) ( Source . create [ Node . create_with_default_location statement ] ) in transform_expressions ~ transform : sanitize_expression statement |> sanitize_signatures |> SanitizeSignatures . source |> Source . statements in match sanitized_statement with | [ { Node . value = statement ; _ } ] -> statement | _ -> statement
module Toc = struct open Tyxml type t = heading list and heading = H of int * string let to_string ( H ( size , text ) ) = " H " ^ string_of_int size ^ " " ^ text let get_int = function H ( i , _ ) -> i let toc doc = let open Omd in let rec loop acc = function | [ ] -> List . rev acc | ( b : attributes block ) :: bs -> ( match b with | Heading ( _attrs , s , il ) -> ( match il with | Text ( _ , heading ) -> loop ( H ( s , heading ) :: acc ) bs | _ -> loop acc bs ) | _ -> loop acc bs ) in loop [ ] doc let transform doc = let open Omd in let f ( b : attributes block ) = match b with | Heading ( attrs , s , il ) -> ( match il with | Text ( _ , heading ) -> Heading ( ( " id " , Utils . title_to_dirname heading ) :: attrs , s , il ) | _ -> b ) | _ -> b in List . map f doc type ' a tree = Br of ' a * ' a tree list let to_tree lst = let arr = Array . init 7 ( fun i -> Br ( H ( i , " " ) , [ ] ) ) in let rec tidy arr until = function | n when n <= until -> ( ) | n -> let t = arr . ( n ) in let ( Br ( v , lst ) ) = arr . ( n - 1 ) in arr . ( n - 1 ) <- Br ( v , lst @ [ t ] ) ; tidy arr until ( n - 1 ) in let rec aux last = function | [ ] -> tidy arr 0 last ; arr . ( 0 ) | [ a ] -> let x = get_int a in arr . ( x ) <- Br ( a , [ ] ) ; aux x [ ] | a :: b :: xs -> let x = get_int a in let y = get_int b in let _t = arr . ( x ) in let ( Br ( p , lst ) ) = arr . ( x - 1 ) in if x = y then ( arr . ( x - 1 ) <- Br ( p , lst @ [ Br ( a , [ ] ) ] ) ; aux x ( b :: xs ) ) else if x > y then ( arr . ( x ) <- Br ( a , [ ] ) ; tidy arr ( y - 1 ) x ; aux x ( b :: xs ) ) else ( arr . ( x ) <- Br ( a , [ ] ) ; aux x ( b :: xs ) ) in aux 0 lst let map_to_item h = let to_elt cl link txt = [ % html " < a class " = cl " href " = ( " " # ^ link ) " " > [ Html . txt txt ] " </ a " ] > in match h with | H ( i , txt ) -> if String . equal txt " " then [ ] else [ to_elt [ " toc - link " ; " toc - item " - ^ string_of_int i ] ( Utils . title_to_dirname txt ) txt ; ] let rec preorder = function | Br ( v , [ ] ) -> [ % html " < ul class ' = toc ' >< li class ' = toc - li ' " > ( map_to_item v ) " </ li ></ ul " ] > | Br ( v , lst ) -> [ % html " < ul class ' = toc ' >< li " > ( map_to_item v @ List . fold_left ( fun acc v -> acc @ [ preorder v ] ) [ ] lst ) " </ li ></ ul " ] > let pp ppf t = List . iter ( fun h -> Format . pp_print_string ppf ( to_string h ^ " \ n " ) ) t let rec accessibility = function | x :: y :: ys -> let a = get_int x in let b = get_int y in if get_int x < get_int y then if b - a = 1 then accessibility ( y :: ys ) else raise ( Failure " Failed because of inproper heading nesting " ) | _ -> assert true let to_html toc = ( try accessibility toc with Failure t -> print_endline " == Failed Heading List " ; == pp Format . std_formatter toc ; raise ( Failure t ) ) ; let tree = to_tree toc in preorder tree |> fun list -> [ % html " < details >< summary > Table of Contents </ summary " > [ list ] " </ details " ] > end
module Image = struct type t = { conf : Image . Transform . conf ; path : Fpath . t ; responsive : Responsive . Images . t ; } let v ~ quality ~ path ~ dst responsive = { conf = Image . Transform . { quality ; dst ; rename = Fun . id ; files = [ ] } ; path ; responsive ; } let transform t blocks = let open Omd in let f ( b : attributes block ) = let make_img img = let html = Fmt . str " % a " ( Tyxml . Html . pp_elt ( ) ) img in Html ( [ ] , html ) in match b with | Paragraph ( attrs , il ) -> ( match il with | Omd . Image ( _ , { label = Omd . Text ( _ , alt ) ; destination ; _ } ) -> let conf = { t . conf with files = [ Fpath . v destination ] } in let conf = Responsive . Images . { conf ; root = t . path } in let img = Responsive . Images . v ~ alt ~ conf t . responsive |> List . hd |> snd in Paragraph ( attrs , make_img img ) | _ -> b ) | _ -> b in List . map f blocks end
module ModifyingTransformer : sig type t = int include Transform . Transformer with type t := t val final : t -> int include Transform . Identity type t = int let final count = count let expression _ = function | { Node . location ; value = Expression . Constant ( Constant . Integer number ) } -> { Node . location ; value = Expression . Constant ( Constant . Integer ( number + 1 ) ) } | expression -> expression end
module ShallowModifyingTransformer : sig type t = int include Transform . Transformer with type t := t include Transform . Identity include ModifyingTransformer let transform_children state _ = state , false end
module ModifyingTransform = Transform . Make ( ModifyingTransformer )
module ShallowModifyingTransform = Transform . Make ( ShallowModifyingTransformer )
let assert_modifying_source ( ? shallow = false ) statements expected_statements expected_sum = let state , modified = if shallow then let { ShallowModifyingTransform . state ; source } = ShallowModifyingTransform . transform 0 ( Source . create statements ) in state , source else let { ModifyingTransform . state ; source } = ModifyingTransform . transform 0 ( Source . create statements ) in state , source in assert_source_equal ( Source . create expected_statements ) modified ; assert_equal expected_sum ( ModifyingTransformer . final state ) ~ printer : string_of_int
let test_transform _ = assert_modifying_source [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 1 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Integer 2 ) ) ; ] [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 2 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ; ] 0 ; assert_modifying_source [ + Statement . Expression ( + Expression . WalrusOperator { target = " ! a " ; value = + Expression . Constant ( Constant . Integer 1 ) } ) ; ] [ + Statement . Expression ( + Expression . WalrusOperator { target = " ! a " ; value = + Expression . Constant ( Constant . Integer 2 ) } ) ; ] 0 ; assert_modifying_source [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 2 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 4 ) ) ] ; } ; ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ] ; } ; ] [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 2 ) ; body = [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 3 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 4 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ] ; } ; ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 6 ) ) ] ; } ; ] 0 ; assert_modifying_source ~ shallow : true [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 2 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 4 ) ) ] ; } ; ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ] ; } ; ] [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 2 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 4 ) ) ] ; } ; ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ] ; } ; ] 0 ; assert_modifying_source [ + Statement . Match { Match . subject = + Expression . Constant ( Constant . Integer 0 ) ; cases = [ { Match . Case . pattern = + Match . Pattern . MatchSingleton ( Constant . Integer 2 ) ; guard = Some ( + Expression . Constant ( Constant . Integer 4 ) ) ; body = [ ] ; } ; ] ; } ; ] [ + Statement . Match { Match . subject = + Expression . Constant ( Constant . Integer 1 ) ; cases = [ { Match . Case . pattern = + Match . Pattern . MatchSingleton ( Constant . Integer 3 ) ; guard = Some ( + Expression . Constant ( Constant . Integer 5 ) ) ; body = [ ] ; } ; ] ; } ; ] 0
module ExpandingTransformer : sig type t = unit include Transform . Transformer with type t := t include Transform . Identity type t = unit let statement state statement = state , [ statement ; statement ] end
module ShallowExpandingTransformer : sig type t = unit include Transform . Transformer with type t := t include Transform . Identity include ExpandingTransformer let transform_children state _ = state , false end
module ExpandingTransform = Transform . Make ( ExpandingTransformer )
module ShallowExpandingTransform = Transform . Make ( ShallowExpandingTransformer )
let assert_expanded_source ( ? shallow = false ) statements expected_statements = let modified = if shallow then ShallowExpandingTransform . transform ( ) ( Source . create statements ) |> ShallowExpandingTransform . source else ExpandingTransform . transform ( ) ( Source . create statements ) |> ExpandingTransform . source in assert_source_equal ( Source . create expected_statements ) modified
let test_expansion _ = assert_expanded_source [ + Statement . Expression ( + Expression . Constant ( Constant . Float 1 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 2 . 0 ) ) ; ] [ + Statement . Expression ( + Expression . Constant ( Constant . Float 1 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 1 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 2 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 2 . 0 ) ) ; ] ; assert_expanded_source ~ shallow : true [ + Statement . Expression ( + Expression . Constant ( Constant . Float 1 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 2 . 0 ) ) ; ] [ + Statement . Expression ( + Expression . Constant ( Constant . Float 1 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 1 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 2 . 0 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Float 2 . 0 ) ) ; ] ; assert_expanded_source [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ] ; } ; ] [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ; ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ; ] ; } ; + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ; ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ; + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ; ] ; } ; ] ; assert_expanded_source ~ shallow : true [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ] ; } ; ] [ + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ] ; } ; + Statement . If { If . test = + Expression . Constant ( Constant . Integer 1 ) ; body = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 3 ) ) ] ; orelse = [ + Statement . Expression ( + Expression . Constant ( Constant . Integer 5 ) ) ] ; } ; ]
let test_expansion_with_stop _ = let module StoppingExpandingTransformer : sig type t = unit include Transform . Transformer with type t := t end = struct include ExpandingTransformer let transform_children state _ = state , false end in let module StoppingExpandingTransform = Transform . Make ( StoppingExpandingTransformer ) in let assert_expanded_source_with_stop source expected_source = let modified = StoppingExpandingTransform . transform ( ) ( parse source ) |> StoppingExpandingTransform . source in assert_source_equal ~ location_insensitive : true ( parse expected_source ) modified in assert_expanded_source_with_stop { | if ( 1 ) : if ( 2 ) : 3 else : 4 else : if ( 5 ) : 6 else : 7 } | { | if ( 1 ) : if ( 2 ) : 3 else : 4 else : if ( 5 ) : 6 else : 7 if ( 1 ) : if ( 2 ) : 3 else : 4 else : if ( 5 ) : 6 else : 7 } |
let test_double_count _ = let module DoubleCounterTransformer : sig type t = int include Transform . Transformer with type t := t end = struct include Transform . Identity type t = int let statement count statement = count + 1 , [ statement ] end in let module ShallowDoubleCounterTransformer : sig type t = int include Transform . Transformer with type t := t end = struct include Transform . Identity include DoubleCounterTransformer let transform_children state _ = state , false end in let module DoubleCounterTransform = Transform . Make ( DoubleCounterTransformer ) in let module ShallowDoubleCounterTransform = Transform . Make ( ShallowDoubleCounterTransformer ) in let assert_double_count ( ? shallow = false ) source expected_sum = let state , modified = if shallow then let { ShallowDoubleCounterTransform . state ; source } = ShallowDoubleCounterTransform . transform 0 ( parse source ) in state , source else let { DoubleCounterTransform . state ; source } = DoubleCounterTransform . transform 0 ( parse source ) in state , source in assert_source_equal ( parse source ) modified ; assert_equal expected_sum ( ModifyingTransformer . final state ) ~ printer : string_of_int in assert_double_count { | 1 . 0 2 . 0 } | 2 ; assert_double_count ~ shallow : true { | 1 . 0 2 . 0 } | 2 ; assert_double_count { | if ( 1 ) : 3 else : 5 } | 3 ; assert_double_count ~ shallow : true { | if ( 1 ) : 3 else : 5 } | 1 ; assert_double_count { | if ( 1 ) : if ( 2 ) : 3 else : 4 else : if ( 5 ) : 6 else : 7 } | 7 ; assert_double_count ~ shallow : true { | if ( 1 ) : if ( 2 ) : 3 else : 4 else : if ( 5 ) : 6 else : 7 } | 1
let test_conditional_count _ = let module NestedCounterTransformer : sig type t = { is_nested : bool ; statement_count : int ; } include Transform . Transformer with type t := t end = struct type t = { is_nested : bool ; statement_count : int ; } let transform_expression_children _ _ = false let transform_children ( { is_nested ; _ } as state ) statement = match Node . value statement with | Statement . Class _ -> { state with is_nested = true } , true | _ -> state , is_nested let expression _ expression = expression let statement { statement_count ; is_nested } statement = let is_nested , statement_count = match Node . value statement with | Statement . Class _ -> false , statement_count | _ -> is_nested , if is_nested then statement_count + 1 else statement_count in { is_nested ; statement_count } , [ statement ] end in let module NestedCounterTransform = Transform . Make ( NestedCounterTransformer ) in let assert_conditional_count source expected_statement_count = let statement_count { NestedCounterTransformer . statement_count ; _ } = statement_count in let state , modified = let { NestedCounterTransform . state ; source } = NestedCounterTransform . transform { statement_count = 0 ; is_nested = false } ( parse source ) in state , source in assert_source_equal ( parse source ) modified ; assert_equal expected_statement_count ( statement_count state ) in assert_conditional_count { | 1 . 0 2 . 0 } | 0 ; assert_conditional_count { | 1 . 0 class Foo : 2 . 0 } | 1 ; assert_conditional_count { | 1 . 0 class Foo : 2 . 0 def method ( self ) -> None : 3 . 0 4 . 0 } | 3 ; ( )
let test_statement_transformer _ = let module ModifyingStatementTransformer : sig type t = int include Transform . StatementTransformer with type t := t val final : t -> int end = struct type t = int let final count = count let statement count { Node . location ; value } = let count , value = match value with | Statement . Assign ( { Assign . value = { Node . value = Constant ( Constant . Integer number ) ; _ } as value ; _ } as assign ) -> ( count + number , Statement . Assign { assign with Assign . value = { value with Node . value = Constant ( Constant . Integer ( number + 1 ) ) } ; } ) | _ -> count , value in count , [ { Node . location ; value } ] end in let module Transform = Transform . MakeStatementTransformer ( ModifyingStatementTransformer ) in let assert_transform source expected expected_sum = let { Transform . state ; source = modified } = Transform . transform 0 ( parse source ) in assert_source_equal ( parse expected ) modified ; assert_equal expected_sum ( ModifyingStatementTransformer . final state ) ~ printer : string_of_int in assert_transform { | def foo ( ) : x = 1 y = 2 2 3 + 4 x = 3 y = 4 if 1 == 3 : x = 5 else : if a > b : y = 6 class C : z = 7 match x : case 1 : w = 0 } | { | def foo ( ) : x = 2 y = 3 2 3 + 4 x = 4 y = 5 if 1 == 3 : x = 6 else : if a > b : y = 7 class C : z = 8 match x : case 1 : w = 1 } | 28
let test_transform_expression _ = let keep_first_argument = function | Expression . Call { Call . callee = { Node . value = Name ( Identifier given_callee_name ) ; location } ; arguments = argument :: _ ; } -> Expression . Call { Call . callee = { Node . value = Name ( Identifier given_callee_name ) ; location } ; arguments = [ argument ] ; } | expression -> expression in let assert_transform given expected = match parse given |> Source . statements , parse expected |> Source . statements with | [ { Node . value = given ; _ } ] , [ { Node . value = expected ; _ } ] -> let actual = Transform . transform_expressions ~ transform : keep_first_argument given in let printer x = [ % sexp_of : Statement . statement ] x |> Sexp . to_string_hum in assert_equal ~ cmp ( : fun left right -> Statement . location_insensitive_compare ( Node . create_with_default_location left ) ( Node . create_with_default_location right ) = 0 ) ~ printer ~ pp_diff ( : diff ~ print ( : fun format x -> Format . fprintf format " % s " ( printer x ) ) ) expected actual | _ -> failwith " expected one statement each " in assert_transform { | def foo ( ) : bar ( 1 , 2 ) x = bar ( bar ( 1 , bar ( 2 , 3 ) ) , bar ( 4 , 5 ) ) some_other_function ( ) } | { | def foo ( ) : bar ( 1 ) x = bar ( bar ( 1 ) ) some_other_function ( ) } ; | ( )
let test_sanitize_statement _ = let assert_sanitized statements expected = let given_statement , expected_statement = match statements , parse expected |> Source . statements with | [ { Node . value = given_statement ; _ } ] , [ { Node . value = expected_statement ; _ } ] -> given_statement , expected_statement | _ -> failwith " Expected defines " in assert_equal ~ cmp ( : fun left right -> Statement . location_insensitive_compare left right = 0 ) ~ printer [ :% show : Statement . t ] ( expected_statement |> Node . create_with_default_location ) ( Transform . sanitize_statement given_statement |> Node . create_with_default_location ) in assert_sanitized [ + Statement . Define { Define . signature = { Define . Signature . name = " !&$ local_test ? foo $ bar " ; parameters = [ { + Parameter . name = " $ parameter $ a " ; value = None ; annotation = Some " ! int " } ] ; decorators = [ ] ; return_annotation = Some " ! int " ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ + Statement . Assign { Assign . target = " !$ local_test ? foo ? bar $ my_kwargs " ; annotation = None ; value = + Expression . Dictionary { Dictionary . entries = [ { Dictionary . Entry . key = + Expression . Constant ( Constant . String ( StringLiteral . create " a " ) ) ; value = " !$ parameter $ a " ; } ; ] ; keywords = [ ] ; } ; } ; + Statement . Expression ( + Expression . Call { Call . callee = " ! print " ; arguments = [ { Call . Argument . name = None ; value = " !$ local_test ? foo ? bar $ my_kwargs " } ] ; } ) ; + Statement . Return { Return . is_implicit = false ; expression = Some ( + Expression . Call { Call . callee = " !$ local_test ? foo $ baz " ; arguments = [ { Call . Argument . name = None ; value = " !$ parameter $ a " } ] ; } ) ; } ; ] ; } ; ] { | def bar ( a : int ) -> int : my_kwargs = { " a " : a } print ( my_kwargs ) return baz ( a ) } ; | assert_sanitized [ + Statement . Define { Define . signature = { Define . Signature . name = " !& bar " ; parameters = [ { + Parameter . name = " a " ; value = None ; annotation = Some " ! int " } ] ; decorators = [ ] ; return_annotation = Some " ! int " ; async = false ; generator = false ; parent = None ; nesting_define = None ; } ; captures = [ ] ; unbound_names = [ ] ; body = [ + Statement . Assign { Assign . target = " ! my_kwargs " ; annotation = None ; value = + Expression . Dictionary { Dictionary . entries = [ { Dictionary . Entry . key = + Expression . Constant ( Constant . String ( StringLiteral . create " a " ) ) ; value = " ! a " ; } ; ] ; keywords = [ ] ; } ; } ; + Statement . Expression ( + Expression . Call { Call . callee = " ! print " ; arguments = [ { Call . Argument . name = None ; value = " ! my_kwargs " } ] ; } ) ; + Statement . Return { Return . is_implicit = false ; expression = Some ( + Expression . Call { Call . callee = " ! baz " ; arguments = [ { Call . Argument . name = None ; value = " ! a " } ] ; } ) ; } ; ] ; } ; ] { | def bar ( a : int ) -> int : my_kwargs = { " a " : a } print ( my_kwargs ) return baz ( a ) } ; | ( )
let ( ) = " transform " >::: [ " transform " >:: test_transform ; " expansion " >:: test_expansion ; " expansion_with_stop " >:: test_expansion_with_stop ; " statement_double_counter " >:: test_double_count ; " statement_conditional_counter " >:: test_conditional_count ; " statement_transformer " >:: test_statement_transformer ; " transform_expression " >:: test_transform_expression ; " sanitize_statement " >:: test_sanitize_statement ; ] |> Test . run
module Apply_optimization_framework ( Input : Semantics . Bioinformatics_base ) module Transformation_types = struct type ' a from = ' a Input . repr type ' a term = | Unknown : ' a from -> ' a term | Apply : ( ' a -> ' b ) term * ' a term -> ' b term | Lambda : ( ' a term -> ' b term ) -> ( ' a -> ' b ) term | List_make : ( ' a term ) list -> ' a list term | List_map : ( ' a list term * ( ' a -> ' b ) term ) -> ' b list term | Pair : ' a term * ' b term -> ( ' a * ' b ) term | Fst : ( ' a * ' b ) term -> ' a term | Snd : ( ' a * ' b ) term -> ' b term let fwd x = Unknown x let rec bwd : type a . a term -> a from = function | Apply ( Lambda f , v ) -> bwd ( f v ) | Apply ( other , v ) -> Input . apply ( bwd other ) ( bwd v ) | List_map ( List_make l , Lambda f ) -> Input . list ( List . map ~ f ( : fun x -> bwd ( f x ) ) l ) | List_map ( x , f ) -> Input . list_map ~ f ( : bwd f ) ( bwd x ) | Lambda f -> Input . lambda ( fun x -> ( bwd ( f ( fwd x ) ) ) ) | List_make l -> Input . list ( List . map ~ f : bwd l ) | Fst ( Pair ( a , b ) ) -> bwd a | Snd ( Pair ( a , b ) ) -> bwd b | Pair ( a , b ) -> Input . pair ( bwd a ) ( bwd b ) | Fst b -> Input . pair_first ( bwd b ) | Snd b -> Input . pair_second ( bwd b ) | Unknown x -> x end module Transformation = Optimization_framework . Define_transformation ( Transformation_types ) open Transformation module Language_delta = struct open Transformation_types let apply f x = Apply ( f , x ) let lambda f = Lambda f let list l = List_make l let list_map l ~ f = List_map ( l , f ) let pair a b = Pair ( a , b ) let pair_first p = Fst p let pair_second p = Snd p end end
module Apply ( Input : Semantics . Bioinformatics_base ) = struct module The_pass = Apply_optimization_framework ( Input ) include Optimization_framework . Generic_optimizer ( The_pass . Transformation ) ( Input ) include The_pass . Language_delta end
module Big_int = struct include Big_int exception Error let sexp_of_big_int x = Sexp . Atom ( Big_int . string_of_big_int x ) let big_int_of_sexp sexp = match sexp with | Sexp . Atom str -> Big_int . big_int_of_string str | Sexp . List _ -> raise Error end
module T = struct type t = [ | ` Null | ` String of String . t | ` Bool of Bool . t | ` Int of Int64 . t | ` BigInt of Big_int . big_int | ` Float of Float . t | ` Bytes of string | ` Array of t list | ` Map of ( t , t ) Map . Poly . t | ` UUID of Uuid . t | ` Keyword of String . t | ` Symbol of String . t | ` Time of Time . t | ` URI of String . t | ` List of t list | ` Set of t Set . Poly . t | ` Extension of string * t ] with sexp , compare end
module CacheCode = struct exception Invalid_cache_code of string let base_char_index = 48 let cache_code_digits = 44 let max_count = 44 * 44 - 1 let to_int s = match String . length s with | 1 -> ( Char . to_int s . [ 0 ] ) - base_char_index | 2 -> ( ( Char . to_int s . [ 0 ] ) - base_char_index ) * cache_code_digits + ( ( Char . to_int s . [ 1 ] ) - base_char_index ) | _ -> raise ( Invalid_cache_code s ) let of_int i = let hi = i / cache_code_digits in let lo = i % cache_code_digits in if i > max_count then raise ( Invalid_cache_code " Integer is larger than 1936 " ) else if hi = 0 then " " ^ ^ String . of_char ( Char . of_int_exn ( lo + base_char_index ) ) else " " ^ ^ String . of_char ( Char . of_int_exn ( hi + base_char_index ) ) ^ String . of_char ( Char . of_int_exn ( lo + base_char_index ) ) end
module Reader = struct exception Internal_error exception Parse_error of string module Context = struct type tag = | Quote | List | Set | CMap | Unknown of string with sexp let tag_of_string = function | " ' " ~# -> Quote | " ~# list " -> List | " ~# set " -> Set | " ~# cmap " -> CMap | s -> Unknown ( String . drop_prefix s 2 ) module Transit_cache = struct type entry = ETransit of T . t | ETag of tag type t = { m : entry Int . Map . t ; c : int } let empty = { m = Int . Map . empty ; c = 0 } let track { m ; c } s = let m ' = Int . Map . add m ~ key : c ~ data : s in if c > CacheCode . max_count then empty else { m = m ' ; c = c + 1 } let track_transit x v = track x ( ETransit v ) let track_tag x v = track x ( ETag v ) let find_exn { m ; _ } x = Int . Map . find_exn m x end module Cache = Transit_cache type context = | Empty | Focused of T . t | Array of T . t list * context | MapKey of ( T . t * T . t ) list * context | MapValue of T . t * ( T . t * T . t ) list * context | Tagged of tag * context with sexp type t = Cache . t * context let empty = ( Cache . empty , Empty ) let result ( _ , ctx ) = match ctx with | Focused v -> v | _ -> raise Internal_error let track_transit ( cache , ctx ) s x = if String . length s > 3 then ( Cache . track_transit cache x , ctx ) else ( cache , ctx ) let track_tag ( cache , ctx ) s x = let rec add ( cache , ctx ) e = match ctx with | Empty -> ( cache , Focused e ) | Focused _ -> raise Internal_error | Array ( es , ctx ) -> ( cache , Array ( e :: es , ctx ) ) | Tagged ( t , inner ) -> let ( cache ' , inner ' ) = add ( cache , inner ) e in ( cache ' , Tagged ( t , inner ' ) ) | MapKey ( es , ctx ) -> ( match e with | ` String s when String . length s > 3 -> ( Cache . track_transit cache e , MapValue ( e , es , ctx ) ) | _ -> ( cache , MapValue ( e , es , ctx ) ) ) | MapValue ( k , es , ctx ) -> ( cache , MapKey ( ( k , e ) :: es , ctx ) ) let push_map_as_array ( cache , ctx ) = match ctx with | Array ( [ ] , parent ) -> ( cache , MapKey ( [ ] , parent ) ) | _ -> raise ( Parse_error " Map - as - array marker in wrong location " ) ! let push_array ( cache , ctx ) = ( cache , Array ( [ ] , ctx ) ) let push_map ( cache , ctx ) = ( cache , MapKey ( [ ] , ctx ) ) let push_tagged ( cache , ctx ) t = match ctx with | Array ( [ ] , _ ) as cx -> ( cache , Tagged ( t , cx ) ) | MapKey ( [ ] , parent ) -> ( cache , Tagged ( t , MapValue ( ` Null , [ ] , parent ) ) ) | _ -> raise ( Parse_error " Array tag , but not parsing an array " ) let rec pairup = function | [ ] -> [ ] | k :: v :: rest -> ( k , v ) :: ( pairup rest ) | _ -> raise ( Parse_error " Odd number of pairs " ) let pop_map ( cache , ctx ) = match ctx with | MapKey ( res , parent ) -> add ( cache , parent ) ( ` Map ( Map . Poly . of_alist_exn res ) ) | Tagged ( Quote , MapKey ( [ _ , res ] , parent ) ) -> add ( cache , parent ) res | Tagged ( Set , MapKey ( [ _ , ` Array res ] , parent ) ) -> add ( cache , parent ) ( ` Set ( Set . Poly . of_list res ) ) | Tagged ( List , MapKey ( [ _ , ` Array res ] , parent ) ) -> add ( cache , parent ) ( ` List res ) | Tagged ( CMap , MapKey ( [ _ , ` Array res ] , parent ) ) -> add ( cache , parent ) ( ` Map ( Map . Poly . of_alist_exn ( pairup res ) ) ) | Tagged ( Unknown t , MapKey ( [ _ , res ] , parent ) ) -> add ( cache , parent ) ( ` Extension ( t , res ) ) | Tagged ( _ , _ ) -> raise Internal_error | MapValue ( _ , _ , _ ) -> raise ( Parse_error " end_of_map called with an “ free ” key " ) | Array ( _ , _ ) -> raise ( Parse_error " end_of_map in array context " ) | Empty -> raise ( Parse_error " end_of_map called in empty context " ) | Focused _ -> raise ( Parse_error " end_of_map called in focused context " ) let pop_array ( cache , ctx ) = match ctx with | Array ( res , parent ) -> add ( cache , parent ) ( ` Array ( List . rev res ) ) | Tagged ( List , Array ( [ ` Array res ] , parent ) ) -> add ( cache , parent ) ( ` List res ) | Tagged ( List , Array ( _ , _ ) ) -> raise ( Parse_error " Wrong ~# list encoding " ) | Tagged ( Set , Array ( [ ` Array res ] , parent ) ) -> add ( cache , parent ) ( ` Set ( Set . Poly . of_list res ) ) | Tagged ( Set , Array ( _ , _ ) ) -> raise ( Parse_error " Wrong ~# set encoding " ) | Tagged ( Quote , Array ( [ res ] , parent ) ) -> add ( cache , parent ) res | Tagged ( Quote , Array ( _ , _ ) ) -> raise ( Parse_error " Quote with multi - elem array " ) | Tagged ( CMap , Array ( [ ` Array res ] , parent ) ) -> add ( cache , parent ) ( ` Map ( Map . Poly . of_alist_exn ( pairup res ) ) ) | Tagged ( Unknown t , Array ( [ res ] , parent ) ) -> add ( cache , parent ) ( ` Extension ( t , res ) ) | Tagged ( _ , _ ) -> raise Internal_error | MapValue ( _ , _ , _ ) -> raise ( Parse_error " Odd number of k / v pairs in map - as - array / cmap " ) | MapKey ( res , parent ) -> add ( cache , parent ) ( ` Map ( Map . Poly . of_alist_exn res ) ) | Empty -> raise ( Parse_error " end_of_array called in Empty context " ) | Focused _ -> raise ( Parse_error " end_of_array called in Focused context " ) let cache_lookup ( ( cache , _ ) as cx ) s = match CacheCode . to_int s |> Cache . find_exn cache with | Cache . ETransit x -> add cx x | Cache . ETag t -> push_tagged cx t end let decode_tagged s = function | ' _ ' -> ` Null | ' s ' -> ` String s | ' ' ? -> ( match s with | " t " -> ` Bool true | " f " -> ` Bool false | _ -> raise ( Parse_error " decode_tagged ? case " ) ) | ' i ' -> ` Int ( Int64 . of_string s ) | ' n ' -> let i = Big_int . big_int_of_string s in ( try ` Int ( Big_int . int64_of_big_int i ) with Failure " nativeint_of_big_int " -> ` BigInt i ) | ' d ' -> ` Float ( Float . of_string s ) | ' b ' -> ` Bytes ( Base64 . decode_string s ) | ' u ' -> ( ` UUID ( Uuid . of_string s ) ) | ' r ' -> ( ` URI s ) | ' ' : -> ( ` Keyword s ) | ' ' $ -> ( ` Symbol s ) | ' m ' -> let f = Big_int . float_of_big_int ( Big_int . big_int_of_string s ) in ( ` Time ( Time . of_float ( f . / 1000 . 0 ) ) ) | ' t ' -> let tp = Time . of_string s in ` Time tp | t -> ` Extension ( String . of_char t , ` String s ) let decode_string s ctx head = let track x = Context . add ( Context . track_transit ctx s x ) x in match head with | ( ' ' , ^ ' ' ) -> Context . push_map_as_array ctx | ( ' ' , ^ _ ) -> Context . cache_lookup ctx ( String . drop_prefix s 1 ) | ( ' ' , ~ ' ' ) ~ -> ` String ( String . drop_prefix s 1 ) |> Context . add ctx | ( ' ' , ~ ' ' ) ^ -> ` String ( String . drop_prefix s 1 ) |> Context . add ctx | ( ' ' , ~ ' ' ) # -> let array_tag = Context . tag_of_string s in Context . push_tagged ( Context . track_tag ctx s array_tag ) array_tag | ( ' ' , ~ t ) -> ( match decode_tagged ( String . drop_prefix s 2 ) t with | ` Symbol sy -> track ( ` Symbol sy ) | ` Keyword k -> track ( ` Keyword k ) | value -> Context . add ctx value ) | _ -> Context . add ctx ( ` String s ) let on_null ctx = Context . add ctx ` Null let on_bool ctx b = Context . add ctx ( ` Bool b ) let on_int ctx i = Context . add ctx ( ` Int i ) let on_float ctx f = Context . add ctx ( ` Float f ) let on_string ctx buf offset len = let str = String . sub buf ~ pos : offset ~ len : len in match String . length str with | 0 | 1 -> Context . add ctx ( ` String str ) | _ -> decode_string str ctx ( str . [ 0 ] , str . [ 1 ] ) module JSON = struct let callbacks = { YAJL . on_null = on_null ; on_bool = on_bool ; on_number = ` Parse_numbers ( ( ` Int64 on_int ) , on_float ) ; on_string = on_string ; on_start_map = Context . push_map ; on_map_key = on_string ; on_end_map = Context . pop_map ; on_start_array = Context . push_array ; on_end_array = Context . pop_array ; } let from_string str = let p = YAJL . make_parser callbacks Context . empty in let ( ) = YAJL . parse p str in YAJL . complete_parse p |> Context . result end end
module Writer = struct exception Todo module Cache = struct type t = { count : int ; cache : int String . Map . t } let empty = { count = 0 ; cache = String . Map . empty } let find { cache ; _ } = String . Map . find cache let track { cache ; count } key = if String . length key > 3 then if count > CacheCode . max_count then empty else { count = count + 1 ; cache = String . Map . add cache ~ key ~ data : count } else { cache ; count } end module CtxBase = struct type ' a t = ( Cache . t * YAJL . gen -> ' a * Cache . t * YAJL . gen ) let runState f init = f init let return x = fun ( c , g ) -> ( x , c , g ) let bind act1 fact2 s = let ( iv , ic , ig ) = runState act1 s in let act2 = fact2 iv in runState act2 ( ic , ig ) let map = ` Define_using_bind end module Ctx = struct include Monad . Make ( CtxBase ) let runState f init = f init let get_gen ( c , g ) = ( g , c , g ) let get_cache ( c , g ) = ( c , c , g ) let put_cache c ' ( _c , g ) = ( ( ) , c ' , g ) end let int_53_bit_upper = Int64 . of_int 9007199254740992 let int_53_bit_lower = Int64 . of_int ( - 9007199254740992 ) let to_string t = let open Ctx . Monad_infix in let ( ) >> f1 f2 = f1 >>= ( fun ( ) -> f2 ) in let string x = Ctx . get_gen >>= ( fun gen -> YAJL . gen_string gen x ; Ctx . return ( ) ) in let int i = Ctx . get_gen >>= ( fun gen -> YAJL . gen_int64 gen i ; Ctx . return ( ) ) in let null = Ctx . get_gen >>= ( fun gen -> YAJL . gen_null gen ; Ctx . return ( ) ) in let bool b = Ctx . get_gen >>= ( fun gen -> YAJL . gen_bool gen b ; Ctx . return ( ) ) in let float f = Ctx . get_gen >>= ( fun gen -> YAJL . gen_float gen f ; Ctx . return ( ) ) in let start_array = Ctx . get_gen >>= ( fun gen -> Ctx . return ( YAJL . gen_start_array gen ) ) in let end_array = Ctx . get_gen >>= ( fun gen -> Ctx . return ( YAJL . gen_end_array gen ) ) in let track str = Ctx . get_cache >>= ( fun c -> match Cache . find c str with | None -> let c ' = Cache . track c str in Ctx . put_cache c ' >> string str | Some i -> string ( CacheCode . of_int i ) ) in let is_composite_map m = let keys = Map . Poly . keys m in let composite_key = function | ` Map _ -> true | ` Array _ -> true | ` Set _ -> true | ` List _ -> true | _ -> false in List . exists keys ~ f : composite_key in let rec array_tagged tag x = start_array >> track tag >> write_json x ~ string_key : false >> end_array and write_map m = let f ( key , data ) = write_json key ~ string_key : true >> write_json data ~ string_key : false in let l = Map . Poly . to_alist m in if is_composite_map m then begin start_array >> string " ~# cmap " >> start_array >> Ctx . all_ignore ( List . map l ~ f ) >> end_array >> end_array end else begin start_array >> string " ^ " >> Ctx . all_ignore ( List . map l ~ f ) >> end_array end and write_json x ~ string_key = let string = if string_key then track else string in match x with | ` Null -> null | ` Bool b -> bool b | ` String " " -> string " " | ` String s -> let str = match s . [ 0 ] with | ' ' ~ -> " " ~ ^ s | ' ' ^ -> " " ~ ^ s | _ -> s in if string_key then track str else string str | ` Int i -> if string_key then track ( " ~ i " ^ Int64 . to_string i ) else if i < int_53_bit_upper && i > int_53_bit_lower then int i else string ( " ~ i " ^ Int64 . to_string i ) | ` BigInt n -> string ( " ~ n " ^ Big_int . string_of_big_int n ) | ` Keyword k -> track ( " " ~: ^ k ) | ` Symbol symb -> track ( " " ~$ ^ symb ) | ` UUID uuid -> string ( " ~ u " ^ Uuid . to_string uuid ) | ` URI s -> string ( " ~ r " ^ s ) | ` Time t -> let i = ( Time . to_float t ) . * 1000 . 0 |> Float . to_int64 in string ( " ~ m " ^ Int64 . to_string i ) | ` Float f -> if string_key then track ( " ~ d " ^ Float . to_string f ) else float f | ` Array ts -> begin start_array >> Ctx . all_ignore ( List . map ts ~ f ( : fun x -> write_json x ~ string_key : false ) ) >> end_array end | ` List ts -> array_tagged " ~# list " ( ` Array ts ) | ` Set s -> array_tagged " ~# set " ( ` Array ( Set . Poly . to_list s ) ) | ` Map m -> write_map m | ` Extension ( tag , x ) -> start_array >> string ( " " ~# ^ tag ) >> write_json x ~ string_key : string_key >> end_array | _ -> raise Todo in let quote x = start_array >> string " ' " ~# >> write_json x ~ string_key : false >> end_array in let write_json_toplevel = function | ` Null -> quote ` Null | ` Bool b -> quote ( ` Bool b ) | ` String s -> quote ( ` String s ) | ` Float f -> quote ( ` Float f ) | ` Int i -> quote ( ` Int i ) | ` Time t -> quote ( ` Time t ) | ` Keyword kw -> quote ( ` Keyword kw ) | ` Symbol symb -> quote ( ` Symbol symb ) | ` URI u -> quote ( ` URI u ) | ` UUID uuid -> quote ( ` UUID uuid ) | x -> write_json x ~ string_key : false in let write x = let gen = YAJL . make_gen ( ) in let ( ( ) , _ , _ ) = Ctx . runState ( write_json_toplevel x ) ( Cache . empty , gen ) in let ( buf , pos , len ) = YAJL . gen_get_buf gen in let res = String . sub buf ~ pos ~ len in YAJL . gen_clear gen ; res in write t end
module type Inputs_intf = sig module Transition_frontier : module type of Transition_frontier end
module Make ( Inputs : Inputs_intf ) Inputs_intf : Mina_intf . Transition_chain_prover_intf with type transition_frontier := Inputs . Transition_frontier . t = struct open Inputs let find_in_root_history frontier state_hash = let open Transition_frontier . Extensions in let open Option . Let_syntax in let root_history = get_extension ( Transition_frontier . extensions frontier ) frontier Root_history in let % map root_data = Root_history . lookup root_history state_hash in External_transition . Validated . lower @@ Frontier_base . Root_data . Historical . transition root_data module Merkle_list = Merkle_list_prover . Make_ident ( struct type value = Mina_block . Validated . t type context = Transition_frontier . t type proof_elem = State_body_hash . t let to_proof_elem = Mina_block . Validated . state_body_hash let get_previous ~ context transition = let parent_hash = transition |> Mina_block . Validated . forget |> With_hash . data |> Mina_block . header |> Mina_block . Header . protocol_state |> Protocol_state . previous_state_hash in let open Option . Let_syntax in Option . merge Transition_frontier ( . find context parent_hash >>| Breadcrumb . validated_transition ) validated_transition ( find_in_root_history context parent_hash ) parent_hash ~ f : Fn . const end ) end let prove ? length ~ frontier state_hash = let open Option . Let_syntax in let % map requested_transition = Option . merge Transition_frontier ( . find frontier state_hash >>| Breadcrumb . validated_transition ) validated_transition ( find_in_root_history frontier state_hash ) state_hash ~ f : Fn . const in let first_transition , merkle_list = Merkle_list . prove ? length ~ context : frontier requested_transition in ( Mina_block . Validated . state_hash first_transition , merkle_list ) merkle_list end module Transition_frontier = Transition_frontier end ) end
let global_max_length ( genesis_constants : Genesis_constants . t ) t = genesis_constants . protocol . k
let rejected_blocks = Queue . create ( )
let validated_blocks = Queue . create ( )
type t = { logger : Logger . t ; verifier : Verifier . t ; consensus_local_state : Consensus . Data . Local_state . t ; catchup_tree : Catchup_tree . t ; full_frontier : Full_frontier . t ; persistent_root : Persistent_root . t ; persistent_root_instance : Persistent_root . Instance . t ; persistent_frontier : Persistent_frontier . t ; persistent_frontier_instance : Persistent_frontier . Instance . t ; extensions : Extensions . t ; genesis_state_hash : State_hash . t ; closed : unit Ivar . t }
let catchup_tree t = t . catchup_tree
type Structured_log_events . t += Added_breadcrumb_user_commands [ @@ deriving register_event ] register_event
type Structured_log_events . t += Applying_diffs of { diffs : Yojson . Safe . t list } [ @@ deriving register_event { msg = " Applying diffs : $ diffs " } ]
let genesis_root_data ~ precomputed_values = let transition = External_transition . Validated . lift @@ Mina_block . Validated . lift @@ Mina_block . genesis ~ precomputed_values in let constraint_constants = precomputed_values . constraint_constants in let scan_state = Staged_ledger . Scan_state . empty ~ constraint_constants ( ) in let protocol_states = [ ] in let pending_coinbase = Or_error . ok_exn ( Pending_coinbase . create ~ depth : constraint_constants . pending_coinbase_depth ( ) ) in Root_data . Limited . create ~ transition ~ scan_state ~ pending_coinbase ~ protocol_states
let load_from_persistence_and_start ~ logger ~ verifier ~ consensus_local_state ~ max_length ~ persistent_root ~ persistent_root_instance ~ persistent_frontier ~ persistent_frontier_instance ~ precomputed_values ~ catchup_mode ignore_consensus_local_state = let open Deferred . Result . Let_syntax in let root_identifier = match Persistent_root . Instance . load_root_identifier persistent_root_instance with | Some root_identifier -> root_identifier | None -> failwith " no persistent root identifier found ( should have been written \ already ) already " in let % bind ( ) = Deferred . return ( match Persistent_frontier . Instance . fast_forward persistent_frontier_instance root_identifier with | Ok ( ) -> [ % log info ] info " Fast forward successful " ; Ok ( ) | Error ` Sync_cannot_be_running -> Error ( ` Failure " sync job is already running on persistent frontier ) " | Error ` Bootstrap_required -> Error ` Bootstrap_required | Error ( ` Failure msg ) msg -> [ % log fatal ] fatal ~ metadata : [ ( " target_root " , Root_identifier . to_yojson root_identifier ) root_identifier ] " Unable to fast forward persistent frontier : % s " msg ; Error ( ` Failure msg ) msg ) in let % bind full_frontier , extensions = Deferred . map ( Persistent_frontier . Instance . load_full_frontier persistent_frontier_instance ~ max_length ~ root_ledger : ( Persistent_root . Instance . snarked_ledger persistent_root_instance ) persistent_root_instance ~ consensus_local_state ~ ignore_consensus_local_state ~ precomputed_values ~ persistent_root_instance ) ~ f : ( Result . map_error ~ f ( : function | ` Sync_cannot_be_running -> ` Failure " sync job is already running on persistent frontier " | ` Failure _ as err -> err ) ) in [ % log info ] info " Loaded full frontier and extensions " ; let % map ( ) = Deferred . return ( Persistent_frontier . Instance . start_sync ~ constraint_constants : precomputed_values . constraint_constants ~ persistent_root_instance persistent_frontier_instance |> Result . map_error ~ f ( : function | ` Sync_cannot_be_running -> ` Failure " sync job is already running on persistent frontier " | ` Not_found _ as err -> ` Failure ( Persistent_frontier . Database . Error . not_found_message err ) err ) ) in { logger ; catchup_tree = Catchup_tree . create catchup_mode ~ root ( : Full_frontier . root full_frontier ) full_frontier ; verifier ; consensus_local_state ; full_frontier ; persistent_root ; persistent_root_instance ; persistent_frontier ; persistent_frontier_instance ; extensions ; closed = Ivar . create ( ) ; genesis_state_hash = ( Precomputed_values . genesis_state_hashes precomputed_values ) precomputed_values . state_hash }
let rec load_with_max_length : max_length : int -> ? retry_with_fresh_db : bool -> logger : Logger . t -> verifier : Verifier . t -> consensus_local_state : Consensus . Data . Local_state . t -> persistent_root : Persistent_root . t -> persistent_frontier : Persistent_frontier . t -> precomputed_values : Precomputed_values . t -> catchup_mode [ : ` Normal | ` Super ] -> unit -> ( t , [ > ` Bootstrap_required | ` Persistent_frontier_malformed | ` Failure of string ] ) Deferred . Result . t = fun ~ max_length ( ? retry_with_fresh_db = true ) true ~ logger ~ verifier ~ consensus_local_state ~ persistent_root ~ persistent_frontier ~ precomputed_values ~ catchup_mode ( ) -> let open Deferred . Let_syntax in let continue persistent_frontier_instance ~ ignore_consensus_local_state ~ snarked_ledger_hash = match Persistent_root . load_from_disk_exn persistent_root ~ snarked_ledger_hash ~ logger with | Error _ as err -> let % map ( ) = Persistent_frontier . Instance . destroy persistent_frontier_instance in err | Ok persistent_root_instance -> ( match % bind load_from_persistence_and_start ~ logger ~ verifier ~ consensus_local_state ~ max_length ~ persistent_root ~ persistent_root_instance ~ catchup_mode ~ persistent_frontier ~ persistent_frontier_instance ~ precomputed_values ignore_consensus_local_state with | Ok _ as result -> return result | Error _ as err -> let % map ( ) = Persistent_frontier . Instance . destroy persistent_frontier_instance in Persistent_root . Instance . close persistent_root_instance ; err ) in let persistent_frontier_instance = Persistent_frontier . create_instance_exn persistent_frontier in let reset_and_continue ( ? destroy_frontier_instance = true ) true ( ) = let % bind ( ) = if destroy_frontier_instance then Persistent_frontier . Instance . destroy persistent_frontier_instance else return ( ) in let % bind ( ) = Persistent_frontier . reset_database_exn persistent_frontier ~ root_data ( : genesis_root_data ~ precomputed_values ) precomputed_values ~ genesis_state_hash : ( State_hash . With_state_hashes . state_hash precomputed_values . protocol_state_with_hashes ) in Persistent_root . reset_to_genesis_exn persistent_root ~ precomputed_values ; let genesis_ledger_hash = Precomputed_values . genesis_ledger precomputed_values |> Lazy . force |> Ledger . merkle_root |> Frozen_ledger_hash . of_ledger_hash in continue ( Persistent_frontier . create_instance_exn persistent_frontier ) persistent_frontier ~ ignore_consensus_local_state : false ~ snarked_ledger_hash : genesis_ledger_hash in match Persistent_frontier . Instance . check_database ~ genesis_state_hash : ( State_hash . With_state_hashes . state_hash precomputed_values . protocol_state_with_hashes ) persistent_frontier_instance with | Error ` Not_initialized -> [ % log info ] info " persistent frontier database does not exist " ; reset_and_continue ( ) | Error ` Invalid_version -> [ % log info ] info " persistent frontier database out of date " ; reset_and_continue ( ) | Error ( ` Genesis_state_mismatch persisted_genesis_state_hash ) persisted_genesis_state_hash -> [ % log info ] info " Genesis state in persisted frontier $ persisted_state_hash differs \ from the current genesis state $ precomputed_state_hash " ~ metadata : [ ( " persisted_state_hash " , State_hash . to_yojson persisted_genesis_state_hash ) ; ( " precomputed_state_hash " , State_hash . to_yojson ( State_hash . With_state_hashes . state_hash precomputed_values . protocol_state_with_hashes ) ) ] ; reset_and_continue ( ) | Error ( ` Corrupt err ) err -> [ % log error ] error " Persistent frontier database is corrupt : % s " ( Persistent_frontier . Database . Error . message err ) err ; if retry_with_fresh_db then ( [ % log info ] info " destroying old persistent frontier database " ; let % bind ( ) = Persistent_frontier . Instance . destroy persistent_frontier_instance in let % bind ( ) = Persistent_frontier . destroy_database_exn persistent_frontier in load_with_max_length ~ max_length ~ logger ~ verifier ~ consensus_local_state ~ persistent_root ~ persistent_frontier ~ retry_with_fresh_db : false ~ precomputed_values ~ catchup_mode ( ) >>| Result . map_error ~ f ( : function | ` Persistent_frontier_malformed -> ` Failure " failed to destroy and create new persistent frontier \ database " | err -> err ) ) else return ( Error ` Persistent_frontier_malformed ) Persistent_frontier_malformed | Ok snarked_ledger_hash -> ( match % bind continue persistent_frontier_instance ~ ignore_consensus_local_state : true ~ snarked_ledger_hash with | Error ( ` Failure err ) err when retry_with_fresh_db -> [ % log error ] error " Failed to initialize transition frontier : $ err . Destroying old \ persistent frontier database and retrying . " ~ metadata [ : ( " err " , ` String err ) err ] ; reset_and_continue ~ destroy_frontier_instance : false ( ) | res -> return res )
let load ( ? retry_with_fresh_db = true ) true ~ logger ~ verifier ~ consensus_local_state ~ persistent_root ~ persistent_frontier ~ precomputed_values ~ catchup_mode ( ) = let max_length = global_max_length ( Precomputed_values . genesis_constants precomputed_values ) precomputed_values in load_with_max_length ~ max_length ~ retry_with_fresh_db ~ logger ~ verifier ~ consensus_local_state ~ persistent_root ~ persistent_frontier ~ precomputed_values ~ catchup_mode ( )
let close ~ loc { logger ; verifier = _ ; consensus_local_state = _ ; catchup_tree = _ ; full_frontier ; persistent_root = _safe_to_ignore_1 ; persistent_root_instance ; persistent_frontier = _safe_to_ignore_2 ; persistent_frontier_instance ; extensions ; closed ; genesis_state_hash = _ } = [ % log debug ] debug " Closing transition frontier " ; Full_frontier . close ~ loc full_frontier ; Extensions . close extensions ; let % map ( ) = Persistent_frontier . Instance . destroy persistent_frontier_instance in Persistent_root . Instance . close persistent_root_instance ; Ivar . fill_if_empty closed ( )
let closed t = Ivar . read t . closed
let persistent_root { persistent_root ; _ } = persistent_root
let persistent_frontier { persistent_frontier ; _ } = persistent_frontier
let extensions { extensions ; _ } = extensions
let genesis_state_hash { genesis_state_hash ; _ } = genesis_state_hash
let root_snarked_ledger { persistent_root_instance ; _ } = Persistent_root . Instance . snarked_ledger persistent_root_instance