123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572(*****************************************************************************)(* *)(* MIT License *)(* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)letwith_seed(f:unit->unit)=(* Seed for deterministic pseudo-randomness:
If the environment variable RANDOM_SEED is set, then its value is used as
as seed. Otherwise, a random seed is used.
WARNING: using [Random.self_init] elsewhere in the tests breaks thedeterminism.
*)letseed=matchSys.getenv_opt"RANDOM_SEED"with|None->Random.self_init();Random.int1073741823|Somev->(tryint_of_stringvwith_->failwith(Format.sprintf"Invalid random seed '%s'. Maybe you need to run '$ unset \
RANDOM_SEED' in your terminal?"v))inPrintf.printf"Random seed: %d\n"seed;Random.initseed;f()letoutput_buffer=refstdoutletwith_output_to_file(f:unit->unit)=output_buffer:=open_out"test.output";f();close_out!output_bufferletset_seeds=Random.initsletbigstring_of_filefilename~hash=letbs=letfd=Unix.openfilefilename[Unix.O_RDONLY]0o440inBigarray.array1_of_genarray@@Unix.map_filefdBigarray.charBigarray.c_layoutfalse[|(* [-1] means read the whole file *)-1|]inletcomputed_hash=letst=Hacl_star.EverCrypt.Hash.init~alg:Hacl_star.SharedDefs.HashDefs.BLAKE2binletlen=48(* works for both g1 and g2 *)inletmsg=Bytes.createleninfori=0to(Bigstringaf.lengthbs/len)-1doBigstringaf.blit_to_bytesbs~src_off:(i*len)msg~dst_off:0~len;Hacl_star.EverCrypt.Hash.update~st~msgdone;Hacl_star.EverCrypt.Hash.finish~stinlethash=Hex.to_bytes(`Hexhash)inifcomputed_hash<>hashthenfailwith("Invalid hash: "^filename);bsletload_real_srsprefix=letopenOctez_bls12_381_polynomial.Srsinlet(//)s1s2=s1^"/"^s2in((Srs_g1.of_bigstring(bigstring_of_file(prefix//"srs_filecoin_g1_21")~hash:"25281025229b67eed4bcf4451dca0e5ac3fc6c5bf5934f54449105a7feba8049cf0e9f390f23528d5f860387c07a6b374f2ef6dad6fd73b051e4cc4699974738")~len:(1lsl21)|>Result.get_ok,Srs_g2.of_bigstring(bigstring_of_file(prefix//"srs_filecoin_g2_1")~hash:"ee034f5e6d3d9dc2097861ffb278438573f0a9c84afd6806a5b53b158b0e6e6847dc8a84e1b01c3c161ed4593816d59bf4817c797ffad6fffbea143987e340a4")~len:2|>Result.get_ok),(Srs_g1.of_bigstring(bigstring_of_file(prefix//"srs_zcash_g1_1")~hash:"435fd5b85e1e3271c8e241b25da799df3e312e67d06c9e009fb967a8d597ed37897047aa48659526ce10db857ee02c64e6f577ef80485d34d7506fff40a901b4")~len:2|>Result.get_ok,Srs_g2.of_bigstring(bigstring_of_file(prefix//"srs_zcash_g2_10")~hash:"39ebc126d18caade1bee9294124292a089746441cee6b80efb37f0a1e6a37e8acabfa3c0a3b0c6ce15ea3a46a5f5373be222bb1a54b332d43e25f489c66dec49")~len:(1lsl10)|>Result.get_ok))letmake_fake_srs()=letopenOctez_bls12_381_polynomialin(Srs.generate_insecure145,Srs.generate_insecure114)letsrs=matchSys.getenv_opt"SRS_DIR"with|None->make_fake_srs()|Someprefix->load_real_srsprefixletrecrepeatnf()=ifn>0then(f();repeat(n-1)f())letmust_failf=letexceptionLocalintry(tryf()with_->raiseLocal);assertfalsewith|Local->()|_->assertfalseletstring_of_bytesbytes=ifbytes<=1024.thenPrintf.sprintf"%3.2f B "byteselseletkilobytes=bytes/.1024.inifkilobytes<=1024.thenPrintf.sprintf"%3.2f KB"kilobyteselseletmegabytes=kilobytes/.1024.inifmegabytes<=1024.thenPrintf.sprintf"%3.2f MB"megabyteselseletgigabytes=megabytes/.1024.inPrintf.sprintf"%.2f GB"gigabyteslethash_of_reprtv=letserialized_bytes=Bytes.of_string@@Repr.(unstage@@to_bin_stringt)vinHacl_star.Hacl.Blake2b_32.hashserialized_bytes32|>Hex.of_bytes|>Hex.showletget_input_com_secretsprivate_inputsinput_com_sizes=letsecrets,_=List.fold_left(fun(secrets,l)size->(Array.subprivate_inputslsize::secrets,l+size))([],0)input_com_sizesinList.revsecretsmoduleTime=structtypedata={n:int;sum:float;sum_squares:float;last:float}letstr_time=ref""letzero_data={n=0;sum=0.;sum_squares=0.;last=0.}letsetup=refzero_dataletprove=refzero_dataletverify=refzero_dataletreset()=setup:=zero_data;prove:=zero_data;verify:=zero_dataletupdatedatatime=letsum=time+.!data.suminletsum_squares=(time*.time)+.!data.sum_squaresindata:={n=!data.n+1;sum;sum_squares;last=time}letmeandata=!data.sum/.float_of_int!data.nletvardata=letm=meandatain(!data.sum_squares/.float_of_int!data.n)-.(m*.m)letstddata=sqrt(vardata)letstring_of_timet=ift>60.thenPrintf.sprintf"%3.2f m "(t/.60.)elseift>1.thenPrintf.sprintf"%3.2f s "telseift>0.001thenPrintf.sprintf"%3.2f ms"(t*.1_000.)elsePrintf.sprintf"%3.0f µs"(t*.1_000_000.)lettimedescriptionf=Gc.full_major();letst1=Gc.stat()inletstart=Unix.gettimeofday()inletres=f()inletstop=Unix.gettimeofday()inletd=stop-.startinlet()=matchdescriptionwith|"setup"->updatesetupd|"prove"->updateproved|"verify"->updateverifyd|_->()inlett_str=string_of_timedinletst2=Gc.stat()inletallocations=(st2.minor_words+.st2.major_words-.st2.promoted_words-.(st1.minor_words+.st1.major_words-.st1.promoted_words))*.8.|>string_of_bytesinlettop_heap_words=ifst2.top_heap_words>st1.top_heap_wordsthenst2.top_heap_words|>float_of_int|>Float.mul8.|>string_of_floatelse"?"inPrintf.printf"%-8s: Time: %8s Allocations %6s MaxHeap: %s\n%!"descriptiont_strallocationstop_heap_words;resletreset_str()=str_time:=""letupdate_str?header()=letheader=matchheaderwithNone->""|Someheader->header^"\n"instr_time:=!str_time^Printf.sprintf"%s%f\n%f\n%f\n"header!setup.last!prove.last!verify.lastletprint_time_in_filefile=letoc=open_outfileinPrintf.fprintfoc"%s"!str_time;close_outocletbench_test_circuit~nb_repfunc()=reset();repeatnb_repfunc();assert(nb_rep=!setup.n&&nb_rep=!prove.n&&nb_rep=!verify.n);Printf.printf"\nTimes over %d repetitions (95%% confidence interval):\n\n"nb_rep;letpp=string_of_timeinletz=1.96inPrintf.printf" Setup : %s ± %s\n"(pp(meansetup))(pp(z*.stdsetup));Printf.printf" Prove : %s ± %s\n"(pp(meanprove))(pp(z*.stdprove));Printf.printf" Verify: %s ± %s\n"(pp(meanverify))(pp(z*.stdverify));Printf.printf"\n"lettime_if_verboseverbosedescriptionf=ifverbosethentimedescriptionfelsef()endmoduleMake(Main:Plonk.Main_protocol.S)=structopenPlonk.CircuitmoduleSingleton=structincludeMainletsetup~zero_knowledgecircuit~srs=letcircuits_map=Kzg.SMap.singleton""(circuit,1)inMain.setup~zero_knowledgecircuits_map~srsletprovepp~(inputs:circuit_prover_inputlist)=letinputs=Kzg.SMap.singleton""inputsinMain.provepp~inputsletverifypp~inputsproof=letinputs=Kzg.SMap.singleton""inputsinMain.verifypp~inputsproofendletmulti_input_commitppinput_commitment_secrets=List.fold_left(fun(cmts,shift)secret->(Main.input_commit~shiftppsecret::cmts,shift+Array.lengthsecret))([],0)input_commitment_secrets|>fst|>List.revletprint_infonamezero_knowledgeproofpp_proverpp_verifier=letproof_size=Data_encoding.Binary.lengthMain.proof_encodingproof|>Float.of_intinletproof_hash=hash_of_reprMain.proof_tproofinletprover_pp_hash=hash_of_reprMain.prover_public_parameters_tpp_proverinletverifier_pp_hash=hash_of_reprMain.verifier_public_parameters_tpp_verifierinPrintf.fprintf!output_buffer"%s:\n\
Proof size: %s\n\
Proof hash: %s\n\
Prover_pp hash: %s\n\
Verifier_pp hash: %s\n\n"(ifzero_knowledgethen"zk-"^nameelsename)(string_of_bytesproof_size)proof_hashprover_pp_hashverifier_pp_hashletmake_secretpp_proverinput_com_sizeswitness=letopenMaininletinput_com_secrets=get_input_com_secretswitnessinput_com_sizesinletinput_commitments=multi_input_commitpp_proverinput_com_secretsin{witness;input_commitments}lettest_circuits~name?(zero_knowledge=false)?(outcome=Cases.Valid)?(verbose=false)circuit_mapprivate_inputs=lettime_if_verboseverbosedescriptionf=ifverbosethenTime.timedescriptionfelsef()inifverbosethenKzg.SMap.iter(funcname(circuit,_n)->Format.printf"circuit '%s' has %d constraints\n"cnamecircuit.circuit_size)circuit_map;letpp_prover,pp_verifier=time_if_verboseverbose"setup"(fun()->Main.setup~zero_knowledgecircuit_map~srs)inletprover_inputs=Kzg.SMap.mapi(func_name->letc=fst(Kzg.SMap.findc_namecircuit_map)inList.map(make_secretpp_proverc.input_com_sizes))private_inputsinletverifier_inputs=Main.to_verifier_inputspp_proverprover_inputsinmatchoutcomewith|Valid->(letproof=time_if_verboseverbose"prove"(fun()->Main.provepp_prover~inputs:prover_inputs)inGc.full_major();letv=time_if_verboseverbose"verify"(fun()->Main.verifypp_verifier~inputs:verifier_inputsproof)inassertv;print_infonamezero_knowledgeproofpp_proverpp_verifier;(* Test that verification fails if we mutate public inputs *)matchMain.Internal_for_tests.mutate_viverifier_inputswith|None->()(* No public inputs *)|Someverifier_inputs->letv=Main.verifypp_verifier~inputs:verifier_inputsproofinassert(notv))|_->(tryletproof=Main.provepp_prover~inputs:prover_inputsinassert(not(Main.verifypp_verifier~inputs:verifier_inputsproof))with|Main.Rest_not_null_->ifoutcome=Proof_errorthen()elseraise(Invalid_argument"Proving error: incorrect witness")|Main.Entry_not_in_table_->ifoutcome=Lookup_errorthen()elseraise(Invalid_argument"Proving error: incorrect lookup")|e->raisee)(* generator must be n-th root of unity
n must be in the form 2^i
for k number of gates
a_c, b_c, c_c, ql, qr, qo, qm, qc must be lists of length k
x is an array of length m = 3+2(k-1)
l between 0 and m-1, l first parameters will be taken as public inputs
n = k+l
valid_proof is true if the proof is expected valid, false if it must fail
if verbose print run times when valid_proof is true
*)lettest_circuit~name?zero_knowledge?outcome?verbosecircuitprivate_inputs=letcircuit_map=Kzg.SMap.singletonname(circuit,1)inletinputs=Kzg.SMap.singletonname[private_inputs]intest_circuits~name?zero_knowledge?outcome?verbosecircuit_mapinputsletrun_test_case~zero_knowledge?verboseCases.{name;circuit;witness;outcome}()=test_circuit~name~zero_knowledge~outcome?verbosecircuitwitnesslettest_aggregated_cases?(prefix="")cases=letname,circuits_map,inputs_map,outcome=Cases.aggregate_cases~prefixcasesin(name,fun~zero_knowledge()->test_circuits~name~zero_knowledgecircuits_mapinputs_map~outcome)endmodulePlompiler_Helpers=structopenPlompilermoduleCS=Plonk.Circuittypetest_info={valid:bool;name:string;flamegraph:bool}moduletypeTest=functor(L:LIB)->sigopenLvaltests:((unit->unitreprt)*test_info)listendletto_test?plonk?(optimize=true)test()=letmoduleTest=(valtest:Test)inletcircuits=letmoduleE1=Test(LibCircuit)inE1.testsinletresults=letmoduleE2=Test(LibResult)inE2.testsinletprint_regressionsinfo_name(cs:LibCircuit.cs_result)=letnb_constraints=Array.(concatcs.cs|>length)inletmax_rc,sum_rc=letw_bounds=List.map(fun(_w,lw)->List.fold_left(funacc(_i,b)->acc+b)0lw)cs.range_checksinletmax_rc=List.fold_leftmax0w_boundsinletsum_rc=List.fold_leftInt.add0w_boundsin(max_rc,sum_rc)inletsize_of_tables=List.fold_left(funacct->acc+Csir.Table.sizet)0cs.tablesinletcircuit_size=maxnb_constraints(maxmax_rcsize_of_tables)inletlog2x=ifx=0then0.elseFloat.log2@@Int.to_floatxinPrintf.fprintf!output_buffer"%s:\n\
Constraints : %d [%.2f]\n\
Range-Checks-Total: %d [%.2f]\n\
Range-Checks-Max : %d [%.2f]\n\
Tables : %d [%.2f]\n\
Circuit Size : %d [%.2f]\n\n"info_namenb_constraints(log2nb_constraints)sum_rc(log2sum_rc)max_rc(log2max_rc)size_of_tables(log2size_of_tables)circuit_size(log2circuit_size)inletrun_one_test(circuit,info)(result,_)=letcs=LibCircuit.(get_cs(circuit()))inletinitial,_=LibCircuit.(get_inputs(circuit()))inifinfo.flamegraphthen(Plompiler.Utils.dump_label_traces(info.name^"_flamegraph")cs.cs;Plompiler.Utils.dump_label_range_checks_traces(info.name^"_flamegraph_range_checks")cs.range_checks_labels);letpi=trySolver.solvecs.solverinitial|>funx->Somexwith_->Noneinmatchpiwith|None->assert(notinfo.valid)|Someprivate_inputs->(* Printf.printf
"Trace:\n%s\n%s\n"
(String.concat
","
(List.init (Array.length private_inputs) string_of_int))
(String.concat
","
(List.map S.string_of_scalar (Array.to_list private_inputs))) ;
Printf.printf "CS:\n%s\n" (CS.to_string cs) ; *)ifnotinfo.validthenassert(not@@CS.satcsprivate_inputs)else(print_regressionsinfo.namecs;letres=LibResult.get_result(result())inletserialized_res=LibResult.serializeresinletout_size=Array.lengthserialized_resinlettrace_out=Array.subprivate_inputs(Array.lengthprivate_inputs-out_size)out_sizeinassert(CS.satcsprivate_inputs);letcs,private_inputs=ifoptimizethen(letcs=LibCircuit.(get_cs~optimize(circuit()))inprint_regressions(info.name^"_optimized")cs;letprivate_inputs=Solver.solvecs.solverinitialinassert(CS.satcsprivate_inputs);(cs,private_inputs))else(cs,private_inputs)inifinfo.flamegraphthenPlompiler.Utils.dump_label_traces(info.name^"_opt_flamegraph")cs.cs;(* Compare values obtained from Result and Circuit interpreters *)assert(Array.for_all2S.(=)serialized_restrace_out);matchplonkwith|None->()|Someplonk->letmoduleMain=(valplonk:Plonk.Main_protocol.S)inletopenMake(Main)inletcircuit=CS.to_plonkcsintest_circuit~name:info.name~zero_knowledge:false~outcome:Validcircuitprivate_inputs)inList.iter2run_one_testcircuitsresultsmoduleUtils(L:LIB)=structopenL(* We test equality for Num, Bool, lists, tuples *)lettest_equalxz()=let*x=input~kind:`Publicxinlet*z=inputzinassert_equalxzletsix=Input.scalar@@S.of_string@@string_of_intxlettest~valid?(name="test")?(flamegraph=false)x=(x,{valid;name;flamegraph})endendincludePlompiler_Helpers