Skip to main content

libkeri/keri/core/eventing/
exchange.rs

1//! Peer-to-peer `exn` messages (keripy: peer/exchanging.py exchange).
2
3use crate::cesr::counting::{ctr_dex_1_0, BaseCounter, Counter};
4use crate::cesr::pather::Pather;
5use crate::cesr::saider::Saider;
6use crate::keri::core::serdering::{Rawifiable, SadValue, Sadder, Serder, SerderKERI};
7use crate::keri::KERIError;
8use crate::Matter;
9
10/// The current time as keripy `helping.nowIso8601` writes it: microseconds
11/// and a `+00:00` offset.
12pub fn now_iso8601() -> String {
13    chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.6f+00:00").to_string()
14}
15
16/// Build an `exn` message (keripy: peer/exchanging.py exchange).
17///
18/// * `route`: the `r` field, e.g. `/fwd`.
19/// * `sender`: the `i` field, the sender's AID.
20/// * `payload`: the `a` block; `recipient`, when given, goes first in it as `i`.
21/// * `modifiers`: the `q` block.
22/// * `embeds`: named KERI messages (with attachments) embedded in `e`. Each
23///   message's body goes in `e[label]`; its attachments are returned in the
24///   second value as a pathed material group pointing at `/e/label`.
25/// * `date`: the `dt` field; `None` is now.
26/// * `dig`: the `p` field, the SAID of a prior `exn`.
27///
28/// Returns the `exn` and the pathed attachments to send after its own
29/// signatures.
30pub fn exchange(
31    route: &str,
32    sender: &str,
33    payload: Sadder,
34    modifiers: Sadder,
35    embeds: &[(&str, &[u8])],
36    recipient: Option<&str>,
37    date: Option<&str>,
38    dig: Option<&str>,
39) -> Result<(SerderKERI, Vec<u8>), KERIError> {
40    let mut e = Sadder::new();
41    let mut end = Vec::new();
42    for (label, msg) in embeds {
43        let serder = SerderKERI::from_raw(msg, None)?;
44        e.insert(label.to_string(), SadValue::Object(serder.sad().clone()));
45        let atc = &msg[serder.size()..];
46        if atc.is_empty() {
47            continue;
48        }
49        let mut pathed = Pather::from_path(&["e", label])?.qb64b();
50        pathed.extend_from_slice(atc);
51        let code = if pathed.len() / 4 < 4096 {
52            ctr_dex_1_0::PATHED_MATERIAL_GROUP
53        } else {
54            ctr_dex_1_0::BIG_PATHED_MATERIAL_GROUP
55        };
56        let counter = BaseCounter::from_code_and_count(Some(code), Some((pathed.len() / 4) as u64), Some("1.0"))
57            .map_err(|e| KERIError::ValueError(format!("pathed counter: {}", e)))?;
58        end.extend_from_slice(&counter.qb64b());
59        end.extend_from_slice(&pathed);
60    }
61    if !e.is_empty() {
62        e.insert("d".to_string(), SadValue::String(String::new()));
63        let (_, saidified) = Saider::saidify(e, None, None, None, None)?;
64        e = saidified;
65    }
66
67    let mut attrs = Sadder::new();
68    if let Some(recipient) = recipient {
69        attrs.insert("i".to_string(), SadValue::String(recipient.to_string()));
70    }
71    attrs.extend(payload);
72
73    let mut ked = Sadder::new();
74    ked.insert("v".to_string(), SadValue::String("KERI10JSON000000_".to_string()));
75    ked.insert("t".to_string(), SadValue::String("exn".to_string()));
76    ked.insert("d".to_string(), SadValue::String(String::new()));
77    ked.insert("i".to_string(), SadValue::String(sender.to_string()));
78    ked.insert("rp".to_string(), SadValue::String(recipient.unwrap_or("").to_string()));
79    ked.insert("p".to_string(), SadValue::String(dig.unwrap_or("").to_string()));
80    ked.insert(
81        "dt".to_string(),
82        SadValue::String(date.map(str::to_string).unwrap_or_else(now_iso8601)),
83    );
84    ked.insert("r".to_string(), SadValue::String(route.to_string()));
85    ked.insert("q".to_string(), SadValue::Object(modifiers));
86    ked.insert("a".to_string(), SadValue::Object(attrs));
87    ked.insert("e".to_string(), SadValue::Object(e));
88    let serder = SerderKERI::from_sad_and_saids(&ked, None)?;
89    Ok((serder, end))
90}