Skip to main content

kute_protocol/
lib.rs

1//! Vocabulary exchange between two KUTE peers (development directive v0.2,
2//! R9). Before one side sends encoded data, both must hold the same
3//! vocabulary, identified by its content digest. The protocol lets them
4//! find out, transfer the vocabulary if needed, extend it together, and
5//! check that what was sent is what was decoded.
6//!
7//! [`Peer`] is the state machine: it takes a message and returns replies,
8//! and does no I/O. [`Session`] drives the initiating side over a
9//! [`Transport`]. [`Framed`] is a transport over any byte stream.
10//!
11//! There is no encryption and no authentication here. A peer treats
12//! everything it receives as untrusted: vocabularies are validated and
13//! their digests recomputed, sizes are bounded before allocation, and
14//! decoding is bounded before output is produced.
15
16use kute::{Engine, KuteError, Result, TokenPayload, TokenSequence, Tokenizer, UnknownPolicy, Version, Vocabulary};
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19use std::collections::BTreeMap;
20use std::io::{Read, Write};
21
22#[cfg(feature = "tls")]
23pub mod tls;
24
25/// Version 2 added the evolution rule to `CAPABILITIES` and to
26/// `SYMBOL_PROPOSE`, the `UNSUPPORTED_RULE` and `BUSY` errors, and the
27/// delivery contract for repeated message ids. A version 1 peer is refused
28/// at `HELLO`.
29pub const PROTOCOL_VERSION: u32 = 2;
30/// Most signatures one proposal may carry: as many as a vocabulary file.
31pub const MAX_PROPOSAL_SIGNATURES: usize = 16;
32/// The rule by which this build derives an evolved vocabulary. Two peers
33/// that name different rules would derive different children from the same
34/// proposal, so a proposal is only taken under this exact name.
35pub const EVOLUTION_RULE: &str = kute::bpe::sequence::EVOLVE_GENERATOR;
36/// Default and largest frame a peer will read.
37pub const DEFAULT_MAX_FRAME: u64 = 64 * 1024 * 1024;
38
39/// What identifies a vocabulary to the other side.
40#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
41pub struct VocabRef {
42    pub id: String,
43    pub version: String,
44    pub digest: String,
45    pub algorithm: String,
46    pub tokens: u64,
47}
48
49impl VocabRef {
50    pub fn of(vocabulary: &Vocabulary) -> Result<Self> {
51        Ok(Self {
52            id: vocabulary.id().to_string(),
53            version: vocabulary.version().to_string(),
54            digest: vocabulary.digest()?,
55            algorithm: vocabulary.manifest.algorithm.clone(),
56            tokens: vocabulary.len() as u64,
57        })
58    }
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "snake_case")]
63pub enum ErrorCode {
64    /// A message arrived before the handshake allowed it.
65    OutOfOrder,
66    UnsupportedProtocol,
67    UnsupportedAlgorithm,
68    /// Same id and version as a vocabulary the peer holds, different content.
69    VocabularyConflict,
70    UnknownVocabulary,
71    /// The vocabulary, message or proposal failed validation.
72    Invalid,
73    /// The peer's policy does not allow the request.
74    Refused,
75    TooLarge,
76    /// The proposal names an evolution rule this peer does not implement.
77    UnsupportedRule,
78    /// The peer's inbox is full; nothing was delivered. Send again later.
79    Busy,
80}
81
82#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
83#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
84pub enum Message {
85    Hello { protocol: u32, peer: String, software: String },
86    Capabilities {
87        algorithms: Vec<String>,
88        adapters: Vec<String>,
89        max_frame_bytes: u64,
90        accepts_vocabularies: bool,
91        accepts_proposals: bool,
92        /// Evolution rules this peer can apply to a proposal.
93        #[serde(default)]
94        evolution_rules: Vec<String>,
95        /// KVF versions this peer reads.
96        #[serde(default)]
97        kvf_versions: Vec<String>,
98    },
99    /// "I intend to use this vocabulary."
100    VocabAnnounce { vocabulary: VocabRef },
101    /// "I do not have it; send it."
102    VocabRequest { digest: String },
103    /// The vocabulary as a KVF document. Not in the directive's list; it is
104    /// the answer to `VOCAB_REQUEST`.
105    VocabData {
106        digest: String,
107        #[serde(with = "kute::b64")]
108        kvf: Vec<u8>,
109    },
110    /// "I hold a validated vocabulary with this digest."
111    VocabAccept { digest: String },
112    /// "Is this symbol sequence a token of that vocabulary?"
113    SymbolQuery { digest: String, symbols: Vec<String> },
114    /// Answer to `SYMBOL_QUERY`.
115    SymbolInfo { digest: String, token_id: Option<u32>, content_hash: String },
116    /// "Extend that vocabulary with these symbols and sequences, as this
117    /// version." Accepted with `VOCAB_ACCEPT` naming the new digest.
118    /// `rule` names the derivation the proposer used; a peer that does not
119    /// implement exactly that rule refuses before deriving anything.
120    /// `signatures` are of the digest of the vocabulary the proposal
121    /// derives: the proposer derived it first and vouches for the result.
122    /// A peer with a check attaches them to what it derives itself and
123    /// puts that to the check; without one that passes, nothing is held.
124    SymbolPropose {
125        digest: String,
126        additions: Vec<Vec<String>>,
127        version: String,
128        #[serde(default)]
129        rule: String,
130        #[serde(default, skip_serializing_if = "Vec::is_empty")]
131        signatures: Vec<kute::Signature>,
132    },
133    /// "Re-encode this sequence under another vocabulary you hold."
134    Translate {
135        id: u64,
136        #[serde(with = "kute::b64")]
137        container: Vec<u8>,
138        to_digest: String,
139    },
140    /// A `.kute` container.
141    EncodedMessage {
142        id: u64,
143        #[serde(with = "kute::b64")]
144        container: Vec<u8>,
145    },
146    /// Receipt for an encoded message: how much it decoded to, and the
147    /// SHA-256 of the decoded bytes.
148    Ack { id: u64, units: u64, sha256: String },
149    Error { code: ErrorCode, message: String },
150}
151
152fn refuse(code: ErrorCode, message: impl Into<String>) -> Vec<Message> {
153    vec![Message::Error { code, message: message.into() }]
154}
155
156/// What a peer is willing to do for the other side.
157///
158/// The default takes nothing new from the other side (no vocabularies, no
159/// proposals) and gives nothing away (no vocabulary files, no answers
160/// about symbols, no translation). It delivers messages encoded under a
161/// vocabulary this peer holds, and that is all. Everything else has to be
162/// switched on.
163#[derive(Clone, Debug, PartialEq, Eq)]
164pub struct Policy {
165    /// Send a held vocabulary's file to the other side when it asks.
166    pub give_vocabularies: bool,
167    /// Say whether a held vocabulary has a token for given symbols.
168    pub answer_queries: bool,
169    /// Re-encode the other side's sequences under another held vocabulary.
170    pub translate: bool,
171    /// The held vocabularies the other side may use at all, by digest;
172    /// `None` is every one held. One that is held but not listed is
173    /// answered as if it were not held. A vocabulary the other side adds
174    /// itself (when it may) joins the list.
175    pub vocabularies: Option<std::collections::BTreeSet<String>>,
176    /// Refuse a container that declares more tokens than this, before its
177    /// ids are decompressed. Four bytes of memory per token.
178    pub max_message_tokens: u64,
179    /// Take vocabularies it does not have from the other side.
180    pub accept_vocabularies: bool,
181    /// Extend a held vocabulary when the other side proposes it.
182    pub accept_proposals: bool,
183    pub max_frame_bytes: u64,
184    pub max_vocabulary_tokens: u64,
185    /// Refuse a message that would decode to more than this.
186    pub max_decoded_units: u64,
187    /// The most vocabularies this peer will hold, counting its own. The
188    /// other side cannot add one past this.
189    pub max_held_vocabularies: u64,
190    /// The most tokens over all held vocabularies, counting its own.
191    pub max_held_tokens: u64,
192    /// Delivered messages kept until `take_inbox`. When full, a message is
193    /// answered `BUSY` and not delivered.
194    pub max_inbox_messages: u64,
195    /// Bytes kept until `take_inbox`: for each message its decoded bytes,
196    /// its token ids at four bytes each, and its container.
197    pub max_inbox_bytes: u64,
198    /// How many of the latest message ids are remembered, so that a repeat
199    /// gets its first receipt again instead of a second delivery.
200    pub replay_window: u64,
201}
202
203impl Default for Policy {
204    fn default() -> Self {
205        Self {
206            give_vocabularies: false,
207            answer_queries: false,
208            translate: false,
209            vocabularies: None,
210            max_message_tokens: 16 * 1024 * 1024,
211            accept_vocabularies: false,
212            accept_proposals: false,
213            max_frame_bytes: DEFAULT_MAX_FRAME,
214            max_vocabulary_tokens: 1_000_000,
215            max_decoded_units: 256 * 1024 * 1024,
216            max_held_vocabularies: 64,
217            max_held_tokens: 4_000_000,
218            max_inbox_messages: 1024,
219            max_inbox_bytes: 256 * 1024 * 1024,
220            replay_window: 1024,
221        }
222    }
223}
224
225/// A message this peer received and decoded.
226#[derive(Clone, Debug, PartialEq)]
227pub struct Delivered {
228    pub id: u64,
229    pub sequence: TokenSequence,
230    /// The decoded bytes, through the vocabulary's adapter.
231    pub bytes: Vec<u8>,
232}
233
234struct Held {
235    vocabulary: Vocabulary,
236    tokenizer: Box<dyn Tokenizer>,
237}
238
239#[derive(Clone, Copy, PartialEq, Eq)]
240enum Stage {
241    New,
242    Greeted,
243    Ready,
244}
245
246/// A test a vocabulary must pass before it is taken from the other side.
247/// It is given the vocabulary after its digest has been recomputed and
248/// matched; an `Err` is the reason it is refused. The protocol does no
249/// cryptography of its own: a caller that wants signatures checks them here.
250pub type VocabularyCheck = Box<dyn Fn(&Vocabulary) -> std::result::Result<(), String> + Send>;
251
252/// One side of the protocol.
253pub struct Peer {
254    name: String,
255    engine: Engine,
256    policy: Policy,
257    check: Option<VocabularyCheck>,
258    held: BTreeMap<String, Held>,
259    stage: Stage,
260    wanted: Option<VocabRef>,
261    inbox: Vec<Delivered>,
262    inbox_bytes: u64,
263    /// The latest message ids: id, SHA-256 of the container, receipt sent.
264    seen: std::collections::VecDeque<(u64, String, Message)>,
265}
266
267pub fn sha256_hex(bytes: &[u8]) -> String {
268    kute::hex(&Sha256::digest(bytes))
269}
270
271impl Peer {
272    pub fn new(name: &str, engine: Engine, policy: Policy) -> Self {
273        Self {
274            name: name.to_string(),
275            engine,
276            policy,
277            check: None,
278            held: BTreeMap::new(),
279            stage: Stage::New,
280            wanted: None,
281            inbox: Vec::new(),
282            inbox_bytes: 0,
283            seen: Default::default(),
284        }
285    }
286
287    /// Take a vocabulary from the other side only if `check` passes it.
288    /// Vocabularies this side adds itself are not checked: their holder
289    /// chose them. While a check is set, a proposal is taken only if it
290    /// carries signatures and the vocabulary this side derives from it,
291    /// with those signatures attached, passes the check. A proposal with
292    /// none is refused before anything is derived.
293    pub fn require_vocabulary_check(&mut self, check: VocabularyCheck) {
294        self.check = Some(check);
295    }
296
297    /// Hold `vocabulary`. Returns its digest.
298    pub fn add_vocabulary(&mut self, vocabulary: Vocabulary) -> Result<String> {
299        vocabulary.validate()?;
300        let digest = vocabulary.compute_digest()?;
301        if let Some(other) = self.held.values().find(|h| h.vocabulary.id() == vocabulary.id() && h.vocabulary.version() == vocabulary.version()) {
302            if other.vocabulary.digest()? != digest {
303                return Err(KuteError::VocabularyMismatch(format!(
304                    "a different vocabulary is already held as {} {}",
305                    vocabulary.id(),
306                    vocabulary.version()
307                )));
308            }
309        }
310        let tokenizer = self.engine.tokenizer(vocabulary.clone())?;
311        let vocabulary = tokenizer.vocabulary().cloned().unwrap_or(vocabulary);
312        self.held.insert(digest.clone(), Held { vocabulary, tokenizer });
313        Ok(digest)
314    }
315
316    pub fn vocabulary(&self, digest: &str) -> Option<&Vocabulary> {
317        self.held.get(digest).map(|h| &h.vocabulary)
318    }
319
320    pub fn digests(&self) -> Vec<String> {
321        self.held.keys().cloned().collect()
322    }
323
324    /// How many delivered messages are waiting for `take_inbox`.
325    pub fn inbox_len(&self) -> usize {
326        self.inbox.len()
327    }
328
329    /// Messages received and decoded since the last call.
330    pub fn take_inbox(&mut self) -> Vec<Delivered> {
331        self.inbox_bytes = 0;
332        std::mem::take(&mut self.inbox)
333    }
334
335    /// Whether the other side may add a vocabulary of `tokens` tokens: the
336    /// refusal if it would pass what this peer is willing to hold in all.
337    fn over_budget(&self, tokens: u64) -> Option<Vec<Message>> {
338        if self.held.len() as u64 >= self.policy.max_held_vocabularies {
339            return Some(refuse(ErrorCode::TooLarge, format!("this peer already holds {} vocabularies, its limit", self.held.len())));
340        }
341        let held: u64 = self.held.values().map(|h| h.vocabulary.len() as u64).sum();
342        if held.saturating_add(tokens) > self.policy.max_held_tokens {
343            return Some(refuse(
344                ErrorCode::TooLarge,
345                format!("this peer holds {held} tokens and takes at most {} in all", self.policy.max_held_tokens),
346            ));
347        }
348        None
349    }
350
351    pub fn engine(&self) -> &Engine {
352        &self.engine
353    }
354
355    fn hold(&self, digest: &str) -> Result<&Held> {
356        self.held.get(digest).ok_or_else(|| KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")))
357    }
358
359    /// Whether the other side may use the vocabulary with this digest.
360    fn sees(&self, digest: &str) -> bool {
361        self.policy.vocabularies.as_ref().is_none_or(|listed| listed.contains(digest))
362    }
363
364    /// A held vocabulary, for the other side: one it may not use is
365    /// answered exactly as one that is not held.
366    fn usable(&self, digest: &str) -> Result<&Held> {
367        if !self.sees(digest) {
368            return Err(KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")));
369        }
370        self.hold(digest)
371    }
372
373    /// A vocabulary the other side added is one it may use.
374    fn show(&mut self, digest: &str) {
375        if let Some(listed) = &mut self.policy.vocabularies {
376            listed.insert(digest.to_string());
377        }
378    }
379
380    /// The most tokens a container from the other side may declare. Every
381    /// token decodes to at least one unit, so the unit limit bounds it too.
382    fn token_limit(&self) -> u64 {
383        self.policy.max_message_tokens.min(self.policy.max_decoded_units)
384    }
385
386    pub fn hello(&self) -> Message {
387        Message::Hello { protocol: PROTOCOL_VERSION, peer: self.name.clone(), software: format!("kute {}", kute::KUTE_VERSION) }
388    }
389
390    pub fn capabilities(&self) -> Message {
391        Message::Capabilities {
392            algorithms: self.engine.registry().algorithm_names(),
393            adapters: self.engine.registry().adapter_names(),
394            max_frame_bytes: self.policy.max_frame_bytes,
395            accepts_vocabularies: self.policy.accept_vocabularies,
396            accepts_proposals: self.policy.accept_proposals,
397            evolution_rules: vec![EVOLUTION_RULE.to_string()],
398            kvf_versions: vec![kute::KVF_VERSION.to_string()],
399        }
400    }
401
402    /// Encode `raw` under a held vocabulary and wrap it as a message.
403    /// Returns the message and the SHA-256 the receiver's `ACK` must carry.
404    pub fn encode_message(&self, id: u64, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<(Message, String)> {
405        let held = self.hold(digest)?;
406        let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), raw, policy)?;
407        let expected = sha256_hex(&self.engine.decode_raw(held.tokenizer.as_ref(), &sequence)?);
408        Ok((Message::EncodedMessage { id, container: sequence.to_bytes_compressed()? }, expected))
409    }
410
411    /// Apply an evolution step to a held vocabulary and hold the result.
412    pub fn evolve(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
413        let version = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
414        let child = kute::bpe::sequence::evolve(&self.hold(digest)?.vocabulary, additions, version)?;
415        self.add_vocabulary(child)
416    }
417
418    /// Re-encode a sequence under another held vocabulary. Symbols the
419    /// target lacks are escaped, so nothing is lost.
420    pub fn translate(&self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
421        let from = self.hold(&sequence.vocabulary_digest)?;
422        let to = self.hold(to_digest)?;
423        let units = kute::decoded_units(&from.vocabulary, sequence)?;
424        if units > self.policy.max_decoded_units {
425            return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units")));
426        }
427        // Symbols can be a kilobyte each, so their count is not their size.
428        // The translation goes back in one frame, so a frame bounds it.
429        let bytes = kute::decoded_bytes_at_least(&from.vocabulary, sequence)?;
430        if bytes > self.policy.max_frame_bytes {
431            return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; a frame holds {}", self.policy.max_frame_bytes)));
432        }
433        to.tokenizer.encode_open(&from.tokenizer.decode(sequence)?, UnknownPolicy::Escape)
434    }
435
436    /// Handle one message from the other side. Never fails: anything wrong
437    /// is answered with an `ERROR` message.
438    pub fn handle(&mut self, message: Message) -> Vec<Message> {
439        match (self.stage, &message) {
440            (Stage::New, Message::Hello { protocol, .. }) => {
441                if *protocol != PROTOCOL_VERSION {
442                    return refuse(ErrorCode::UnsupportedProtocol, format!("this peer speaks protocol {PROTOCOL_VERSION}, not {protocol}"));
443                }
444                self.stage = Stage::Greeted;
445                return vec![self.hello()];
446            }
447            (Stage::Greeted, Message::Capabilities { .. }) => {
448                self.stage = Stage::Ready;
449                return vec![self.capabilities()];
450            }
451            (Stage::Ready, Message::Hello { .. } | Message::Capabilities { .. }) | (Stage::New | Stage::Greeted, _) => {
452                return refuse(ErrorCode::OutOfOrder, "expected HELLO, then CAPABILITIES, before anything else");
453            }
454            (Stage::Ready, _) => {}
455        }
456        match self.respond(message) {
457            Ok(replies) => replies,
458            Err(e) => {
459                let code = match e {
460                    KuteError::LimitExceeded(_) => ErrorCode::TooLarge,
461                    KuteError::VocabularyMismatch(_) => ErrorCode::UnknownVocabulary,
462                    _ => ErrorCode::Invalid,
463                };
464                refuse(code, e.to_string())
465            }
466        }
467    }
468
469    fn respond(&mut self, message: Message) -> Result<Vec<Message>> {
470        match message {
471            Message::VocabAnnounce { vocabulary } => {
472                // A vocabulary that is held but not this peer's to use is
473                // treated from here on exactly as one that is not held: the
474                // same checks, the same request for its content. If the
475                // peer then sends it, it had the content already, and it
476                // becomes one it may use.
477                if self.held.contains_key(&vocabulary.digest) && self.sees(&vocabulary.digest) {
478                    return Ok(vec![Message::VocabAccept { digest: vocabulary.digest }]);
479                }
480                if self.held.values().any(|h| {
481                    h.vocabulary.id().as_str() == vocabulary.id && h.vocabulary.version().to_string() == vocabulary.version && h.vocabulary.integrity.as_ref().is_none_or(|i| i.digest != vocabulary.digest)
482                }) {
483                    // This does tell a peer that the id and version are
484                    // taken, whether or not it may use the holder. Two
485                    // vocabularies cannot share them, so the refusal cannot
486                    // be avoided, only worded the same in both cases.
487                    return Ok(refuse(
488                        ErrorCode::VocabularyConflict,
489                        format!("{} {} is held here with different content", vocabulary.id, vocabulary.version),
490                    ));
491                }
492                if !self.engine.registry().algorithm_names().contains(&vocabulary.algorithm) {
493                    return Ok(refuse(ErrorCode::UnsupportedAlgorithm, format!("algorithm {:?} is not available here", vocabulary.algorithm)));
494                }
495                if !self.policy.accept_vocabularies {
496                    return Ok(refuse(ErrorCode::Refused, "this peer does not take vocabularies from the other side"));
497                }
498                if vocabulary.tokens > self.policy.max_vocabulary_tokens {
499                    return Ok(refuse(ErrorCode::TooLarge, format!("vocabularies above {} tokens are not taken", self.policy.max_vocabulary_tokens)));
500                }
501                if let Some(refusal) = self.over_budget(vocabulary.tokens) {
502                    return Ok(refusal);
503                }
504                let digest = vocabulary.digest.clone();
505                self.wanted = Some(vocabulary);
506                Ok(vec![Message::VocabRequest { digest }])
507            }
508            Message::VocabRequest { digest } => {
509                if !self.policy.give_vocabularies {
510                    return Ok(refuse(ErrorCode::Refused, "this peer does not give out vocabularies"));
511                }
512                let kvf = kute::vocab::to_vec(&self.usable(&digest)?.vocabulary)?;
513                Ok(vec![Message::VocabData { digest, kvf }])
514            }
515            Message::VocabData { digest, kvf } => {
516                let Some(wanted) = self.wanted.take().filter(|w| w.digest == digest) else {
517                    return Ok(refuse(ErrorCode::OutOfOrder, "vocabulary data that was not requested"));
518                };
519                let vocabulary = kute::vocab::from_slice(&kvf)?;
520                // The digest is recomputed from content; the one in the file
521                // and the one announced are both only claims.
522                if vocabulary.compute_digest()? != digest || VocabRef::of(&vocabulary)? != wanted {
523                    return Ok(refuse(ErrorCode::Invalid, "the vocabulary sent is not the one announced"));
524                }
525                if vocabulary.len() as u64 > self.policy.max_vocabulary_tokens {
526                    return Ok(refuse(ErrorCode::TooLarge, "vocabulary exceeds the token limit"));
527                }
528                // Again, on what was sent and not on what was announced.
529                if let Some(refusal) = self.over_budget(vocabulary.len() as u64) {
530                    return Ok(refusal);
531                }
532                if let Some(check) = &self.check {
533                    if let Err(why) = check(&vocabulary) {
534                        return Ok(refuse(ErrorCode::Refused, format!("the vocabulary is not taken: {why}")));
535                    }
536                }
537                let report = self.engine.verify(&vocabulary)?;
538                if !report.ok() {
539                    return Ok(refuse(ErrorCode::Invalid, format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
540                }
541                let digest = self.add_vocabulary(vocabulary)?;
542                self.show(&digest);
543                Ok(vec![Message::VocabAccept { digest }])
544            }
545            Message::SymbolQuery { digest, symbols } => {
546                if !self.policy.answer_queries {
547                    return Ok(refuse(ErrorCode::Refused, "this peer does not answer questions about its vocabularies"));
548                }
549                let payload = TokenPayload::Symbols(symbols);
550                let token_id = self.usable(&digest)?.vocabulary.tokens.iter().find(|t| t.payload == payload).map(|t| t.id);
551                Ok(vec![Message::SymbolInfo { digest, token_id, content_hash: payload.content_hash() }])
552            }
553            Message::SymbolPropose { digest, additions, version, rule, signatures } => {
554                if !self.policy.accept_proposals {
555                    return Ok(refuse(ErrorCode::Refused, "this peer does not accept vocabulary proposals"));
556                }
557                if self.check.is_some() && signatures.is_empty() {
558                    return Ok(refuse(ErrorCode::Refused, "this peer takes only vocabularies that pass its check, and this proposal carries no signature of the vocabulary it derives"));
559                }
560                if signatures.len() > MAX_PROPOSAL_SIGNATURES || signatures.iter().any(|s| s.key_id.len() > 256 || s.algorithm.len() > 64 || s.signature.len() > 1024) {
561                    return Ok(refuse(ErrorCode::TooLarge, format!("a proposal carries at most {MAX_PROPOSAL_SIGNATURES} signatures, none with an overlong field")));
562                }
563                // Before anything is derived: under another rule the child
564                // would differ, and the two sides would part silently.
565                if rule != EVOLUTION_RULE {
566                    return Ok(refuse(
567                        ErrorCode::UnsupportedRule,
568                        format!("the proposal uses evolution rule {rule:?}; this peer implements {EVOLUTION_RULE:?}"),
569                    ));
570                }
571                // An addition of n symbols adds at most n symbols and n merges.
572                let most: u64 = additions.iter().map(|a| 2 * a.len() as u64).sum();
573                let parent = self.usable(&digest)?.vocabulary.len() as u64;
574                if parent.saturating_add(most) > self.policy.max_vocabulary_tokens {
575                    return Ok(refuse(ErrorCode::TooLarge, "the proposal would pass the vocabulary token limit"));
576                }
577                if let Some(refusal) = self.over_budget(parent.saturating_add(most)) {
578                    return Ok(refusal);
579                }
580                // The child is derived even when its id and version are
581                // already held: a repeat of the same proposal has to be
582                // accepted again, and only the derivation tells a repeat
583                // from a conflict. Its cost is bounded by the checks above.
584                let parsed = Version::parse(&version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
585                let mut child = kute::bpe::sequence::evolve(&self.hold(&digest)?.vocabulary, &additions, parsed)?;
586                if !signatures.is_empty() {
587                    // Of the vocabulary derived here, not of anything
588                    // received: a signature made for other content does
589                    // not hold for this digest.
590                    child.seal()?;
591                    child.integrity.as_mut().expect("sealed").signatures = signatures;
592                }
593                if let Some(check) = &self.check {
594                    if let Err(why) = check(&child) {
595                        return Ok(refuse(ErrorCode::Refused, format!("the proposed vocabulary is not taken: {why}")));
596                    }
597                }
598                let digest = match self.add_vocabulary(child) {
599                    Ok(digest) => digest,
600                    Err(KuteError::VocabularyMismatch(why)) => return Ok(refuse(ErrorCode::VocabularyConflict, why)),
601                    Err(e) => return Err(e),
602                };
603                self.show(&digest);
604                Ok(vec![Message::VocabAccept { digest }])
605            }
606            Message::Translate { id, container, to_digest } => {
607                if !self.policy.translate {
608                    return Ok(refuse(ErrorCode::Refused, "this peer does not translate for the other side"));
609                }
610                // A container that declares more tokens than the limit is
611                // refused before its ids are decompressed.
612                let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
613                self.usable(&sequence.vocabulary_digest)?;
614                self.usable(&to_digest)?;
615                let translated = self.translate(&sequence, &to_digest)?;
616                Ok(vec![Message::EncodedMessage { id, container: translated.to_bytes_compressed()? }])
617            }
618            Message::EncodedMessage { id, container } => {
619                // A repeat of a delivered message gets its receipt again and
620                // is not delivered twice; the same id on other content is an
621                // error. Ids older than the window are not remembered.
622                let fingerprint = sha256_hex(&container);
623                if let Some((_, first, receipt)) = self.seen.iter().find(|(seen, _, _)| *seen == id) {
624                    return Ok(if *first == fingerprint {
625                        vec![receipt.clone()]
626                    } else {
627                        refuse(ErrorCode::Invalid, format!("message id {id} was already used for different content"))
628                    });
629                }
630                if self.inbox.len() as u64 >= self.policy.max_inbox_messages {
631                    return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} messages, its limit", self.inbox.len())));
632                }
633                let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
634                let held = self.usable(&sequence.vocabulary_digest)?;
635                let units = kute::decoded_units(&held.vocabulary, &sequence)?;
636                let bytes = self.engine.decode_raw_within(held.tokenizer.as_ref(), &sequence, self.policy.max_decoded_units, self.policy.max_inbox_bytes)?;
637                // What the inbox keeps for this message: the decoded bytes
638                // and the sequence (ids, and the escapes the container holds).
639                let kept = (bytes.len() as u64).saturating_add(4 * sequence.ids.len() as u64).saturating_add(container.len() as u64);
640                if self.inbox_bytes.saturating_add(kept) > self.policy.max_inbox_bytes {
641                    return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} bytes and takes at most {}", self.inbox_bytes, self.policy.max_inbox_bytes)));
642                }
643                let receipt = Message::Ack { id, units, sha256: sha256_hex(&bytes) };
644                self.inbox_bytes += kept;
645                self.inbox.push(Delivered { id, sequence, bytes });
646                self.seen.push_back((id, fingerprint, receipt.clone()));
647                while self.seen.len() as u64 > self.policy.replay_window {
648                    self.seen.pop_front();
649                }
650                Ok(vec![receipt])
651            }
652            Message::VocabAccept { .. } | Message::SymbolInfo { .. } | Message::Ack { .. } | Message::Error { .. } => {
653                Ok(refuse(ErrorCode::OutOfOrder, "a reply arrived where a request was expected"))
654            }
655            Message::Hello { .. } | Message::Capabilities { .. } => Ok(refuse(ErrorCode::OutOfOrder, "the handshake is already complete")),
656        }
657    }
658}
659
660/// Something that carries messages to the other peer and back.
661pub trait Transport {
662    fn send(&mut self, message: &Message) -> Result<()>;
663    /// The next message, or `None` when the other side has closed.
664    fn recv(&mut self) -> Result<Option<Message>>;
665}
666
667/// Messages over a byte stream: a four-byte little-endian length, then that
668/// many bytes of JSON.
669pub struct Framed<S: Read + Write> {
670    stream: S,
671    max_frame: u64,
672}
673
674impl<S: Read + Write> Framed<S> {
675    pub fn new(stream: S, max_frame: u64) -> Self {
676        Self { stream, max_frame: max_frame.min(DEFAULT_MAX_FRAME) }
677    }
678}
679
680impl<S: Read + Write> Transport for Framed<S> {
681    fn send(&mut self, message: &Message) -> Result<()> {
682        let body = serde_json::to_vec(message)?;
683        if body.len() as u64 > self.max_frame {
684            return Err(KuteError::LimitExceeded(format!("message of {} bytes exceeds the frame limit of {}", body.len(), self.max_frame)));
685        }
686        self.stream.write_all(&(body.len() as u32).to_le_bytes())?;
687        self.stream.write_all(&body)?;
688        self.stream.flush()?;
689        Ok(())
690    }
691
692    fn recv(&mut self) -> Result<Option<Message>> {
693        let mut length = [0u8; 4];
694        let mut got = 0;
695        while got < 4 {
696            match self.stream.read(&mut length[got..]) {
697                Ok(0) if got == 0 => return Ok(None),
698                Ok(0) => return Err(KuteError::InvalidInput("the stream ended inside a frame header".into())),
699                Ok(n) => got += n,
700                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
701                Err(e) => return Err(e.into()),
702            }
703        }
704        let length = u32::from_le_bytes(length) as u64;
705        if length > self.max_frame {
706            return Err(KuteError::LimitExceeded(format!("incoming frame of {length} bytes exceeds the limit of {}", self.max_frame)));
707        }
708        // Read through `take` so a forged length cannot make us allocate
709        // more than actually arrives.
710        let mut body = Vec::new();
711        (&mut self.stream).take(length).read_to_end(&mut body)?;
712        if body.len() as u64 != length {
713            return Err(KuteError::InvalidInput("the stream ended inside a frame".into()));
714        }
715        serde_json::from_slice(&body).map(Some).map_err(|e| KuteError::InvalidInput(format!("not a protocol message: {e}")))
716    }
717}
718
719/// The other side's answer to `CAPABILITIES`.
720#[derive(Clone, Debug, PartialEq, Eq)]
721pub struct Remote {
722    pub peer: String,
723    pub software: String,
724    pub algorithms: Vec<String>,
725    pub accepts_vocabularies: bool,
726    pub accepts_proposals: bool,
727    pub evolution_rules: Vec<String>,
728}
729
730fn peer_error(code: ErrorCode, message: String) -> KuteError {
731    KuteError::Backend(format!("the peer answered {code:?}: {message}"))
732}
733
734/// A peer together with its connection.
735pub struct Session<T: Transport> {
736    pub peer: Peer,
737    transport: T,
738    next_id: u64,
739    remote: Option<Remote>,
740}
741
742impl<T: Transport> Session<T> {
743    pub fn new(peer: Peer, transport: T) -> Self {
744        Self { peer, transport, next_id: 1, remote: None }
745    }
746
747    fn ask(&mut self, message: &Message) -> Result<Message> {
748        self.transport.send(message)?;
749        match self.transport.recv()? {
750            Some(Message::Error { code, message }) => Err(peer_error(code, message)),
751            Some(reply) => Ok(reply),
752            None => Err(KuteError::Backend("the peer closed the connection".into())),
753        }
754    }
755
756    fn unexpected<R>(reply: Message) -> Result<R> {
757        Err(KuteError::Backend(format!("unexpected reply from the peer: {reply:?}")))
758    }
759
760    /// Initiator: handshake and capability exchange.
761    pub fn connect(&mut self) -> Result<Remote> {
762        let (peer, software) = match self.ask(&self.peer.hello())? {
763            Message::Hello { protocol, peer, software } if protocol == PROTOCOL_VERSION => (peer, software),
764            other => return Self::unexpected(other),
765        };
766        match self.ask(&self.peer.capabilities())? {
767            Message::Capabilities { algorithms, accepts_vocabularies, accepts_proposals, evolution_rules, .. } => {
768                let remote = Remote { peer, software, algorithms, accepts_vocabularies, accepts_proposals, evolution_rules };
769                self.remote = Some(remote.clone());
770                Ok(remote)
771            }
772            other => Self::unexpected(other),
773        }
774    }
775
776    /// Initiator: make sure the other side holds the vocabulary `digest`,
777    /// sending it if asked. Returns true if it had to be transferred.
778    pub fn share(&mut self, digest: &str) -> Result<bool> {
779        let vocabulary = VocabRef::of(&self.peer.hold(digest)?.vocabulary)?;
780        match self.ask(&Message::VocabAnnounce { vocabulary })? {
781            Message::VocabAccept { digest: d } if d == digest => Ok(false),
782            Message::VocabRequest { digest: d } if d == digest => {
783                let kvf = kute::vocab::to_vec(&self.peer.hold(digest)?.vocabulary)?;
784                match self.ask(&Message::VocabData { digest: digest.to_string(), kvf })? {
785                    Message::VocabAccept { digest: d } if d == digest => Ok(true),
786                    other => Self::unexpected(other),
787                }
788            }
789            other => Self::unexpected(other),
790        }
791    }
792
793    /// Initiator: encode `raw`, send it, and check the receipt. Returns the
794    /// number of units the other side decoded. Fails if the other side
795    /// decoded anything other than what this side's decoder gives.
796    pub fn send(&mut self, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<u64> {
797        let id = self.next_id;
798        self.next_id += 1;
799        let (message, expected) = self.peer.encode_message(id, digest, raw, policy)?;
800        match self.ask(&message)? {
801            Message::Ack { id: acked, units, sha256 } if acked == id => {
802                if sha256 != expected {
803                    return Err(KuteError::Integrity("the peer decoded the message to different content".into()));
804                }
805                Ok(units)
806            }
807            other => Self::unexpected(other),
808        }
809    }
810
811    /// Initiator: extend a shared vocabulary on both sides. Each side
812    /// applies the step itself; the digests must agree. Returns the new
813    /// digest. Nothing changes locally if the other side refuses.
814    pub fn propose(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
815        self.propose_signed(digest, additions, version, &|_| Ok(()))
816    }
817
818    /// [`Session::propose`], vouching for the result. `sign` is given the
819    /// vocabulary this side derived, sealed, and adds its signatures to
820    /// it; they travel with the proposal, and the vocabulary held here
821    /// afterwards carries them. The protocol makes no signature itself.
822    pub fn propose_signed(&mut self, digest: &str, additions: &[Vec<String>], version: &str, sign: &dyn Fn(&mut Vocabulary) -> Result<()>) -> Result<String> {
823        if let Some(remote) = &self.remote {
824            if !remote.evolution_rules.iter().any(|r| r == EVOLUTION_RULE) {
825                return Err(KuteError::Unsupported(format!(
826                    "the peer implements evolution rules {:?}, not {EVOLUTION_RULE:?}; a proposal would derive different vocabularies on the two sides",
827                    remote.evolution_rules
828                )));
829            }
830        }
831        let parsed = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
832        let mut child = kute::bpe::sequence::evolve(&self.peer.hold(digest)?.vocabulary, additions, parsed)?;
833        child.seal()?;
834        let expected = child.digest()?;
835        sign(&mut child)?;
836        if child.compute_digest()? != expected {
837            return Err(KuteError::Integrity("signing changed the vocabulary".into()));
838        }
839        let propose = Message::SymbolPropose {
840            digest: digest.to_string(),
841            additions: additions.to_vec(),
842            version: version.to_string(),
843            rule: EVOLUTION_RULE.to_string(),
844            signatures: child.integrity.as_ref().map(|i| i.signatures.clone()).unwrap_or_default(),
845        };
846        match self.ask(&propose)? {
847            Message::VocabAccept { digest: theirs } if theirs == expected => self.peer.add_vocabulary(child),
848            Message::VocabAccept { digest: theirs } => {
849                Err(KuteError::Integrity(format!("the peer derived {theirs}, this side derived {expected}")))
850            }
851            other => Self::unexpected(other),
852        }
853    }
854
855    /// Initiator: ask whether a symbol sequence is a token over there.
856    pub fn query(&mut self, digest: &str, symbols: &[String]) -> Result<Option<u32>> {
857        match self.ask(&Message::SymbolQuery { digest: digest.to_string(), symbols: symbols.to_vec() })? {
858            Message::SymbolInfo { token_id, .. } => Ok(token_id),
859            other => Self::unexpected(other),
860        }
861    }
862
863    /// Initiator: have the other side re-encode a sequence under another
864    /// vocabulary it holds.
865    pub fn translate(&mut self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
866        let id = self.next_id;
867        self.next_id += 1;
868        let ask = Message::Translate { id, container: sequence.to_bytes_compressed()?, to_digest: to_digest.to_string() };
869        match self.ask(&ask)? {
870            Message::EncodedMessage { id: got, container } if got == id => {
871                let translated = TokenSequence::from_bytes(&container)?;
872                if translated.vocabulary_digest != to_digest {
873                    return Err(KuteError::Integrity("the peer translated to a different vocabulary".into()));
874                }
875                Ok(translated)
876            }
877            other => Self::unexpected(other),
878        }
879    }
880
881    /// Responder: answer messages until the other side closes. Returns the
882    /// number of messages handled.
883    pub fn serve(&mut self) -> Result<u64> {
884        self.serve_observed(&mut |_, _| {})
885    }
886
887    /// As `serve`, calling `after` once each message has been handled and
888    /// answered, with the peer as it then is and the count so far. It is
889    /// for showing progress; it cannot change what is answered.
890    pub fn serve_observed(&mut self, after: &mut dyn FnMut(&Peer, u64)) -> Result<u64> {
891        let mut handled = 0;
892        while let Some(message) = self.transport.recv()? {
893            for reply in self.peer.handle(message) {
894                self.transport.send(&reply)?;
895            }
896            handled += 1;
897            after(&self.peer, handled);
898        }
899        Ok(handled)
900    }
901}