sn_data_types/
map.rs

1// Copyright 2021 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
4// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
5// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
6// modified, or distributed except according to those terms. Please review the Licences for the
7// specific language governing permissions and limitations relating to use of the SAFE Network
8// Software.
9
10//! Map
11//!
12//! All Map is unpublished. Map can be either sequenced or unsequenced.
13//!
14//! ## Private data
15//!
16//! Please see `append_only_data.rs` for more about unpublished versus published data.
17//!
18//! ## Sequenced and unsequenced data.
19//!
20//! Explicitly sequencing all mutations is an option provided for clients to allow them to avoid
21//! dealing with conflicting mutations. However, we don't need the version for preventing replay
22//! attacks.
23//!
24//! For sequenced Map the client must specify the next version number of a value while
25//! modifying/deleting keys. Similarly, while modifying the Map shell (permissions,
26//! ownership, etc.), the next version number must be passed. For unsequenced Map the client
27//! does not have to pass version numbers for keys, but it still must pass the next version number
28//! while modifying the Map shell.
29
30use crate::{utils, Error, PublicKey, Result};
31use serde::{Deserialize, Serialize};
32use std::{
33    collections::{btree_map::Entry, BTreeMap, BTreeSet},
34    fmt::{self, Debug, Formatter},
35    mem,
36};
37use xor_name::XorName;
38
39/// Map that is unpublished on the network. This data can only be fetched by the owner or
40/// those in the permissions fields with `Permission::Read` access.
41#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
42pub struct SeqData {
43    /// Network address.
44    address: Address,
45    /// Key-Value semantics.
46    data: SeqEntries,
47    /// Maps an application key to a list of allowed or forbidden actions.
48    permissions: BTreeMap<PublicKey, PermissionSet>,
49    /// Version should be increased for any changes to Map fields except for data.
50    version: u64,
51    /// Contains the public key of an owner or owners of this data.
52    ///
53    /// Data Handlers in nodes enforce that a mutation request has a valid signature of the owner.
54    owner: PublicKey,
55}
56
57impl Debug for SeqData {
58    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
59        write!(formatter, "SeqMap {:?}", self.name())
60    }
61}
62
63/// Map that is unpublished on the network. This data can only be fetched by the owner or
64/// those in the permissions fields with `Permission::Read` access.
65#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
66pub struct UnseqData {
67    /// Network address.
68    address: Address,
69    /// Key-Value semantics.
70    data: UnseqEntries,
71    /// Maps an application key to a list of allowed or forbidden actions.
72    permissions: BTreeMap<PublicKey, PermissionSet>,
73    /// Version should be increased for any changes to Map fields except for data.
74    version: u64,
75    /// Contains the public key of an owner or owners of this data.
76    ///
77    /// Data Handlers in nodes enforce that a mutation request has a valid signature of the owner.
78    owner: PublicKey,
79}
80
81impl Debug for UnseqData {
82    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
83        write!(formatter, "UnseqMap {:?}", self.name())
84    }
85}
86
87/// A value in sequenced Map.
88#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
89pub struct SeqValue {
90    /// Actual data.
91    pub data: Vec<u8>,
92    /// Version, incremented sequentially for any change to `data`.
93    pub version: u64,
94}
95
96impl Debug for SeqValue {
97    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
98        write!(f, "{:<8} :: {}", hex::encode(&self.data), self.version)
99    }
100}
101
102/// Wrapper type for values, which can be sequenced or unsequenced.
103#[derive(Debug, Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
104pub enum Value {
105    /// Sequenced value.
106    Seq(SeqValue),
107    /// Unsequenced value.
108    Unseq(Vec<u8>),
109}
110
111impl From<SeqValue> for Value {
112    fn from(value: SeqValue) -> Self {
113        Value::Seq(value)
114    }
115}
116
117impl From<Vec<u8>> for Value {
118    fn from(value: Vec<u8>) -> Self {
119        Value::Unseq(value)
120    }
121}
122
123/// Wrapper type for lists of sequenced or unsequenced values.
124#[derive(Debug, Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
125pub enum Values {
126    /// List of sequenced values.
127    Seq(Vec<SeqValue>),
128    /// List of unsequenced values.
129    Unseq(Vec<Vec<u8>>),
130}
131
132impl From<Vec<SeqValue>> for Values {
133    fn from(values: Vec<SeqValue>) -> Self {
134        Values::Seq(values)
135    }
136}
137
138impl From<Vec<Vec<u8>>> for Values {
139    fn from(values: Vec<Vec<u8>>) -> Self {
140        Values::Unseq(values)
141    }
142}
143
144/// Set of user permissions.
145#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize, Default)]
146pub struct PermissionSet {
147    permissions: BTreeSet<Action>,
148}
149
150impl PermissionSet {
151    /// Constructs new permission set.
152    pub fn new() -> PermissionSet {
153        PermissionSet {
154            permissions: Default::default(),
155        }
156    }
157
158    /// Allows the given action.
159    pub fn allow(mut self, action: Action) -> Self {
160        let _ = self.permissions.insert(action);
161        self
162    }
163
164    /// Denies the given action.
165    pub fn deny(mut self, action: Action) -> Self {
166        let _ = self.permissions.remove(&action);
167        self
168    }
169
170    /// Is the given action allowed according to this permission set?
171    pub fn is_allowed(&self, action: Action) -> bool {
172        self.permissions.contains(&action)
173    }
174}
175
176/// Set of Actions that can be performed on the Map.
177#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
178pub enum Action {
179    /// Permission to read entries.
180    Read,
181    /// Permission to insert new entries.
182    Insert,
183    /// Permission to update existing entries.
184    Update,
185    /// Permission to delete existing entries.
186    Delete,
187    /// Permission to modify permissions for other users.
188    ManagePermissions,
189}
190
191macro_rules! impl_map {
192    ($flavour:ident) => {
193        impl $flavour {
194            /// Returns the address.
195            pub fn address(&self) -> &Address {
196                &self.address
197            }
198
199            /// Returns the name.
200            pub fn name(&self) -> &XorName {
201                self.address.name()
202            }
203
204            /// Returns the tag type.
205            pub fn tag(&self) -> u64 {
206                self.address.tag()
207            }
208
209            /// Returns the kind.
210            pub fn kind(&self) -> Kind {
211                self.address.kind()
212            }
213
214            /// Returns the version of the Map fields (not the data version).
215            pub fn version(&self) -> u64 {
216                self.version
217            }
218
219            /// Returns the owner key.
220            pub fn owner(&self) -> &PublicKey {
221                &self.owner
222            }
223
224            /// Returns all the keys in the data.
225            pub fn keys(&self) -> BTreeSet<Vec<u8>> {
226                self.data.keys().cloned().collect()
227            }
228
229            /// Returns the shell of this Map (the fields without the data).
230            pub fn shell(&self) -> Self {
231                Self {
232                    address: self.address.clone(),
233                    data: BTreeMap::new(),
234                    permissions: self.permissions.clone(),
235                    version: self.version,
236                    owner: self.owner,
237                }
238            }
239
240            /// Gets a complete list of permissions.
241            pub fn permissions(&self) -> BTreeMap<PublicKey, PermissionSet> {
242                self.permissions.clone()
243            }
244
245            /// Gets the permissions for the provided user.
246            pub fn user_permissions(&self, user: &PublicKey) -> Result<&PermissionSet> {
247                self.permissions.get(user).ok_or(Error::NoSuchKey)
248            }
249
250            /// Checks if the provided user is an owner.
251            ///
252            /// Returns `Ok(())` on success and `Err(Error::AccessDenied)` if the user is not an
253            /// owner.
254            pub fn check_is_owner(&self, requester: &PublicKey) -> Result<()> {
255                if &self.owner == requester {
256                    Ok(())
257                } else {
258                    Err(Error::AccessDenied(*requester))
259                }
260            }
261
262            /// Checks permissions for given `action` for the provided user.
263            ///
264            /// Returns `Err(Error::AccessDenied)` if the permission check has failed.
265            pub fn check_permissions(&self, action: Action, requester: &PublicKey) -> Result<()> {
266                if &self.owner == requester {
267                    Ok(())
268                } else {
269                    let permissions = self
270                        .user_permissions(requester)
271                        .map_err(|_| Error::AccessDenied(*requester))?;
272                    if permissions.is_allowed(action) {
273                        Ok(())
274                    } else {
275                        Err(Error::AccessDenied(*requester))
276                    }
277                }
278            }
279
280            /// Inserts or updates permissions for the provided user.
281            ///
282            /// Requires the new `version` of the Map fields. If it does not match the
283            /// current version + 1, an error will be returned.
284            pub fn set_user_permissions(
285                &mut self,
286                user: PublicKey,
287                permissions: PermissionSet,
288                version: u64,
289            ) -> Result<()> {
290                if version != self.version + 1 {
291                    return Err(Error::InvalidSuccessor(self.version));
292                }
293
294                let _prev = self.permissions.insert(user, permissions);
295                self.version = version;
296
297                Ok(())
298            }
299
300            /// Deletes permissions for the provided user.
301            ///
302            /// Requires the new `version` of the Map fields. If it does not match the
303            /// current version + 1, an error will be returned.
304            pub fn del_user_permissions(&mut self, user: PublicKey, version: u64) -> Result<()> {
305                if version != self.version + 1 {
306                    return Err(Error::InvalidSuccessor(self.version));
307                }
308                if !self.permissions.contains_key(&user) {
309                    return Err(Error::NoSuchKey);
310                }
311
312                let _ = self.permissions.remove(&user);
313                self.version = version;
314
315                Ok(())
316            }
317
318            /// Deletes user permissions without performing any validation.
319            ///
320            /// Requires the new `version` of the Map fields. If it does not match the
321            /// current version + 1, an error will be returned.
322            pub fn del_user_permissions_without_validation(
323                &mut self,
324                user: PublicKey,
325                version: u64,
326            ) -> bool {
327                if version <= self.version {
328                    return false;
329                }
330
331                let _ = self.permissions.remove(&user);
332                self.version = version;
333
334                true
335            }
336
337            /// Changes the owner.
338            ///
339            /// Requires the new `version` of the Map fields. If it does not match the
340            /// current version + 1, an error will be returned.
341            pub fn change_owner(&mut self, new_owner: PublicKey, version: u64) -> Result<()> {
342                if version != self.version + 1 {
343                    return Err(Error::InvalidSuccessor(self.version));
344                }
345
346                self.owner = new_owner;
347                self.version = version;
348
349                Ok(())
350            }
351
352            /// Changes the owner without performing any validation.
353            ///
354            /// Requires the new `version` of the Map fields. If it does not match the
355            /// current version + 1, an error will be returned.
356            pub fn change_owner_without_validation(
357                &mut self,
358                new_owner: PublicKey,
359                version: u64,
360            ) -> bool {
361                if version <= self.version {
362                    return false;
363                }
364
365                self.owner = new_owner;
366                self.version = version;
367
368                true
369            }
370
371            /// Returns true if `action` is allowed for the provided user.
372            pub fn is_action_allowed(&self, requester: &PublicKey, action: Action) -> bool {
373                match self.permissions.get(requester) {
374                    Some(perms) => perms.is_allowed(action),
375                    None => false,
376                }
377            }
378        }
379    };
380}
381
382impl_map!(SeqData);
383impl_map!(UnseqData);
384
385impl UnseqData {
386    /// Creates a new unsequenced Map.
387    pub fn new(name: XorName, tag: u64, owner: PublicKey) -> Self {
388        Self {
389            address: Address::Unseq { name, tag },
390            data: Default::default(),
391            permissions: Default::default(),
392            version: 0,
393            owner,
394        }
395    }
396
397    /// Creates a new unsequenced Map with entries and permissions.
398    pub fn new_with_data(
399        name: XorName,
400        tag: u64,
401        data: UnseqEntries,
402        permissions: BTreeMap<PublicKey, PermissionSet>,
403        owner: PublicKey,
404    ) -> Self {
405        Self {
406            address: Address::Unseq { name, tag },
407            data,
408            permissions,
409            version: 0,
410            owner,
411        }
412    }
413
414    /// Returns a value for the given key.
415    pub fn get(&self, key: &[u8]) -> Option<&Vec<u8>> {
416        self.data.get(key)
417    }
418
419    /// Returns values of all entries.
420    pub fn values(&self) -> Vec<Vec<u8>> {
421        self.data.values().cloned().collect()
422    }
423
424    /// Returns all entries.
425    pub fn entries(&self) -> &UnseqEntries {
426        &self.data
427    }
428
429    /// Removes and returns all entries.
430    pub fn take_entries(&mut self) -> UnseqEntries {
431        mem::replace(&mut self.data, BTreeMap::new())
432    }
433
434    /// Mutates entries based on `actions` for the provided user.
435    ///
436    /// Returns `Err(InvalidEntryActions)` if the mutation parameters are invalid.
437    pub fn mutate_entries(
438        &mut self,
439        actions: UnseqEntryActions,
440        requester: &PublicKey,
441    ) -> Result<()> {
442        let (insert, update, delete) = actions.actions.into_iter().fold(
443            (
444                BTreeMap::<Vec<u8>, Vec<u8>>::new(),
445                BTreeMap::<Vec<u8>, Vec<u8>>::new(),
446                BTreeSet::<Vec<u8>>::new(),
447            ),
448            |(mut insert, mut update, mut delete), (key, item)| {
449                match item {
450                    UnseqEntryAction::Ins(value) => {
451                        let _ = insert.insert(key, value);
452                    }
453                    UnseqEntryAction::Update(value) => {
454                        let _ = update.insert(key, value);
455                    }
456                    UnseqEntryAction::Del => {
457                        let _ = delete.insert(key);
458                    }
459                };
460                (insert, update, delete)
461            },
462        );
463
464        if self.owner() != requester
465            && ((!insert.is_empty() && !self.is_action_allowed(requester, Action::Insert))
466                || (!update.is_empty() && !self.is_action_allowed(requester, Action::Update))
467                || (!delete.is_empty() && !self.is_action_allowed(requester, Action::Delete)))
468        {
469            return Err(Error::AccessDenied(*requester));
470        }
471
472        let mut new_data = self.data.clone();
473        let mut errors = BTreeMap::new();
474
475        for (key, val) in insert {
476            match new_data.entry(key) {
477                Entry::Occupied(entry) => {
478                    let _ = errors.insert(entry.key().clone(), Error::EntryExists(0));
479                }
480                Entry::Vacant(entry) => {
481                    let _ = entry.insert(val);
482                }
483            }
484        }
485
486        for (key, val) in update {
487            match new_data.entry(key) {
488                Entry::Occupied(mut entry) => {
489                    let _ = entry.insert(val);
490                }
491                Entry::Vacant(entry) => {
492                    let _ = errors.insert(entry.key().clone(), Error::NoSuchEntry);
493                }
494            }
495        }
496
497        for key in delete {
498            match new_data.entry(key.clone()) {
499                Entry::Occupied(_) => {
500                    let _ = new_data.remove(&key);
501                }
502                Entry::Vacant(entry) => {
503                    let _ = errors.insert(entry.key().clone(), Error::NoSuchEntry);
504                }
505            }
506        }
507
508        if !errors.is_empty() {
509            return Err(Error::InvalidEntryActions(errors));
510        }
511
512        let _old_data = mem::replace(&mut self.data, new_data);
513
514        Ok(())
515    }
516}
517
518/// Implements functions for sequenced Map.
519impl SeqData {
520    /// Creates a new sequenced Map.
521    pub fn new(name: XorName, tag: u64, owner: PublicKey) -> Self {
522        Self {
523            address: Address::Seq { name, tag },
524            data: Default::default(),
525            permissions: Default::default(),
526            version: 0,
527            owner,
528        }
529    }
530
531    /// Creates a new sequenced Map with entries and permissions.
532    pub fn new_with_data(
533        name: XorName,
534        tag: u64,
535        data: SeqEntries,
536        permissions: BTreeMap<PublicKey, PermissionSet>,
537        owner: PublicKey,
538    ) -> Self {
539        Self {
540            address: Address::Seq { name, tag },
541            data,
542            permissions,
543            version: 0,
544            owner,
545        }
546    }
547
548    /// Returns a value by the given key
549    pub fn get(&self, key: &[u8]) -> Option<&SeqValue> {
550        self.data.get(key)
551    }
552
553    /// Returns values of all entries
554    pub fn values(&self) -> Vec<SeqValue> {
555        self.data.values().cloned().collect()
556    }
557
558    /// Returns all entries
559    pub fn entries(&self) -> &SeqEntries {
560        &self.data
561    }
562
563    /// Removes and returns all entries
564    pub fn take_entries(&mut self) -> SeqEntries {
565        mem::replace(&mut self.data, BTreeMap::new())
566    }
567
568    /// Mutates entries (key + value pairs) in bulk.
569    ///
570    /// Returns `Err(InvalidEntryActions)` if the mutation parameters are invalid.
571    pub fn mutate_entries(
572        &mut self,
573        actions: SeqEntryActions,
574        requester: &PublicKey,
575    ) -> Result<()> {
576        // Deconstruct actions into inserts, updates, and deletes
577        let (insert, update, delete) = actions.actions.into_iter().fold(
578            (BTreeMap::new(), BTreeMap::new(), BTreeMap::new()),
579            |(mut insert, mut update, mut delete), (key, item)| {
580                match item {
581                    SeqEntryAction::Ins(value) => {
582                        let _ = insert.insert(key, value);
583                    }
584                    SeqEntryAction::Update(value) => {
585                        let _ = update.insert(key, value);
586                    }
587                    SeqEntryAction::Del(version) => {
588                        let _ = delete.insert(key, version);
589                    }
590                };
591                (insert, update, delete)
592            },
593        );
594
595        if self.owner() != requester
596            && ((!insert.is_empty() && !self.is_action_allowed(requester, Action::Insert))
597                || (!update.is_empty() && !self.is_action_allowed(requester, Action::Update))
598                || (!delete.is_empty() && !self.is_action_allowed(requester, Action::Delete)))
599        {
600            return Err(Error::AccessDenied(*requester));
601        }
602
603        let mut new_data = self.data.clone();
604        let mut errors = BTreeMap::new();
605
606        for (key, val) in insert {
607            match new_data.entry(key) {
608                Entry::Occupied(entry) => {
609                    let _ = errors.insert(
610                        entry.key().clone(),
611                        Error::EntryExists(entry.get().version as u8),
612                    );
613                }
614                Entry::Vacant(entry) => {
615                    let _ = entry.insert(val);
616                }
617            }
618        }
619
620        for (key, val) in update {
621            match new_data.entry(key) {
622                Entry::Occupied(mut entry) => {
623                    let current_version = entry.get().version;
624                    if val.version == current_version + 1 {
625                        let _ = entry.insert(val);
626                    } else {
627                        let _ = errors.insert(
628                            entry.key().clone(),
629                            Error::InvalidSuccessor(current_version),
630                        );
631                    }
632                }
633                Entry::Vacant(entry) => {
634                    let _ = errors.insert(entry.key().clone(), Error::NoSuchEntry);
635                }
636            }
637        }
638
639        for (key, version) in delete {
640            match new_data.entry(key.clone()) {
641                Entry::Occupied(entry) => {
642                    let current_version = entry.get().version;
643                    if version == current_version + 1 {
644                        let _ = new_data.remove(&key);
645                    } else {
646                        let _ = errors.insert(
647                            entry.key().clone(),
648                            Error::InvalidSuccessor(current_version),
649                        );
650                    }
651                }
652                Entry::Vacant(entry) => {
653                    let _ = errors.insert(entry.key().clone(), Error::NoSuchEntry);
654                }
655            }
656        }
657
658        if !errors.is_empty() {
659            return Err(Error::InvalidEntryActions(errors));
660        }
661
662        let _old_data = mem::replace(&mut self.data, new_data);
663
664        Ok(())
665    }
666}
667
668/// Kind of a Map.
669#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Debug)]
670pub enum Kind {
671    /// Unsequenced.
672    Unseq,
673    /// Sequenced.
674    Seq,
675}
676
677impl Kind {
678    /// Creates `Kind` from a `sequenced` flag.
679    pub fn from_flag(sequenced: bool) -> Self {
680        if sequenced {
681            Kind::Seq
682        } else {
683            Kind::Unseq
684        }
685    }
686
687    /// Returns `true` if sequenced.
688    pub fn is_seq(self) -> bool {
689        self == Kind::Seq
690    }
691
692    /// Returns `true` if unsequenced.
693    pub fn is_unseq(self) -> bool {
694        !self.is_seq()
695    }
696}
697
698/// Address of an Map.
699#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Debug)]
700pub enum Address {
701    /// Unsequenced namespace.
702    Unseq {
703        /// Name.
704        name: XorName,
705        /// Tag.
706        tag: u64,
707    },
708    /// Sequenced namespace.
709    Seq {
710        /// Name.
711        name: XorName,
712        /// Tag.
713        tag: u64,
714    },
715}
716
717impl Address {
718    /// Constructs an `Address` given `kind`, `name`, and `tag`.
719    pub fn from_kind(kind: Kind, name: XorName, tag: u64) -> Self {
720        match kind {
721            Kind::Seq => Address::Seq { name, tag },
722            Kind::Unseq => Address::Unseq { name, tag },
723        }
724    }
725
726    /// Returns the kind.
727    pub fn kind(&self) -> Kind {
728        match self {
729            Address::Seq { .. } => Kind::Seq,
730            Address::Unseq { .. } => Kind::Unseq,
731        }
732    }
733
734    /// Returns the name.
735    pub fn name(&self) -> &XorName {
736        match self {
737            Address::Unseq { ref name, .. } | Address::Seq { ref name, .. } => name,
738        }
739    }
740
741    /// Returns the tag.
742    pub fn tag(&self) -> u64 {
743        match self {
744            Address::Unseq { tag, .. } | Address::Seq { tag, .. } => *tag,
745        }
746    }
747
748    /// Returns `true` if sequenced.
749    pub fn is_seq(&self) -> bool {
750        self.kind().is_seq()
751    }
752
753    /// Returns `true` if unsequenced.
754    pub fn is_unseq(&self) -> bool {
755        self.kind().is_unseq()
756    }
757
758    /// Returns the Address serialised and encoded in z-base-32.
759    pub fn encode_to_zbase32(&self) -> Result<String> {
760        utils::encode(&self)
761    }
762
763    /// Creates from z-base-32 encoded string.
764    pub fn decode_from_zbase32<T: AsRef<str>>(encoded: T) -> Result<Self> {
765        utils::decode(encoded)
766    }
767}
768
769/// Object storing a Map variant.
770#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Debug)]
771pub enum Data {
772    /// Sequenced Map.
773    Seq(SeqData),
774    /// Unsequenced Map.
775    Unseq(UnseqData),
776}
777
778impl Data {
779    /// Returns the address of the data.
780    pub fn address(&self) -> &Address {
781        match self {
782            Data::Seq(data) => data.address(),
783            Data::Unseq(data) => data.address(),
784        }
785    }
786
787    /// Returns the kind of the data.
788    pub fn kind(&self) -> Kind {
789        self.address().kind()
790    }
791
792    /// Returns the name of the data.
793    pub fn name(&self) -> &XorName {
794        self.address().name()
795    }
796
797    /// Returns the tag of the data.
798    pub fn tag(&self) -> u64 {
799        self.address().tag()
800    }
801
802    /// Returns true if the data is sequenced.
803    pub fn is_seq(&self) -> bool {
804        self.kind().is_seq()
805    }
806
807    /// Returns true if the data is unsequenced.
808    pub fn is_unseq(&self) -> bool {
809        self.kind().is_unseq()
810    }
811
812    /// Returns the version of this data.
813    pub fn version(&self) -> u64 {
814        match self {
815            Data::Seq(data) => data.version(),
816            Data::Unseq(data) => data.version(),
817        }
818    }
819
820    /// Returns all the keys in the data.
821    pub fn keys(&self) -> BTreeSet<Vec<u8>> {
822        match self {
823            Data::Seq(data) => data.keys(),
824            Data::Unseq(data) => data.keys(),
825        }
826    }
827
828    /// Returns the shell of the data.
829    pub fn shell(&self) -> Self {
830        match self {
831            Data::Seq(data) => Data::Seq(data.shell()),
832            Data::Unseq(data) => Data::Unseq(data.shell()),
833        }
834    }
835
836    /// Gets a complete list of permissions.
837    pub fn permissions(&self) -> BTreeMap<PublicKey, PermissionSet> {
838        match self {
839            Data::Seq(data) => data.permissions(),
840            Data::Unseq(data) => data.permissions(),
841        }
842    }
843
844    /// Gets the permissions for the provided user.
845    pub fn user_permissions(&self, user: &PublicKey) -> Result<&PermissionSet> {
846        match self {
847            Data::Seq(data) => data.user_permissions(user),
848            Data::Unseq(data) => data.user_permissions(user),
849        }
850    }
851
852    /// Inserts or update permissions for the provided user.
853    pub fn set_user_permissions(
854        &mut self,
855        user: PublicKey,
856        permissions: PermissionSet,
857        version: u64,
858    ) -> Result<()> {
859        match self {
860            Data::Seq(data) => data.set_user_permissions(user, permissions, version),
861            Data::Unseq(data) => data.set_user_permissions(user, permissions, version),
862        }
863    }
864
865    /// Deletes permissions for the provided user.
866    pub fn del_user_permissions(&mut self, user: PublicKey, version: u64) -> Result<()> {
867        match self {
868            Data::Seq(data) => data.del_user_permissions(user, version),
869            Data::Unseq(data) => data.del_user_permissions(user, version),
870        }
871    }
872
873    /// Checks permissions for given `action` for the provided user.
874    pub fn check_permissions(&self, action: Action, requester: &PublicKey) -> Result<()> {
875        match self {
876            Data::Seq(data) => data.check_permissions(action, requester),
877            Data::Unseq(data) => data.check_permissions(action, requester),
878        }
879    }
880
881    /// Checks if the provided user is an owner.
882    pub fn check_is_owner(&self, requester: &PublicKey) -> Result<()> {
883        match self {
884            Data::Seq(data) => data.check_is_owner(requester),
885            Data::Unseq(data) => data.check_is_owner(requester),
886        }
887    }
888
889    /// Returns the owner key.
890    pub fn owner(&self) -> PublicKey {
891        match self {
892            Data::Seq(data) => data.owner,
893            Data::Unseq(data) => data.owner,
894        }
895    }
896
897    /// Mutates entries (key + value pairs) in bulk.
898    pub fn mutate_entries(&mut self, actions: EntryActions, requester: &PublicKey) -> Result<()> {
899        match self {
900            Data::Seq(data) => {
901                if let EntryActions::Seq(actions) = actions {
902                    return data.mutate_entries(actions, requester);
903                }
904            }
905            Data::Unseq(data) => {
906                if let EntryActions::Unseq(actions) = actions {
907                    return data.mutate_entries(actions, requester);
908                }
909            }
910        }
911
912        Err(Error::InvalidOperation)
913    }
914}
915
916impl From<SeqData> for Data {
917    fn from(data: SeqData) -> Self {
918        Data::Seq(data)
919    }
920}
921
922impl From<UnseqData> for Data {
923    fn from(data: UnseqData) -> Self {
924        Data::Unseq(data)
925    }
926}
927
928/// Action for a sequenced Entry.
929#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize, Debug)]
930pub enum SeqEntryAction {
931    /// Inserts a new sequenced entry.
932    Ins(SeqValue),
933    /// Updates an entry with a new value and version.
934    Update(SeqValue),
935    /// Deletes an entry.
936    Del(u64),
937}
938
939impl SeqEntryAction {
940    /// Returns the version for this action.
941    pub fn version(&self) -> u64 {
942        match *self {
943            Self::Ins(ref value) => value.version,
944            Self::Update(ref value) => value.version,
945            Self::Del(v) => v,
946        }
947    }
948
949    /// Sets the version for this action.
950    pub fn set_version(&mut self, version: u64) {
951        match *self {
952            Self::Ins(ref mut value) => value.version = version,
953            Self::Update(ref mut value) => value.version = version,
954            Self::Del(ref mut v) => *v = version,
955        }
956    }
957}
958
959/// Action for an unsequenced Entry.
960#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize, Debug)]
961pub enum UnseqEntryAction {
962    /// Inserts a new unsequenced entry.
963    Ins(Vec<u8>),
964    /// Updates an entry with a new value.
965    Update(Vec<u8>),
966    /// Deletes an entry.
967    Del,
968}
969
970/// Sequenced Entry Actions for given entry keys.
971#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize, Debug, Default)]
972pub struct SeqEntryActions {
973    // A map containing keys and corresponding sequenced entry actions to perform.
974    actions: BTreeMap<Vec<u8>, SeqEntryAction>,
975}
976
977impl SeqEntryActions {
978    /// Creates a new sequenced Entry Actions list.
979    pub fn new() -> Self {
980        Default::default()
981    }
982
983    /// Gets the actions.
984    pub fn actions(&self) -> &BTreeMap<Vec<u8>, SeqEntryAction> {
985        &self.actions
986    }
987
988    /// Converts `self` to a map of the keys with their corresponding action.
989    pub fn into_actions(self) -> BTreeMap<Vec<u8>, SeqEntryAction> {
990        self.actions
991    }
992
993    /// Inserts a new key-value pair.
994    ///
995    /// Requires the new `version` of the sequenced entry content. If it does not match the current
996    /// version + 1, an error will be returned.
997    pub fn ins(mut self, key: Vec<u8>, content: Vec<u8>, version: u64) -> Self {
998        let _ = self.actions.insert(
999            key,
1000            SeqEntryAction::Ins(SeqValue {
1001                data: content,
1002                version,
1003            }),
1004        );
1005        self
1006    }
1007
1008    /// Updates an existing key-value pair.
1009    ///
1010    /// Requires the new `version` of the sequenced entry content. If it does not match the current
1011    /// version + 1, an error will be returned.
1012    pub fn update(mut self, key: Vec<u8>, content: Vec<u8>, version: u64) -> Self {
1013        let _ = self.actions.insert(
1014            key,
1015            SeqEntryAction::Update(SeqValue {
1016                data: content,
1017                version,
1018            }),
1019        );
1020        self
1021    }
1022
1023    /// Deletes an entry.
1024    ///
1025    /// Requires the new `version` of the sequenced entry content. If it does not match the current
1026    /// version + 1, an error will be returned.
1027    pub fn del(mut self, key: Vec<u8>, version: u64) -> Self {
1028        let _ = self.actions.insert(key, SeqEntryAction::Del(version));
1029        self
1030    }
1031
1032    /// Adds an action to the list of actions, replacing it if it is already present.
1033    pub fn add_action(&mut self, key: Vec<u8>, action: SeqEntryAction) {
1034        let _ = self.actions.insert(key, action);
1035    }
1036}
1037
1038impl From<SeqEntryActions> for BTreeMap<Vec<u8>, SeqEntryAction> {
1039    fn from(actions: SeqEntryActions) -> Self {
1040        actions.actions
1041    }
1042}
1043
1044impl From<BTreeMap<Vec<u8>, SeqEntryAction>> for SeqEntryActions {
1045    fn from(actions: BTreeMap<Vec<u8>, SeqEntryAction>) -> Self {
1046        SeqEntryActions { actions }
1047    }
1048}
1049
1050/// Unsequenced Entry Actions for given entry keys.
1051#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize, Debug, Default)]
1052pub struct UnseqEntryActions {
1053    // A BTreeMap containing keys to which the corresponding unsequenced entry action is to be
1054    // performed.
1055    actions: BTreeMap<Vec<u8>, UnseqEntryAction>,
1056}
1057
1058impl UnseqEntryActions {
1059    /// Creates a new unsequenced Entry Actions list.
1060    pub fn new() -> Self {
1061        Default::default()
1062    }
1063
1064    /// Gets the actions.
1065    pub fn actions(&self) -> &BTreeMap<Vec<u8>, UnseqEntryAction> {
1066        &self.actions
1067    }
1068
1069    /// Converts UnseqEntryActions struct to a BTreeMap of the keys with their corresponding action.
1070    pub fn into_actions(self) -> BTreeMap<Vec<u8>, UnseqEntryAction> {
1071        self.actions
1072    }
1073
1074    /// Insert a new key-value pair
1075    pub fn ins(mut self, key: Vec<u8>, content: Vec<u8>) -> Self {
1076        let _ = self.actions.insert(key, UnseqEntryAction::Ins(content));
1077        self
1078    }
1079
1080    /// Update existing key-value pair
1081    pub fn update(mut self, key: Vec<u8>, content: Vec<u8>) -> Self {
1082        let _ = self.actions.insert(key, UnseqEntryAction::Update(content));
1083        self
1084    }
1085
1086    /// Delete existing key
1087    pub fn del(mut self, key: Vec<u8>) -> Self {
1088        let _ = self.actions.insert(key, UnseqEntryAction::Del);
1089        self
1090    }
1091
1092    /// Adds a UnseqEntryAction to the list of actions, replacing it if it is already present
1093    pub fn add_action(&mut self, key: Vec<u8>, action: UnseqEntryAction) {
1094        let _ = self.actions.insert(key, action);
1095    }
1096}
1097
1098impl From<UnseqEntryActions> for BTreeMap<Vec<u8>, UnseqEntryAction> {
1099    fn from(actions: UnseqEntryActions) -> Self {
1100        actions.actions
1101    }
1102}
1103
1104impl From<BTreeMap<Vec<u8>, UnseqEntryAction>> for UnseqEntryActions {
1105    fn from(actions: BTreeMap<Vec<u8>, UnseqEntryAction>) -> Self {
1106        UnseqEntryActions { actions }
1107    }
1108}
1109
1110/// Wrapper type for entry actions, which can be sequenced or unsequenced.
1111#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize, Debug)]
1112pub enum EntryActions {
1113    /// Sequenced entry actions.
1114    Seq(SeqEntryActions),
1115    /// Unsequenced entry actions.
1116    Unseq(UnseqEntryActions),
1117}
1118
1119impl EntryActions {
1120    /// Gets the kind.
1121    pub fn kind(&self) -> Kind {
1122        match self {
1123            EntryActions::Seq(_) => Kind::Seq,
1124            EntryActions::Unseq(_) => Kind::Unseq,
1125        }
1126    }
1127}
1128
1129impl From<SeqEntryActions> for EntryActions {
1130    fn from(entry_actions: SeqEntryActions) -> Self {
1131        EntryActions::Seq(entry_actions)
1132    }
1133}
1134
1135impl From<UnseqEntryActions> for EntryActions {
1136    fn from(entry_actions: UnseqEntryActions) -> Self {
1137        EntryActions::Unseq(entry_actions)
1138    }
1139}
1140
1141/// Sequenced entries (key-value pairs, with versioned values).
1142pub type SeqEntries = BTreeMap<Vec<u8>, SeqValue>;
1143/// Unsequenced entries (key-value pairs, without versioned values).
1144pub type UnseqEntries = BTreeMap<Vec<u8>, Vec<u8>>;
1145
1146/// Wrapper type for entries, which can be sequenced or unsequenced.
1147#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Serialize, Deserialize, Debug)]
1148pub enum Entries {
1149    /// Sequenced entries.
1150    Seq(SeqEntries),
1151    /// Unsequenced entries.
1152    Unseq(UnseqEntries),
1153}
1154
1155impl From<SeqEntries> for Entries {
1156    fn from(entries: SeqEntries) -> Self {
1157        Entries::Seq(entries)
1158    }
1159}
1160
1161impl From<UnseqEntries> for Entries {
1162    fn from(entries: UnseqEntries) -> Self {
1163        Entries::Unseq(entries)
1164    }
1165}
1166
1167#[cfg(test)]
1168mod tests {
1169    use super::{Address, XorName};
1170    use crate::Result;
1171
1172    #[test]
1173    fn zbase32_encode_decode_map_address() -> Result<()> {
1174        let name = XorName(rand::random());
1175        let address = Address::Seq { name, tag: 15000 };
1176        let encoded = address.encode_to_zbase32()?;
1177        let decoded = self::Address::decode_from_zbase32(&encoded)?;
1178        assert_eq!(address, decoded);
1179        Ok(())
1180    }
1181}