libkeri 0.1.0

A Rust library for KERI (Key Event Receipt Infrastructure)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use crate::cesr::Versionage;
use crate::keri::core::serdering::{SadValue, SerderKERI};
use crate::keri::{versify, Ilks, KERIError, Kinds};
use chrono::{DateTime, Utc};
use indexmap::IndexMap;

/// Builder for creating KERI reply events
pub struct ReplyEventBuilder {
    route: String,
    data: Option<IndexMap<String, SadValue>>,
    stamp: Option<String>,
    version: String,
    kind: String,
}

impl ReplyEventBuilder {
    /// Create a new ReplyEventBuilder
    pub fn new() -> Self {
        Self {
            route: String::new(),
            data: None,
            stamp: None,
            version: "KERI10JSON000000_".to_string(),
            kind: "JSON".to_string(),
        }
    }

    /// Set the route
    ///
    /// Parameters:
    ///   route - namespaced path, '/' delimited, that indicates data flow
    ///           handler (behavior) to process the reply
    pub fn with_route(mut self, route: String) -> Self {
        self.route = route;
        self
    }

    /// Set the data attributes
    ///
    /// Parameters:
    ///   data - attribute section of reply
    pub fn with_data(mut self, data: IndexMap<String, SadValue>) -> Self {
        self.data = Some(data);
        self
    }

    /// Set the timestamp
    ///
    /// Parameters:
    ///   stamp - date-time-stamp RFC-3339 profile of ISO-8601 datetime of creation of message
    pub fn with_stamp(mut self, stamp: String) -> Self {
        self.stamp = Some(stamp);
        self
    }

    /// Set the version string
    pub fn with_version(mut self, version: String) -> Self {
        self.version = version;
        self
    }

    /// Set the serialization kind
    pub fn with_kind(mut self, kind: String) -> Self {
        self.kind = kind;
        self
    }

    /// Build the reply event serder
    pub fn build(self) -> Result<SerderKERI, KERIError> {
        if !Kinds::contains(&self.kind) {
            return Err(KERIError::ValueError(format!(
                "Invalid kind = {} for rpy.",
                self.kind
            )));
        }

        // Create versified string
        let vs = versify("KERI", &Versionage::from(self.version), &self.kind, 0)?;

        // Generate timestamp if not provided
        let timestamp = self.stamp.unwrap_or_else(|| {
            let now: DateTime<Utc> = Utc::now();
            now.to_rfc3339()
        });

        // Create the key event dict (ked)
        let mut ked = IndexMap::new();
        ked.insert("v".to_string(), SadValue::String(vs));
        ked.insert("t".to_string(), SadValue::String(Ilks::RPY.to_string()));
        ked.insert("d".to_string(), SadValue::String("".to_string()));
        ked.insert("dt".to_string(), SadValue::String(timestamp));
        ked.insert("r".to_string(), SadValue::String(self.route));

        if let Some(data) = self.data {
            ked.insert("a".to_string(), SadValue::Object(data));
        } else {
            // If no data is provided, use an empty object
            ked.insert("a".to_string(), SadValue::Object(IndexMap::new()));
        }

        // Create the serder
        let serder = SerderKERI::from_sad_and_saids(&ked, None)?;
        Ok(serder)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keri::core::serdering::Serder;

    #[test]
    fn test_reply_event_builder_basic() -> Result<(), KERIError> {
        // Create a basic reply
        let serder = ReplyEventBuilder::new()
            .with_route("logs/processor".to_string())
            .build()?;

        // Verify the key event data
        let ked = serder.ked();

        // Check it's a reply event
        assert_eq!(ked["t"].as_str().unwrap(), Ilks::RPY);

        // Check basic fields
        assert_eq!(ked["r"].as_str().unwrap(), "logs/processor");

        // Check dt field exists (timestamp)
        assert!(ked.get("dt").is_some());
        let a = ked["a"].clone();
        let raw_str = std::str::from_utf8(serder.raw()).expect("bad utf8");

        // Check a field is an empty object
        match &ked["a"] {
            SadValue::Object(obj) => assert!(obj.is_empty()),
            _ => panic!("Expected a field to be an object"),
        }

        Ok(())
    }

    #[test]
    fn test_reply_event_with_data() -> Result<(), KERIError> {
        // Create data
        let mut data = IndexMap::new();
        data.insert(
            "d".to_string(),
            SadValue::String("EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM".to_string()),
        );
        data.insert(
            "i".to_string(),
            SadValue::String("EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM".to_string()),
        );
        data.insert(
            "name".to_string(),
            SadValue::String("John Jones".to_string()),
        );
        data.insert("role".to_string(), SadValue::String("Founder".to_string()));

        // Set a specific timestamp
        let timestamp = "2020-08-22T17:50:12.988921+00:00".to_string();

        // Create a reply with data
        let serder = ReplyEventBuilder::new()
            .with_route("logs/processor".to_string())
            .with_data(data)
            .with_stamp(timestamp.clone())
            .build()?;

        // Verify the key event data
        let ked = serder.ked();

        // Check timestamp
        assert_eq!(ked["dt"].as_str().unwrap(), timestamp);

        // Check data attributes
        let a = match &ked["a"] {
            SadValue::Object(obj) => obj,
            _ => panic!("Expected a field to be an object"),
        };

        assert_eq!(
            a["d"].as_str().unwrap(),
            "EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM"
        );
        assert_eq!(
            a["i"].as_str().unwrap(),
            "EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM"
        );
        assert_eq!(a["name"].as_str().unwrap(), "John Jones");
        assert_eq!(a["role"].as_str().unwrap(), "Founder");

        Ok(())
    }

    #[test]
    fn test_reply_event_custom_version_kind() -> Result<(), KERIError> {
        // Create a reply with custom version and kind
        let serder = ReplyEventBuilder::new()
            .with_route("logs/processor".to_string())
            .with_version("KERI10".to_string())
            .with_kind("CBOR".to_string())
            .build()?;

        // Verify the version string
        let ked = serder.ked();
        let version = ked["v"].as_str().unwrap();
        assert!(version.starts_with("KERI10CBOR"));

        Ok(())
    }

    #[test]
    fn test_reply_event_invalid_kind() -> Result<(), KERIError> {
        // Try to create a reply with invalid kind
        let result = ReplyEventBuilder::new()
            .with_kind("INVALID".to_string())
            .build();

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Invalid kind"));

        Ok(())
    }

    #[test]
    fn test_reply_event_said_derivation() -> Result<(), KERIError> {
        // Create a reply
        let serder = ReplyEventBuilder::new()
            .with_route("logs/processor".to_string())
            .build()?;

        // Get the SAID (self-addressing identifier)
        let said = serder.said().expect("Failed to get SAID");

        // SAID should start with 'E' for BLAKE3_256 digest
        assert!(said.starts_with('E'));

        // Verify the SAID is in the 'd' field of the event
        assert_eq!(serder.ked()["d"].as_str().unwrap(), said);

        Ok(())
    }

    #[test]
    fn test_reply_matches_python_example() -> Result<(), KERIError> {
        // Recreate the Python example from the docstring
        let mut data = IndexMap::new();
        data.insert(
            "d".to_string(),
            SadValue::String("EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM".to_string()),
        );
        data.insert(
            "i".to_string(),
            SadValue::String("EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM".to_string()),
        );
        data.insert(
            "name".to_string(),
            SadValue::String("John Jones".to_string()),
        );
        data.insert("role".to_string(), SadValue::String("Founder".to_string()));

        let serder = ReplyEventBuilder::new()
            .with_route("logs/processor".to_string())
            .with_data(data)
            .with_stamp("2020-08-22T17:50:12.988921+00:00".to_string())
            .build()?;

        let ked = serder.ked();

        // Check expected fields from Python example
        assert_eq!(ked["t"].as_str().unwrap(), Ilks::RPY);
        assert_eq!(
            ked["dt"].as_str().unwrap(),
            "2020-08-22T17:50:12.988921+00:00"
        );
        assert_eq!(ked["r"].as_str().unwrap(), "logs/processor");

        let a = match &ked["a"] {
            SadValue::Object(obj) => obj,
            _ => panic!("Expected a field to be an object"),
        };

        assert_eq!(
            a["d"].as_str().unwrap(),
            "EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM"
        );
        assert_eq!(
            a["i"].as_str().unwrap(),
            "EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM"
        );
        assert_eq!(a["name"].as_str().unwrap(), "John Jones");
        assert_eq!(a["role"].as_str().unwrap(), "Founder");

        Ok(())
    }

    #[test]
    fn test_reply_event_builder_serialization() -> Result<(), KERIError> {
        // Create data
        let mut data = IndexMap::new();
        data.insert(
            "d".to_string(),
            SadValue::String("EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM".to_string()),
        );
        data.insert(
            "i".to_string(),
            SadValue::String("EAoTNZH3ULvYAfSVPzhzS6baU6JR2nmwyZ-i0d8JZ5CM".to_string()),
        );
        data.insert(
            "name".to_string(),
            SadValue::String("John Jones".to_string()),
        );
        data.insert("role".to_string(), SadValue::String("Founder".to_string()));

        // Create a timestamp matching the Python example
        let timestamp = "2020-08-22T17:50:12.988921+00:00".to_string();

        // Create the reply event
        let serder = ReplyEventBuilder::new()
            .with_route("logs/processor".to_string())
            .with_data(data)
            .with_stamp(timestamp)
            .build()?;

        // Get raw serialized bytes
        let raw = serder.raw();

        // The SAID will be dynamically generated, so we can't check the exact raw bytes
        // but we can check that it starts and ends correctly
        let raw_str = std::str::from_utf8(&raw).expect("bad utf8");

        // Check that it starts with the correct version and type
        assert!(raw_str.starts_with("{\"v\":\"KERI10JSON"));
        assert!(raw_str.contains("\"t\":\"rpy\""));

        // Check that it contains our data
        assert!(raw_str.contains("\"John Jones\""));
        assert!(raw_str.contains("\"Founder\""));

        // Should have a field for route
        assert!(raw_str.contains("\"r\":\"logs/processor\""));

        Ok(())
    }

    #[test]
    fn test_reply_with_empty_route() -> Result<(), KERIError> {
        // Create a reply with empty route (should be valid)
        let serder = ReplyEventBuilder::new().build()?;

        let ked = serder.ked();

        // Check it's a reply event
        assert_eq!(ked["t"].as_str().unwrap(), Ilks::RPY);

        // Check route is empty string
        assert_eq!(ked["r"].as_str().unwrap(), "");

        Ok(())
    }

    #[test]
    fn test_reply_event_for_role_add() -> Result<(), KERIError> {
        // Define the route
        let route = "/end/role/add".to_string();

        // Create data
        let mut data = IndexMap::new();
        data.insert(
            "cid".to_string(),
            SadValue::String("BLK_YxcmK_sAsSW1CbNLJl_FA0gw0FKDuPr_xUwKcj7y".to_string()),
        );
        data.insert("role".to_string(), SadValue::String("watcher".to_string()));
        data.insert(
            "eid".to_string(),
            SadValue::String("BF6YSJGAtVNmq3b7dpBi04Q0YdqvTfsk9PFkkZaR8LRr".to_string()),
        );

        // Create a timestamp matching the Python test
        let timestamp = "2021-01-01T00:00:00.000000+00:00".to_string();

        // Create the reply event
        let serder = ReplyEventBuilder::new()
            .with_route(route)
            .with_data(data)
            .with_stamp(timestamp)
            .build()?;

        // Verify the timestamp
        let ked = serder.ked();
        assert_eq!(
            ked["dt"].as_str().unwrap(),
            "2021-01-01T00:00:00.000000+00:00"
        );

        // Get the raw serialized output
        let raw = serder.raw();

        // Expected raw output from Python test
        let expected = b"{\"v\":\"KERI10JSON000113_\",\"t\":\"rpy\",\"d\":\"EFlkeg-NociMRXHSGBSqARxV5y7zuT5z-ZpLZAkcoMkk\",\"dt\":\"2021-01-01T00:00:00.000000+00:00\",\"r\":\"/end/role/add\",\"a\":{\"cid\":\"BLK_YxcmK_sAsSW1CbNLJl_FA0gw0FKDuPr_xUwKcj7y\",\"role\":\"watcher\",\"eid\":\"BF6YSJGAtVNmq3b7dpBi04Q0YdqvTfsk9PFkkZaR8LRr\"}}";

        // Compare raw output with expected
        assert_eq!(raw, expected);

        // Get and check the SAID
        let said = serder.said().expect("Failed to get SAID");
        assert_eq!(said, "EFlkeg-NociMRXHSGBSqARxV5y7zuT5z-ZpLZAkcoMkk");

        // Verify the data field contains the expected values
        let a = match &ked["a"] {
            SadValue::Object(obj) => obj,
            _ => panic!("Expected a field to be an object"),
        };

        assert_eq!(
            a["cid"].as_str().unwrap(),
            "BLK_YxcmK_sAsSW1CbNLJl_FA0gw0FKDuPr_xUwKcj7y"
        );
        assert_eq!(a["role"].as_str().unwrap(), "watcher");
        assert_eq!(
            a["eid"].as_str().unwrap(),
            "BF6YSJGAtVNmq3b7dpBi04Q0YdqvTfsk9PFkkZaR8LRr"
        );

        Ok(())
    }
}