bucky_objects/objects/
object_signs.rs

1use crate::*;
2use crate::signature::ObjSignature;
3
4#[derive(Clone, Debug)]
5pub struct ObjectSigns {
6    // 对Desc部分的签名,可以是多个,sign结构有的时候需要说明是“谁的签名”
7    // 表示对Desc内容的认可。
8    desc_signs: Option<Vec<ObjSignature>>,
9
10    // 对MutBody部分的签名,可以是多个。依赖MutBody的稳定编码
11    body_signs: Option<Vec<ObjSignature>>,
12}
13
14pub struct ObjectSignsHelper;
15
16impl ObjectSignsHelper {
17    pub fn set_sign(list: &mut Option<Vec<ObjSignature>>, sign: ObjSignature) {
18        if list.is_none() {
19            *list = Some(vec![]);
20        }
21
22        let list = list.as_mut().unwrap();
23        list.clear();
24        list.push(sign);
25    }
26
27    pub fn push_sign(list: &mut Option<Vec<ObjSignature>>, sign: ObjSignature) {
28        if list.is_none() {
29            *list = Some(vec![]);
30        }
31
32        let list = list.as_mut().unwrap();
33
34        // 相同source的,只保留已有的签名,忽略时间和签名内容
35        if let Some(cur) = list.iter_mut().find(|v| v.compare_source(&sign)) {
36            if sign.sign_time() > cur.sign_time() {
37                info!("desc sign with same source will update! new={:?}, cur={:?}", sign, cur);
38                *cur = sign;
39            } else{
40                warn!("desc sign with same source already exists! sign={:?}", sign);
41            }
42        } else {
43            list.push(sign);
44        }
45    }
46
47    pub fn latest_sign_time(list: &Option<Vec<ObjSignature>>) -> u64 {
48        let mut ret = 0;
49        if let Some(signs) = list.as_ref() {
50            for sign in signs {
51                if ret < sign.sign_time() {
52                    ret = sign.sign_time();
53                }
54            }
55        }
56        ret
57    }
58
59    // FIXME dest和src合并,相同source签名是保留dest的,还是时间戳比较老的?
60    pub fn merge(dest: &mut Option<Vec<ObjSignature>>, src: &Option<Vec<ObjSignature>>) -> usize {
61        match src {
62            Some(src) => {
63                match dest {
64                    Some(dest) => {
65                        let mut ret = 0;
66                        for src_item in src {
67                            match dest.iter_mut().find(|s| s.compare_source(src_item)) {
68                                Some(dest_item) => {
69                                    if src_item.sign_time() > dest_item.sign_time() {
70                                        *dest_item = src_item.clone();
71                                    }
72                                }
73                                None => {
74                                    dest.push(src_item.clone());
75                                    ret += 1;
76                                }
77
78                            }
79                        }
80                        ret
81                    }
82                    None => {
83                        // src里面的签名也需要确保去重
84                        let mut ret = 0;
85                        let mut dest_list: Vec<ObjSignature> = Vec::new();
86                        for src_item in src {
87                            match dest_list.iter_mut().find(|s| s.compare_source(src_item)) {
88                                Some(dest_item) => {
89                                    if src_item.sign_time() > dest_item.sign_time() {
90                                        *dest_item = src_item.clone();
91                                    }
92                                }
93                                None => {
94                                    dest_list.push(src_item.clone());
95                                    ret += 1;
96                                }
97                            }
98                        }
99
100                        if !dest_list.is_empty() {
101                            *dest = Some(dest_list);
102                        }
103
104                        ret
105                    }
106                }
107            }
108            None => 0,
109        }
110    }
111}
112
113#[derive(Clone)]
114pub struct ObjectSignsBuilder {
115    desc_signs: Option<Vec<ObjSignature>>,
116    body_signs: Option<Vec<ObjSignature>>,
117}
118
119impl ObjectSignsBuilder {
120    pub fn new() -> Self {
121        Self {
122            desc_signs: None,
123            body_signs: None,
124        }
125    }
126
127    pub fn set_desc_sign(mut self, sign: ObjSignature) -> Self {
128        ObjectSignsHelper::set_sign(&mut self.desc_signs, sign);
129        self
130    }
131
132    pub fn set_body_sign(mut self, sign: ObjSignature) -> Self {
133        ObjectSignsHelper::set_sign(&mut self.body_signs, sign);
134        self
135    }
136
137    pub fn push_desc_sign(mut self, sign: ObjSignature) -> Self {
138        ObjectSignsHelper::push_sign(&mut self.desc_signs, sign);
139        self
140    }
141
142    pub fn push_body_sign(mut self, sign: ObjSignature) -> Self {
143        ObjectSignsHelper::push_sign(&mut self.body_signs, sign);
144        self
145    }
146
147    pub fn build(self) -> ObjectSigns {
148        ObjectSigns {
149            desc_signs: self.desc_signs,
150            body_signs: self.body_signs,
151        }
152    }
153}
154
155impl ObjectSigns {
156    pub fn new() -> ObjectSignsBuilder {
157        ObjectSignsBuilder::new()
158    }
159
160    pub fn is_desc_signs_empty(&self) -> bool {
161        if let Some(signs) = &self.desc_signs {
162            signs.len() == 0
163        } else {
164            true
165        }
166    }
167
168    pub fn is_body_signs_empty(&self) -> bool {
169        if let Some(signs) = &self.body_signs {
170            signs.len() == 0
171        } else {
172            true
173        }
174    }
175
176    pub fn is_empty(&self) -> bool {
177        self.is_desc_signs_empty() && self.is_body_signs_empty()
178    }
179
180    pub fn desc_signs(&self) -> Option<&Vec<ObjSignature>> {
181        self.desc_signs.as_ref()
182    }
183
184    pub fn body_signs(&self) -> Option<&Vec<ObjSignature>> {
185        self.body_signs.as_ref()
186    }
187
188    pub fn set_desc_sign(&mut self, sign: ObjSignature) {
189        ObjectSignsHelper::set_sign(&mut self.desc_signs, sign)
190    }
191
192    pub fn set_body_sign(&mut self, sign: ObjSignature) {
193        ObjectSignsHelper::set_sign(&mut self.body_signs, sign)
194    }
195
196    pub fn push_desc_sign(&mut self, sign: ObjSignature) {
197        ObjectSignsHelper::push_sign(&mut self.desc_signs, sign)
198    }
199
200    pub fn push_body_sign(&mut self, sign: ObjSignature) {
201        ObjectSignsHelper::push_sign(&mut self.body_signs, sign)
202    }
203
204    pub fn clear_desc_signs(&mut self) {
205        self.desc_signs.take();
206    }
207
208    pub fn clear_body_signs(&mut self) {
209        self.body_signs.take();
210    }
211
212    pub fn latest_body_sign_time(&self) -> u64 {
213        ObjectSignsHelper::latest_sign_time(&self.body_signs)
214    }
215
216    pub fn latest_desc_sign_time(&self) -> u64 {
217        ObjectSignsHelper::latest_sign_time(&self.desc_signs)
218    }
219
220    pub fn latest_sign_time(&self) -> u64 {
221        std::cmp::max(self.latest_desc_sign_time(), self.latest_body_sign_time())
222    }
223
224    pub fn merge(&mut self, other: &ObjectSigns) -> usize {
225        ObjectSignsHelper::merge(&mut self.desc_signs, &other.desc_signs)
226            + ObjectSignsHelper::merge(&mut self.body_signs, &other.body_signs)
227    }
228
229    pub fn merge_ex(&mut self, other: &ObjectSigns, desc: bool, body: bool) -> usize {
230        let mut ret = 0;
231        if desc {
232            ret += ObjectSignsHelper::merge(&mut self.desc_signs, &other.desc_signs);
233        }
234        if body {
235            ret += ObjectSignsHelper::merge(&mut self.body_signs, &other.body_signs);
236        }
237
238        ret
239    }
240}
241
242impl Default for ObjectSigns {
243    fn default() -> Self {
244        Self {
245            desc_signs: None,
246            body_signs: None,
247        }
248    }
249}
250
251impl RawEncodeWithContext<NamedObjectContext> for ObjectSigns {
252    fn raw_measure_with_context(
253        &self,
254        ctx: &mut NamedObjectContext,
255        purpose: &Option<RawEncodePurpose>,
256    ) -> BuckyResult<usize> {
257        let mut size = 0;
258
259        if self.desc_signs.is_some() {
260            ctx.with_desc_signs();
261            assert!(ctx.has_desc_signs());
262            size = size
263                + self
264                    .desc_signs
265                    .as_ref()
266                    .unwrap()
267                    .raw_measure(purpose)
268                    .map_err(|e| {
269                        log::error!(
270                            "ObjectSigns::raw_measure_with_context/desc_signs error:{}",
271                            e
272                        );
273                        e
274                    })?;
275        }
276
277        if self.body_signs.is_some() {
278            ctx.with_body_signs();
279            assert!(ctx.has_body_signs());
280            size = size
281                + self
282                    .body_signs
283                    .as_ref()
284                    .unwrap()
285                    .raw_measure(purpose)
286                    .map_err(|e| {
287                        log::error!(
288                            "ObjectSigns::raw_measure_with_context/body_signs error:{}",
289                            e
290                        );
291                        e
292                    })?;
293        }
294
295        Ok(size)
296    }
297
298    // 调用之前,必须已经被正确measure过了
299    fn raw_encode_with_context<'a>(
300        &self,
301        buf: &'a mut [u8],
302        ctx: &mut NamedObjectContext,
303        purpose: &Option<RawEncodePurpose>,
304    ) -> BuckyResult<&'a mut [u8]> {
305        /*
306        let size = self.raw_measure_with_context(ctx, purpose).unwrap();
307        if buf.len() < size {
308            let msg = format!(
309                "not enough buffer for encode ObjectSigns, except={}, got={}",
310                size,
311                buf.len()
312            );
313            error!("{}", msg);
314
315            return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, msg));
316        }
317        */
318
319        let buf = if self.desc_signs.is_some() {
320            assert!(ctx.has_desc_signs());
321            self.desc_signs
322                .as_ref()
323                .unwrap()
324                .raw_encode(buf, purpose)
325                .map_err(|e| {
326                    log::error!(
327                        "ObjectSigns::raw_encode_with_context/desc_signs error:{}",
328                        e
329                    );
330                    e
331                })?
332        } else {
333            buf
334        };
335
336        let buf = if self.body_signs.is_some() {
337            assert!(ctx.has_body_signs());
338            self.body_signs
339                .as_ref()
340                .unwrap()
341                .raw_encode(buf, purpose)
342                .map_err(|e| {
343                    log::error!(
344                        "ObjectSigns::raw_encode_with_context/body_signs error:{}",
345                        e
346                    );
347                    e
348                })?
349        } else {
350            buf
351        };
352
353        Ok(buf)
354    }
355}
356
357impl<'de> RawDecodeWithContext<'de, &NamedObjectContext> for ObjectSigns {
358    fn raw_decode_with_context(
359        buf: &'de [u8],
360        ctx: &NamedObjectContext,
361    ) -> BuckyResult<(Self, &'de [u8])> {
362        let (desc_signs, buf) = if ctx.has_desc_signs() {
363            let (desc_signs, buf) = Vec::<ObjSignature>::raw_decode(buf).map_err(|e| {
364                log::error!(
365                    "ObjectSigns::raw_decode_with_context/desc_signs error:{}",
366                    e
367                );
368                e
369            })?;
370            (Some(desc_signs), buf)
371        } else {
372            (None, buf)
373        };
374
375        let (body_signs, buf) = if ctx.has_body_signs() {
376            let (body_signs, buf) = Vec::<ObjSignature>::raw_decode(buf).map_err(|e| {
377                log::error!(
378                    "ObjectSigns::raw_decode_with_context/body_signs error:{}",
379                    e
380                );
381                e
382            })?;
383            (Some(body_signs), buf)
384        } else {
385            (None, buf)
386        };
387
388        Ok((
389            Self {
390                desc_signs,
391                body_signs,
392            },
393            buf,
394        ))
395    }
396}