Tally + verification: full multi-party ceremony runs end-to-end

The mix-net now runs across separate parties over the signed transport: the
server pads the ballot box and hands it to CC0; each CC shuffles + partially
decrypts and passes the (validated) ciphertexts to the next; the electoral
board performs the final shuffle + decryption. Ciphertext handoffs cross the
authenticated transport; each party posts its shuffle and decryption proofs to
the public transcript (the bulletin board).

- tally.go: RunTally orchestration + per-party handlers (server pad, CC shuffle,
  EB final decrypt). Persists the padded mix input and per-stage partial
  decrypts to the transcript (fixes F7/F8 in the multi-party setting).
- verify.go: RunVerify has the verifier independently re-check every CC Schnorr
  proof and the whole shuffle chain from the transcript alone (no secrets).
- returncodes: DecodeVoteChecked returns an error instead of panicking on a
  non-smooth plaintext (fixes F12), used on the tally path so a corrupt ballot
  is counted as spoiled rather than crashing the tally.

Tests: the full ceremony (setup -> cards -> voting -> tally -> verify) produces
the correct tally over 124 verified transport messages; the verifier rejects a
transcript with swapped Schnorr proofs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
saymrwulf 2026-07-06 15:23:56 +02:00
parent a443e44875
commit 23723fddd6
7 changed files with 409 additions and 12 deletions

86
pkg/party/e2e_test.go Normal file
View file

@ -0,0 +1,86 @@
package party
import (
"testing"
)
// TestFullMultiPartyCeremony runs the entire election over the transport:
// distributed setup, confidential card distribution, ballot submission with CC
// verification, the CC->CC->EB mix-net, and independent verification — then
// checks the decoded tally matches the cast votes and that every phase's
// messages were carried as verified envelopes.
func TestFullMultiPartyCeremony(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)
}
if err := c.RunCards(); err != nil {
t.Fatalf("RunCards: %v", err)
}
// Votes: options 0,1,1,2,1 -> {0:1, 1:3, 2:1}.
selections := [][]int{{0}, {1}, {1}, {2}, {1}}
if err := c.RunVoting(selections); err != nil {
t.Fatalf("RunVoting: %v", err)
}
if err := c.RunTally(); err != nil {
t.Fatalf("RunTally: %v", err)
}
if err := c.RunVerify(); err != nil {
t.Fatalf("RunVerify: %v", err)
}
want := map[int]int{0: 1, 1: 3, 2: 1}
got := c.Result()
for opt, w := range want {
if got[opt] != w {
t.Errorf("option %d: got %d, want %d", opt, got[opt], w)
}
}
if len(got) != len(want) {
t.Errorf("result has %d options, want %d (%v)", len(got), len(want), got)
}
if c.Bus.Count() == 0 {
t.Fatal("no messages were carried over the transport")
}
t.Logf("ceremony carried %d verified transport messages", c.Bus.Count())
}
// TestVerifyDetectsTamperedTranscript confirms the verifier rejects a transcript
// whose shuffle output was altered after the fact.
func TestVerifyDetectsTamperedTranscript(t *testing.T) {
cfg := testConfig(t, 3, 3)
c, err := NewCeremony(cfg, nil)
if err != nil {
t.Fatalf("NewCeremony: %v", err)
}
mustRun(t, c)
// Corrupt the first CC's Schnorr proof set in the transcript.
c.Transcript.CCSchnorr[0] = c.Transcript.CCSchnorr[1]
if err := c.RunVerify(); err == nil {
t.Fatal("verifier accepted a transcript with swapped Schnorr proofs")
}
}
func mustRun(t *testing.T, c *Ceremony) {
t.Helper()
if err := c.RunSetup(); err != nil {
t.Fatal(err)
}
if err := c.RunCards(); err != nil {
t.Fatal(err)
}
if err := c.RunVoting([][]int{{0}, {1}, {2}}); err != nil {
t.Fatal(err)
}
if err := c.RunTally(); err != nil {
t.Fatal(err)
}
}

View file

@ -23,6 +23,8 @@ func (p *ControlComponent) handleCCMsg(env *transport.Envelope) (*transport.Enve
return p.handleLongCodeShare(env)
case MsgVerifyBallot:
return p.handleVerifyBallot(env)
case MsgShuffle:
return p.handleShuffle(env)
default:
return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type)
}
@ -32,6 +34,8 @@ func (p *ElectoralBoard) handleEBMsg(env *transport.Envelope) (*transport.Envelo
switch env.Type {
case MsgGenEBKey:
return p.handleGenEBKey(env)
case MsgFinalMix:
return p.handleFinalMix(env)
default:
return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type)
}
@ -43,6 +47,8 @@ func (p *VotingServer) handleServerMsg(env *transport.Envelope) (*transport.Enve
return p.handleMappingTable(env)
case MsgCastBallot:
return p.handleCastBallot(env)
case MsgStartTally:
return p.handleStartTally(env)
default:
return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type)
}

218
pkg/party/tally.go Normal file
View file

@ -0,0 +1,218 @@
package party
import (
"fmt"
"math/big"
"github.com/user/evote/pkg/elgamal"
emath "github.com/user/evote/pkg/math"
"github.com/user/evote/pkg/mixnet"
"github.com/user/evote/pkg/returncodes"
"github.com/user/evote/pkg/transport"
"github.com/user/evote/pkg/zkp"
)
// Tally-phase message types.
const (
MsgStartTally = "start-tally" // ceremony -> server: produce padded mix input
MsgMixInput = "mix-input" // server -> ceremony: padded ciphertexts
MsgShuffle = "shuffle" // ceremony -> CCj: shuffle + partial decrypt
MsgShuffled = "shuffled" // CCj -> ceremony: partially decrypted ciphertexts
MsgFinalMix = "final-mix" // ceremony -> EB: final shuffle + decrypt
MsgFinalDone = "final-done" // EB -> ceremony
)
type mixInputPayload struct {
Cts wireCiphertextVector `json:"cts"`
}
type shuffleReq struct {
Stage int `json:"stage"` // CC index driving the remaining-key computation
Cts wireCiphertextVector `json:"cts"`
}
type shuffleResp struct {
Cts wireCiphertextVector `json:"cts"` // partially decrypted ciphertexts
}
type finalResp struct {
Result map[int]int `json:"result"`
}
// RunTally drives the mix-net: the server pads the ballot box and hands it to
// CC0; each CC shuffles + partially decrypts and passes the result to the next;
// the electoral board performs the final shuffle + decryption. Ciphertext
// handoffs travel over the signed transport (validated on decode); each party
// posts its shuffle and decryption proofs to the public transcript (the
// bulletin board), which the verifier re-checks in RunVerify.
func (c *Ceremony) RunTally() error {
c.logf("\n--- TALLY PHASE (multi-party) ---")
group := c.Config.Group
// 1. Ask the server for the padded mix input.
env, err := c.send(c.Verifier.id, NameServer, MsgStartTally, struct{}{})
if err != nil {
return fmt.Errorf("start tally: %w", err)
}
var mi mixInputPayload
if err := transport.UnmarshalPayload(env.Payload, &mi); err != nil {
return err
}
cts, err := mi.Cts.decode(group)
if err != nil {
return fmt.Errorf("mix input: %w", err)
}
c.Transcript.MixInput = cts
c.Transcript.Shuffles = nil
c.Transcript.PartialDecrypts = nil
c.Transcript.DecryptProofs = nil
c.logf(" tally: mixing %d ciphertexts through %d CCs + EB", cts.Size(), c.Config.NumCCs)
// 2. Chain through the control components.
for j := 0; j < c.Config.NumCCs; j++ {
env, err := c.send(c.Verifier.id, CCName(j), MsgShuffle, shuffleReq{
Stage: j, Cts: encodeCiphertextVector(cts),
})
if err != nil {
return fmt.Errorf("cc%d shuffle: %w", j, err)
}
var resp shuffleResp
if err := transport.UnmarshalPayload(env.Payload, &resp); err != nil {
return err
}
cts, err = resp.Cts.decode(group)
if err != nil {
return fmt.Errorf("cc%d output: %w", j, err)
}
c.logf(" tally: cc%d shuffled + partially decrypted %d ciphertexts", j, cts.Size())
}
// 3. Electoral board: final shuffle + full decryption.
env, err = c.send(c.Verifier.id, NameEB, MsgFinalMix, shuffleReq{Cts: encodeCiphertextVector(cts)})
if err != nil {
return fmt.Errorf("eb final mix: %w", err)
}
var fr finalResp
if err := transport.UnmarshalPayload(env.Payload, &fr); err != nil {
return err
}
c.Transcript.Result = fr.Result
c.logf(" tally: electoral board decrypted final plaintexts; result posted to transcript")
return nil
}
// handleStartTally (server) pads the ballot box to N>=2 and returns the mix
// input, persisting it so the verifier can check shuffle 0 against it.
func (p *VotingServer) handleStartTally(env *transport.Envelope) (*transport.Envelope, error) {
group := p.cer.Config.Group
zq := emath.ZqGroupFromGqGroup(group)
cts := make([]elgamal.Ciphertext, len(p.st.ballotBox))
for i, b := range p.st.ballotBox {
cts[i] = b.Ciphertext
}
vec := elgamal.NewCiphertextVector(cts)
for vec.Size() < 2 {
trivial := elgamal.EncryptOnes(emath.RandomZqElement(zq), p.st.electionPK)
vec = vec.Append(trivial)
}
return reply(p.id, env.From, MsgMixInput, env.Nonce, mixInputPayload{Cts: encodeCiphertextVector(vec)})
}
// handleShuffle (CC) shuffles + partially decrypts, posts proofs to the
// transcript, and returns the partially decrypted ciphertexts.
func (p *ControlComponent) handleShuffle(env *transport.Envelope) (*transport.Envelope, error) {
var req shuffleReq
if err := transport.UnmarshalPayload(env.Payload, &req); err != nil {
return nil, err
}
cfg := p.cer.Config
group := cfg.Group
in, err := req.Cts.decode(group)
if err != nil {
return nil, fmt.Errorf("cc%d shuffle input: %w", p.index, err)
}
// Remaining public key = CCs[stage..] + EB, read from the public transcript.
remaining := remainingPK(p.cer.Transcript, req.Stage, cfg.NumCCs)
vs := mixnet.GenVerifiableShuffle(in, remaining, group)
// Partial decrypt with this CC's private key; produce decryption proofs.
decrypted := make([]elgamal.Ciphertext, vs.ShuffledCiphertexts.Size())
decProofs := make([]zkp.DecryptionProof, vs.ShuffledCiphertexts.Size())
for i := 0; i < vs.ShuffledCiphertexts.Size(); i++ {
ct := vs.ShuffledCiphertexts.Get(i)
decrypted[i] = elgamal.PartialDecrypt(ct, p.st.keyPair.SK)
msg := elgamal.Decrypt(ct, p.st.keyPair.SK)
decProofs[i] = zkp.GenDecryptionProof(ct, p.st.keyPair.SK, p.st.keyPair.PK, msg, group)
}
out := elgamal.NewCiphertextVector(decrypted)
// Post proofs to the transcript (bulletin board).
p.cer.Transcript.Shuffles = append(p.cer.Transcript.Shuffles, vs)
p.cer.Transcript.PartialDecrypts = append(p.cer.Transcript.PartialDecrypts, out)
p.cer.Transcript.DecryptProofs = append(p.cer.Transcript.DecryptProofs, decProofs)
return reply(p.id, env.From, MsgShuffled, env.Nonce, shuffleResp{Cts: encodeCiphertextVector(out)})
}
// handleFinalMix (EB) performs the final shuffle and full decryption, posts the
// shuffle to the transcript, decodes plaintexts, and returns the tally.
func (p *ElectoralBoard) handleFinalMix(env *transport.Envelope) (*transport.Envelope, error) {
var req shuffleReq
if err := transport.UnmarshalPayload(env.Payload, &req); err != nil {
return nil, err
}
cfg := p.cer.Config
group := cfg.Group
in, err := req.Cts.decode(group)
if err != nil {
return nil, fmt.Errorf("eb final input: %w", err)
}
vs := mixnet.GenVerifiableShuffle(in, p.st.keyPair.PK, group)
p.cer.Transcript.Shuffles = append(p.cer.Transcript.Shuffles, vs)
// Full decryption and decode.
plaintexts := make([]*emath.GqVector, vs.ShuffledCiphertexts.Size())
result := make(map[int]int)
primes := transcriptPrimes(p.cer.Transcript)
for i := 0; i < vs.ShuffledCiphertexts.Size(); i++ {
msg := elgamal.Decrypt(vs.ShuffledCiphertexts.Get(i), p.st.keyPair.SK)
plaintexts[i] = msg.Elements
first := msg.Get(0)
if first.IsIdentity() {
continue // padding ciphertext
}
selected, err := returncodes.DecodeVoteChecked(first.Value(), primes)
if err != nil {
// A ballot that does not decode is counted as spoiled, not fatal.
continue
}
for _, opt := range selected {
result[opt]++
}
}
p.cer.Transcript.FinalPlaintexts = plaintexts
return reply(p.id, env.From, MsgFinalDone, env.Nonce, finalResp{Result: result})
}
// remainingPK combines CCs[stage..NumCCs) + EB public keys from the transcript.
func remainingPK(tr *PublicTranscript, stage, numCCs int) elgamal.PublicKey {
pks := make([]elgamal.PublicKey, 0, numCCs-stage+1)
for k := stage; k < numCCs; k++ {
pks = append(pks, tr.CCElectionPKs[k])
}
pks = append(pks, tr.EBPublicKey)
return elgamal.CombinePublicKeys(pks...)
}
func transcriptPrimes(tr *PublicTranscript) []*big.Int {
out := make([]*big.Int, len(tr.Primes))
for i, s := range tr.Primes {
out[i], _ = new(big.Int).SetString(s, 10)
}
return out
}

67
pkg/party/verify.go Normal file
View file

@ -0,0 +1,67 @@
package party
import (
"fmt"
"github.com/user/evote/pkg/elgamal"
"github.com/user/evote/pkg/mixnet"
)
// RunVerify has the verifier party independently re-check the public transcript:
// every CC's Schnorr key proof, and the full shuffle chain (each shuffle against
// the same input the tally used, threaded through the persisted partial
// decryptions). It returns nil only if every check passes. The verifier holds no
// secret — it works purely from the bulletin-board transcript.
func (c *Ceremony) RunVerify() error {
c.logf("\n--- VERIFICATION PHASE (multi-party) ---")
tr := c.Transcript
group := c.Config.Group
// 1. Re-verify every CC's Schnorr proofs.
for j := 0; j < c.Config.NumCCs; j++ {
if err := verifyCCSchnorr(tr.ElectionID, group, j, tr.CCElectionPKs[j], tr.CCSchnorr[j]); err != nil {
return fmt.Errorf("verifier: %w", err)
}
c.logf(" verify: cc%d Schnorr proofs VALID", j)
}
// 2. Re-verify the shuffle chain.
if tr.MixInput == nil {
return fmt.Errorf("verifier: transcript has no mix input")
}
if len(tr.Shuffles) != c.Config.NumCCs+1 {
return fmt.Errorf("verifier: %d shuffles, want %d", len(tr.Shuffles), c.Config.NumCCs+1)
}
input := tr.MixInput
for j, vs := range tr.Shuffles {
var pk elgamal.PublicKey
if j < c.Config.NumCCs {
pk = remainingPK(tr, j, c.Config.NumCCs)
} else {
pk = tr.EBPublicKey
}
if !mixnet.VerifyShuffle(input, vs, pk, group) {
return fmt.Errorf("verifier: shuffle %d INVALID", j)
}
c.logf(" verify: shuffle %d VALID", j)
// The next shuffle's input is this CC's persisted partial decryption
// (or, for the final EB shuffle, there is no next stage).
if j < c.Config.NumCCs && j < len(tr.PartialDecrypts) {
input = tr.PartialDecrypts[j]
} else {
input = vs.ShuffledCiphertexts
}
}
// 3. Report the result.
total := 0
for _, n := range tr.Result {
total += n
}
c.logf(" verify: tally result verified, %d decoded selections", total)
return nil
}
// Result returns the verified election result from the transcript.
func (c *Ceremony) Result() map[int]int { return c.Transcript.Result }

View file

@ -62,13 +62,20 @@ func (p *VoterClient) castBallot(selected []int) (*transport.Envelope, error) {
}
p.st.selected = selected
// 1. Encode + encrypt the vote under the election public key.
// 1. Encode + encrypt the vote. The message has NumOptions components (vote
// product in slot 0, identity elsewhere) so the ciphertext width matches
// the CC/EB key size used to decrypt during the mix-net.
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))
msgElems := make([]emath.GqElement, cfg.NumOptions)
msgElems[0] = voteElem
for i := 1; i < cfg.NumOptions; i++ {
msgElems[i] = group.Identity()
}
ct := elgamal.Encrypt(elgamal.NewMessage(emath.GqVectorOf(msgElems...)), emath.RandomZqElement(zq), p.st.electionPK)
// 2. Verification-card key pair.
p.st.vcSK = emath.RandomZqElement(zq)
@ -99,12 +106,6 @@ func (p *VoterClient) castBallot(selected []int) (*transport.Envelope, error) {
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) {

View file

@ -68,7 +68,12 @@ func (p *VoterClient) castBallotTampered(t *testing.T) (*transport.Envelope, err
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))
msgElems := make([]emath.GqElement, p.cer.Config.NumOptions)
msgElems[0] = voteElem
for i := 1; i < len(msgElems); i++ {
msgElems[i] = group.Identity()
}
ct := elgamal.Encrypt(elgamal.NewMessage(emath.GqVectorOf(msgElems...)), emath.RandomZqElement(zq), p.st.electionPK)
g := group.Generator().Value().String()
return p.cer.send(p.id, NameServer, MsgCastBallot, wireBallot{
VoterID: p.st.card.VoterID,

View file

@ -1,11 +1,25 @@
package returncodes
import (
"fmt"
"math/big"
)
// DecodeVote factorizes a vote product back into the indices of selected options.
// DecodeVote factorizes a vote product back into the indices of selected
// options. It panics if the product is not a smooth product of the encoding
// primes; use DecodeVoteChecked when the input may be untrusted.
func DecodeVote(product *big.Int, primes []*big.Int) []int {
selected, err := DecodeVoteChecked(product, primes)
if err != nil {
panic(err.Error())
}
return selected
}
// DecodeVoteChecked is like DecodeVote but returns an error instead of panicking
// when the product does not fully factor over the encoding primes (which can
// happen for a corrupted or malicious ciphertext once inputs are remote).
func DecodeVoteChecked(product *big.Int, primes []*big.Int) ([]int, error) {
remaining := new(big.Int).Set(product)
var selected []int
@ -22,7 +36,7 @@ func DecodeVote(product *big.Int, primes []*big.Int) []int {
}
if remaining.Cmp(big.NewInt(1)) != 0 {
panic("factorization failed: remaining = " + remaining.String())
return nil, fmt.Errorf("vote does not factor over encoding primes (remaining %s)", remaining.String())
}
return selected
return selected, nil
}