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
// Copyright 2023 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.

//! Data messages and their possible responses.
mod cmd;
mod node_id;
mod query;
mod register;
mod response;

pub use self::{
    cmd::{Cmd, Hash},
    node_id::NodeId,
    query::Query,
    register::RegisterCmd,
    response::{CmdOk, CmdResponse, QueryResponse},
};

use super::NetworkAddress;
use crate::{
    error::{Error, Result},
    storage::{Chunk, SpendAddress},
};
use serde::{Deserialize, Serialize};
use sn_registers::SignedRegister;
use sn_transfers::SignedSpend;
use xor_name::XorName;

#[allow(clippy::large_enum_variant)]
/// A request to peers in the network
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Request {
    /// A cmd sent to peers. Cmds are writes, i.e. can cause mutation.
    Cmd(Cmd),
    /// A query sent to peers. Queries are read-only.
    Query(Query),
}

/// A response to peers in the network.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Response {
    /// The response to a cmd.
    Cmd(CmdResponse),
    /// The response to a query.
    Query(QueryResponse),
}

#[derive(custom_debug::Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum ReplicatedData {
    /// A chunk of data.
    Chunk(Chunk),
    /// A set of SignedSpends
    Spend(Vec<SignedSpend>),
    /// A signed register
    Register(SignedRegister),
}

impl Request {
    /// Used to send a request to the close group of the address.
    pub fn dst(&self) -> NetworkAddress {
        match self {
            Request::Cmd(cmd) => cmd.dst(),
            Request::Query(query) => query.dst(),
        }
    }
}

impl ReplicatedData {
    /// Return the name.
    pub fn name(&self) -> Result<XorName> {
        let name = match self {
            Self::Chunk(chunk) => *chunk.name(),
            Self::Spend(spends) => {
                if let Some(spend) = spends.first() {
                    *SpendAddress::from_unique_pubkey(spend.unique_pubkey()).xorname()
                } else {
                    return Err(Error::SpendIsEmpty);
                }
            }
            Self::Register(register) => register.address().xorname(),
        };
        Ok(name)
    }

    /// Return the dst.
    pub fn dst(&self) -> Result<NetworkAddress> {
        let dst = match self {
            Self::Chunk(chunk) => NetworkAddress::from_chunk_address(*chunk.address()),
            Self::Spend(spends) => {
                if let Some(spend) = spends.first() {
                    NetworkAddress::from_cash_note_address(SpendAddress::from_unique_pubkey(
                        spend.unique_pubkey(),
                    ))
                } else {
                    return Err(Error::SpendIsEmpty);
                }
            }
            Self::Register(register) => NetworkAddress::from_register_address(*register.address()),
        };
        Ok(dst)
    }
}

impl std::fmt::Display for Response {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}