vta-service 0.65.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
//! The **voter** role of the PCS engine (`vta/pcs/voter/*`, `vta/pcs/vote`) — operations layer.
//!
//! The third member-side role beside vetter and applicant: the VTA holds its principal's voter
//! key for each election, unblinds the ticket the community issues, and builds the cast — so a
//! client with no PCS implementation can vote, and never holds a key or a ticket
//! (VTI-VOT-020 – 033; conventions `voting/_shared/0.1/CONVENTIONS.md` in trust-tasks-tf).
//!
//! - **A key per election.** The first `voter/register` for a (context, community, election)
//!   allocates a fresh path under the context's base (VTI-VOT-023, VTI-KEY-030); the key is
//!   re-derived from it on every use and never stored.
//! - **No secret leaves.** The blinding state, the ticket and the one-time key that signs a cast
//!   are never returned (conventions §5.1). The cast document is returned whole and signed; the
//!   client sends it from its own connection (VTI-VOT-003, VTI-VOT-033).
//! - **Receipts are checked, not trusted.** A receipt counts only if the ballot box signed it
//!   and it names a cast this engine built (by its board leaf hash), and an inclusion proof is
//!   checked against a head the community kept (VTI-VOT-053).
//! - **Nothing pairs the member with the cast in the clear.** The documents signed as the member
//!   are dropped once the ticket is held; what names a cast (its board leaf hash, its receipt) is
//!   wrapped like the ticket. Once voting closes the ticket is discarded, and
//!   [`RECEIPT_RETENTION`] later everything else ([`sweep`]; CONVENTIONS §5 item 3).
//!
//! Records (`pcs_engine` keyspace, beside the vetter and applicant records):
//!
//! | Key | Value |
//! |---|---|
//! | `voter:<digest(context, community, election)>` | [`VoterRecord`] — public |
//! | `secret:voter:…` | the wrapped [`VoterState`]: blinding state, ticket |
//! | `secret:voter-casts:…` | the wrapped [`VoterCasts`]: the casts' leaf hashes, receipts |

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use trust_tasks_rs::TrustTask;
use trust_tasks_rs::specs::voting::{
    ballot::cast::v0_1 as cast, election::register::v0_1 as register,
};
use vti_voting::{
    board,
    election::{Election, ElectionId},
    rules::{self, RuleError},
    scheme::{Hvk, VotingParams},
    voter::{Ticket, TicketState, Voter},
};
use zeroize::Zeroizing;

use super::pcs::{
    Caller, PcsError, Result, allocate_member_path, load_secret_json, member_seed, proto,
    store_secret_json, write_lock,
};
use crate::error::AppError;
use crate::server::AppState;

const VOTER_STATE_TYPE: &str = "pcs-voter-state";
const VOTER_CASTS_TYPE: &str = "pcs-voter-casts";
const SUITE: &str = "ps-ddh-bls12381";
const CAST_TYPE: &str = "https://trusttasks.org/spec/voting/ballot/cast/0.1#request";
const CAST_ENCRYPTED_TYPE: &str =
    "https://trusttasks.org/spec/voting/ballot/cast-encrypted/0.1#request";
const RECEIPT_TYPE: &str = "https://trusttasks.org/spec/voting/ballot/cast/0.1#response";
const ENCRYPTED_RECEIPT_TYPE: &str =
    "https://trusttasks.org/spec/voting/ballot/cast-encrypted/0.1#response";
const HEAD_TYPE: &str = "https://trusttasks.org/spec/voting/board/head/0.1#response";

/// How long after voting closes a voter's casts and receipts are kept, so the member can still
/// check their cast against the board the result is counted from. Then the record goes.
pub const RECEIPT_RETENTION: chrono::TimeDelta = chrono::TimeDelta::days(30);

/// A voter engine's public record: one per (context, community, election).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoterRecord {
    pub context_id: String,
    pub community: String,
    pub election_id: String,
    /// The registered manifest's digest, multibase multihash.
    pub manifest_digest: String,
    pub voting_key: String,
    pub ballot_box: String,
    pub voting_closes: DateTime<Utc>,
    pub suite: String,
    /// The derivation path of this election's voter key, under the context's base.
    pub path: String,
    pub seed_id: u32,
    /// The voter's PCS identifier — public (the registrar sees it in the request).
    pub id: String,
    /// The ticket request as sent: answered again unchanged until the ticket is held, so the
    /// community's replayed answer can still be unblinded. Null once it is.
    pub request: Value,
    /// The `vtc/elections/tickets/issue` document signed as each member this request was asked
    /// for, kept so a repeat returns it unchanged and the community answers a resend with its
    /// first answer — and dropped once the ticket is held, so no record in the clear names the
    /// member beside an election they cast in.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub ticket_documents: std::collections::BTreeMap<String, Value>,
    pub ticket_held: bool,
    pub created_at: DateTime<Utc>,
}

/// The wrapped state: as secret as the key. Discarded once voting closes.
#[derive(Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct VoterState {
    /// The blinding state of the request in flight, multibase.
    #[serde(default)]
    blinding: Option<String>,
    /// The ticket, multibase.
    #[serde(default)]
    ticket: Option<String>,
}

/// Written by hand: a derived `Debug` would print the ticket.
impl std::fmt::Debug for VoterState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VoterState")
            .field("blinding", &self.blinding.as_ref().map(|_| "<redacted>"))
            .field("ticket", &self.ticket.as_ref().map(|_| "<redacted>"))
            .finish()
    }
}

/// What names this voter's casts, wrapped: kept apart from the ticket so it can outlive it by
/// [`RECEIPT_RETENTION`].
#[derive(Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct VoterCasts {
    /// The board leaf hash of every cast this engine built, multibase — how a receipt is
    /// recognised as this voter's without recomputing the tag.
    #[serde(default)]
    leaves: Vec<String>,
    /// Receipts as received, kept whole: each carries a bearer token for a private board.
    #[serde(default)]
    receipts: Vec<Value>,
}

/// Written by hand: a derived `Debug` would print the receipts' bearer tokens.
impl std::fmt::Debug for VoterCasts {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VoterCasts")
            .field("leaves", &self.leaves.len())
            .field("receipts", &self.receipts.len())
            .finish()
    }
}

fn voter_key(context_id: &str, community: &str, election_id: &str) -> String {
    let mut h = Sha256::new();
    for f in [context_id, community, election_id] {
        h.update((f.len() as u64).to_be_bytes());
        h.update(f.as_bytes());
    }
    format!("voter:{}", hex::encode(h.finalize()))
}

/// The key [`VoterCasts`] is wrapped under, beside the record at `voter_key`.
fn casts_key(voter_key: &str) -> String {
    format!("voter-casts:{}", voter_key.trim_start_matches("voter:"))
}

/// The wrapped [`VoterCasts`], empty before the first cast.
async fn load_casts(state: &AppState, key: &str, seed_id: u32) -> Result<VoterCasts> {
    match load_secret_json(state, &casts_key(key), VOTER_CASTS_TYPE, seed_id).await {
        Err(PcsError::App(AppError::NotFound(_))) => Ok(VoterCasts::default()),
        other => other,
    }
}

fn malformed(why: impl Into<String>) -> PcsError {
    PcsError::App(AppError::Validation(why.into()))
}

/// The community's published voting parameters, read and checked.
fn voting_params(community: &str, published: &Value) -> Result<(VotingParams, String)> {
    let suite = published
        .get("suite")
        .and_then(Value::as_str)
        .unwrap_or_default();
    if suite != SUITE {
        return Err(PcsError::UnsupportedSuite(suite.to_string()));
    }
    let key = published
        .get("votingKey")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();
    let hvk: Hvk = vti_vetting_pcs::scheme::dec(&key)
        .map_err(|e| PcsError::ParametersInvalid(e.to_string()))?;
    let params = VotingParams::new(community, hvk)
        .map_err(|e| PcsError::ParametersInvalid(e.to_string()))?;
    Ok((params, key))
}

fn rule(e: RuleError) -> PcsError {
    match e {
        RuleError::ManifestMismatch => PcsError::ManifestMismatch,
        RuleError::BallotInvalid(why) => PcsError::BallotInvalid(why),
        RuleError::UnsupportedSecrecy(s) => PcsError::UnsupportedSecrecy(s),
        other => malformed(other.to_string()),
    }
}

async fn record(state: &AppState, key: &str) -> Result<Option<VoterRecord>> {
    Ok(state.pcs_engine_ks.get(key.to_string()).await?)
}

async fn voter(
    state: &AppState,
    caller: &Caller<'_>,
    r: &VoterRecord,
    params: &VotingParams,
) -> Result<Voter> {
    let seed = member_seed(state, caller, &r.context_id, &r.path, r.seed_id).await?;
    Voter::from_seed(params, &seed)
        .map_err(|e| PcsError::App(AppError::Internal(format!("voter key: {e}"))))
}

fn election_of(r: &VoterRecord) -> Result<Election> {
    let digest = rules::digest_from_multibase(&r.manifest_digest)
        .ok_or_else(|| PcsError::App(AppError::Internal("stored manifest digest".into())))?;
    let id = ElectionId::new(&r.election_id).map_err(|e| malformed(e.to_string()))?;
    Election::new(&r.community, id, digest).map_err(|e| malformed(e.to_string()))
}

/// Signs the `vtc/elections/tickets/issue` request as the member (`vta/pcs/voter/register`
/// item 9). Built by the task handler once it has found the member's `authentication` key and
/// checked the caller may act as it — so a refused `member` allocates nothing here.
#[async_trait::async_trait]
pub trait TicketSigner: Send + Sync {
    /// The member DID the document is issued as.
    fn did(&self) -> &str;
    /// Attach the member's `authentication` proof to `doc`.
    async fn sign(&self, doc: &mut Value) -> Result<()>;
}

/// [`TicketSigner`] as a persona this VTA holds: the member's `authentication` key, through the
/// gated oracle as `ProtocolDefined` input the VTA built itself, exactly as the witnessed party
/// signs (`operations::witness`). It signs one document type with one payload, and nothing else.
pub struct PersonaTicketSigner<'a> {
    state: &'a AppState,
    auth: &'a crate::auth::AuthClaims,
    did: String,
    key_id: String,
    verification_method: String,
}

impl<'a> PersonaTicketSigner<'a> {
    /// The signer for `did`, when this VTA holds an `authentication` key of it the caller may
    /// act as.
    ///
    /// # Errors
    /// [`PcsError::MemberNotHeld`], the same whether the DID is unknown here or held for a
    /// context the caller may not act in.
    pub async fn for_member(
        state: &'a AppState,
        auth: &'a crate::auth::AuthClaims,
        did: &str,
    ) -> Result<Self> {
        use crate::operations::persona::{PersonaStores, Relationship, persona_key_for};
        let not_held = || PcsError::MemberNotHeld(did.to_string());
        let key = persona_key_for(
            PersonaStores::from_state(state),
            auth,
            did,
            Relationship::Authentication,
        )
        .await
        .map_err(|_| not_held())?
        .ok_or_else(not_held)?;
        crate::operations::keys::require_key_nameable(
            &state.keys_ks,
            &state.acl_ks,
            auth,
            &key.key_id,
        )
        .await
        .map_err(|_| not_held())?;
        Ok(Self {
            state,
            auth,
            did: did.to_string(),
            key_id: key.key_id,
            verification_method: key.verification_method,
        })
    }
}

#[async_trait::async_trait]
impl TicketSigner for PersonaTicketSigner<'_> {
    fn did(&self) -> &str {
        &self.did
    }

    async fn sign(&self, doc: &mut Value) -> Result<()> {
        use crate::operations::room_issuance::{SigningContext, VtaKeySigner};
        let ctx = SigningContext {
            keys_ks: &self.state.keys_ks,
            imported_ks: &self.state.imported_ks,
            internal_ks: &self.state.internal_ks,
            contexts_ks: &self.state.contexts_ks,
            acl_ks: &self.state.acl_ks,
            seed_store: &self.state.seed_store,
            audit: &self.state.audit_sink,
            auth: self.auth,
        };
        let signer = VtaKeySigner::new(ctx, &self.key_id, &self.verification_method);
        let proof = affinidi_data_integrity::DataIntegrityProof::sign(
            &*doc,
            &signer,
            affinidi_data_integrity::SignOptions::new()
                .with_proof_purpose("authentication")
                .with_created(Utc::now()),
        )
        .await
        .map_err(|e| AppError::Internal(format!("sign the ticket request as {}: {e}", self.did)))?;
        doc["proof"] = serde_json::to_value(proof)
            .map_err(|e| AppError::Internal(format!("encode the proof: {e}")))?;
        Ok(())
    }
}

/// The tickets/issue Type URI, bare: every community dispatches it in this form.
const TICKETS_ISSUE: &str = "https://trusttasks.org/spec/vtc/elections/tickets/issue/0.1";

/// The request to the community, signed as `signer` (item 9): a fresh id, the community as
/// recipient, expiring no later than voting closes, and exactly this answer's payload.
async fn ticket_document(
    signer: &dyn TicketSigner,
    community: &str,
    voting_closes: DateTime<Utc>,
    answer: &Value,
) -> Result<Value> {
    let now = Utc::now();
    let expires = (now + chrono::Duration::hours(1)).min(voting_closes);
    let stamp = |t: DateTime<Utc>| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
    let mut doc = json!({
        "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
        "type": TICKETS_ISSUE,
        "issuer": signer.did(),
        "recipient": community,
        "issuedAt": stamp(now),
        "expiresAt": stamp(expires.max(now)),
        "payload": {
            "electionId": answer["electionId"],
            "manifestDigest": answer["manifestDigest"],
            "request": answer["request"],
        },
    });
    signer.sign(&mut doc).await?;
    Ok(doc)
}

/// `vta/pcs/voter/read` items 4 – 6: one of the two election reads, signed as `member`, and
/// nothing else. The caller has already held `type_uri` to `list` or `show` and the payload to
/// that read's schema.
///
/// # Errors
/// [`PcsError::MemberNotHeld`] for a DID this VTA holds no authentication key of the caller may
/// act as.
pub async fn sign_read(
    state: &AppState,
    auth: &crate::auth::AuthClaims,
    member: &str,
    community: &str,
    type_uri: &str,
    payload: Value,
) -> Result<Value> {
    let signer = PersonaTicketSigner::for_member(state, auth, member).await?;
    let now = Utc::now();
    let stamp = |t: DateTime<Utc>| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
    let mut doc = json!({
        "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
        "type": type_uri,
        "issuer": member,
        "recipient": community,
        "issuedAt": stamp(now),
        "expiresAt": stamp(now + chrono::Duration::hours(1)),
        "payload": payload,
    });
    signer.sign(&mut doc).await?;
    Ok(doc)
}

/// `vta/pcs/voter/register`: the blinded ticket request under this election's voter key,
/// creating the key on first use — and, with a `member`, the request to the community signed as
/// that member.
pub async fn register(
    state: &AppState,
    caller: &Caller<'_>,
    context_id: &str,
    community: &str,
    published: &Value,
    manifest_value: &Value,
    member: Option<&dyn TicketSigner>,
) -> Result<Value> {
    let (params, voting_key) = voting_params(community, published)?;
    let manifest: register::Manifest = serde_json::from_value(manifest_value.clone())
        .map_err(|e| malformed(format!("manifest: {e}")))?;
    if manifest.community.as_str() != community {
        return Err(malformed("the manifest names another community"));
    }
    let digest = rules::manifest_digest(manifest_value).map_err(rule)?;
    let digest_text = rules::digest_multibase(&digest);
    let election_id = manifest.election_id.as_str().to_string();
    let key = voter_key(context_id, community, &election_id);

    let _guard = write_lock().await;
    if let Some(existing) = record(state, &key).await? {
        if existing.manifest_digest != digest_text || existing.voting_key != voting_key {
            return Err(PcsError::ElectionChanged);
        }
        if existing.ticket_held {
            return Err(PcsError::TicketHeld);
        }
        let mut answer = json!({
            "electionId": election_id,
            "manifestDigest": digest_text,
            "request": existing.request,
        });
        if let Some(signer) = member {
            let mut existing = existing;
            let doc = match existing.ticket_documents.get(signer.did()) {
                Some(kept) => kept.clone(),
                None => {
                    let doc =
                        ticket_document(signer, community, existing.voting_closes, &answer).await?;
                    existing
                        .ticket_documents
                        .insert(signer.did().to_string(), doc.clone());
                    state.pcs_engine_ks.insert(key, &existing).await?;
                    doc
                }
            };
            answer["ticketDocument"] = doc;
        }
        return Ok(answer);
    }

    let (path, seed_id) = allocate_member_path(state, context_id).await?;
    let seed = member_seed(state, caller, context_id, &path, seed_id).await?;
    let v = Voter::from_seed(&params, &seed)
        .map_err(|e| PcsError::App(AppError::Internal(format!("voter key: {e}"))))?;
    let election = Election::new(
        community,
        ElectionId::new(&election_id).map_err(|e| malformed(e.to_string()))?,
        digest,
    )
    .map_err(|e| malformed(e.to_string()))?;
    let mut rng = vti_voting::rand::rngs::OsRng;
    let (req, blinding) = v
        .ticket_request(&params, &election, &mut rng)
        .map_err(|e| PcsError::App(AppError::Internal(format!("ticket request: {e}"))))?;
    let blinding = predicate_credential_system::serialization::to_multibase(
        &blinding.to_bytes().map_err(|e| proto(e.into()))?,
    );
    let request = json!({
        "label": format!("voter/{election_id}"),
        "id": vti_voting::scheme::point_text(v.id()).map_err(proto)?,
        "request": serde_json::to_value(&req).map_err(|e| AppError::Internal(e.to_string()))?,
    });
    let rec = VoterRecord {
        context_id: context_id.to_string(),
        community: community.to_string(),
        election_id: election_id.clone(),
        manifest_digest: digest_text.clone(),
        voting_key,
        ballot_box: manifest.ballot_box.as_str().to_string(),
        voting_closes: manifest.voting_closes,
        suite: SUITE.to_string(),
        path,
        seed_id,
        id: request["id"].as_str().unwrap_or_default().to_string(),
        request: request.clone(),
        ticket_held: false,
        ticket_documents: Default::default(),
        created_at: Utc::now(),
    };
    store_secret_json(
        state,
        &key,
        VOTER_STATE_TYPE,
        seed_id,
        &VoterState {
            blinding: Some(blinding),
            ..VoterState::default()
        },
    )
    .await?;
    let mut answer =
        json!({ "electionId": election_id, "manifestDigest": digest_text, "request": request });
    let mut rec = rec;
    if let Some(signer) = member {
        let doc = ticket_document(signer, community, rec.voting_closes, &answer).await?;
        rec.ticket_documents
            .insert(signer.did().to_string(), doc.clone());
        answer["ticketDocument"] = doc;
    }
    state.pcs_engine_ks.insert(key, &rec).await?;
    Ok(answer)
}

/// `vta/pcs/voter/accept`: unblind the community's answer into the ticket and keep it wrapped.
pub async fn accept(
    state: &AppState,
    caller: &Caller<'_>,
    context_id: &str,
    community: &str,
    election_id: &str,
    published: &Value,
    answer: &Value,
) -> Result<Value> {
    let (params, voting_key) = voting_params(community, published)?;
    let label = answer["label"].as_str().unwrap_or_default();
    if answer["electionId"].as_str() != Some(election_id) || label != format!("voter/{election_id}")
    {
        return Err(malformed("the answer is for another election"));
    }
    let key = voter_key(context_id, community, election_id);
    let _guard = write_lock().await;
    let mut rec = record(state, &key).await?.ok_or(PcsError::NotFound)?;
    if rec.voting_key != voting_key {
        return Err(PcsError::ParametersInvalid(
            "another voting key than registered".into(),
        ));
    }
    let mut st: VoterState = load_secret_json(state, &key, VOTER_STATE_TYPE, rec.seed_id).await?;
    let Some(encoded) = st.blinding.clone() else {
        return Err(PcsError::NoRequestInFlight);
    };
    let bytes = Zeroizing::new(
        predicate_credential_system::serialization::from_multibase(&encoded)
            .map_err(|e| proto(e.into()))?,
    );
    let blinding = TicketState::from_bytes(&bytes).map_err(|e| proto(e.into()))?;
    let pre = vti_vetting_pcs::scheme::dec(answer["preCredential"].as_str().unwrap_or_default())
        .map_err(|e| PcsError::CredentialInvalid(e.to_string()))?;
    let election = election_of(&rec)?;
    let v = voter(state, caller, &rec, &params).await?;
    let ticket = v
        .accept_ticket(&params, &election, &pre, &blinding)
        .map_err(|e| PcsError::CredentialInvalid(e.to_string()))?;
    st.ticket = Some(
        ticket
            .to_text()
            .map_err(|e| PcsError::App(AppError::Internal(e.to_string())))?,
    );
    st.blinding = None;
    store_secret_json(state, &key, VOTER_STATE_TYPE, rec.seed_id, &st).await?;
    rec.ticket_held = true;
    rec.ticket_documents.clear();
    rec.request = Value::Null;
    state.pcs_engine_ks.insert(key, &rec).await?;
    Ok(json!({ "electionId": election_id, "ticketHeld": true }))
}

/// `vta/pcs/vote`: validate the ballot, build the cast, sign it as a key made for this cast
/// alone, and return the document for the client to send.
#[allow(clippy::too_many_arguments)]
pub async fn vote(
    state: &AppState,
    caller: &Caller<'_>,
    context_id: &str,
    community: &str,
    published: &Value,
    manifest_value: &Value,
    ballot_value: &Value,
    now: DateTime<Utc>,
) -> Result<Value> {
    let (params, voting_key) = voting_params(community, published)?;
    let manifest: register::Manifest = serde_json::from_value(manifest_value.clone())
        .map_err(|e| malformed(format!("manifest: {e}")))?;
    let ballot: cast::Ballot = serde_json::from_value(ballot_value.clone())
        .map_err(|e| malformed(format!("ballot: {e}")))?;
    let election_id = manifest.election_id.as_str().to_string();
    let key = voter_key(context_id, community, &election_id);

    let _guard = write_lock().await;
    let rec = record(state, &key).await?.ok_or(PcsError::NotFound)?;
    if rec.voting_key != voting_key {
        return Err(PcsError::ParametersInvalid(
            "another voting key than registered".into(),
        ));
    }
    let digest = rules::manifest_digest(manifest_value).map_err(rule)?;
    if rules::digest_multibase(&digest) != rec.manifest_digest {
        return Err(PcsError::ManifestMismatch);
    }
    rules::check_ballot(&manifest, &digest, &ballot).map_err(rule)?;
    if manifest.secrecy != register::SecrecyLevel::Open {
        return Err(malformed(
            "a sealed or tallied-encrypted election is cast with vta/pcs/vote-encrypted",
        ));
    }
    if now < manifest.voting_opens || now >= manifest.voting_closes {
        return Err(PcsError::NotOpen);
    }
    let st: VoterState = load_secret_json(state, &key, VOTER_STATE_TYPE, rec.seed_id).await?;
    let Some(ticket_text) = st.ticket else {
        return Err(PcsError::NotFound);
    };
    let ticket = Ticket::from_text(election_of(&rec)?, &ticket_text)
        .map_err(|e| PcsError::App(AppError::Internal(e.to_string())))?;
    let v = voter(state, caller, &rec, &params).await?;
    let mut rng = vti_voting::rand::rngs::OsRng;
    let cast = v
        .cast_wire(&params, &ticket, ballot_value, &mut rng)
        .map_err(|e| PcsError::App(AppError::Internal(format!("cast: {e}"))))?;

    let document = sign_as_one_time_key(&rec, CAST_TYPE, &cast, now).await?;
    remember_leaf(state, &rec, &key, "cast", &cast).await?;
    Ok(json!({ "castDocument": document, "tag": cast["tag"] }))
}

/// Record the board leaf hash of a cast this engine built, wrapped, so its receipt is
/// recognised.
async fn remember_leaf(
    state: &AppState,
    rec: &VoterRecord,
    key: &str,
    kind: &str,
    cast: &Value,
) -> Result<()> {
    let entry_jcs = serde_json_canonicalizer::to_vec(&json!({ "kind": kind, "cast": cast }))
        .map_err(|e| AppError::Internal(e.to_string()))?;
    let mut casts = load_casts(state, key, rec.seed_id).await?;
    casts
        .leaves
        .push(rules::digest_multibase(&board::leaf_hash(&entry_jcs)));
    store_secret_json(
        state,
        &casts_key(key),
        VOTER_CASTS_TYPE,
        rec.seed_id,
        &casts,
    )
    .await
}

/// `vta/pcs/vote-encrypted`: `vta/pcs/vote` for the sealed and tallied-encrypted levels — the
/// ballot sealed to the election key, or encrypted option by option with its proofs, and the
/// attestation over the encrypted form (CONVENTIONS §9.4 – 9.5). The plaintext ballot never
/// leaves.
#[allow(clippy::too_many_arguments)]
pub async fn vote_encrypted(
    state: &AppState,
    caller: &Caller<'_>,
    context_id: &str,
    community: &str,
    published: &Value,
    manifest_value: &Value,
    ceremony: &Value,
    ballot_value: &Value,
    now: DateTime<Utc>,
) -> Result<Value> {
    let (params, voting_key) = voting_params(community, published)?;
    let manifest: register::Manifest = serde_json::from_value(manifest_value.clone())
        .map_err(|e| malformed(format!("manifest: {e}")))?;
    let ballot: cast::Ballot = serde_json::from_value(ballot_value.clone())
        .map_err(|e| malformed(format!("ballot: {e}")))?;
    let election_id = manifest.election_id.as_str().to_string();
    let key = voter_key(context_id, community, &election_id);

    let _guard = write_lock().await;
    let rec = record(state, &key).await?.ok_or(PcsError::NotFound)?;
    if rec.voting_key != voting_key {
        return Err(PcsError::ParametersInvalid(
            "another voting key than registered".into(),
        ));
    }
    let Some(trustees) = manifest
        .trustees
        .as_ref()
        .filter(|_| manifest.secrecy != register::SecrecyLevel::Open)
    else {
        return Err(PcsError::WrongLevel);
    };
    let th = vti_voting::trustees::Threshold::new(
        u32::try_from(trustees.threshold).unwrap_or(0),
        u32::try_from(trustees.dids.len()).unwrap_or(0),
    )
    .map_err(|e| PcsError::ElectionKeyInvalid(e.to_string()))?;
    let digest = rules::manifest_digest(manifest_value).map_err(rule)?;
    if rules::digest_multibase(&digest) != rec.manifest_digest {
        return Err(PcsError::ManifestMismatch);
    }
    rules::check_ballot(&manifest, &digest, &ballot).map_err(rule)?;
    if now < manifest.voting_opens || now >= manifest.voting_closes {
        return Err(PcsError::NotOpen);
    }
    let st: VoterState = load_secret_json(state, &key, VOTER_STATE_TYPE, rec.seed_id).await?;
    let Some(ticket_text) = st.ticket else {
        return Err(PcsError::NotFound);
    };
    let election = election_of(&rec)?;
    // The key this VTA forms itself from the trustees' signed steps (CONVENTIONS §9.6): a key
    // handed to it could be one a community or a client holds.
    let requests = ceremony.as_array().ok_or_else(|| {
        PcsError::ElectionKeyInvalid("the ceremony is not a list of steps".into())
    })?;
    let resolver = state.trust_task_vm_resolver();
    let resolver = &resolver;
    let proven = vti_voting::steps::ProvenRequests::prove_requests(requests, |r| async move {
        vti_common::auth::verify_trust_task_proof_value(&r, resolver)
            .await
            .ok()
    })
    .await;
    let dids: Vec<&str> = trustees.dids.iter().map(|d| d.as_str()).collect();
    let c = vti_voting::steps::replay(
        requests,
        vti_voting::steps::Election {
            community,
            election_id: &election_id,
            trustees: &dids,
        },
        th,
        election.trustee_context(),
        &proven,
        now >= manifest.voting_opens,
    )
    .map_err(PcsError::ElectionKeyInvalid)?;
    let ek = c
        .key()
        .cloned()
        .ok_or_else(|| PcsError::ElectionKeyInvalid("the ceremony formed no key".into()))?;
    let ticket = Ticket::from_text(election.clone(), &ticket_text)
        .map_err(|e| PcsError::App(AppError::Internal(e.to_string())))?;
    let v = voter(state, caller, &rec, &params).await?;
    let mut rng = vti_voting::rand::rngs::OsRng;
    let tag = v
        .tag_for(&params, &ticket, &mut rng)
        .map_err(|e| PcsError::App(AppError::Internal(format!("tag: {e}"))))?;
    let form =
        vti_voting::voter::encrypted_form(&manifest, &election, &ek, ballot_value, &tag, &mut rng)
            .map_err(|e| PcsError::BallotInvalid(e.to_string()))?;
    let cast = v
        .cast_encrypted_wire(&params, &ticket, &form, &mut rng)
        .map_err(|e| PcsError::App(AppError::Internal(format!("cast: {e}"))))?;
    let document = sign_as_one_time_key(&rec, CAST_ENCRYPTED_TYPE, &cast, now).await?;
    remember_leaf(state, &rec, &key, "encryptedCast", &cast).await?;
    Ok(json!({ "castDocument": document, "tag": cast["tag"] }))
}

/// The `voting/ballot/cast` request, signed by a `did:key` made here and dropped here: no
/// record of it outlives this call (VTI-VOT-003).
async fn sign_as_one_time_key(
    rec: &VoterRecord,
    type_uri: &str,
    cast: &Value,
    now: DateTime<Utc>,
) -> Result<Value> {
    let mut seed = Zeroizing::new([0u8; 32]);
    vti_voting::rand::RngCore::fill_bytes(&mut vti_voting::rand::rngs::OsRng, &mut *seed);
    let public = ed25519_dalek::SigningKey::from_bytes(&seed)
        .verifying_key()
        .to_bytes();
    let did = format!(
        "did:key:{}",
        vta_sdk::did_key::ed25519_multibase_pubkey(&public)
    );
    let key = vta_sdk::trust_task_sign::HolderKey::from_did_key(
        &did,
        multibase::encode(multibase::Base::Base58Btc, *seed),
    )
    .map_err(|e| AppError::Internal(format!("one-time key: {e}")))?;
    let doc = json!({
        "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
        "type": type_uri,
        "issuer": did,
        "recipient": rec.ballot_box,
        "issuedAt": now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        "expiresAt": rec.voting_closes.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        "payload": { "community": rec.community, "electionId": rec.election_id, "cast": cast },
    });
    let mut typed: TrustTask<Value> =
        serde_json::from_value(doc).map_err(|e| AppError::Internal(e.to_string()))?;
    vta_sdk::trust_task_sign::sign_in_place_with(&mut typed, &key)
        .await
        .map_err(|e| AppError::Internal(format!("signing the cast: {e}")))?;
    Ok(serde_json::to_value(&typed).map_err(|e| AppError::Internal(e.to_string()))?)
}

/// The issuer a received document's proof verifies as, over the document as received.
async fn proven_issuer(state: &AppState, doc: &Value) -> std::result::Result<String, String> {
    let signer =
        vti_common::auth::verify_trust_task_proof_value(doc, &state.trust_task_vm_resolver())
            .await
            .map_err(|e| e.to_string())?;
    if doc["issuer"].as_str() != Some(signer.as_str()) {
        return Err("the proof is not the issuer's".into());
    }
    Ok(signer)
}

/// `vta/pcs/voter/receipt`: keep a receipt, and say whether a head the community kept includes
/// it.
#[allow(clippy::too_many_arguments)]
pub async fn receipt(
    state: &AppState,
    context_id: &str,
    community: &str,
    election_id: &str,
    receipt: &Value,
    checkpoint: Option<&Value>,
    inclusion: Option<&Value>,
) -> Result<Value> {
    let key = voter_key(context_id, community, election_id);
    let rec = record(state, &key).await?.ok_or(PcsError::NotFound)?;

    // The receipt: the ballot box's signed answer to a cast this engine built.
    if !matches!(
        receipt["type"].as_str(),
        Some(RECEIPT_TYPE | ENCRYPTED_RECEIPT_TYPE)
    ) {
        return Err(PcsError::ReceiptInvalid(
            "not a voting/ballot/cast or cast-encrypted response".into(),
        ));
    }
    let signer = proven_issuer(state, receipt)
        .await
        .map_err(PcsError::ReceiptInvalid)?;
    if signer != rec.ballot_box {
        return Err(PcsError::ReceiptInvalid(
            "not signed by the registered ballot box".into(),
        ));
    }
    let payload = &receipt["payload"];
    if payload["electionId"].as_str() != Some(election_id) {
        return Err(PcsError::ReceiptInvalid("for another election".into()));
    }
    let entry_hash = payload["entryHash"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    let leaf_index = payload["leafIndex"].as_u64().unwrap_or_default();

    {
        let _guard = write_lock().await;
        let mut casts = load_casts(state, &key, rec.seed_id).await?;
        if !casts.leaves.contains(&entry_hash) {
            return Err(PcsError::ReceiptInvalid(
                "names no cast this engine built".into(),
            ));
        }
        if !casts.receipts.contains(receipt) {
            casts.receipts.push(receipt.clone());
            store_secret_json(
                state,
                &casts_key(&key),
                VOTER_CASTS_TYPE,
                rec.seed_id,
                &casts,
            )
            .await?;
        }
    }

    let (Some(checkpoint), Some(inclusion)) = (checkpoint, inclusion) else {
        return Ok(json!({ "electionId": election_id, "status": "kept", "leafIndex": leaf_index }));
    };
    let evidence = |why: &str| PcsError::EvidenceInvalid(why.to_string());
    if checkpoint["type"].as_str() != Some(HEAD_TYPE) {
        return Err(evidence(
            "the checkpoint is not a voting/board/head response",
        ));
    }
    let head_signer = proven_issuer(state, checkpoint)
        .await
        .map_err(PcsError::EvidenceInvalid)?;
    if head_signer != rec.ballot_box {
        return Err(evidence(
            "the checkpoint is not signed by the registered ballot box",
        ));
    }
    let head = &checkpoint["payload"]["head"];
    if head["electionId"].as_str() != Some(election_id) {
        return Err(evidence("the checkpoint is for another election"));
    }
    let tree_size = head["treeSize"].as_u64().unwrap_or_default();
    if inclusion["leafIndex"].as_u64() != Some(leaf_index)
        || inclusion["treeSize"].as_u64() != Some(tree_size)
    {
        return Err(evidence("the inclusion proof is for another leaf or head"));
    }
    let root = rules::digest_from_multibase(head["rootHash"].as_str().unwrap_or_default())
        .ok_or_else(|| evidence("the head's root cannot be read"))?;
    let leaf = rules::digest_from_multibase(&entry_hash)
        .ok_or_else(|| evidence("the leaf hash cannot be read"))?;
    let path = inclusion["path"]
        .as_array()
        .map(|p| {
            p.iter()
                .map(|h| h.as_str().and_then(rules::digest_from_multibase))
                .collect::<Option<Vec<_>>>()
        })
        .unwrap_or(Some(Vec::new()))
        .ok_or_else(|| evidence("the audit path cannot be read"))?;
    let included = leaf_index < tree_size
        && board::verify_inclusion(leaf_index as usize, tree_size as usize, &leaf, &path, &root);
    Ok(json!({
        "electionId": election_id,
        "status": if included { "included" } else { "notIncluded" },
        "leafIndex": leaf_index,
    }))
}

/// Discard what a voter engine keeps once it is of no more use (CONVENTIONS §5 item 3): the
/// ticket and its blinding state once voting closes — no ballot box admits a cast after — and the
/// record, its casts and receipts [`RECEIPT_RETENTION`] later. The voter key goes with the
/// record: it was never stored, and nothing names its path any more. Returns how many records
/// were removed whole.
///
/// Deleting needs no seed, so the storage thread runs this. Nothing is audited: a row naming the
/// election would be the pairing VTI-VOT-100 forbids.
pub async fn sweep(ks: &vti_common::store::KeyspaceHandle, now: DateTime<Utc>) -> Result<usize> {
    let _guard = write_lock().await;
    let mut removed = 0;
    for (key, value) in ks.prefix_iter_raw("voter:").await? {
        let key = String::from_utf8_lossy(&key).into_owned();
        // A row this build cannot read is left for an operator, never guessed at.
        let Ok(rec) = serde_json::from_slice::<VoterRecord>(&value) else {
            continue;
        };
        if now < rec.voting_closes {
            continue;
        }
        vta_keys::imported::delete_secret(ks, &key).await?;
        if now >= rec.voting_closes + RECEIPT_RETENTION {
            vta_keys::imported::delete_secret(ks, &casts_key(&key)).await?;
            ks.remove(key).await?;
            removed += 1;
        }
    }
    Ok(removed)
}