logo
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright 2022 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use super::{CmdError, Error, QueryResponse, Result};

use crate::messaging::{data::OperationId, SectionAuth};
use crate::types::register::{EntryHash, Register};
use crate::types::{
    register::{Entry, Policy, RegisterOp, User},
    RegisterAddress as Address,
};

use serde::{Deserialize, Serialize};
use xor_name::XorName;

/// [`Register`] read operations.
#[allow(clippy::large_enum_variant)]
#[derive(Hash, Eq, PartialEq, PartialOrd, Clone, Serialize, Deserialize, Debug)]
pub enum RegisterQuery {
    /// Retrieve the [`Register`] at the given address.
    ///
    /// This should eventually lead to a [`GetRegister`] response.
    ///
    /// [`GetRegister`]: QueryResponse::GetRegister
    Get(Address),
    /// Retrieve the current entries from the [`Register`] at the given address.
    ///
    /// Multiple entries occur on concurrent writes. This should eventually lead to a
    /// [`ReadRegister`] response.
    ///
    /// [`ReadRegister`]: QueryResponse::ReadRegister
    Read(Address),
    /// Get an entry from a [`Register`] on the Network by its hash
    ///
    /// This should eventually lead to a [`GetRegisterEntry`] response.
    ///
    /// [`GetEntry`]: QueryResponse::GetRegisterEntry
    GetEntry {
        /// Register address.
        address: Address,
        /// The hash of the entry.
        hash: EntryHash,
    },
    /// Retrieve the policy of the [`Register`] at the given address.
    ///
    /// This should eventually lead to a [`GetRegisterPolicy`] response.
    ///
    /// [`GetRegisterPolicy`]: QueryResponse::GetRegisterPolicy
    GetPolicy(Address),
    /// Retrieve the permissions of a given user for the [`Register`] at the given address.
    ///
    /// This should eventually lead to a [`GetRegisterUserPermissions`] response.
    ///
    /// [`GetRegisterUserPermissions`]: QueryResponse::GetRegisterUserPermissions
    GetUserPermissions {
        /// Register address.
        address: Address,
        /// User to get permissions for.
        user: User,
    },
    /// Retrieve the owner of the [`Register`] at the given address.
    ///
    /// This should eventually lead to a [`GetRegisterOwner`] response.
    ///
    /// [`GetRegisterOwner`]: QueryResponse::GetRegisterOwner
    GetOwner(Address),
}

/// A [`Register`] cmd that is stored in a log on Adults.
#[allow(clippy::large_enum_variant)]
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize, Debug)]
pub enum RegisterCmd {
    /// Create a new [`Register`] on the network.
    Create {
        /// The user signed op.
        cmd: SignedRegisterCreate,
        /// Section signature over the operation,
        /// verifying that it was paid for.
        section_auth: SectionAuth,
    },
    /// Edit the [`Register`].
    Edit(SignedRegisterEdit),
    /// Delete the [`Register`].
    Delete(SignedRegisterDelete),
    /// Extend the size of the [`Register`].
    Extend {
        /// The user signed op.
        cmd: SignedRegisterExtend,
        /// Section signature over the operation,
        /// verifying that it was paid for.
        section_auth: SectionAuth,
    },
}

///
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum CreateRegister {
    /// Populated with entries
    Populated(Register),
    /// Without entries
    Empty {
        /// The name of the [`Register`].
        name: XorName,
        /// The tag on the [`Register`].
        tag: u64,
        /// The initial size of the [`Register`].
        size: u16,
        /// The policy of the [`Register`].
        policy: Policy,
    },
}

impl CreateRegister {
    ///
    pub fn owner(&self) -> User {
        use CreateRegister::*;
        match self {
            Populated(reg) => reg.owner(),
            Empty { policy, .. } => *policy.owner(),
        }
    }

    ///
    pub fn size(&self) -> u16 {
        use CreateRegister::*;
        match self {
            Populated(reg) => reg.size() as u16,
            Empty { size, .. } => *size,
        }
    }

    ///
    pub fn address(&self) -> Address {
        use CreateRegister::*;
        match self {
            Populated(reg) => *reg.address(),
            Empty {
                policy, name, tag, ..
            } => {
                if let Policy::Public { .. } = policy {
                    Address::Public {
                        name: *name,
                        tag: *tag,
                    }
                } else {
                    Address::Private {
                        name: *name,
                        tag: *tag,
                    }
                }
            }
        }
    }
}

///
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct ExtendRegister {
    /// The address of the [`Register`] to extend.
    pub address: Address,
    /// The size to extend the [`Register`] with.
    pub extend_with: u16,
}

///
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct DeleteRegister(pub Address);

///
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct EditRegister {
    /// The address of the [`Register`] to edit.
    pub address: Address,
    /// The operation to perform.
    pub edit: RegisterOp<Entry>,
}

/// A signed cmd to create a [`Register`].
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct SignedRegisterCreate {
    /// Create a [`Register`].
    pub op: CreateRegister,
    /// A signature carrying authority to perform the operation.
    ///
    /// This will be verified against the register's owner and permissions.
    pub auth: crate::messaging::ServiceAuth,
}

/// A signed cmd to create a [`Register`].
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct SignedRegisterExtend {
    /// Extend a [`Register`].
    pub op: ExtendRegister,
    /// A signature carrying authority to perform the operation.
    ///
    /// This will be verified against the register's owner and permissions.
    pub auth: crate::messaging::ServiceAuth,
}

/// A [`Register`] write operation signed by the requester.
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize, Debug)]
pub struct SignedRegisterEdit {
    /// The operation to perform.
    pub op: EditRegister,
    /// A signature carrying authority to perform the operation.
    ///
    /// This will be verified against the register's owner and permissions.
    pub auth: crate::messaging::ServiceAuth,
}

/// A [`Register`] write operation.
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct SignedRegisterDelete {
    /// Delete a private [`Register`].
    ///
    /// This operation will result in an error if applied to a public register. Only private
    /// registers can be deleted, and only by their current owner(s).
    pub op: DeleteRegister,
    /// A signature carrying authority to perform the operation.
    ///
    /// This will be verified against the register's owner and permissions.
    pub auth: crate::messaging::ServiceAuth,
}

impl SignedRegisterCreate {
    /// Returns the dst address of the register.
    pub fn dst_address(&self) -> Address {
        self.op.address()
    }
}

impl SignedRegisterEdit {
    /// Returns the dst address of the register.
    pub fn dst_address(&self) -> &Address {
        &self.op.address
    }
}

impl SignedRegisterDelete {
    /// Returns the dst address of the register.
    pub fn dst_address(&self) -> &Address {
        &self.op.0
    }
}

impl SignedRegisterExtend {
    /// Returns the dst address of the register.
    pub fn dst_address(&self) -> &Address {
        &self.op.address
    }
}

impl RegisterQuery {
    /// Creates a Response containing an error, with the Response variant corresponding to the
    /// Request variant.
    pub fn error(&self, error: Error) -> Result<QueryResponse> {
        match *self {
            RegisterQuery::Get(_) => Ok(QueryResponse::GetRegister((
                Err(error),
                self.operation_id()?,
            ))),
            RegisterQuery::Read(_) => Ok(QueryResponse::ReadRegister((
                Err(error),
                self.operation_id()?,
            ))),
            RegisterQuery::GetPolicy(_) => Ok(QueryResponse::GetRegisterPolicy((
                Err(error),
                self.operation_id()?,
            ))),
            RegisterQuery::GetUserPermissions { .. } => Ok(
                QueryResponse::GetRegisterUserPermissions((Err(error), self.operation_id()?)),
            ),
            RegisterQuery::GetEntry { .. } => Ok(QueryResponse::GetRegisterEntry((
                Err(error),
                self.operation_id()?,
            ))),
            RegisterQuery::GetOwner(_) => Ok(QueryResponse::GetRegisterOwner((
                Err(error),
                self.operation_id()?,
            ))),
        }
    }

    /// Returns the dst address for the request. (Scoped to Private/Public)
    pub fn dst_address(&self) -> Address {
        match self {
            RegisterQuery::Get(ref address)
            | RegisterQuery::Read(ref address)
            | RegisterQuery::GetPolicy(ref address)
            | RegisterQuery::GetUserPermissions { ref address, .. }
            | RegisterQuery::GetEntry { ref address, .. }
            | RegisterQuery::GetOwner(ref address) => *address,
        }
    }

    /// Returns the xorname of the data for request.
    pub fn dst_name(&self) -> XorName {
        match self {
            RegisterQuery::Get(ref address)
            | RegisterQuery::Read(ref address)
            | RegisterQuery::GetPolicy(ref address)
            | RegisterQuery::GetUserPermissions { ref address, .. }
            | RegisterQuery::GetEntry { ref address, .. }
            | RegisterQuery::GetOwner(ref address) => *address.name(),
        }
    }

    /// Retrieves the operation identifier for this response, use in tracking node liveness
    /// and responses at clients.
    /// Must be the same as the query response
    /// Right now returning result to fail for anything non-chunk, as that's all we're tracking from other nodes here just now.
    pub fn operation_id(&self) -> Result<OperationId> {
        match self {
            RegisterQuery::Get(_) => Ok(format!("Get-{:?}", self.encode_to_zbase32()?)),
            RegisterQuery::Read(_) => Ok(format!("Read-{:?}", self.encode_to_zbase32()?)),
            RegisterQuery::GetPolicy(_) => Ok(format!("GetPolicy-{:?}", self.encode_to_zbase32()?)),
            RegisterQuery::GetUserPermissions { .. } => Ok(format!(
                "GetUserPermissions-{:?}",
                self.encode_to_zbase32()?
            )),
            RegisterQuery::GetEntry { .. } => {
                Ok(format!("GetEntry-{:?}", self.encode_to_zbase32()?))
            }
            RegisterQuery::GetOwner(_) => Ok(format!("GetOwner-{:?}", self.encode_to_zbase32()?)),
        }
    }

    /// Returns the query serialised and encoded in z-base-32.
    fn encode_to_zbase32(&self) -> Result<String> {
        crate::types::utils::encode(&self).map_err(|_| Error::NoOperationId)
    }
}

impl RegisterCmd {
    /// Creates a Response containing an error, with the Response variant corresponding to the
    /// Request variant.
    pub fn error(&self, error: Error) -> CmdError {
        CmdError::Data(error)
    }

    /// Returns the name of the register.
    /// This is not a unique identifier.
    pub fn name(&self) -> XorName {
        *self.dst_address().name()
    }

    // /// Returns the id of the register.
    // /// This is a unique identifier, used
    // /// in order to not co-locate private and public
    // /// and different tags of same register name.
    // pub fn dst_id(&self) -> Result<XorName> {
    //     self.dst_address().id()
    // }

    /// Returns the dst address of the register.
    pub fn dst_address(&self) -> Address {
        match self {
            Self::Create { cmd, .. } => cmd.dst_address(),
            Self::Edit(cmd) => *cmd.dst_address(),
            Self::Delete(cmd) => *cmd.dst_address(),
            Self::Extend { cmd, .. } => *cmd.dst_address(),
        }
    }

    /// Owner of the Register
    pub fn owner(&self) -> Option<User> {
        match self {
            Self::Create {
                cmd: SignedRegisterCreate { op, .. },
                ..
            } => Some(op.owner()),
            _ => None,
        }
    }
}