diff --git a/pkg/party/phases.go b/pkg/party/phases.go index 26f5632..7663463 100644 --- a/pkg/party/phases.go +++ b/pkg/party/phases.go @@ -16,11 +16,21 @@ func (p *SetupComponent) handleSetupMsg(env *transport.Envelope) (*transport.Env } func (p *ControlComponent) handleCCMsg(env *transport.Envelope) (*transport.Envelope, error) { - return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type) + switch env.Type { + case MsgGenCCKeys: + return p.handleGenCCKeys(env) + default: + return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type) + } } func (p *ElectoralBoard) handleEBMsg(env *transport.Envelope) (*transport.Envelope, error) { - return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type) + switch env.Type { + case MsgGenEBKey: + return p.handleGenEBKey(env) + default: + return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type) + } } func (p *VotingServer) handleServerMsg(env *transport.Envelope) (*transport.Envelope, error) { diff --git a/pkg/party/setup.go b/pkg/party/setup.go new file mode 100644 index 0000000..dfe2d13 --- /dev/null +++ b/pkg/party/setup.go @@ -0,0 +1,230 @@ +package party + +import ( + "fmt" + "math/big" + + "github.com/user/evote/pkg/elgamal" + "github.com/user/evote/pkg/hash" + emath "github.com/user/evote/pkg/math" + "github.com/user/evote/pkg/transport" + "github.com/user/evote/pkg/zkp" +) + +// Setup-phase message types. +const ( + MsgGenCCKeys = "gen-cc-keys" // setup -> CCj: generate election keys + MsgCCKeys = "cc-keys" // CCj -> setup: PK + Schnorr proofs + MsgGenEBKey = "gen-eb-key" // setup -> EB: generate board key + MsgEBKey = "eb-key" // EB -> setup: PK +) + +// --- payloads --- + +type genCCKeysReq struct { + ElectionID string `json:"election_id"` + NumOptions int `json:"num_options"` + CCIndex int `json:"cc_index"` +} + +type ccKeysResp struct { + PK wirePublicKey `json:"pk"` + Schnorr []wireSchnorr `json:"schnorr"` +} + +type genEBKeyReq struct { + ElectionID string `json:"election_id"` + NumOptions int `json:"num_options"` +} + +type ebKeyResp struct { + PK wirePublicKey `json:"pk"` +} + +// RunSetup executes the distributed key-generation part of the setup phase over +// the transport. Each CC and the EB generate their own key material privately; +// only public keys and proofs cross the bus. The setup component verifies every +// CC's Schnorr proof on receipt, combines the keys, and publishes the setup +// artifacts to the public transcript. +func (c *Ceremony) RunSetup() error { + cfg := c.Config + group := cfg.Group + zq := emath.ZqGroupFromGqGroup(group) + + c.logf("\n--- SETUP PHASE (multi-party) ---") + + // 1. Encoding primes (public, computed by the setup component). + raw := emath.SmallPrimes(cfg.NumOptions) + c.Setup.st.primes = make([]*big.Int, cfg.NumOptions) + for i, rp := range raw { + sq := new(big.Int).Exp(rp, big.NewInt(2), group.P()) + if !group.IsGroupMember(sq) { + return fmt.Errorf("encoding prime %d not a group member", i) + } + c.Setup.st.primes[i] = sq + } + + // 2. Ask each CC to generate its election keys; verify the returned proofs. + ccPKs := make([]elgamal.PublicKey, cfg.NumCCs) + c.Transcript.CCElectionPKs = make([]elgamal.PublicKey, cfg.NumCCs) + c.Transcript.CCSchnorr = make([][]zkp.SchnorrProof, cfg.NumCCs) + + for j := 0; j < cfg.NumCCs; j++ { + env, err := c.send(c.Setup.id, CCName(j), MsgGenCCKeys, genCCKeysReq{ + ElectionID: cfg.ElectionID, NumOptions: cfg.NumOptions, CCIndex: j, + }) + if err != nil { + return fmt.Errorf("setup->cc%d keygen: %w", j, err) + } + var resp ccKeysResp + if err := transport.UnmarshalPayload(env.Payload, &resp); err != nil { + return err + } + pk, err := resp.PK.decode(group) + if err != nil { + return fmt.Errorf("cc%d pk: %w", j, err) + } + proofs := make([]zkp.SchnorrProof, len(resp.Schnorr)) + for i, ws := range resp.Schnorr { + p, err := ws.decode(zq) + if err != nil { + return fmt.Errorf("cc%d schnorr %d: %w", j, i, err) + } + proofs[i] = p + } + // Verify each CC's proof of knowledge of its secret key (the setup + // component does not trust the CC's word). + if err := verifyCCSchnorr(cfg.ElectionID, group, j, pk, proofs); err != nil { + return err + } + c.logf(" setup: cc%d keys received, %d Schnorr proofs VALID", j, len(proofs)) + + ccPKs[j] = pk + c.Transcript.CCElectionPKs[j] = pk + c.Transcript.CCSchnorr[j] = proofs + } + + // 3. Ask the electoral board to generate its key. + env, err := c.send(c.Setup.id, NameEB, MsgGenEBKey, genEBKeyReq{ + ElectionID: cfg.ElectionID, NumOptions: cfg.NumOptions, + }) + if err != nil { + return fmt.Errorf("setup->eb keygen: %w", err) + } + var ebResp ebKeyResp + if err := transport.UnmarshalPayload(env.Payload, &ebResp); err != nil { + return err + } + ebPK, err := ebResp.PK.decode(group) + if err != nil { + return fmt.Errorf("eb pk: %w", err) + } + c.logf(" setup: electoral board key received") + + // 4. Combine keys. + c.Setup.st.returnCodePK = elgamal.CombinePublicKeys(ccPKs...) + c.Setup.st.electionPK = elgamal.CombinePublicKeys(append(append([]elgamal.PublicKey{}, ccPKs...), ebPK)...) + + // 5. Publish setup artifacts to the transcript. + c.Transcript.ElectionID = cfg.ElectionID + c.Transcript.EBPublicKey = ebPK + c.Transcript.ElectionPK = c.Setup.st.electionPK + c.Transcript.Primes = make([]string, len(c.Setup.st.primes)) + for i, p := range c.Setup.st.primes { + c.Transcript.Primes[i] = p.String() + } + c.logf(" setup: election public key assembled and published to transcript") + return nil +} + +// verifyCCSchnorr checks that every key element's Schnorr proof is valid for the +// stated CC index (using the same aux binding as generation). +func verifyCCSchnorr(electionID string, group *emath.GqGroup, j int, pk elgamal.PublicKey, proofs []zkp.SchnorrProof) error { + if len(proofs) != pk.Elements.Size() { + return fmt.Errorf("cc%d: %d proofs for %d keys", j, len(proofs), pk.Elements.Size()) + } + for i := 0; i < pk.Elements.Size(); i++ { + aux := []hash.Hashable{ + hash.HashableBigInt{Value: big.NewInt(int64(i))}, + hash.HashableString{Value: electionID}, + hash.HashableBigInt{Value: big.NewInt(int64(j))}, + } + if !zkp.VerifySchnorrProof(proofs[i], pk.Elements.Get(i), group, aux...) { + return fmt.Errorf("cc%d key %d: Schnorr proof INVALID", j, i) + } + } + return nil +} + +// --- CC handler: generate election keys --- + +func (p *ControlComponent) handleGenCCKeys(env *transport.Envelope) (*transport.Envelope, error) { + var req genCCKeysReq + if err := transport.UnmarshalPayload(env.Payload, &req); err != nil { + return nil, err + } + cfg := p.cer.Config + group := cfg.Group + zq := emath.ZqGroupFromGqGroup(group) + + kp := elgamal.GenKeyPair(group, req.NumOptions) + proofs := make([]zkp.SchnorrProof, req.NumOptions) + wireProofs := make([]wireSchnorr, req.NumOptions) + for i := 0; i < req.NumOptions; i++ { + aux := []hash.Hashable{ + hash.HashableBigInt{Value: big.NewInt(int64(i))}, + hash.HashableString{Value: req.ElectionID}, + hash.HashableBigInt{Value: big.NewInt(int64(req.CCIndex))}, + } + proofs[i] = zkp.GenSchnorrProof(kp.SK.Get(i), kp.PK.Get(i), group, aux...) + wireProofs[i] = encodeSchnorr(proofs[i]) + } + + // Store private key material; only the PK and proofs leave the CC. + p.st.keyPair = kp + p.st.returnCodeSecret = emath.RandomZqElement(zq) + p.st.schnorrProofs = proofs + + return reply(p.id, env.From, MsgCCKeys, env.Nonce, ccKeysResp{ + PK: encodePK(kp.PK), + Schnorr: wireProofs, + }) +} + +// --- EB handler: generate board key --- + +func (p *ElectoralBoard) handleGenEBKey(env *transport.Envelope) (*transport.Envelope, error) { + var req genEBKeyReq + if err := transport.UnmarshalPayload(env.Payload, &req); err != nil { + return nil, err + } + cfg := p.cer.Config + group := cfg.Group + zq := emath.ZqGroupFromGqGroup(group) + + // EB key is derived from board passwords (as in the single-process version), + // but the secret never leaves the EB. + p.st.passwords = []string{"password1", "password2"} + g := group.Generator() + skElems := make([]emath.ZqElement, req.NumOptions) + pkElems := make([]emath.GqElement, req.NumOptions) + for i := 0; i < req.NumOptions; i++ { + args := []hash.Hashable{ + hash.HashableString{Value: "ElectoralBoardSecretKey"}, + hash.HashableString{Value: req.ElectionID}, + hash.HashableBigInt{Value: big.NewInt(int64(i))}, + } + for _, pw := range p.st.passwords { + args = append(args, hash.HashableString{Value: pw}) + } + skVal := hash.RecursiveHashToZq(group.Q(), args...) + skElems[i], _ = emath.NewZqElement(skVal, zq) + pkElems[i] = g.Exponentiate(skElems[i]) + } + p.st.keyPair = elgamal.KeyPair{ + SK: elgamal.PrivateKey{Elements: emath.ZqVectorOf(skElems...)}, + PK: elgamal.PublicKey{Elements: emath.GqVectorOf(pkElems...)}, + } + + return reply(p.id, env.From, MsgEBKey, env.Nonce, ebKeyResp{PK: encodePK(p.st.keyPair.PK)}) +} diff --git a/pkg/party/setup_test.go b/pkg/party/setup_test.go new file mode 100644 index 0000000..343ab7f --- /dev/null +++ b/pkg/party/setup_test.go @@ -0,0 +1,50 @@ +package party + +import ( + "testing" +) + +// TestRunSetupDistributedKeygen runs the distributed key generation over the +// transport and checks that: every CC's Schnorr proof verified (RunSetup would +// have errored otherwise), the combined election public key equals the product +// of the individual CC and EB keys, and the transcript captured the artifacts. +func TestRunSetupDistributedKeygen(t *testing.T) { + cfg := testConfig(t, 5, 3) + c, err := NewCeremony(cfg, nil) + if err != nil { + t.Fatalf("NewCeremony: %v", err) + } + if err := c.RunSetup(); err != nil { + t.Fatalf("RunSetup: %v", err) + } + + tr := c.Transcript + if len(tr.CCElectionPKs) != cfg.NumCCs { + t.Fatalf("transcript has %d CC keys, want %d", len(tr.CCElectionPKs), cfg.NumCCs) + } + if len(tr.Primes) != cfg.NumOptions { + t.Fatalf("transcript has %d primes, want %d", len(tr.Primes), cfg.NumOptions) + } + + // Recompute election PK = Π CC_j.PK * EB.PK per component and compare. + for i := 0; i < cfg.NumOptions; i++ { + want := cfg.Group.Identity() + for j := 0; j < cfg.NumCCs; j++ { + want = want.Multiply(tr.CCElectionPKs[j].Elements.Get(i)) + } + want = want.Multiply(tr.EBPublicKey.Elements.Get(i)) + got := tr.ElectionPK.Elements.Get(i) + if !got.Equals(want) { + t.Fatalf("election PK component %d mismatch", i) + } + } + + // The setup component must actually hold private primes; a CC must hold a + // secret key that never appeared in the transcript. + if c.Setup.st.primes == nil { + t.Fatal("setup component did not retain encoding primes") + } + if c.CCs[0].st.keyPair.SK.Elements == nil { + t.Fatal("cc0 did not retain its private key") + } +} diff --git a/pkg/party/wire.go b/pkg/party/wire.go new file mode 100644 index 0000000..77b4486 --- /dev/null +++ b/pkg/party/wire.go @@ -0,0 +1,170 @@ +package party + +import ( + "fmt" + "math/big" + + "github.com/user/evote/pkg/elgamal" + emath "github.com/user/evote/pkg/math" + "github.com/user/evote/pkg/zkp" +) + +// This file is the validated serialization boundary between parties. Crypto +// objects have unexported fields and cannot be JSON-marshaled directly, so they +// travel as decimal-string DTOs. Every decode routes group elements through the +// checked constructors (NewGqElement / NewZqElement), so a peer can never inject +// a value outside G_q or Z_q — this closes the small-subgroup / non-residue hole +// (finding M4) at the point where proofs and ciphertexts cross a trust boundary. + +// --- scalar helpers --- + +func gqToStr(e emath.GqElement) string { return e.Value().String() } +func zqToStr(e emath.ZqElement) string { return e.Value().String() } + +func strToGq(s string, group *emath.GqGroup) (emath.GqElement, error) { + v, ok := new(big.Int).SetString(s, 10) + if !ok { + return emath.GqElement{}, fmt.Errorf("invalid integer %q", s) + } + return emath.NewGqElement(v, group) // validates membership in G_q +} + +func strToZq(s string, zq *emath.ZqGroup) (emath.ZqElement, error) { + v, ok := new(big.Int).SetString(s, 10) + if !ok { + return emath.ZqElement{}, fmt.Errorf("invalid integer %q", s) + } + return emath.NewZqElement(v, zq) // validates range [0, q) +} + +// --- vectors --- + +func gqVecToStrs(v *emath.GqVector) []string { + out := make([]string, v.Size()) + for i := 0; i < v.Size(); i++ { + out[i] = gqToStr(v.Get(i)) + } + return out +} + +func strsToGqVec(ss []string, group *emath.GqGroup) (*emath.GqVector, error) { + elems := make([]emath.GqElement, len(ss)) + for i, s := range ss { + e, err := strToGq(s, group) + if err != nil { + return nil, fmt.Errorf("gq vector element %d: %w", i, err) + } + elems[i] = e + } + return emath.GqVectorOf(elems...), nil +} + +func zqVecToStrs(v *emath.ZqVector) []string { + out := make([]string, v.Size()) + for i := 0; i < v.Size(); i++ { + out[i] = zqToStr(v.Get(i)) + } + return out +} + +func strsToZqVec(ss []string, zq *emath.ZqGroup) (*emath.ZqVector, error) { + elems := make([]emath.ZqElement, len(ss)) + for i, s := range ss { + e, err := strToZq(s, zq) + if err != nil { + return nil, fmt.Errorf("zq vector element %d: %w", i, err) + } + elems[i] = e + } + return emath.ZqVectorOf(elems...), nil +} + +// --- public key --- + +type wirePublicKey struct { + Elements []string `json:"elements"` +} + +func encodePK(pk elgamal.PublicKey) wirePublicKey { + return wirePublicKey{Elements: gqVecToStrs(pk.Elements)} +} + +func (w wirePublicKey) decode(group *emath.GqGroup) (elgamal.PublicKey, error) { + vec, err := strsToGqVec(w.Elements, group) + if err != nil { + return elgamal.PublicKey{}, fmt.Errorf("public key: %w", err) + } + return elgamal.PublicKey{Elements: vec}, nil +} + +// --- Schnorr proof --- + +type wireSchnorr struct { + E string `json:"e"` + Z string `json:"z"` +} + +func encodeSchnorr(p zkp.SchnorrProof) wireSchnorr { + return wireSchnorr{E: zqToStr(p.E), Z: zqToStr(p.Z)} +} + +func (w wireSchnorr) decode(zq *emath.ZqGroup) (zkp.SchnorrProof, error) { + e, err := strToZq(w.E, zq) + if err != nil { + return zkp.SchnorrProof{}, fmt.Errorf("schnorr E: %w", err) + } + z, err := strToZq(w.Z, zq) + if err != nil { + return zkp.SchnorrProof{}, fmt.Errorf("schnorr Z: %w", err) + } + return zkp.SchnorrProof{E: e, Z: z}, nil +} + +// --- ciphertext --- + +type wireCiphertext struct { + Gamma string `json:"gamma"` + Phis []string `json:"phis"` +} + +func encodeCiphertext(ct elgamal.Ciphertext) wireCiphertext { + return wireCiphertext{Gamma: gqToStr(ct.Gamma), Phis: gqVecToStrs(ct.Phis)} +} + +func (w wireCiphertext) decode(group *emath.GqGroup) (elgamal.Ciphertext, error) { + gamma, err := strToGq(w.Gamma, group) + if err != nil { + return elgamal.Ciphertext{}, fmt.Errorf("ciphertext gamma: %w", err) + } + phis, err := strsToGqVec(w.Phis, group) + if err != nil { + return elgamal.Ciphertext{}, fmt.Errorf("ciphertext phis: %w", err) + } + return elgamal.NewCiphertext(gamma, phis), nil +} + +// --- ciphertext vector --- + +type wireCiphertextVector struct { + Cts []wireCiphertext `json:"cts"` +} + +func encodeCiphertextVector(v *elgamal.CiphertextVector) wireCiphertextVector { + out := make([]wireCiphertext, v.Size()) + for i := 0; i < v.Size(); i++ { + out[i] = encodeCiphertext(v.Get(i)) + } + return wireCiphertextVector{Cts: out} +} + +func (w wireCiphertextVector) decode(group *emath.GqGroup) (*elgamal.CiphertextVector, error) { + cts := make([]elgamal.Ciphertext, len(w.Cts)) + for i, wc := range w.Cts { + ct, err := wc.decode(group) + if err != nil { + return nil, fmt.Errorf("ciphertext %d: %w", i, err) + } + cts[i] = ct + } + return elgamal.NewCiphertextVector(cts), nil +}