safe_nd/
map.rs

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