text
stringlengths 0
601k
|
---|
module I = struct type ' a t = { start : ' a ; bytecode_start_address : ' a [ @ bits dbits ] ; atom_table_address : ' a [ @ bits dbits ] ; globals_start_address : ' a [ @ bits dbits ] ; heap_start_address : ' a [ @ bits dbits ] ; stack_start_address : ' a [ @ bits dbits ] ; memory_i : ' a Memory . I . t ; c_call_ready : ' a ; c_call_result : ' a [ @ bits dbits ] } [ @@ deriving sexp_of , hardcaml ] end |
module O = struct type ' a t = { state : ' a ; pc : ' a [ @ bits dbits ] ; sp : ' a [ @ bits dbits ] ; accu : ' a [ @ bits dbits ] ; env : ' a [ @ bits dbits ] ; extra_args : ' a [ @ bits dbits ] ; instruction : ' a [ @ bits 8 ] ; error : ' a ; memory_o : ' a Memory . O . t ; decode : ' a Decode . t ; c_call_request : ' a ; c_call_prim : ' a [ @ bits dbits ] } [ @@ deriving sexp_of , hardcaml ] end |
type decinstr = { lte : t ; gte : t ; eq : t ; range : t } |
let decode instr = let constins i = consti ~ width : 8 ( Opcode . to_int i ) in let ins = Opcode . all in let sel = let sel = Array . of_list @@ List . map ins ~ f ( : fun i -> let i = constins i in { lte = instr <=: i ; gte = instr >=: i ; eq = instr ==: i ; range = instr -: i } ) in fun i -> sel . ( Opcode . to_int i ) in let acc = ( sel ACC ) . lte in let acc_op = ( sel ACC0 ) . range . [ : 3 , 0 ] in let push = ( sel PUSH ) . eq |: ( sel PUSHACC0 ) . eq in let pushacc = ( sel PUSH ) . gte &: ( sel PUSHACC ) . lte in let push_op = ( sel PUSHACC0 ) . range . [ : 3 , 0 ] in let pop = ( sel POP ) . eq in let assign = ( sel ASSIGN ) . eq in let envacc = ( sel ENVACC1 ) . gte &: ( sel ENVACC ) . lte in let envacc_op = ( sel ENVACC1 ) . range . [ : 2 , 0 ] in let pushenvacc = ( sel PUSHENVACC1 ) . gte &: ( sel PUSHENVACC ) . lte in let pushenvacc_op = ( sel PUSHENVACC1 ) . range . [ : 2 , 0 ] in let push_retaddr = ( sel PUSH_RETADDR ) . eq in let apply = ( sel APPLY ) . gte &: ( sel APPLY3 ) . lte in let apply_op = ( sel APPLY ) . range . [ : 1 , 0 ] in let appterm = ( sel APPTERM ) . gte &: ( sel APPTERM3 ) . lte in let appterm_op = ( sel APPTERM ) . range . [ : 1 , 0 ] in let closure = ( sel CLOSURE ) . eq in let closurerec = ( sel CLOSUREREC ) . eq in let return = ( sel RETURN ) . eq in let restart = ( sel RESTART ) . eq in let grab = ( sel GRAB ) . eq in let pushgetglobal = ( sel PUSHGETGLOBAL ) . eq in let getglobal = ( sel GETGLOBAL ) . eq in let pushgetglobalfield = ( sel PUSHGETGLOBALFIELD ) . eq in let getglobalfield = ( sel GETGLOBALFIELD ) . eq in let setglobal = ( sel SETGLOBAL ) . eq in let offsetclosure = ( sel OFFSETCLOSUREM2 ) . gte &: ( sel OFFSETCLOSURE ) . lte in let offsetclosure_op = ( sel OFFSETCLOSUREM2 ) . range . [ : 1 , 0 ] in let pushoffsetclosure = ( sel PUSHOFFSETCLOSUREM2 ) . gte &: ( sel PUSHOFFSETCLOSURE ) . lte in let pushoffsetclosure_op = ( sel PUSHOFFSETCLOSUREM2 ) . range . [ : 1 , 0 ] in let atom = ( sel ATOM0 ) . gte &: ( sel ATOM ) . lte in let atom_op = ( sel ATOM0 ) . range . [ : 0 , 0 ] in let pushatom = ( sel PUSHATOM0 ) . gte &: ( sel PUSHATOM ) . lte in let pushatom_op = ( sel PUSHATOM0 ) . range . [ : 0 , 0 ] in let makeblock = ( sel MAKEBLOCK ) . gte &: ( sel MAKEFLOATBLOCK ) . lte in let makeblock_op = ( sel MAKEBLOCK ) . range . [ : 2 , 0 ] in let getfield = ( sel GETFIELD ) . gte &: ( sel GETFLOATFIELD ) . lte in let getfield_op = ( sel GETFIELD ) . range . [ : 2 , 0 ] in let setfield = ( sel SETFIELD ) . gte &: ( sel SETFLOATFIELD ) . lte in let setfield_op = ( sel SETFIELD ) . range . [ : 2 , 0 ] in let vectlength = ( sel VECTLENGTH ) . eq in let getvectitem = ( sel GETVECTITEM ) . eq in let setvectitem = ( sel SETVECTITEM ) . eq in let getstringchar = ( sel GETSTRINGCHAR ) . eq in let setstringchar = ( sel SETSTRINGCHAR ) . eq in let branch = ( sel BRANCH ) . gte &: ( sel SWITCH ) . lte in let branch_op = ( sel BRANCH ) . range . [ : 1 , 0 ] in let boolnot = ( sel BOOLNOT ) . eq in let pushtrap = ( sel PUSHTRAP ) . eq in let poptrap = ( sel POPTRAP ) . eq in let raise_ = ( sel RAISE ) . eq in let check_signals = ( sel CHECK_SIGNALS ) . eq in let c_call = ( sel C_CALL1 ) . gte &: ( sel C_CALLN ) . lte in let c_call_op = ( sel C_CALL1 ) . range . [ : 2 , 0 ] in let const = ( sel CONST0 ) . gte &: ( sel CONSTINT ) . lte in let const_op = ( sel CONST0 ) . range . [ : 2 , 0 ] in let pushconst = ( sel PUSHCONST0 ) . gte &: ( sel PUSHCONSTINT ) . lte in let pushconst_op = ( sel PUSHCONST0 ) . range . [ : 2 , 0 ] in let alu = ( sel NEGINT ) . gte &: ( sel ASRINT ) . lte in let alu_op = ( sel NEGINT ) . range . [ : 3 , 0 ] in let comp = ( sel EQ ) . gte &: ( sel GEINT ) . lte in let comp_op = ( sel EQ ) . range . [ : 2 , 0 ] in let offsetint = ( sel OFFSETINT ) . eq in let offsetref = ( sel OFFSETREF ) . eq in let isint = ( sel ISINT ) . eq in let getmethod = ( sel GETMETHOD ) . eq in let bcomp = ( sel BEQ ) . gte &: ( sel BGEINT ) . lte in let bcomp_op = ( sel BGEINT ) . range . [ : 2 , 0 ] in let ucomp = ( sel ULTINT ) . gte &: ( sel UGEINT ) . lte in let ucomp_op = ( sel ULTINT ) . range . [ : 0 , 0 ] in let bucomp = ( sel BULTINT ) . gte &: ( sel BUGEINT ) . lte in let bucomp_op = ( sel BULTINT ) . range . [ : 0 , 0 ] in let getpubmet = ( sel GETPUBMET ) . eq in let getdynmet = ( sel GETDYNMET ) . eq in let stop = ( sel STOP ) . eq in let event = ( sel EVENT ) . eq in let break = ( sel BREAK ) . eq in let reraise = ( sel RERAISE ) . eq in let raise_notrace = ( sel RAISE_NOTRACE ) . eq in Decode . { acc ; acc_op ; push ; pushacc ; push_op ; pop ; assign ; envacc ; envacc_op ; pushenvacc ; pushenvacc_op ; push_retaddr ; apply ; apply_op ; appterm ; appterm_op ; closure ; closurerec ; return ; restart ; grab ; offsetclosure ; offsetclosure_op ; pushoffsetclosure ; pushoffsetclosure_op ; pushgetglobal ; getglobal ; pushgetglobalfield ; getglobalfield ; setglobal ; atom ; atom_op ; pushatom ; pushatom_op ; makeblock ; makeblock_op ; getfield ; getfield_op ; setfield ; setfield_op ; vectlength ; getvectitem ; setvectitem ; getstringchar ; setstringchar ; branch ; branch_op ; boolnot ; pushtrap ; poptrap ; raise_ ; check_signals ; c_call ; c_call_op ; const ; const_op ; pushconst ; pushconst_op ; alu ; alu_op ; comp ; comp_op ; offsetref ; isint ; getmethod ; offsetint ; bcomp ; bcomp_op ; ucomp ; ucomp_op ; bucomp ; bucomp_op ; getpubmet ; getdynmet ; stop ; event ; break ; reraise ; raise_notrace } ; ; |
let alu_int op a b = let a , b , z = msbs a , msbs b , zero ( dbits - 1 ) in mux op [ z ; a +: b ; a -: b ; ( a *+ b ) . [ : dbits - 2 , 0 ] ; z ; z ; a &: b ; a |: b ; a ^: b ; log_shift sll a b . [ : 5 , 0 ] ; log_shift srl a b . [ : 5 , 0 ] ; log_shift sra a b . [ : 5 , 0 ] ] @: vdd ; ; |
let comp_int op a b = let a , b = msbs a , msbs b in zero ( dbits - 2 ) @: mux op [ a ==: b ; a <>: b ; a <+ b ; a <=+ b ; a >+ b ; a >=+ b ] @: vdd ; ; |
let ucomp_int op a b = let a , b = msbs a , msbs b in zero ( dbits - 2 ) @: mux op [ a <: b ; a >: b ] @: vdd ; ; |
module States = struct type t = [ ` init | ` fetch | ` decode | ` acc_set | ` acc_offset | ` pushacc | ` envacc | ` pop | ` constint | ` branch | ` c_call0 | ` c_call1 | ` c_call2 | ` c_call3 | ` alu | ` comp | ` ucomp | ` bcomp | ` bucomp | ` bcomp_setpc | ` closure_nfuncs | ` closure_nvars | ` closure_alloc | ` closure_var_start | ` closure_var_read | ` closure_var_write | ` closure_func_start | ` closure_func_hdr | ` closure_func_pc | ` closure_func_wpc | ` closure_func_stack | ` closure_accu_pc0 | ` closure_accu_pc1 | ` closure_accu_pc2 | ` setglobal | ` getglobal_data | ` getglobal | ` getglobalfield_data | ` getglobalfield | ` makeblock | ` makeblock_alloc | ` makeblock_accu | ` makeblock_read | ` makeblock_write | ` offsetint | ` offsetref0 | ` offsetref1 | ` offsetref2 | ` atom | ` apply_pop_stack | ` apply_push_stack_env | ` apply_push_stack_pc | ` apply_push_stack_args | ` apply_eargs | ` apply | ` appterm0 | ` appterm1 | ` appterm2 | ` appterm3 | ` appterm4 | ` grab | ` push_retaddr0 | ` push_retaddr1 | ` push_retaddr2 | ` push_retaddr3 | ` vectlength | ` getvectitem0 | ` getvectitem1 | ` setvectitem0 | ` setvectitem1 | ` setvectitem2 | ` getstringchar0 | ` getstringchar1 | ` setstringchar0 | ` setstringchar1 | ` setstringchar2 | ` setstringchar3 | ` not_implemented | ` invalid_instruction ] [ @@ deriving sexp_of , compare , enumerate ] end |
let state_str = List . map States . all ~ f ( : fun s -> Sexp . to_string_hum ( States . sexp_of_t s ) ) |
module M = Mlvalues . Make ( struct include Signal let ( /: ) _ _ = failwith " " /: let ( %: ) _ _ = failwith " " %: let const = consti ~ width : dbits let zero = const 0 let one = const 1 let log_shift f a b = if Signal . is_const b then f a ( to_int b ) else log_shift f a b let sll a b = log_shift sll a b . [ : 5 , 0 ] let srl a b = log_shift srl a b . [ : 5 , 0 ] let sra a b = log_shift sra a b . [ : 5 , 0 ] end ) |
let zinc i = let open Memory . O in let open Memory . I in let open Decode in let open I in let open O in let open Always in let e = vdd in let ures x = uresize x dbits in let sres x = sresize x dbits in let val_int x = uresize x ( dbits - 1 ) @: vdd in let val_unit = val_int ( zero dbits ) in let int_val x = sra x 1 in let stack_o = Memory . O . ( map t ~ f ( : fun ( _ , b ) -> Variable . reg ~ enable : e reg_spec ~ width : b ) ) in let mem_o = Memory . O . ( map t ~ f ( : fun ( _ , b ) -> Variable . reg ~ enable : e reg_spec ~ width : b ) ) in let bc_o = Memory . O . ( map t ~ f ( : fun ( _ , b ) -> Variable . reg ~ enable : e reg_spec ~ width : b ) ) in let memory_o , stack_i , bc_i , mem_i = memory_if ~ e ~ stack_o ~ bc_o ~ mem_o ~ ext_i : i . memory_i in let bc_sel = Variable . reg reg_spec ~ enable : e ~ width : 1 in let bc_i = { bc_i with memory_data_in = sres @@ mux2 bc_sel . value bc_i . memory_data_in . [ : 63 , 32 ] bc_i . memory_data_in . [ : 31 , 0 ] } in let pc = Variable . reg reg_spec ~ enable : e ~ width : dbits in let pc_next = pc . value . +: 4 in let sp = Variable . reg reg_spec ~ enable : e ~ width : dbits in let accu = Variable . reg reg_spec ~ enable : e ~ width : dbits in let env = Variable . reg reg_spec ~ enable : e ~ width : dbits in let extra_args = Variable . reg reg_spec ~ enable : e ~ width : dbits in let error = Variable . reg reg_spec ~ enable : e ~ width : 1 in let state = State_machine . create ( module States ) reg_spec ~ enable : e in let n_temps = 3 in let temp = Array . init n_temps ~ f ( : fun i -> let g = Variable . reg reg_spec ~ enable : e ~ width : dbits in ignore ( g . value -- ( " temp_ " ^ Int . to_string i ) : Signal . t ) ; g ) in let clear_temps = proc ( Array . to_list @@ Array . map temp ~ f ( : fun t -> t . <-- 0 ) ) in let shift_temp_up din = proc ( Array . to_list @@ Array . init n_temps ~ f ( : fun i -> temp . ( i ) <-- if i = 0 then din else temp . ( i - 1 ) . value ) ) in let shift_temp_down din = proc ( Array . to_list @@ Array . init n_temps ~ f ( : fun i -> temp . ( i ) <-- if i = n_temps - 1 then din else temp . ( i + 1 ) . value ) ) in let count = let r = Variable . reg reg_spec ~ enable : e ~ width : dbits in ignore ( r . value -- " count " : Signal . t ) ; r in let count_next = count . value . +: 1 -- " count_next " in let alloc_base = Variable . reg reg_spec ~ enable : e ~ width : dbits in let alloc_pointer = Variable . reg reg_spec ~ enable : e ~ width : dbits in let instruction = bc_i . memory_data_in . [ : 7 , 0 ] in let decode = decode instruction in let decode ' = let e = e &: state . is ` decode in Decode . map decode ~ f ( : reg reg_spec ~ enable : e ) in let c_call_request = Variable . reg reg_spec ~ enable : e ~ width : 1 in let c_call_prim = Variable . reg reg_spec ~ enable : e ~ width : dbits in let access_memif mem_i mem_o = let read addr nstate = proc [ mem_o . memory_address <-- addr ; mem_o . memory_request . <-- 1 ; mem_o . memory_read_write . <-- 0 ; state . set_next nstate ] in let write addr data nstate = proc [ mem_o . memory_address <-- addr ; mem_o . memory_data_out <-- data ; mem_o . memory_request . <-- 1 ; mem_o . memory_read_write . <-- 1 ; state . set_next nstate ] in let ready = let ready = ( ~: mem_o . memory_request . value ) |: mem_i . memory_ready in fun f -> when_ ready [ mem_o . memory_request . <-- 0 ; proc ( f mem_i . memory_data_in ) ] in read , write , ready in let read_bytecode , when_bytecode_ready = let read , _ , ready = access_memif bc_i bc_o in let pcaddr = pc . value . [ : dbits - 1 , asft ] @: zero asft in let pcsel = pc . value . [ : 2 , 2 ] in let read nstate = proc [ bc_sel <-- pcsel ; read pcaddr nstate ; pc <-- pc_next ] in read , ready in let read_mem , write_mem , when_mem_ready = access_memif mem_i mem_o in let alloc_block col tag words rstate = proc [ write_mem alloc_base . value ( M . make_header words col tag ) rstate ; alloc_base <-- alloc_base . value +: sll ( words . +: 1 ) asft ; alloc_pointer <-- alloc_base . value . +: bpw ] in let alloc_pointer_next = alloc_pointer . value . +: bpw in let read_stack , write_stack , when_stack_ready = access_memif stack_i stack_o in let push_stack = let sp_next = sp . value . -: bpw in fun data nstate -> proc [ write_stack sp_next data nstate ; sp <-- sp_next ] in let pop_stack = let sp_next = sp . value . +: bpw in fun nstate -> proc [ read_stack sp . value nstate ; sp <-- sp_next ] in let push_stack_accu = push_stack accu . value in let closure_nfuncs = temp . ( 0 ) in let closure_nvars = temp . ( 1 ) in let closure_base_pc = temp . ( 2 ) in let closure_nfuncs_offs = mux2 decode ' . closure ( one dbits ) ( sll ( closure_nfuncs . value -- " nfuncs " ) 1 . -: 1 ) in let closure_blksize = closure_nfuncs_offs +: closure_nvars . value in let makeblock_wosize = temp . ( 0 ) in let makeblock_accu_base = temp . ( 1 ) in let alu_int = alu_int decode ' . alu_op accu . value stack_i . memory_data_in in let bcomp_int = ( comp_int decode ' . bcomp_op bc_i . memory_data_in accu . value ) . [ : 1 , 1 ] in let bucomp_int = ( ucomp_int decode ' . bucomp_op bc_i . memory_data_in accu . value ) . [ : 1 , 1 ] in let comp_int = comp_int decode ' . comp_op accu . value stack_i . memory_data_in in let ucomp_int = ucomp_int decode ' . ucomp_op accu . value stack_i . memory_data_in in let atom_ptr tag = i . atom_table_address +: sll tag asft in let aofs v = sll ( uresize v dbits ) 3 in let bcofs v = sll ( uresize v dbits ) 2 in let hdrp v = v +: aofs ( consti ~ width : dbits ( - 1 ) ) in let get_byte s d = let f n = d . [ ( : 8 * n ) + 7 , 8 * n ] in mux s @@ Array . to_list @@ Array . init 8 ~ f in let set_byte s d b = let f n = insert ~ into : d b ~ at_offset ( : n * 8 ) in mux s @@ Array . to_list @@ Array . init 8 ~ f in compile [ mem_o . memory_read_write . <-- 0 ; mem_o . memory_data_out . <-- 0 ; mem_o . memory_request . <-- 0 ; mem_o . memory_address . <-- 0 ; bc_o . memory_read_write . <-- 0 ; bc_o . memory_data_out . <-- 0 ; state . switch [ ( ` init , [ accu <-- val_unit ; sp <-- i . stack_start_address ; pc <-- i . bytecode_start_address ; alloc_base <-- i . heap_start_address ; env <-- atom_ptr ( zero dbits ) ; extra_args . <-- 0 ; when_ i . start [ state . set_next ` fetch ] ] ) ; ( ` fetch , [ read_bytecode ` decode ; count . <-- 0 ; clear_temps ] ) ; ( ` decode , [ when_bytecode_ready ( fun _ -> [ if_ ( reduce ~ f ( : |: ) [ decode . return ; decode . restart ; decode . offsetclosure ; decode . pushoffsetclosure ; decode . pushtrap ; decode . poptrap ; decode . raise_ ; decode . check_signals ; decode . getmethod ; decode . getpubmet ; decode . getdynmet ; decode . event ; decode . break ; decode . reraise ; decode . raise_notrace ; decode . alu &: ( decode . alu_op . ==: 4 ) ; decode . alu &: ( decode . alu_op . ==: 5 ) ; decode . c_call &: ( decode . c_call_op . ==: 5 ) ; decode . branch &: ( decode . branch_op . ==: 3 ) ; decode . apply &: ( decode . apply_op . ==: 0 ) ; decode . appterm &: ( decode . appterm_op . ==: 0 ) ; decode . makeblock &: ( decode . makeblock_op . ==: 4 ) ] ) [ state . set_next ` not_implemented ] @@ elif decode . acc [ if_ ( msb decode . acc_op ) [ read_bytecode ` acc_offset ] [ read_stack ( sp . value +: aofs decode . acc_op ) ` acc_set ] ] @@ elif ( decode . pushacc |: decode . pushconst |: decode . pushgetglobal |: decode . pushgetglobalfield |: decode . pushatom |: decode . pushenvacc ) [ push_stack_accu ` pushacc ] @@ elif decode . envacc [ read_mem ( env . value +: aofs ( decode . envacc_op . +: 1 ) ) ` envacc ] @@ elif decode . const [ if_ ( msb decode . const_op ) [ read_bytecode ` constint ] [ accu <-- val_int decode . const_op ; state . set_next ` fetch ] ] @@ elif decode . branch [ read_bytecode ` branch ] @@ elif decode . pop [ read_bytecode ` pop ] @@ elif decode . alu [ if_ ( decode . alu_op . ==: 0 ) [ accu <-- val_int ( negate ( msbs accu . value ) ) ; state . set_next ` fetch ] [ pop_stack ` alu ; when_ ( decode . alu_op . ==: 4 ) [ state . set_next ` invalid_instruction ] ; when_ ( decode . alu_op . ==: 5 ) [ state . set_next ` invalid_instruction ] ] ] @@ elif decode . comp [ pop_stack ` comp ] @@ elif decode . ucomp [ pop_stack ` ucomp ] @@ elif decode . bcomp [ read_bytecode ` bcomp ] @@ elif decode . bucomp [ read_bytecode ` bucomp ] @@ elif decode . offsetint [ read_bytecode ` offsetint ] @@ elif decode . offsetref [ read_bytecode ` offsetref0 ] @@ elif decode . isint [ accu <-- ures accu . value . [ : 0 , 0 ] ; state . set_next ` fetch ] @@ elif decode . closure [ read_bytecode ` closure_nvars ] @@ elif decode . closurerec [ read_bytecode ` closure_nfuncs ] @@ elif decode . setglobal [ read_bytecode ` setglobal ] @@ elif ( decode . getglobal |: decode . getglobalfield ) [ read_bytecode ` getglobal_data ] @@ elif decode . makeblock [ if_ ( decode . makeblock_op . ==: 0 ) [ read_bytecode ` makeblock ] [ makeblock_wosize <-- ures decode . makeblock_op ; read_bytecode ` makeblock_alloc ] ] @@ elif decode . c_call [ push_stack env . value ` c_call0 ] @@ elif decode . atom [ if_ decode . atom_op [ read_bytecode ` atom ] [ state . set_next ` atom ] ] @@ elif decode . apply [ if_ decode . apply_op [ state . set_next ` apply_pop_stack ] [ read_bytecode ` apply_eargs ] ] @@ elif decode . appterm [ if_ decode . appterm_op [ temp . ( 0 ) <-- ures decode . appterm_op ; read_bytecode ` appterm1 ] [ read_bytecode ` appterm0 ] ] @@ elif decode . grab [ read_bytecode ` grab ] @@ elif decode . stop [ state . set_next ` invalid_instruction ] @@ elif decode . push_retaddr [ read_bytecode ` push_retaddr0 ] @@ elif decode . vectlength [ read_mem ( hdrp accu . value ) ` vectlength ] @@ elif decode . getvectitem [ pop_stack ` getvectitem0 ] @@ elif decode . setvectitem [ pop_stack ` setvectitem0 ] @@ elif decode . getstringchar [ pop_stack ` getstringchar0 ] @@ elif decode . setstringchar [ pop_stack ` setstringchar0 ] @@ elif decode . boolnot [ accu <-- val_int ( ~: accu . value . [ : 1 , 1 ] ) ; state . set_next ` fetch ] [ state . set_next ` invalid_instruction ] ] ) ] ) ; ( ` acc_offset , [ when_bytecode_ready ( fun offset -> [ read_stack ( sp . value +: aofs offset ) ` acc_set ] ) ] ) ; ( ` acc_set , [ when_stack_ready ( fun data -> [ accu <-- data ; state . set_next ` fetch ] ) ] ) ; ( ` pushacc , [ when_stack_ready ( fun _ -> [ if_ decode ' . pushconst [ if_ ( msb decode ' . pushconst_op ) [ read_bytecode ` constint ] [ accu <-- val_int decode ' . pushconst_op ; state . set_next ` fetch ] ] @@ elif decode ' . push [ state . set_next ` fetch ] @@ elif decode ' . pushenvacc [ read_mem ( env . value +: aofs ( decode ' . pushenvacc_op . +: 1 ) ) ` envacc ] @@ elif ( decode ' . pushgetglobal |: decode ' . pushgetglobalfield ) [ read_bytecode ` getglobal_data ] @@ elif decode ' . pushatom [ if_ decode ' . pushatom_op [ read_bytecode ` atom ] [ state . set_next ` atom ] ] [ if_ ( msb decode ' . push_op ) [ read_bytecode ` acc_offset ] [ read_stack ( sp . value +: aofs decode ' . push_op ) ` acc_set ] ] ] ) ] ) ; ( ` envacc , [ when_mem_ready ( fun data -> [ accu <-- data ; state . set_next ` fetch ; when_ ( decode ' . envacc &: ( decode ' . envacc_op . ==: 4 ) |: ( decode ' . pushenvacc &: ( decode ' . pushenvacc_op . ==: 4 ) ) ) [ state . set_next ` invalid_instruction ] ] ) ] ) ; ( ` pop , [ when_bytecode_ready ( fun offset -> [ sp <-- sp . value +: aofs offset ; state . set_next ` fetch ] ) ] ) ; ( ` constint , [ when_bytecode_ready ( fun data -> [ accu <-- val_int data ; state . set_next ` fetch ] ) ] ) ; ( ` branch , [ when_bytecode_ready ( fun data -> [ pc <-- pc . value +: bcofs ( data . -: 1 ) ; state . set_next ` fetch ] ) ] ) ; ( ` alu , [ when_stack_ready ( fun _ -> [ accu <-- alu_int ; state . set_next ` fetch ] ) ] ) ; ( ` comp , [ when_stack_ready ( fun _ -> [ accu <-- comp_int ; state . set_next ` fetch ] ) ] ) ; ( ` ucomp , [ when_stack_ready ( fun _ -> [ accu <-- ucomp_int ; state . set_next ` fetch ] ) ] ) ; ( ` bcomp , [ when_bytecode_ready ( fun _ -> [ if_ bcomp_int [ read_bytecode ` bcomp_setpc ] [ pc <-- pc_next ; state . set_next ` fetch ] ] ) ] ) ; ( ` bucomp , [ when_bytecode_ready ( fun _ -> [ if_ bucomp_int [ read_bytecode ` bcomp_setpc ] [ pc <-- pc_next ; state . set_next ` fetch ] ] ) ] ) ; ( ` bcomp_setpc , [ when_bytecode_ready ( fun data -> [ pc <-- pc . value +: bcofs ( data . -: 1 ) ; state . set_next ` fetch ] ) ] ) ; ( ` makeblock , [ when_bytecode_ready ( fun wosize -> [ makeblock_wosize <-- wosize ; read_bytecode ` makeblock_alloc ] ) ] ) ; ( ` makeblock_alloc , [ when_bytecode_ready ( fun tag -> [ alloc_block M . black ( ures tag . [ : 7 , 0 ] ) makeblock_wosize . value ` makeblock_accu ] ) ] ) ; ( ` makeblock_accu , [ when_mem_ready ( fun _ -> [ makeblock_accu_base <-- alloc_pointer . value ; count <-- count_next ; alloc_pointer <-- alloc_pointer_next ; write_mem alloc_pointer . value accu . value ` makeblock_read ] ) ] ) ; ( ` makeblock_read , [ when_mem_ready ( fun _ -> [ if_ ( count . value ==: makeblock_wosize . value ) [ accu <-- makeblock_accu_base . value ; state . set_next ` fetch ] [ pop_stack ` makeblock_write ] ] ) ] ) ; ( ` makeblock_write , [ when_stack_ready ( fun data -> [ count <-- count_next ; alloc_pointer <-- alloc_pointer_next ; write_mem alloc_pointer . value ( mux2 ( count . value . ==: 0 ) accu . value data ) ` makeblock_read ] ) ] ) ; ( ` closure_nfuncs , [ when_bytecode_ready ( fun data -> [ closure_nfuncs <-- data ; read_bytecode ` closure_nvars ] ) ] ) ; ( ` closure_nvars , [ when_bytecode_ready ( fun data -> [ closure_nvars <-- data ; if_ ( data . >: 0 ) [ push_stack_accu ` closure_alloc ] [ state . set_next ` closure_alloc ] ] ) ] ) ; ( ` closure_alloc , [ when_stack_ready ( fun _ -> [ alloc_block M . black M . closure_tag closure_blksize ` closure_var_start ] ) ] ) ; ( ` closure_var_start , [ accu <-- alloc_pointer . value ; when_mem_ready ( fun _ -> [ count . <-- 0 ; if_ ( closure_nvars . value . <>: 0 ) [ state . set_next ` closure_var_read ] @@ elif decode ' . closure [ read_bytecode ` closure_accu_pc1 ] [ state . set_next ` closure_func_start ] ] ) ] ) ; ( ` closure_var_read , [ when_mem_ready ( fun _ -> [ pop_stack ` closure_var_write ] ) ] ) ; ( ` closure_var_write , [ when_stack_ready ( fun data -> let addr = alloc_pointer . value +: aofs ( count . value +: closure_nfuncs_offs ) in [ write_mem addr data ` closure_var_read ; count <-- count_next ; when_ ( count_next ==: closure_nvars . value ) [ if_ decode ' . closure [ state . set_next ` closure_accu_pc0 ] [ state . set_next ` closure_func_start ] ] ] ) ] ) ; ( ` closure_func_start , [ count . <-- 0 ; closure_base_pc <-- pc . value ; when_mem_ready ( fun _ -> [ read_bytecode ` closure_func_wpc ] ) ] ) ; ( ` closure_func_hdr , let data = M . make_header ( sll count . value 1 ) M . white M . infix_tag in [ when_stack_ready ( fun _ -> [ alloc_pointer <-- alloc_pointer_next ; if_ ( count . value ==: closure_nfuncs . value ) [ state . set_next ` fetch ] [ write_mem alloc_pointer . value data ` closure_func_pc ] ] ) ] ) ; ( ` closure_func_pc , [ when_mem_ready ( fun _ -> [ read_bytecode ` closure_func_wpc ] ) ] ) ; ( ` closure_func_wpc , [ when_bytecode_ready ( fun data -> [ alloc_pointer <-- alloc_pointer_next ; write_mem alloc_pointer . value ( closure_base_pc . value +: bcofs data ) ` closure_func_stack ] ) ] ) ; ( ` closure_func_stack , let data = mux2 ( count . value . ==: 0 ) accu . value ( alloc_pointer . value +: ( aofs ( sll count . value 1 ) . +: 1 ) ) in [ when_mem_ready ( fun _ -> [ count <-- count_next ; push_stack data ` closure_func_hdr ] ) ] ) ; ( ` closure_accu_pc0 , [ when_mem_ready ( fun _ -> [ read_bytecode ` closure_accu_pc1 ] ) ] ) ; ( ` closure_accu_pc1 , [ when_bytecode_ready ( fun ofs -> [ write_mem accu . value ( pc . value +: bcofs ( ofs . -: 1 ) ) ` closure_accu_pc2 ] ) ] ) ; ` closure_accu_pc2 , [ when_mem_ready ( fun _ -> [ state . set_next ` fetch ] ) ] ; ( ` setglobal , [ when_bytecode_ready ( fun ofs -> [ write_mem ( i . globals_start_address +: aofs ofs ) accu . value ` fetch ; accu <-- val_unit ] ) ] ) ; ( ` getglobal_data , [ when_bytecode_ready ( fun ofs -> [ read_mem ( i . globals_start_address +: aofs ofs ) ` getglobal ] ) ] ) ; ( ` getglobal , [ when_mem_ready ( fun data -> [ accu <-- data ; if_ ( decode ' . getglobalfield |: decode ' . pushgetglobalfield ) [ read_bytecode ` getglobalfield_data ] [ state . set_next ` fetch ] ] ) ] ) ; ( ` getglobalfield_data , [ when_bytecode_ready ( fun ofs -> [ read_mem ( accu . value +: aofs ofs ) ` getglobalfield ] ) ] ) ; ( ` getglobalfield , [ when_mem_ready ( fun data -> [ accu <-- data ; state . set_next ` fetch ] ) ] ) ; ` c_call0 , [ when_stack_ready ( fun _ -> [ read_bytecode ` c_call1 ] ) ] ; ( ` c_call1 , [ when_bytecode_ready ( fun prim -> [ c_call_prim <-- prim ; if_ ( decode ' . c_call_op . ==: 5 ) [ state . set_next ` invalid_instruction ] [ c_call_request . <-- 1 ; state . set_next ` c_call2 ] ] ) ] ) ; ( ` c_call2 , [ when_ i . c_call_ready [ c_call_request . <-- 0 ; accu <-- i . c_call_result ; pop_stack ` c_call3 ] ] ) ; ( ` c_call3 , [ when_stack_ready ( fun _ -> [ sp <-- sp . value +: aofs decode ' . c_call_op ; state . set_next ` fetch ] ) ] ) ; ( ` offsetint , [ when_bytecode_ready ( fun data -> [ accu <-- accu . value +: sll data 1 ; state . set_next ` fetch ] ) ] ) ; ( ` offsetref0 , [ when_bytecode_ready ( fun data -> [ temp . ( 0 ) <-- data ; read_mem accu . value ` offsetref1 ] ) ] ) ; ( ` offsetref1 , [ when_mem_ready ( fun data -> [ write_mem accu . value ( data +: sll temp . ( 0 ) . value 1 ) ` offsetref2 ] ) ] ) ; ( ` offsetref2 , [ when_mem_ready ( fun _ -> [ accu <-- val_unit ; state . set_next ` fetch ] ) ] ) ; ( ` atom , let get_tag ofs = mux2 ( decode ' . atom &: decode ' . atom_op |: ( decode ' . pushatom &: decode ' . pushatom_op ) ) ofs ( zero dbits ) in [ when_bytecode_ready ( fun ofs -> [ accu <-- atom_ptr ( get_tag ofs ) ; state . set_next ` fetch ] ) ] ) ; ( ` apply_pop_stack , [ when_stack_ready ( fun d -> [ shift_temp_up d ; count <-- count_next ; if_ ( count . value ==: ures decode ' . apply_op ) [ count . <-- 0 ; push_stack ( val_int extra_args . value ) ` apply_push_stack_env ; extra_args <-- ures ( decode ' . apply_op . -: 1 ) ] [ pop_stack ` apply_pop_stack ] ] ) ] ) ; ( ` apply_push_stack_env , [ when_stack_ready ( fun _ -> [ push_stack env . value ` apply_push_stack_pc ] ) ] ) ; ( ` apply_push_stack_pc , [ when_stack_ready ( fun _ -> [ push_stack pc . value ` apply_push_stack_args ] ) ] ) ; ( ` apply_push_stack_args , [ when_stack_ready ( fun _ -> [ shift_temp_down ( zero dbits ) ; count <-- count_next ; if_ ( count . value ==: ures decode ' . apply_op ) [ read_mem accu . value ` apply ] [ push_stack temp . ( 0 ) . value ` apply_push_stack_args ] ] ) ] ) ; ( ` apply_eargs , [ when_bytecode_ready ( fun earg -> [ extra_args <-- mux2 ( decode ' . apply_op . ==: 0 ) ( earg . -: 1 ) ( zero dbits ) ; pc <-- accu . value ; state . set_next ` fetch ] ) ] ) ; ( ` apply , [ when_mem_ready ( fun pc ' -> [ pc <-- pc ' ; env <-- accu . value ; state . set_next ` fetch ] ) ] ) ; ( ` appterm0 , [ when_bytecode_ready ( fun nargs -> [ temp . ( 0 ) <-- nargs ; read_bytecode ` appterm1 ] ) ] ) ; ( ` appterm1 , [ when_bytecode_ready ( fun slotsize -> [ temp . ( 1 ) <-- sp . value +: aofs ( slotsize -: temp . ( 0 ) . value ) ; count <-- temp . ( 0 ) . value . -: 1 ; state . set_next ` appterm2 ] ) ] ) ; ( ` appterm2 , [ when_stack_ready ( fun _ -> [ if_ ( count . value . ==: - 1 ) [ read_mem accu . value ` appterm4 ] [ read_stack ( sp . value +: aofs count . value ) ` appterm3 ] ] ) ] ) ; ( ` appterm3 , [ when_stack_ready ( fun d -> [ write_stack ( temp . ( 1 ) . value +: aofs count . value ) d ` appterm2 ; count <-- count . value . -: 1 ] ) ] ) ; ( ` appterm4 , [ when_mem_ready ( fun pcn -> [ sp <-- temp . ( 1 ) . value ; pc <-- pcn ; env <-- accu . value ; extra_args <-- extra_args . value +: temp . ( 0 ) . value . -: 1 ; state . set_next ` fetch ] ) ] ) ; ( ` grab , [ when_bytecode_ready ( fun reqd -> [ if_ ( extra_args . value >=: reqd ) [ extra_args <-- extra_args . value -: reqd ; state . set_next ` fetch ] [ state . set_next ` invalid_instruction ] ] ) ] ) ; ( ` push_retaddr0 , [ when_bytecode_ready ( fun ofs -> [ push_stack ( pc . value +: aofs ofs ) ` push_retaddr1 ] ) ] ) ; ( ` push_retaddr1 , [ when_stack_ready ( fun _ -> [ push_stack env . value ` push_retaddr2 ] ) ] ) ; ( ` push_retaddr2 , [ when_stack_ready ( fun _ -> [ push_stack ( val_int extra_args . value ) ` push_retaddr3 ] ) ] ) ; ` push_retaddr3 , [ when_stack_ready ( fun _ -> [ state . set_next ` fetch ] ) ] ; ( ` vectlength , [ when_mem_ready ( fun d -> [ accu <-- val_int ( srl d 10 ) ] ) ] ) ; ( ` getvectitem0 , [ when_stack_ready ( fun ofs -> [ read_mem ( accu . value +: aofs ofs ) ` getvectitem1 ] ) ] ) ; ( ` getvectitem1 , [ when_mem_ready ( fun data -> [ accu <-- data ; state . set_next ` fetch ] ) ] ) ; ( ` setvectitem0 , [ when_stack_ready ( fun d -> [ temp . ( 0 ) <-- d ; pop_stack ` setvectitem1 ] ) ] ) ; ( ` setvectitem1 , [ when_stack_ready ( fun d -> [ write_mem ( accu . value +: aofs ( int_val temp . ( 0 ) . value ) ) d ` fetch ] ) ] ) ; ( ` setvectitem2 , [ when_mem_ready ( fun _ -> [ accu <-- val_unit ; state . set_next ` fetch ] ) ] ) ; ( ` getstringchar0 , [ when_stack_ready ( fun d -> [ temp . ( 0 ) <-- d ; read_mem accu . value ` getstringchar1 ] ) ] ) ; ( ` getstringchar0 , [ when_stack_ready ( fun d -> [ accu <-- val_int @@ get_byte temp . ( 0 ) . value . [ : 3 , 1 ] d ; state . set_next ` fetch ] ) ] ) ; ( ` setstringchar0 , [ when_stack_ready ( fun d -> [ temp . ( 0 ) <-- d ; pop_stack ` setstringchar1 ] ) ] ) ; ( ` setstringchar1 , [ when_stack_ready ( fun d -> [ temp . ( 1 ) <-- d ; read_mem accu . value ` setstringchar2 ] ) ] ) ; ( ` setstringchar2 , [ when_mem_ready ( fun d -> [ write_mem accu . value ( set_byte temp . ( 1 ) . value . [ : 3 , 1 ] d temp . ( 0 ) . value . [ : 8 , 1 ] ) ` setstringchar3 ] ) ] ) ; ` setstringchar3 , [ when_mem_ready ( fun _ -> [ state . set_next ` fetch ] ) ] ; ` not_implemented , [ error . <-- 1 ] ; ` invalid_instruction , [ error . <-- 1 ] ] ] ; { state = state . current ; pc = pc . value ; sp = sp . value ; accu = accu . value ; env = env . value ; extra_args = extra_args . value ; instruction = mux2 ( state . is ` decode &: bc_i . memory_ready ) instruction ( consti ~ width : 8 255 ) ; error = error . value ; memory_o ; decode = decode ' ; c_call_request = c_call_request . value ; c_call_prim = c_call_prim . value } ; ; |
module Z = Cyclesim . With_interface ( Zinc . I ) ( Zinc . O ) |
type cfg = { waves : bool ; instr_trace : bool ; state_trace : bool ; mem_trace : bool } |
let make cfg exe = let mem_size_words = 1024 * 1024 in let _show_instr = let ins = Base . List . map Opcode . all ~ f : Opcode . to_string |> Base . Array . of_list in fun x -> let i = Bits . to_int x in try ins . ( i ) with | _ -> " " in let sim = Z . create Zinc . zinc in let waves , sim = if cfg . waves then ( let waves , sim = Waveform . create sim in Some waves , sim ) else None , sim in let open Zinc . Memory . I in let open Zinc . Memory . O in let open Zinc . I in let open Zinc . O in let i = Zinc . I . map ( Cyclesim . inputs sim ) ~ f ( : fun i d -> i := Bits . consti ~ width ( : Bits . width ! i ) d ) in let i64 = Zinc . I . map ( Cyclesim . inputs sim ) ~ f ( : fun i d -> i := Bits . consti64 ~ width ( : Bits . width ! i ) d ) in let o = Zinc . O . map ( Cyclesim . outputs sim ) ~ f ( : fun o ( ) -> Bits . to_int ! o ) in let n = Zinc . O . map ( Cyclesim . outputs ~ clock_edge : After sim ) ~ f ( : fun o ( ) -> Bits . to_int ! o ) in let n64 = Zinc . O . map ( Cyclesim . outputs ~ clock_edge : After sim ) ~ f ( : fun o ( ) -> Bits . to_int64 ! o ) in let o64 = Zinc . O . map ( Cyclesim . outputs sim ) ~ f ( : fun o ( ) -> Bits . to_int ! o |> Int64 . of_int ) in let mapping , memory = init_memory exe mem_size_words in let trace ( ) = Trace . machine { Machine . empty with memory ; mapping ; env = o64 . env ( ) ; sp = o64 . sp ( ) ; accu = o64 . sp ( ) } in Cyclesim . reset sim ; i . bytecode_start_address mapping . code_address ; i . atom_table_address ( mapping . atoms_address + 8 ) ; i . globals_start_address ( mapping . globals_address + 8 ) ; i . heap_start_address mapping . heap_address ; i . stack_start_address mapping . stack_address ; i . start 1 ; let log_mem_access cycle rw addr data sp = if cfg . mem_trace then ( let offs , typ = if addr < mapping . atoms_address then ( addr - 0 ) * 2 , " BYTE " else if addr < mapping . globals_address then addr - mapping . atoms_address , " ATOM " else if addr < mapping . heap_address then addr - mapping . globals_address , " GLBL " else if addr >= sp - 8 then mapping . stack_address - addr - 1 , " STCK " else addr - mapping . heap_address , " HEAP " in printf " [ %- 8i ] % s % s [ . @% 8x | . % 8x ] = . % 16Lx [ sp =% i ] \ n " cycle ( if rw = 0 then " R " else " W " ) typ addr offs data sp ) in let run ( ) = let cycle = ref 0 in let stop = ref false in let instr_no = ref 1 in while ( not ! stop ) && o . error ( ) <> 1 do if o . state ( ) = 2 then ( try if cfg . state_trace then printf " \ n ##% i \ n " ! instr_no ; incr instr_no ; if cfg . instr_trace then printf " % 6i % s \ n " %! ( ( o . pc ( ) / 4 ) - 1 ) ( o . instruction ( ) |> Opcode . of_int |> Opcode . to_string ) ; if cfg . state_trace then trace ( ) with | _ -> stop := true ; printf " INVALID \ n " ) ; %! Cyclesim . cycle sim ; i . memory_i . memory_ready 0 ; if n . memory_o . memory_request ( ) <> 0 then ( let addr = n . memory_o . memory_address ( ) in let rw = n . memory_o . memory_read_write ( ) in let sp = o . sp ( ) in if rw = 0 then ( let data = memory . { addr lsr 3 } in log_mem_access ! cycle rw addr data sp ; i64 . memory_i . memory_data_in data ) else ( let data = n64 . memory_o . memory_data_out ( ) in log_mem_access ! cycle rw addr data sp ; memory . { addr lsr 3 } <- data ) ; i . memory_i . memory_ready 1 ) ; i . c_call_ready 0 ; if n . c_call_request ( ) = 1 then ( let prim = n . c_call_prim ( ) in if cfg . instr_trace then Printf . printf " c_call_request : [ % i ] % s \ n " prim exe . Load . prim . ( prim ) ; let value = match C_runtime . run exe prim { Machine . empty with Machine . env = o64 . env ( ) ; accu = o64 . accu ( ) ; sp = o64 . sp ( ) ; memory } with | ` ok v -> v | ` exn _ -> failwith " c - call exn not implemented " in i64 . c_call_result value ; i . c_call_ready 1 ) ; i . start 0 ; incr cycle done in let ( ) = try run ( ) with | Failure x -> printf " \ n \ nEXN : % s \ n \ n " %! x | _ -> printf " \ n \ nEXN % s \ n \ n " %! ( Printexc . get_backtrace ( ) ) in match waves with | None -> ( ) | Some waves -> Hardcaml_waveterm_interactive . run waves ; ; |
let read2 ic = let lb = read1 ic in let hb = read1 ic in lb lor ( hb lsl 8 ) 8 |
let read4 ic = let lw = read2 ic in let hw = read2 ic in Int32 . logor ( Int32 . of_int lw ) lw ( Int32 . shift_left ( Int32 . of_int hw ) hw 16 ) 16 |
let read4_int ic = let lw = read2 ic in let hw = read2 ic in if hw > max_int lsr 16 then raise ( Error ( Error " " , " " , " 32 - bit data too large ) ) " ; lw lor ( hw lsl 16 ) 16 |
let readstring ic n = let s = Bytes . create n in really_input ic s 0 n ; Bytes . to_string s |
let write2 oc n = write1 oc n ; write1 oc ( n lsr 8 ) 8 |
let write4 oc n = write2 oc ( Int32 . to_int n ) n ; write2 oc ( Int32 . to_int ( Int32 . shift_right_logical n 16 ) 16 ) 16 |
let write4_int oc n = write2 oc n ; write2 oc ( n lsr 16 ) 16 |
let writestring oc s = output oc ( Bytes . of_string s ) s 0 ( String . length s ) s |
let writebytes oc s = output oc s 0 ( Bytes . length s ) s |
type compression_method = Stored | Deflated |
type entry = { filename : string ; extra : string ; comment : string ; methd : compression_method ; mtime : float ; crc : int32 ; uncompressed_size : int ; compressed_size : int ; is_directory : bool ; file_offset : int64 } |
type in_file = { if_filename : string ; if_channel : Pervasives . in_channel ; if_entries : entry list ; if_directory : ( string , entry ) entry Hashtbl . t ; if_comment : string } |
let entries ifile = ifile . if_entries |
let comment ifile = ifile . if_comment |
type out_file = { of_filename : string ; of_channel : Pervasives . out_channel ; mutable of_entries : entry list ; of_comment : string } |
let strrstr pattern buf ofs len = let rec search i j = if i < ofs then - 1 else if j >= String . length pattern then i else if pattern [ . j ] j = buf [ . i + j ] j then search i ( j + 1 ) 1 else search ( i - 1 ) 1 0 in search ( ofs + len - String . length pattern ) pattern 0 |
let filename_is_directory name = String . length name > 0 && name [ . String . length name - 1 ] 1 = ' / ' |
let unixtime_of_dostime time date = fst ( fstUnix . mktime { Unix . tm_sec = ( time lsl 1 ) 1 land 0x3e ; Unix . tm_min = ( time lsr 5 ) 5 land 0x3f ; Unix . tm_hour = ( time lsr 11 ) 11 land 0x1f ; Unix . tm_mday = date land 0x1f ; Unix . tm_mon = ( ( date lsr 5 ) 5 land 0xf ) 0xf - 1 ; Unix . tm_year = ( ( date lsr 9 ) 9 land 0x7f ) 0x7f + 80 ; Unix . tm_wday = 0 ; Unix . tm_yday = 0 ; Unix . tm_isdst = false } ) |
let dostime_of_unixtime t = let tm = Unix . localtime t in ( tm . Unix . tm_sec lsr 1 + ( tm . Unix . tm_min lsl 5 ) 5 + ( tm . Unix . tm_hour lsl 11 ) 11 , tm . Unix . tm_mday + ( tm . Unix . tm_mon + 1 ) 1 lsl 5 + ( tm . Unix . tm_year - 80 ) 80 lsl 9 ) 9 |
let read_ecd filename ic = let buf = Bytes . create 256 in let filelen = in_channel_length ic in let rec find_ecd pos len = if pos <= 0 || filelen - pos >= 0x10000 then raise ( Error ( Errorfilename , " " , " end of central directory not found , not a ZIP file ) ) " ; let toread = min pos 128 in Bytes . blit buf 0 buf toread ( 256 - toread ) toread ; let newpos = pos - toread in seek_in ic newpos ; really_input ic buf 0 toread ; let newlen = min ( toread + len ) len 256 in let ofs = strrstr " PK \ 005 \ 006 " ( Bytes . to_string buf ) buf 0 newlen in if ofs < 0 || newlen < 22 || ( let comment_len = Char . code ( Bytes . get buf ( ofs + 20 ) 20 ) 20 lor ( Char . code ( Bytes . get buf ( ofs + 21 ) 21 ) 21 lsl 8 ) 8 in newpos + ofs + 22 + comment_len <> filelen ) filelen then find_ecd newpos newlen else newpos + ofs in seek_in ic ( find_ecd filelen 0 ) 0 ; let magic = read4 ic in let disk_no = read2 ic in let cd_disk_no = read2 ic in let _disk_entries = read2 ic in let cd_entries = read2 ic in let cd_size = read4 ic in let cd_offset = read4 ic in let comment_len = read2 ic in let comment = readstring ic comment_len in assert ( magic = Int32 . of_int 0x06054b50 ) 0x06054b50 ; if disk_no <> 0 || cd_disk_no <> 0 then raise ( Error ( Errorfilename , " " , " multi - disk ZIP files not supported ) ) " ; ( cd_entries , cd_size , cd_offset , comment ) comment |
let read_cd filename ic cd_entries cd_offset cd_bound = let cd_bound = Int64 . of_int32 cd_bound in try LargeFile . seek_in ic ( Int64 . of_int32 cd_offset ) cd_offset ; let e = ref [ ] in let entrycnt = ref 0 in while ( LargeFile . pos_in ic < cd_bound ) cd_bound do incr entrycnt ; let magic = read4 ic in let _version_made_by = read2 ic in let _version_needed = read2 ic in let flags = read2 ic in let methd = read2 ic in let lastmod_time = read2 ic in let lastmod_date = read2 ic in let crc = read4 ic in let compr_size = read4_int ic in let uncompr_size = read4_int ic in let name_len = read2 ic in let extra_len = read2 ic in let comment_len = read2 ic in let _disk_number = read2 ic in let _internal_attr = read2 ic in let _external_attr = read4 ic in let header_offset = Int64 . of_int32 ( of_int32read4 ic ) ic in let name = readstring ic name_len in let extra = readstring ic extra_len in let comment = readstring ic comment_len in if magic <> Int32 . of_int 0x02014b50 then raise ( Error ( Errorfilename , name , " wrong file header in central directory ) ) " ; if flags land 1 <> 0 then raise ( Error ( Errorfilename , name , " encrypted entries not supported ) ) " ; e := { filename = name ; extra = extra ; comment = comment ; methd = ( match methd with 0 -> Stored | 8 -> Deflated | _ -> raise ( Error ( Errorfilename , name , " unknown compression method ) ) ) " ; mtime = unixtime_of_dostime lastmod_time lastmod_date ; crc = crc ; uncompressed_size = uncompr_size ; compressed_size = compr_size ; is_directory = filename_is_directory name ; file_offset = header_offset } :: ! e done ; assert ( assert ( assertcd_bound = ( LargeFile . pos_in ic ) ic ) ic && ( cd_entries = 65535 || ! entrycnt = cd_entries ) cd_entries ) cd_entries ; List . rev ! e with End_of_file -> raise ( Error ( Errorfilename , " " , " end - of - file while reading central directory ) ) " |
let open_in filename = let ic = Pervasives . open_in_bin filename in let ( cd_entries , cd_size , cd_offset , cd_comment ) cd_comment = read_ecd filename ic in let entries = read_cd filename ic cd_entries cd_offset ( Int32 . add cd_offset cd_size ) cd_size in let dir = Hashtbl . create ( cd_entries / 3 ) 3 in List . iter ( fun e -> Hashtbl . add dir e . filename e ) e entries ; { if_filename = filename ; if_channel = ic ; if_entries = entries ; if_directory = dir ; if_comment = cd_comment } |
let close_in ifile = Pervasives . close_in ifile . if_channel |
let find_entry ifile name = Hashtbl . find ifile . if_directory name |
let goto_entry ifile e = try let ic = ifile . if_channel in LargeFile . seek_in ic e . file_offset ; let magic = read4 ic in let _version_needed = read2 ic in let _flags = read2 ic in let _methd = read2 ic in let _lastmod_time = read2 ic in let _lastmod_date = read2 ic in let _crc = read4 ic in let _compr_size = read4_int ic in let _uncompr_size = read4_int ic in let filename_len = read2 ic in let extra_len = read2 ic in if magic <> Int32 . of_int 0x04034b50 then raise ( Error ( Errorifile . if_filename , e . filename , " wrong local file header ) ) " ; LargeFile . seek_in ifile . if_channel ( Int64 . add e . file_offset ( Int64 . of_int ( 30 + filename_len + extra_len ) extra_len ) extra_len ) extra_len with End_of_file -> raise ( Error ( Errorifile . if_filename , e . filename , " truncated local file header ) ) " |
let read_entry ifile e = try goto_entry ifile e ; let res = Bytes . create e . uncompressed_size in match e . methd with Stored -> if e . compressed_size <> e . uncompressed_size then raise ( Error ( Errorifile . if_filename , e . filename , " wrong size for stored entry ) ) " ; really_input ifile . if_channel res 0 e . uncompressed_size ; Bytes . to_string res | Deflated -> let in_avail = ref e . compressed_size in let out_pos = ref 0 in begin try Zlib . uncompress ~ header : false ( fun buf -> let read = input ifile . if_channel buf 0 ( min ! in_avail ( Bytes . length buf ) buf ) buf in in_avail := ! in_avail - read ; read ) read ( fun buf len -> if ! out_pos + len > Bytes . length res then raise ( Error ( Errorifile . if_filename , e . filename , " wrong size for deflated entry ( too much data ) data ) ) " ; Bytes . blit buf 0 res ! out_pos len ; out_pos := ! out_pos + len ) len with Failure ( Failure_ ) Failure_ -> raise ( Error ( Errorifile . if_filename , e . filename , " decompression error ) ) " end ; if ! out_pos <> Bytes . length res then raise ( Error ( Errorifile . if_filename , e . filename , " wrong size for deflated entry ( not enough data ) data ) ) " ; let crc = Zlib . update_crc Int32 . zero res 0 ( Bytes . length res ) res in if crc <> e . crc then raise ( Error ( Errorifile . if_filename , e . filename , " CRC mismatch ) ) " ; Bytes . to_string res with End_of_file -> raise ( Error ( Errorifile . if_filename , e . filename , " truncated data ) ) " |
let copy_entry_to_channel ifile e oc = try goto_entry ifile e ; match e . methd with Stored -> if e . compressed_size <> e . uncompressed_size then raise ( Error ( Errorifile . if_filename , e . filename , " wrong size for stored entry ) ) " ; let buf = Bytes . create 4096 in let rec copy n = if n > 0 then begin let r = input ifile . if_channel buf 0 ( min n ( Bytes . length buf ) buf ) buf in output oc buf 0 r ; copy ( n - r ) r end in copy e . uncompressed_size | Deflated -> let in_avail = ref e . compressed_size in let crc = ref Int32 . zero in begin try Zlib . uncompress ~ header : false ( fun buf -> let read = input ifile . if_channel buf 0 ( min ! in_avail ( Bytes . length buf ) buf ) buf in in_avail := ! in_avail - read ; read ) read ( fun buf len -> output oc buf 0 len ; crc := Zlib . update_crc ! crc buf 0 len ) len with Failure _ -> raise ( Error ( Errorifile . if_filename , e . filename , " decompression error ) ) " end ; if ! crc <> e . crc then raise ( Error ( Errorifile . if_filename , e . filename , " CRC mismatch ) ) " with End_of_file -> raise ( Error ( Errorifile . if_filename , e . filename , " truncated data ) ) " |
let copy_entry_to_file ifile e outfilename = let oc = open_out_bin outfilename in try copy_entry_to_channel ifile e oc ; close_out oc ; begin try Unix . utimes outfilename e . mtime e . mtime with Unix . Unix_error ( Unix_error_ , _ , _ ) _ | Invalid_argument _ -> ( ) end with x -> close_out oc ; Sys . remove outfilename ; raise x |
let open_out ( ? comment = ) " " filename = if String . length comment >= 0x10000 then raise ( raiseError ( raiseErrorfilename , " " , " comment too long ) ) " ; { of_filename = filename ; of_channel = Pervasives . open_out_bin filename ; of_entries = [ ] ; of_comment = comment } |
let write_directory_entry oc e = write4 oc ( Int32 . of_int 0x02014b50 ) 0x02014b50 ; let version = match e . methd with Stored -> 10 | Deflated -> 20 in write2 oc version ; write2 oc version ; write2 oc 8 ; write2 oc ( match e . methd with Stored -> 0 | Deflated -> 8 ) 8 ; let ( time , date ) date = dostime_of_unixtime e . mtime in write2 oc time ; write2 oc date ; write4 oc e . crc ; write4_int oc e . compressed_size ; write4_int oc e . uncompressed_size ; write2 oc ( String . length e . filename ) filename ; write2 oc ( String . length e . extra ) extra ; write2 oc ( String . length e . comment ) comment ; write2 oc 0 ; write2 oc 0 ; write4_int oc 0 ; write4 oc ( Int64 . to_int32 e . file_offset ) file_offset ; writestring oc e . filename ; writestring oc e . extra ; writestring oc e . comment |
let close_out ofile = let oc = ofile . of_channel in let start_cd = pos_out oc in List . iter ( write_directory_entry oc ) oc ( List . rev ofile . of_entries ) of_entries ; let cd_size = pos_out oc - start_cd in let num_entries = List . length ofile . of_entries in if num_entries >= 0x10000 then raise ( raiseError ( raiseErrorofile . of_filename , " " , " too many entries ) ) " ; write4 oc ( Int32 . of_int 0x06054b50 ) 0x06054b50 ; write2 oc 0 ; write2 oc 0 ; write2 oc num_entries ; write2 oc num_entries ; write4_int oc cd_size ; write4_int oc start_cd ; write2 oc ( String . length ofile . of_comment ) of_comment ; writestring oc ofile . of_comment ; Pervasives . close_out oc |
let add_entry_header ofile extra comment level mtime filename = if level < 0 || level > 9 then raise ( raiseError ( raiseErrorofile . of_filename , filename , " wrong compression level ) ) " ; if String . length filename >= 0x10000 then raise ( raiseError ( raiseErrorofile . of_filename , filename , " filename too long ) ) " ; if String . length extra >= 0x10000 then raise ( raiseError ( raiseErrorofile . of_filename , filename , " extra data too long ) ) " ; if String . length comment >= 0x10000 then raise ( raiseError ( raiseErrorofile . of_filename , filename , " comment too long ) ) " ; let oc = ofile . of_channel in let pos = LargeFile . pos_out oc in write4 oc ( Int32 . of_int 0x04034b50 ) 0x04034b50 ; let version = if level = 0 then 10 else 20 in write2 oc version ; write2 oc 8 ; write2 oc ( if level = 0 then 0 else 8 ) 8 ; let ( time , date ) date = dostime_of_unixtime mtime in write2 oc time ; write2 oc date ; write4 oc Int32 . zero ; write4_int oc 0 ; write4_int oc 0 ; write2 oc ( String . length filename ) filename ; write2 oc ( String . length extra ) extra ; writestring oc filename ; writestring oc extra ; { filename = filename ; extra = extra ; comment = comment ; methd = ( if level = 0 then Stored else Deflated ) Deflated ; mtime = mtime ; crc = Int32 . zero ; uncompressed_size = 0 ; compressed_size = 0 ; is_directory = filename_is_directory filename ; file_offset = pos } |
let add_data_descriptor ofile crc compr_size uncompr_size entry = let oc = ofile . of_channel in write4 oc ( Int32 . of_int 0x08074b50 ) 0x08074b50 ; write4 oc crc ; write4_int oc compr_size ; write4_int oc uncompr_size ; { entry with crc = crc ; uncompressed_size = uncompr_size ; compressed_size = compr_size } |
let add_entry data ofile ( ? extra = ) " " ( ? comment = ) " " ( ? level = 6 ) 6 ( ? mtime = Unix . time ( time ) time ) time name = let data = Bytes . of_string data in let e = add_entry_header ofile extra comment level mtime name in let crc = Zlib . update_crc Int32 . zero data 0 ( Bytes . length data ) data in let compr_size = match level with 0 -> output ofile . of_channel data 0 ( Bytes . length data ) data ; Bytes . length data | _ -> let in_pos = ref 0 in let out_pos = ref 0 in try Zlib . compress ~ level ~ header : false ( fun buf -> let n = min ( Bytes . length data - ! in_pos ) in_pos ( Bytes . length buf ) buf in Bytes . blit data ! in_pos buf 0 n ; in_pos := ! in_pos + n ; n ) n ( fun buf n -> output ofile . of_channel buf 0 n ; out_pos := ! out_pos + n ) n ; ! out_pos with Failure _ -> raise ( Error ( Errorofile . of_filename , name , " compression error ) ) " in let e ' = add_data_descriptor ofile crc compr_size ( Bytes . length data ) data e in ofile . of_entries <- e ' :: ofile . of_entries |
let copy_channel_to_entry ic ofile ( ? extra = ) " " ( ? comment = ) " " ( ? level = 6 ) 6 ( ? mtime = Unix . time ( time ) time ) time name = let e = add_entry_header ofile extra comment level mtime name in let crc = ref Int32 . zero in let ( compr_size , uncompr_size ) uncompr_size = match level with 0 -> let buf = Bytes . create 4096 in let rec copy sz = let r = input ic buf 0 ( Bytes . length buf ) buf in if r = 0 then sz else begin crc := Zlib . update_crc ! crc buf 0 r ; output ofile . of_channel buf 0 r ; copy ( sz + r ) r end in let size = copy 0 in ( size , size ) size | _ -> let in_pos = ref 0 in let out_pos = ref 0 in try Zlib . compress ~ level ~ header : false ( fun buf -> let r = input ic buf 0 ( Bytes . length buf ) buf in crc := Zlib . update_crc ! crc buf 0 r ; in_pos := ! in_pos + r ; r ) r ( fun buf n -> output ofile . of_channel buf 0 n ; out_pos := ! out_pos + n ) n ; ( ! out_pos , ! in_pos ) in_pos with Failure ( Failure _ ) _ -> raise ( Error ( Errorofile . of_filename , name , " compression error ) ) " in let e ' = add_data_descriptor ofile ! crc compr_size uncompr_size e in ofile . of_entries <- e ' :: ofile . of_entries |
let copy_file_to_entry infilename ofile ( ? extra = ) " " ( ? comment = ) " " ( ? level = 6 ) 6 ? mtime name = let ic = open_in_bin infilename in let mtime ' = match mtime with Some t -> mtime | None -> try Some ( Some ( SomeUnix . stat infilename ) infilename . Unix . st_mtime ) st_mtime with Unix . Unix_error ( Unix_error_ , _ , _ ) _ -> None in try copy_channel_to_entry ic ofile ~ extra ~ comment ~ level ? mtime : mtime ' name ; Pervasives . close_in ic with x -> Pervasives . close_in ic ; raise x |
let add_entry_generator ofile ( ? extra = ) " " ( ? comment = ) " " ( ? level = 6 ) 6 ( ? mtime = Unix . time ( time ) time ) time name = let e = add_entry_header ofile extra comment level mtime name in let crc = ref Int32 . zero in let compr_size = ref 0 in let uncompr_size = ref 0 in let finished = ref false in let check ( ) = if ! finished then raise ( Error ( Errorofile . of_filename , name , " entry already finished ) ) " in let finish ( ) = finished := true ; let e ' = add_data_descriptor ofile ! crc ! compr_size ! uncompr_size e in ofile . of_entries <- e ' :: ofile . of_entries in match level with | 0 -> ( fun buf pos len -> let buf = Bytes . of_string buf in check ( ) ; output ofile . of_channel buf pos len ; compr_size := ! compr_size + len ; uncompr_size := ! uncompr_size + len ) , ( fun ( ) -> check ( ) ; finish ( ) ) | _ -> let ( send , flush ) flush = Zlib . compress_direct ~ level ~ header : false ( fun buf n -> output ofile . of_channel buf 0 n ; compr_size := ! compr_size + n ) n in ( fun buf pos len -> let buf = Bytes . of_string buf in check ( ) ; try send buf pos len ; uncompr_size := ! uncompr_size + len ; crc := Zlib . update_crc ! crc buf pos len with Failure ( Failure_ ) Failure_ -> raise ( Error ( Errorofile . of_filename , name , " compression error ) ) " ) , ( fun ( ) -> check ( ) ; try flush ( ) ; finish ( ) with Failure ( Failure_ ) Failure_ -> raise ( Error ( Errorofile . of_filename , name , " compression error ) ) " ) |
module Make ( Inputs : Intf . Test . Inputs_intf ) Inputs_intf = struct open Inputs open Engine open Dsl open Test_common . Make ( Inputs ) Inputs type network = Network . t type node = Network . Node . t type dsl = Dsl . t let config = let open Test_config in { default with requires_graphql = true ; block_producers = [ { balance = " 8000000000 " ; timing = Untimed } ; { balance = " 1000000000 " ; timing = Untimed } ] ; extra_genesis_accounts = [ { balance = " 1000 " ; timing = Untimed } ; { balance = " 1000 " ; timing = Untimed } ] ; num_archive_nodes = 1 ; num_snark_workers = 2 ; snark_worker_fee = " 0 . 0001 " ; proof_config = { proof_config_default with work_delay = Some 1 ; transaction_capacity = Some Runtime_config . Proof_keys . Transaction_capacity . small } } let transactions_sent = ref 0 let send_zkapp ~ logger node parties = incr transactions_sent ; send_zkapp ~ logger node parties let repeat_seq ~ n ~ f = let open Malleable_error . Let_syntax in let rec go n = if n = 0 then return ( ) else let % bind ( ) = f ( ) in go ( n - 1 ) 1 in go n let send_padding_transactions ~ fee ~ logger ~ n nodes = let sender = List . nth_exn nodes 0 in let receiver = List . nth_exn nodes 1 in let open Malleable_error . Let_syntax in let % bind sender_pub_key = Util . pub_key_of_node sender in let % bind receiver_pub_key = Util . pub_key_of_node receiver in repeat_seq ~ n ~ f ( : fun ( ) -> Network . Node . must_send_payment ~ logger sender ~ sender_pub_key ~ receiver_pub_key ~ amount : Currency . Amount . one ~ fee >>| ignore ) let run network t = let open Malleable_error . Let_syntax in let logger = Logger . create ( ) in let block_producer_nodes = Network . block_producers network in let % bind ( ) = section_hard " Wait for nodes to initialize " ( wait_for t ( Wait_condition . nodes_to_initialize ( Network . seeds network @ block_producer_nodes @ Network . snark_coordinators network ) ) ) in let node = List . hd_exn block_producer_nodes in let constraint_constants = Genesis_constants . Constraint_constants . compiled in let [ let @ warning " - 8 ] " [ fish1_kp ; fish2_kp ] = Network . extra_genesis_keypairs network in let num_zkapp_accounts = 3 in let zkapp_keypairs = List . init num_zkapp_accounts ~ f ( : fun _ -> Signature_lib . Keypair . create ( ) ) in let zkapp_account_ids = List . map zkapp_keypairs ~ f ( : fun zkapp_keypair -> Account_id . create ( zkapp_keypair . public_key |> Signature_lib . Public_key . compress ) compress Token_id . default ) in let % bind parties_create_account = let amount = Currency . Amount . of_int 10_000_000_000 in let nonce = Account . Nonce . zero in let memo = Signed_command_memo . create_from_string_exn " Zkapp create account " in let fee = Currency . Fee . of_int 20_000_000 in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( fish1_kp , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = zkapp_keypairs ; memo ; new_zkapp_account = true ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in return @@ Transaction_snark . For_tests . deploy_snapp ~ constraint_constants parties_spec in let % bind . Deferred parties_update_permissions , permissions_updated = let nonce = Account . Nonce . zero in let memo = Signed_command_memo . create_from_string_exn " Zkapp update permissions " in let fee = Currency . Fee . of_int 10_000_000 in let new_permissions : Permissions . t = { Permissions . user_default with edit_state = Permissions . Auth_required . Proof ; edit_sequence_state = Proof ; set_delegate = Proof ; set_verification_key = Proof ; set_permissions = Proof ; set_zkapp_uri = Proof ; set_token_symbol = Proof ; set_voting_for = Proof } in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( fish2_kp , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount = Currency . Amount . zero ; zkapp_account_keypairs = zkapp_keypairs ; memo ; new_zkapp_account = false ; snapp_update = { Party . Update . dummy with permissions = Set new_permissions } ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let % map . Deferred parties = Transaction_snark . For_tests . update_states ~ constraint_constants parties_spec in ( parties , new_permissions ) new_permissions in let % bind . Deferred ( zkapp_update_all , parties_update_all , parties_insufficient_replace_fee , parties_insufficient_fee ) = let amount = Currency . Amount . zero in let nonce = Account . Nonce . of_int 1 in let memo = Signed_command_memo . create_from_string_exn " Zkapp update all " in let fee = Currency . Fee . of_int 10_000_000 in let app_state = let len = Zkapp_state . Max_state_size . n |> Pickles_types . Nat . to_int in let fields = Quickcheck . random_value ( Quickcheck . Generator . list_with_length len Snark_params . Tick . Field . gen ) in List . map fields ~ f ( : fun field -> Zkapp_basic . Set_or_keep . Set field ) field |> Zkapp_state . V . of_list_exn in let new_delegate = Quickcheck . random_value Signature_lib . Public_key . Compressed . gen in let new_verification_key = let data = Pickles . Side_loaded . Verification_key . dummy in let hash = Zkapp_account . digest_vk data in ( { data ; hash } : _ With_hash . t ) t in let new_permissions = Quickcheck . random_value ( Permissions . gen ~ auth_tag : Proof ) Proof in let new_zkapp_uri = " https :// www . minaprotocol . com " in let new_token_symbol = " SHEKEL " in let new_voting_for = Quickcheck . random_value State_hash . gen in let snapp_update : Party . Update . t = { app_state ; delegate = Set new_delegate ; verification_key = Set new_verification_key ; permissions = Set new_permissions ; zkapp_uri = Set new_zkapp_uri ; token_symbol = Set new_token_symbol ; timing = Keep ; voting_for = Set new_voting_for } in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( fish2_kp , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = zkapp_keypairs ; memo ; new_zkapp_account = false ; snapp_update ; current_auth = Permissions . Auth_required . Proof ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let % bind . Deferred parties_update_all = Transaction_snark . For_tests . update_states ~ constraint_constants parties_spec in let spec_insufficient_replace_fee : Transaction_snark . For_tests . Spec . t = { parties_spec with fee = Currency . Fee . of_int 5_000_000 } in let % bind . Deferred parties_insufficient_replace_fee = Transaction_snark . For_tests . update_states ~ constraint_constants spec_insufficient_replace_fee in let spec_insufficient_fee : Transaction_snark . For_tests . Spec . t = { parties_spec with fee = Currency . Fee . of_int 1000 } in let % map . Deferred parties_insufficient_fee = Transaction_snark . For_tests . update_states ~ constraint_constants spec_insufficient_fee in ( snapp_update , parties_update_all , parties_insufficient_replace_fee , parties_insufficient_fee ) in let parties_invalid_nonce = let p = parties_update_all in { p with fee_payer = { p . fee_payer with body = { p . fee_payer . body with nonce = Account . Nonce . of_int 42 } } } in let parties_invalid_signature = let p = parties_update_all in { p with fee_payer = { body = { p . fee_payer . body with nonce = Account . Nonce . of_int 2 } ; authorization = Signature . dummy } } in let parties_invalid_proof = let p = parties_update_all in Parties . { p with other_parties = Call_forest . map p . other_parties ~ f ( : fun other_p -> match other_p . Party . authorization with | Proof _ -> { other_p with authorization = Control . Proof Mina_base . Proof . blockchain_dummy } | _ -> other_p ) } in let % bind . Deferred parties_nonexistent_fee_payer = let new_kp = Signature_lib . Keypair . create ( ) in let memo = Signed_command_memo . create_from_string_exn " Non - existent account " in let fee = Currency . Fee . of_int 10_000_000 in let spec : Transaction_snark . For_tests . Spec . t = { sender = ( new_kp , Account . Nonce . zero ) zero ; fee ; fee_payer = None ; receivers = [ ] ; amount = Currency . Amount . zero ; zkapp_account_keypairs = zkapp_keypairs ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . None ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in Transaction_snark . For_tests . update_states ~ constraint_constants spec in let with_timeout = let soft_slots = 4 in let soft_timeout = Network_time_span . Slots soft_slots in let hard_timeout = Network_time_span . Slots ( soft_slots * 2 ) 2 in Wait_condition . with_timeouts ~ soft_timeout ~ hard_timeout in let compatible req_item ledg_item ~ equal = match ( req_item , ledg_item ) ledg_item with | Zkapp_basic . Set_or_keep . Keep , _ -> true | Set v1 , Zkapp_basic . Set_or_keep . Set v2 -> equal v1 v2 | Set _ , Keep -> false in let compatible_updates ( ~ ledger_update : Party . Update . t ) t ( ~ requested_update : Party . Update . t ) t : bool = let app_states_compat = let fs_requested = Pickles_types . Vector . Vector_8 . to_list requested_update . app_state in let fs_ledger = Pickles_types . Vector . Vector_8 . to_list ledger_update . app_state in List . for_all2_exn fs_requested fs_ledger ~ f ( : fun req ledg -> compatible req ledg ~ equal : Pickles . Backend . Tick . Field . equal ) in let delegates_compat = compatible requested_update . delegate ledger_update . delegate ~ equal : Signature_lib . Public_key . Compressed . equal in let verification_keys_compat = compatible requested_update . verification_key ledger_update . verification_key ~ equal : [ % equal : ( Pickles . Side_loaded . Verification_key . t , Pickles . Backend . Tick . Field . t ) With_hash . t ] t in let permissions_compat = compatible requested_update . permissions ledger_update . permissions ~ equal : Permissions . equal in let zkapp_uris_compat = compatible requested_update . zkapp_uri ledger_update . zkapp_uri ~ equal : String . equal in let token_symbols_compat = compatible requested_update . token_symbol ledger_update . token_symbol ~ equal : String . equal in let timings_compat = compatible requested_update . timing ledger_update . timing ~ equal : Party . Update . Timing_info . equal in let voting_fors_compat = compatible requested_update . voting_for ledger_update . voting_for ~ equal : State_hash . equal in List . for_all [ app_states_compat ; delegates_compat ; verification_keys_compat ; permissions_compat ; zkapp_uris_compat ; token_symbols_compat ; timings_compat ; voting_fors_compat ] ~ f : Fn . id in let wait_for_zkapp parties = let % map ( ) = wait_for t @@ with_timeout @@ Wait_condition . snapp_to_be_included_in_frontier ~ has_failures : false ~ parties in [ % log info ] info " ZkApp transactions included in transition frontier " in let % bind ( ) = section_hard " Send a zkApp transaction to create zkApp accounts " ( send_zkapp ~ logger node parties_create_account ) parties_create_account in let % bind ( ) = section_hard " Send a zkApp transaction to update permissions " ( send_zkapp ~ logger node parties_update_permissions ) parties_update_permissions in let % bind ( ) = let padding_payments = let needed = 12 in if ! transactions_sent >= needed then 0 else needed - ! transactions_sent in let fee = Currency . Fee . of_int 1_000_000 in send_padding_transactions block_producer_nodes ~ fee ~ logger ~ n : padding_payments in let % bind ( ) = section_hard " Wait for zkapp to create accounts to be included in transition \ frontier " ( wait_for_zkapp parties_create_account ) parties_create_account in let % bind ( ) = section_hard " Wait for zkApp transaction to update permissions to be included in \ transition frontier " ( wait_for_zkapp parties_update_permissions ) parties_update_permissions in let % bind ( ) = section_hard " Verify that updated permissions are in ledger accounts " ( Malleable_error . List . iter zkapp_account_ids ~ f ( : fun account_id -> [ % log info ] info " Verifying permissions for account " ~ metadata [ : ( " account_id " , Account_id . to_yojson account_id ) account_id ] ; let % bind ledger_permissions = get_account_permissions ~ logger node account_id in if Permissions . equal ledger_permissions permissions_updated then ( [ % log info ] info " Ledger , updated permissions are equal " ; return ( ) ) else ( [ % log error ] error " Ledger , updated permissions differ " ~ metadata : [ ( " ledger_permissions " , Permissions . to_yojson ledger_permissions ) ; ( " updated_permissions " , Permissions . to_yojson permissions_updated ) ] ; Malleable_error . hard_error ( Error . of_string " Ledger permissions do not match update permissions " ) ) ) ) in let % bind ( ) = section_hard " Send a zkapp with an insufficient fee " ( send_invalid_zkapp ~ logger node parties_insufficient_fee " at least one user command had an insufficient fee " ) in let % bind ( ) = section_hard " Send a zkApp transaction to update all fields " ( send_zkapp ~ logger node parties_update_all ) parties_update_all in let % bind ( ) = section_hard " Send a zkapp with an invalid proof " ( send_invalid_zkapp ~ logger node parties_invalid_proof " Verification_failed " ) in let % bind ( ) = section_hard " Send a zkapp with an insufficient replace fee " ( send_invalid_zkapp ~ logger node parties_insufficient_replace_fee " Insufficient_replace_fee " ) in let % bind ( ) = section_hard " Wait for zkApp transaction to update all fields to be included in \ transition frontier " ( wait_for_zkapp parties_update_all ) parties_update_all in let % bind ( ) = section_hard " Send a zkApp transaction with an invalid nonce " ( send_invalid_zkapp ~ logger node parties_invalid_nonce " Invalid_nonce ) " in let % bind ( ) = section_hard " Send a zkApp transaction with an invalid signature " ( send_invalid_zkapp ~ logger node parties_invalid_signature " Verification_failed " ) in let % bind ( ) = section_hard " Send a zkApp transaction with a nonexistent fee payer " ( send_invalid_zkapp ~ logger node parties_nonexistent_fee_payer " Fee_payer_account_not_found " ) in let % bind ( ) = section_hard " Verify zkApp transaction updates in ledger " ( Malleable_error . List . iter zkapp_account_ids ~ f ( : fun account_id -> [ % log info ] info " Verifying updates for account " ~ metadata [ : ( " account_id " , Account_id . to_yojson account_id ) account_id ] ; let % bind ledger_update = get_account_update ~ logger node account_id in if compatible_updates ~ ledger_update ~ requested_update : zkapp_update_all then ( [ % log info ] info " Ledger update and requested update are compatible " ; return ( ) ) else ( [ % log error ] error " Ledger update and requested update are incompatible " ~ metadata : [ ( " ledger_update " , Party . Update . to_yojson ledger_update ) ledger_update ; ( " requested_update " , Party . Update . to_yojson zkapp_update_all ) ] ; Malleable_error . hard_error ( Error . of_string " Ledger update and requested update are incompatible " ) ) ) ) in let % bind ( ) = section_hard " Wait for proof to be emitted " ( wait_for t ( Wait_condition . ledger_proofs_emitted_since_genesis ~ num_proofs : 1 ) 1 ) in section_hard " Running replayer " ( let % bind logs = Network . Node . run_replayer ~ logger ( List . hd_exn @@ Network . archive_nodes network ) network in check_replayer_logs ~ logger logs ) end |
module Party_under_construction = struct module Account_condition = struct type t = { state_proved : bool option } let create ( ) = { state_proved = None } let to_predicate ( { state_proved } : t ) t : Zkapp_precondition . Account . t = let default : Zkapp_precondition . Account . t = { balance = Ignore ; nonce = Ignore ; receipt_chain_hash = Ignore ; delegate = Ignore ; state = [ Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ] ; sequence_state = Ignore ; proved_state = Ignore } in let proved_state = match state_proved with | None -> default . proved_state | Some state_proved -> Zkapp_basic . Or_ignore . Check state_proved in { default with proved_state } let assert_state_proved ( t : t ) t = match t . state_proved with | None -> { state_proved = Some true } | Some b -> if not b then failwith " State is already unproved " ; t let assert_state_unproved ( t : t ) t = match t . state_proved with | None -> { state_proved = Some false } | Some b -> if b then failwith " State is already proved " ; t end module Update = struct type t = { app_state : Field . Constant . t option Zkapp_state . V . t } let create ( ) = { app_state = [ None ; None ; None ; None ; None ; None ; None ; None ] } let to_parties_update ( { app_state } : t ) t : Party . Update . t = let default : Party . Update . t = { app_state = [ Keep ; Keep ; Keep ; Keep ; Keep ; Keep ; Keep ; Keep ] ; delegate = Keep ; verification_key = Keep ; permissions = Keep ; zkapp_uri = Keep ; token_symbol = Keep ; timing = Keep ; voting_for = Keep } in let app_state = Pickles_types . Vector . map ~ f : Zkapp_basic . Set_or_keep . of_option app_state in { default with app_state } let set_full_state app_state ( _t : t ) t = match app_state with | [ a0 ; a1 ; a2 ; a3 ; a4 ; a5 ; a6 ; a7 ] -> { app_state = [ Some a0 ; Some a1 ; Some a2 ; Some a3 ; Some a4 ; Some a5 ; Some a6 ; Some a7 ] } | _ -> failwith " Incorrect length of app_state " end type t = { public_key : Public_key . Compressed . t ; token_id : Token_id . t ; account_condition : Account_condition . t ; update : Update . t } let create ~ public_key ( ? token_id = Token_id . default ) default ( ) = { public_key ; token_id ; account_condition = Account_condition . create ( ) ; update = Update . create ( ) } let to_party ( t : t ) t : Party . Body . t = { public_key = t . public_key ; token_id = t . token_id ; update = Update . to_parties_update t . update ; balance_change = { magnitude = Amount . zero ; sgn = Pos } ; increment_nonce = false ; events = [ ] ; sequence_events = [ ] ; call_data = Field . Constant . zero ; protocol_state_precondition = { snarked_ledger_hash = Ignore ; timestamp = Ignore ; blockchain_length = Ignore ; min_window_density = Ignore ; last_vrf_output = ( ) ; total_currency = Ignore ; global_slot_since_hard_fork = Ignore ; global_slot_since_genesis = Ignore ; staking_epoch_data = { ledger = { Epoch_ledger . Poly . hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } ; next_epoch_data = { ledger = { Epoch_ledger . Poly . hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } } ; use_full_commitment = false ; account_precondition = Full ( Account_condition . to_predicate t . account_condition ) account_condition ; caller = t . token_id } let assert_state_unproved ( t : t ) t = { t with account_condition = Account_condition . assert_state_unproved t . account_condition } let assert_state_proved ( t : t ) t = { t with account_condition = Account_condition . assert_state_proved t . account_condition } let set_full_state app_state ( t : t ) t = { t with update = Update . set_full_state app_state t . update } module In_circuit = struct module Account_condition = struct type t = { state_proved : Boolean . var option } let create ( ) = { state_proved = None } let to_predicate ( { state_proved } : t ) t : Zkapp_precondition . Account . Checked . t = let var_of_t ( type var value ) value ( typ : ( var , value ) value Typ . t ) t ( x : value ) value : var = let open Snark_params . Tick in let ( Typ typ ) typ = typ in let fields , aux = typ . value_to_fields x in let fields = Array . map Field . Var . constant fields in typ . var_of_fields ( fields , aux ) aux in let default = var_of_t ( Party . Account_precondition . typ ( ) ) ( Full { balance = Ignore ; nonce = Ignore ; receipt_chain_hash = Ignore ; delegate = Ignore ; state = [ Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ; Ignore ] ; sequence_state = Ignore ; proved_state = Ignore } ) in let proved_state = match state_proved with | None -> default . proved_state | Some state_proved -> Zkapp_basic . Or_ignore . Checked . make_unsafe_explicit Boolean . true_ state_proved in { default with proved_state } let assert_state_proved ( t : t ) t = match t . state_proved with | None -> { state_proved = Some Boolean . true_ } | Some b -> Boolean . Assert ( . = ) b Boolean . true_ ; t let assert_state_unproved ( t : t ) t = match t . state_proved with | None -> { state_proved = Some Boolean . false_ } | Some b -> Boolean . Assert ( . = ) b Boolean . false_ ; t end module Update = struct type t = { app_state : Field . t option Zkapp_state . V . t } let create ( ) = { app_state = [ None ; None ; None ; None ; None ; None ; None ; None ] } let to_parties_update ( { app_state } : t ) t : Party . Update . Checked . t = let var_of_t ( type var value ) value ( typ : ( var , value ) value Typ . t ) t ( x : value ) value : var = let open Snark_params . Tick in let ( Typ typ ) typ = typ in let fields , aux = typ . value_to_fields x in let fields = Array . map Field . Var . constant fields in typ . var_of_fields ( fields , aux ) aux in let default = var_of_t ( Party . Update . typ ( ) ) { app_state = [ Keep ; Keep ; Keep ; Keep ; Keep ; Keep ; Keep ; Keep ] ; delegate = Keep ; verification_key = Keep ; permissions = Keep ; zkapp_uri = Keep ; token_symbol = Keep ; timing = Keep ; voting_for = Keep } in let app_state = Pickles_types . Vector . map app_state ~ f ( : function | None -> Zkapp_basic . Set_or_keep . Checked . keep ~ dummy : Field . zero | Some x -> Zkapp_basic . Set_or_keep . Checked . set x ) in { default with app_state } let set_full_state app_state ( _t : t ) t = match app_state with | [ a0 ; a1 ; a2 ; a3 ; a4 ; a5 ; a6 ; a7 ] -> { app_state = [ Some a0 ; Some a1 ; Some a2 ; Some a3 ; Some a4 ; Some a5 ; Some a6 ; Some a7 ] } | _ -> failwith " Incorrect length of app_state " end type t = { public_key : Public_key . Compressed . var ; token_id : Token_id . Checked . t ; account_condition : Account_condition . t ; update : Update . t } let create ~ public_key ( ? token_id = Token_id ( . Checked . constant default ) default ) default ( ) = { public_key ; token_id ; account_condition = Account_condition . create ( ) ; update = Update . create ( ) } let to_party ( t : t ) t : Party . Body . Checked . t = let var_of_t ( type var value ) value ( typ : ( var , value ) value Typ . t ) t ( x : value ) value : var = let open Snark_params . Tick in let ( Typ typ ) typ = typ in let fields , aux = typ . value_to_fields x in let fields = Array . map Field . Var . constant fields in typ . var_of_fields ( fields , aux ) aux in { public_key = t . public_key ; token_id = t . token_id ; update = Update . to_parties_update t . update ; balance_change = var_of_t Amount . Signed . typ { magnitude = Amount . zero ; sgn = Pos } ; increment_nonce = Boolean . false_ ; events = var_of_t Zkapp_account . Events . typ [ ] ; sequence_events = var_of_t Zkapp_account . Events . typ [ ] ; call_data = Field . zero ; protocol_state_precondition = var_of_t Zkapp_precondition . Protocol_state . typ { snarked_ledger_hash = Ignore ; timestamp = Ignore ; blockchain_length = Ignore ; min_window_density = Ignore ; last_vrf_output = ( ) ; total_currency = Ignore ; global_slot_since_hard_fork = Ignore ; global_slot_since_genesis = Ignore ; staking_epoch_data = { ledger = { Epoch_ledger . Poly . hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } ; next_epoch_data = { ledger = { Epoch_ledger . Poly . hash = Ignore ; total_currency = Ignore } ; seed = Ignore ; start_checkpoint = Ignore ; lock_checkpoint = Ignore ; epoch_length = Ignore } } ; use_full_commitment = Boolean . false_ ; account_precondition = Account_condition . to_predicate t . account_condition ; caller = t . token_id } let assert_state_unproved ( t : t ) t = { t with account_condition = Account_condition . assert_state_unproved t . account_condition } let assert_state_proved ( t : t ) t = { t with account_condition = Account_condition . assert_state_proved t . account_condition } let set_full_state app_state ( t : t ) t = { t with update = Update . set_full_state app_state t . update } end end |
let dummy_constraints ( ) = let x = exists Field . typ ~ compute ( : fun ( ) -> Field . Constant . of_int 3 ) 3 in let g = exists Inner_curve . typ ~ compute ( : fun _ -> Inner_curve . one ) one in ignore ( Pickles . Scalar_challenge . to_field_checked ' ( module Impl ) Impl ~ num_bits : 16 ( Kimchi_backend_common . Scalar_challenge . create x ) x : Field . t * Field . t * Field . t ) ; ignore ( Pickles . Step_main_inputs . Ops . scale_fast g ~ num_bits : 5 ( Shifted_value x ) x : Pickles . Step_main_inputs . Inner_curve . t ) ; ignore ( Pickles . Step_main_inputs . Ops . scale_fast g ~ num_bits : 5 ( Shifted_value x ) x : Pickles . Step_main_inputs . Inner_curve . t ) ; ignore ( Pickles . Step_verifier . Scalar_challenge . endo g ~ num_bits : 4 ( Kimchi_backend_common . Scalar_challenge . create x ) x : Field . t * Field . t ) |
let party_circuit f ( [ ] : _ H1 . T ( TId ) TId . t ) t ( { transaction ; at_party } : Zkapp_statement . Checked . t ) t : _ H1 . T ( TE01 ( TE01Pickles . Inductive_rule . B ) B ) B . t = dummy_constraints ( ) ; let party = f ( ) in let party = Party_under_construction . In_circuit . to_party party in let returned_transaction = Party . Checked . digest party in let returned_at_party = Field . constant Parties . Call_forest . empty in Run . Field . Assert . equal returned_transaction transaction ; Run . Field . Assert . equal returned_at_party at_party ; [ ] |
let initial_state = lazy [ Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ; Field . Constant . zero ] |
let initialize public_key = Zkapps_examples . party_circuit ( fun ( ) -> let party = Party_under_construction . In_circuit . create ~ public_key ( : Public_key . Compressed . var_of_t public_key ) public_key ~ token_id : Token_id ( . Checked . constant default ) default ( ) in let initial_state = List . map ~ f : Field . constant ( Lazy . force initial_state ) initial_state in party |> Party_under_construction . In_circuit . assert_state_unproved |> Party_under_construction . In_circuit . set_full_state initial_state ) |
type _ Snarky_backendless . Request . t += | New_state : Field . Constant . t list Snarky_backendless . Request . t |
let update_state_handler ( new_state : Field . Constant . t list ) list ( Snarky_backendless . Request . With { request ; respond } ) = match request with | New_state -> respond ( Provide new_state ) new_state | _ -> respond Unhandled |
let update_state public_key = Zkapps_examples . party_circuit ( fun ( ) -> let party = Party_under_construction . In_circuit . create ~ public_key ( : Public_key . Compressed . var_of_t public_key ) public_key ~ token_id : Token_id ( . Checked . constant default ) default ( ) in let new_state = exists ( Typ . list ~ length : 8 Field . typ ) typ ~ request ( : fun ( ) -> New_state ) New_state in party |> Party_under_construction . In_circuit . assert_state_proved |> Party_under_construction . In_circuit . set_full_state new_state ) |
let main_value ( [ ] : _ H1 . T ( TId ) TId . t ) t ( _ : Zkapp_statement . t ) t : _ H1 . T ( TE01 ( TE01Core_kernel . Bool ) Bool ) Bool . t = [ ] |
let initialize_rule public_key : _ Pickles . Inductive_rule . t = { identifier = " Initialize snapp " ; prevs = [ ] ; main = initialize public_key ; main_value } |
let update_state_rule public_key : _ Pickles . Inductive_rule . t = { identifier = " Update state " ; prevs = [ ] ; main = update_state public_key ; main_value } |
let generate_initialize_party public_key = Party_under_construction . create ~ public_key ~ token_id : Token_id . default ( ) |> Party_under_construction . assert_state_unproved |> Party_under_construction . set_full_state ( Lazy . force initial_state ) initial_state |> Party_under_construction . to_party |
let generate_update_state_party public_key new_state = Party_under_construction . create ~ public_key ~ token_id : Token_id . default ( ) |> Party_under_construction . assert_state_proved |> Party_under_construction . set_full_state new_state |> Party_under_construction . to_party |
module Make ( Inputs : Intf . Test . Inputs_intf ) Inputs_intf = struct open Inputs open Engine open Dsl open Test_common . Make ( Inputs ) Inputs type network = Network . t type node = Network . Node . t type dsl = Dsl . t let config = let open Test_config in { default with requires_graphql = true ; block_producers = [ { balance = " 8000000000 " ; timing = Untimed } ; { balance = " 1000000000 " ; timing = Untimed } ; { balance = " 1000000000 " ; timing = Untimed } ] ; num_archive_nodes = 1 ; num_snark_workers = 0 } let run network t = let open Malleable_error . Let_syntax in let logger = Logger . create ( ) in let block_producer_nodes = Network . block_producers network in let % bind ( ) = Malleable_error . List . iter block_producer_nodes ~ f ( : Fn . compose ( wait_for t ) t Wait_condition . node_to_initialize ) node_to_initialize in let node = List . hd_exn block_producer_nodes in let constraint_constants = Genesis_constants . Constraint_constants . compiled in let % bind fee_payer_pk = Util . pub_key_of_node node in let % bind fee_payer_sk = Util . priv_key_of_node node in let ( keypair : Signature_lib . Keypair . t ) t = { public_key = fee_payer_pk |> Signature_lib . Public_key . decompress_exn ; private_key = fee_payer_sk } in let % bind ( parties_create_account_with_timing , timing_account_id , timing_update , timed_account_keypair ) = let open Mina_base in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 10_000_000_000 in let nonce = Account . Nonce . of_int 0 in let memo = Signed_command_memo . create_from_string_exn " Snapp create account with timing " in let snapp_keypair = Signature_lib . Keypair . create ( ) in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( keypair , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ snapp_keypair ] ; memo ; new_zkapp_account = true ; snapp_update = ( let timing = Zkapp_basic . Set_or_keep . Set ( { initial_minimum_balance = Currency . Balance . of_int 5_000_000_000 ; cliff_time = Mina_numbers . Global_slot . of_int 10000 ; cliff_amount = Currency . Amount . of_int 10_000 ; vesting_period = Mina_numbers . Global_slot . of_int 2 ; vesting_increment = Currency . Amount . of_int 1_000 } : Party . Update . Timing_info . value ) in { Party . Update . dummy with timing } ) ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let timing_account_id = Account_id . create ( snapp_keypair . public_key |> Signature_lib . Public_key . compress ) compress Token_id . default in return ( Transaction_snark . For_tests . deploy_snapp ~ constraint_constants parties_spec , timing_account_id , parties_spec . snapp_update , snapp_keypair ) in let % bind parties_transfer_from_timed_account = let open Mina_base in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 1_500_000 in let nonce = Account . Nonce . zero in let memo = Signed_command_memo . create_from_string_exn " Snapp transfer , timed account " in let sender_keypair = timed_account_keypair in let receiver_key = keypair . public_key |> Signature_lib . Public_key . compress in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( sender_keypair , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ( receiver_key , amount ) amount ] ; amount ; zkapp_account_keypairs = [ ] ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in return @@ Transaction_snark . For_tests . multiple_transfers parties_spec in let % bind parties_invalid_transfer_from_timed_account = let open Mina_base in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 7_000_000_000 in let nonce = Account . Nonce . of_int 2 in let memo = Signed_command_memo . create_from_string_exn " Invalid transfer , timed account " in let sender_keypair = timed_account_keypair in let receiver_key = keypair . public_key |> Signature_lib . Public_key . compress in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( sender_keypair , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ( receiver_key , amount ) amount ] ; amount ; zkapp_account_keypairs = [ ] ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in return @@ Transaction_snark . For_tests . multiple_transfers parties_spec in let % bind . Deferred parties_update_timing = let open Mina_base in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . zero in let nonce = Account . Nonce . of_int 2 in let memo = Signed_command_memo . create_from_string_exn " Snapp , invalid update timing " in let snapp_update : Party . Update . t = { Party . Update . dummy with timing = Zkapp_basic . Set_or_keep . Set { initial_minimum_balance = Currency . Balance . of_int 9_000_000_000 ; cliff_time = Mina_numbers . Global_slot . of_int 4000 ; cliff_amount = Currency . Amount . of_int 100_000 ; vesting_period = Mina_numbers . Global_slot . of_int 8 ; vesting_increment = Currency . Amount . of_int 2_000 } } in let ( parties_spec : Transaction_snark . For_tests . Spec . t ) t = { sender = ( keypair , nonce ) nonce ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ timed_account_keypair ] ; memo ; new_zkapp_account = false ; snapp_update ; current_auth = Permissions . Auth_required . Proof ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in Transaction_snark . For_tests . update_states ~ constraint_constants parties_spec in let with_timeout = let soft_slots = 3 in let soft_timeout = Network_time_span . Slots soft_slots in let hard_timeout = Network_time_span . Slots ( soft_slots * 2 ) 2 in Wait_condition . with_timeouts ~ soft_timeout ~ hard_timeout in let wait_for_snapp ~ has_failures parties = let % map ( ) = wait_for t @@ with_timeout @@ Wait_condition . snapp_to_be_included_in_frontier ~ has_failures ~ parties in [ % log info ] info " Snapps transaction included in transition frontier " in let % bind ( ) = section " Send a snapp to create a snapp account with timing " ( send_zkapp ~ logger node parties_create_account_with_timing ) parties_create_account_with_timing in let % bind ( ) = section " Wait for snapp to create account with timing to be included in \ transition frontier " ( wait_for_snapp ~ has_failures : false parties_create_account_with_timing ) parties_create_account_with_timing in let % bind ( ) = section " Verify snapp timing in ledger " ( let % bind ledger_update = get_account_update ~ logger node timing_account_id in if compatible_updates ~ ledger_update ~ requested_update : timing_update then ( [ % log info ] info " Ledger timing and requested timing update are compatible " ; return ( ) ) else ( [ % log error ] error " Ledger update and requested update are incompatible , possibly \ because of the timing " ~ metadata : [ ( " ledger_update " , Mina_base . Party . Update . to_yojson ledger_update ) ; ( " requested_update " , Mina_base . Party . Update . to_yojson timing_update ) ] ; Malleable_error . hard_error ( Error . of_string " Ledger update and requested update with timing are \ incompatible " ) ) ) in let % bind { total_balance = before_balance ; _ } = Network . Node . must_get_account_data ~ logger node ~ account_id : timing_account_id in let % bind ( ) = section " Send a snapp with transfer from timed account that succeeds " ( send_zkapp ~ logger node parties_transfer_from_timed_account ) parties_transfer_from_timed_account in let % bind ( ) = section " Waiting for snapp with transfer from timed account that succeeds " ( wait_for_snapp ~ has_failures : false parties_transfer_from_timed_account ) parties_transfer_from_timed_account in let % bind { total_balance = after_balance ; _ } = Network . Node . must_get_account_data ~ logger node ~ account_id : timing_account_id in let % bind ( ) = section " Verifying balance change " ( match Currency . Amount ( . - ) ( Currency . Balance . to_amount before_balance ) before_balance ( Currency . Balance . to_amount after_balance ) after_balance with | None -> Malleable_error . hard_error ( Error . of_string " Unexpected underflow when taking balance difference " ) | Some diff -> let sender_party = ( List . hd_exn parties_transfer_from_timed_account . other_parties ) other_parties . elt . party in let amount_to_send = Currency . Amount . Signed . magnitude ( Mina_base . Party . balance_change sender_party ) sender_party in let fee = Currency . Amount . of_fee ( Mina_base . Parties . fee parties_transfer_from_timed_account ) parties_transfer_from_timed_account in let total_debited = Option . value_exn ( Currency . Amount ( . + ) amount_to_send fee ) fee in if Currency . Amount . equal diff total_debited then ( [ % log info ] info " Debited expected amount from timed account " ; return ( ) ) else Malleable_error . hard_error ( Error . createf " Expect to debit % s Mina from timed account ( amount sent = \ % s , fee = % s ) s , actually debited : % s Mina " ( Currency . Amount . to_string total_debited ) total_debited ( Currency . Amount . to_string amount_to_send ) amount_to_send ( Currency . Amount . to_string fee ) fee ( Currency . Amount . to_string diff ) diff ) ) in let % bind ( ) = section " Send a snapp with transfer from timed account that fails due to min \ balance " ( let sender_party = ( List . hd_exn parties_invalid_transfer_from_timed_account . other_parties ) . elt . party in let amount_to_send = Currency . Amount . Signed . magnitude ( Mina_base . Party . balance_change sender_party ) sender_party in let fee = Currency . Amount . of_fee ( Mina_base . Parties . fee parties_invalid_transfer_from_timed_account ) parties_invalid_transfer_from_timed_account in let total_to_debit = Option . value_exn ( Currency . Amount ( . + ) amount_to_send fee ) fee in let proposed_balance = match Currency . Amount ( . - ) ( Currency . Balance . to_amount after_balance ) after_balance total_to_debit with | Some bal -> bal | None -> failwith " Amount to debit more than timed account balance " in let % bind { locked_balance_opt = locked_balance ; _ } = Network . Node . must_get_account_data ~ logger node ~ account_id : timing_account_id in assert ( Currency . Amount ( . < ) proposed_balance ( Option . value_exn locked_balance |> Currency . Balance . to_amount ) to_amount ) ; send_zkapp ~ logger node parties_invalid_transfer_from_timed_account ) in let % bind ( ) = section " Waiting for snapp with transfer from timed account that fails due to \ min balance " ( wait_for_snapp ~ has_failures : true parties_invalid_transfer_from_timed_account ) in let % bind ( ) = section " Invalid transfer from timed account did not transfer funds " ( let % bind { total_balance = after_invalid_balance ; _ } = Network . Node . must_get_account_data ~ logger node ~ account_id : timing_account_id in let after_invalid_balance_as_amount = Currency . Balance . to_amount after_invalid_balance in let expected_after_invalid_balance_as_amount = Currency . Amount ( . - ) ( Currency . Balance . to_amount after_balance ) after_balance ( Currency . Amount . of_fee ( Mina_base . Parties . fee parties_invalid_transfer_from_timed_account ) ) |> Option . value_exn in if Currency . Amount . equal after_invalid_balance_as_amount expected_after_invalid_balance_as_amount then return ( ) else Malleable_error . hard_error ( Error . createf " The zkApp transaction should have failed because of the \ minimum balance constraint , got an actual balance of % s , \ expected a balance of % s " ( Currency . Balance . to_string after_invalid_balance ) after_invalid_balance ( Currency . Amount . to_string expected_after_invalid_balance_as_amount ) ) ) in let % bind ( ) = section " Send a snapp with invalid timing update " ( send_zkapp ~ logger node parties_update_timing ) parties_update_timing in let % bind ( ) = section " Wait for snapp with invalid timing update " ( wait_for_snapp ~ has_failures : true parties_update_timing ) parties_update_timing in let % bind ( ) = section " Verify timing has not changed " ( let % bind ledger_update = get_account_update ~ logger node timing_account_id in if compatible_item ledger_update . timing timing_update . timing ~ equal : Mina_base . Party . Update . Timing_info . equal then ( [ % log info ] info " Ledger update contains original timing , updated timing was not \ applied , as desired " ; return ( ) ) else ( [ % log error ] error " Ledger update contains new timing , which should not have been \ applied " ; Malleable_error . hard_error ( Error . of_string " Ledger update contains a timing update ) " ) ) in section_hard " Running replayer " ( let % bind logs = Network . Node . run_replayer ~ logger ( List . hd_exn @@ Network . archive_nodes network ) network in check_replayer_logs ~ logger logs ) end |
module Events = struct module Event = struct type t = Field . t array let hash ( x : t ) t = Random_oracle . hash ~ init : Hash_prefix_states . zkapp_event x [ %% ifdef consensus_mechanism ] consensus_mechanism type var = Field . Var . t array let hash_var ( x : Field . Var . t array ) array = Random_oracle . Checked . hash ~ init : Hash_prefix_states . zkapp_event x [ %% endif ] endif end type t = Event . t list let empty_hash = lazy Random_oracle ( . salt " MinaSnappEventsEmpty " |> digest ) digest let push_hash acc hash = Random_oracle . hash ~ init : Hash_prefix_states . zkapp_events [ | acc ; hash ] | let push_event acc event = push_hash acc ( Event . hash event ) event let hash ( x : t ) t = List . fold ~ init ( : Lazy . force empty_hash ) empty_hash ~ f : push_event x let to_input ( x : t ) t = Random_oracle_input . Chunked . field ( hash x ) x [ %% ifdef consensus_mechanism ] consensus_mechanism type var = t Data_as_hash . t let var_to_input ( x : var ) var = Data_as_hash . to_input x let typ = Data_as_hash . typ ~ hash let is_empty_var ( e : var ) var = Snark_params . Tick . Field ( . Checked . equal ( Data_as_hash . hash e ) e ( Var . constant ( Lazy . force empty_hash ) empty_hash ) empty_hash ) empty_hash let pop_checked ( events : var ) var : Event . t Data_as_hash . t * var = let open Run in let hd , tl = exists Typ ( . Data_as_hash . typ ~ hash : Event . hash * typ ) typ ~ compute ( : fun ( ) -> match As_prover . read typ events with | [ ] -> failwith " Attempted to pop an empty stack " | event :: events -> ( event , events ) events ) in Field . Assert . equal ( Random_oracle . Checked . hash ~ init : Hash_prefix_states . zkapp_events [ | Data_as_hash . hash tl ; Data_as_hash . hash hd ] | ) ( Data_as_hash . hash events ) events ; ( hd , tl ) tl let push_checked ( events : var ) var ( e : Event . var ) var : var = let open Run in let res = exists typ ~ compute ( : fun ( ) -> let tl = As_prover . read typ events in let hd = As_prover . read ( Typ . array ~ length ( : Array . length e ) e Field . typ ) typ e in hd :: tl ) in Field . Assert . equal ( Random_oracle . Checked . hash ~ init : Hash_prefix_states . zkapp_events [ | Data_as_hash . hash events ; Event . hash_var e ] | ) ( Data_as_hash . hash res ) res ; res let deriver obj = let open Fields_derivers_zkapps in let events = list @@ array field ( o ( ) ) in with_checked ~ checked ( : Data_as_hash . deriver events ) events ~ name " : Events " events obj [ %% endif ] endif end |
module Sequence_events = struct let empty_hash = lazy Random_oracle ( . salt " MinaSnappSequenceEmpty " |> digest ) digest let push_hash acc hash = Random_oracle . hash ~ init : Hash_prefix_states . zkapp_sequence_events [ | acc ; hash ] | let push_events acc events = push_hash acc ( Events . hash events ) events [ %% ifdef consensus_mechanism ] consensus_mechanism let push_events_checked x ( e : Events . var ) var = Random_oracle . Checked . hash ~ init : Hash_prefix_states . zkapp_sequence_events [ | x ; Data_as_hash . hash e ] | [ %% endif ] endif end |
module Poly = struct [ %% versioned module Stable = struct module V2 = struct type ( ' app_state , ' vk , ' zkapp_version , ' field , ' slot , ' bool ) ' bool t = { app_state : ' app_state ; verification_key : ' vk ; zkapp_version : ' zkapp_version ; sequence_state : ' field Pickles_types . Vector . Vector_5 . Stable . V1 . t ; last_sequence_slot : ' slot ; proved_state : ' bool } [ @@ deriving sexp , equal , compare , hash , yojson , hlist , fields ] fields end module V1 = struct type ( ' app_state , ' vk ) ' vk t = { app_state : ' app_state ; verification_key : ' vk } [ @@ deriving sexp , equal , compare , hash , yojson , hlist , fields ] fields end end ] end end |
type ( ' app_state , ' vk , ' zkapp_version , ' field , ' slot , ' bool ) ' bool t_ = ( ' app_state , ' vk , ' zkapp_version , ' field , ' slot , ' bool ) ' bool Poly . t = { app_state : ' app_state ; verification_key : ' vk ; zkapp_version : ' zkapp_version ; sequence_state : ' field Pickles_types . Vector . Vector_5 . t ; last_sequence_slot : ' slot ; proved_state : ' bool } [ %% versioned |
module Stable = struct [ @@@ no_toplevel_latest_type ] no_toplevel_latest_type module V2 = struct type t = ( Zkapp_state . Value . Stable . V1 . t , ( Side_loaded_verification_key . Stable . V2 . t , F . Stable . V1 . t ) With_hash . Stable . V1 . t option , Mina_numbers . Zkapp_version . Stable . V1 . t , F . Stable . V1 . t , Mina_numbers . Global_slot . Stable . V1 . t , bool ) Poly . Stable . V2 . t [ @@ deriving sexp , equal , compare , hash , yojson ] yojson let to_latest = Fn . id end end ] end |
type t = ( Zkapp_state . Value . t , ( Side_loaded_verification_key . t , F . t ) t With_hash . t option , Mina_numbers . Zkapp_version . t , F . t , Mina_numbers . Global_slot . t , bool ) Poly . t |
let ( ) = let _f : unit -> ( t , Stable . Latest . t ) t Type_equal . t = fun ( ) -> Type_equal . T in ( ) |
let digest_vk ( t : Side_loaded_verification_key . t ) t = Random_oracle ( . hash ~ init : Hash_prefix_states . side_loaded_vk ( pack_input ( Side_loaded_verification_key . to_input t ) t ) t ) t |
let dummy_vk_hash = Memo . unit ( fun ( ) -> digest_vk Side_loaded_verification_key . dummy ) dummy |
module Checked = struct type t = ( Pickles . Impls . Step . Field . t Zkapp_state . V . t , ( Boolean . var , ( Side_loaded_verification_key . t option , Field . t ) t With_hash . t Data_as_hash . t ) Flagged_option . t , Mina_numbers . Zkapp_version . Checked . t , Pickles . Impls . Step . Field . t , Mina_numbers . Global_slot . Checked . t , Boolean . var ) Poly . t let to_input ' ( t : _ Poly . t ) t = let open Random_oracle . Input . Chunked in let f mk acc field = mk ( Core_kernel . Field . get field t ) t :: acc in let app_state v = Random_oracle . Input . Chunked . field_elements ( Vector . to_array v ) v in Poly . Fields . fold ~ init [ ] : ~ app_state ( : f app_state ) app_state ~ verification_key ( : f ( fun x -> field x ) x ) x ~ zkapp_version ( : f ( fun x -> Mina_numbers . Zkapp_version . Checked . to_input x ) x ) x ~ sequence_state ( : f app_state ) app_state ~ last_sequence_slot : ( f ( fun x -> Mina_numbers . Global_slot . Checked . to_input x ) x ) x ~ proved_state : ( f ( fun ( b : Boolean . var ) var -> Random_oracle . Input . Chunked . packed ( ( b :> Field . Var . t ) t , 1 ) 1 ) ) |> List . reduce_exn ~ f : append let to_input ( t : t ) t = to_input ' { t with verification_key = Data_as_hash . hash t . verification_key . data } let digest_vk t = Random_oracle . Checked ( . hash ~ init : Hash_prefix_states . side_loaded_vk ( pack_input ( Pickles . Side_loaded . Verification_key . Checked . to_input t ) t ) t ) t let digest t = Random_oracle . Checked ( . hash ~ init : Hash_prefix_states . zkapp_account ( pack_input ( to_input t ) t ) t ) t let digest ' t = Random_oracle . Checked ( . hash ~ init : Hash_prefix_states . zkapp_account ( pack_input ( to_input ' t ) t ) t ) t end |
let typ : ( Checked . t , t ) t Typ . t = let open Poly in Typ . of_hlistable [ Zkapp_state . typ Field . typ ; Flagged_option . option_typ ~ default { : With_hash . data = None ; hash = dummy_vk_hash ( ) } ( Data_as_hash . typ ~ hash : With_hash . hash ) hash |> Typ . transport ~ there ( : Option . map ~ f ( : With_hash . map ~ f : Option . some ) some ) some ~ back : ( Option . map ~ f ( : With_hash . map ~ f ( : fun x -> Option . value_exn x ) x ) x ) x ; Mina_numbers . Zkapp_version . typ ; Pickles_types . Vector . typ Field . typ Pickles_types . Nat . N5 . n ; Mina_numbers . Global_slot . typ ; Boolean . typ ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif |
let to_input ( t : t ) t = let open Random_oracle . Input . Chunked in let f mk acc field = mk ( Core_kernel . Field . get field t ) t :: acc in let app_state v = Random_oracle . Input . Chunked . field_elements ( Vector . to_array v ) v in Poly . Fields . fold ~ init [ ] : ~ app_state ( : f app_state ) app_state ~ verification_key : ( f ( Fn . compose field ( Option . value_map ~ default ( : dummy_vk_hash ( ) ) ~ f : With_hash . hash ) hash ) ) ~ zkapp_version ( : f Mina_numbers . Zkapp_version . to_input ) to_input ~ sequence_state ( : f app_state ) app_state ~ last_sequence_slot ( : f Mina_numbers . Global_slot . to_input ) to_input ~ proved_state : ( f ( fun b -> Random_oracle . Input . Chunked . packed ( field_of_bool b , 1 ) 1 ) 1 ) 1 |> List . reduce_exn ~ f : append |
let default : _ Poly . t = { app_state = Vector . init Zkapp_state . Max_state_size . n ~ f ( : fun _ -> F . zero ) zero ; verification_key = None ; zkapp_version = Mina_numbers . Zkapp_version . zero ; sequence_state = ( let empty = Lazy . force Sequence_events . empty_hash in [ empty ; empty ; empty ; empty ; empty ] ) ; last_sequence_slot = Mina_numbers . Global_slot . zero ; proved_state = false } |
let digest ( t : t ) t = Random_oracle ( . hash ~ init : Hash_prefix_states . zkapp_account ( pack_input ( to_input t ) t ) t ) t |
let default_digest = lazy ( digest default ) default |
let field_of_bool = Mina_base_util . field_of_bool [ %% endif ] endif |
let int_to_bits ~ length x = List . init length ~ f ( : fun i -> ( x lsr i ) i land 1 = 1 ) 1 |
let int_of_bits = List . foldi ~ init : 0 ~ f ( : fun i acc b -> if b then acc lor ( 1 lsl i ) i else acc ) acc |
module Transition = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = { prev : ' a ; next : ' a } [ @@ deriving hlist , sexp , equal , yojson , hash , compare ] compare end end ] end let to_input { prev ; next } ~ f = Random_oracle_input . Chunked . append ( f prev ) prev ( f next ) next [ %% ifdef consensus_mechanism ] consensus_mechanism let typ t = Typ . of_hlistable [ t ; t ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif end |
module Flagged_data = struct type ( ' flag , ' a ) ' a t = { flag : ' flag ; data : ' a } [ @@ deriving hlist , fields ] fields [ %% ifdef consensus_mechanism ] consensus_mechanism let typ flag t = Typ . of_hlistable [ flag ; t ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist [ %% endif ] endif let to_input ' { flag ; data } ~ flag : f ~ data : d = Random_oracle_input . Chunked ( . append ( f flag ) flag ( d data ) data ) data end |
module Flagged_option = struct type ( ' bool , ' a ) ' a t = { is_some : ' bool ; data : ' a } [ @@ deriving hlist , fields ] fields let to_input ' ~ field_of_bool { is_some ; data } ~ f = Random_oracle_input . Chunked ( . append ( packed ( field_of_bool is_some , 1 ) 1 ) 1 ( f data ) data ) data let to_input { is_some ; data } ~ default ~ f = let data = if is_some then data else default in to_input ' { is_some ; data } ~ f let of_option t ~ default = match t with | None -> { is_some = false ; data = default } | Some data -> { is_some = true ; data } let to_option { is_some ; data } = Option . some_if is_some data let map ~ f { is_some ; data } = { is_some ; data = f data } [ %% ifdef consensus_mechanism ] consensus_mechanism let if_ ( ~ if_ : ' b -> then_ : ' var -> else_ : ' var -> ' var ) ' var b ~ then_ ~ else_ = { is_some = Run . run_checked ( Boolean . if_ b ~ then_ : then_ . is_some ~ else_ : else_ . is_some ) is_some ; data = if_ b ~ then_ : then_ . data ~ else_ : else_ . data } let typ t = Typ . of_hlistable [ Boolean . typ ; t ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist let option_typ ~ default t = Typ . transport ( typ t ) t ~ there ( : of_option ~ default ) default ~ back : to_option [ %% endif ] endif end |
module Set_or_keep = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = Set of ' a | Keep [ @@ deriving sexp , equal , compare , hash , yojson ] yojson end end ] end let map t ~ f = match t with Keep -> Keep | Set x -> Set ( f x ) x let to_option = function Set x -> Some x | Keep -> None let of_option = function Some x -> Set x | None -> Keep let set_or_keep t x = match t with Keep -> x | Set y -> y let is_set = function Set _ -> true | _ -> false let is_keep = function Keep -> true | _ -> false let deriver inner obj = let open Fields_derivers_zkapps . Derivers in iso ~ map : of_option ~ contramap : to_option ( ( option ~ js_type ` : Flagged_option @@ inner @@ o ( ) ) ( o ( ) ) ) obj let gen gen_a = let open Quickcheck . Let_syntax in let % bind b = Quickcheck . Generator . bool in if b then let % bind a = gen_a in return ( Set a ) a else return Keep [ %% ifdef consensus_mechanism ] consensus_mechanism module Checked : sig type ' a t val is_keep : _ t -> Boolean . var val is_set : _ t -> Boolean . var val set_or_keep : if_ ( : Boolean . var -> then_ : ' a -> else_ : ' a -> ' a ) ' a -> ' a t -> ' a -> ' a val data : ' a t -> ' a val typ : dummy : ' a -> ( ' a_var , ' a ) ' a Typ . t -> ( ' a_var t , ' a Stable . Latest . t ) t Typ . t val optional_typ : to_option ( : ' new_value -> ' value option ) option -> of_option ( : ' value option -> ' new_value ) ' new_value -> ( ' var , ' new_value ) ' new_value Typ . t -> ( ' var t , ' value Stable . Latest . t ) t Typ . t val map : f ( : ' a -> ' b ) ' b -> ' a t -> ' b t val to_input : ' a t -> f ( : ' a -> Field . Var . t Random_oracle_input . Chunked . t ) t -> Field . Var . t Random_oracle_input . Chunked . t val set : ' a -> ' a t val keep : dummy : ' a -> ' a t val make_unsafe : Boolean . var -> ' a -> ' a t end = struct type ' a t = ( Boolean . var , ' a ) ' a Flagged_option . t let set_or_keep ~ if_ ( { is_some ; data } : _ t ) t x = if_ is_some ~ then_ : data ~ else_ : x let data = Flagged_option . data let is_set = Flagged_option . is_some let is_keep x = Boolean . not ( Flagged_option . is_some x ) x let map = Flagged_option . map let typ ~ dummy t = Typ . transport ( Flagged_option . option_typ ~ default : dummy t ) t ~ there : to_option ~ back : of_option let optional_typ ( type new_value value var ) var : to_option ( : new_value -> value option ) option -> of_option ( : value option -> new_value ) new_value -> ( var , new_value ) new_value Typ . t -> ( var t , value Stable . Latest . t ) t Typ . t = fun ~ to_option ~ of_option t -> Typ . transport ( Flagged_option . typ t ) t ~ there ( : function | Set x -> { Flagged_option . is_some = true ; data = of_option ( Some x ) x } | Keep -> { Flagged_option . is_some = false ; data = of_option None } ) ~ back ( : function | { Flagged_option . is_some = true ; data = x } -> Set ( Option . value_exn ( to_option x ) x ) x | { Flagged_option . is_some = false ; data = x } -> assert ( Option . is_none ( to_option x ) x ) x ; Keep ) let to_input ( t : _ t ) t ~ f = Flagged_option . to_input ' t ~ f ~ field_of_bool ( : fun ( b : Boolean . var ) var -> ( b :> Field . Var . t ) t ) let make_unsafe is_keep data = { Flagged_option . is_some = is_keep ; data } let set data = { Flagged_option . is_some = Boolean . true_ ; data } let keep ~ dummy = { Flagged_option . is_some = Boolean . false_ ; data = dummy } end let typ = Checked . typ let optional_typ = Checked . optional_typ [ %% endif ] endif let to_input t ~ dummy : default ~ f = Flagged_option . to_input ~ default ~ f ~ field_of_bool ( Flagged_option . of_option ~ default ( to_option t ) t ) t end |
module Or_ignore = struct [ %% versioned module Stable = struct module V1 = struct type ' a t = Check of ' a | Ignore [ @@ deriving sexp , equal , compare , hash , yojson ] yojson end end ] end let gen gen_a = let open Quickcheck . Let_syntax in let % bind b = Quickcheck . Generator . bool in if b then let % map a = gen_a in Check a else return Ignore let to_option = function Ignore -> None | Check x -> Some x let of_option = function None -> Ignore | Some x -> Check x let deriver_base ~ js_type inner obj = let open Fields_derivers_zkapps . Derivers in iso ~ map : of_option ~ contramap : to_option ( ( option ~ js_type @@ inner @@ o ( ) ) ( o ( ) ) ) obj let deriver inner obj = deriver_base ~ js_type ` : Flagged_option inner obj let deriver_implicit inner obj = deriver_base ~ js_type ` : Implicit inner obj [ %% ifdef consensus_mechanism ] consensus_mechanism module Checked : sig type ' a t val typ_implicit : equal ( : ' a -> ' a -> bool ) bool -> ignore : ' a -> ( ' a_var , ' a ) ' a Typ . t -> ( ' a_var t , ' a Stable . Latest . t ) t Typ . t val typ_explicit : ignore : ' a -> ( ' a_var , ' a ) ' a Typ . t -> ( ' a_var t , ' a Stable . Latest . t ) t Typ . t val to_input : ' a t -> f ( : ' a -> Field . Var . t Random_oracle_input . Chunked . t ) t -> Field . Var . t Random_oracle_input . Chunked . t val check : ' a t -> f ( : ' a -> Boolean . var ) var -> Boolean . var val map : f_implicit ( : ' a -> ' b ) ' b -> f_explicit ( ( : Boolean . var , ' a ) ' a Flagged_option . t -> ' b ) ' b -> ' a t -> ' b val make_unsafe_implicit : ' a -> ' a t val make_unsafe_explicit : Boolean . var -> ' a -> ' a t end = struct type ' a t = | Implicit of ' a | Explicit of ( Boolean . var , ' a ) ' a Flagged_option . t let to_input t ~ f = match t with | Implicit x -> f x | Explicit t -> Flagged_option . to_input ' t ~ f ~ field_of_bool ( : fun ( b : Boolean . var ) var -> ( b :> Field . Var . t ) t ) let check t ~ f = match t with | Implicit x -> f x | Explicit { is_some ; data } -> Pickles . Impls . Step . Boolean ( . any [ not is_some ; f data ] ) let map ~ f_implicit ~ f_explicit = function | Implicit x -> f_implicit x | Explicit t -> f_explicit t let typ_implicit ( type a a_var ) a_var ~ equal ( ~ ignore : a ) a ( t : ( a_var , a ) a Typ . t ) t : ( a_var t , a Stable . Latest . t ) t Typ . t = Typ . transport t ~ there ( : function Check x -> x | Ignore -> ignore ) ignore ~ back ( : fun x -> if equal x ignore then Ignore else Check x ) x |> Typ . transport_var ~ there ( : function Implicit x -> x | Explicit _ -> assert false ) false ~ back ( : fun x -> Implicit x ) x let typ_explicit ( type a_var a ) a ~ ignore ( t : ( a_var , a ) a Typ . t ) t = Typ . transport_var ( Flagged_option . option_typ ~ default : ignore t ) t ~ there ( : function Implicit _ -> assert false | Explicit t -> t ) t ~ back ( : fun t -> Explicit t ) t |> Typ . transport ~ there : to_option ~ back : of_option let make_unsafe_implicit data = Implicit data let make_unsafe_explicit is_ignore data = Explicit { is_some = is_ignore ; data } end let typ_implicit = Checked . typ_implicit let typ_explicit = Checked . typ_explicit [ %% endif ] endif end |
module Account_state = struct [ %% versioned module Stable = struct module V1 = struct type t = Empty | Non_empty | Any [ @@ deriving sexp , equal , yojson , hash , compare , enum ] enum let to_latest = Fn . id end end ] end module Encoding = struct type ' b t = { any : ' b ; empty : ' b } [ @@ deriving hlist ] hlist let to_input ~ field_of_bool { any ; empty } = Random_oracle_input . Chunked . packeds [ | ( field_of_bool any , 1 ) 1 ; ( field_of_bool empty , 1 ) 1 ] | end let encode : t -> bool Encoding . t = function | Empty -> { any = false ; empty = true } | Non_empty -> { any = false ; empty = false } | Any -> { any = true ; empty = false } let decode : bool Encoding . t -> t = function | { any = false ; empty = true } -> Empty | { any = false ; empty = false } -> Non_empty | { any = true ; empty = false } | { any = true ; empty = true } -> Any let to_input ( x : t ) t = Encoding . to_input ~ field_of_bool ( encode x ) x let check ( t : t ) t ( x : [ ` Empty | ` Non_empty ] ) = match ( t , x ) x with | Any , _ | Non_empty , ` Non_empty | Empty , ` Empty -> Ok ( ) | _ -> Or_error . error_string " Bad account_type " [ %% ifdef consensus_mechanism ] consensus_mechanism module Checked = struct open Pickles . Impls . Step type t = Boolean . var Encoding . t let to_input ( t : t ) t = Encoding . to_input t ~ field_of_bool ( : fun ( b : Boolean . var ) var -> ( b :> Field . t ) t ) let check ( t : t ) t ~ is_empty = Boolean ( . any [ t . any ; t . empty && is_empty ; ( not t . empty ) empty && not is_empty ] ) end let typ : ( Checked . t , t ) t Typ . t = let open Encoding in Typ . of_hlistable [ Boolean . typ ; Boolean . typ ] ~ var_to_hlist : to_hlist ~ var_of_hlist : of_hlist ~ value_to_hlist : to_hlist ~ value_of_hlist : of_hlist |> Typ . transport ~ there : encode ~ back : decode [ %% endif ] endif end |
module F = Pickles . Backend . Tick . Field [ %% else ] else |
module F = Snark_params . Tick . Field [ %% endif ] endif |
let invalid_public_key : Public_key . Compressed . t = { x = F . zero ; is_odd = false } Option . is_none ( Public_key . decompress invalid_public_key ) invalid_public_key |
module Spec = Transaction_snark . For_tests . Spec ( module struct let memo = Signed_command_memo . create_from_string_exn " Snapp deploy tests " let constraint_constants = U . constraint_constants let % test_unit " create a new snapp account / deploy a smart contract " = let open Mina_transaction_logic . For_tests in Quickcheck . test ~ trials : 1 U . gen_snapp_ledger ~ f ( : fun ( { init_ledger ; specs } , new_kp ) new_kp -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let spec = List . hd_exn specs in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 10_000_000_000 in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ new_kp ] ; memo ; new_zkapp_account = true ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let parties = Transaction_snark . For_tests . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " deploy multiple ZkApps " = let open Mina_transaction_logic . For_tests in let gen = let open Quickcheck . Generator . Let_syntax in let % bind spec , kp1 = U . gen_snapp_ledger in let % map kps = Quickcheck . Generator . list_with_length 2 Signature_lib . Keypair . gen in ( spec , kp1 :: kps ) kps in Quickcheck . test ~ trials : 1 gen ~ f ( : fun ( { init_ledger ; specs } , kps ) kps -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let spec = List . hd_exn specs in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 7_000_000_000 in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = kps ; memo ; new_zkapp_account = true ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let parties = Transaction_snark . For_tests . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " change a non - snapp account to snapp account / deploy a smart \ contract " = let open Mina_transaction_logic . For_tests in Quickcheck . test ~ trials : 1 U . gen_snapp_ledger ~ f ( : fun ( { init_ledger ; specs } , _new_kp ) _new_kp -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let spec = List . hd_exn specs in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 10_000_000_000 in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ fst spec . sender ] ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let parties = Transaction_snark . For_tests . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " change a non - snapp account to snapp account / deploy a smart \ contract - different fee payer " = let open Mina_transaction_logic . For_tests in Quickcheck . test ~ trials : 1 U . gen_snapp_ledger ~ f ( : fun ( { init_ledger ; specs } , _new_kp ) _new_kp -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let spec0 = List . nth_exn specs 0 in let spec1 = List . nth_exn specs 1 in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . of_int 10_000_000_000 in let test_spec : Spec . t = { sender = spec0 . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ fst spec1 . sender ] ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let parties = Transaction_snark . For_tests . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger [ parties ] ) ) ) let % test_unit " Fails to deploy if the account is not present and amount is \ insufficient " = let open Mina_transaction_logic . For_tests in Quickcheck . test ~ trials : 1 U . gen_snapp_ledger ~ f ( : fun ( { init_ledger ; specs } , new_kp ) new_kp -> Ledger . with_ledger ~ depth : U . ledger_depth ~ f ( : fun ledger -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> let spec = List . hd_exn specs in let fee = Currency . Fee . of_int 1_000_000 in let amount = Currency . Amount . zero in let test_spec : Spec . t = { sender = spec . sender ; fee ; fee_payer = None ; receivers = [ ] ; amount ; zkapp_account_keypairs = [ new_kp ] ; memo ; new_zkapp_account = false ; snapp_update = Party . Update . dummy ; current_auth = Permissions . Auth_required . Signature ; call_data = Snark_params . Tick . Field . zero ; events = [ ] ; sequence_events = [ ] ; protocol_state_precondition = None ; account_precondition = None } in let parties = Transaction_snark . For_tests . deploy_snapp test_spec ~ constraint_constants in Init_ledger . init ( module Ledger . Ledger_inner ) Ledger_inner init_ledger ledger ; U . check_parties_with_merges_exn ledger ~ expected_failure : Invalid_fee_excess [ parties ] ) ) ) end ) |
let logger = Logger . create ( ) |
let mk_ledgers_and_fee_payers ( ? is_timed = false ) false ~ num_of_fee_payers ( ) = let fee_payer_keypairs = Array . init num_of_fee_payers ~ f ( : fun _ -> Keypair . create ( ) ) in let fee_payer_pks = Array . map fee_payer_keypairs ~ f ( : fun fee_payer_keypair -> Public_key . compress fee_payer_keypair . public_key ) in let fee_payer_account_ids = Array . map fee_payer_pks ~ f ( : fun fee_payer_pk -> Account_id . create fee_payer_pk Token_id . default ) in let ( initial_balance : Currency . Balance . t ) t = Currency . Balance . of_int 1_000_000_000_000_000 in let ( fee_payer_accounts : Account . t array ) array = if is_timed then let initial_minimum_balance = Currency . Balance . of_int 1_000_000_000_000_000 in let cliff_time = Mina_numbers . Global_slot . of_int 1_000 in let cliff_amount = Currency . Amount . zero in let vesting_period = Mina_numbers . Global_slot . of_int 10 in let vesting_increment = Currency . Amount . of_int 100_000_000_000 in Array . map fee_payer_account_ids ~ f ( : fun fee_payer_account_id -> Account . create_timed fee_payer_account_id initial_balance ~ initial_minimum_balance ~ cliff_time ~ cliff_amount ~ vesting_period ~ vesting_increment |> Or_error . ok_exn ) else Array . map fee_payer_account_ids ~ f ( : fun fee_payer_account_id -> Account . create fee_payer_account_id initial_balance ) in let ledger = Mina_ledger . Ledger . create ~ depth : 10 ( ) in Array . iter2_exn fee_payer_accounts fee_payer_account_ids ~ f ( : fun fee_payer_account fee_payer_account_id -> Mina_ledger . Ledger . get_or_create_account ledger fee_payer_account_id fee_payer_account |> Or_error . ok_exn |> fun _ -> ( ) ) ; let keys = List . init 1000 ~ f ( : fun _ -> Keypair . create ( ) ) in let keymap = List . map ( Array . to_list fee_payer_keypairs @ keys ) keys ~ f ( : fun { public_key ; private_key } -> ( Public_key . compress public_key , private_key ) private_key ) |> Public_key . Compressed . Map . of_alist_exn in ( ledger , fee_payer_keypairs , keymap ) keymap |
let ` VK vk , ` Prover prover = Lazy . force U . trivial_zkapp |
let generate_parties_and_apply_them_consecutively ( ) = let num_of_fee_payers = 5 in let trials = 6 in let ledger , fee_payer_keypairs , keymap = mk_ledgers_and_fee_payers ~ num_of_fee_payers ( ) in Test_util . with_randomness 123456789 ( fun ( ) -> let test i = Quickcheck . test ~ trials : 1 ( Mina_generators . Parties_generators . gen_parties_from ~ protocol_state_view : U . genesis_state_view ~ fee_payer_keypair : fee_payer_keypairs ( . i / 2 ) 2 ~ keymap ~ ledger ~ vk ~ prover ( ) ) ~ f ( : fun parties -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> [ % log info ] info ~ metadata : [ ( " parties " , Parties . to_yojson parties ) parties ; ( " accounts " , ` List ( List . map ( Mina_ledger . Ledger . accounts ledger |> Set . to_list ) to_list ~ f ( : fun account_id -> Mina_ledger . Ledger . location_of_account ledger account_id |> Option . value_exn |> Mina_ledger . Ledger . get ledger |> Option . value_exn |> Account . to_yojson ) ) ) ] " generated parties " ; U . check_parties_with_merges_exn ledger [ parties ] ) ) in for i = 0 to trials - 1 do test i done ) |
let generate_parties_and_apply_them_freshly ( ) = let num_of_fee_payers = 5 in let trials = 6 in Test_util . with_randomness 123456789 ( fun ( ) -> let test i = let ledger , fee_payer_keypairs , keymap = mk_ledgers_and_fee_payers ~ num_of_fee_payers ( ) in Quickcheck . test ~ trials : 1 ( Mina_generators . Parties_generators . gen_parties_from ~ protocol_state_view : U . genesis_state_view ~ fee_payer_keypair : fee_payer_keypairs ( . i / 2 ) 2 ~ keymap ~ ledger ~ vk ~ prover ( ) ) ~ f ( : fun parties -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> U . check_parties_with_merges_exn ledger [ parties ] ) ) in for i = 0 to trials - 1 do test i done ) |
let mk_invalid_test ~ num_of_fee_payers ~ trials ~ type_of_failure ~ expected_failure_status = Test_util . with_randomness 123456789 ( fun ( ) -> let test i = let ledger , fee_payer_keypairs , keymap = mk_ledgers_and_fee_payers ~ num_of_fee_payers ( ) in Quickcheck . test ~ trials : 1 ( Mina_generators . Parties_generators . gen_parties_from ~ failure ( : Some type_of_failure ) type_of_failure ~ protocol_state_view : U . genesis_state_view ~ fee_payer_keypair : fee_payer_keypairs ( . i / 2 ) 2 ~ keymap ~ ledger ~ vk ~ prover ( ) ) ~ f ( : fun parties -> Async . Thread_safe . block_on_async_exn ( fun ( ) -> [ % log info ] info ~ metadata [ : ( " parties " , Parties . to_yojson parties ) parties ] " generated parties " ; U . check_parties_with_merges_exn ~ expected_failure : expected_failure_status ledger [ parties ] ~ state_body : U . genesis_state_body ) ) in for i = 0 to trials - 1 do test i done ) |
Subsets and Splits