depo_api/request/
update_key.rs

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
use bc_components::PublicKeyBase;
use bc_envelope::prelude::*;
use anyhow::{Error, Result};

use crate::{NEW_KEY_PARAM, UPDATE_KEY_FUNCTION, util::{Abbrev, FlankedFunction}};

//
// Request
//

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateKey(PublicKeyBase);

impl UpdateKey {
    pub fn new(new_key: PublicKeyBase) -> Self {
        Self(new_key)
    }

    pub fn new_key(&self) -> &PublicKeyBase {
        &self.0
    }
}

impl From<UpdateKey> for Expression {
    fn from(value: UpdateKey) -> Self {
        Expression::new(UPDATE_KEY_FUNCTION)
            .with_parameter(NEW_KEY_PARAM, value.0)
    }
}

impl TryFrom<Expression> for UpdateKey {
    type Error = Error;

    fn try_from(expression: Expression) -> Result<Self> {
        let new_key: PublicKeyBase = expression.extract_object_for_parameter(NEW_KEY_PARAM)?;
        Ok(Self::new(new_key))
    }
}

impl std::fmt::Display for UpdateKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{} new {}",
            "updateKey".flanked_function(),
            self.new_key().abbrev()
        ))
    }
}

#[cfg(test)]
mod tests {
    use bc_components::PrivateKeyBase;
    use indoc::indoc;

    use super::*;

    #[test]
    fn test_request() {
        bc_envelope::register_tags();

        let new_key = PrivateKeyBase::new().schnorr_public_key_base();

        let request = UpdateKey::new(new_key);
        let expression: Expression = request.clone().into();
        let request_envelope = expression.to_envelope();
        // println!("{}", request_envelope.format());
        assert_eq!(request_envelope.format(), indoc! {r#"
        «"updateKey"» [
            ❰"newKey"❱: PublicKeyBase
        ]
        "#}.trim());
        let decoded_expression = Expression::try_from(request_envelope).unwrap();
        let decoded = UpdateKey::try_from(decoded_expression).unwrap();
        assert_eq!(request, decoded);
    }
}