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
use super::proto;
use super::streaming::{InboundStream, OutboundTryStream};

#[cfg(feature = "legacy")]
use super::legacy;

use crate::core::server::{BlockService, FragmentService, GossipService, Node};
use crate::data::p2p::NodeId;
use crate::data::{block, fragment, BlockId, Peer};
use crate::PROTOCOL_VERSION;
use tonic::{Code, Status};

#[cfg(feature = "legacy")]
use tonic::metadata::MetadataValue;

use std::net::SocketAddr;

pub type Server<T> = proto::node::node_server::NodeServer<NodeService<T>>;

/// Builder to customize the gRPC server.
#[derive(Default)]
pub struct Builder {
    #[cfg(feature = "legacy")]
    legacy_node_id: Option<legacy::NodeId>,
}

impl Builder {
    pub fn new() -> Self {
        Builder {
            #[cfg(feature = "legacy")]
            legacy_node_id: None,
        }
    }

    /// Make the server add "node-id-bin" metadata with the passed value
    /// into subscription responses, for backward compatibility with
    /// jormungandr versions prior to 0.9.
    #[cfg(feature = "legacy")]
    pub fn legacy_node_id(&mut self, node_id: legacy::NodeId) -> &mut Self {
        self.legacy_node_id = Some(node_id);
        self
    }

    pub fn build<T: Node>(&self, inner: T) -> Server<T> {
        let service = NodeService {
            #[cfg(feature = "legacy")]
            legacy_node_id: self.legacy_node_id,
            ..NodeService::new(inner)
        };
        Server::new(service)
    }
}

#[derive(Debug)]
pub struct NodeService<T> {
    inner: T,
    #[cfg(feature = "legacy")]
    legacy_node_id: Option<legacy::NodeId>,
}

impl<T> NodeService<T>
where
    T: Node,
{
    pub fn new(inner: T) -> Self {
        NodeService {
            inner,
            #[cfg(feature = "legacy")]
            legacy_node_id: None,
        }
    }

    fn block_service(&self) -> Result<&T::BlockService, Status> {
        self.inner
            .block_service()
            .ok_or_else(|| Status::new(Code::Unimplemented, "not implemented"))
    }

    fn fragment_service(&self) -> Result<&T::FragmentService, Status> {
        self.inner
            .fragment_service()
            .ok_or_else(|| Status::new(Code::Unimplemented, "not implemented"))
    }

    fn gossip_service(&self) -> Result<&T::GossipService, Status> {
        self.inner
            .gossip_service()
            .ok_or_else(|| Status::new(Code::Unimplemented, "not implemented"))
    }

    #[allow(unused_mut)]
    #[allow(clippy::let_and_return)]
    fn subscription_response<S>(&self, outbound: S) -> tonic::Response<OutboundTryStream<S>> {
        let mut res = tonic::Response::new(OutboundTryStream::new(outbound));
        #[cfg(feature = "legacy")]
        if let Some(node_id) = self.legacy_node_id {
            let val = MetadataValue::from_bytes(&node_id.encode());
            res.metadata_mut().insert_bin("node-id-bin", val);
        }
        res
    }
}

fn remote_addr_to_peer(maybe_addr: Option<SocketAddr>) -> Result<Peer, Status> {
    match maybe_addr {
        Some(addr) => Ok(addr.into()),
        None => Err(Status::internal(
            "transport does not provide the remote address",
        )),
    }
}

#[tonic::async_trait]
impl<T> proto::node::node_server::Node for NodeService<T>
where
    T: Node,
{
    async fn handshake(
        &self,
        req: tonic::Request<proto::node::HandshakeRequest>,
    ) -> Result<tonic::Response<proto::node::HandshakeResponse>, tonic::Status> {
        let peer = remote_addr_to_peer(req.remote_addr())?;
        let req = req.into_inner();
        let nonce = &req.nonce;
        let hr = self.inner.handshake(peer, nonce).await?;
        let res = proto::node::HandshakeResponse {
            version: PROTOCOL_VERSION,
            block0: hr.block0_id.as_bytes().into(),
            node_id: hr.auth.id().as_bytes().into(),
            signature: hr.auth.signature().into(),
            nonce: hr.nonce.into(),
        };
        Ok(tonic::Response::new(res))
    }

    async fn client_auth(
        &self,
        req: tonic::Request<proto::node::ClientAuthRequest>,
    ) -> Result<tonic::Response<proto::node::ClientAuthResponse>, tonic::Status> {
        let peer = remote_addr_to_peer(req.remote_addr())?;
        let req = req.into_inner();
        let node_id = NodeId::try_from(&req.node_id[..])?;
        let auth = node_id.authenticated(&req.signature)?;
        self.inner.client_auth(peer, auth).await?;
        let res = proto::node::ClientAuthResponse {};
        Ok(tonic::Response::new(res))
    }

    async fn tip(
        &self,
        _: tonic::Request<proto::node::TipRequest>,
    ) -> Result<tonic::Response<proto::node::TipResponse>, tonic::Status> {
        let service = self.block_service()?;
        let header = service.tip().await?;
        let res = proto::node::TipResponse {
            block_header: header.into(),
        };
        Ok(tonic::Response::new(res))
    }

    async fn peers(
        &self,
        req: tonic::Request<proto::node::PeersRequest>,
    ) -> Result<tonic::Response<proto::node::PeersResponse>, tonic::Status> {
        let service = self.gossip_service()?;
        let peers = service.peers(req.into_inner().limit).await?;
        let res = proto::node::PeersResponse {
            peers: peers
                .nodes
                .iter()
                .cloned()
                .map(|node| node.into_bytes())
                .collect(),
        };
        Ok(tonic::Response::new(res))
    }

    type GetBlocksStream = OutboundTryStream<<T::BlockService as BlockService>::GetBlocksStream>;

    async fn get_blocks(
        &self,
        req: tonic::Request<proto::types::BlockIds>,
    ) -> Result<tonic::Response<Self::GetBlocksStream>, tonic::Status> {
        let service = self.block_service()?;
        let ids = block::try_ids_from_iter(req.into_inner().ids)?;
        let stream = service.get_blocks(ids).await?;
        Ok(tonic::Response::new(OutboundTryStream::new(stream)))
    }

    type GetHeadersStream = OutboundTryStream<<T::BlockService as BlockService>::GetHeadersStream>;

    async fn get_headers(
        &self,
        req: tonic::Request<proto::types::BlockIds>,
    ) -> Result<tonic::Response<Self::GetHeadersStream>, tonic::Status> {
        let service = self.block_service()?;
        let ids = block::try_ids_from_iter(req.into_inner().ids)?;
        let stream = service.get_headers(ids).await?;
        Ok(tonic::Response::new(OutboundTryStream::new(stream)))
    }

    type GetFragmentsStream =
        OutboundTryStream<<T::FragmentService as FragmentService>::GetFragmentsStream>;

    async fn get_fragments(
        &self,
        req: tonic::Request<proto::types::FragmentIds>,
    ) -> Result<tonic::Response<Self::GetFragmentsStream>, tonic::Status> {
        let service = self.fragment_service()?;
        let ids = fragment::try_ids_from_iter(req.into_inner().ids)?;
        let stream = service.get_fragments(ids).await?;
        Ok(tonic::Response::new(OutboundTryStream::new(stream)))
    }

    type PullHeadersStream =
        OutboundTryStream<<T::BlockService as BlockService>::PullHeadersStream>;

    async fn pull_headers(
        &self,
        req: tonic::Request<proto::node::PullHeadersRequest>,
    ) -> Result<tonic::Response<Self::PullHeadersStream>, tonic::Status> {
        let service = self.block_service()?;
        let (from, to) = {
            let req = req.into_inner();
            (
                block::try_ids_from_iter(req.from)?,
                BlockId::try_from(&req.to[..])?,
            )
        };
        let stream = service.pull_headers(from, to).await?;
        Ok(tonic::Response::new(OutboundTryStream::new(stream)))
    }

    type PullBlocksStream = OutboundTryStream<<T::BlockService as BlockService>::PullBlocksStream>;

    async fn pull_blocks(
        &self,
        req: tonic::Request<proto::node::PullBlocksRequest>,
    ) -> Result<tonic::Response<Self::PullBlocksStream>, tonic::Status> {
        let service = self.block_service()?;
        let req = req.into_inner();
        let from = block::try_ids_from_iter(req.from)?;
        let to = BlockId::try_from(&req.to[..])?;
        let stream = service.pull_blocks(from, to).await?;
        Ok(tonic::Response::new(OutboundTryStream::new(stream)))
    }

    type PullBlocksToTipStream =
        OutboundTryStream<<T::BlockService as BlockService>::PullBlocksToTipStream>;

    async fn pull_blocks_to_tip(
        &self,
        req: tonic::Request<proto::node::PullBlocksToTipRequest>,
    ) -> Result<tonic::Response<Self::PullBlocksToTipStream>, tonic::Status> {
        let service = self.block_service()?;
        let from = block::try_ids_from_iter(req.into_inner().from)?;
        let stream = service.pull_blocks_to_tip(from).await?;
        Ok(tonic::Response::new(OutboundTryStream::new(stream)))
    }

    async fn push_headers(
        &self,
        req: tonic::Request<tonic::Streaming<proto::types::Header>>,
    ) -> Result<tonic::Response<proto::node::PushHeadersResponse>, tonic::Status> {
        let service = self.block_service()?;
        let stream = InboundStream::new(req.into_inner());
        service.push_headers(Box::pin(stream)).await?;
        Ok(tonic::Response::new(proto::node::PushHeadersResponse {}))
    }

    async fn upload_blocks(
        &self,
        req: tonic::Request<tonic::Streaming<proto::types::Block>>,
    ) -> Result<tonic::Response<proto::node::UploadBlocksResponse>, tonic::Status> {
        let service = self.block_service()?;
        let stream = InboundStream::new(req.into_inner());
        service.upload_blocks(Box::pin(stream)).await?;
        Ok(tonic::Response::new(proto::node::UploadBlocksResponse {}))
    }

    type BlockSubscriptionStream =
        OutboundTryStream<<T::BlockService as BlockService>::SubscriptionStream>;

    async fn block_subscription(
        &self,
        req: tonic::Request<tonic::Streaming<proto::types::Header>>,
    ) -> Result<tonic::Response<Self::BlockSubscriptionStream>, tonic::Status> {
        let service = self.block_service()?;
        let peer = remote_addr_to_peer(req.remote_addr())?;
        let inbound = InboundStream::new(req.into_inner());
        let outbound = service.block_subscription(peer, Box::pin(inbound)).await?;
        let res = self.subscription_response(outbound);
        Ok(res)
    }

    type FragmentSubscriptionStream =
        OutboundTryStream<<T::FragmentService as FragmentService>::SubscriptionStream>;

    async fn fragment_subscription(
        &self,
        req: tonic::Request<tonic::Streaming<proto::types::Fragment>>,
    ) -> Result<tonic::Response<Self::FragmentSubscriptionStream>, tonic::Status> {
        let service = self.fragment_service()?;
        let peer = remote_addr_to_peer(req.remote_addr())?;
        let inbound = InboundStream::new(req.into_inner());
        let outbound = service
            .fragment_subscription(peer, Box::pin(inbound))
            .await?;
        let res = self.subscription_response(outbound);
        Ok(res)
    }

    type GossipSubscriptionStream =
        OutboundTryStream<<T::GossipService as GossipService>::SubscriptionStream>;

    async fn gossip_subscription(
        &self,
        req: tonic::Request<tonic::Streaming<proto::node::Gossip>>,
    ) -> Result<tonic::Response<Self::GossipSubscriptionStream>, tonic::Status> {
        let service = self.gossip_service()?;
        let peer = remote_addr_to_peer(req.remote_addr())?;
        let inbound = InboundStream::new(req.into_inner());
        let outbound = service.gossip_subscription(peer, Box::pin(inbound)).await?;
        let res = self.subscription_response(outbound);
        Ok(res)
    }
}