ant_protocol/messages/
response.rs

1// Copyright 2024 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
4// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
5// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6// KIND, either express or implied. Please review the Licences for the specific language governing
7// permissions and limitations relating to use of the SAFE Network Software.
8
9use crate::{error::Result, NetworkAddress};
10
11use super::ChunkProof;
12use ant_evm::PaymentQuote;
13use bytes::Bytes;
14use core::fmt;
15use libp2p::Multiaddr;
16use serde::{Deserialize, Serialize};
17use std::fmt::Debug;
18
19/// The response to a query, containing the query result.
20#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
21pub enum QueryResponse {
22    // ===== GetStoreQuote =====
23    //
24    /// Response to [`GetStoreQuote`]
25    ///
26    /// [`GetStoreQuote`]: crate::messages::Query::GetStoreQuote
27    GetStoreQuote {
28        /// The store cost quote for storing the next record.
29        quote: Result<PaymentQuote>,
30        /// Node's Peer Address
31        peer_address: NetworkAddress,
32        /// Storage proofs based on requested target address and difficulty
33        storage_proofs: Vec<(NetworkAddress, Result<ChunkProof>)>,
34    },
35    CheckNodeInProblem {
36        /// Address of the peer that queried
37        reporter_address: NetworkAddress,
38        /// Address of the target to be queried
39        target_address: NetworkAddress,
40        /// Status flag indicating whether the target is in trouble
41        is_in_trouble: bool,
42    },
43    // ===== ReplicatedRecord =====
44    //
45    /// Response to [`GetReplicatedRecord`]
46    ///
47    /// [`GetReplicatedRecord`]: crate::messages::Query::GetReplicatedRecord
48    GetReplicatedRecord(Result<(NetworkAddress, Bytes)>),
49    // ===== ChunkExistenceProof =====
50    //
51    /// Response to [`GetChunkExistenceProof`]
52    ///
53    /// [`GetChunkExistenceProof`]: crate::messages::Query::GetChunkExistenceProof
54    GetChunkExistenceProof(Vec<(NetworkAddress, Result<ChunkProof>)>),
55    // ===== GetClosestPeers =====
56    //
57    /// Response to [`GetClosestPeers`]
58    ///
59    /// [`GetClosestPeers`]: crate::messages::Query::GetClosestPeers
60    GetClosestPeers {
61        // The target address that the original request is about.
62        target: NetworkAddress,
63        // `Multiaddr` is required to allow the requester to dial the peer
64        // Note: the list doesn't contain the node that being queried.
65        peers: Vec<(NetworkAddress, Vec<Multiaddr>)>,
66        // Signature of signing the above (if requested), for future economic model usage.
67        signature: Option<Vec<u8>>,
68    },
69    /// *** From now on, the order of variants shall be retained to be backward compatible
70    // ===== GetVersion =====
71    //
72    /// Response to [`GetVersion`]
73    ///
74    /// [`GetVersion`]: crate::messages::Query::GetVersion
75    GetVersion {
76        peer: NetworkAddress,
77        version: String,
78    },
79}
80
81// Debug implementation for QueryResponse, to avoid printing Vec<u8>
82impl Debug for QueryResponse {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        match self {
85            QueryResponse::GetStoreQuote {
86                quote,
87                peer_address,
88                storage_proofs,
89            } => {
90                let payment_address = quote.as_ref().map(|q| q.rewards_address).ok();
91                write!(
92                    f,
93                    "GetStoreQuote(quote: {quote:?}, from {peer_address:?} w/ payment_address: {payment_address:?}, and {} storage proofs)",
94                    storage_proofs.len()
95                )
96            }
97            QueryResponse::CheckNodeInProblem {
98                reporter_address,
99                target_address,
100                is_in_trouble,
101            } => {
102                write!(
103                    f,
104                    "CheckNodeInProblem({reporter_address:?} report target {target_address:?} as {is_in_trouble:?} in problem"
105                )
106            }
107            QueryResponse::GetReplicatedRecord(result) => match result {
108                Ok((holder, data)) => {
109                    write!(
110                        f,
111                        "GetReplicatedRecord(Ok((holder: {:?}, datalen: {:?})))",
112                        holder,
113                        data.len()
114                    )
115                }
116                Err(err) => {
117                    write!(f, "GetReplicatedRecord(Err({err:?}))")
118                }
119            },
120            QueryResponse::GetChunkExistenceProof(proofs) => {
121                let addresses: Vec<_> = proofs.iter().map(|(addr, _)| addr.clone()).collect();
122                write!(f, "GetChunkExistenceProof(checked chunks: {addresses:?})")
123            }
124            QueryResponse::GetClosestPeers { target, peers, .. } => {
125                let addresses: Vec<_> = peers.iter().map(|(addr, _)| addr.clone()).collect();
126                write!(
127                    f,
128                    "GetClosestPeers target {target:?} close peers {addresses:?}"
129                )
130            }
131            QueryResponse::GetVersion { peer, version } => {
132                write!(f, "GetVersion peer {peer:?} has version of {version:?}")
133            }
134        }
135    }
136}
137
138/// The response to a Cmd, containing the query result.
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140pub enum CmdResponse {
141    //
142    // ===== Replication =====
143    //
144    /// Response to replication cmd
145    Replicate(Result<()>),
146    /// Response to fresh replication cmd
147    FreshReplicate(Result<()>),
148    //
149    // ===== PeerConsideredAsBad =====
150    //
151    /// Response to the considered as bad notification
152    PeerConsideredAsBad(Result<()>),
153}