Voting cards: distributed return-code generation + confidential delivery

Setup now generates each voter's return-code card by collecting shares from all
four CCs over the bus (the GenEncLongCodeShares exchange) and distributes cards
and the mapping table over CONFIDENTIAL channels.

- codes.go: deriveReturnCodeKey is the SINGLE key-derivation function used by a
  CC both when contributing to card assembly and (later) at vote-time extraction
  — structurally preventing the setup/extraction derivation mismatch (F1). Each
  CC computes its choice/confirm shares from its private return-code secret;
  only the shares (validated as G_q members on decode) cross the bus.
- RunCards assembles cards, registers mapping-table entries, and delivers cards
  to voters + the mapping table to the server via sendConfidential (X25519 ECDH
  session key + AES-256-GCM, then Ed25519-signed) — exercising the secure
  channel in the ceremony, not just in tests.
- returncodes: MappingTable Export/ImportMappingTable for transport.

Test confirms every voter receives its card confidentially with the right code
count and the server receives the full mapping table + public election keys.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
saymrwulf 2026-07-06 15:15:38 +02:00
parent 6933835bac
commit dbf00153f8
6 changed files with 379 additions and 1 deletions

View file

@ -156,3 +156,47 @@ func (c *Ceremony) send(from *transport.Identity, to, msgType string, payload an
var globalNonce uint64
func (c *Ceremony) nextNonce() uint64 { globalNonce++; return globalNonce }
// sendConfidential signs AND encrypts a message: the payload is sealed under an
// X25519-derived session key (AES-256-GCM) before the envelope is Ed25519-signed.
// This gives both confidentiality (channel) and authenticity (signature).
func (c *Ceremony) sendConfidential(from *transport.Identity, to, msgType string, payload any) (*transport.Envelope, error) {
peer, err := c.Dir.Lookup(to)
if err != nil {
return nil, err
}
ch, err := from.NewSecureChannel(to, peer.XPub)
if err != nil {
return nil, err
}
plain, err := transport.MarshalPayload(payload)
if err != nil {
return nil, err
}
sealed, err := ch.EncryptPayload(plain, []byte(msgType))
if err != nil {
return nil, err
}
env := &transport.Envelope{From: from.Name, To: to, Type: msgType, Nonce: c.nextNonce(), Encrypted: true, Payload: sealed}
if err := env.Seal(from); err != nil {
return nil, err
}
return c.Bus.Send(env)
}
// openConfidential decrypts an encrypted envelope addressed to the local party.
func (c *Ceremony) openConfidential(local *transport.Identity, env *transport.Envelope, v any) error {
peer, err := c.Dir.Lookup(env.From)
if err != nil {
return err
}
ch, err := local.NewSecureChannel(env.From, peer.XPub)
if err != nil {
return err
}
plain, err := ch.DecryptPayload(env.Payload, []byte(env.Type))
if err != nil {
return fmt.Errorf("decrypt %s->%s: %w", env.From, env.To, err)
}
return transport.UnmarshalPayload(plain, v)
}

252
pkg/party/codes.go Normal file
View file

@ -0,0 +1,252 @@
package party
import (
"fmt"
"math/big"
"github.com/user/evote/pkg/hash"
"github.com/user/evote/pkg/kdf"
emath "github.com/user/evote/pkg/math"
"github.com/user/evote/pkg/returncodes"
"github.com/user/evote/pkg/transport"
)
// Return-code share generation (the GenEncLongCodeShares exchange). The setup
// component asks each CC for its per-voter shares; each CC computes them from
// its PRIVATE return-code secret using deriveReturnCodeKey — the SINGLE key
// derivation used both here (card assembly) and later at vote-time extraction,
// which is what keeps the two consistent (this is the structural fix for the
// old setup/extraction derivation mismatch, finding F1).
const (
MsgLongCodeShareReq = "long-code-share-req" // setup -> CCj
MsgLongCodeShareResp = "long-code-share-resp"
MsgVotingCard = "voting-card" // setup -> voter (confidential)
MsgMappingTable = "mapping-table" // setup -> server (confidential)
labelChoice = "VoterChoiceReturnCodeGeneration"
labelConfirm = "VoterVoteCastReturnCodeGeneration"
)
// deriveReturnCodeKey derives a CC's voter-specific return-code key from its
// secret. Used identically at setup and extraction time.
func deriveReturnCodeKey(secret emath.ZqElement, label, electionID, vcID string, group *emath.GqGroup) emath.ZqElement {
zq := emath.ZqGroupFromGqGroup(group)
info := kdf.BuildKDFInfo(label, electionID, vcID)
kVal := kdf.KDFToZq(hash.IntegerToByteArray(secret.Value()), info, group.Q())
k, _ := emath.NewZqElement(kVal, zq)
return k
}
type longCodeShareReq struct {
VcID string `json:"vc_id"`
ElectionID string `json:"election_id"`
Primes []string `json:"primes"` // decimal encodings of the encoding primes
}
type longCodeShareResp struct {
ChoiceShares []string `json:"choice_shares"` // hpCC_i^{k_choice} per option
ConfirmShare string `json:"confirm_share"` // hCK^{k_confirm}
}
// handleLongCodeShare computes this CC's return-code shares for one voter.
func (p *ControlComponent) handleLongCodeShare(env *transport.Envelope) (*transport.Envelope, error) {
var req longCodeShareReq
if err := transport.UnmarshalPayload(env.Payload, &req); err != nil {
return nil, err
}
group := p.cer.Config.Group
kChoice := deriveReturnCodeKey(p.st.returnCodeSecret, labelChoice, req.ElectionID, req.VcID, group)
choiceShares := make([]string, len(req.Primes))
for i, ps := range req.Primes {
prime, ok := new(big.Int).SetString(ps, 10)
if !ok {
return nil, fmt.Errorf("cc%d: invalid prime %q", p.index, ps)
}
hpCC := hash.HashAndSquare(prime, group)
choiceShares[i] = hpCC.Exponentiate(kChoice).Value().String()
}
// Confirmation-code share, keyed off a per-voter confirmation key.
kConfirm := deriveReturnCodeKey(p.st.returnCodeSecret, labelConfirm, req.ElectionID, req.VcID, group)
ckElem := confirmationKeyElement(req.VcID, group)
hCK := hash.HashAndSquare(ckElem.Value(), group)
confirmShare := hCK.Exponentiate(kConfirm).Value().String()
return reply(p.id, env.From, MsgLongCodeShareResp, env.Nonce, longCodeShareResp{
ChoiceShares: choiceShares,
ConfirmShare: confirmShare,
})
}
// RunCards assembles each voter's return-code card (collecting shares from the
// CCs) and distributes cards to voters and the mapping table to the voting
// server — both over CONFIDENTIAL (X25519-encrypted, Ed25519-signed) channels.
func (c *Ceremony) RunCards() error {
cfg := c.Config
c.Setup.st.mappingTable = returncodes.NewMappingTable()
c.logf(" setup: generating %d voting cards from CC shares...", cfg.NumVoters)
for v := 0; v < cfg.NumVoters; v++ {
card, err := c.assembleVotingCard(v)
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 {
return fmt.Errorf("deliver card to voter %d: %w", v, err)
}
}
// Hand the mapping table and public election data to the voting server.
rows := c.Setup.st.mappingTable.Export()
primeStrs := make([]string, len(c.Setup.st.primes))
for i, p := range c.Setup.st.primes {
primeStrs[i] = p.String()
}
payload := mappingTablePayload{
Rows: rows,
ElectionPK: encodePK(c.Setup.st.electionPK),
ReturnCodePK: encodePK(c.Setup.st.returnCodePK),
Primes: primeStrs,
}
if _, err := c.sendConfidential(c.Setup.id, NameServer, MsgMappingTable, payload); err != nil {
return fmt.Errorf("deliver mapping table to server: %w", err)
}
c.logf(" setup: %d cards delivered to voters; mapping table delivered to server (all confidential)", cfg.NumVoters)
return nil
}
type mappingTablePayload struct {
Rows []returncodes.MappingRow `json:"rows"`
ElectionPK wirePublicKey `json:"election_pk"`
ReturnCodePK wirePublicKey `json:"return_code_pk"`
Primes []string `json:"primes"`
}
// handleVotingCard (voter) receives and stores its confidential card.
func (p *VoterClient) handleVotingCard(env *transport.Envelope) (*transport.Envelope, error) {
var card votingCard
if err := p.cer.openConfidential(p.id, env, &card); err != nil {
return nil, err
}
p.st.card = &card
return reply(p.id, env.From, MsgAck, env.Nonce, ackPayload{Party: p.id.Name, OK: true})
}
// handleMappingTable (server) receives and stores the confidential mapping table
// and public election parameters.
func (p *VotingServer) handleMappingTable(env *transport.Envelope) (*transport.Envelope, error) {
var payload mappingTablePayload
if err := p.cer.openConfidential(p.id, env, &payload); err != nil {
return nil, err
}
group := p.cer.Config.Group
p.st.mappingTable = returncodes.ImportMappingTable(payload.Rows)
pk, err := payload.ElectionPK.decode(group)
if err != nil {
return nil, err
}
rcPK, err := payload.ReturnCodePK.decode(group)
if err != nil {
return nil, err
}
p.st.electionPK = pk
p.st.returnCodePK = rcPK
p.st.primes = make([]*big.Int, len(payload.Primes))
for i, ps := range payload.Primes {
v, ok := new(big.Int).SetString(ps, 10)
if !ok {
return nil, fmt.Errorf("server: 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})
}
// confirmationKeyElement deterministically maps a voter id to a G_q element used
// as the confirmation key (as in the single-process version).
func confirmationKeyElement(vcID string, group *emath.GqGroup) emath.GqElement {
seed := hash.RecursiveHashToZq(group.Q(),
hash.HashableString{Value: "ConfirmationKey"},
hash.HashableString{Value: vcID},
)
plusOne := new(big.Int).Add(seed, big.NewInt(1))
elem, err := emath.GqElementFromSquareRoot(plusOne, group)
if err != nil {
// plusOne is in [1, q] by construction, so this cannot fail.
panic("confirmation key element: " + err.Error())
}
return elem
}
// assembleVotingCard collects return-code shares from all CCs for one voter,
// combines them into the long code values, registers the (value -> short code)
// entries in the mapping table, and returns the voter's card.
func (c *Ceremony) assembleVotingCard(voterIdx int) (*votingCard, error) {
cfg := c.Config
group := cfg.Group
vcID := fmt.Sprintf("vc-%04d", voterIdx)
primeStrs := make([]string, len(c.Setup.st.primes))
for i, p := range c.Setup.st.primes {
primeStrs[i] = p.String()
}
// Collect combined choice shares across all CCs.
choiceCombined := make([]emath.GqElement, cfg.NumOptions)
for i := range choiceCombined {
choiceCombined[i] = group.Identity()
}
confirmCombined := group.Identity()
for j := 0; j < cfg.NumCCs; j++ {
env, err := c.send(c.Setup.id, CCName(j), MsgLongCodeShareReq, longCodeShareReq{
VcID: vcID, ElectionID: cfg.ElectionID, Primes: primeStrs,
})
if err != nil {
return nil, fmt.Errorf("voter %d cc%d share: %w", voterIdx, j, err)
}
var resp longCodeShareResp
if err := transport.UnmarshalPayload(env.Payload, &resp); err != nil {
return nil, err
}
if len(resp.ChoiceShares) != cfg.NumOptions {
return nil, fmt.Errorf("voter %d cc%d: %d shares, want %d", voterIdx, j, len(resp.ChoiceShares), cfg.NumOptions)
}
for i, ss := range resp.ChoiceShares {
share, err := strToGq(ss, group) // validated group membership
if err != nil {
return nil, fmt.Errorf("voter %d cc%d share %d: %w", voterIdx, j, i, err)
}
choiceCombined[i] = choiceCombined[i].Multiply(share)
}
cShare, err := strToGq(resp.ConfirmShare, group)
if err != nil {
return nil, fmt.Errorf("voter %d cc%d confirm share: %w", voterIdx, j, err)
}
confirmCombined = confirmCombined.Multiply(cShare)
}
// Derive the short codes and register mapping-table entries.
choiceCodes := make([]string, cfg.NumOptions)
for i := 0; i < cfg.NumOptions; i++ {
lCC := returncodes.ComputeLCCValue(choiceCombined[i], vcID, cfg.ElectionID, c.Setup.st.primes[i])
short := fmt.Sprintf("CC-%02d", i)
choiceCodes[i] = short
c.Setup.st.mappingTable.Add(lCC, short)
}
lVCC := returncodes.ComputeLVCCValue(confirmCombined, vcID, cfg.ElectionID)
vcc := fmt.Sprintf("VCC-%04d", voterIdx)
c.Setup.st.mappingTable.Add(lVCC, vcc)
return &votingCard{
VoterID: fmt.Sprintf("voter-%04d", voterIdx),
VerificationCardID: vcID,
StartVotingKey: fmt.Sprintf("SVK-%04d", voterIdx),
ChoiceReturnCodes: choiceCodes,
VoteConfirmCode: vcc,
BallotCastingKey: fmt.Sprintf("BCK-%04d", voterIdx),
}, nil
}

47
pkg/party/codes_test.go Normal file
View file

@ -0,0 +1,47 @@
package party
import (
"testing"
)
// TestRunCardsConfidentialDistribution runs setup + card generation and checks
// that each voter received its card over the confidential channel, the cards
// carry the right number of return codes, and the server received the mapping
// table plus public election parameters.
func TestRunCardsConfidentialDistribution(t *testing.T) {
cfg := testConfig(t, 4, 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)
}
for v, voter := range c.Voters {
if voter.st.card == nil {
t.Fatalf("voter %d never received a card", v)
}
if voter.st.card.VerificationCardID == "" {
t.Fatalf("voter %d card missing vcID", v)
}
if len(voter.st.card.ChoiceReturnCodes) != cfg.NumOptions {
t.Fatalf("voter %d card has %d choice codes, want %d", v, len(voter.st.card.ChoiceReturnCodes), cfg.NumOptions)
}
}
if c.Server.st.mappingTable == nil {
t.Fatal("server never received the mapping table")
}
// Each voter contributes NumOptions choice entries + 1 confirm entry.
wantEntries := cfg.NumVoters * (cfg.NumOptions + 1)
if got := c.Server.st.mappingTable.Size(); got != wantEntries {
t.Fatalf("mapping table has %d entries, want %d", got, wantEntries)
}
if c.Server.st.electionPK.Elements == nil {
t.Fatal("server did not receive the election public key")
}
}

View file

@ -117,6 +117,8 @@ func (p *VoterClient) handle(env *transport.Envelope) (*transport.Envelope, erro
switch env.Type {
case MsgHello:
return handleHello(p.id, env)
case MsgVotingCard:
return p.handleVotingCard(env)
default:
return nil, fmt.Errorf("%s: unexpected message type %q", p.id.Name, env.Type)
}

View file

@ -19,6 +19,8 @@ func (p *ControlComponent) handleCCMsg(env *transport.Envelope) (*transport.Enve
switch env.Type {
case MsgGenCCKeys:
return p.handleGenCCKeys(env)
case MsgLongCodeShareReq:
return p.handleLongCodeShare(env)
default:
return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type)
}
@ -34,5 +36,10 @@ func (p *ElectoralBoard) handleEBMsg(env *transport.Envelope) (*transport.Envelo
}
func (p *VotingServer) handleServerMsg(env *transport.Envelope) (*transport.Envelope, error) {
return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type)
switch env.Type {
case MsgMappingTable:
return p.handleMappingTable(env)
default:
return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type)
}
}

View file

@ -75,3 +75,29 @@ func (mt *MappingTable) Lookup(lCCValue *big.Int) (string, error) {
func (mt *MappingTable) Size() int {
return len(mt.entries)
}
// MappingRow is a serializable mapping-table entry (for transport between the
// setup component and the voting server).
type MappingRow struct {
Key string `json:"key"`
Ciphertext []byte `json:"ciphertext"`
Nonce []byte `json:"nonce"`
}
// Export returns the table's entries in a serializable form.
func (mt *MappingTable) Export() []MappingRow {
rows := make([]MappingRow, 0, len(mt.entries))
for k, e := range mt.entries {
rows = append(rows, MappingRow{Key: k, Ciphertext: e.Ciphertext, Nonce: e.Nonce})
}
return rows
}
// ImportMappingTable rebuilds a mapping table from exported rows.
func ImportMappingTable(rows []MappingRow) *MappingTable {
mt := NewMappingTable()
for _, r := range rows {
mt.entries[r.Key] = MappingEntry{Ciphertext: r.Ciphertext, Nonce: r.Nonce}
}
return mt
}