Add party layer scaffolding: PKI bootstrap + signed handshake

pkg/party models each endpoint of the system as a separate object holding only
its own private state, wired together through the transport bus.

- ceremony.go: NewCeremony bootstraps the Ed25519 root CA, enrolls all parties
  (setup, 4 CCs, electoral board, voting server, verifier, N voters) with
  CA-signed identity certs, registers each in the directory, and wires its
  handler into the bus.
- parties.go: the six party types and a shared hello/ack handshake; Handshake()
  proves the full sign -> route -> verify -> reply -> verify path for every
  party before any election logic runs.
- state.go: per-party private state structs (nothing shared across parties).
- transcript.go: PublicTranscript, the append-only bulletin board a remote
  verifier will consume (no secrets).
- phases.go: phase handlers reject unknown message types cleanly (the transport
  boundary never panics on unexpected input) — filled in over the next commits.

Transport CA API simplified to own its serial counter (NewCA/Issue).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
saymrwulf 2026-07-06 15:07:31 +02:00
parent f7cbe4f634
commit 313db92321
8 changed files with 535 additions and 14 deletions

158
pkg/party/ceremony.go Normal file
View file

@ -0,0 +1,158 @@
// Package party implements the multi-party e-voting ceremony. Each party
// (setup component, four control components, electoral board, voting server,
// voter clients, verifier) is a distinct endpoint holding only its own private
// state; all data that crosses between parties travels as Ed25519-signed
// envelopes over the transport bus (pkg/transport), with the signature and key
// agreement performed in Rust (pkg/transportsec).
//
// This mirrors the Swiss Post trust structure without emulating its scale: the
// point is the trust boundaries and their transport security, not throughput.
package party
import (
"fmt"
"github.com/user/evote/pkg/protocol"
"github.com/user/evote/pkg/transport"
)
// Party name constants used as transport addresses and certificate CNs.
const (
NameSetup = "setup-component"
NameEB = "electoral-board"
NameServer = "voting-server"
NameVerifier = "verifier"
)
// CCName returns the transport name of control component j.
func CCName(j int) string { return fmt.Sprintf("control-component-%d", j) }
// VoterName returns the transport name of voter v.
func VoterName(v int) string { return fmt.Sprintf("voter-%04d", v) }
// Ceremony wires the parties, the PKI, and the bus together.
type Ceremony struct {
Config *protocol.Config
CA *transport.CA
Dir *transport.Directory
Bus *transport.Bus
Setup *SetupComponent
CCs []*ControlComponent
EB *ElectoralBoard
Server *VotingServer
Voters []*VoterClient
Verifier *VerifierParty
Transcript *PublicTranscript
logf func(string, ...any)
}
// NewCeremony bootstraps the PKI and every party identity, registering each in
// the CA-anchored directory and wiring its handler into the bus. It does not run
// the election — call RunSetup/RunVoting/RunTally/RunVerify (added incrementally).
func NewCeremony(cfg *protocol.Config, logf func(string, ...any)) (*Ceremony, error) {
if logf == nil {
logf = func(string, ...any) {}
}
c := &Ceremony{Config: cfg, logf: logf}
// 1. Root CA (Ed25519, Rust-signed).
ca, err := transport.NewCA("evote-root-ca")
if err != nil {
return nil, fmt.Errorf("CA: %w", err)
}
c.CA = ca
c.Dir = transport.NewDirectory(ca)
c.Bus = transport.NewBus(c.Dir)
c.Bus.Log = func(format string, args ...any) { c.logf(format, args...) }
// 2. Enroll every party: issue an Ed25519 identity cert and register it.
enroll := func(name string) (*transport.Identity, error) {
id, err := ca.Issue(name)
if err != nil {
return nil, err
}
if err := c.Dir.Register(id); err != nil {
return nil, err
}
return id, nil
}
setupID, err := enroll(NameSetup)
if err != nil {
return nil, err
}
c.Setup = &SetupComponent{id: setupID, cer: c}
c.CCs = make([]*ControlComponent, cfg.NumCCs)
for j := 0; j < cfg.NumCCs; j++ {
id, err := enroll(CCName(j))
if err != nil {
return nil, err
}
c.CCs[j] = &ControlComponent{index: j, id: id, cer: c}
}
ebID, err := enroll(NameEB)
if err != nil {
return nil, err
}
c.EB = &ElectoralBoard{id: ebID, cer: c}
serverID, err := enroll(NameServer)
if err != nil {
return nil, err
}
c.Server = &VotingServer{id: serverID, cer: c}
verID, err := enroll(NameVerifier)
if err != nil {
return nil, err
}
c.Verifier = &VerifierParty{id: verID, cer: c}
c.Voters = make([]*VoterClient, cfg.NumVoters)
for v := 0; v < cfg.NumVoters; v++ {
id, err := enroll(VoterName(v))
if err != nil {
return nil, err
}
c.Voters[v] = &VoterClient{index: v, id: id, cer: c}
}
// 3. Register message handlers on the bus.
c.Bus.Handle(NameSetup, c.Setup.handle)
for _, cc := range c.CCs {
c.Bus.Handle(cc.id.Name, cc.handle)
}
c.Bus.Handle(NameEB, c.EB.handle)
c.Bus.Handle(NameServer, c.Server.handle)
c.Bus.Handle(NameVerifier, c.Verifier.handle)
for _, v := range c.Voters {
c.Bus.Handle(v.id.Name, v.handle)
}
c.Transcript = &PublicTranscript{}
return c, nil
}
// send is a helper the parties use to sign and dispatch a typed message,
// returning the (verified) reply payload.
func (c *Ceremony) send(from *transport.Identity, to, msgType string, payload any) (*transport.Envelope, error) {
data, err := transport.MarshalPayload(payload)
if err != nil {
return nil, err
}
env := &transport.Envelope{From: from.Name, To: to, Type: msgType, Nonce: c.nextNonce(), Payload: data}
if err := env.Seal(from); err != nil {
return nil, err
}
return c.Bus.Send(env)
}
var globalNonce uint64
func (c *Ceremony) nextNonce() uint64 { globalNonce++; return globalNonce }

View file

@ -0,0 +1,60 @@
package party
import (
"math/big"
"testing"
emath "github.com/user/evote/pkg/math"
"github.com/user/evote/pkg/protocol"
)
const (
testP = "179688417486862032111147025351064878713905624387098436271724698527496946737299"
testQ = "89844208743431016055573512675532439356952812193549218135862349263748473368649"
testG = "4"
)
func testConfig(t *testing.T, numVoters, numOptions int) *protocol.Config {
t.Helper()
p, _ := new(big.Int).SetString(testP, 10)
q, _ := new(big.Int).SetString(testQ, 10)
g, _ := new(big.Int).SetString(testG, 10)
group, err := emath.NewGqGroup(p, q, g)
if err != nil {
t.Fatalf("test group: %v", err)
}
return &protocol.Config{
Group: group,
NumCCs: 4,
NumOptions: numOptions,
NumVoters: numVoters,
ElectionID: "party-unit-test",
SecurityLvl: 128,
}
}
// TestCeremonyBootstrapAndHandshake proves the full PKI + transport wiring:
// every party is enrolled with a CA-signed Ed25519 cert, registered in the
// directory, and reachable via a signed hello/ack exchange over the bus.
func TestCeremonyBootstrapAndHandshake(t *testing.T) {
cfg := testConfig(t, 3, 3)
c, err := NewCeremony(cfg, nil)
if err != nil {
t.Fatalf("NewCeremony: %v", err)
}
// Expected enrolled parties: setup, EB, server, verifier, 4 CCs, 3 voters.
wantParties := 4 + cfg.NumCCs + cfg.NumVoters
if got := len(c.CCs) + len(c.Voters) + 4; got != wantParties {
t.Fatalf("party count = %d, want %d", got, wantParties)
}
before := c.Bus.Count()
if err := c.Handshake(); err != nil {
t.Fatalf("handshake: %v", err)
}
// Each hello + ack is two verified messages; one exchange per non-setup party.
if c.Bus.Count() <= before {
t.Fatal("handshake carried no verified messages")
}
}

166
pkg/party/parties.go Normal file
View file

@ -0,0 +1,166 @@
package party
import (
"fmt"
"github.com/user/evote/pkg/transport"
)
// Message type constants exchanged over the bus.
const (
MsgHello = "hello" // enrollment handshake
MsgAck = "ack"
)
// reply is a small helper for a party to build a signed reply envelope.
func reply(from *transport.Identity, to, msgType string, nonce uint64, payload any) (*transport.Envelope, error) {
data, err := transport.MarshalPayload(payload)
if err != nil {
return nil, err
}
env := &transport.Envelope{From: from.Name, To: to, Type: msgType, Nonce: nonce, Payload: data}
if err := env.Seal(from); err != nil {
return nil, err
}
return env, nil
}
// ackPayload is returned by every party's hello handler.
type ackPayload struct {
Party string `json:"party"`
OK bool `json:"ok"`
}
// handleHello is the shared handshake handler: any party acknowledges a hello.
func handleHello(id *transport.Identity, env *transport.Envelope) (*transport.Envelope, error) {
if env.Type != MsgHello {
return nil, fmt.Errorf("%s: unexpected message type %q", id.Name, env.Type)
}
return reply(id, env.From, MsgAck, env.Nonce, ackPayload{Party: id.Name, OK: true})
}
// SetupComponent is the SDM analog: it generates election parameters and
// assembles voting cards and the return-codes mapping table.
type SetupComponent struct {
id *transport.Identity
cer *Ceremony
st setupState
}
func (p *SetupComponent) handle(env *transport.Envelope) (*transport.Envelope, error) {
switch env.Type {
case MsgHello:
return handleHello(p.id, env)
default:
return p.handleSetupMsg(env)
}
}
// ControlComponent is one of the split-trust CCs.
type ControlComponent struct {
index int
id *transport.Identity
cer *Ceremony
st ccState
}
func (p *ControlComponent) handle(env *transport.Envelope) (*transport.Envelope, error) {
switch env.Type {
case MsgHello:
return handleHello(p.id, env)
default:
return p.handleCCMsg(env)
}
}
// ElectoralBoard performs the final (offline) shuffle and decryption.
type ElectoralBoard struct {
id *transport.Identity
cer *Ceremony
st ebState
}
func (p *ElectoralBoard) handle(env *transport.Envelope) (*transport.Envelope, error) {
switch env.Type {
case MsgHello:
return handleHello(p.id, env)
default:
return p.handleEBMsg(env)
}
}
// VotingServer receives ballots and drives return-code extraction and tally.
type VotingServer struct {
id *transport.Identity
cer *Ceremony
st serverState
}
func (p *VotingServer) handle(env *transport.Envelope) (*transport.Envelope, error) {
switch env.Type {
case MsgHello:
return handleHello(p.id, env)
default:
return p.handleServerMsg(env)
}
}
// VoterClient encrypts a ballot and checks return codes.
type VoterClient struct {
index int
id *transport.Identity
cer *Ceremony
st voterState
}
func (p *VoterClient) handle(env *transport.Envelope) (*transport.Envelope, error) {
switch env.Type {
case MsgHello:
return handleHello(p.id, env)
default:
return nil, fmt.Errorf("%s: unexpected message type %q", p.id.Name, env.Type)
}
}
// VerifierParty independently re-checks the public transcript.
type VerifierParty struct {
id *transport.Identity
cer *Ceremony
}
func (p *VerifierParty) handle(env *transport.Envelope) (*transport.Envelope, error) {
switch env.Type {
case MsgHello:
return handleHello(p.id, env)
default:
return nil, fmt.Errorf("%s: unexpected message type %q", p.id.Name, env.Type)
}
}
// Handshake sends a signed hello to every enrolled party and verifies the acks.
// It proves the full sign → route → verify → reply → verify path works for all
// party types before any election logic runs.
func (c *Ceremony) Handshake() error {
targets := []string{NameSetup, NameEB, NameServer, NameVerifier}
for _, cc := range c.CCs {
targets = append(targets, cc.id.Name)
}
for _, v := range c.Voters {
targets = append(targets, v.id.Name)
}
for _, to := range targets {
env, err := c.send(c.Setup.id, to, MsgHello, nil)
if err != nil {
return fmt.Errorf("handshake to %s: %w", to, err)
}
var ack ackPayload
if err := transport.UnmarshalPayload(env.Payload, &ack); err != nil {
return err
}
if !ack.OK || ack.Party != to {
return fmt.Errorf("handshake to %s: bad ack %+v", to, ack)
}
}
c.logf(" [ceremony] handshake OK: %d parties enrolled and reachable", len(targets)+1)
return nil
}

28
pkg/party/phases.go Normal file
View file

@ -0,0 +1,28 @@
package party
import (
"fmt"
"github.com/user/evote/pkg/transport"
)
// Phase message handlers. These are filled in incrementally (setup, then
// voting, then tally). Until a phase is implemented its handler rejects unknown
// message types cleanly rather than panicking — the transport boundary must
// never crash on an unexpected message.
func (p *SetupComponent) handleSetupMsg(env *transport.Envelope) (*transport.Envelope, error) {
return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type)
}
func (p *ControlComponent) handleCCMsg(env *transport.Envelope) (*transport.Envelope, error) {
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)
}
func (p *VotingServer) handleServerMsg(env *transport.Envelope) (*transport.Envelope, error) {
return nil, fmt.Errorf("%s: unhandled message type %q", p.id.Name, env.Type)
}

77
pkg/party/state.go Normal file
View file

@ -0,0 +1,77 @@
package party
import (
"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/zkp"
)
// The state structs below hold each party's PRIVATE state. Nothing here may be
// read by another party except through an explicit signed message.
// setupState is the setup component's working store while assembling cards.
type setupState struct {
primes []*big.Int
votingCards []*votingCard
mappingTable *returncodes.MappingTable
electionPK elgamal.PublicKey
returnCodePK elgamal.PublicKey
}
// ccState is a control component's private key material and mix state.
type ccState struct {
keyPair elgamal.KeyPair
returnCodeSecret emath.ZqElement
schnorrProofs []zkp.SchnorrProof
// Tally working state.
shuffle mixnet.VerifiableShuffle
decProofs []zkp.DecryptionProof
shuffleIn *elgamal.CiphertextVector
shuffleOut *elgamal.CiphertextVector
}
// ebState is the electoral board's private key material.
type ebState struct {
passwords []string
keyPair elgamal.KeyPair
}
// serverState is the voting server / ballot box.
type serverState struct {
mappingTable *returncodes.MappingTable
ballotBox []encryptedBallot
electionPK elgamal.PublicKey
returnCodePK elgamal.PublicKey
primes []*big.Int
}
// voterState is a voter client's private card and ballot secrets.
type voterState struct {
card *votingCard
vcSK emath.ZqElement
selected []int
}
// votingCard is a voter's credential bundle (private to the voter, produced by
// the setup component and delivered over a confidential channel).
type votingCard struct {
VoterID string `json:"voter_id"`
VerificationCardID string `json:"vc_id"`
StartVotingKey string `json:"svk"`
ChoiceReturnCodes []string `json:"choice_return_codes"`
VoteConfirmCode string `json:"vote_confirm_code"`
BallotCastingKey string `json:"bck"`
}
// encryptedBallot is a ballot as stored in the ballot box.
type encryptedBallot struct {
VoterID string
VerificationCardID string
Ciphertext elgamal.Ciphertext
VcPK emath.GqElement
}

30
pkg/party/transcript.go Normal file
View file

@ -0,0 +1,30 @@
package party
import (
"github.com/user/evote/pkg/elgamal"
emath "github.com/user/evote/pkg/math"
"github.com/user/evote/pkg/mixnet"
"github.com/user/evote/pkg/zkp"
)
// PublicTranscript is the append-only bulletin board: everything a remote
// verifier needs to re-check the election, and nothing secret. It is populated
// by the parties as the ceremony proceeds and consumed by the verifier.
type PublicTranscript struct {
ElectionID string
// Setup artifacts.
CCElectionPKs []elgamal.PublicKey // per-CC election public keys
CCSchnorr [][]zkp.SchnorrProof // per-CC Schnorr proofs of key knowledge
EBPublicKey elgamal.PublicKey // electoral board public key
ElectionPK elgamal.PublicKey // combined election public key
Primes []string // decimal encodings of the encoding primes
// Tally artifacts.
MixInput *elgamal.CiphertextVector // padded ballot ciphertexts fed to shuffle 0
Shuffles []mixnet.VerifiableShuffle // one per CC + EB
PartialDecrypts []*elgamal.CiphertextVector // partial decryption after each CC
DecryptProofs [][]zkp.DecryptionProof // per-stage decryption proofs
FinalPlaintexts []*emath.GqVector // EB's decrypted messages
Result map[int]int // option index → count
}

View file

@ -64,16 +64,17 @@ func (id *Identity) SigningSeed() []byte { return id.edSeed }
func (id *Identity) ECDHPrivate() []byte { return id.xPriv }
// CA is a minimal root certificate authority that issues Ed25519 identity
// certificates. Its own signing key is Rust-backed.
// certificates. Its own signing key is Rust-backed. It owns a serial counter so
// certificate serials are deterministic (crypto/rand serials would make runs
// non-reproducible; a counter suffices for a single-CA PoC).
type CA struct {
signer rustSigner
Cert *x509.Certificate
CertDER []byte
serials serialCounter
}
// serialCounter deterministically supplies certificate serial numbers.
// (crypto/rand-based serials would make runs non-reproducible; a counter is
// sufficient for a single-CA PoC and keeps ceremonies deterministic.)
type serialCounter struct{ n int64 }
func (c *serialCounter) next() *big.Int { c.n++; return big.NewInt(c.n) }
@ -86,15 +87,16 @@ var (
)
// NewCA creates a self-signed Ed25519 root CA named name.
func NewCA(name string, serials *serialCounter) (*CA, error) {
func NewCA(name string) (*CA, error) {
seed, pub, err := transportsec.Ed25519GenerateKey()
if err != nil {
return nil, fmt.Errorf("CA keygen: %w", err)
}
signer := rustSigner{seed: seed, pub: ed25519.PublicKey(pub)}
ca := &CA{signer: signer}
tmpl := &x509.Certificate{
SerialNumber: serials.next(),
SerialNumber: ca.serials.next(),
Subject: pkix.Name{CommonName: name},
NotBefore: fixedNotBefore,
NotAfter: fixedNotAfter,
@ -112,11 +114,13 @@ func NewCA(name string, serials *serialCounter) (*CA, error) {
if err != nil {
return nil, fmt.Errorf("CA parse: %w", err)
}
return &CA{signer: signer, Cert: cert, CertDER: der}, nil
ca.Cert = cert
ca.CertDER = der
return ca, nil
}
// Issue creates an Identity for a party, with an Ed25519 cert signed by the CA.
func (ca *CA) Issue(name string, serials *serialCounter) (*Identity, error) {
func (ca *CA) Issue(name string) (*Identity, error) {
edSeed, edPub, err := transportsec.Ed25519GenerateKey()
if err != nil {
return nil, fmt.Errorf("%s ed keygen: %w", name, err)
@ -127,7 +131,7 @@ func (ca *CA) Issue(name string, serials *serialCounter) (*Identity, error) {
}
tmpl := &x509.Certificate{
SerialNumber: serials.next(),
SerialNumber: ca.serials.next(),
Subject: pkix.Name{CommonName: name},
NotBefore: fixedNotBefore,
NotAfter: fixedNotAfter,

View file

@ -7,15 +7,14 @@ import (
func newTestPKI(t *testing.T, names ...string) (*CA, *Directory, map[string]*Identity) {
t.Helper()
serials := &serialCounter{}
ca, err := NewCA("evote-root-ca", serials)
ca, err := NewCA("evote-root-ca")
if err != nil {
t.Fatalf("NewCA: %v", err)
}
dir := NewDirectory(ca)
ids := make(map[string]*Identity)
for _, n := range names {
id, err := ca.Issue(n, serials)
id, err := ca.Issue(n)
if err != nil {
t.Fatalf("issue %s: %v", n, err)
}
@ -33,9 +32,8 @@ func TestCertificateChainVerifies(t *testing.T) {
t.Fatalf("issued cert should verify: %v", err)
}
// A cert from a different CA must not verify against this one.
serials := &serialCounter{}
other, _ := NewCA("evil-ca", serials)
forged, _ := other.Issue("cc0", serials)
other, _ := NewCA("evil-ca")
forged, _ := other.Issue("cc0")
if err := ca.VerifyCertificate(forged.Cert); err == nil {
t.Fatal("cert from foreign CA must not verify")
}