web5_rust/dwn/
protocol.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
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
use super::Error;

use super::permission::{
    ChannelPermissionOptions,
    PermissionOptions,
    PermissionSet,
};

use crate::common::Schemas;
use chrono::{DateTime, Utc};

use simple_crypto::{PublicKey, Hashable, Hash};

use std::collections::BTreeMap;

use simple_database::Indexable;

use schemars::{JsonSchema, schema_for};
use serde::{Serialize, Deserialize};

#[derive(JsonSchema, Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct ChannelProtocol {
    pub child_protocols: Option<Vec<Hash>>, //None for any child empty for no children
}
impl ChannelProtocol {
    pub fn new(child_protocols: Option<Vec<&Protocol>>) -> Self {
        ChannelProtocol{child_protocols: child_protocols.map(|cp| cp.into_iter().map(|p| p.hash()).collect())}
    }
}

#[derive(JsonSchema, Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Protocol {
    pub name: String,
    pub delete: bool,//Weather record can be deleted
    pub permissions: PermissionOptions,
    pub schema: Option<String>,
    pub channel: Option<ChannelProtocol>
}

impl Hashable for Protocol {}
impl Indexable for Protocol {
    fn primary_key(&self) -> Vec<u8> {self.hash_bytes()}
}

impl Protocol {
    pub fn new(
        name: &str,
        delete: bool,//Weather record can be deleted
        permissions: PermissionOptions,
        schema: Option<String>,
        channel: Option<ChannelProtocol>
    ) -> Result<Self, Error> {
        let protocol = Protocol{name: name.to_string(), delete, permissions, schema, channel};
        protocol.validate()?;
        Ok(protocol)
    }

    pub fn is_valid_child(&self, child_protocol: &Hash) -> Result<(), Error> {
        let error = |r: &str| Error::bad_request("Protocol.validate_child_protocol", r);
        if let Some(channel) = &self.channel {
            if let Some(cps) = &channel.child_protocols {
                if !cps.contains(child_protocol) {
                    return Err(error("ChildProtocol not supported by channel"));
                }
            }
            Ok(())
        } else {Err(error("Protocol Has No Channel"))}
    }

    fn validate(&self) -> Result<(), Error> {
        let error = |r: &str| Error::bad_request("Protocol.validate_self", r);
        if self.channel.is_some() != self.permissions.channel.is_some() {
            return Err(error("Channel permission present with out channel protocol"));
        }
        if !self.delete && self.permissions.can_delete {
            return Err(error("Delete Permission Required while deletese are disabled"));
        }
        Ok(())
    }
}

pub struct SystemProtocols{}
impl SystemProtocols {
    pub fn get_map() -> BTreeMap<Hash, Protocol> {
        let dm = Self::dms_channel();
        let ak = Self::agent_keys();
        let dt = Self::date_time();
        let us = Self::usize();
        let ci = Self::channel_item();
        let sp = Self::shared_pointer();
        let pp = Self::perm_pointer();
        let p = Self::pointer();
        let r = Self::root();
        BTreeMap::from([
            (dm.hash(), dm),
            (ak.hash(), ak),
            (dt.hash(), dt),
            (us.hash(), us),
            (ci.hash(), ci),
            (sp.hash(), sp),
            (pp.hash(), pp),
            (p.hash(), p),
            (r.hash(), r),
        ])
    }

    pub fn root() -> Protocol {
        Protocol::new(
            "root",
            false,
            PermissionOptions::new(true, true, false, Some(
                ChannelPermissionOptions::new(true, true, true)
            )),
            None,
            Some(ChannelProtocol::new(None))
        ).unwrap()
    }

    pub fn protocol_folder(protocol: Hash) -> Protocol {
        Protocol::new(
            &format!("protocol_folder: {}", hex::encode(protocol.as_bytes())),
            false,
            PermissionOptions::new(false, false, false, Some(
                ChannelPermissionOptions::new(false, false, false)
            )),
            None,
            Some(ChannelProtocol{child_protocols: Some(vec![protocol])})
        ).unwrap()
    }

    pub fn dms_channel() -> Protocol {
        Protocol::new(
            "dms_channel",
            true,
            PermissionOptions::new(true, true, true, Some(
                ChannelPermissionOptions::new(true, true, true)
            )),
            None,
            //Some(ChannelProtocol::new(Some(vec![Self::pointer().hash()])))
            Some(ChannelProtocol::new(None))
        ).unwrap()
    }

    pub fn agent_keys() -> Protocol {
        Protocol::new(
            "agent_keys",
            true,
            PermissionOptions::new(true, true, true, None),
            Some(serde_json::to_string(&schema_for!(Vec<PublicKey>)).unwrap()),
            None
        ).unwrap()
    }

    pub fn date_time() -> Protocol {
        Protocol::new(
            "date_time",
            true,
            PermissionOptions::new(true, true, true, None),
            Some(serde_json::to_string(&schema_for!(DateTime<Utc>)).unwrap()),
            None
        ).unwrap()
    }

    pub fn usize() -> Protocol {
        Protocol::new(
            "date_time",
            true,
            PermissionOptions::new(true, true, true, None),
            Some(serde_json::to_string(&schema_for!(usize)).unwrap()),
            None
        ).unwrap()
    }

    pub fn channel_item() -> Protocol {
        Protocol::new(
            "channel_item",
            false,
            PermissionOptions::new(false, false, false, None),
            Some(serde_json::to_string(&Schemas::any()).unwrap()),
            None
        ).unwrap()
    }

    pub fn perm_pointer() -> Protocol {
        Protocol::new(
            "perm_pointer",
            false,
            PermissionOptions::new(true, true, false, None),
            Some(serde_json::to_string(&schema_for!(PermissionSet)).unwrap()),
            None
        ).unwrap()
    }

    pub fn pointer() -> Protocol {
        Protocol::new(
            "pointer",
            true,
            PermissionOptions::new(true, true, true, None),
            Some(serde_json::to_string(&schema_for!(PermissionSet)).unwrap()),
            None
        ).unwrap()
    }

    pub fn shared_pointer() -> Protocol {
        Protocol::new(
            "shared_pointer",
            false,
            PermissionOptions::new(true, true, false, None),
            Some(serde_json::to_string(&schema_for!(Vec<Vec<u8>>)).unwrap()),
            None
        ).unwrap()
    }
}