From a443e4487504a5e3c7ba14f7d4babb31ff469980 Mon Sep 17 00:00:00 2001 From: saymrwulf Date: Mon, 6 Jul 2026 15:19:07 +0200 Subject: [PATCH] Voting phase: ballot submission with cross-party proof verification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Voters encrypt their selection under the election key, build the (sound) exponentiation proof binding the ballot to their verification-card key, and submit to the voting server. The server validates every group element on receipt, routes the ballot to all four CCs for proof verification, and stores it only on unanimous acceptance — persisting vcPK (finding F6) so the proof statement is reconstructible by any party. - voting.go: castBallot (voter), handleCastBallot (server), handleVerifyBallot (CC). The CC re-derives the proof statement and verifies it; a malformed proof or bad group element yields a clean reject, never a panic (the trust-boundary hardening deferred from the due-diligence pass). - wire.go: exponentiation-proof DTO. Tests: 4 ballots flow end-to-end and are stored with vcPK; a ballot with a zeroed proof is rejected by the CCs and never stored. Co-Authored-By: Claude Fable 5 --- pkg/party/codes.go | 46 +++++++-- pkg/party/phases.go | 4 + pkg/party/state.go | 8 +- pkg/party/voting.go | 209 +++++++++++++++++++++++++++++++++++++++ pkg/party/voting_test.go | 82 +++++++++++++++ pkg/party/wire.go | 18 ++++ 6 files changed, 358 insertions(+), 9 deletions(-) create mode 100644 pkg/party/voting.go create mode 100644 pkg/party/voting_test.go diff --git a/pkg/party/codes.go b/pkg/party/codes.go index af59bd1..23baa19 100644 --- a/pkg/party/codes.go +++ b/pkg/party/codes.go @@ -93,8 +93,19 @@ func (c *Ceremony) RunCards() error { if err != nil { return err } - // Deliver the card to the voter confidentially. - if _, err := c.sendConfidential(c.Setup.id, VoterName(v), MsgVotingCard, card); err != nil { + // Deliver the card plus the public election parameters the voter needs + // to encrypt, confidentially. + primeStrs := make([]string, len(c.Setup.st.primes)) + for i, p := range c.Setup.st.primes { + primeStrs[i] = p.String() + } + delivery := cardDelivery{ + Card: *card, + ElectionPK: encodePK(c.Setup.st.electionPK), + ReturnCodePK: encodePK(c.Setup.st.returnCodePK), + Primes: primeStrs, + } + if _, err := c.sendConfidential(c.Setup.id, VoterName(v), MsgVotingCard, delivery); err != nil { return fmt.Errorf("deliver card to voter %d: %w", v, err) } } @@ -125,13 +136,36 @@ type mappingTablePayload struct { Primes []string `json:"primes"` } -// handleVotingCard (voter) receives and stores its confidential card. +// cardDelivery is the confidential payload a voter receives: its private card +// plus the public election parameters it needs to encrypt a ballot. +type cardDelivery struct { + Card votingCard `json:"card"` + ElectionPK wirePublicKey `json:"election_pk"` + ReturnCodePK wirePublicKey `json:"return_code_pk"` + Primes []string `json:"primes"` +} + +// handleVotingCard (voter) receives and stores its confidential card + params. func (p *VoterClient) handleVotingCard(env *transport.Envelope) (*transport.Envelope, error) { - var card votingCard - if err := p.cer.openConfidential(p.id, env, &card); err != nil { + var d cardDelivery + if err := p.cer.openConfidential(p.id, env, &d); err != nil { return nil, err } - p.st.card = &card + group := p.cer.Config.Group + pk, err := d.ElectionPK.decode(group) + if err != nil { + return nil, err + } + p.st.card = &d.Card + p.st.electionPK = pk + p.st.primes = make([]*big.Int, len(d.Primes)) + for i, ps := range d.Primes { + v, ok := new(big.Int).SetString(ps, 10) + if !ok { + return nil, fmt.Errorf("voter: invalid prime %q", ps) + } + p.st.primes[i] = v + } return reply(p.id, env.From, MsgAck, env.Nonce, ackPayload{Party: p.id.Name, OK: true}) } diff --git a/pkg/party/phases.go b/pkg/party/phases.go index 66c238a..f607388 100644 --- a/pkg/party/phases.go +++ b/pkg/party/phases.go @@ -21,6 +21,8 @@ func (p *ControlComponent) handleCCMsg(env *transport.Envelope) (*transport.Enve return p.handleGenCCKeys(env) case MsgLongCodeShareReq: return p.handleLongCodeShare(env) + case MsgVerifyBallot: + return p.handleVerifyBallot(env) default: return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type) } @@ -39,6 +41,8 @@ func (p *VotingServer) handleServerMsg(env *transport.Envelope) (*transport.Enve switch env.Type { case MsgMappingTable: return p.handleMappingTable(env) + case MsgCastBallot: + return p.handleCastBallot(env) default: return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type) } diff --git a/pkg/party/state.go b/pkg/party/state.go index 1e06fa3..ff5e7ec 100644 --- a/pkg/party/state.go +++ b/pkg/party/state.go @@ -52,9 +52,11 @@ type serverState struct { // voterState is a voter client's private card and ballot secrets. type voterState struct { - card *votingCard - vcSK emath.ZqElement - selected []int + card *votingCard + electionPK elgamal.PublicKey + primes []*big.Int + vcSK emath.ZqElement + selected []int } // votingCard is a voter's credential bundle (private to the voter, produced by diff --git a/pkg/party/voting.go b/pkg/party/voting.go new file mode 100644 index 0000000..629a615 --- /dev/null +++ b/pkg/party/voting.go @@ -0,0 +1,209 @@ +package party + +import ( + "fmt" + + "github.com/user/evote/pkg/elgamal" + "github.com/user/evote/pkg/hash" + emath "github.com/user/evote/pkg/math" + "github.com/user/evote/pkg/returncodes" + "github.com/user/evote/pkg/transport" + "github.com/user/evote/pkg/zkp" +) + +// Voting-phase message types. +const ( + MsgCastBallot = "cast-ballot" // voter -> server + MsgBallotStored = "ballot-stored" // server -> voter + MsgVerifyBallot = "verify-ballot" // server -> CCj + MsgBallotVerdict = "ballot-verdict" +) + +// wireBallot is a submitted ballot. It carries the encrypted vote, the +// exponentiated ciphertext, the verification-card public key (persisted so a +// remote party can reconstruct the proof statement — finding F6), and the +// exponentiation proof binding vcPK to the exponentiation. +type wireBallot struct { + VoterID string `json:"voter_id"` + VcID string `json:"vc_id"` + Ciphertext wireCiphertext `json:"ciphertext"` + ExponentiatedG string `json:"exp_gamma"` + ExponentiatedP string `json:"exp_phi0"` + VcPK string `json:"vc_pk"` + ExpProof wireSchnorr `json:"exp_proof"` +} + +// RunVoting has every voter encrypt its selection and submit a ballot; the +// server routes each ballot to all CCs for proof verification and stores the +// accepted ballots. Selections are provided per voter (indexed by voter). +func (c *Ceremony) RunVoting(selections [][]int) error { + c.logf("\n--- VOTING PHASE (multi-party) ---") + for v, voter := range c.Voters { + sel := []int{0} + if v < len(selections) && len(selections[v]) > 0 { + sel = selections[v] + } + if _, err := voter.castBallot(sel); err != nil { + return fmt.Errorf("voter %d cast: %w", v, err) + } + } + c.logf(" voting: %d ballots submitted and accepted", len(c.Voters)) + return nil +} + +// castBallot (voter) encrypts the selection, builds the exponentiation proof, +// and submits the ballot to the server. +func (p *VoterClient) castBallot(selected []int) (*transport.Envelope, error) { + cfg := p.cer.Config + group := cfg.Group + zq := emath.ZqGroupFromGqGroup(group) + if p.st.card == nil { + return nil, fmt.Errorf("%s has no voting card", p.id.Name) + } + p.st.selected = selected + + // 1. Encode + encrypt the vote under the election public key. + product := returncodes.EncodeVote(selected, p.st.primes) + voteElem, err := emath.NewGqElement(product, group) + if err != nil { + return nil, fmt.Errorf("vote product not in group: %w", err) + } + ct := elgamal.Encrypt(elgamal.NewMessage(emath.GqVectorOf(voteElem)), emath.RandomZqElement(zq), singlePK(p.st.electionPK)) + + // 2. Verification-card key pair. + p.st.vcSK = emath.RandomZqElement(zq) + vcPK := group.Generator().Exponentiate(p.st.vcSK) + + // 3. Exponentiated ciphertext components (E1_tilde). + gammaExp := ct.Gamma.Exponentiate(p.st.vcSK) + phi0Exp := ct.GetPhi(0).Exponentiate(p.st.vcSK) + + // 4. Exponentiation proof: knowledge of vcSK s.t. (vcPK,gammaExp,phi0Exp) are + // (g,gamma,phi0) raised to the same vcSK. This binds the ballot to vcPK. + bases := emath.GqVectorOf(group.Generator(), ct.Gamma, ct.GetPhi(0)) + exps := emath.GqVectorOf(vcPK, gammaExp, phi0Exp) + expProof := zkp.GenExponentiationProof(bases, p.st.vcSK, exps, group, + hash.HashableString{Value: cfg.ElectionID}, + hash.HashableString{Value: p.st.card.VerificationCardID}, + ) + + ballot := wireBallot{ + VoterID: p.st.card.VoterID, + VcID: p.st.card.VerificationCardID, + Ciphertext: encodeCiphertext(ct), + ExponentiatedG: gammaExp.Value().String(), + ExponentiatedP: phi0Exp.Value().String(), + VcPK: vcPK.Value().String(), + ExpProof: encodeExponentiation(expProof), + } + return p.cer.send(p.id, NameServer, MsgCastBallot, ballot) +} + +// singlePK returns a single-element public key (index 0) for encrypting the vote +// product as a one-component message. +func singlePK(pk elgamal.PublicKey) elgamal.PublicKey { + return elgamal.PublicKey{Elements: emath.GqVectorOf(pk.Elements.Get(0))} +} + +// handleCastBallot (server) validates a ballot's structure, asks every CC to +// verify its exponentiation proof, and stores it on unanimous acceptance. +func (p *VotingServer) handleCastBallot(env *transport.Envelope) (*transport.Envelope, error) { + var b wireBallot + if err := transport.UnmarshalPayload(env.Payload, &b); err != nil { + return nil, err + } + group := p.cer.Config.Group + + // Decode + validate all group elements (rejects malformed ballots cleanly). + ct, err := b.Ciphertext.decode(group) + if err != nil { + return nil, fmt.Errorf("ballot ciphertext: %w", err) + } + vcPK, err := strToGq(b.VcPK, group) + if err != nil { + return nil, fmt.Errorf("ballot vcPK: %w", err) + } + if _, err := strToGq(b.ExponentiatedG, group); err != nil { + return nil, fmt.Errorf("ballot exp gamma: %w", err) + } + if _, err := strToGq(b.ExponentiatedP, group); err != nil { + return nil, fmt.Errorf("ballot exp phi0: %w", err) + } + + // Route to every CC for proof verification; require unanimous acceptance. + for j := 0; j < p.cer.Config.NumCCs; j++ { + env2, err := p.cer.send(p.id, CCName(j), MsgVerifyBallot, b) + if err != nil { + return nil, fmt.Errorf("server->cc%d verify: %w", j, err) + } + var verdict ballotVerdict + if err := transport.UnmarshalPayload(env2.Payload, &verdict); err != nil { + return nil, err + } + if !verdict.Accept { + return nil, fmt.Errorf("cc%d rejected ballot %s: %s", j, b.VcID, verdict.Reason) + } + } + + // Store the ballot (persisting vcPK, finding F6). + p.st.ballotBox = append(p.st.ballotBox, encryptedBallot{ + VoterID: b.VoterID, + VerificationCardID: b.VcID, + Ciphertext: ct, + VcPK: vcPK, + }) + return reply(p.id, env.From, MsgBallotStored, env.Nonce, ackPayload{Party: p.id.Name, OK: true}) +} + +type ballotVerdict struct { + Accept bool `json:"accept"` + Reason string `json:"reason"` +} + +// handleVerifyBallot (CC) re-derives the exponentiation-proof statement and +// verifies it. A malformed proof yields a clean reject, never a panic. +func (p *ControlComponent) handleVerifyBallot(env *transport.Envelope) (*transport.Envelope, error) { + var b wireBallot + if err := transport.UnmarshalPayload(env.Payload, &b); err != nil { + return nil, err + } + cfg := p.cer.Config + group := cfg.Group + zq := emath.ZqGroupFromGqGroup(group) + + reject := func(reason string) (*transport.Envelope, error) { + return reply(p.id, env.From, MsgBallotVerdict, env.Nonce, ballotVerdict{Accept: false, Reason: reason}) + } + + ct, err := b.Ciphertext.decode(group) + if err != nil { + return reject("bad ciphertext") + } + vcPK, err := strToGq(b.VcPK, group) + if err != nil { + return reject("bad vcPK") + } + gammaExp, err := strToGq(b.ExponentiatedG, group) + if err != nil { + return reject("bad exp gamma") + } + phi0Exp, err := strToGq(b.ExponentiatedP, group) + if err != nil { + return reject("bad exp phi0") + } + proof, err := b.ExpProof.decodeExponentiation(zq) + if err != nil { + return reject("bad proof encoding") + } + + bases := emath.GqVectorOf(group.Generator(), ct.Gamma, ct.GetPhi(0)) + exps := emath.GqVectorOf(vcPK, gammaExp, phi0Exp) + ok := zkp.VerifyExponentiationProof(bases, exps, proof, group, + hash.HashableString{Value: cfg.ElectionID}, + hash.HashableString{Value: b.VcID}, + ) + if !ok { + return reject("exponentiation proof INVALID") + } + return reply(p.id, env.From, MsgBallotVerdict, env.Nonce, ballotVerdict{Accept: true}) +} diff --git a/pkg/party/voting_test.go b/pkg/party/voting_test.go new file mode 100644 index 0000000..5828784 --- /dev/null +++ b/pkg/party/voting_test.go @@ -0,0 +1,82 @@ +package party + +import ( + "testing" + + "github.com/user/evote/pkg/elgamal" + emath "github.com/user/evote/pkg/math" + "github.com/user/evote/pkg/returncodes" + "github.com/user/evote/pkg/transport" +) + +func runToVoting(t *testing.T, voters, options int) *Ceremony { + t.Helper() + cfg := testConfig(t, voters, options) + c, err := NewCeremony(cfg, nil) + if err != nil { + t.Fatalf("NewCeremony: %v", err) + } + if err := c.RunSetup(); err != nil { + t.Fatalf("RunSetup: %v", err) + } + if err := c.RunCards(); err != nil { + t.Fatalf("RunCards: %v", err) + } + return c +} + +// TestRunVotingBallotFlow submits ballots and confirms each is CC-verified and +// stored with its vcPK persisted. +func TestRunVotingBallotFlow(t *testing.T) { + c := runToVoting(t, 4, 3) + sel := [][]int{{0}, {1}, {1}, {2}} + if err := c.RunVoting(sel); err != nil { + t.Fatalf("RunVoting: %v", err) + } + if got := len(c.Server.st.ballotBox); got != 4 { + t.Fatalf("ballot box has %d ballots, want 4", got) + } + for i, b := range c.Server.st.ballotBox { + if b.VcPK.Value() == nil { + t.Fatalf("ballot %d did not persist vcPK", i) + } + } +} + +// TestBallotWithBadProofRejected confirms a ballot whose exponentiation proof +// does not match is rejected by the CCs (and the server does not store it), +// without any panic. +func TestBallotWithBadProofRejected(t *testing.T) { + c := runToVoting(t, 1, 3) + voter := c.Voters[0] + + // Build a valid ballot, then corrupt the proof before submitting. + if _, err := voter.castBallotTampered(t); err == nil { + t.Fatal("server accepted a ballot with a tampered proof") + } + if len(c.Server.st.ballotBox) != 0 { + t.Fatal("tampered ballot was stored") + } +} + +// castBallotTampered submits a structurally valid ballot (real ciphertext, +// well-formed group elements) but with a zeroed exponentiation proof that cannot +// verify. Used only by the test above. +func (p *VoterClient) castBallotTampered(t *testing.T) (*transport.Envelope, error) { + t.Helper() + group := p.cer.Config.Group + zq := emath.ZqGroupFromGqGroup(group) + product := returncodes.EncodeVote([]int{0}, p.st.primes) + voteElem, _ := emath.NewGqElement(product, group) + ct := elgamal.Encrypt(elgamal.NewMessage(emath.GqVectorOf(voteElem)), emath.RandomZqElement(zq), singlePK(p.st.electionPK)) + g := group.Generator().Value().String() + return p.cer.send(p.id, NameServer, MsgCastBallot, wireBallot{ + VoterID: p.st.card.VoterID, + VcID: p.st.card.VerificationCardID, + Ciphertext: encodeCiphertext(ct), + ExponentiatedG: g, + ExponentiatedP: g, + VcPK: g, + ExpProof: wireSchnorr{E: "0", Z: "0"}, + }) +} diff --git a/pkg/party/wire.go b/pkg/party/wire.go index 77b4486..e897793 100644 --- a/pkg/party/wire.go +++ b/pkg/party/wire.go @@ -120,6 +120,24 @@ func (w wireSchnorr) decode(zq *emath.ZqGroup) (zkp.SchnorrProof, error) { return zkp.SchnorrProof{E: e, Z: z}, nil } +// --- exponentiation proof (same shape as Schnorr) --- + +func encodeExponentiation(p zkp.ExponentiationProof) wireSchnorr { + return wireSchnorr{E: zqToStr(p.E), Z: zqToStr(p.Z)} +} + +func (w wireSchnorr) decodeExponentiation(zq *emath.ZqGroup) (zkp.ExponentiationProof, error) { + e, err := strToZq(w.E, zq) + if err != nil { + return zkp.ExponentiationProof{}, fmt.Errorf("exp E: %w", err) + } + z, err := strToZq(w.Z, zq) + if err != nil { + return zkp.ExponentiationProof{}, fmt.Errorf("exp Z: %w", err) + } + return zkp.ExponentiationProof{E: e, Z: z}, nil +} + // --- ciphertext --- type wireCiphertext struct {