bucky_objects/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    // Default implementation, from obj_type to 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    // calculate object_id with desc
36    fn calculate_id(&self) -> ObjectId;
37
38    // Get the dec-id(object-id) of the DECApp to which it belongs
39    fn dec_id(&self) -> &Option<ObjectId>;
40
41    // List of linked objects
42    fn ref_objs(&self) -> &Option<Vec<ObjectLink>>;
43
44    // Previous version number
45    fn prev(&self) -> &Option<ObjectId>;
46
47    // The associated hash at the time of creation, e.g. BTC Transaction hash
48    fn create_timestamp(&self) -> &Option<HashValue>;
49
50    // Created timestamp, or return 0 if it does not exist
51    fn create_time(&self) -> u64;
52    fn option_create_time(&self) -> Option<u64>;
53
54    // Expiration timestamp
55    fn expired_time(&self) -> Option<u64>;
56}
57
58/// Authorized-Object, maybe oneof PublicKey::Single or PublicKey::MN
59pub trait PublicKeyObjectDesc {
60    fn public_key_ref(&self) -> Option<PublicKeyRef>;
61}
62
63/// Single public key Authorized object, explicitly using the PublicKey::Single type
64/// The object that implements the Trait must also implement the PublicKeyObjectDesc
65pub trait SingleKeyObjectDesc: PublicKeyObjectDesc {
66    fn public_key(&self) -> &PublicKey;
67}
68
69/// Multi public key Authorized object, explicitly using the PublicKey::MN type
70/// The object that implements the Trait must also implement the PublicKeyObjectDesc
71pub trait MNKeyObjectDesc: PublicKeyObjectDesc {
72    fn mn_public_key(&self) -> &MNPublicKey;
73}
74
75/// Owned-Object
76pub trait OwnerObjectDesc {
77    fn owner(&self) -> &Option<ObjectId>;
78}
79
80/// Object with author
81pub trait AuthorObjectDesc {
82    fn author(&self) -> &Option<ObjectId>;
83}
84
85/// Object with area
86pub trait AreaObjectDesc {
87    fn area(&self) -> &Option<Area>;
88}
89
90// obj_flags: u16
91// ========
92// * The first 5 bits are used to indicate the codec status and are not counted in the hash calculation. (Always fill in 0 when calculating)
93// * The remaining 11bits are used to identify the desc header
94//
95// Object segment codec flags
96// --------
97// 0:  If encrypted crypto (now the encryption structure is not defined, must fill in 0)
98// 1:  If contains mut_body
99// 2:  If contains desc_signs
100// 3:  If contains body_signs
101// 4:  If contains nonce
102//
103// ObjectDesc codec flags
104// --------
105// 5:  If contains dec_id
106// 6:  If contains ref_objecs
107// 7:  If contains prev
108// 8:  If contains create_timestamp
109// 9:  If contains create_time
110// 10: If contains expired_time
111//
112// OwnerObjectDesc/AreaObjectDesc/AuthorObjectDesc/PublicKeyObjectDesc 标志位
113// ---------
114// 11: If contains owner
115// 12: If contains area
116// 13: If contains author
117// 14: If contains public_key
118// 15: If contains ext
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// If contains the ext field, reserved for the non-DescContent part of the extension, including a u16 length + the corresponding content
138pub const OBJECT_FLAG_EXT: u16 = 0x01 << 15;
139
140// Object type interval definition, [start, end)
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
156// Whether include extended fields, in the same format as desc
157pub const OBJECT_BODY_FLAG_EXT: u8 = 0x01 << 2;
158
159#[derive(Clone, Debug)]
160pub struct NamedObjectBodyContext {
161    body_content_cached_size: Option<usize>,
162}
163
164impl NamedObjectBodyContext {
165    pub fn new() -> Self {
166        Self {
167            body_content_cached_size: None,
168        }
169    }
170
171    pub fn cache_body_content_size(&mut self, size: usize) -> &mut Self {
172        assert!(self.body_content_cached_size.is_none());
173        self.body_content_cached_size = Some(size);
174        self
175    }
176
177    pub fn get_body_content_cached_size(&self) -> usize {
178        self.body_content_cached_size.unwrap()
179    }
180}
181
182#[derive(Clone, Debug)]
183pub struct NamedObjectContext {
184    obj_type: u16,
185    obj_flags: u16,
186    obj_type_code: ObjectTypeCode,
187
188    // DescContent缓存的大小
189    desc_content_cached_size: Option<u16>,
190
191    body_context: NamedObjectBodyContext,
192}
193
194impl NamedObjectContext {
195    pub fn new(obj_type: u16, obj_flags: u16) -> Self {
196        let obj_type_code = obj_type.into();
197        Self {
198            obj_type,
199            obj_flags,
200            obj_type_code,
201            desc_content_cached_size: None,
202            body_context: NamedObjectBodyContext::new(),
203        }
204    }
205
206    pub fn obj_type_code(&self) -> ObjectTypeCode {
207        self.obj_type_code.clone()
208    }
209
210    pub fn obj_type(&self) -> u16 {
211        self.obj_type
212    }
213
214    pub fn obj_flags(&self) -> u16 {
215        self.obj_flags
216    }
217
218    pub fn is_standard_object(&self) -> bool {
219        object_type_helper::is_standard_object(self.obj_type)
220    }
221
222    pub fn is_core_object(&self) -> bool {
223        object_type_helper::is_core_object(self.obj_type)
224    }
225
226    pub fn is_decapp_object(&self) -> bool {
227        object_type_helper::is_dec_app_object(self.obj_type)
228    }
229
230    //
231    // common
232    //
233
234    pub fn with_crypto(&mut self) -> &mut Self {
235        self.obj_flags = self.obj_flags | OBJECT_FLAG_CTYPTO;
236        self
237    }
238
239    pub fn has_crypto(&self) -> bool {
240        self.has_flag(OBJECT_FLAG_CTYPTO)
241    }
242
243    pub fn with_mut_body(&mut self) -> &mut Self {
244        self.obj_flags = self.obj_flags | OBJECT_FLAG_MUT_BODY;
245        self
246    }
247
248    pub fn has_mut_body(&self) -> bool {
249        self.has_flag(OBJECT_FLAG_MUT_BODY)
250    }
251
252    pub fn with_desc_signs(&mut self) -> &mut Self {
253        self.obj_flags = self.obj_flags | OBJECT_FLAG_DESC_SIGNS;
254        self
255    }
256
257    pub fn has_desc_signs(&self) -> bool {
258        self.has_flag(OBJECT_FLAG_DESC_SIGNS)
259    }
260
261    pub fn with_body_signs(&mut self) -> &mut Self {
262        self.obj_flags = self.obj_flags | OBJECT_FLAG_BODY_SIGNS;
263        self
264    }
265
266    pub fn has_body_signs(&self) -> bool {
267        self.has_flag(OBJECT_FLAG_BODY_SIGNS)
268    }
269
270    pub fn with_nonce(&mut self) -> &mut Self {
271        self.obj_flags = self.obj_flags | OBJECT_FLAG_NONCE;
272        self
273    }
274
275    pub fn has_nonce(&self) -> bool {
276        self.has_flag(OBJECT_FLAG_NONCE)
277    }
278
279    //
280    // ObjectDesc
281    //
282
283    pub fn with_dec_id(&mut self) -> &mut Self {
284        self.obj_flags = self.obj_flags | OBJECT_FLAG_DESC_ID;
285        self
286    }
287
288    pub fn has_dec_id(&self) -> bool {
289        self.has_flag(OBJECT_FLAG_DESC_ID)
290    }
291
292    pub fn with_ref_objects(&mut self) -> &mut Self {
293        self.obj_flags = self.obj_flags | OBJECT_FLAG_REF_OBJECTS;
294        self
295    }
296
297    pub fn has_ref_objects(&self) -> bool {
298        self.has_flag(OBJECT_FLAG_REF_OBJECTS)
299    }
300
301    pub fn with_prev(&mut self) -> &mut Self {
302        self.obj_flags = self.obj_flags | OBJECT_FLAG_PREV;
303        self
304    }
305
306    pub fn has_prev(&self) -> bool {
307        self.has_flag(OBJECT_FLAG_PREV)
308    }
309
310    pub fn with_create_timestamp(&mut self) -> &mut Self {
311        self.obj_flags = self.obj_flags | OBJECT_FLAG_CREATE_TIMESTAMP;
312        self
313    }
314
315    pub fn has_create_time_stamp(&self) -> bool {
316        self.has_flag(OBJECT_FLAG_CREATE_TIMESTAMP)
317    }
318
319    pub fn with_create_time(&mut self) -> &mut Self {
320        self.obj_flags = self.obj_flags | OBJECT_FLAG_CREATE_TIME;
321        self
322    }
323
324    pub fn has_create_time(&self) -> bool {
325        self.has_flag(OBJECT_FLAG_CREATE_TIME)
326    }
327
328    pub fn with_expired_time(&mut self) -> &mut Self {
329        self.obj_flags = self.obj_flags | OBJECT_FLAG_EXPIRED_TIME;
330        self
331    }
332
333    pub fn has_expired_time(&self) -> bool {
334        self.has_flag(OBJECT_FLAG_EXPIRED_TIME)
335    }
336
337    //
338    // OwnderObjectDesc/AreaObjectDesc/AuthorObjectDesc/PublicKeyObjectDesc
339    //
340
341    pub fn with_owner(&mut self) -> &mut Self {
342        self.obj_flags = self.obj_flags | OBJECT_FLAG_OWNER;
343        self
344    }
345
346    pub fn has_owner(&self) -> bool {
347        self.has_flag(OBJECT_FLAG_OWNER)
348    }
349
350    pub fn with_area(&mut self) -> &mut Self {
351        self.obj_flags = self.obj_flags | OBJECT_FLAG_AREA;
352        self
353    }
354
355    pub fn has_area(&self) -> bool {
356        self.has_flag(OBJECT_FLAG_AREA)
357    }
358
359    pub fn with_public_key(&mut self) -> &mut Self {
360        self.obj_flags = self.obj_flags | OBJECT_FLAG_PUBLIC_KEY;
361        self
362    }
363
364    pub fn has_public_key(&self) -> bool {
365        self.has_flag(OBJECT_FLAG_PUBLIC_KEY)
366    }
367
368    pub fn with_author(&mut self) -> &mut Self {
369        self.obj_flags = self.obj_flags | OBJECT_FLAG_AUTHOR;
370        self
371    }
372
373    pub fn has_author(&self) -> bool {
374        self.has_flag(OBJECT_FLAG_AUTHOR)
375    }
376
377    pub fn has_ext(&self) -> bool {
378        self.has_flag(OBJECT_FLAG_EXT)
379    }
380
381    // desc_content's cache size during codec
382    pub fn cache_desc_content_size(&mut self, size: u16) -> &mut Self {
383        assert!(self.desc_content_cached_size.is_none());
384        self.desc_content_cached_size = Some(size);
385        self
386    }
387
388    pub fn get_desc_content_cached_size(&self) -> u16 {
389        self.desc_content_cached_size.unwrap()
390    }
391
392    // body_context
393    pub fn body_context(&self) -> &NamedObjectBodyContext {
394        &self.body_context
395    }
396
397    pub fn mut_body_context(&mut self) -> &mut NamedObjectBodyContext {
398        &mut self.body_context
399    }
400
401    // inner
402    fn has_flag(&self, flag_pos: u16) -> bool {
403        (self.obj_flags & flag_pos) == flag_pos
404    }
405}
406
407impl RawEncode for NamedObjectContext {
408    fn raw_measure(&self, _purpose: &Option<RawEncodePurpose>) -> BuckyResult<usize> {
409        Ok(u16::raw_bytes().unwrap() * 2)
410    }
411
412    fn raw_encode<'a>(
413        &self,
414        buf: &'a mut [u8],
415        purpose: &Option<RawEncodePurpose>,
416    ) -> BuckyResult<&'a mut [u8]> {
417        let buf = self.obj_type.raw_encode(buf, purpose).map_err(|e| {
418            log::error!("NamedObjectContext::raw_encode/obj_type error:{}", e);
419            e
420        })?;
421
422        let buf = self.obj_flags.raw_encode(buf, purpose).map_err(|e| {
423            log::error!("NamedObjectContext::raw_encode/obj_flags error:{}", e);
424            e
425        })?;
426
427        Ok(buf)
428    }
429}
430
431impl<'de> RawDecode<'de> for NamedObjectContext {
432    fn raw_decode(buf: &'de [u8]) -> BuckyResult<(Self, &'de [u8])> {
433        let (obj_type, buf) = u16::raw_decode(buf).map_err(|e| {
434            log::error!("NamedObjectContext::raw_decode/obj_type error:{}", e);
435            e
436        })?;
437
438        let (obj_flags, buf) = u16::raw_decode(buf).map_err(|e| {
439            log::error!("NamedObjectContext::raw_decode/obj_flags error:{}", e);
440            e
441        })?;
442
443        Ok((NamedObjectContext::new(obj_type, obj_flags), buf))
444    }
445}
446
447#[derive(Clone, Debug)]
448pub struct ObjectBodyExt {
449    // The object_id of the associated desc
450    object_id: Option<ObjectId>,
451}
452
453impl Default for ObjectBodyExt {
454    fn default() -> Self {
455        Self { object_id: None }
456    }
457}
458
459impl ObjectBodyExt {
460    pub fn is_empty(&self) -> bool {
461        self.object_id.is_none()
462    }
463}
464
465// object body ext should use protobuf for codec
466impl TryFrom<protos::ObjectBodyExt> for ObjectBodyExt {
467    type Error = BuckyError;
468
469    fn try_from(value: protos::ObjectBodyExt) -> BuckyResult<Self> {
470        let mut ret = Self { object_id: None };
471
472        if value.has_object_id() {
473            ret.object_id = Some(ObjectId::clone_from_slice(value.get_object_id())?);
474        }
475
476        Ok(ret)
477    }
478}
479
480impl TryFrom<&ObjectBodyExt> for protos::ObjectBodyExt {
481    type Error = BuckyError;
482
483    fn try_from(value: &ObjectBodyExt) -> BuckyResult<Self> {
484        let mut ret = Self::new();
485
486        if let Some(object_id) = &value.object_id {
487            ret.set_object_id(object_id.to_vec()?);
488        }
489
490        Ok(ret)
491    }
492}
493
494crate::inner_impl_default_protobuf_raw_codec!(ObjectBodyExt);
495
496
497#[derive(Clone)]
498pub struct ObjectMutBody<B, O>
499where
500    O: ObjectType,
501    B: BodyContent,
502{
503    prev_version: Option<HashValue>, // Perv versions's ObjectMutBody Hash
504    update_time: u64, // Record the timestamp of the last update of body, in bucky time format
505    content: B,       // Depending on the type, there can be different MutBody
506    user_data: Option<Vec<u8>>, // Any data can be embedded. (e.g. json?)
507    ext: Option<ObjectBodyExt>,
508    obj_type: Option<PhantomData<O>>,
509}
510
511impl<B, O> std::fmt::Debug for ObjectMutBody<B, O>
512where
513    B: std::fmt::Debug + BodyContent,
514    O: ObjectType,
515{
516    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517        write!(
518            f,
519            "ObjectMutBody:{{ prev_version={:?}, update_time={}, version={}, format={}, content={:?}, ext={:?} user_data: ... }}",
520            self.prev_version, self.update_time, self.content.version(), self.content.format(), self.content, self.ext,
521        )
522    }
523}
524
525#[derive(Clone)]
526pub struct ObjectMutBodyBuilder<B, O>
527where
528    O: ObjectType,
529    B: BodyContent,
530{
531    prev_version: Option<HashValue>,
532    update_time: u64,
533    content: B,
534    user_data: Option<Vec<u8>>,
535    ext: ObjectBodyExt,
536    obj_type: Option<PhantomData<O>>,
537}
538
539impl<B, O> ObjectMutBodyBuilder<B, O>
540where
541    B: BodyContent,
542    O: ObjectType,
543{
544    pub fn new(content: B) -> Self {
545        Self {
546            prev_version: None,
547            update_time: bucky_time_now(),
548            content,
549            user_data: None,
550            ext: ObjectBodyExt::default(),
551            obj_type: None,
552        }
553    }
554
555    pub fn update_time(mut self, value: u64) -> Self {
556        self.update_time = value;
557        self
558    }
559
560    pub fn option_update_time(mut self, value: Option<u64>) -> Self {
561        if value.is_some() {
562            self.update_time = value.unwrap();
563        }
564
565        self
566    }
567
568    pub fn prev_version(mut self, value: HashValue) -> Self {
569        self.prev_version = Some(value);
570        self
571    }
572
573    pub fn option_prev_version(mut self, value: Option<HashValue>) -> Self {
574        self.prev_version = value;
575        self
576    }
577
578    pub fn user_data(mut self, value: Vec<u8>) -> Self {
579        self.user_data = Some(value);
580        self
581    }
582
583    pub fn option_user_data(mut self, value: Option<Vec<u8>>) -> Self {
584        self.user_data = value;
585        self
586    }
587
588    pub fn object_id(mut self, value: ObjectId) -> Self {
589        self.ext.object_id = Some(value);
590        self
591    }
592
593    pub fn option_object_id(mut self, value: Option<ObjectId>) -> Self {
594        self.ext.object_id = value;
595        self
596    }
597
598    pub fn build(self) -> ObjectMutBody<B, O> {
599        ObjectMutBody::<B, O> {
600            prev_version: self.prev_version,
601            update_time: self.update_time,
602            content: self.content,
603            user_data: self.user_data,
604            obj_type: self.obj_type,
605            ext: if self.ext.is_empty() {
606                None
607            } else {
608                Some(self.ext)
609            },
610        }
611    }
612}
613
614impl<B, O> ObjectMutBody<B, O>
615where
616    B: BodyContent,
617    O: ObjectType,
618{
619    //pub fn new(content: B) -> ObjectMutBodyBuilder<B, O> {
620    //    ObjectMutBodyBuilder::<B, O>::new(content)
621    //}
622
623    // real only methods
624
625    pub fn prev_version(&self) -> &Option<HashValue> {
626        &self.prev_version
627    }
628
629    pub fn update_time(&self) -> u64 {
630        self.update_time
631    }
632
633    pub fn content(&self) -> &B {
634        &self.content
635    }
636
637    pub fn into_content(self) -> B {
638        self.content
639    }
640
641    pub fn user_data(&self) -> &Option<Vec<u8>> {
642        &self.user_data
643    }
644
645    pub fn object_id(&self) -> &Option<ObjectId> {
646        match &self.ext {
647            Some(ext) => &ext.object_id,
648            None => &None,
649        }
650    }
651
652    pub fn verify_object_id(&self, object_id: &ObjectId) -> BuckyResult<()> {
653        match &self.object_id() {
654            Some(bind_object_id) => {
655                if object_id != bind_object_id {
656                    let msg = format!("object_id and object_id of body binding do not match! body object_id={}, object_id={}", bind_object_id, object_id);
657                    warn!("{}", msg);
658                    Err(BuckyError::new(BuckyErrorCode::Unmatch, msg))
659                } else {
660                    Ok(())
661                }
662            }
663            None => Ok(()),
664        }
665    }
666
667    // Modify relate methods
668
669    pub fn set_update_time(&mut self, value: u64) {
670        self.update_time = value;
671    }
672
673    // Update the last modify time, and make sure it is greater than the old time
674    pub fn increase_update_time(&mut self, mut value: u64) {
675        if value < self.update_time {
676            warn!(
677                "object body new time is older than current time! now={}, cur={}",
678                value, self.update_time
679            );
680            value = self.update_time + 1;
681        }
682
683        self.set_update_time(value);
684    }
685
686    pub fn content_mut(&mut self) -> &mut B {
687        &mut self.content
688    }
689
690    pub fn set_userdata(&mut self, user_data: &[u8]) {
691        let buf = Vec::from(user_data);
692        self.user_data = Some(buf);
693        self.increase_update_time(bucky_time_now());
694    }
695
696    pub fn set_object_id(&mut self, object_id: Option<ObjectId>) {
697        if self.ext.is_none() {
698            self.ext = Some(ObjectBodyExt::default());
699        }
700
701        self.ext.as_mut().unwrap().object_id = object_id;
702    }
703
704    /// Split the Body,Move everything inside
705    /// ===
706    /// * content: O::ContentType,
707    /// * update_time: u64,
708    /// * prev_version: Option<HashValue>,
709    /// * user_data: Option<Vec<u8>>,
710    pub fn split(self) -> (B, u64, Option<HashValue>, Option<Vec<u8>>) {
711        let content = self.content;
712        let update_time = self.update_time;
713        let prev_version = self.prev_version;
714        let user_data = self.user_data;
715        (content, update_time, prev_version, user_data)
716    }
717}
718
719impl<B, O> ObjectMutBody<B, O>
720where
721    B: RawEncode + BodyContent,
722    O: ObjectType,
723{
724    pub fn calculate_hash(&self) -> BuckyResult<HashValue> {
725        let hash = self.raw_hash_value().map_err(|e| {
726            log::error!(
727                "ObjectMutBody<B, O>::calculate_hash/raw_hash_value error:{}",
728                e
729            );
730            e
731        })?;
732
733        Ok(hash)
734    }
735}
736
737impl<'de, B, O> Default for ObjectMutBody<B, O>
738where
739    B: RawEncode + RawDecode<'de> + Default + BodyContent,
740    O: ObjectType,
741{
742    fn default() -> Self {
743        Self {
744            prev_version: None,
745            update_time: 0,
746            content: B::default(),
747            user_data: None,
748            obj_type: None,
749            ext: None,
750        }
751    }
752}
753
754impl<'de, B, O> RawEncodeWithContext<NamedObjectBodyContext> for ObjectMutBody<B, O>
755where
756    B: RawEncode + BodyContent,
757    O: ObjectType,
758{
759    fn raw_measure_with_context(
760        &self,
761        ctx: &mut NamedObjectBodyContext,
762        purpose: &Option<RawEncodePurpose>,
763    ) -> BuckyResult<usize> {
764        // body_flags
765        let mut size = u8::raw_bytes().unwrap();
766
767        // prev_version
768        if self.prev_version.is_some() {
769            size = size
770                + self
771                    .prev_version
772                    .unwrap()
773                    .raw_measure(purpose)
774                    .map_err(|e| {
775                        log::error!("ObjectMutBody<B, O>::raw_measure/prev_version error:{}", e);
776                        e
777                    })?;
778        }
779
780        // update_time
781        size += u64::raw_bytes().unwrap();
782
783        // ext
784        if let Some(ext) = &self.ext {
785            if !ext.is_empty() {
786                size = size
787                    + u16::raw_bytes().unwrap()
788                    + ext.raw_measure(purpose).map_err(|e| {
789                        log::error!("ObjectMutBody<B, O>::raw_measure/ext error:{}", e);
790                        e
791                    })?;
792            }
793        }
794
795        // verison+format
796        size += u16::raw_bytes().unwrap();
797
798        // content,包含usize+content
799        let body_size = self.content.raw_measure(purpose).map_err(|e| {
800            log::error!("ObjectMutBody<B, O>::raw_measure/content error:{}", e);
801            e
802        })?;
803        size += USize(body_size).raw_measure(purpose)?;
804        size += body_size;
805
806        // 缓存body_size
807        ctx.cache_body_content_size(body_size);
808
809        // user_data
810        let ud = self.user_data.as_ref();
811        let ud_size = if ud.is_some() {
812            let ud = ud.unwrap();
813            let len = ud.len();
814            u64::raw_bytes().unwrap() + len
815        } else {
816            0usize
817        };
818
819        size = size + ud_size;
820
821        Ok(size)
822    }
823
824    fn raw_encode_with_context<'a>(
825        &self,
826        buf: &'a mut [u8],
827        ctx: &mut NamedObjectBodyContext,
828        purpose: &Option<RawEncodePurpose>,
829    ) -> BuckyResult<&'a mut [u8]> {
830        /*
831        let size = self.raw_measure(purpose).unwrap();
832        if buf.len() < size {
833            let message = format!("[raw_encode] not enough buffer for ObjectMutBody, obj_type:{}, obj_type_code:{:?}", O::obj_type(), O::obj_type_code());
834            return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, message));
835        }
836        */
837
838        let ud = self.user_data.as_ref();
839
840        // body_flags
841        let mut body_flags = 0u8;
842
843        if self.prev_version().is_some() {
844            body_flags |= OBJECT_BODY_FLAG_PREV;
845        }
846        if ud.is_some() {
847            body_flags |= OBJECT_BODY_FLAG_USER_DATA;
848        }
849
850        let mut encode_ext = false;
851        if let Some(ext) = &self.ext {
852            if !ext.is_empty() {
853                body_flags |= OBJECT_BODY_FLAG_EXT;
854                encode_ext = true;
855            }
856        }
857
858        // Version information is added by default and no longer occupies the flags field
859        let buf = body_flags.raw_encode(buf, purpose).map_err(|e| {
860            log::error!("ObjectMutBody<B, O>::raw_encode/body_flags error:{}", e);
861            e
862        })?;
863
864        // prev_version
865        let buf = if self.prev_version().is_some() {
866            let buf = self
867                .prev_version
868                .unwrap()
869                .raw_encode(buf, purpose)
870                .map_err(|e| {
871                    log::error!("ObjectMutBody<B, O>::raw_encode/prev_version error:{}", e);
872                    e
873                })?;
874            buf
875        } else {
876            buf
877        };
878
879        // update_time
880        let buf = self.update_time.raw_encode(buf, purpose).map_err(|e| {
881            log::error!("ObjectMutBody<B, O>::raw_encode/update_time error:{}", e);
882            e
883        })?;
884
885        // ext
886        let buf = if encode_ext {
887            let ext = self.ext.as_ref().unwrap();
888            let size = ext.raw_measure(purpose)? as u16;
889            let buf = size.raw_encode(buf, purpose).map_err(|e| {
890                log::error!("ObjectMutBody<B, O>::raw_encode/ext error:{}", e);
891                e
892            })?;
893
894            let buf = ext.raw_encode(buf, purpose).map_err(|e| {
895                log::error!("ObjectMutBody<B, O>::raw_encode/ext error:{}", e);
896                e
897            })?;
898            buf
899        } else {
900            buf
901        };
902
903        // version+format
904        let buf = self
905            .content
906            .version()
907            .raw_encode(buf, purpose)
908            .map_err(|e| {
909                log::error!("ObjectMutBody<B, O>::raw_encode/version error:{}", e);
910                e
911            })?;
912        let buf = self
913            .content
914            .format()
915            .raw_encode(buf, purpose)
916            .map_err(|e| {
917                log::error!("ObjectMutBody<B, O>::raw_encode/version error:{}", e);
918                e
919            })?;
920
921        // content, include usize+content
922        let buf = {
923            let body_size = ctx.get_body_content_cached_size();
924
925            let buf = USize(body_size).raw_encode(buf, purpose).map_err(|e| {
926                log::error!("ObjectMutBody<B, O>::raw_encode/content_usize error:{}", e);
927                e
928            })?;
929
930            // 对bodycontent编码,采用精确大小的buf
931            let body_buf = &mut buf[..body_size];
932            let left_buf = self.content.raw_encode(body_buf, purpose).map_err(|e| {
933                log::error!("ObjectMutBody<B, O>::raw_encode/content error:{}", e);
934                e
935            })?;
936
937            if left_buf.len() != 0 {
938                warn!("encode body content by remaining buf is not empty! obj_type={}, body_size={}, remaining={}", O::obj_type(), body_size, left_buf.len());
939                // assert!(left_buf.len() == 0);
940            }
941
942            &mut buf[body_size..]
943        };
944
945        // user_data
946        let buf = if ud.is_some() {
947            let ud = ud.unwrap();
948            let len = ud.len();
949            let buf = (len as u64).raw_encode(buf, purpose).map_err(|e| {
950                log::error!("ObjectMutBody<B, O>::raw_encode/user_data len error:{}", e);
951                e
952            })?;
953
954            buf[..len].copy_from_slice(ud.as_slice());
955            &mut buf[len..]
956        } else {
957            buf
958        };
959
960        Ok(buf)
961    }
962}
963
964impl<'de, B, O> RawDecodeWithContext<'de, &NamedObjectBodyContext> for ObjectMutBody<B, O>
965where
966    B: RawDecode<'de> + BodyContent,
967    O: ObjectType,
968{
969    fn raw_decode_with_context(
970        buf: &'de [u8],
971        _ctx: &NamedObjectBodyContext,
972    ) -> BuckyResult<(Self, &'de [u8])> {
973        // body_flags
974        let (body_flags, buf) = u8::raw_decode(buf).map_err(|e| {
975            let msg = format!("ObjectMutBody<B, O>::raw_decode/body_flags error:{}", e);
976            error!("{}", msg);
977            BuckyError::new(BuckyErrorCode::InvalidData, msg)
978        })?;
979
980        // prev_version
981        let (prev_version, buf) = if (body_flags & OBJECT_BODY_FLAG_PREV) == OBJECT_BODY_FLAG_PREV {
982            let (prev_version, buf) = HashValue::raw_decode(buf).map_err(|e| {
983                let msg = format!("ObjectMutBody<B, O>::raw_decode/prev_version error:{}", e);
984                error!("{}", msg);
985                BuckyError::new(BuckyErrorCode::InvalidData, msg)
986            })?;
987            (Some(prev_version), buf)
988        } else {
989            (None, buf)
990        };
991
992        // update_time
993        let (update_time, buf) = u64::raw_decode(buf).map_err(|e| {
994            let msg = format!(
995                "ObjectMutBody<B, O>::raw_decode/update_time error:{}, body={}",
996                e,
997                B::debug_info()
998            );
999            error!("{}", msg);
1000            BuckyError::new(BuckyErrorCode::InvalidData, msg)
1001        })?;
1002
1003        // Here we try to read if there is an ext extension field, if it exists then we have to skip it for forward compatibility
1004        let mut ext = None;
1005        let buf = if (body_flags & OBJECT_BODY_FLAG_EXT) == OBJECT_BODY_FLAG_EXT {
1006            let (len, buf) = u16::raw_decode(buf).map_err(|e| {
1007                let msg = format!(
1008                    "ObjectMutBody<B, O>::raw_decode/ext error:{}, body={}",
1009                    e,
1010                    B::debug_info()
1011                );
1012                error!("{}", msg);
1013                BuckyError::new(BuckyErrorCode::InvalidData, msg)
1014            })?;
1015            warn!(
1016                "read unknown body ext content! len={}, body={}",
1017                len,
1018                B::debug_info()
1019            );
1020
1021            if len as usize > buf.len() {
1022                let msg = format!("read unknown body ext content but extend buffer limit, body={}, len={}, buf={}", B::debug_info(), len, buf.len());
1023                error!("{}", msg);
1024                return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, msg));
1025            }
1026
1027            if len > 0 {
1028                // Decode using exact size buffer
1029                let ext_buf = &buf[..len as usize];
1030                let (ret, _) = ObjectBodyExt::raw_decode(ext_buf).map_err(|e| {
1031                    let msg = format!(
1032                        "ObjectMutBody<B, O>::raw_decode/ext error:{}, body={}",
1033                        e,
1034                        B::debug_info()
1035                    );
1036                    error!("{}", msg);
1037                    BuckyError::new(BuckyErrorCode::InvalidData, msg)
1038                })?;
1039
1040                ext = Some(ret);
1041            }
1042            
1043            // Skip the specified length
1044            &buf[len as usize..]
1045        } else {
1046            buf
1047        };
1048
1049        // version
1050        let (version, buf) = u8::raw_decode(buf).map_err(|e| {
1051            let msg = format!("ObjectMutBody<B, O>::raw_decode/version error:{}", e);
1052            error!("{}", msg);
1053            BuckyError::new(BuckyErrorCode::InvalidData, msg)
1054        })?;
1055
1056        // format
1057        let (format, buf) = u8::raw_decode(buf).map_err(|e| {
1058            let msg = format!("ObjectMutBody<B, O>::raw_decode/format error:{}", e);
1059            error!("{}", msg);
1060            BuckyError::new(BuckyErrorCode::InvalidData, msg)
1061        })?;
1062
1063        // For BodyContent,we  use the decoding with option to be compatible with older versions of decoding
1064        let opt = RawDecodeOption { version, format };
1065
1066        // body content
1067        let (content, buf) = {
1068            let (body_size, buf) = USize::raw_decode(buf).map_err(|e| {
1069                let msg = format!(
1070                    "ObjectMutBody<B, O>::raw_decode/content_usize error:{}, body={}",
1071                    e,
1072                    B::debug_info()
1073                );
1074                error!("{}", msg);
1075                BuckyError::new(BuckyErrorCode::InvalidData, msg)
1076            })?;
1077
1078            let body_size = body_size.value();
1079            if buf.len() < body_size {
1080                let msg = format!(
1081                    "invalid body content buffer size: expect={}, buf={}, body={}",
1082                    body_size,
1083                    buf.len(),
1084                    B::debug_info(),
1085                );
1086                error!("{}", msg);
1087                return Err(BuckyError::new(BuckyErrorCode::OutOfLimit, msg));
1088            }
1089
1090            // Decode using exact size buffer
1091            let body_buf = &buf[..body_size];
1092            let (content, left_buf) = B::raw_decode_with_option(&body_buf, &opt).map_err(|e| {
1093                let msg = format!(
1094                    "ObjectMutBody<B, O>::raw_decode/content error:{}, body={}",
1095                    e,
1096                    B::debug_info()
1097                );
1098                error!("{}", msg);
1099                BuckyError::new(BuckyErrorCode::InvalidData, msg)
1100            })?;
1101
1102            if left_buf.len() != 0 {
1103                warn!("decode body content by remaining buf is not empty! obj_type={}, body_size={}, remaining={}", O::obj_type(), body_size, left_buf.len());
1104                // assert!(left_buf.len() == 0);
1105            }
1106
1107            (content, &buf[body_size..])
1108        };
1109
1110        // user_data
1111        let (user_data, buf) = if (body_flags & OBJECT_BODY_FLAG_USER_DATA)
1112            == OBJECT_BODY_FLAG_USER_DATA
1113        {
1114            let (len, buf) = u64::raw_decode(buf).map_err(|e| {
1115                let msg = format!(
1116                    "ObjectMutBody<B, O>::raw_decode/user_data len error:{}, body={}",
1117                    e,
1118                    B::debug_info()
1119                );
1120                error!("{}", msg);
1121                BuckyError::new(BuckyErrorCode::InvalidData, msg)
1122            })?;
1123
1124            let bytes = len as usize;
1125            if bytes > buf.len() {
1126                let msg = format!("ObjectMutBody<B, O>::raw_decode/user_data len overflow: body={}, len={}, left={}",
1127                        B::debug_info(),
1128                        len,
1129                        buf.len()
1130                    );
1131                error!("{}", msg);
1132                return Err(BuckyError::new(BuckyErrorCode::InvalidData, msg));
1133            }
1134
1135            let mut user_data = vec![0u8; bytes];
1136            user_data.copy_from_slice(&buf[..bytes]);
1137            (Some(user_data), &buf[bytes..])
1138        } else {
1139            (None, buf)
1140        };
1141
1142        Ok((
1143            Self {
1144                prev_version,
1145                update_time,
1146                content,
1147                user_data,
1148                obj_type: None,
1149                ext,
1150            },
1151            buf,
1152        ))
1153    }
1154}
1155
1156impl<'de, B, O> RawEncode for ObjectMutBody<B, O>
1157where
1158    B: RawEncode + BodyContent,
1159    O: ObjectType,
1160{
1161    fn raw_measure(&self, _purpose: &Option<RawEncodePurpose>) -> BuckyResult<usize> {
1162        unimplemented!();
1163    }
1164
1165    fn raw_encode<'a>(
1166        &self,
1167        _buf: &'a mut [u8],
1168        _purpose: &Option<RawEncodePurpose>,
1169    ) -> BuckyResult<&'a mut [u8]> {
1170        unimplemented!();
1171    }
1172
1173    fn raw_hash_encode(&self) -> BuckyResult<Vec<u8>> {
1174        let mut ctx = NamedObjectBodyContext::new();
1175        let size = self.raw_measure_with_context(&mut ctx, &Some(RawEncodePurpose::Hash)).map_err(|e|{
1176            error!("ObjectMutBody<B, O>::rraw_measure_with_context error:{}, obj_type:{}, obj_type_code:{:?}", e, O::obj_type(), O::obj_type_code());
1177            e
1178        })?;
1179
1180        let mut buf = vec![0u8; size];
1181        let left_buf = self.raw_encode_with_context(&mut buf, &mut ctx, &Some(RawEncodePurpose::Hash)).map_err(|e|{
1182            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());
1183            e
1184        })?;
1185
1186        if left_buf.len() != 0 {
1187            warn!("encode body content by remaining buf is not empty! obj_type={}, body_size={}, remaining={}", O::obj_type(), size, left_buf.len());
1188            // assert!(left_buf.len() == 0);
1189        }
1190
1191        Ok(buf)
1192    }
1193}
1194
1195impl<'de, B, O> RawDecode<'de> for ObjectMutBody<B, O>
1196where
1197    B: RawDecode<'de> + BodyContent,
1198    O: ObjectType,
1199{
1200    fn raw_decode(buf: &'de [u8]) -> BuckyResult<(Self, &'de [u8])> {
1201        let ctx = NamedObjectBodyContext::new();
1202        Self::raw_decode_with_context(buf, &ctx)
1203    }
1204}
1205
1206pub trait NamedObject<O>
1207where
1208    O: ObjectType,
1209    O::ContentType: BodyContent,
1210{
1211    fn obj_flags(&self) -> u16;
1212
1213    fn desc(&self) -> &O::DescType;
1214
1215    fn desc_mut(&mut self) -> &mut O::DescType;
1216
1217    fn body(&self) -> &Option<ObjectMutBody<O::ContentType, O>>;
1218
1219    fn body_expect(&self, msg: &str) -> &ObjectMutBody<O::ContentType, O> {
1220        let msg = format!("expect obj_type {} body failed, msg:{}", O::obj_type(), msg);
1221        self.body().as_ref().expect(&msg)
1222    }
1223
1224    fn body_mut(&mut self) -> &mut Option<ObjectMutBody<O::ContentType, O>>;
1225
1226    fn body_mut_expect(&mut self, msg: &str) -> &mut ObjectMutBody<O::ContentType, O> {
1227        let msg = format!(
1228            "expect obj_type {} body_mut failed, msg:{}",
1229            O::obj_type(),
1230            msg
1231        );
1232        self.body_mut().as_mut().expect(&msg)
1233    }
1234
1235    fn signs(&self) -> &ObjectSigns;
1236
1237    fn signs_mut(&mut self) -> &mut ObjectSigns;
1238
1239    fn nonce(&self) -> &Option<u128>;
1240
1241    // Get the latest modification time of the body and sign sections, in bucky time
1242    fn latest_update_time(&self) -> u64 {
1243        let update_time = match self.body() {
1244            Some(body) => body.update_time(),
1245            None => 0_u64,
1246        };
1247
1248        // If the signature time is relatively new, then take the signature time
1249        let latest_sign_time = self.signs().latest_sign_time();
1250
1251        std::cmp::max(update_time, latest_sign_time)
1252    }
1253}
1254
1255// TODO concat_idents! currently is an unstable util
1256#[macro_export]
1257macro_rules! declare_object {
1258    ($name:ident) => {
1259        type concat_idents!($name, Type) = cyfs_base::NamedObjType<concat_idents!($name, DescContent), concat_idents!($name, BodyContent)>;
1260        type concat_idents!($name, Builder) = cyfs_base::NamedObjectBuilder<concat_idents!($name, DescContent), concat_idents!($name, BodyContent)>;
1261
1262        type concat_idents!($name, Id) = cyfs_base::NamedObjectId<concat_idents!($name, Type)>;
1263        type concat_idents!($name, Desc) = cyfs_base::NamedObjectDesc<concat_idents!($name, DescContent)>;
1264        type $name = cyfs_base::NamedObjectBase<concat_idents!($name,Type)>;
1265    }
1266}