cyfs_base/objects/
object.rs

1use crate::*;
2
3use std::fmt;
4use std::marker::PhantomData;
5
6pub trait ObjectDesc {
7    fn obj_type(&self) -> u16;
8
9    // 默认实现,从obj_type 转 obj_type_code
10    fn obj_type_code(&self) -> ObjectTypeCode {
11        let t = self.obj_type();
12        t.into()
13    }
14
15    fn is_standard_object(&self) -> bool {
16        let c = self.obj_type_code();
17        c != ObjectTypeCode::Custom
18    }
19
20    fn is_core_object(&self) -> bool {
21        let t = self.obj_type();
22        let c = self.obj_type_code();
23        c == ObjectTypeCode::Custom && object_type_helper::is_core_object(t)
24    }
25
26    fn is_dec_app_object(&self) -> bool {
27        let t = self.obj_type();
28        let c = self.obj_type_code();
29        c == ObjectTypeCode::Custom && object_type_helper::is_dec_app_object(t)
30    }
31
32    fn object_id(&self) -> ObjectId {
33        self.calculate_id()
34    }
35    // 计算 id
36    fn calculate_id(&self) -> ObjectId;
37
38    // 获取所属 DECApp 的 id
39    fn dec_id(&self) -> &Option<ObjectId>;
40
41    // 链接对象列表
42    fn ref_objs(&self) -> &Option<Vec<ObjectLink>>;
43
44    // 前一个版本号
45    fn prev(&self) -> &Option<ObjectId>;
46
47    // 创建时的 BTC Hash
48    fn create_timestamp(&self) -> &Option<HashValue>;
49
50    // 创建时间戳,如果不存在,则返回0
51    fn create_time(&self) -> u64;
52    fn option_create_time(&self) -> Option<u64>;
53    
54    // 过期时间戳
55    fn expired_time(&self) -> Option<u64>;
56}
57
58/// 有权对象,可能是PublicKey::Single 或 PublicKey::MN
59pub trait PublicKeyObjectDesc {
60    fn public_key_ref(&self) -> Option<PublicKeyRef>;
61}
62
63/// 单公钥有权对象,明确用了PublicKey::Single类型
64/// 实现了该Trait的对象一定同时实现了PublicKeyObjectDesc
65pub trait SingleKeyObjectDesc: PublicKeyObjectDesc {
66    fn public_key(&self) -> &PublicKey;
67}
68
69/// 多公钥有权对象,明确用了PublicKey::MN类型
70/// 实现了该Trait的对象一定同时实现了PublicKeyObjectDesc
71pub trait MNKeyObjectDesc: PublicKeyObjectDesc {
72    fn mn_public_key(&self) -> &MNPublicKey;
73}
74
75/// 有主对象
76pub trait OwnerObjectDesc {
77    fn owner(&self) -> &Option<ObjectId>;
78}
79
80/// 有作者对象
81pub trait AuthorObjectDesc {
82    fn author(&self) -> &Option<ObjectId>;
83}
84
85/// 有区域对象
86pub trait AreaObjectDesc {
87    fn area(&self) -> &Option<Area>;
88}
89
90// obj_flags: u16
91// ========
92// * 前5个bits是用来指示编码状态,不计入hash计算。(计算时永远填0)
93// * 剩下的11bits用来标识desc header
94//
95// 段编码标志位
96// --------
97// 0:  是否加密 crypto(现在未定义加密结构,一定填0)
98// 1:  是否包含 mut_body
99// 2:  是否包含 desc_signs
100// 3:  是否包含 body_signs
101// 4:  是否包含 nonce
102//
103// ObjectDesc编码标志位
104// --------
105// 5:  是否包含 dec_id
106// 6:  是否包含 ref_objecs
107// 7:  是否包含 prev
108// 8:  是否包含 create_timestamp
109// 9:  是否包含 create_time
110// 10: 是否包含 expired_time
111//
112// OwnerObjectDesc/AreaObjectDesc/AuthorObjectDesc/PublicKeyObjectDesc 标志位
113// ---------
114// 11: 是否包含 owner
115// 12: 是否包含 area
116// 13: 是否包含 author
117// 14: 是否包含 public_key
118// 15: 是否包含扩展字段
119pub const OBJECT_FLAG_CTYPTO: u16 = 0x01;
120pub const OBJECT_FLAG_MUT_BODY: u16 = 0x01 << 1;
121pub const OBJECT_FLAG_DESC_SIGNS: u16 = 0x01 << 2;
122pub const OBJECT_FLAG_BODY_SIGNS: u16 = 0x01 << 3;
123pub const OBJECT_FLAG_NONCE: u16 = 0x01 << 4;
124
125pub const OBJECT_FLAG_DESC_ID: u16 = 0x01 << 5;
126pub const OBJECT_FLAG_REF_OBJECTS: u16 = 0x01 << 6;
127pub const OBJECT_FLAG_PREV: u16 = 0x01 << 7;
128pub const OBJECT_FLAG_CREATE_TIMESTAMP: u16 = 0x01 << 8;
129pub const OBJECT_FLAG_CREATE_TIME: u16 = 0x01 << 9;
130pub const OBJECT_FLAG_EXPIRED_TIME: u16 = 0x01 << 10;
131
132pub const OBJECT_FLAG_OWNER: u16 = 0x01 << 11;
133pub const OBJECT_FLAG_AREA: u16 = 0x01 << 12;
134pub const OBJECT_FLAG_AUTHOR: u16 = 0x01 << 13;
135pub const OBJECT_FLAG_PUBLIC_KEY: u16 = 0x01 << 14;
136
137// 是否包含扩展字段,预留的非DescContent部分的扩展,包括一个u16长度+对应的content
138pub const OBJECT_FLAG_EXT: u16 = 0x01 << 15;
139
140// 左闭右闭 区间定义
141pub const OBJECT_TYPE_ANY: u16 = 0;
142pub const OBJECT_TYPE_STANDARD_START: u16 = 1;
143pub const OBJECT_TYPE_STANDARD_END: u16 = 16;
144pub const OBJECT_TYPE_CORE_START: u16 = 17;
145pub const OBJECT_TYPE_CORE_END: u16 = 32767;
146pub const OBJECT_TYPE_DECAPP_START: u16 = 32768;
147pub const OBJECT_TYPE_DECAPP_END: u16 = 65535;
148
149pub const OBJECT_PUBLIC_KEY_NONE: u8 = 0x00;
150pub const OBJECT_PUBLIC_KEY_SINGLE: u8 = 0x01;
151pub const OBJECT_PUBLIC_KEY_MN: u8 = 0x02;
152
153pub const OBJECT_BODY_FLAG_PREV: u8 = 0x01;
154pub const OBJECT_BODY_FLAG_USER_DATA: u8 = 0x01 << 1;
155// 是否包含扩展字段,格式和desc一致
156pub const OBJECT_BODY_FLAG_EXT: u8 = 0x01 << 2;
157
158#[derive(Clone, Debug)]
159pub struct NamedObjectBodyContext {
160    body_content_cached_size: Option<usize>,
161}
162
163impl NamedObjectBodyContext {
164    pub fn new() -> Self {
165        Self {
166            body_content_cached_size: None,
167        }
168    }
169
170    pub fn cache_body_content_size(&mut self, size: usize) -> &mut Self {
171        assert!(self.body_content_cached_size.is_none());
172        self.body_content_cached_size = Some(size);
173        self
174    }
175
176    pub fn get_body_content_cached_size(&self) -> usize {
177        self.body_content_cached_size.unwrap()
178    }
179}
180
181#[derive(Clone, Debug)]
182pub struct NamedObjectContext {
183    obj_type: u16,
184    obj_flags: u16,
185    obj_type_code: ObjectTypeCode,
186
187    // DescContent缓存的大小
188    desc_content_cached_size: Option<u16>,
189
190    body_context: NamedObjectBodyContext,
191}
192
193impl NamedObjectContext {
194    pub fn new(obj_type: u16, obj_flags: u16) -> Self {
195        let obj_type_code = obj_type.into();
196        Self {
197            obj_type,
198            obj_flags,
199            obj_type_code,
200            desc_content_cached_size: None,
201            body_context: NamedObjectBodyContext::new(),
202        }
203    }
204
205    pub fn obj_type_code(&self) -> ObjectTypeCode {
206        self.obj_type_code.clone()
207    }
208
209    pub fn obj_type(&self) -> u16 {
210        self.obj_type
211    }
212
213    pub fn obj_flags(&self) -> u16 {
214        self.obj_flags
215    }
216
217    pub fn is_standard_object(&self) -> bool {
218        object_type_helper::is_standard_object(self.obj_type)
219    }
220
221    pub fn is_core_object(&self) -> bool {
222        object_type_helper::is_core_object(self.obj_type)
223    }
224
225    pub fn is_decapp_object(&self) -> bool {
226        object_type_helper::is_dec_app_object(self.obj_type)
227    }
228
229    //
230    // common
231    //
232
233    pub fn with_crypto(&mut self) -> &mut Self {
234        self.obj_flags = self.obj_flags | OBJECT_FLAG_CTYPTO;
235        self
236    }
237
238    pub fn has_crypto(&self) -> bool {
239        self.has_flag(OBJECT_FLAG_CTYPTO)
240    }
241
242    pub fn with_mut_body(&mut self) -> &mut Self {
243        self.obj_flags = self.obj_flags | OBJECT_FLAG_MUT_BODY;
244        self
245    }
246
247    pub fn has_mut_body(&self) -> bool {
248        self.has_flag(OBJECT_FLAG_MUT_BODY)
249    }
250
251    pub fn with_desc_signs(&mut self) -> &mut Self {
252        self.obj_flags = self.obj_flags | OBJECT_FLAG_DESC_SIGNS;
253        self
254    }
255
256    pub fn has_desc_signs(&self) -> bool {
257        self.has_flag(OBJECT_FLAG_DESC_SIGNS)
258    }
259
260    pub fn with_body_signs(&mut self) -> &mut Self {
261        self.obj_flags = self.obj_flags | OBJECT_FLAG_BODY_SIGNS;
262        self
263    }
264
265    pub fn has_body_signs(&self) -> bool {
266        self.has_flag(OBJECT_FLAG_BODY_SIGNS)
267    }
268
269    pub fn with_nonce(&mut self) -> &mut Self {
270        self.obj_flags = self.obj_flags | OBJECT_FLAG_NONCE;
271        self
272    }
273
274    pub fn has_nonce(&self) -> bool {
275        self.has_flag(OBJECT_FLAG_NONCE)
276    }
277
278    //
279    // ObjectDesc
280    //
281
282    pub fn with_dec_id(&mut self) -> &mut Self {
283        self.obj_flags = self.obj_flags | OBJECT_FLAG_DESC_ID;
284        self
285    }
286
287    pub fn has_dec_id(&self) -> bool {
288        self.has_flag(OBJECT_FLAG_DESC_ID)
289    }
290
291    pub fn with_ref_objects(&mut self) -> &mut Self {
292        self.obj_flags = self.obj_flags | OBJECT_FLAG_REF_OBJECTS;
293        self
294    }
295
296    pub fn has_ref_objects(&self) -> bool {
297        self.has_flag(OBJECT_FLAG_REF_OBJECTS)
298    }
299
300    pub fn with_prev(&mut self) -> &mut Self {
301        self.obj_flags = self.obj_flags | OBJECT_FLAG_PREV;
302        self
303    }
304
305    pub fn has_prev(&self) -> bool {
306        self.has_flag(OBJECT_FLAG_PREV)
307    }
308
309    pub fn with_create_timestamp(&mut self) -> &mut Self {
310        self.obj_flags = self.obj_flags | OBJECT_FLAG_CREATE_TIMESTAMP;
311        self
312    }
313
314    pub fn has_create_time_stamp(&self) -> bool {
315        self.has_flag(OBJECT_FLAG_CREATE_TIMESTAMP)
316    }
317
318    pub fn with_create_time(&mut self) -> &mut Self {
319        self.obj_flags = self.obj_flags | OBJECT_FLAG_CREATE_TIME;
320        self
321    }
322
323    pub fn has_create_time(&self) -> bool {
324        self.has_flag(OBJECT_FLAG_CREATE_TIME)
325    }
326
327    pub fn with_expired_time(&mut self) -> &mut Self {
328        self.obj_flags = self.obj_flags | OBJECT_FLAG_EXPIRED_TIME;
329        self
330    }
331
332    pub fn has_expired_time(&self) -> bool {
333        self.has_flag(OBJECT_FLAG_EXPIRED_TIME)
334    }
335
336    //
337    // OwnderObjectDesc/AreaObjectDesc/AuthorObjectDesc/PublicKeyObjectDesc
338    //
339
340    pub fn with_owner(&mut self) -> &mut Self {
341        self.obj_flags = self.obj_flags | OBJECT_FLAG_OWNER;
342        self
343    }
344
345    pub fn has_owner(&self) -> bool {
346        self.has_flag(OBJECT_FLAG_OWNER)
347    }
348
349    pub fn with_area(&mut self) -> &mut Self {
350        self.obj_flags = self.obj_flags | OBJECT_FLAG_AREA;
351        self
352    }
353
354    pub fn has_area(&self) -> bool {
355        self.has_flag(OBJECT_FLAG_AREA)
356    }
357
358    pub fn with_public_key(&mut self) -> &mut Self {
359        self.obj_flags = self.obj_flags | OBJECT_FLAG_PUBLIC_KEY;
360        self
361    }
362
363    pub fn has_public_key(&self) -> bool {
364        self.has_flag(OBJECT_FLAG_PUBLIC_KEY)
365    }
366
367    pub fn with_author(&mut self) -> &mut Self {
368        self.obj_flags = self.obj_flags | OBJECT_FLAG_AUTHOR;
369        self
370    }
371
372    pub fn has_author(&self) -> bool {
373        self.has_flag(OBJECT_FLAG_AUTHOR)
374    }
375
376    pub fn has_ext(&self) -> bool {
377        self.has_flag(OBJECT_FLAG_EXT)
378    }
379
380    // desc_content的缓存大小
381    pub fn cache_desc_content_size(&mut self, size: u16) -> &mut Self {
382        assert!(self.desc_content_cached_size.is_none());
383        self.desc_content_cached_size = Some(size);
384        self
385    }
386
387    pub fn get_desc_content_cached_size(&self) -> u16 {
388        self.desc_content_cached_size.unwrap()
389    }
390
391    // body_context
392    pub fn body_context(&self) -> &NamedObjectBodyContext {
393        &self.body_context
394    }
395
396    pub fn mut_body_context(&mut self) -> &mut NamedObjectBodyContext {
397        &mut self.body_context
398    }
399
400    // inner
401    fn has_flag(&self, flag_pos: u16) -> bool {
402        (self.obj_flags & flag_pos) == flag_pos
403    }
404}
405
406impl RawEncode for NamedObjectContext {
407    fn raw_measure(&self, _purpose: &Option<RawEncodePurpose>) -> BuckyResult<usize> {
408        Ok(u16::raw_bytes().unwrap() * 2)
409    }
410
411    fn raw_encode<'a>(
412        &self,
413        buf: &'a mut [u8],
414        purpose: &Option<RawEncodePurpose>,
415    ) -> BuckyResult<&'a mut [u8]> {
416        let buf = self.obj_type.raw_encode(buf, purpose).map_err(|e| {
417            log::error!("NamedObjectContext::raw_encode/obj_type error:{}", e);
418            e
419        })?;
420
421        let buf = self.obj_flags.raw_encode(buf, purpose).map_err(|e| {
422            log::error!("NamedObjectContext::raw_encode/obj_flags error:{}", e);
423            e
424        })?;
425
426        Ok(buf)
427    }
428}
429
430impl<'de> RawDecode<'de> for NamedObjectContext {
431    fn raw_decode(buf: &'de [u8]) -> BuckyResult<(Self, &'de [u8])> {
432        let (obj_type, buf) = u16::raw_decode(buf).map_err(|e| {
433            log::error!("NamedObjectContext::raw_decode/obj_type error:{}", e);
434            e
435        })?;
436
437        let (obj_flags, buf) = u16::raw_decode(buf).map_err(|e| {
438            log::error!("NamedObjectContext::raw_decode/obj_flags error:{}", e);
439            e
440        })?;
441
442        Ok((NamedObjectContext::new(obj_type, obj_flags), buf))
443    }
444}
445
446#[derive(Clone)]
447pub struct ObjectMutBody<B, O>
448where
449    O: ObjectType,
450    B: BodyContent,
451{
452    prev_version: Option<HashValue>, // 上个版本的MutBody Hash
453    update_time: u64,                // 时间戳
454    content: B,                      // 根据不同的类型,可以有不同的MutBody
455    user_data: Option<Vec<u8>>,      // 可以嵌入任意数据。(比如json?)
456    obj_type: Option<PhantomData<O>>,
457}
458
459impl<B, O> std::fmt::Debug for ObjectMutBody<B, O>
460where
461    B: std::fmt::Debug + BodyContent,
462    O: ObjectType,
463{
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        write!(
466            f,
467            "ObjectMutBody:{{ prev_version:{:?}, update_time:{}, version={}, format={}, content:{:?}, user_data: ... }}",
468            self.prev_version, self.update_time, self.content.version(), self.content.format(), self.content,
469        )
470    }
471}
472
473#[derive(Clone)]
474pub struct ObjectMutBodyBuilder<B, O>
475where
476    O: ObjectType,
477    B: BodyContent,
478{
479    prev_version: Option<HashValue>,
480    update_time: u64,
481    content: B,
482    user_data: Option<Vec<u8>>,
483    obj_type: Option<PhantomData<O>>,
484}
485
486impl<B, O> ObjectMutBodyBuilder<B, O>
487where
488    B: BodyContent,
489    O: ObjectType,
490{
491    pub fn new(content: B) -> Self {
492        Self {
493            prev_version: None,
494            update_time: bucky_time_now(),
495            content,
496            user_data: None,
497            obj_type: None,
498        }
499    }
500
501    pub fn update_time(mut self, value: u64) -> Self {
502        self.update_time = value;
503        self
504    }
505
506    pub fn option_update_time(mut self, value: Option<u64>) -> Self {
507        if value.is_some() {
508            self.update_time = value.unwrap();
509        }
510
511        self
512    }
513
514    pub fn prev_version(mut self, value: HashValue) -> Self {
515        self.prev_version = Some(value);
516        self
517    }
518
519    pub fn option_prev_version(mut self, value: Option<HashValue>) -> Self {
520        self.prev_version = value;
521        self
522    }
523
524    pub fn user_data(mut self, value: Vec<u8>) -> Self {
525        self.user_data = Some(value);
526        self
527    }
528
529    pub fn option_user_data(mut self, value: Option<Vec<u8>>) -> Self {
530        self.user_data = value;
531        self
532    }
533
534    pub fn build(self) -> ObjectMutBody<B, O> {
535        ObjectMutBody::<B, O> {
536            prev_version: self.prev_version,
537            update_time: self.update_time,
538            content: self.content,
539            user_data: self.user_data,
540            obj_type: self.obj_type,
541        }
542    }
543}
544
545impl<B, O> ObjectMutBody<B, O>
546where
547    B: BodyContent,
548    O: ObjectType,
549{
550    //pub fn new(content: B) -> ObjectMutBodyBuilder<B, O> {
551    //    ObjectMutBodyBuilder::<B, O>::new(content)
552    //}
553
554    // 只读接口
555
556    pub fn prev_version(&self) -> &Option<HashValue> {
557        &self.prev_version
558    }
559
560    pub fn update_time(&self) -> u64 {
561        self.update_time
562    }
563
564    pub fn content(&self) -> &B {
565        &self.content
566    }
567
568    pub fn into_content(self) -> B {
569        self.content
570    }
571
572    pub fn user_data(&self) -> &Option<Vec<u8>> {
573        &self.user_data
574    }
575
576    // 编辑接口
577
578    pub fn set_update_time(&mut self, value: u64) {
579        self.update_time = value;
580    }
581
582    // 更新时间,并且确保大于旧时间
583    pub fn increase_update_time(&mut self, mut value: u64) {
584        if value < self.update_time {
585            warn!(
586                "object body new time is older than current time! now={}, cur={}",
587                value, self.update_time
588            );
589            value = self.update_time + 1;
590        }
591
592        self.set_update_time(value);
593    }
594
595    pub fn content_mut(&mut self) -> &mut B {
596        &mut self.content
597    }
598
599    pub fn set_userdata(&mut self, user_data: &[u8]) {
600        let buf = Vec::from(user_data);
601        self.user_data = Some(buf);
602        self.increase_update_time(bucky_time_now());
603    }
604
605    /// 拆解Body,Move出内部数据
606    /// ===
607    /// * content: O::ContentType,
608    /// * update_time: u64,
609    /// * prev_version: Option<HashValue>,
610    /// * user_data: Option<Vec<u8>>,
611    pub fn split(self) -> (B, u64, Option<HashValue>, Option<Vec<u8>>) {
612        let content = self.content;
613        let update_time = self.update_time;
614        let prev_version = self.prev_version;
615        let user_data = self.user_data;
616        (content, update_time, prev_version, user_data)
617    }
618}
619
620impl<B, O> ObjectMutBody<B, O>
621where
622    B: RawEncode + BodyContent,
623    O: ObjectType,
624{
625    pub fn calculate_hash(&self) -> BuckyResult<HashValue> {
626        let hash = self.raw_hash_value().map_err(|e| {
627            log::error!(
628                "ObjectMutBody<B, O>::calculate_hash/raw_hash_value error:{}",
629                e
630            );
631            e
632        })?;
633
634        Ok(hash)
635    }
636}
637
638impl<'de, B, O> Default for ObjectMutBody<B, O>
639where
640    B: RawEncode + RawDecode<'de> + Default + BodyContent,
641    O: ObjectType,
642{
643    fn default() -> Self {
644        Self {
645            prev_version: None,
646            update_time: 0,
647            content: B::default(),
648            user_data: None,
649            obj_type: None,
650        }
651    }
652}
653
654impl<'de, B, O> RawEncodeWithContext<NamedObjectBodyContext> for ObjectMutBody<B, O>
655where
656    B: RawEncode + BodyContent,
657    O: ObjectType,
658{
659    fn raw_measure_with_context(
660        &self,
661        ctx: &mut NamedObjectBodyContext,
662        purpose: &Option<RawEncodePurpose>,
663    ) -> BuckyResult<usize> {
664        // body_flags
665        let mut size = u8::raw_bytes().unwrap();
666
667        // prev_version
668        if self.prev_version.is_some() {
669            size = size
670                + self
671                    .prev_version
672                    .unwrap()
673                    .raw_measure(purpose)
674                    .map_err(|e| {
675                        log::error!("ObjectMutBody<B, O>::raw_measure/prev_version error:{}", e);
676                        e
677                    })?;
678        }
679
680        // update_time
681        size += u64::raw_bytes().unwrap();
682
683        // verison+format
684        size += u16::raw_bytes().unwrap();
685
686        // content,包含usize+content
687        let body_size = self.content.raw_measure(purpose).map_err(|e| {
688            log::error!("ObjectMutBody<B, O>::raw_measure/content error:{}", e);
689            e
690        })?;
691        size += USize(body_size).raw_measure(purpose)?;
692        size += body_size;
693
694        // 缓存body_size
695        ctx.cache_body_content_size(body_size);
696
697        // user_data
698        let ud = self.user_data.as_ref();
699        let ud_size = if ud.is_some() {
700            let ud = ud.unwrap();
701            let len = ud.len();
702            u64::raw_bytes().unwrap() + len
703        } else {
704            0usize
705        };
706
707        size = size + ud_size;
708
709        Ok(size)
710    }
711
712    fn raw_encode_with_context<'a>(
713        &self,
714        buf: &'a mut [u8],
715        ctx: &mut NamedObjectBodyContext,
716        purpose: &Option<RawEncodePurpose>,
717    ) -> BuckyResult<&'a mut [u8]> {
718        /*
719        let size = self.raw_measure(purpose).unwrap();
720        if buf.len() < size {
721            let message = format!("[raw_encode] not enough buffer for ObjectMutBody, obj_type:{}, obj_type_code:{:?}", O::obj_type(), O::obj_type_code());
722            return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, message));
723        }
724        */
725
726        let ud = self.user_data.as_ref();
727
728        // body_flags
729        let mut body_flags = 0u8;
730        if self.prev_version().is_some() {
731            body_flags |= OBJECT_BODY_FLAG_PREV;
732        }
733        if ud.is_some() {
734            body_flags |= OBJECT_BODY_FLAG_USER_DATA;
735        }
736
737        // 默认都添加版本信息,不再占用flags字段
738        let buf = body_flags.raw_encode(buf, purpose).map_err(|e| {
739            log::error!("ObjectMutBody<B, O>::raw_encode/body_flags error:{}", e);
740            e
741        })?;
742
743        // prev_version
744        let buf = if self.prev_version().is_some() {
745            let buf = self
746                .prev_version
747                .unwrap()
748                .raw_encode(buf, purpose)
749                .map_err(|e| {
750                    log::error!("ObjectMutBody<B, O>::raw_encode/prev_version error:{}", e);
751                    e
752                })?;
753            buf
754        } else {
755            buf
756        };
757
758        // update_time
759        let buf = self.update_time.raw_encode(buf, purpose).map_err(|e| {
760            log::error!("ObjectMutBody<B, O>::raw_encode/update_time error:{}", e);
761            e
762        })?;
763
764        // version+format
765        let buf = self
766            .content
767            .version()
768            .raw_encode(buf, purpose)
769            .map_err(|e| {
770                log::error!("ObjectMutBody<B, O>::raw_encode/version error:{}", e);
771                e
772            })?;
773        let buf = self
774            .content
775            .format()
776            .raw_encode(buf, purpose)
777            .map_err(|e| {
778                log::error!("ObjectMutBody<B, O>::raw_encode/version error:{}", e);
779                e
780            })?;
781
782        // content,包含usize+content
783        let buf = {
784            let body_size = ctx.get_body_content_cached_size();
785
786            let buf = USize(body_size).raw_encode(buf, purpose).map_err(|e| {
787                log::error!("ObjectMutBody<B, O>::raw_encode/content_usize error:{}", e);
788                e
789            })?;
790
791            // 对bodycontent编码,采用精确大小的buf
792            let body_buf = &mut buf[..body_size];
793            let left_buf = self.content.raw_encode(body_buf, purpose).map_err(|e| {
794                log::error!("ObjectMutBody<B, O>::raw_encode/content error:{}", e);
795                e
796            })?;
797
798            if left_buf.len() != 0 {
799                warn!("encode body content by remaining buf is not empty! obj_type={}, body_size={}, remaining={}", O::obj_type(), body_size, left_buf.len());
800                // assert!(left_buf.len() == 0);
801            }
802
803            &mut buf[body_size..]
804        };
805
806        // user_data
807        let buf = if ud.is_some() {
808            let ud = ud.unwrap();
809            let len = ud.len();
810            let buf = (len as u64).raw_encode(buf, purpose).map_err(|e| {
811                log::error!("ObjectMutBody<B, O>::raw_encode/user_data len error:{}", e);
812                e
813            })?;
814
815            buf[..len].copy_from_slice(ud.as_slice());
816            &mut buf[len..]
817        } else {
818            buf
819        };
820
821        Ok(buf)
822    }
823}
824
825impl<'de, B, O> RawDecodeWithContext<'de, &NamedObjectBodyContext> for ObjectMutBody<B, O>
826where
827    B: RawDecode<'de> + BodyContent,
828    O: ObjectType,
829{
830    fn raw_decode_with_context(
831        buf: &'de [u8],
832        _ctx: &NamedObjectBodyContext,
833    ) -> BuckyResult<(Self, &'de [u8])> {
834        // body_flags
835        let (body_flags, buf) = u8::raw_decode(buf).map_err(|e| {
836            let msg = format!("ObjectMutBody<B, O>::raw_decode/body_flags error:{}", e);
837            error!("{}", msg);
838            BuckyError::new(BuckyErrorCode::InvalidData, msg)
839        })?;
840
841        // prev_version
842        let (prev_version, buf) = if (body_flags & OBJECT_BODY_FLAG_PREV) == OBJECT_BODY_FLAG_PREV {
843            let (prev_version, buf) = HashValue::raw_decode(buf).map_err(|e| {
844                let msg = format!("ObjectMutBody<B, O>::raw_decode/prev_version error:{}", e);
845                error!("{}", msg);
846                BuckyError::new(BuckyErrorCode::InvalidData, msg)
847            })?;
848            (Some(prev_version), buf)
849        } else {
850            (None, buf)
851        };
852
853        // update_time
854        let (update_time, buf) = u64::raw_decode(buf).map_err(|e| {
855            let msg = format!(
856                "ObjectMutBody<B, O>::raw_decode/update_time error:{}, body={}",
857                e,
858                B::debug_info()
859            );
860            error!("{}", msg);
861            BuckyError::new(BuckyErrorCode::InvalidData, msg)
862        })?;
863
864        // 这里尝试读取是否存在ext扩展字段,如果存在那么为了向前兼容要跳过
865        let buf = if (body_flags & OBJECT_BODY_FLAG_EXT) == OBJECT_BODY_FLAG_EXT {
866            let (len, buf) = u16::raw_decode(buf).map_err(|e| {
867                let msg = format!(
868                    "ObjectMutBody<B, O>::raw_decode/ext error:{}, body={}",
869                    e,
870                    B::debug_info()
871                );
872                error!("{}", msg);
873                BuckyError::new(BuckyErrorCode::InvalidData, msg)
874            })?;
875            warn!(
876                "read unknown body ext content! len={}, body={}",
877                len,
878                B::debug_info()
879            );
880
881            if len as usize > buf.len() {
882                let msg = format!("read unknown body ext content but extend buffer limit, body={}, len={}, buf={}", B::debug_info(), len, buf.len());
883                error!("{}", msg);
884                return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, msg));
885            }
886
887            // 跳过指定的长度
888            &buf[len as usize..]
889        } else {
890            buf
891        };
892
893        // version
894        let (version, buf) = u8::raw_decode(buf).map_err(|e| {
895            let msg = format!("ObjectMutBody<B, O>::raw_decode/version error:{}", e);
896            error!("{}", msg);
897            BuckyError::new(BuckyErrorCode::InvalidData, msg)
898        })?;
899
900        // format
901        let (format, buf) = u8::raw_decode(buf).map_err(|e| {
902            let msg = format!("ObjectMutBody<B, O>::raw_decode/format error:{}", e);
903            error!("{}", msg);
904            BuckyError::new(BuckyErrorCode::InvalidData, msg)
905        })?;
906
907        // 对于BodyContent,使用带option的解码,用以兼容老版本的解码
908        let opt = RawDecodeOption { version, format };
909
910        // body content
911        let (content, buf) = {
912            let (body_size, buf) = USize::raw_decode(buf).map_err(|e| {
913                let msg = format!(
914                    "ObjectMutBody<B, O>::raw_decode/content_usize error:{}, body={}",
915                    e,
916                    B::debug_info()
917                );
918                error!("{}", msg);
919                BuckyError::new(BuckyErrorCode::InvalidData, msg)
920            })?;
921
922            let body_size = body_size.value();
923            if buf.len() < body_size {
924                let msg = format!(
925                    "invalid body content buffer size: expect={}, buf={}, body={}",
926                    body_size,
927                    buf.len(),
928                    B::debug_info(),
929                );
930                error!("{}", msg);
931                return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, msg));
932            }
933
934            // 使用精确大小的buffer解码
935            let body_buf = &buf[..body_size];
936            let (content, left_buf) = B::raw_decode_with_option(&body_buf, &opt).map_err(|e| {
937                let msg = format!(
938                    "ObjectMutBody<B, O>::raw_decode/content error:{}, body={}",
939                    e,
940                    B::debug_info()
941                );
942                error!("{}", msg);
943                BuckyError::new(BuckyErrorCode::InvalidData, msg)
944            })?;
945
946            if left_buf.len() != 0 {
947                warn!("decode body content by remaining buf is not empty! obj_type={}, body_size={}, remaining={}", O::obj_type(), body_size, left_buf.len());
948                // assert!(left_buf.len() == 0);
949            }
950
951            (content, &buf[body_size..])
952        };
953
954        // user_data
955        let (user_data, buf) = if (body_flags & OBJECT_BODY_FLAG_USER_DATA)
956            == OBJECT_BODY_FLAG_USER_DATA
957        {
958            let (len, buf) = u64::raw_decode(buf).map_err(|e| {
959                let msg = format!(
960                    "ObjectMutBody<B, O>::raw_decode/user_data len error:{}, body={}",
961                    e,
962                    B::debug_info()
963                );
964                error!("{}", msg);
965                BuckyError::new(BuckyErrorCode::InvalidData, msg)
966            })?;
967
968            let bytes = len as usize;
969            if bytes > buf.len() {
970                let msg = format!("ObjectMutBody<B, O>::raw_decode/user_data len overflow: body={}, len={}, left={}",
971                        B::debug_info(),
972                        len,
973                        buf.len()
974                    );
975                error!("{}", msg);
976                return Err(BuckyError::new(BuckyErrorCode::InvalidData, msg));
977            }
978
979            let mut user_data = vec![0u8; bytes];
980            user_data.copy_from_slice(&buf[..bytes]);
981            (Some(user_data), &buf[bytes..])
982        } else {
983            (None, buf)
984        };
985
986        Ok((
987            Self {
988                prev_version,
989                update_time,
990                content,
991                user_data,
992                obj_type: None,
993            },
994            buf,
995        ))
996    }
997}
998
999impl<'de, B, O> RawEncode for ObjectMutBody<B, O>
1000where
1001    B: RawEncode + BodyContent,
1002    O: ObjectType,
1003{
1004    fn raw_measure(&self, _purpose: &Option<RawEncodePurpose>) -> BuckyResult<usize> {
1005        unimplemented!();
1006    }
1007
1008    fn raw_encode<'a>(
1009        &self,
1010        _buf: &'a mut [u8],
1011        _purpose: &Option<RawEncodePurpose>,
1012    ) -> BuckyResult<&'a mut [u8]> {
1013        unimplemented!();
1014    }
1015
1016    fn raw_hash_encode(&self) -> BuckyResult<Vec<u8>> {
1017        let mut ctx = NamedObjectBodyContext::new();
1018        let size = self.raw_measure_with_context(&mut ctx, &Some(RawEncodePurpose::Hash)).map_err(|e|{
1019            error!("ObjectMutBody<B, O>::rraw_measure_with_context error:{}, obj_type:{}, obj_type_code:{:?}", e, O::obj_type(), O::obj_type_code());
1020            e
1021        })?;
1022
1023        let mut buf = vec![0u8; size];
1024        let left_buf = self.raw_encode_with_context(&mut buf, &mut ctx, &Some(RawEncodePurpose::Hash)).map_err(|e|{
1025            error!("ObjectMutBody<B, O>::raw_encode/self.raw_encode_with_context error:{}, obj_type:{}, obj_type_code:{:?}", e, O::obj_type(), O::obj_type_code());
1026            e
1027        })?;
1028
1029        if left_buf.len() != 0 {
1030            warn!("encode body content by remaining buf is not empty! obj_type={}, body_size={}, remaining={}", O::obj_type(), size, left_buf.len());
1031            // assert!(left_buf.len() == 0);
1032        }
1033
1034        Ok(buf)
1035    }
1036}
1037
1038impl<'de, B, O> RawDecode<'de> for ObjectMutBody<B, O>
1039where
1040    B: RawDecode<'de> + BodyContent,
1041    O: ObjectType,
1042{
1043    fn raw_decode(buf: &'de [u8]) -> BuckyResult<(Self, &'de [u8])> {
1044        let ctx = NamedObjectBodyContext::new();
1045        Self::raw_decode_with_context(buf, &ctx)
1046    }
1047}
1048
1049pub trait NamedObject<O>
1050where
1051    O: ObjectType,
1052    O::ContentType: BodyContent,
1053{
1054    fn obj_flags(&self) -> u16;
1055
1056    fn desc(&self) -> &O::DescType;
1057
1058    fn desc_mut(&mut self) -> &mut O::DescType;
1059
1060    fn body(&self) -> &Option<ObjectMutBody<O::ContentType, O>>;
1061
1062    fn body_expect(&self, msg: &str) -> &ObjectMutBody<O::ContentType, O> {
1063        let msg = format!("expect obj_type {} body failed, msg:{}", O::obj_type(), msg);
1064        self.body().as_ref().expect(&msg)
1065    }
1066
1067    fn body_mut(&mut self) -> &mut Option<ObjectMutBody<O::ContentType, O>>;
1068
1069    fn body_mut_expect(&mut self, msg: &str) -> &mut ObjectMutBody<O::ContentType, O> {
1070        let msg = format!(
1071            "expect obj_type {} body_mut failed, msg:{}",
1072            O::obj_type(),
1073            msg
1074        );
1075        self.body_mut().as_mut().expect(&msg)
1076    }
1077
1078    fn signs(&self) -> &ObjectSigns;
1079
1080    fn signs_mut(&mut self) -> &mut ObjectSigns;
1081
1082    fn nonce(&self) -> &Option<u128>;
1083
1084    // 获取body和sign部分的最新的修改时间
1085    fn latest_update_time(&self) -> u64 {
1086        let update_time = match self.body() {
1087            Some(body) => body.update_time(),
1088            None => 0_u64,
1089        };
1090
1091        // 如果签名时间比较新,那么取签名时间
1092        let latest_sign_time = self.signs().latest_sign_time();
1093
1094        std::cmp::max(update_time, latest_sign_time)
1095    }
1096}
1097
1098// TODO concat_idents!目前是unstable功能
1099#[macro_export]
1100macro_rules! declare_object {
1101    ($name:ident) => {
1102        type concat_idents!($name, Type) = cyfs_base::NamedObjType<concat_idents!($name, DescContent), concat_idents!($name, BodyContent)>;
1103        type concat_idents!($name, Builder) = cyfs_base::NamedObjectBuilder<concat_idents!($name, DescContent), concat_idents!($name, BodyContent)>;
1104
1105        type concat_idents!($name, Id) = cyfs_base::NamedObjectId<concat_idents!($name, Type)>;
1106        type concat_idents!($name, Desc) = cyfs_base::NamedObjectDesc<concat_idents!($name, DescContent)>;
1107        type $name = cyfs_base::NamedObjectBase<concat_idents!($name,Type)>;
1108    }
1109}