123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.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. *)(* *)(*****************************************************************************)(* We reshadow the List module with Stdlib's because there are many safe uses of
double-list traversors *)moduleList=Stdlib.ListmoduleH=Blake2B(** Polynomial ring (ℤ/qℤ)[X] *)modulePZ_q(Z_q:Znz.ZN):sigtypetmoduleZ_q:Znz.ZN(** Evaluates the polynomial p at point x *)valeval:p:t->x:Z_q.t->Z_q.t(** Builds the polynomial from a list of coefficient, ordered by power.
That is, of_list [a₀; a₁; a₂; …] = a₀ + a₁ x + a₂ x² + … *)valof_list:Z_q.tlist->tendwithtypeZ_q.t=Z_q.t=structmoduleZ_q=Z_qtypet=Z_q.tlistleteval~p~x=List.fold_right(funcy->Z_q.((y*x)+c))pZ_q.zeroletof_listl=lend(** Functor type for an Cyclic group *)moduletypeCYCLIC_GROUP=sigtypetvalpp:Format.formatter->t->unitincludeCompare.Swithtypet:=tincludeS.RAW_DATAwithtypet:=tincludeS.B58_DATAwithtypet:=tincludeS.ENCODERwithtypet:=tvalname:stringmoduleZ_m:Znz.ZNvale:tvalg1:tvalg2:tval(*):t->t->tvalpow:t->Z_m.t->tvalto_bits:t->String.tvalof_bits:String.t->toptionend(** Type of a module that handles proofs for the discrete logarithm
equality equation. *)moduletypeDLEQ=sig(** A DLEQ equation. *)typeequation(** A non-interactive zero-knowledge proof-of-knowledge of an
exponent solving the equation. *)typeproofvalproof_encoding:proofData_encoding.t(** Group element. *)typeelement(** Exponent, i.e. an integer modulo the group's order. *)typeexponent(** Sets up a equation of the form
∀ i, ∃ x(i), b₁ˣ⁽ⁱ⁾ = h₁ᵢ and b₂ᵢˣ⁽ⁱ⁾ = h₂ᵢ. The arguments
are given as b₁, h₁ᵢ, b₂ᵢ, h₂ᵢ *)valsetup_equation:element->elementlist->elementlist->elementlist->equation(** Creates a zero-knowledge proof of knowledge of the exponent list *)valmake_proof:equation->exponentlist->proof(** Checks the proof created by make_proof for a given equation *)valcheck_proof:equation->proof->boolend(** Functor for creating a module handling proofs for the discrete logarithm
equality in cyclic group G *)moduleMakeDleq(G:CYCLIC_GROUP):DLEQwithtypeelement=G.tandtypeexponent=G.Z_m.t=structtypeelement=G.ttypeexponent=G.Z_m.ttypeequation=element*elementlist*elementlist*elementlisttypeproof=exponent*exponentlistletproof_encoding=Data_encoding.(tup2G.Z_m.encoding(listG.Z_m.encoding))(* Fiat-Shamir heuristic to derive a random element of ℤ/mℤ from the
hash of a list of group elements *)letfiat_shamir?(exponents=[])elements=String.concat"||"("tezosftw"::List.mapG.to_bitselements@List.mapG.Z_m.to_bitsexponents)|>(funx->H.hash_string[x])|>H.to_string|>G.Z_m.of_bits_exnletsetup_equationb1h1_nb2_nh2_n=(b1,h1_n,b2_n,h2_n)letmake_proof(b1,h1_n,b2_n,h2_n)x_n=(* First, draw blinding factors. Normally these should be picked randomly. To maximize
reproducibility and avoid weak random number generation, we generate the blinding
factor deterministically from the problem parameters and the secret x_n.
TODO: review with cryptographer
*)letpseudo_seed=fiat_shamir(b1::List.concat[h1_n;b2_n;h2_n])~exponents:x_ninletw_n=List.mapi(funi__->fiat_shamir[]~exponents:[pseudo_seed;G.Z_m.of_inti])h1_ninleta1_n=List.map(G.powb1)w_nanda2_n=List.map2G.powb2_nw_ninlet(* Pick the challenge, c, following the Fiat-Shamir heuristic. *)c=fiat_shamir(List.concat[h1_n;h2_n;a1_n;a2_n])inlet(* rᵢ = wᵢ - c * xᵢ *)r_n=List.map2(funwx->G.Z_m.(w-(c*x)))w_nx_nin(c,r_n)letcheck_proof(b1,h1_n,b2_n,h2_n)(c,r_n)=(* First check that the lists have the same sizes. *)letsame_sizes=(Compare.Int.equal0@@List.compare_lengthsh1_nb2_n)&&(Compare.Int.equal0@@List.compare_lengthsb2_nh2_n)&&(Compare.Int.equal0@@List.compare_lengthsh2_nr_n)inifnotsame_sizesthenfalseelseleta1_n=(* Original, non-optimized form
List.map2
G.( * )
(List.map (G.pow b1) r_n)
(List.map (fun h1 -> G.pow h1 c) h1_n)
*)List.map2(funrh1->letopenGinpowb1r*powh1c)r_nh1_nanda2_n=(* Original, non-optimized form
List.map2
G.( * )
(List.map2 G.pow b2_n r_n)
(List.map (fun h2 -> G.pow h2 c) h2_n)
*)letrecmap3fxsyszs=match(xs,ys,zs)with|([],[],[])->[]|(x::xs,y::ys,z::zs)->letr=fxyzinr::map3fxsyszs|_->invalid_arg"Pvss: List.map3"inmap3(funb2rh2->letopenGinpowb2r*powh2c)b2_nr_nh2_ninG.Z_m.(c=fiat_shamir(List.concat[h1_n;h2_n;a1_n;a2_n]))endmoduletypePVSS=sigmoduletypeENCODED=sigtypetincludeS.B58_DATAwithtypet:=tincludeS.ENCODERwithtypet:=tendmoduleCommitment:ENCODEDmoduleEncrypted_share:ENCODEDmoduleClear_share:ENCODEDmodulePublic_key:sigtypetvalpp:Format.formatter->t->unitincludeCompare.Swithtypet:=tincludeS.RAW_DATAwithtypet:=tincludeS.B58_DATAwithtypet:=tincludeS.ENCODERwithtypet:=tendmoduleSecret_key:sigincludeENCODEDvalto_public_key:t->Public_key.tendtypeproofvalproof_encoding:proofData_encoding.tvaldealer_shares_and_proof:secret:Secret_key.t->threshold:int->public_keys:Public_key.tlist->Encrypted_share.tlist*Commitment.tlist*proofvalcheck_dealer_proof:Encrypted_share.tlist->Commitment.tlist->proof:proof->public_keys:Public_key.tlist->boolvalreveal_share:Encrypted_share.t->secret_key:Secret_key.t->public_key:Public_key.t->Clear_share.t*proofvalcheck_revealed_share:Encrypted_share.t->Clear_share.t->public_key:Public_key.t->proof->boolvalreconstruct:Clear_share.tlist->intlist->Public_key.tendmoduleMakePvss(G:CYCLIC_GROUP):PVSS=structmoduletypeENCODED=sigtypetincludeS.B58_DATAwithtypet:=tincludeS.ENCODERwithtypet:=tend(* Module to make discrete logarithm equality proofs *)moduleDleq=MakeDleq(G)typeproof=Dleq.proof(* Polynomials over ℤ/mℤ *)modulePZ_m=PZ_q(G.Z_m)(* A public key is a group element *)modulePublic_key=GmoduleSecret_key=structincludeG.Z_mletto_public_keyx=G.(powg2x)endmoduleEncrypted_share=GmoduleClear_share=GmoduleCommitment=Gletproof_encoding=Dleq.proof_encoding(* generate a "random": polynomial of degree t to hide secret `secret` *)letrandom_polynomialsecrett=(* the t-1 coefficients are computed deterministically from
the secret and mapped to G.Z_m *)letnonce=[String.concat"||"[G.Z_m.to_bitssecret]]|>H.hash_string|>H.to_stringin(* TODO: guard against buffer overflow *)letrecmake_coefs=function|0->[]|k->leth=H.hash_string[string_of_intk;"||";nonce]|>H.to_string|>G.Z_m.of_bits_exninh::make_coefs(k-1)inletcoefs=secret::make_coefs(t-1)in(* let coefs = secret :: List_Utils.list_init ~f:G.Z_m.random ~n:(t-1) in *)letpoly=PZ_m.of_listcoefsin(coefs,poly)(* Hides secret s in a random polynomial of degree t = threshold, publishes t
commitments to the polynomial coefficients and n encrypted shares for the
holders of the public keys *)letdealer_shares_and_proof~secret~threshold~public_keys=let(coefs,poly)=random_polynomialsecretthresholdinlet(* Cⱼ represents the commitment to the coefficients of the polynomial
Cⱼ = g₁^(aⱼ) for j in 0 to t-1 *)cC_j=List.mapG.(powg1)coefsand(* pᵢ = p(i) for i in 1…n, with i ∈ ℤ/mℤ: points of the polynomial. *)p_i=List.mapi(funi_->PZ_m.eval~p:poly~x:(i+1|>G.Z_m.of_int))public_keysinlet(* yᵢ = pkᵢᵖ⁽ⁱ⁾ for i ∈ 1…n: the value of p(i) encrypted with pkᵢ,
the public key of the party receiving the iᵗʰ party. The public
keys use the g₂ generator of G. Thus pkᵢ = g₂ˢᵏⁱ *)y_i=List.map2G.powpublic_keysp_iand(* xᵢ = g₁ᵖ⁽ⁱ⁾ for in in 1…n: commitment to polynomial points *)x_i=List.mapG.(powg1)p_iinletequation=Dleq.setup_equationG.g1x_ipublic_keysy_iinletproof=Dleq.make_proofequationp_iin(y_i,cC_j,proof)letcheck_dealer_proofy_icC_j~proof~public_keys=(* Reconstruct Xᵢ from Cⱼ *)letx_i=(* prod_C_j_to_the__i_to_the_j = i ↦ Πⱼ₌₀ᵗ⁻¹ Cⱼ^(iʲ) *)letprod_C_j_to_the__i_to_the_ji=(* Original, non-optimized form
List.mapi (fun j cC -> G.pow cC (G.Z_m.pow i (Z.of_int j))) cC_j
|> List.fold_left G.( * ) G.e
*)List.fold_left(fun(power,acc)cC->letopenGin(Z_m.(*)poweri,acc*powcCpower))(G.Z_m.one,G.e)cC_j|>sndinList.mapi(funi_->prod_C_j_to_the__i_to_the_j(i+1|>G.Z_m.of_int))y_iinletequation=Dleq.setup_equationG.g1x_ipublic_keysy_iinDleq.check_proofequationproof(* reveal a share *)letreveal_sharey~secret_key~public_key=matchG.Z_m.invsecret_keywith|None->failwith"Invalid secret key"|Someinverse_key->letreveal=G.(powyinverse_key)in(* y = g₂^(private_key) and public_key = reveal^(private_key) *)letequation=Dleq.setup_equationG.g2[public_key][reveal][y]inletproof=Dleq.make_proofequation[secret_key]in(reveal,proof)(* check the validity of a revealed share *)letcheck_revealed_sharesharereveal~public_keyproof=letequation=Dleq.setup_equationG.g2[public_key][reveal][share]inDleq.check_proofequationproof(* reconstruct the secret *)letreconstructrevealsint_indices=(* check that there enough reveals *)letindices=List.map(funx->G.Z_m.of_int(1+x))int_indicesinletlagrangei=(* Original, non-optimized form
List.fold_left
G.Z_m.( * )
G.Z_m.one
(List.map
(fun j ->
if G.Z_m.(j = i) then G.Z_m.one
else
match G.Z_m.(inv (j - i)) with
| None ->
failwith "Unexpected error inverting scalar."
| Some inverse ->
G.Z_m.(j * inverse))
indices)
*)List.fold_left(funaccindice->ifG.Z_m.(=)indiceithenaccelsematchG.Z_m.(inv(indice-i))with|None->failwith"Unexpected error inverting scalar."|Someinverse->letopenG.Z_minacc*indice*inverse)G.Z_m.oneindicesin(* Original, non-optimized form
let lagrange = List.map lagrange indices in
List.fold_left G.( * ) G.e (List.map2 G.pow reveals lagrange)
*)List.fold_left2(funaccrevealindice->letopenGinacc*powreveal(lagrangeindice))G.erevealsindicesend