123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167(*****************************************************************************)(* *)(* 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. *)(* *)(*****************************************************************************)includeLang_coremoduleTables=Csir.TablesopenSolvermoduleCS=Csir.CSlettables=Csir.table_registryletone=S.oneletmone=S.(negateone)typescalar=XofS.ttype_repr=|Unit:unitrepr|Scalar:int->scalarrepr|Bool:int->boolrepr|Pair:'arepr*'brepr->('a*'b)repr|List:'areprlist->'alistreprtypestate={nvars:int;cs:CS.t;inputs:S.tarray;pi_size:int;(* Flag indicating if we are receiving public inputs. Starts true.*)public:bool;(* Flag indicating if we are receiving inputs. Starts true. This prevents
assigning intermediary variables (using fresh) before an input. *)input_flag:bool;(*
Boolean wires to be checked.
If at the end of the circuit ([get_cs]) this is not empty, their
conjunction will be asserted.
*)check_wires:boolreprlist;(* Delayed computation, used to dump the implicit checks at the end.
This is necessary because some implicit checks on the inputs might
create intermediary variables, which would set to false the [input_flag]
before some inputs are processed.
*)delayed:state->state*unitrepr;tables:stringlist;solver:Solver.t;(* label trace *)labels:stringlist;}type'at=state->state*'aletret:'a->'at=funxs->(s,x)let(let*):'at->('a->'bt)->'bt=funmfs->lets,o=msinfoslet(let*&):scalarreprt->(int->'breprt)->'breprt=funmfs->lets,Scalaro=msinfoslet(>*)mf=let*Unit=minfletrecfoldMfel=matchlwith|[]->rete|x::xs->let*y=fexinfoldMfyxsletrecmapM:('a->'bt)->'alist->'blistt=funfls->matchlswith|[]->ret@@[]|l::ls->let*o=flinlet*rest=mapMflsinret@@(o::rest)letmap2Mflsrs=mapM(fun(a,b)->fab)(List.combinelsrs)letreciterMfl=matchlwith|[]->retUnit|x::xs->let*_=fxiniterMfxsletiter2Mflsrs=iterM(fun(a,b)->fab)(List.combinelsrs)letwith_bool_check:boolreprt->unitreprt=funcs->lets,b=csin({swithcheck_wires=b::s.check_wires},Unit)moduleInput=structtype'aimplicit_check='arepr->unitreprtletdefault_check:'aimplicit_check=fun_->retUnittype'at'=|U:unitt'|S:scalar->scalart'|B:bool->boolt'|P:'at'*'bt'->('a*'b)t'|L:'at'list->'alistt'and'ainput='at'*'aimplicit_checktype'at='ainputletwith_implicit_bool_checkbc(i,a)=letcheckxs=({swithdelayed=s.delayed>*with_bool_check(bcx)},Unit)in(i,funrepr->arepr>*checkrepr)letwith_assertionna(i,a)=letdelay_assertionxs=({swithdelayed=s.delayed>*nax},Unit)in(i,funrepr->arepr>*delay_assertionrepr)letsx=(S(Xx),default_check)letscalarx=sxletto_scalar(S(Xx),_)=xletboolb=(Bb,default_check)letto_bool(Bb,_)=bletunit=(U,default_check)letpair:'at->'bt->('a*'b)t=fun(a,check_a)(b,check_b)->(P(a,b),fun(Pair(ar,br))->check_aar>*check_bbr)letto_pair(P(a,b),_)=((a,default_check),(b,default_check))letlist:'atlist->'alistt=funl->(L(List.mapfstl),fun(Listlr)->let*_l=mapM(fun((_,asssertion),r)->asssertionr)(List.combinellr)inretUnit)letto_list(Ll,_)=List.map(funi->(i,default_check))lletrecmake_repr:typea.at'->int->arepr*int=funinputstart->matchinputwith|U->(Unit,start)|S_->(Scalarstart,start+1)|B_->(Boolstart,start+1)|P(l,r)->letl,m=make_reprlstartinletr,e=make_reprrmin(Pair(l,r),e)|Ll->letl,e=List.fold_left(fun(l,i)x->letr,i'=make_reprxiin(r::l,i'))([],start)lin(List(List.revl),e)endmoduleDummy=structletscalar=Input.(S(XS.zero))letbool=Input.Bfalseletlistna=Input.L(List.initn(fun_->a))endletrecencode:typea.aInput.t'->S.tlist=funinput->matchinputwith|U->[]|S(Xs)->[s]|Bb->ifbthen[S.one]else[S.zero]|P(l,r)->encodel@encoder|Ll->List.concat_mapencodelletserializei=Array.of_list@@encodeiletreceq:typea.arepr->arepr->bool=funab->match(a,b)with|Scalara,Scalarb|Boola,Boolb->a=b|Pair(al,ar),Pair(bl,br)->eqalbl&&eqarbr|Listl1,Listl2->List.for_all2eql1l2|Unit,Unit->trueletpairlr=Pair(l,r)letof_pair(Pair(l,r))=(l,r)letto_listl=Listlletof_list(Listl)=lletwith_label~labelms=lets'={swithlabels=label::s.labels}inlets'',a=ms'in({s''withlabels=s.labels},a)letadd_solver:solver:Solver.solver_desc->unitreprt=fun~solvers->({swithsolver=Solver.append_solversolvers.solver},Unit)letmap5f(a,b,c,d,e)=(fa,fb,fc,fd,fe)letdefault_solver?(to_solve=C)g=letc=g.(0)inletqc,ql,qr,qo,qm=map5CS.(get_selc.sels)("qc","ql","qr","qo","qm")inArith{a=c.a;b=c.b;c=c.c;qc;ql;qr;qo;qm;to_solve}letappend:CS.gate->?solver:Solver.solver_desc->unitreprt=fungate?solvers->letsolver=matchsolverwith|Somes->s|None->ifArray.lengthgate=1thendefault_solvergateelseSkipinletgate=Array.map(func->Csir.CS.{cwithlabel=c.label@s.labels})gateinletcs=gate::s.csinletsolver=Solver.append_solversolvers.solverin({swithcs;solver},Unit)letappend_lookup:a:inttagged->b:inttagged->c:inttagged->table:string->string->unitreprt=fun~a~b~c~tablelabels->letrecfind_index:'alist->int->'a->intoption=funliy->matchlwith|[]->None|x::xs->ifx=ythenSomeielsefind_indexxs(i+1)yinletuse_tablesid=matchfind_indexs.tables0idwith|Somei->(s,i)|None->leti=List.lengths.tablesinlettables=s.tables@[id]in({swithtables},i)inlets,index=use_tablestableinletsolver=Lookup{a;b;c;table}inletmap3f(a,b,c)=(fa,fb,fc)inleta,b,c=map3untag(a,b,c)inletcstr=CS.new_constraint~a~b~c~q_plookup:S.one~q_table:(S.of_z(Z.of_intindex))~labels:s.labelslabelinletcs=[|cstr|]::s.csin({swithcs;solver=Solver.append_solversolvers.solver},Unit)(* Records inputs, for external use *)letinput:typea.?public:bool->aInput.t->areprt=fun?(public=false)inp->letrecaux:typea.?public:bool->aInput.t'->areprt=fun?(public=false)inps->ifpublic&¬s.publicthenfailwith"Public input after private";ifnots.input_flagthenfailwith"Inputs must be assigned before operations";letserialized=serializeinpinletinputs=Array.appends.inputsserializedinletpi_size=(ifpublicthenArray.lengthserializedelse0)+s.pi_sizeinmatchinpwith|Input.U|Input.S_->letr,nvars=Input.make_reprinps.nvarsin({swithnvars;inputs;pi_size;public},r)|Input.B_->letBoolo,nvars=Input.make_reprinps.nvarsinlets,_=(append[|CS.new_constraint~a:o~b:o~c:0~ql:mone~qm:one"bool"|]~solver:Skip){swithnvars;inputs;pi_size;public}in(s,Boolo)|Input.P(l,r)->(let*l=aux~publiclinlet*r=aux~publicrinret@@Pair(l,r))s|Input.Lls->(let*l=mapM(aux~public)lsinret@@Listl)sinletinp,implicit_check=inpinlet*i=with_label~label:"Core.input"@@aux~publicinpinimplicit_checki>*reti(* Doesn't record inputs, for interal use *)letfresh:typea.aInput.t'->areprt=letrecaux:typea.aInput.t'->areprt=funinputs->lets={swithinput_flag=false}inmatchinputwith|Input.U|Input.S_->letr,nvars=Input.make_reprinputs.nvarsin({swithnvars},r)|Input.B_->letBoolo,nvars=Input.make_reprinputs.nvarsinlets,_=append[|CS.new_constraint~a:o~b:o~c:0~ql:mone~qm:one"bool"|]~solver:Skip{swithnvars}in(s,Boolo)|Input.P(l,r)->(let*l=auxlinlet*r=auxrinret@@Pair(l,r))s|Input.Lls->(let*l=mapMauxlsinret@@Listl)sinfuninput->with_label~label:"Core.fresh"@@auxinputletserialize(i,_)=serializeiletdeserialize:typea.S.tarray->aInput.t->aInput.t=letrecaux:typea.S.tarray->aInput.t'->int->aInput.t'*int=funawi->letopenInputinmatchwwith|U->(U,i)|S_->lets=a.(i)in(S(Xs),i+1)|B_->lets=a.(i)in(B(S.is_ones),i+1)|P(wl,wr)->letl,i=auxawliinletr,i=auxawriin(P(l,r),i)|Lws->letl,i=List.fold_left(fun(acc,i)w->letx,i=auxawiin(x::acc,i))([],i)wsin(L(List.revl),i)infuna(w,check)->(fst@@auxaw0,check)letconstant_scalars=let*&o=freshDummy.scalarinappend[|CS.new_constraint~a:0~b:0~c:o~qc:s~qo:mone"constant_scalar"|]>*ret(Scalaro)letscalar_of_bool(Boolb)=Scalarbletunsafe_bool_of_scalar(Scalarb)=Boolbletunit=UnitmoduleNum=structtypenonrecscalar=scalartypenonrec'arepr='areprtypenonrec'at='at(* l ≠ 0 <=> ∃ r ≠ 0 : l * r - 1 = 0 *)letassert_nonzero(Scalarl)=let*&r=freshDummy.scalarin(* 0*l + 0*r + 0*0 + 1*l*r -1 = 0 *)letgate=[|CS.new_constraint~a:l~b:r~c:0~qc:mone~qm:one"assert_nonzero"|]inletsolver=default_solvergate~to_solve:Binappendgate~solverletis_zero(Scalarl)=with_label~label:"Num.is_zero"@@let*(Boolbit)=freshDummy.boolinlet*(Scalarr)=freshDummy.scalarinletgate=[|CS.new_constraint~a:l~b:r~c:bit~qc:mone~qo:one~qm:one"is_zero";|]inletsolver=IsZero{a=l;b=r;c=bit}inappendgate~solver>*assert_nonzero(Scalarr)>*ret@@Boolbitletis_not_zero(Scalarl)=with_label~label:"Num.is_not_zero"@@let*(Boolbit)=freshDummy.boolinlet*(Scalarr)=freshDummy.scalarinletgate=[|CS.new_constraint~a:l~b:r~c:bit~qo:mone~qm:one"is_not_zero"|]inletsolver=IsNotZero{a=l;b=r;c=bit}inappendgate~solver>*assert_nonzero(Scalarr)>*ret@@Boolbitletcustom?(qc=S.zero)?(ql=S.zero)?(qr=S.zero)?(qo=S.mone)?(qm=S.zero)(Scalarl)(Scalarr)=let*&o=freshDummy.scalarinappend[|CS.new_constraint~a:l~b:r~c:o~qc~ql~qr~qo~qm"custom"|]>*ret@@Scalaroletassert_custom?(qc=S.zero)?(ql=S.zero)?(qr=S.zero)?(qo=S.zero)?(qm=S.zero)(Scalarl)(Scalarr)(Scalaro)=append[|CS.new_constraint~a:l~b:r~c:o~qc~ql~qr~qo~qm"assert_custom"|]~solver:Skipletadd?(qc=S.zero)?(ql=S.one)?(qr=S.one)(Scalarl)(Scalarr)=let*&o=freshDummy.scalarinappend[|CS.new_constraint~a:l~b:r~c:o~qc~ql~qr~qo:mone"add"|]>*ret@@Scalaroletadd_constant?(ql=S.one)(k:S.t)(Scalarl)=let*&o=freshDummy.scalarinappend[|CS.new_constraint~a:l~b:0~c:o~qc:k~ql~qo:mone"add_constant"|]>*ret@@Scalaroletsub(Scalarl)(Scalarr)=let*&o=freshDummy.scalarinappend[|CS.new_constraint~a:l~b:r~c:o~ql:one~qr:mone~qo:mone"sub"|]>*ret@@Scalaroletmul?(qm=one)(Scalarl)(Scalarr)=let*&o=freshDummy.scalarinappend[|CS.new_constraint~a:l~b:r~c:o~qm~qo:mone"mul"|]>*ret@@Scalaroletdiv?(qm=one)(Scalarl)(Scalarr)=with_label~label:"Num.div"@@assert_nonzero(Scalarr)>*let*&o=freshDummy.scalarinletgate=[|CS.new_constraint~a:r~b:o~c:l~qm~qo:mone"div"|]inletsolver=default_solvergate~to_solve:Bin(* r * o - l = 0 <=> o = l / r *)appendgate~solver>*ret@@Scalaroletpow5(Scalarl)=let*&o=freshDummy.scalarinletgate=[|CS.new_constraint~a:l~b:0~c:o~qx5a:one~qo:mone"pow5"|]inletsolver=Pow5{a=l;c=o}inappendgate~solver>*ret@@Scalaroletadd5?(k1=one)?(k2=one)?(k3=one)?(k4=one)?(k5=one)(Scalarx1)(Scalarx2)(Scalarx3)(Scalarx4)(Scalarx5)=with_label~label:"Num.add5"@@let*&o=freshDummy.scalarinletgate=[|CS.new_constraint~a:x1~b:x2~c:o~ql:k1~qr:k2~qo:mone~qlg:k3~qrg:k4~qog:k5"add5.1";CS.new_constraint~a:x3~b:x4~c:x5"add5.2";|]inletsolver=Add5{x1;x2;x3;x4;x5;o;k1;k2;k3;k4;k5}inappendgate~solver>*ret(Scalaro)endmoduleBool=structincludeNumletconstant_bool:bool->boolreprt=funb->lets=ifbthenS.oneelseS.zeroinlet*(Scalars)=constant_scalarsinret(Bools)letassert_true(Boolbit)=append[|CS.new_constraint~a:bit~b:0~c:0~qc:mone~ql:one"assert_true"|]~solver:Skipletassert_false(Boolbit)=append[|CS.new_constraint~a:bit~b:0~c:0~ql:one"assert_false"|]~solver:Skipletband:boolrepr->boolrepr->boolreprt=fun(Booll)(Boolr)->(* NB: Here [o] is declared as a fresh scalar to avoid adding the constraint
asserting it's a bool. It's safe to do so because:
- We can assume that [l] and [r] are booleans
- This operation is closed in {0, 1}
This has additionally been proven using Z3 (see z3 directory).
*)let*&o=freshDummy.scalarin(* o - l*r = 0 *)append[|CS.new_constraint~a:l~b:r~c:o~qm:mone~qo:one"band"|]>*ret@@Boololetbnot(Boolb)=(* NB: Here [o] is declared as a fresh scalar to avoid adding the constraint
asserting it's a bool. It's safe to do so because:
- We can assume that [b] is a boolen.
- This operation is closed in {0, 1}
This has additionally been proven using Z3 (see z3 directory).
*)let*&o=freshDummy.scalarin(* o - (1 - i) = 0 *)append[|CS.new_constraint~a:b~b:0~c:o~qc:mone~ql:one~qo:one"bnot"|]>*ret@@Boololetxor(Booll)(Boolr)=(* NB: Here [o] is declared as a fresh scalar to avoid adding the constraint
asserting it's a bool. It's safe to do so because:
- We can assume that [l] and [r] are booleans
- This operation is closed in {0, 1}
This has additionally been proven using Z3 (see z3 directory).
*)let*&o=freshDummy.scalarinletmtwo=S.of_string"-2"inappend[|CS.new_constraint~a:l~b:r~c:o~ql:one~qr:one~qo:mone~qm:mtwo"xor";|]>*ret@@Boololetbor(Booll)(Boolr)=(* NB: Here [o] is declared as a fresh scalar to avoid adding the constraint
asserting it's a bool. It's safe to do so because:
- We can assume that [l] and [r] are booleans
- This operation is closed in {0, 1}
This has additionally been proven using Z3 (see z3 directory).
*)let*&o=freshDummy.scalarinappend[|CS.new_constraint~a:l~b:r~c:o~ql:one~qr:one~qo:mone~qm:mone"nor";|]>*ret@@Boololetbor_lookup(Booll)(Boolr)=let*(Boolo)=freshDummy.boolinappend_lookup~a:(Inputl)~b:(Inputr)~c:(Outputo)~table:"or""bor lookup">*ret@@Boololetifthenelse:typea.boolrepr->arepr->arepr->areprt=letscalar_ifthenelseblr=let*lo=mul(scalar_of_boolb)linlet*bnot=bnotbinlet*ro=mul(scalar_of_boolbnot)rinaddloroinletbool_ifthenelseblr=let*(Scalarres)=scalar_ifthenelseb(scalar_of_booll)(scalar_of_boolr)inret@@Boolresinletrecaux:typea.boolrepr->arepr->arepr->areprt=funblr->match(l,r)with|Unit,Unit->retUnit|Scalar_,Scalar_->scalar_ifthenelseblr|Bool_,Bool_->bool_ifthenelseblr|Pair(l1,r1),Pair(l2,r2)->let*l3=auxbl1l2inlet*r3=auxbr1r2inret@@Pair(l3,r3)|Listls,Listrs->let*l=map2M(funlr->auxblr)lsrsinret@@Listlinfunblr->with_label~label:"Bool.ifthenelse"@@auxblrletis_eq_constls=with_label~label:"Bool.is_eq_const"@@let*diff=Num.add_constant~ql:S.moneslinis_zerodiffletband_listl=with_label~label:"Bool.band_list"@@matchlwith|[]->constant_booltrue|hd::tl->let*sum=foldMNum.add(scalar_of_boolhd)(List.mapscalar_of_booltl)inis_eq_constsum(S.of_int@@(List.lengthtl+1))endlethd(Listl)=matchlwith[]->assertfalse|x::_->retxletassert_equal:typea.arepr->arepr->unitreprt=letrecaux:typea.arepr->arepr->unitreprt=funab->match(a,b)with|Unit,Unit->retUnit|Boola,Boolb|Scalara,Scalarb->append[|CS.new_constraint~a~b~c:0~ql:mone~qr:one"assert_equal"|]~solver:Skip|Pair(la,ra),Pair(lb,rb)->auxlalb>*auxrarb|Listls,Listrs->iter2Mauxlsrsinfunab->with_label~label:"Core.assert_equal"@@auxabletequal:typea.arepr->arepr->boolreprt=letrecaux:typea.arepr->arepr->boolreprt=funab->letopenBoolinletopenNuminmatch(a,b)with|Unit,Unit->constant_booltrue|Boola,Boolb->let*s=sub(Scalara)(Scalarb)inis_zeros|Scalar_,Scalar_->let*s=subabinis_zeros|Pair(la,ra),Pair(lb,rb)->let*le=auxlalbinlet*re=auxrarbinbandlere|Listls,Listrs->letlrs=List.map2pairlsrsinlet*acc=constant_booltrueinfoldM(funacc(Pair(l,r))->let*e=auxlrinbandacce)acclrsinfunab->with_label~label:"Core.equal"@@auxab(* If [add_alpha], this function returns the binary decomposition of
[l + Utils.alpha], instead of the binary decompostion of [l], where
Utils.alpha is the difference between Scalar.order and its succeeding
power of 2 *)letbits_of_scalar?(shift=Z.zero)~nb_bits(Scalarl)=with_label~label:"Core.bits_of_scalar"@@let*bits=fresh@@Dummy.listnb_bitsDummy.boolinadd_solver~solver:(BitsOfS{nb_bits;shift;l;bits=List.map(fun(Boolx)->x)@@of_listbits;})>*let*sum=letpowers=List.initnb_bits(funi->S.of_zZ.(pow(of_int2)i))inletsbits=List.mapscalar_of_bool(of_listbits)infoldM(funacc(qr,w)->Num.add~qraccw)(List.hdsbits)List.(tl@@combinepowerssbits)inlet*l=ifZ.(not@@equalshiftzero)thenNum.add_constant(S.of_zshift)(Scalarl)elseret(Scalarl)inassert_equallsum>*retbitsmoduleEcc=structletweierstrass_add(Pair(Scalarx1,Scalary1))(Pair(Scalarx2,Scalary2))=with_label~label:"Ecc.weierstrass_add"@@let*&x3=freshDummy.scalarinlet*&y3=freshDummy.scalarinletgate=[|CS.new_constraint~a:x1~b:x2~c:x3~qecc_ws_add:one"weierstrass-add.1";CS.new_constraint~a:y1~b:y2~c:y3"weierstrass-add.2";|]inletsolver=Ecc_Ws{x1;x2;x3;y1;y2;y3}inappendgate~solver>*ret(Pair(Scalarx3,Scalary3))letedwards_add(Pair(Scalarx1,Scalary1))(Pair(Scalarx2,Scalary2))=(* Improve Me: Functorize to pass curve in parameter. *)with_label~label:"Ecc.edwards_add"@@letmoduleW=Mec.Curve.Jubjub.AffineEdwardsinlets_of_bases=S.of_z(W.Base.to_zs)inleta,d=(s_of_baseW.a,s_of_baseW.d)inlet*&x3=freshDummy.scalarinlet*&y3=freshDummy.scalarinletgate=[|CS.new_constraint~a:x1~b:x2~c:x3~qecc_ed_add:one"edwards-add.1";CS.new_constraint~a:y1~b:y2~c:y3"edwards-add.2";|]inletsolver=Ecc_Ed{x1;x2;x3;y1;y2;y3;a;d}inappendgate~solver>*ret(Pair(Scalarx3,Scalary3))endmodulePoseidon=structmoduleVS=Linear_algebra.Make_VectorSpace(S)modulePoly=Polynomial.MakeUnivariate(S)modulePoly_Module=Linear_algebra.Make_Module(structincludePolyleteq=Poly.equalletnegatep=Poly.(zero-p)letmul=Poly.(*)end)letposeidon128_full_round~matrix~k~variant(Scalarx0,Scalarx1,Scalarx2)=let*&y0=freshDummy.scalarinlet*&y1=freshDummy.scalarinlet*&y2=freshDummy.scalarinletsolver=Poseidon128Full{x0;y0;x1;y1;x2;y2;k;variant}inletminv=VS.inversematrixinletk_vec=VS.(mulminv(transpose[|k|]))in(* We enforce the following constraints:
[x0 y0] with selectors {qc, qx5, qo, qrg, qog}
[x1 y1 y2] with selectors {qc, qx5, qr, qo, qrg}
[x2 y0 y1] with selectors {qc, qx5, qr, qo, qrg}
[ y2 ] with no selectors
where the selector constants are given by the inverse of the MDS
matrix. In particular:
y = M * x^5 + k iff M^{-1} * y - x^5 - M^{-1} * k = 0
(This allows us to have 1 power of 5 (instead of all 3) per constraint,
since vector x^5 is not multiplied by M in the second representation.) *)append[|CS.new_constraint~a:x0~b:0~c:y0~qx5a:mone~qc:(S.negatek_vec.(0).(0))~qo:minv.(0).(0)~qrg:minv.(0).(1)~qog:minv.(0).(2)"pos128_full.1";CS.new_constraint~a:x1~b:y1~c:y2~qx5a:mone~qc:(S.negatek_vec.(1).(0))~qr:minv.(1).(1)~qo:minv.(1).(2)~qrg:minv.(1).(0)"pos128_full.2";CS.new_constraint~a:x2~b:y0~c:y1~qx5a:mone~qc:(S.negatek_vec.(2).(0))~qr:minv.(2).(0)~qo:minv.(2).(1)~qrg:minv.(2).(2)"pos128_full.3";CS.new_constraint~a:0~b:y2~c:0"pos128_full.4";|]~solver>*ret@@to_list[Scalary0;Scalary1;Scalary2]letposeidon128_four_partial_rounds~matrix~ks~variant(Scalarx0,Scalarx1,Scalarx2)=let*&a=freshDummy.scalarinlet*&a_5=freshDummy.scalarinlet*&b=freshDummy.scalarinlet*&b_5=freshDummy.scalarinlet*&c=freshDummy.scalarinlet*&c_5=freshDummy.scalarinlet*&y0=freshDummy.scalarinlet*&y1=freshDummy.scalarinlet*&y2=freshDummy.scalarinletk_cols=Array.init4(funi->VS.filter_cols(Int.equali)ks)inletsolver=Poseidon128Partial{a;b;c;a_5;b_5;c_5;x0;y0;x1;y1;x2;y2;k_cols;variant}in(* We represent variables x0, x1, x2_5, a, a_5, b, b_5, c, c_5, y0, y1, y2
with monomials x, x^2, x^3, ..., x^12 respectively. *)letmoduleSMap=Map.Make(String)inletvars=["x0";"x1";"x2_5";"a";"a_5";"b";"b_5";"c";"c_5";"y0";"y1";"y2";]inletvarsMap=SMap.of_seq@@List.(to_seq@@mapi(funis->(s,i+1))vars)inletvars=SMap.findsvarsMapinletpvars=Poly.of_coefficients[(S.one,vars)]inletstate=[|[|pvar"x0"|];[|pvar"x1"|];[|pvar"x2_5"|]|]inletto_poly=Array.(map(map(func->Poly.of_coefficients[(c,0)])))inletmatrix=to_polymatrixin(* Apply partial round 0 *)letstate=Poly_Module.(add(mulmatrixstate)@@to_polyk_cols.(0))inleteq1=Poly.(state.(2).(0)-pvar"a")instate.(2)<-[|pvar"a_5"|];(* Apply partial round 1 *)letstate=Poly_Module.(add(mulmatrixstate)@@to_polyk_cols.(1))inleteq2=Poly.(state.(2).(0)-pvar"b")instate.(2)<-[|pvar"b_5"|];(* Apply partial round 2 *)letstate=Poly_Module.(add(mulmatrixstate)@@to_polyk_cols.(2))inleteq3=Poly.(state.(2).(0)-pvar"c")instate.(2)<-[|pvar"c_5"|];(* Apply partial round 3 *)letstate=Poly_Module.(add(mulmatrixstate)@@to_polyk_cols.(3))inleteq4=Poly.(state.(0).(0)-pvar"y0")inleteq5=Poly.(state.(1).(0)-pvar"y1")inleteq6=Poly.(state.(2).(0)-pvar"y2")inleteqs=letrow_of_eqeq=(* This function gives coefficients in decending order of degree *)letcoeffs=Poly.get_dense_polynomial_coefficientseqinList.(revcoeffs@init(13-List.lengthcoeffs)(fun_->S.zero))|>Array.of_listinArray.maprow_of_eq[|eq1;eq2;eq3;eq4;eq5;eq6|]inletcancelijx=letx=varxinVS.row_add~coeff:S.(negate@@(eqs.(i).(x)/eqs.(j).(x)))ijeqsin(* Cancel x2_5 *)cancel10"x2_5";cancel20"x2_5";cancel30"x2_5";cancel40"x2_5";cancel50"x2_5";(* Cancel a_5 *)cancel21"a_5";cancel31"a_5";cancel41"a_5";cancel51"a_5";(* Cancel b_5 *)cancel32"b_5";cancel42"b_5";cancel52"b_5";(* Cancel c_5 *)cancel43"c_5";(* Cancel x0 in equation 5 (b_5 comes back) *)cancel42"x0";VS.row_swap24eqs;(* We enforce the following constraints:
[x2 ] with selectors {qc, qx5, qlg, qrg, qog}
[a x0 x1] with selectors {qc, qx5, ql, qr, qo, qlg}
[b y1 x1] with selectors {qc, qx5, ql, qr, qo, qlg, qrg, qog}
[c y0 a] with selectors {qc, qx5, ql, qr, qo, qlg, qrg, qog}
[b x0 x1] with selectors {qc, qx5, ql, qr, qo, qlg, qrg}
[c a b] with selectors {qc, qx5, ql, qr, qo, qlg, qrg, qog}
[y2 x0 x1] with no selectors. *)append[|CS.new_constraint~a:x2~b:0~c:0~qc:eqs.(0).(0)~qx5a:eqs.(0).(var"x2_5")~qlg:eqs.(0).(var"a")~qrg:eqs.(0).(var"x0")~qog:eqs.(0).(var"x1")"pos128_4partial.1";CS.new_constraint~a~b:x0~c:x1~qc:eqs.(1).(0)~qx5a:eqs.(1).(var"a_5")~ql:eqs.(1).(var"a")~qr:eqs.(1).(var"x0")~qo:eqs.(1).(var"x1")~qlg:eqs.(1).(var"b")"pos128_4partial.2";CS.new_constraint~a:b~b:y1~c:x1~qc:eqs.(2).(0)~qx5a:eqs.(2).(var"b_5")~ql:eqs.(2).(var"b")~qr:eqs.(2).(var"y1")~qo:eqs.(2).(var"x1")~qlg:eqs.(2).(var"c")~qrg:eqs.(2).(var"y0")~qog:eqs.(2).(var"a")"pos128_4partial.3";CS.new_constraint~a:c~b:y0~c:a~qc:eqs.(3).(0)~qx5a:eqs.(3).(var"c_5")~ql:eqs.(3).(var"c")~qr:eqs.(3).(var"y0")~qo:eqs.(3).(var"a")~qlg:eqs.(3).(var"b")~qrg:eqs.(3).(var"x0")~qog:eqs.(3).(var"x1")"pos128_4partial.4";CS.new_constraint~a:b~b:x0~c:x1~qc:eqs.(4).(0)~qx5a:eqs.(4).(var"b_5")~ql:eqs.(4).(var"b")~qr:eqs.(4).(var"x0")~qo:eqs.(4).(var"x1")~qlg:eqs.(4).(var"c")~qrg:eqs.(4).(var"a")"pos128_4partial.5";CS.new_constraint~a:c~b:a~c:b~qc:eqs.(5).(0)~qx5a:eqs.(5).(var"c_5")~ql:eqs.(5).(var"c")~qr:eqs.(5).(var"a")~qo:eqs.(5).(var"b")~qlg:eqs.(5).(var"y2")~qrg:eqs.(5).(var"x0")~qog:eqs.(5).(var"x1")"pos128_4partial.6";CS.new_constraint~a:y2~b:x0~c:x1"pos128_4partial.7";|]~solver>*ret@@to_list[Scalary0;Scalary1;Scalary2]endmoduleAnemoi=structletbeta=Bls12_381_hash.Anemoi.Parameters.betaletgamma=Bls12_381_hash.Anemoi.Parameters.gammaletg=Bls12_381_hash.Anemoi.Parameters.gletdelta=Bls12_381_hash.Anemoi.Parameters.delta(* Hash function described in https://eprint.iacr.org/2022/840.pdf *)letanemoi_round~kx~ky(Scalarx0,Scalary0)=let*&w=freshDummy.scalarinlet*&v=freshDummy.scalarinlet*&x1=freshDummy.scalarinlet*&y1=freshDummy.scalarinletsolver=AnemoiRound{x0;y0;w;v;x1;y1;kx;ky}in(*
The equations of a Anemoi round are as follows,
a. x1 - u - g*v - (kx + g*ky) = 0
Corresponds to Linear layer equation (after adding the round constant to x_i ), eq.4 page 24
b. y1 - g u - (g^2+1)*v - (g*kx + (g^2+1)*ky) = 0
Corresponds to Linear layer equation (after adding the round constant to y_i ), eq.5 page 24
c. w^5 + beta y0^2 + gamma - x0 = 0
Corresponds to the first equation of S-box, eq.2 page 24
d. y0 - v - w = 0
Corresponds to the second equation of S-box layer, eq.1 page 24
e. w^5 + beta v^2 + delta - u = 0
Corresponds to the third equation of S-box, eq.3 page 24
We inlined $u$ from a. in e. and re-ordered the equations so that the variables fit in the wires.
The result is as follows,
1. w^5 + beta y0^2 + gamma - x0 = 0 <- c
2. y0 - v - w = 0 <- d
3. w^5 + beta v^2 + g*v - x1 + (delta + kx + g*ky) = 0 <- e - a
4. y1 - g x1 - v - ky = 0 <- b - g * a
*)append[|CS.new_constraint~a:y0~b:y0~c:w~qc:gamma~qm:beta~qx5c:one~qlg:mone"anemoi.1";CS.new_constraint~a:x0~b:y0~c:w~qr:one~qlg:mone~qo:mone"anemoi.2";CS.new_constraint~a:v~b:v~c:w~qc:S.(kx+delta+(g*ky))~qm:beta~qx5c:one~ql:g~qlg:mone"anemoi.3";CS.new_constraint~a:x1~b:y1~c:v~qc:S.(negateky)~ql:S.(negateg)~qr:one~qo:mone"anemoi.4";|]~solver>*ret@@pair(Scalarx1)(Scalary1)letanemoi_double_round~kx1~ky1~kx2~ky2(Scalarx0,Scalary0)=let*&w0=freshDummy.scalarinlet*&w1=freshDummy.scalarinlet*&y1=freshDummy.scalarinlet*&x2=freshDummy.scalarinlet*&y2=freshDummy.scalarinletsolver=AnemoiDoubleRound{x0;y0;w0;w1;y1;x2;y2;kx1;kx2;ky1;ky2}inlettwo=S.(addoneone)inletg2=S.(g*g)inletg2_p_1=S.(g2+one)inletg_beta=S.(g*beta)in(*
Equations | Wires | Selectors
-------------------------------------------------------------------------------------------------------------
a <- 2. -(beta*g)*w0^2 + (2*beta*g)*w0*y0 + (g^2+1)*w0 - g*x0 - (g^2+1)*y0 + y1 + (g*gamma - delta*g - g*kx1 - (g^2+1)*ky1)
| a: y0, b: w0, c: x0
| qr2=-(beta*g) qm:(2*beta*g) qr:(g^2+1) qo:-g ql:-(g^2+1) qlg:1 qc =(g*gamma - delta*g - g*kx1 - (g^2+1)*ky1)
b <- 4. -(g * beta)*w1^2 + (2 * g * beta)*w1*y1 - w0 + g^2*w1 + g*x2 + y0 - (g^2+1)*y1 + (g*gamma + ky1 - delta*g - g*kx2 - g^2*ky2)
| a: y1, b: w1, c: w0
| qr2=-(g*beta) qm:(2*g*beta) qo:-1 qr:g^2 qrg:g qlg:1 ql:-(g^2+1) qc:(g*gamma + ky1 - delta*g -g*kx2 - g^2*ky2)
c <- 5. w1 - g*x2 - y1 + y2 - ky2
| a: y0, b: x2, c: y2
| qlg:1 qr:-g qrg:-1 qo:1 qc:-ky2
d <- 3. g*w1^5 + (g * beta)*y1^2 - w0 + y0 - y1 + (ky1 + g*gamma)
| a: w1, b: y1, c: __
| ql5=g qr2=(g*beta) qlg:-1 qrg:1 qr:-1 qc:(ky1 + g*gamma)
e <- 1. w0^5 + beta*y0^2 - x0 + gamma
| a: w0, b: y0, c: x0
| ql5=1 qr2=beta qo:-1 qc:gamma
*)letqca=S.(sub(gamma*g)((g*(kx1+delta))+(g2_p_1*ky1)))inletqcb=S.(sub((gamma*g)+ky1)((g*(kx2+delta))+(g2*ky2)))inletqcd=S.(ky1+(g*gamma))inappend[|CS.new_constraint~a:y0~b:w0~c:x0~qx2b:S.(negateg_beta)~qm:S.(two*g_beta)~qr:g2_p_1~qo:S.(negateg)~ql:S.(negateg2_p_1)~qlg:S.one~qc:qca"anemoi_double.a";CS.new_constraint~a:y1~b:w1~c:w0~qx2b:S.(negateg_beta)~qm:S.(two*g_beta)~qo:mone~qr:g2~qrg:g~qlg:one~ql:S.(negateg2_p_1)~qc:qcb"anemoi_double.b";CS.new_constraint~a:y0~b:x2~c:y2~qlg:one~qr:S.(negateg)~qrg:mone~qo:one~qc:S.(negateky2)"anemoi_double.c";CS.new_constraint~a:w1~b:y1~c:y1~qx5a:g~qx2b:g_beta~qlg:mone~qrg:one~qr:mone~qc:qcd"anemoi_double.d";CS.new_constraint~a:w0~b:y0~c:x0~qx5a:one~qx2b:beta~qo:mone~qc:gamma"anemoi_double.e";|]~solver>*ret@@pair(Scalarx2)(Scalary2)endletget_checks_wires=lets,Unit=s.delayedsinlets,w=Bool.band_lists.check_wiressin({swithcheck_wires=[];delayed=retUnit},w)letgetf=lets,res=f{nvars=0;cs=[];inputs=Array.init0(fun_->S.zero);pi_size=0;public=true;input_flag=true;tables=[];solver=Solver.empty_solver;delayed=retUnit;check_wires=[];labels=[];}inlets,Unit=s.delayedsinlets,res=matchs.check_wireswith|[]->(s,res)|ws->lets,w=Bool.band_listwssinlets,Unit=Bool.assert_truewsin(s,res)inletsolver={s.solverwithfinal_size=s.nvars;initial_size=Array.lengths.inputs}inlets={swithsolver}in(s,res)letget_inputsf=lets,_=getfin(s.inputs,s.pi_size)typecs_result={nvars:int;free_wires:intlist;cs:Csir.CS.t;tables:Csir.Table.tlist;solver:Solver.t;}[@@derivingrepr]letcs_ti_t=Repr.pairCsir.CS.tOptimizer.trace_info_tletget_cs?(optimize=false)f:cs_result=lets,_=getfinletts=List.map(funt_id->Tables.findt_idtables)s.tablesinletcs,solver,free_wires,nvars=ifoptimizethenletcircuit_id=Utils.get_circuit_ids.csinletpath=Utils.circuit_pathcircuit_idinletcs,ti=ifSys.file_existspaththen((* If defined, load it up *)letinc=open_inpathinletsize=in_channel_lengthincinletbuffer=Bytes.createsizeinreally_inputincbuffer0(in_channel_lengthinc);close_ininc;Utils.of_bytescs_ti_tbuffer)elseletnb_inputs=Array.lengths.inputsinleto=Optimizer.optimize~nb_inputss.csinletserialized=Utils.to_bytescs_ti_toinletoutc=open_out_binpathinoutput_bytesoutcserialized;close_outoutc;oin(cs,Solver.append_solver(Updaterti)s.solver,ti.free_wires,s.nvars)else(s.cs,s.solver,[],s.nvars)in{nvars;free_wires;cs;tables=ts;solver}