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    /// Messages received and decoded since the last call.
325    pub fn take_inbox(&mut self) -> Vec<Delivered> {
326        self.inbox_bytes = 0;
327        std::mem::take(&mut self.inbox)
328    }
329
330    /// Whether the other side may add a vocabulary of `tokens` tokens: the
331    /// refusal if it would pass what this peer is willing to hold in all.
332    fn over_budget(&self, tokens: u64) -> Option<Vec<Message>> {
333        if self.held.len() as u64 >= self.policy.max_held_vocabularies {
334            return Some(refuse(ErrorCode::TooLarge, format!("this peer already holds {} vocabularies, its limit", self.held.len())));
335        }
336        let held: u64 = self.held.values().map(|h| h.vocabulary.len() as u64).sum();
337        if held.saturating_add(tokens) > self.policy.max_held_tokens {
338            return Some(refuse(
339                ErrorCode::TooLarge,
340                format!("this peer holds {held} tokens and takes at most {} in all", self.policy.max_held_tokens),
341            ));
342        }
343        None
344    }
345
346    pub fn engine(&self) -> &Engine {
347        &self.engine
348    }
349
350    fn hold(&self, digest: &str) -> Result<&Held> {
351        self.held.get(digest).ok_or_else(|| KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")))
352    }
353
354    /// Whether the other side may use the vocabulary with this digest.
355    fn sees(&self, digest: &str) -> bool {
356        self.policy.vocabularies.as_ref().is_none_or(|listed| listed.contains(digest))
357    }
358
359    /// A held vocabulary, for the other side: one it may not use is
360    /// answered exactly as one that is not held.
361    fn usable(&self, digest: &str) -> Result<&Held> {
362        if !self.sees(digest) {
363            return Err(KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")));
364        }
365        self.hold(digest)
366    }
367
368    /// A vocabulary the other side added is one it may use.
369    fn show(&mut self, digest: &str) {
370        if let Some(listed) = &mut self.policy.vocabularies {
371            listed.insert(digest.to_string());
372        }
373    }
374
375    /// The most tokens a container from the other side may declare. Every
376    /// token decodes to at least one unit, so the unit limit bounds it too.
377    fn token_limit(&self) -> u64 {
378        self.policy.max_message_tokens.min(self.policy.max_decoded_units)
379    }
380
381    pub fn hello(&self) -> Message {
382        Message::Hello { protocol: PROTOCOL_VERSION, peer: self.name.clone(), software: format!("kute {}", kute::KUTE_VERSION) }
383    }
384
385    pub fn capabilities(&self) -> Message {
386        Message::Capabilities {
387            algorithms: self.engine.registry().algorithm_names(),
388            adapters: self.engine.registry().adapter_names(),
389            max_frame_bytes: self.policy.max_frame_bytes,
390            accepts_vocabularies: self.policy.accept_vocabularies,
391            accepts_proposals: self.policy.accept_proposals,
392            evolution_rules: vec![EVOLUTION_RULE.to_string()],
393            kvf_versions: vec![kute::KVF_VERSION.to_string()],
394        }
395    }
396
397    /// Encode `raw` under a held vocabulary and wrap it as a message.
398    /// Returns the message and the SHA-256 the receiver's `ACK` must carry.
399    pub fn encode_message(&self, id: u64, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<(Message, String)> {
400        let held = self.hold(digest)?;
401        let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), raw, policy)?;
402        let expected = sha256_hex(&self.engine.decode_raw(held.tokenizer.as_ref(), &sequence)?);
403        Ok((Message::EncodedMessage { id, container: sequence.to_bytes_compressed()? }, expected))
404    }
405
406    /// Apply an evolution step to a held vocabulary and hold the result.
407    pub fn evolve(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
408        let version = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
409        let child = kute::bpe::sequence::evolve(&self.hold(digest)?.vocabulary, additions, version)?;
410        self.add_vocabulary(child)
411    }
412
413    /// Re-encode a sequence under another held vocabulary. Symbols the
414    /// target lacks are escaped, so nothing is lost.
415    pub fn translate(&self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
416        let from = self.hold(&sequence.vocabulary_digest)?;
417        let to = self.hold(to_digest)?;
418        let units = kute::decoded_units(&from.vocabulary, sequence)?;
419        if units > self.policy.max_decoded_units {
420            return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units")));
421        }
422        // Symbols can be a kilobyte each, so their count is not their size.
423        // The translation goes back in one frame, so a frame bounds it.
424        let bytes = kute::decoded_bytes_at_least(&from.vocabulary, sequence)?;
425        if bytes > self.policy.max_frame_bytes {
426            return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; a frame holds {}", self.policy.max_frame_bytes)));
427        }
428        to.tokenizer.encode_open(&from.tokenizer.decode(sequence)?, UnknownPolicy::Escape)
429    }
430
431    /// Handle one message from the other side. Never fails: anything wrong
432    /// is answered with an `ERROR` message.
433    pub fn handle(&mut self, message: Message) -> Vec<Message> {
434        match (self.stage, &message) {
435            (Stage::New, Message::Hello { protocol, .. }) => {
436                if *protocol != PROTOCOL_VERSION {
437                    return refuse(ErrorCode::UnsupportedProtocol, format!("this peer speaks protocol {PROTOCOL_VERSION}, not {protocol}"));
438                }
439                self.stage = Stage::Greeted;
440                return vec![self.hello()];
441            }
442            (Stage::Greeted, Message::Capabilities { .. }) => {
443                self.stage = Stage::Ready;
444                return vec![self.capabilities()];
445            }
446            (Stage::Ready, Message::Hello { .. } | Message::Capabilities { .. }) | (Stage::New | Stage::Greeted, _) => {
447                return refuse(ErrorCode::OutOfOrder, "expected HELLO, then CAPABILITIES, before anything else");
448            }
449            (Stage::Ready, _) => {}
450        }
451        match self.respond(message) {
452            Ok(replies) => replies,
453            Err(e) => {
454                let code = match e {
455                    KuteError::LimitExceeded(_) => ErrorCode::TooLarge,
456                    KuteError::VocabularyMismatch(_) => ErrorCode::UnknownVocabulary,
457                    _ => ErrorCode::Invalid,
458                };
459                refuse(code, e.to_string())
460            }
461        }
462    }
463
464    fn respond(&mut self, message: Message) -> Result<Vec<Message>> {
465        match message {
466            Message::VocabAnnounce { vocabulary } => {
467                // A vocabulary that is held but not this peer's to use is
468                // treated from here on exactly as one that is not held: the
469                // same checks, the same request for its content. If the
470                // peer then sends it, it had the content already, and it
471                // becomes one it may use.
472                if self.held.contains_key(&vocabulary.digest) && self.sees(&vocabulary.digest) {
473                    return Ok(vec![Message::VocabAccept { digest: vocabulary.digest }]);
474                }
475                if self.held.values().any(|h| {
476                    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)
477                }) {
478                    // This does tell a peer that the id and version are
479                    // taken, whether or not it may use the holder. Two
480                    // vocabularies cannot share them, so the refusal cannot
481                    // be avoided, only worded the same in both cases.
482                    return Ok(refuse(
483                        ErrorCode::VocabularyConflict,
484                        format!("{} {} is held here with different content", vocabulary.id, vocabulary.version),
485                    ));
486                }
487                if !self.engine.registry().algorithm_names().contains(&vocabulary.algorithm) {
488                    return Ok(refuse(ErrorCode::UnsupportedAlgorithm, format!("algorithm {:?} is not available here", vocabulary.algorithm)));
489                }
490                if !self.policy.accept_vocabularies {
491                    return Ok(refuse(ErrorCode::Refused, "this peer does not take vocabularies from the other side"));
492                }
493                if vocabulary.tokens > self.policy.max_vocabulary_tokens {
494                    return Ok(refuse(ErrorCode::TooLarge, format!("vocabularies above {} tokens are not taken", self.policy.max_vocabulary_tokens)));
495                }
496                if let Some(refusal) = self.over_budget(vocabulary.tokens) {
497                    return Ok(refusal);
498                }
499                let digest = vocabulary.digest.clone();
500                self.wanted = Some(vocabulary);
501                Ok(vec![Message::VocabRequest { digest }])
502            }
503            Message::VocabRequest { digest } => {
504                if !self.policy.give_vocabularies {
505                    return Ok(refuse(ErrorCode::Refused, "this peer does not give out vocabularies"));
506                }
507                let kvf = kute::vocab::to_vec(&self.usable(&digest)?.vocabulary)?;
508                Ok(vec![Message::VocabData { digest, kvf }])
509            }
510            Message::VocabData { digest, kvf } => {
511                let Some(wanted) = self.wanted.take().filter(|w| w.digest == digest) else {
512                    return Ok(refuse(ErrorCode::OutOfOrder, "vocabulary data that was not requested"));
513                };
514                let vocabulary = kute::vocab::from_slice(&kvf)?;
515                // The digest is recomputed from content; the one in the file
516                // and the one announced are both only claims.
517                if vocabulary.compute_digest()? != digest || VocabRef::of(&vocabulary)? != wanted {
518                    return Ok(refuse(ErrorCode::Invalid, "the vocabulary sent is not the one announced"));
519                }
520                if vocabulary.len() as u64 > self.policy.max_vocabulary_tokens {
521                    return Ok(refuse(ErrorCode::TooLarge, "vocabulary exceeds the token limit"));
522                }
523                // Again, on what was sent and not on what was announced.
524                if let Some(refusal) = self.over_budget(vocabulary.len() as u64) {
525                    return Ok(refusal);
526                }
527                if let Some(check) = &self.check {
528                    if let Err(why) = check(&vocabulary) {
529                        return Ok(refuse(ErrorCode::Refused, format!("the vocabulary is not taken: {why}")));
530                    }
531                }
532                let report = self.engine.verify(&vocabulary)?;
533                if !report.ok() {
534                    return Ok(refuse(ErrorCode::Invalid, format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
535                }
536                let digest = self.add_vocabulary(vocabulary)?;
537                self.show(&digest);
538                Ok(vec![Message::VocabAccept { digest }])
539            }
540            Message::SymbolQuery { digest, symbols } => {
541                if !self.policy.answer_queries {
542                    return Ok(refuse(ErrorCode::Refused, "this peer does not answer questions about its vocabularies"));
543                }
544                let payload = TokenPayload::Symbols(symbols);
545                let token_id = self.usable(&digest)?.vocabulary.tokens.iter().find(|t| t.payload == payload).map(|t| t.id);
546                Ok(vec![Message::SymbolInfo { digest, token_id, content_hash: payload.content_hash() }])
547            }
548            Message::SymbolPropose { digest, additions, version, rule, signatures } => {
549                if !self.policy.accept_proposals {
550                    return Ok(refuse(ErrorCode::Refused, "this peer does not accept vocabulary proposals"));
551                }
552                if self.check.is_some() && signatures.is_empty() {
553                    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"));
554                }
555                if signatures.len() > MAX_PROPOSAL_SIGNATURES || signatures.iter().any(|s| s.key_id.len() > 256 || s.algorithm.len() > 64 || s.signature.len() > 1024) {
556                    return Ok(refuse(ErrorCode::TooLarge, format!("a proposal carries at most {MAX_PROPOSAL_SIGNATURES} signatures, none with an overlong field")));
557                }
558                // Before anything is derived: under another rule the child
559                // would differ, and the two sides would part silently.
560                if rule != EVOLUTION_RULE {
561                    return Ok(refuse(
562                        ErrorCode::UnsupportedRule,
563                        format!("the proposal uses evolution rule {rule:?}; this peer implements {EVOLUTION_RULE:?}"),
564                    ));
565                }
566                // An addition of n symbols adds at most n symbols and n merges.
567                let most: u64 = additions.iter().map(|a| 2 * a.len() as u64).sum();
568                let parent = self.usable(&digest)?.vocabulary.len() as u64;
569                if parent.saturating_add(most) > self.policy.max_vocabulary_tokens {
570                    return Ok(refuse(ErrorCode::TooLarge, "the proposal would pass the vocabulary token limit"));
571                }
572                if let Some(refusal) = self.over_budget(parent.saturating_add(most)) {
573                    return Ok(refusal);
574                }
575                // The child is derived even when its id and version are
576                // already held: a repeat of the same proposal has to be
577                // accepted again, and only the derivation tells a repeat
578                // from a conflict. Its cost is bounded by the checks above.
579                let parsed = Version::parse(&version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
580                let mut child = kute::bpe::sequence::evolve(&self.hold(&digest)?.vocabulary, &additions, parsed)?;
581                if !signatures.is_empty() {
582                    // Of the vocabulary derived here, not of anything
583                    // received: a signature made for other content does
584                    // not hold for this digest.
585                    child.seal()?;
586                    child.integrity.as_mut().expect("sealed").signatures = signatures;
587                }
588                if let Some(check) = &self.check {
589                    if let Err(why) = check(&child) {
590                        return Ok(refuse(ErrorCode::Refused, format!("the proposed vocabulary is not taken: {why}")));
591                    }
592                }
593                let digest = match self.add_vocabulary(child) {
594                    Ok(digest) => digest,
595                    Err(KuteError::VocabularyMismatch(why)) => return Ok(refuse(ErrorCode::VocabularyConflict, why)),
596                    Err(e) => return Err(e),
597                };
598                self.show(&digest);
599                Ok(vec![Message::VocabAccept { digest }])
600            }
601            Message::Translate { id, container, to_digest } => {
602                if !self.policy.translate {
603                    return Ok(refuse(ErrorCode::Refused, "this peer does not translate for the other side"));
604                }
605                // A container that declares more tokens than the limit is
606                // refused before its ids are decompressed.
607                let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
608                self.usable(&sequence.vocabulary_digest)?;
609                self.usable(&to_digest)?;
610                let translated = self.translate(&sequence, &to_digest)?;
611                Ok(vec![Message::EncodedMessage { id, container: translated.to_bytes_compressed()? }])
612            }
613            Message::EncodedMessage { id, container } => {
614                // A repeat of a delivered message gets its receipt again and
615                // is not delivered twice; the same id on other content is an
616                // error. Ids older than the window are not remembered.
617                let fingerprint = sha256_hex(&container);
618                if let Some((_, first, receipt)) = self.seen.iter().find(|(seen, _, _)| *seen == id) {
619                    return Ok(if *first == fingerprint {
620                        vec![receipt.clone()]
621                    } else {
622                        refuse(ErrorCode::Invalid, format!("message id {id} was already used for different content"))
623                    });
624                }
625                if self.inbox.len() as u64 >= self.policy.max_inbox_messages {
626                    return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} messages, its limit", self.inbox.len())));
627                }
628                let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
629                let held = self.usable(&sequence.vocabulary_digest)?;
630                let units = kute::decoded_units(&held.vocabulary, &sequence)?;
631                let bytes = self.engine.decode_raw_within(held.tokenizer.as_ref(), &sequence, self.policy.max_decoded_units, self.policy.max_inbox_bytes)?;
632                // What the inbox keeps for this message: the decoded bytes
633                // and the sequence (ids, and the escapes the container holds).
634                let kept = (bytes.len() as u64).saturating_add(4 * sequence.ids.len() as u64).saturating_add(container.len() as u64);
635                if self.inbox_bytes.saturating_add(kept) > self.policy.max_inbox_bytes {
636                    return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} bytes and takes at most {}", self.inbox_bytes, self.policy.max_inbox_bytes)));
637                }
638                let receipt = Message::Ack { id, units, sha256: sha256_hex(&bytes) };
639                self.inbox_bytes += kept;
640                self.inbox.push(Delivered { id, sequence, bytes });
641                self.seen.push_back((id, fingerprint, receipt.clone()));
642                while self.seen.len() as u64 > self.policy.replay_window {
643                    self.seen.pop_front();
644                }
645                Ok(vec![receipt])
646            }
647            Message::VocabAccept { .. } | Message::SymbolInfo { .. } | Message::Ack { .. } | Message::Error { .. } => {
648                Ok(refuse(ErrorCode::OutOfOrder, "a reply arrived where a request was expected"))
649            }
650            Message::Hello { .. } | Message::Capabilities { .. } => Ok(refuse(ErrorCode::OutOfOrder, "the handshake is already complete")),
651        }
652    }
653}
654
655/// Something that carries messages to the other peer and back.
656pub trait Transport {
657    fn send(&mut self, message: &Message) -> Result<()>;
658    /// The next message, or `None` when the other side has closed.
659    fn recv(&mut self) -> Result<Option<Message>>;
660}
661
662/// Messages over a byte stream: a four-byte little-endian length, then that
663/// many bytes of JSON.
664pub struct Framed<S: Read + Write> {
665    stream: S,
666    max_frame: u64,
667}
668
669impl<S: Read + Write> Framed<S> {
670    pub fn new(stream: S, max_frame: u64) -> Self {
671        Self { stream, max_frame: max_frame.min(DEFAULT_MAX_FRAME) }
672    }
673}
674
675impl<S: Read + Write> Transport for Framed<S> {
676    fn send(&mut self, message: &Message) -> Result<()> {
677        let body = serde_json::to_vec(message)?;
678        if body.len() as u64 > self.max_frame {
679            return Err(KuteError::LimitExceeded(format!("message of {} bytes exceeds the frame limit of {}", body.len(), self.max_frame)));
680        }
681        self.stream.write_all(&(body.len() as u32).to_le_bytes())?;
682        self.stream.write_all(&body)?;
683        self.stream.flush()?;
684        Ok(())
685    }
686
687    fn recv(&mut self) -> Result<Option<Message>> {
688        let mut length = [0u8; 4];
689        let mut got = 0;
690        while got < 4 {
691            match self.stream.read(&mut length[got..]) {
692                Ok(0) if got == 0 => return Ok(None),
693                Ok(0) => return Err(KuteError::InvalidInput("the stream ended inside a frame header".into())),
694                Ok(n) => got += n,
695                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
696                Err(e) => return Err(e.into()),
697            }
698        }
699        let length = u32::from_le_bytes(length) as u64;
700        if length > self.max_frame {
701            return Err(KuteError::LimitExceeded(format!("incoming frame of {length} bytes exceeds the limit of {}", self.max_frame)));
702        }
703        // Read through `take` so a forged length cannot make us allocate
704        // more than actually arrives.
705        let mut body = Vec::new();
706        (&mut self.stream).take(length).read_to_end(&mut body)?;
707        if body.len() as u64 != length {
708            return Err(KuteError::InvalidInput("the stream ended inside a frame".into()));
709        }
710        serde_json::from_slice(&body).map(Some).map_err(|e| KuteError::InvalidInput(format!("not a protocol message: {e}")))
711    }
712}
713
714/// The other side's answer to `CAPABILITIES`.
715#[derive(Clone, Debug, PartialEq, Eq)]
716pub struct Remote {
717    pub peer: String,
718    pub software: String,
719    pub algorithms: Vec<String>,
720    pub accepts_vocabularies: bool,
721    pub accepts_proposals: bool,
722    pub evolution_rules: Vec<String>,
723}
724
725fn peer_error(code: ErrorCode, message: String) -> KuteError {
726    KuteError::Backend(format!("the peer answered {code:?}: {message}"))
727}
728
729/// A peer together with its connection.
730pub struct Session<T: Transport> {
731    pub peer: Peer,
732    transport: T,
733    next_id: u64,
734    remote: Option<Remote>,
735}
736
737impl<T: Transport> Session<T> {
738    pub fn new(peer: Peer, transport: T) -> Self {
739        Self { peer, transport, next_id: 1, remote: None }
740    }
741
742    fn ask(&mut self, message: &Message) -> Result<Message> {
743        self.transport.send(message)?;
744        match self.transport.recv()? {
745            Some(Message::Error { code, message }) => Err(peer_error(code, message)),
746            Some(reply) => Ok(reply),
747            None => Err(KuteError::Backend("the peer closed the connection".into())),
748        }
749    }
750
751    fn unexpected<R>(reply: Message) -> Result<R> {
752        Err(KuteError::Backend(format!("unexpected reply from the peer: {reply:?}")))
753    }
754
755    /// Initiator: handshake and capability exchange.
756    pub fn connect(&mut self) -> Result<Remote> {
757        let (peer, software) = match self.ask(&self.peer.hello())? {
758            Message::Hello { protocol, peer, software } if protocol == PROTOCOL_VERSION => (peer, software),
759            other => return Self::unexpected(other),
760        };
761        match self.ask(&self.peer.capabilities())? {
762            Message::Capabilities { algorithms, accepts_vocabularies, accepts_proposals, evolution_rules, .. } => {
763                let remote = Remote { peer, software, algorithms, accepts_vocabularies, accepts_proposals, evolution_rules };
764                self.remote = Some(remote.clone());
765                Ok(remote)
766            }
767            other => Self::unexpected(other),
768        }
769    }
770
771    /// Initiator: make sure the other side holds the vocabulary `digest`,
772    /// sending it if asked. Returns true if it had to be transferred.
773    pub fn share(&mut self, digest: &str) -> Result<bool> {
774        let vocabulary = VocabRef::of(&self.peer.hold(digest)?.vocabulary)?;
775        match self.ask(&Message::VocabAnnounce { vocabulary })? {
776            Message::VocabAccept { digest: d } if d == digest => Ok(false),
777            Message::VocabRequest { digest: d } if d == digest => {
778                let kvf = kute::vocab::to_vec(&self.peer.hold(digest)?.vocabulary)?;
779                match self.ask(&Message::VocabData { digest: digest.to_string(), kvf })? {
780                    Message::VocabAccept { digest: d } if d == digest => Ok(true),
781                    other => Self::unexpected(other),
782                }
783            }
784            other => Self::unexpected(other),
785        }
786    }
787
788    /// Initiator: encode `raw`, send it, and check the receipt. Returns the
789    /// number of units the other side decoded. Fails if the other side
790    /// decoded anything other than what this side's decoder gives.
791    pub fn send(&mut self, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<u64> {
792        let id = self.next_id;
793        self.next_id += 1;
794        let (message, expected) = self.peer.encode_message(id, digest, raw, policy)?;
795        match self.ask(&message)? {
796            Message::Ack { id: acked, units, sha256 } if acked == id => {
797                if sha256 != expected {
798                    return Err(KuteError::Integrity("the peer decoded the message to different content".into()));
799                }
800                Ok(units)
801            }
802            other => Self::unexpected(other),
803        }
804    }
805
806    /// Initiator: extend a shared vocabulary on both sides. Each side
807    /// applies the step itself; the digests must agree. Returns the new
808    /// digest. Nothing changes locally if the other side refuses.
809    pub fn propose(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
810        self.propose_signed(digest, additions, version, &|_| Ok(()))
811    }
812
813    /// [`Session::propose`], vouching for the result. `sign` is given the
814    /// vocabulary this side derived, sealed, and adds its signatures to
815    /// it; they travel with the proposal, and the vocabulary held here
816    /// afterwards carries them. The protocol makes no signature itself.
817    pub fn propose_signed(&mut self, digest: &str, additions: &[Vec<String>], version: &str, sign: &dyn Fn(&mut Vocabulary) -> Result<()>) -> Result<String> {
818        if let Some(remote) = &self.remote {
819            if !remote.evolution_rules.iter().any(|r| r == EVOLUTION_RULE) {
820                return Err(KuteError::Unsupported(format!(
821                    "the peer implements evolution rules {:?}, not {EVOLUTION_RULE:?}; a proposal would derive different vocabularies on the two sides",
822                    remote.evolution_rules
823                )));
824            }
825        }
826        let parsed = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
827        let mut child = kute::bpe::sequence::evolve(&self.peer.hold(digest)?.vocabulary, additions, parsed)?;
828        child.seal()?;
829        let expected = child.digest()?;
830        sign(&mut child)?;
831        if child.compute_digest()? != expected {
832            return Err(KuteError::Integrity("signing changed the vocabulary".into()));
833        }
834        let propose = Message::SymbolPropose {
835            digest: digest.to_string(),
836            additions: additions.to_vec(),
837            version: version.to_string(),
838            rule: EVOLUTION_RULE.to_string(),
839            signatures: child.integrity.as_ref().map(|i| i.signatures.clone()).unwrap_or_default(),
840        };
841        match self.ask(&propose)? {
842            Message::VocabAccept { digest: theirs } if theirs == expected => self.peer.add_vocabulary(child),
843            Message::VocabAccept { digest: theirs } => {
844                Err(KuteError::Integrity(format!("the peer derived {theirs}, this side derived {expected}")))
845            }
846            other => Self::unexpected(other),
847        }
848    }
849
850    /// Initiator: ask whether a symbol sequence is a token over there.
851    pub fn query(&mut self, digest: &str, symbols: &[String]) -> Result<Option<u32>> {
852        match self.ask(&Message::SymbolQuery { digest: digest.to_string(), symbols: symbols.to_vec() })? {
853            Message::SymbolInfo { token_id, .. } => Ok(token_id),
854            other => Self::unexpected(other),
855        }
856    }
857
858    /// Initiator: have the other side re-encode a sequence under another
859    /// vocabulary it holds.
860    pub fn translate(&mut self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
861        let id = self.next_id;
862        self.next_id += 1;
863        let ask = Message::Translate { id, container: sequence.to_bytes_compressed()?, to_digest: to_digest.to_string() };
864        match self.ask(&ask)? {
865            Message::EncodedMessage { id: got, container } if got == id => {
866                let translated = TokenSequence::from_bytes(&container)?;
867                if translated.vocabulary_digest != to_digest {
868                    return Err(KuteError::Integrity("the peer translated to a different vocabulary".into()));
869                }
870                Ok(translated)
871            }
872            other => Self::unexpected(other),
873        }
874    }
875
876    /// Responder: answer messages until the other side closes. Returns the
877    /// number of messages handled.
878    pub fn serve(&mut self) -> Result<u64> {
879        let mut handled = 0;
880        while let Some(message) = self.transport.recv()? {
881            for reply in self.peer.handle(message) {
882                self.transport.send(&reply)?;
883            }
884            handled += 1;
885        }
886        Ok(handled)
887    }
888}