text
stringlengths 12
786k
|
---|
let upgrades_encoding = let open Data_encoding in def " user_activated . upgrades " ~ title " : User activated upgrades " ~ description : " User activated upgrades : at given level , switch to given protocol . " ( list ( obj2 ( req " level " int32 ) ( req " replacement_protocol " Protocol_hash . encoding ) ) ) |
type protocol_overrides = ( Protocol_hash . t * Protocol_hash . t ) list |
let protocol_overrides_encoding = let open Data_encoding in def " user_activated . protocol_overrides " ~ title " : User activated protocol overrides " ~ description : " User activated protocol overrides : activate a protocol instead of \ another . " @@ list ( obj2 ( req " replaced_protocol " Protocol_hash . encoding ) ( req " replacement_protocol " Protocol_hash . encoding ) ) |
let ( ) = Data_encoding . Registration . register upgrades_encoding ; Data_encoding . Registration . register protocol_overrides_encoding |
let test_metadata_consistency ~ migrate_from ~ migrate_to = Test . register ~ __FILE__ ~ title " : metadata consistency " ~ tags [ " : rpc " ; " metadata " ; " migration " ] @@ fun ( ) -> let node = Node . create [ ] in let * ( ) = Node . config_init node [ ] in let migration_level = 3 in Node . Config_file . ( update node ( set_sandbox_network_with_user_activated_upgrades [ ( migration_level , migrate_to ) ] ) ) ; let * ( ) = Node . run node [ ] in let * ( ) = Node . wait_for_ready node in let * client = Client . ( init ~ endpoint ( : Node node ) ( ) ) in let * ( ) = Client . activate_protocol ~ protocol : migrate_from client in let * ( ) = repeat ( migration_level - 1 ) ( fun ( ) -> Client . bake_for client ) in let * non_migration_block = RPC . get_block_metadata ~ block ( : string_of_int ( migration_level - 1 ) ) client in let protocol = JSON . ( non_migration_block |-> " protocol " |> as_string ) in Log . info " checking consistency of block at level % d " ( migration_level - 1 ) ; Check . ( ( protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected protocol = % R , got % L " ) ; let next_protocol = JSON . ( non_migration_block |-> " next_protocol " |> as_string ) in Check . ( ( next_protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected next_protocol = % R , got % L " ) ; Log . info " checking consistency of block at level % d " migration_level ; let * migration_block = RPC . get_block_metadata ~ block ( : string_of_int migration_level ) client in let protocol = JSON . ( migration_block |-> " protocol " |> as_string ) in Check . ( ( protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected protocol = % R , got % L " ) ; let next_protocol = JSON . ( migration_block |-> " next_protocol " |> as_string ) in Check . ( ( next_protocol = Protocol . hash migrate_to ) string ~ error_msg " : expected next_protocol = % R , got % L " ) ; Log . info " checking consistency of block at level % d ( again ) " ( migration_level - 1 ) ; let * non_migration_block = RPC . get_block_metadata ~ block ( : string_of_int ( migration_level - 1 ) ) client in let protocol = JSON . ( non_migration_block |-> " protocol " |> as_string ) in Check . ( ( protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected protocol = % R , got % L " ) ; let next_protocol = JSON . ( non_migration_block |-> " next_protocol " |> as_string ) in Check . ( ( next_protocol = Protocol . hash migrate_from ) string ~ error_msg " : expected next_protocol = % R , got % L " ) ; unit |
let register ~ migrate_from ~ migrate_to = test_metadata_consistency ~ migrate_from ~ migrate_to |
type t = { ua_family : string ; ua_major : string option ; ua_minor : string option ; ua_patch : string option ; os_family : string ; os_major : string option ; os_minor : string option ; os_patch : string option ; os_patch_minor : string option ; device_family : string ; device_brand : string option ; device_model : string option ; } |
let uaparser = User_agent_parser . init ( ) |
let parse s = let parsed = User_agent_parser . parse uaparser s in let open User_agent_parser in let open User_agent_parser . UAParser in let open User_agent_parser . OSParser in let open User_agent_parser . DeviceParser in { ua_family = parsed . ua . family ; ua_major = parsed . ua . major ; ua_minor = parsed . ua . minor ; ua_patch = parsed . ua . patch ; os_family = parsed . os . family ; os_major = parsed . os . major ; os_minor = parsed . os . minor ; os_patch = parsed . os . patch ; os_patch_minor = parsed . os . patch_minor ; device_family = parsed . device . family ; device_brand = parsed . device . brand ; device_model = parsed . device . model ; } |
let is_bot t = let is_google_bot ( ) = let regex = Str . regexp " Googlebot ( \\- Mobile \\|- Image \\|- Video \\|- News ) \\?\\| Feedfetcher - Google \\| Google - Test \\| Google - Site - Verification \\| Google \ Web \ Preview \\| AdsBot - Google ( \\- Mobile ) \\?\\| Mediapartners - Google \\| Google . */\\+/ web / snippet \\| GoogleProducer " in Str . string_match regex t . ua_family 0 in let is_generic_bot ( ) = let regex = Str . regexp [ " a - z0 - 9 \\- _ ] _ ( *\\ bot \\| crawler \\| archiver \\| transcoder \\| spider ) " \\ in Str . string_match regex t . ua_family 0 in if is_google_bot ( ) then true else if is_generic_bot ( ) then true else false |
module Poly = struct [ %% versioned module Stable = struct module V2 = struct type ( ' u , ' s ) ' s t = Signed_command of ' u | Parties of ' s [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest = Fn . id end module V1 = struct type ( ' u , ' s ) ' s t = Signed_command of ' u | Snapp_command of ' s [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest : _ t -> _ V2 . t = function | Signed_command x -> Signed_command x | Snapp_command _ -> failwith " Snapp_command " end end ] end end |
type ( ' u , ' s ) ' s t_ = ( ' u , ' s ) ' s Poly . Stable . Latest . t = | Signed_command of ' u | Parties of ' s |
module Gen_make ( C : Signed_command_intf . Gen_intf ) Gen_intf = struct let to_signed_command f = Quickcheck . Generator . map f ~ f ( : fun c -> Signed_command c ) c open C . Gen let payment ? sign_type ~ key_gen ? nonce ~ max_amount ~ fee_range ( ) = to_signed_command ( payment ? sign_type ~ key_gen ? nonce ~ max_amount ~ fee_range ( ) ) let payment_with_random_participants ? sign_type ~ keys ? nonce ~ max_amount ~ fee_range ( ) = to_signed_command ( payment_with_random_participants ? sign_type ~ keys ? nonce ~ max_amount ~ fee_range ( ) ) let stake_delegation ~ key_gen ? nonce ~ fee_range ( ) = to_signed_command ( stake_delegation ~ key_gen ? nonce ~ fee_range ( ) ) let stake_delegation_with_random_participants ~ keys ? nonce ~ fee_range ( ) = to_signed_command ( stake_delegation_with_random_participants ~ keys ? nonce ~ fee_range ( ) ) let sequence ? length ? sign_type a = Quickcheck . Generator . map ( sequence ? length ? sign_type a ) a ~ f ( : List . map ~ f ( : fun c -> Signed_command c ) c ) c end |
module Gen = Gen_make ( Signed_command ) Signed_command |
module Valid = struct [ %% versioned module Stable = struct module V2 = struct type t = ( Signed_command . With_valid_signature . Stable . V2 . t , Parties . Valid . Stable . V1 . t ) Poly . Stable . V2 . t [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest = Fn . id end end ] end module Gen = Gen_make ( Signed_command . With_valid_signature ) With_valid_signature end [ %% versioned |
module Stable = struct module V2 = struct type t = ( Signed_command . Stable . V2 . t , Parties . Stable . V1 . t ) t Poly . Stable . V2 . t [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest = Fn . id end end ] end |
module Zero_one_or_two = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = [ ` Zero | ` One of ' a | ` Two of ' a * ' a ] [ @@ deriving sexp , compare , equal , hash , yojson ] yojson end end ] end end |
module Verifiable = struct [ %% versioned module Stable = struct module V2 = struct type t = ( Signed_command . Stable . V2 . t , Parties . Verifiable . Stable . V1 . t ) Poly . Stable . V2 . t [ @@ deriving sexp , compare , equal , hash , yojson ] yojson let to_latest = Fn . id end end ] end let fee_payer ( t : t ) t = match t with | Signed_command x -> Signed_command . fee_payer x | Parties p -> Party . Fee_payer . account_id p . fee_payer end |
let to_verifiable ( t : t ) t ~ ledger ~ get ~ location_of_account : Verifiable . t = let find_vk ( p : Party . t ) t = let ( ! ) x = Option . value_exn x in let id = Party . account_id p in Option . try_with ( fun ( ) -> let account : Account . t = ( ! get ledger ( ! location_of_account ledger id ) id ) id in ( ( !! account . zkapp ) zkapp . verification_key ) verification_key . data ) in match t with | Signed_command c -> Signed_command c | Parties { fee_payer ; other_parties ; memo } -> Parties { fee_payer ; other_parties = other_parties |> Parties . Call_forest . map ~ f ( : fun party -> ( party , find_vk party ) party ) party ; memo } |
let of_verifiable ( t : Verifiable . t ) t : t = match t with | Signed_command x -> Signed_command x | Parties p -> Parties ( Parties . of_verifiable p ) p |
let fee : t -> Currency . Fee . t = function | Signed_command x -> Signed_command . fee x | Parties p -> Parties . fee p |
let has_insufficient_fee t = Currency . Fee ( . fee t < minimum_fee ) minimum_fee |
let accounts_accessed ( t : t ) t = match t with | Signed_command x -> Signed_command . accounts_accessed x | Parties ps -> Parties . accounts_accessed ps |
let to_base58_check ( t : t ) t = match t with | Signed_command x -> Signed_command . to_base58_check x | Parties ps -> Parties . to_base58_check ps |
let fee_payer ( t : t ) t = match t with | Signed_command x -> Signed_command . fee_payer x | Parties p -> Parties . fee_payer p |
let nonce_exn ( t : t ) t = match t with | Signed_command x -> Signed_command . nonce x | Parties p -> Parties . nonce p |
let check ( t : t ) t : Valid . t option = match t with | Signed_command x -> Option . map ( Signed_command . check x ) x ~ f ( : fun c -> Signed_command c ) c | Parties p -> Some ( Parties ( p :> Parties . Valid . t ) t ) t |
let fee_token ( t : t ) t = match t with | Signed_command x -> Signed_command . fee_token x | Parties x -> Parties . fee_token x |
let valid_until ( t : t ) t = match t with | Signed_command x -> Signed_command . valid_until x | Parties _ -> Mina_numbers . Global_slot . max_value |
let forget_check ( t : Valid . t ) t : t = ( t :> t ) t |
let to_valid_unsafe ( t : t ) t = ` If_this_is_used_it_should_have_a_comment_justifying_it ( match t with | Parties x -> Parties x | Signed_command x -> let ( ` If_this_is_used_it_should_have_a_comment_justifying_it x ) x = Signed_command . to_valid_unsafe x in Signed_command x ) |
let filter_by_participant ( commands : t list ) list public_key = List . filter commands ~ f ( : fun user_command -> Core_kernel . List . exists ( accounts_accessed user_command ) user_command ~ f : ( Fn . compose ( Signature_lib . Public_key . Compressed . equal public_key ) public_key Account_id . public_key ) ) |
let weight : Stable . Latest . t -> int = function | Signed_command signed_command -> Signed_command . payload signed_command |> Signed_command_payload . weight | Parties parties -> Parties . weight parties |
let fee_per_wu ( user_command : Stable . Latest . t ) t : Currency . Fee_rate . t = Currency . Fee_rate . make_exn ( fee user_command ) user_command ( weight user_command ) user_command |
module Query_first_seen = [ % graphql { | query query ( $ hashes : [ String ] ) !! { user_commands ( user_commandswhere : { hash : { _in : $ hashes } hashes } hashes ) { hash @ bsDecoder ( bsDecoderfn : " Transaction_hash . of_base58_check_exn ) " first_seen @ bsDecoder ( bsDecoderfn : " Base_types . deserialize_optional_block_time ) " } } } ] | |
module Query_participants = [ % graphql { | query query ( $ hashes : [ String ] ) !! { user_commands ( user_commandswhere : { hash : { _in : $ hashes } hashes } hashes ) { receiver { id value @ bsDecoder ( fn : " Public_key . Compressed . of_base58_check_exn ) " } sender { id value @ bsDecoder ( fn : " Public_key . Compressed . of_base58_check_exn ) " } } } } ] | |
module Query = [ % graphql { | query query ( $ hash : String ) ! { user_commands ( user_commandswhere : { hash : { _eq : $ hash } hash } hash ) { fee @ bsDecoder ( fn : " Base_types . Fee . deserialize ) " hash @ bsDecoder ( bsDecoderfn : " Transaction_hash . of_base58_check_exn ) " memo @ bsDecoder ( bsDecoderfn : " Signed_command_memo . of_base58_check_exn ) " nonce @ bsDecoder ( fn : " Base_types . Nonce . deserialize ) " sender { value @ bsDecoder ( fn : " Public_key . Compressed . of_base58_check_exn ) " } receiver { value @ bsDecoder ( fn : " Public_key . Compressed . of_base58_check_exn ) " } typ @ bsDecoder ( fn : " Base_types . User_command_type . decode ) " amount @ bsDecoder ( fn : " Base_types . Amount . deserialize ) " first_seen @ bsDecoder ( bsDecoderfn : " Base_types . deserialize_optional_block_time ) " } } } ] | |
module Insert = [ % graphql { | mutation insert ( $ user_commands : [ user_commands_insert_input ] ) !! { insert_user_commands ( insert_user_commandsobjects : $ user_commands , on_conflict : { constraint : user_commands_hash_key , update_columns : first_seen } first_seen ) { returning { hash @ bsDecoder ( bsDecoderfn : " Transaction_hash . of_base58_check_exn ) " first_seen @ bsDecoder ( bsDecoderfn : " Base_types . deserialize_optional_block_time ) " } } } } ] | |
let parties_with_ledger ( ) = let open Quickcheck . Let_syntax in let open Signature_lib in let num_keypairs = ( Parties_generators . max_other_parties * 2 ) 2 + 2 in let keypairs = List . init num_keypairs ~ f ( : fun _ -> Keypair . create ( ) ) in let keymap = List . fold keypairs ~ init : Public_key . Compressed . Map . empty ~ f ( : fun map { public_key ; private_key } -> let key = Public_key . compress public_key in Public_key . Compressed . Map . add_exn map ~ key ~ data : private_key ) in let num_keypairs_in_ledger = Parties_generators . max_other_parties + 1 in let keypairs_in_ledger = List . take keypairs num_keypairs_in_ledger in let account_ids = List . map keypairs_in_ledger ~ f ( : fun { public_key ; _ } -> Account_id . create ( Public_key . compress public_key ) public_key Token_id . default ) in let % bind balances = let min_cmd_fee = Mina_compile_config . minimum_user_command_fee in let min_balance = Currency . Fee . to_int min_cmd_fee |> Int ( . + ) 500_000_000_000 |> Currency . Balance . of_int in let max_balance = match Currency . Balance . add_amount min_balance ( Currency . Amount . of_int 20_000_000_000_000 ) 20_000_000_000_000 with | None -> failwith " parties_with_ledger : overflow for max_balance " | Some bal -> bal in Quickcheck . Generator . list_with_length num_keypairs_in_ledger ( Currency . Balance . gen_incl min_balance max_balance ) max_balance in let account_ids_and_balances = List . zip_exn account_ids balances in let snappify_account ( account : Account . t ) t : Account . t = let permissions = { Permissions . user_default with edit_state = Permissions . Auth_required . Either ; send = Either ; set_delegate = Either ; set_permissions = Either ; set_verification_key = Either ; set_zkapp_uri = Either ; edit_sequence_state = Either ; set_token_symbol = Either ; increment_nonce = Either ; set_voting_for = Either } in let verification_key = Some With_hash . { data = Side_loaded_verification_key . dummy ; hash = Zkapp_account . dummy_vk_hash ( ) } in let zkapp = Some { Zkapp_account . default with verification_key } in { account with permissions ; zkapp } in let accounts = List . mapi account_ids_and_balances ~ f ( : fun ndx ( account_id , balance ) balance -> let account = Account . create account_id balance in if ndx mod 2 = 0 then account else snappify_account account ) in let fee_payer_keypair = List . hd_exn keypairs in let ledger = Ledger . create ~ depth : ledger_depth ( ) in List . iter2_exn account_ids accounts ~ f ( : fun acct_id acct -> match Ledger . get_or_create_account ledger acct_id acct with | Error err -> failwithf " parties : error adding account for account id : % s , error : % s . " @ ( Account_id . to_yojson acct_id |> Yojson . Safe . to_string ) to_string ( Error . to_string_hum err ) err ( ) | Ok ( ` Existed , _ ) _ -> failwithf " parties : account for account id already exists : % s . " @ ( Account_id . to_yojson acct_id |> Yojson . Safe . to_string ) to_string ( ) | Ok ( ` Added , _ ) _ -> ( ) ) ; let % bind parties = Parties_generators . gen_parties_from ~ fee_payer_keypair ~ keymap ~ ledger ( ) in return ( User_command . Parties parties , fee_payer_keypair , keymap , ledger ) ledger |
let sequence_parties_with_ledger ? length ( ) = let open Quickcheck . Let_syntax in let % bind length = match length with | Some n -> return n | None -> Quickcheck . Generator . small_non_negative_int in let merge_ledger source_ledger target_ledger = Ledger . iteri source_ledger ~ f ( : fun _ndx acct -> let acct_id = Account_id . create acct . public_key acct . token_id in match Ledger . get_or_create_account target_ledger acct_id acct with | Ok ( ` Added , _ ) _ -> ( ) | Ok ( ` Existed , _ ) _ -> failwith " Account already existed in target ledger " | Error err -> failwithf " Could not add account to target ledger : % s " ( Error . to_string_hum err ) err ( ) ) in let init_ledger = Ledger . create ~ depth : ledger_depth ( ) in let rec go parties_and_fee_payer_keypairs n = if n <= 0 then return ( List . rev parties_and_fee_payer_keypairs , init_ledger ) init_ledger else let % bind parties , fee_payer_keypair , keymap , ledger = parties_with_ledger ( ) in let parties_and_fee_payer_keypairs ' = ( parties , fee_payer_keypair , keymap ) keymap :: parties_and_fee_payer_keypairs in merge_ledger ledger init_ledger ; go parties_and_fee_payer_keypairs ' ( n - 1 ) 1 in go [ ] length |
let pk_to_public_key ~ context ( ` Pk pk ) pk = Public_key . Compressed . of_base58_check pk |> Result . map_error ~ f ( : fun _ -> Errors . create ~ context ` Public_key_format_not_valid ) |
let account_id ( ` Pk pk ) pk ( ` Token_id token_id ) token_id = { Account_identifier . address = pk ; sub_account = None ; metadata = Some ( Amount_of . Token_id . encode token_id ) token_id } |
let token_id_of_account ( account : Account_identifier . t ) t = let module Decoder = Amount_of . Token_id . T ( Result ) Result in Decoder . decode account . metadata |> Result . map ~ f ( : Option . value ~ default : Amount_of . Token_id . default ) default |> Result . ok |
module Op = struct type ' a t = { label : ' a ; related_to : ' a option } [ @@ deriving equal ] equal module T ( M : Monad . S2 ) S2 = struct let build ~ a_eq ~ plan ~ f = let open M . Let_syntax in let % map _ , rev_data = List . fold plan ~ init ( : M . return ( 0 , [ ] ) ) ~ f ( : fun macc op -> let open M . Let_syntax in let % bind i , acc = macc in let operation_identifier i = { Operation_identifier . index = Int64 . of_int_exn i ; network_index = None } in let related_operations = op . related_to |> Option . bind ~ f ( : fun relate -> List . findi plan ~ f ( : fun _ a -> a_eq relate a . label ) label ) |> Option . map ~ f ( : fun ( i , _ ) _ -> [ operation_identifier i ] ) in let % map a = f ~ related_operations ~ operation_identifier ( : operation_identifier i ) i op in ( i + 1 , a :: acc ) acc ) in List . rev rev_data end module Ident2 = struct type ( ' a , ' e ) ' e t = ' a module T = struct type ( ' a , ' e ) ' e t = ' a let map = ` Define_using_bind let return a = a let bind a ~ f = f a end include Monad . Make2 ( T ) T end include T ( Ident2 ) Ident2 end |
module Kind = struct type t = [ ` Payment | ` Delegation ] [ @@ deriving yojson , equal , sexp , compare ] compare end |
module Account_creation_fees_paid = struct type t = | By_no_one | By_fee_payer of Unsigned_extended . UInt64 . t | By_receiver of Unsigned_extended . UInt64 . t [ @@ deriving equal , to_yojson , sexp , compare ] compare end |
module Failure_status = struct type t = [ ` Applied of Account_creation_fees_paid . t | ` Failed of string ] [ @@ deriving equal , to_yojson , sexp , compare ] compare end |
type t = { kind : Kind . t ; fee_payer : [ ` Pk of string ] ; source : [ ` Pk of string ] ; receiver : [ ` Pk of string ] ; fee_token : [ ` Token_id of string ] ; token : [ ` Token_id of string ] ; fee : Unsigned_extended . UInt64 . t ; nonce : Unsigned_extended . UInt32 . t ; amount : Unsigned_extended . UInt64 . t option ; valid_until : Unsigned_extended . UInt32 . t option ; memo : string option ; hash : string ; failure_status : Failure_status . t option } |
module Partial = struct type t = { kind : Kind . t ; fee_payer : [ ` Pk of string ] ; source : [ ` Pk of string ] ; receiver : [ ` Pk of string ] ; fee_token : [ ` Token_id of string ] ; token : [ ` Token_id of string ] ; fee : Unsigned_extended . UInt64 . t ; amount : Unsigned_extended . UInt64 . t option ; valid_until : Unsigned_extended . UInt32 . t option ; memo : string option } [ @@ deriving to_yojson , sexp , compare , equal ] equal module Reason = Errors . Partial_reason let to_user_command_payload : t -> nonce : Unsigned_extended . UInt32 . t -> ( Signed_command . Payload . t , Errors . t ) t Result . t = fun t ~ nonce -> let open Result . Let_syntax in let % bind fee_payer_pk = pk_to_public_key ~ context " : Fee payer " t . fee_payer in let % bind source_pk = pk_to_public_key ~ context " : Source " t . source in let % bind receiver_pk = pk_to_public_key ~ context " : Receiver " t . receiver in let % bind memo = match t . memo with | Some memo -> ( try Ok ( Signed_command_memo . create_from_string_exn memo ) memo with _ -> Error ( Errors . create ` Memo_invalid ) Memo_invalid ) | None -> Ok Signed_command_memo . empty in let % map body = match t . kind with | ` Payment -> let % map amount = Result . of_option t . amount ~ error : ( Errors . create ( ` Operations_not_valid [ Errors . Partial_reason . Amount_not_some ] ) ) in let payload = { Payment_payload . Poly . source_pk ; receiver_pk ; amount = Amount_currency . of_uint64 amount } in Signed_command . Payload . Body . Payment payload | ` Delegation -> let payload = Stake_delegation . Set_delegate { delegator = source_pk ; new_delegate = receiver_pk } in Result . return @@ Signed_command . Payload . Body . Stake_delegation payload in Signed_command . Payload . create ~ fee ( : Fee_currency . of_uint64 t . fee ) fee ~ fee_payer_pk ~ nonce ~ body ~ memo ~ valid_until : ( Option . map ~ f : Mina_numbers . Global_slot . of_uint32 t . valid_until ) valid_until end |
let forget ( t : t ) t : Partial . t = { kind = t . kind ; fee_payer = t . fee_payer ; source = t . source ; receiver = t . receiver ; fee_token = t . fee_token ; token = t . token ; fee = t . fee ; amount = t . amount ; valid_until = t . valid_until ; memo = t . memo } |
let remember ~ nonce ~ hash t = { kind = t . kind ; fee_payer = t . fee_payer ; source = t . source ; receiver = t . receiver ; fee_token = t . fee_token ; token = t . token ; fee = t . fee ; amount = t . amount ; valid_until = t . valid_until ; memo = t . memo ; hash ; nonce ; failure_status = None } |
let of_operations ? memo ? valid_until ( ops : Operation . t list ) list : ( Partial . t , Partial . Reason . t ) t Validation . t = let find_kind k ( ops : Operation . t list ) list = let name = Operation_types . name k in List . find ops ~ f ( : fun op -> String . equal op . Operation . _type name ) name |> Result . of_option ~ error [ : Partial . Reason . Can ' t_find_kind name ] in let module V = Validation in let open V . Let_syntax in let open Partial . Reason in let payment = let % map ( ) = if Int . equal ( List . length ops ) ops 3 then V . return ( ) else V . fail Length_mismatch and account_a = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Payment_source_dec ops and { account = account ' ; _ } = find_kind ` Fee_payment ops in match ( account , account ' ) account ' with | Some x , Some y when Account_identifier . equal x y -> V . return x | Some _ , Some _ -> V . fail Fee_payer_and_source_mismatch | None , _ | _ , None -> V . fail Account_not_some and token = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Payment_source_dec ops in match account with | Some account -> ( match token_id_of_account account with | None -> V . fail Incorrect_token_id | Some token -> V . return ( ` Token_id token ) token ) | None -> V . fail Account_not_some and fee_token = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Fee_payment ops in match account with | Some account -> ( match token_id_of_account account with | Some token_id -> V . return ( ` Token_id token_id ) token_id | None -> V . fail Incorrect_token_id ) | None -> V . fail Account_not_some and account_b = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Payment_receiver_inc ops in Result . of_option account ~ error [ : Account_not_some ] and ( ) = if List . for_all ops ~ f ( : fun op -> let p = Option . equal String . equal op . status in p None || p ( Some ) " " ) then V . return ( ) else V . fail Status_not_pending and payment_amount_x = let open Result . Let_syntax in let % bind { amount ; _ } = find_kind ` Payment_source_dec ops and { amount = amount ' ; _ } = find_kind ` Payment_receiver_inc ops in match ( amount , amount ' ) amount ' with | Some x , Some y when Amount . equal ( Amount_of . negated x ) x y -> V . return y | Some _ , Some _ -> V . fail Amount_inc_dec_mismatch | None , _ | _ , None -> V . fail Amount_not_some and payment_amount_y = let open Result . Let_syntax in let % bind { amount ; _ } = find_kind ` Fee_payment ops in match amount with | Some x -> V . return ( Amount_of . negated x ) x | None -> V . fail Amount_not_some in { Partial . kind = ` Payment ; fee_payer = ` Pk account_a . address ; source = ` Pk account_a . address ; receiver = ` Pk account_b . address ; fee_token ; token ; fee = Unsigned . UInt64 . of_string payment_amount_y . Amount . value ; amount = Some ( Unsigned . UInt64 . of_string payment_amount_x . Amount . value ) value ; valid_until ; memo } in let delegation = let % map ( ) = if Int . equal ( List . length ops ) ops 2 then V . return ( ) else V . fail Length_mismatch and account_a = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Fee_payment ops in Option . value_map account ~ default ( : V . fail Account_not_some ) Account_not_some ~ f : V . return and fee_token = let open Result . Let_syntax in let % bind { account ; _ } = find_kind ` Fee_payment ops in match account with | Some account -> ( match token_id_of_account account with | Some token_id -> V . return ( ` Token_id token_id ) token_id | None -> V . fail Incorrect_token_id ) | None -> V . fail Account_not_some and account_b = let open Result . Let_syntax in let % bind { metadata ; _ } = find_kind ` Delegate_change ops in match metadata with | Some metadata -> ( match metadata with | ` Assoc [ ( " delegate_change_target " , ` String s ) s ] -> return s | _ -> V . fail Invalid_metadata ) | None -> V . fail Account_not_some and ( ) = if List . for_all ops ~ f ( : fun op -> let p = Option . equal String . equal op . status in p None || p ( Some ) " " ) then V . return ( ) else V . fail Status_not_pending and payment_amount_y = let open Result . Let_syntax in let % bind { amount ; _ } = find_kind ` Fee_payment ops in match amount with | Some x -> V . return ( Amount_of . negated x ) x | None -> V . fail Amount_not_some in { Partial . kind = ` Delegation ; fee_payer = ` Pk account_a . address ; source = ` Pk account_a . address ; receiver = ` Pk account_b ; fee_token ; token = ` Token_id Token_id ( . default |> to_string ) to_string ; fee = Unsigned . UInt64 . of_string payment_amount_y . Amount . value ; amount = None ; valid_until ; memo } in let partials = [ payment ; delegation ] in let oks , errs = List . partition_map partials ~ f : Result . to_either in match ( oks , errs ) errs with | [ ] , errs -> Error ( List . concat errs ) errs | [ partial ] , _ -> Ok partial | _ , _ -> failwith " A sequence of operations must represent exactly one user command " |
let to_operations ~ failure_status ( t : Partial . t ) t : Operation . t list = let plan : ' a Op . t list = ( if not Unsigned . UInt64 ( . equal t . fee zero ) zero then [ { Op . label = ` Fee_payment ; related_to = None } ] else [ ] ) @ ( match failure_status with | Some ( ` Applied ( Account_creation_fees_paid . By_receiver amount ) amount ) amount -> [ { Op . label = ` Account_creation_fee_via_payment amount ; related_to = None } ] | Some ( ` Applied ( Account_creation_fees_paid . By_fee_payer amount ) amount ) amount -> [ { Op . label = ` Account_creation_fee_via_fee_payer amount ; related_to = None } ] | _ -> [ ] ) @ match t . kind with | ` Payment -> ( match t . amount with | Some amount -> [ { Op . label = ` Payment_source_dec amount ; related_to = None } ; { Op . label = ` Payment_receiver_inc amount ; related_to = Some ( ` Payment_source_dec amount ) amount } ] | None -> [ ] ) | ` Delegation -> [ { Op . label = ` Delegate_change ; related_to = None } ] in Op . build ~ a_eq : [ % eq : [ ` Fee_payment | ` Payment_source_dec of Unsigned . UInt64 . t | ` Payment_receiver_inc of Unsigned . UInt64 . t ] ] ~ plan ~ f ( : fun ~ related_operations ~ operation_identifier op -> let status , metadata , did_fail = match ( op . label , failure_status ) failure_status with | _ , None -> ( None , None , false ) false | _ , Some ( ` Applied _ ) _ -> ( Some ` Success , None , false ) false | _ , Some ( ` Failed reason ) reason -> ( Some ` Failed , Some ( ` Assoc [ ( " reason " , ` String reason ) reason ] ) , true ) true in let pending_or_success_only = function | None -> None | Some ( ` Success | ` Failed ) Failed -> Some ` Success in let merge_metadata m1 m2 = match ( m1 , m2 ) m2 with | None , None -> None | Some x , None | None , Some x -> Some x | Some ( ` Assoc xs ) xs , Some ( ` Assoc ys ) ys -> Some ( ` Assoc ( xs @ ys ) ys ) ys | _ -> failwith " Unexpected pattern " in match op . label with | ` Fee_payment -> { Operation . operation_identifier ; related_operations ; status = status |> pending_or_success_only |> Option . map ~ f : Operation_statuses . name ; account = Some ( account_id t . fee_payer t . fee_token ) fee_token ; _type = Operation_types . name ` Fee_payment ; amount = Some Amount_of ( . negated @@ token t . fee_token t . fee ) fee ; coin_change = None ; metadata } | ` Payment_source_dec amount -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . source t . token ) token ; _type = Operation_types . name ` Payment_source_dec ; amount = ( if did_fail then None else Some Amount_of ( . negated @@ token t . token amount ) amount ) ; coin_change = None ; metadata } | ` Payment_receiver_inc amount -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . receiver t . token ) token ; _type = Operation_types . name ` Payment_receiver_inc ; amount = ( if did_fail then None else Some ( Amount_of . token t . token amount ) amount ) amount ; coin_change = None ; metadata } | ` Account_creation_fee_via_payment account_creation_fee -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . receiver t . token ) token ; _type = Operation_types . name ` Account_creation_fee_via_payment ; amount = Some Amount_of ( . negated @@ mina account_creation_fee ) account_creation_fee ; coin_change = None ; metadata } | ` Account_creation_fee_via_fee_payer account_creation_fee -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . fee_payer t . fee_token ) fee_token ; _type = Operation_types . name ` Account_creation_fee_via_fee_payer ; amount = Some Amount_of ( . negated @@ mina account_creation_fee ) account_creation_fee ; coin_change = None ; metadata } | ` Delegate_change -> { Operation . operation_identifier ; related_operations ; status = Option . map ~ f : Operation_statuses . name status ; account = Some ( account_id t . source ( ` Token_id Amount_of . Token_id . default ) default ) default ; _type = Operation_types . name ` Delegate_change ; amount = None ; coin_change = None ; metadata = merge_metadata metadata ( Some ( ` Assoc [ ( " delegate_change_target " , ` String ( let ( ` Pk r ) r = t . receiver in r ) ) ] ) ) } ) |
let to_operations ' ( t : t ) t : Operation . t list = to_operations ~ failure_status : t . failure_status ( forget t ) t let start = { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; fee_token = ` Token_id Amount_of . Token_id . default ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = None ; hash = " TXN_1_HASH " ; valid_until = Some ( Unsigned . UInt32 . of_int 10_000 ) 10_000 ; memo = Some " hello " } in let ops = to_operations ' start in match of_operations ? valid_until : start . valid_until ? memo : start . memo ops with | Ok partial -> [ % test_eq : Partial . t ] t partial ( forget start ) start | Error e -> failwithf " ! Mismatch because { % sexp : Partial . Reason . t list } list " e ( ) let start = { kind = ` Delegation ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 1_000_000_000 ; receiver = ` Pk " Bob " ; fee_token = ` Token_id Amount_of . Token_id . default ; nonce = Unsigned . UInt32 . of_int 42 ; amount = None ; failure_status = None ; hash = " TXN_2_HASH " ; valid_until = Some ( Unsigned . UInt32 . of_int 867888 ) 867888 ; memo = Some " hello " } in let ops = to_operations ' start in match of_operations ops ? valid_until : start . valid_until ? memo : start . memo with | Ok partial -> [ % test_eq : Partial . t ] t partial ( forget start ) start | Error e -> failwithf " ! Mismatch because { % sexp : Partial . Reason . t list } list " e ( ) |
let non_default_token = ` Token_id ( Token_id . to_string ( Quickcheck . random_value Token_id . gen_non_default ) gen_non_default ) gen_non_default |
let dummies = [ { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee_token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Applied Account_creation_fees_paid . By_no_one ) By_no_one ; hash = " TXN_1_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee_token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Applied ( Account_creation_fees_paid . By_receiver ( Unsigned . UInt64 . of_int 1_000_000 ) 1_000_000 ) ) ; hash = " TXN_1new_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee_token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Failed " Failure ) " ; hash = " TXN_1fail_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = non_default_token ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; fee_token = ` Token_id Amount_of . Token_id . default ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Applied Account_creation_fees_paid . By_no_one ) By_no_one ; hash = " TXN_1a_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Payment ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; fee_token = non_default_token ; nonce = Unsigned . UInt32 . of_int 3 ; amount = Some ( Unsigned . UInt64 . of_int 2_000_000_000 ) 2_000_000_000 ; failure_status = Some ( ` Applied Account_creation_fees_paid . By_no_one ) By_no_one ; hash = " TXN_1b_HASH " ; valid_until = None ; memo = Some " hello " } ; { kind = ` Delegation ; fee_payer = ` Pk " Alice " ; source = ` Pk " Alice " ; token = ` Token_id Amount_of . Token_id . default ; fee_token = ` Token_id Amount_of . Token_id . default ; fee = Unsigned . UInt64 . of_int 2_000_000_000 ; receiver = ` Pk " Bob " ; nonce = Unsigned . UInt32 . of_int 3 ; amount = None ; failure_status = Some ( ` Applied Account_creation_fees_paid . By_no_one ) By_no_one ; hash = " TXN_2_HASH " ; valid_until = None ; memo = Some " hello " } ] |
module Payload = struct module Common = struct [ %% versioned module Stable = struct module V2 = struct type t = ( Currency . Fee . Stable . V1 . t , Public_key . Compressed . Stable . V1 . t , Account_nonce . Stable . V1 . t option , Global_slot . Stable . V1 . t , Signed_command_memo . Stable . V1 . t ) Signed_command_payload . Common . Poly . Stable . V2 . t [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end let create ~ fee ~ fee_payer_pk ? nonce ~ valid_until ~ memo : t = { fee ; fee_payer_pk ; nonce ; valid_until ; memo } let to_user_command_common ( t : t ) t ~ minimum_nonce ~ inferred_nonce : ( Signed_command_payload . Common . t , string ) string Result . t = let open Result . Let_syntax in let % map nonce = match t . nonce with | None -> Ok inferred_nonce | Some nonce -> if Account_nonce ( . minimum_nonce <= nonce && nonce <= inferred_nonce ) inferred_nonce then Ok nonce else Error ( sprintf " ! Input nonce % s either different from inferred nonce % s or \ below minimum_nonce % s " ( Account_nonce . to_string nonce ) nonce ( Account_nonce . to_string inferred_nonce ) inferred_nonce ( Account_nonce . to_string minimum_nonce ) minimum_nonce ) in { Signed_command_payload . Common . Poly . fee = t . fee ; fee_payer_pk = t . fee_payer_pk ; nonce ; valid_until = t . valid_until ; memo = t . memo } let fee_payer ( { fee_payer_pk ; _ } : t ) t = Account_id . create fee_payer_pk Mina_base . Token_id . default end [ %% versioned module Stable = struct module V2 = struct type t = ( Common . Stable . V2 . t , Signed_command_payload . Body . Stable . V2 . t ) Signed_command_payload . Poly . Stable . V1 . t [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end let create ~ fee ~ fee_payer_pk ? nonce ~ valid_until ~ memo ~ body : t = { common = Common . create ~ fee ~ fee_payer_pk ? nonce ~ valid_until ~ memo ; body } let to_user_command_payload ( t : t ) t ~ minimum_nonce ~ inferred_nonce : ( Signed_command_payload . t , string ) string Result . t = let open Result . Let_syntax in let % map common = Common . to_user_command_common t . common ~ minimum_nonce ~ inferred_nonce in { Signed_command_payload . Poly . common ; body = t . body } let fee_payer ( { common ; _ } : t ) t = Common . fee_payer common end |
module Sign_choice = struct [ %% versioned module Stable = struct module V1 = struct type t = | Signature of Signature . Stable . V1 . t | Hd_index of Unsigned_extended . UInt32 . Stable . V1 . t | Keypair of Keypair . 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 = ( Payload . Stable . V2 . t , Public_key . Compressed . Stable . V1 . t , Sign_choice . Stable . V1 . t ) Signed_command . Poly . Stable . V1 . t [ @@ deriving sexp , to_yojson ] to_yojson let to_latest = Fn . id end end ] end |
let fee_payer ( { payload ; _ } : t ) t = Payload . fee_payer payload |
let create ? nonce ~ fee ~ fee_payer_pk ~ valid_until ~ memo ~ body ~ signer ~ sign_choice ( ) : t = let valid_until = Option . value valid_until ~ default : Global_slot . max_value in let payload = Payload . create ~ fee ~ fee_payer_pk ? nonce ~ valid_until ~ memo ~ body in { payload ; signer ; signature = sign_choice } |
let sign ~ signer ( ~ user_command_payload : Signed_command_payload . t ) t = function | Sign_choice . Signature signature -> Option . value_map ~ default ( : Deferred . return ( Error " Invalid_signature ) ) " ( Signed_command . create_with_signature_checked signature signer user_command_payload ) ~ f : Deferred . Result . return | Keypair signer_kp -> Deferred . Result . return ( Signed_command . sign signer_kp user_command_payload ) user_command_payload | Hd_index hd_index -> Secrets . Hardware_wallets . sign ~ hd_index ~ public_key ( : Public_key . decompress_exn signer ) signer ~ user_command_payload |
let inferred_nonce ~ get_current_nonce ( ~ fee_payer : Account_id . t ) t ~ nonce_map = let open Result . Let_syntax in let update_map = Map . set nonce_map ~ key : fee_payer in match Map . find nonce_map fee_payer with | Some ( min_nonce , nonce ) nonce -> let next_nonce = Account_nonce . succ nonce in let updated_map = update_map ~ data ( : min_nonce , next_nonce ) next_nonce in Ok ( min_nonce , next_nonce , updated_map ) updated_map | None -> let % map ` Min min_nonce , txn_pool_or_account_nonce = get_current_nonce fee_payer in let updated_map = update_map ~ data ( : min_nonce , txn_pool_or_account_nonce ) txn_pool_or_account_nonce in ( min_nonce , txn_pool_or_account_nonce , updated_map ) updated_map |
let warn_if_unable_to_pay_account_creation_fee ~ get_account ( ~ constraint_constants : Genesis_constants . Constraint_constants . t ) t ~ logger user_command_payload = let receiver_pk = Signed_command_payload . receiver_pk user_command_payload in let token = Signed_command_payload . token user_command_payload in let receiver = Account_id . create receiver_pk token in let receiver_account = get_account receiver in let amount = Signed_command_payload . amount user_command_payload in match ( receiver_account , amount ) amount with | ` Bootstrapping , _ | ` Active ( Some _ ) _ , _ | _ , None -> ( ) | ` Active None , Some amount -> let open Currency . Amount in let account_creation_fee = of_fee constraint_constants . account_creation_fee in if amount < account_creation_fee then [ % log warn ] warn " A transaction was submitted that is likely to fail because the \ receiver account doesn ' t appear to have been created already and \ the transaction amount of % s is smaller than the account creation \ fee of % s . " ( to_formatted_string amount ) amount ( to_formatted_string account_creation_fee ) account_creation_fee ; ( ) |
let to_user_command ( ? nonce_map = Account_id . Map . empty ) empty ~ get_current_nonce ~ get_account ~ constraint_constants ~ logger ( client_input : t ) t = Deferred . map ~ f : ( Result . map_error ~ f ( : fun str -> Error . createf " Error creating user command : % s Error : % s " ( Yojson . Safe . to_string ( to_yojson client_input ) client_input ) client_input str ) ) @@ let open Deferred . Result . Let_syntax in let fee_payer = fee_payer client_input in let % bind minimum_nonce , inferred_nonce , updated_nonce_map = inferred_nonce ~ get_current_nonce ~ fee_payer ~ nonce_map |> Deferred . return in let % bind user_command_payload = Payload . to_user_command_payload client_input . payload ~ minimum_nonce ~ inferred_nonce |> Deferred . return in let ( ) = warn_if_unable_to_pay_account_creation_fee ~ get_account ~ constraint_constants ~ logger user_command_payload in let % map signed_user_command = sign ~ signer : client_input . signer ~ user_command_payload client_input . signature in ( Signed_command . forget_check signed_user_command , updated_nonce_map ) updated_nonce_map |
let to_user_commands ( ? nonce_map = Account_id . Map . empty ) empty ~ get_current_nonce ~ get_account ~ constraint_constants ~ logger uc_inputs : Signed_command . t list Deferred . Or_error . t = let open Deferred . Or_error . Let_syntax in let % map user_commands , _ = Deferred . Or_error . List . fold ~ init ( [ ] , : nonce_map ) nonce_map uc_inputs ~ f ( : fun ( valid_user_commands , nonce_map ) nonce_map uc_input -> let % map res , updated_nonce_map = to_user_command ~ nonce_map ~ get_current_nonce ~ get_account ~ constraint_constants ~ logger uc_input in ( res :: valid_user_commands , updated_nonce_map ) updated_nonce_map ) in List . rev user_commands |
type t = { author_name : string option ; email : string option ; github_username : string option ; create_switch : bool option } |
let of_dec ( dec : Dec_user_config . t ) t = { author_name = dec . author_name ; email = dec . email ; github_username = dec . github_username ; create_switch = dec . create_switch } |
let path_of_opt value = value |> Option . map Result . ok |> Option . value ~ default : ( Config . spin_config_dir |> Result . map ( fun p -> Filename . concat p " default ) ) " |
let read ? path ( ) = let decode_if_exists path = if Sys . file_exists path then Decoder . decode_sexps_file path Dec_user_config . decode |> Result . map of_dec |> Result . map Option . some |> Result . map_error ( Spin_error . of_decoder_error ~ file : path ) path else Ok None in Result . bind ( path_of_opt path ) path decode_if_exists |
let save ? path ( t : t ) t = let open Result . Syntax in let + path = path_of_opt path in let ( ) = Sys . mkdir_p ( Filename . dirname path ) path in Encoder . encode_file path Dec_user_config . { author_name = t . author_name ; email = t . email ; github_username = t . github_username ; create_switch = t . create_switch } Dec_user_config . encode |
let validate_strip s = match String . trim s with " " -> Error " Enter a value . " | s -> Ok s |
let prompt ? default : d ( ) = let author_name = Inquire . input " Your name " ? default ( : Option . bind d ( fun d -> d . author_name ) author_name ) author_name ~ validate : validate_strip in let email = Inquire . input " Your email " ? default ( : Option . bind d ( fun d -> d . email ) email ) email ~ validate : validate_strip in let github_username = Inquire . input " Your GitHub username " ? default ( : Option . bind d ( fun d -> d . github_username ) github_username ) github_username ~ validate : validate_strip in let create_switch = Inquire . confirm " Create switches when generating projects " ? default ( : Option . bind d ( fun d -> d . create_switch ) create_switch ) create_switch in { author_name = Some author_name ; email = Some email ; github_username = Some github_username ; create_switch = Some create_switch } |
let to_context t = let context = Hashtbl . create 256 in Option . iter ( fun v -> Hashtbl . add context " author_name " v |> ignore ) ignore t . author_name ; Option . iter ( fun v -> Hashtbl . add context " email " v |> ignore ) ignore t . email ; Option . iter ( fun v -> Hashtbl . add context " github_username " v |> ignore ) ignore t . github_username ; context |
module Search = struct module Query = Empty . Query module Request = struct type t = { search_term : string ; limited : int option } [ @@ deriving accessor ] let encoding = let to_tuple t = t . search_term , t . limited in let of_tuple v = let search_term , limited = v in { search_term ; limited } in let with_tuple = obj2 ( req " search_term " string ) ( opt " limited " int ) in conv to_tuple of_tuple with_tuple end module Response = struct module User = struct type t = { user_id : string ; display_name : string option ; avatar_url : string option ; } [ @@ deriving accessor ] let encoding = let to_tuple t = t . user_id , t . display_name , t . avatar_url in let of_tuple v = let user_id , display_name , avatar_url = v in { user_id ; display_name ; avatar_url } in let with_tuple = obj3 ( req " user_id " string ) ( opt " display_name " string ) ( opt " avatar_url " string ) in conv to_tuple of_tuple with_tuple end type t = { results : User . t list ; limited : bool } [ @@ deriving accessor ] let encoding = let to_tuple t = t . results , t . limited in let of_tuple v = let results , limited = v in { results ; limited } in let with_tuple = obj2 ( req " results " ( list User . encoding ) ) ( req " limited " bool ) in conv to_tuple of_tuple with_tuple end end |
type links = | LINKS of ( ( int * int ) * int ) list | WHATEVER | SOME | TYPE of string * string |
type cc_port = { port_links : links ; port_states : string list option ; } |
type site = | Port of cc_port | Counter of int |
type cc_site = { site_name : string ; site_type : site } |
type cc_node = { node_type : string ; node_id : int option ; node_sites : cc_site array ; } |
type connected_component = cc_node option array array |
module LinkSetMap = SetMap . Make ( struct type t = ( int * int ) * int let print = Pp . pair ( Pp . pair Format . pp_print_int Format . pp_print_int ) Format . pp_print_int let compare ( x , y ) ( x ' , y ' ) = let c = Mods . int_pair_compare x x ' in if c = 0 then Mods . int_compare y y ' else c end ) |
let print_link ( dangling , free_id ) p f = function | WHATEVER -> Format . pp_print_string f " [ ] " # | SOME -> Format . pp_print_string f " [ _ ] " | TYPE ( si , ty ) -> Format . fprintf f " [ % s . % s ] " si ty | LINKS [ ] -> Format . pp_print_string f " [ . ] " | LINKS l -> let myself = ref ( LinkSetMap . Map . find_default LinkSetMap . Map . empty p ! dangling ) in let ( ) = Format . fprintf f " [ % a ] " ( Pp . list Pp . space ( fun f p ' -> let i = if p = p ' then - 1 else match Option_util . bind ( LinkSetMap . Map . find_option p ) ( LinkSetMap . Map . find_option p ' ! dangling ) with | None -> let ( ) = incr free_id in let ( ) = myself := LinkSetMap . Map . add p ' ! free_id ! myself in ! free_id | Some va -> va in Format . fprintf f " % i " i ) ) l in dangling := LinkSetMap . Map . add p ! myself ! dangling |
let print_port with_link node p id f = Format . fprintf f " % a % a " ( fun f -> function | None -> Format . pp_print_string f " { } " # | Some [ ] -> ( ) | Some l -> Format . fprintf f " { % a } " ( Pp . list Pp . space ( fun f i -> Format . fprintf f " % s " i ) ) l ) p . port_states ( match with_link with | Some pack -> print_link pack ( node , id ) | None -> ( fun _ _ -> ( ) ) ) p . port_links |
let print_intf with_link node = Pp . array Pp . space ( fun id f si -> let ( ) = Format . fprintf f " % s " si . site_name in ( match si . site_type with | Port p -> print_port with_link node p id f | Counter i -> Format . fprintf f " { =% i } " i ) ) |
let print_agent with_id link node f = function | None -> Format . pp_print_string f " . " | Some ag -> Format . fprintf f " % a % s ( [ @< h >% a ] ) " @ ( Pp . option ~ with_space : false ( fun f i -> Format . fprintf f " x % i " : i ) ) ( if with_id then ag . node_id else None ) ag . node_type ( print_intf link node ) ag . node_sites |
let print_cc f mix = let link = Some ( ref ( LinkSetMap . Map . empty ) , ref 0 ) in Pp . array ( fun f -> Format . fprintf f " \\@ " ) ( fun al -> Pp . array Pp . comma ( fun ar -> print_agent true link ( al , ar ) ) ) f mix |
let get_color = let store = Hashtbl . create 10 in fun i -> try Hashtbl . find store i with Not_found -> let v = Format . sprintf " #% x % x % x " ( Random . int 255 ) ( Random . int 255 ) ( Random . int 255 ) in let ( ) = Hashtbl . add store i v in v |
let print_dot_cc nb_cc f mix = Pp . array Pp . empty ( fun il -> Pp . array Pp . empty ( fun ir f -> function | None -> ( ) | Some ag -> Format . fprintf f " node % d_ % d_ % d [ label = " [ \@< h >% a ] " , @\ color = " \% s " , \ style = filled ] ; , " @ nb_cc il ir ( print_agent false None ( il , ir ) ) ( Some ag ) ( get_color ag . node_type ) ; Format . fprintf f " node % d_ % d_ % d -> counter % d [ style = invis ] ; , " @ nb_cc il ir nb_cc ) ) f mix ; ignore @@ Array . iteri ( fun al -> Array . iteri ( fun ar -> function | None -> ( ) | Some ag -> Array . iteri ( fun s si -> match si . site_type with | Counter _ -> ( ) | Port p -> match p . port_links with | WHATEVER -> assert false | SOME -> assert false | TYPE ( _si , _ty ) -> assert false | LINKS links -> Pp . list Pp . empty ( fun f ( ( al ' , ar ' ) , s ' ) -> if al < al ' || ( al = al ' && ( ar < ar ' || ( ar = ar ' && s < s ' ) ) ) then match mix . ( al ' ) . ( ar ' ) with | None -> assert false | Some ag ' -> Format . fprintf f " node % d_ % d_ % d -> node % d_ % d_ % d \ [ taillabel " =\% s " , \ headlabel " =\% s " , \ dir = none ] ; , " @ nb_cc al ar nb_cc al ' ar ' si . site_name ag ' . node_sites . ( s ' ) . site_name ) f links ) ag . node_sites ) ) mix |
let write_cc_port ob p = let ( ) = Bi_outbuf . add_char ob ' { ' in let ( ) = JsonUtil . write_field " port_links " ( fun ob -> function | WHATEVER -> Yojson . Basic . write_null ob ( ) | SOME -> Yojson . Basic . write_bool ob true | TYPE ( si , ty ) -> let ( ) = Bi_outbuf . add_string ob " { " \ site_name " " " \:\ in let ( ) = Bi_outbuf . add_string ob si in let ( ) = Bi_outbuf . add_string ob " " , " \\ agent_type " " " \:\ in let ( ) = Bi_outbuf . add_string ob ty in Bi_outbuf . add_string ob " " } " \ | LINKS l -> JsonUtil . write_list ( JsonUtil . write_compact_pair ( JsonUtil . write_compact_pair Yojson . Basic . write_int Yojson . Basic . write_int ) Yojson . Basic . write_int ) ob l ) ob p . port_links in let ( ) = JsonUtil . write_comma ob in let ( ) = JsonUtil . write_field " port_states " ( JsonUtil . write_option ( JsonUtil . write_list Yojson . Basic . write_string ) ) ob p . port_states in Bi_outbuf . add_char ob ' } ' |
let write_site ob f = let ( ) = Bi_outbuf . add_char ob ' [ ' in let ( ) = match f . site_type with | Counter i -> let ( ) = Yojson . Basic . write_string ob " counter " in let ( ) = Bi_outbuf . add_char ob ' , ' in Yojson . Basic . write_int ob i | Port p -> let ( ) = Yojson . Basic . write_string ob " port " in let ( ) = Bi_outbuf . add_char ob ' , ' in write_cc_port ob p in Bi_outbuf . add_char ob ' ] ' |
let write_cc_site ob f = let ( ) = Bi_outbuf . add_char ob ' { ' in let ( ) = JsonUtil . write_field " site_name " Yojson . Basic . write_string ob f . site_name in let ( ) = JsonUtil . write_comma ob in let ( ) = JsonUtil . write_field " site_type " write_site ob f in Bi_outbuf . add_char ob ' } ' |
let links_of_yojson = function | ` Null -> WHATEVER | ` Bool b -> let ( ) = assert b in SOME | ` Assoc [ " site_name " , ` String si ; " agent_type " , ` String ty ] | ` Assoc [ " agent_type " , ` String ty ; " site_name " , ` String si ] -> TYPE ( si , ty ) | ` List _ as x -> let error_msg = None in LINKS ( JsonUtil . to_list ( JsonUtil . compact_to_pair ( JsonUtil . compact_to_pair ( JsonUtil . to_int ? error_msg ) ( JsonUtil . to_int ? error_msg ) ) ( JsonUtil . to_int ? error_msg ) ) x ) | x -> raise ( Yojson . Basic . Util . Type_error ( " Incorrect cc_port " , x ) ) |
let read_cc_port p lb = let ( port_links , port_states ) = Yojson . Basic . read_fields ( fun ( s , i ) key p lb -> if key = " port_links " then ( links_of_yojson ( Yojson . Basic . read_json p lb ) , i ) else let ( ) = assert ( key = " port_states " ) in ( s , JsonUtil . read_option ( Yojson . Basic . read_list Yojson . Basic . read_string ) p lb ) ) ( LINKS [ ] , Some [ ] ) p lb in { port_links ; port_states } |
let read_site p lb = let ( ) = Yojson . Basic . read_lbr p lb in let key = JsonUtil . read_between_spaces Yojson . Basic . read_string p lb in let ( ) = Yojson . Basic . read_comma p lb in let out = JsonUtil . read_between_spaces ( fun p lb -> if key = " counter " then Counter ( Yojson . Basic . read_int p lb ) else let ( ) = assert ( key = " port " ) in Port ( read_cc_port p lb ) ) p lb in let ( ) = Yojson . Basic . read_rbr p lb in out |
let read_cc_site p lb = let ( site_name , site_type ) = Yojson . Basic . read_fields ( fun ( n , s ) key p lb -> if key = " site_name " then ( Yojson . Basic . read_string p lb , s ) else let ( ) = assert ( key = " site_type " ) in ( n , read_site p lb ) ) ( " " , Counter ( - 1 ) ) p lb in { site_name ; site_type } |
let write_cc_node ob x = JsonUtil . write_option ( fun ob f -> let ( ) = Bi_outbuf . add_char ob ' { ' in let ( ) = JsonUtil . write_field " node_type " Yojson . Basic . write_string ob f . node_type in let ( ) = JsonUtil . write_comma ob in let ( ) = match f . node_id with | None -> ( ) | Some node_id -> let ( ) = JsonUtil . write_field " node_id " Yojson . Basic . write_int ob node_id in JsonUtil . write_comma ob in let ( ) = JsonUtil . write_field " node_sites " ( JsonUtil . write_array write_cc_site ) ob f . node_sites in Bi_outbuf . add_char ob ' } ' ) ob x |
let read_cc_node p lb = JsonUtil . read_option ( fun p lb -> let ( node_id , node_type , node_sites ) = Yojson . Basic . read_fields ( fun ( id , n , s ) key p lb -> if key = " node_id " then ( Some ( Yojson . Basic . read_int p lb ) , n , s ) else if key = " node_type " then ( id , Yojson . Basic . read_string p lb , s ) else let ( ) = assert ( key = " node_sites " ) in ( id , n , Yojson . Basic . read_array read_cc_site p lb ) ) ( None , " " , [ ] ) || p lb in { node_id ; node_type ; node_sites } ) p lb |
let write_connected_component ob f = JsonUtil . write_array ( JsonUtil . write_array write_cc_node ) ob f |
let read_connected_component ob f = Yojson . Basic . read_array ( Yojson . Basic . read_array read_cc_node ) ob f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.