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
use super::{
    buffer_sizes,
    convert::{self, Decode, Encode, ResponseStream},
    p2p::{
        comm::{BlockEventSubscription, FragmentSubscription, GossipSubscription},
        Address,
    },
    subscription, Channels, GlobalStateR,
};
use crate::{
    blockcfg as app_data,
    intercom::{self, BlockMsg, ClientMsg, RequestSink, TopologyMsg},
    topology::{self, Gossips, NodeId},
    utils::async_msg::MessageBox,
};
use async_trait::async_trait;
use chain_network::{
    core::server::{BlockService, FragmentService, GossipService, Node, PushStream},
    data::{
        p2p::{AuthenticatedNodeId, Peer},
        Block, BlockId, BlockIds, Fragment, FragmentIds, Gossip, HandshakeResponse, Header,
    },
    error::{Code as ErrorCode, Error},
};
use futures::{prelude::*, try_join};
use std::convert::TryFrom;
use tracing::{instrument, Span};
use tracing_futures::Instrument;

#[derive(Clone)]
pub struct NodeService {
    channels: Channels,
    global_state: GlobalStateR,
}

impl NodeService {
    pub fn new(channels: Channels, global_state: GlobalStateR) -> Self {
        NodeService {
            channels,
            global_state,
        }
    }

    async fn peer_id(&self, addr: Address) -> Result<NodeId, Error> {
        self.global_state
            .peers
            .client_id(addr)
            .await
            .ok_or_else(|| Error::new(ErrorCode::FailedPrecondition, "handshake not performed"))
    }
}

#[async_trait]
impl Node for NodeService {
    type BlockService = Self;
    type FragmentService = Self;
    type GossipService = Self;

    async fn handshake(&self, peer: Peer, nonce: &[u8]) -> Result<HandshakeResponse, Error> {
        let block0_id = BlockId::try_from(self.global_state.block0_hash.as_bytes()).unwrap();
        let keypair = &self.global_state.keypair;
        let auth = keypair.sign(nonce);
        let addr = peer.addr();
        let nonce = self.global_state.peers.generate_auth_nonce(addr).await;

        Ok(HandshakeResponse {
            block0_id,
            auth,
            nonce: nonce.into(),
        })
    }

    /// Handles client ID authentication.
    async fn client_auth(&self, peer: Peer, auth: AuthenticatedNodeId) -> Result<(), Error> {
        let addr = peer.addr();
        let id = auth.id().clone().decode()?;
        self.global_state
            .peers
            .server_complete_handshake(addr, id, |nonce| auth.verify(&nonce[..]))
            .await?;
        Ok(())
    }

    fn block_service(&self) -> Option<&Self::BlockService> {
        Some(self)
    }

    fn fragment_service(&self) -> Option<&Self::FragmentService> {
        Some(self)
    }

    fn gossip_service(&self) -> Option<&Self::GossipService> {
        Some(self)
    }
}

async fn send_message<T>(mut mbox: MessageBox<T>, msg: T) -> Result<(), Error> {
    mbox.send(msg).await.map_err(|e| {
        tracing::error!(
            reason = %e,
            "failed to enqueue message for processing"
        );
        Error::new(ErrorCode::Internal, e)
    })
}

type SubscriptionStream<S> =
    stream::Map<S, fn(<S as Stream>::Item) -> Result<<S as Stream>::Item, Error>>;

fn serve_subscription<S: Stream>(sub: Option<S>) -> Result<SubscriptionStream<S>, Error> {
    Ok(sub
        .ok_or_else(|| Error::new(ErrorCode::FailedPrecondition, "handshake not performed"))?
        .map(Ok))
}

// extracted as an external function as a workaround for
// https://github.com/dtolnay/async-trait/issues/144
async fn join_streams<T, V, E, R>(
    stream: PushStream<T>,
    sink: RequestSink<<T as Decode>::Object>,
    reply: V,
) -> Result<(), Error>
where
    T: Decode,
    E: Into<Error>,
    V: Future<Output = Result<R, E>>,
{
    try_join!(
        stream
            .and_then(|header| async { header.decode() })
            .forward(sink.sink_err_into()),
        reply.err_into::<Error>(),
    )?;
    Ok(())
}

#[async_trait]
impl BlockService for NodeService {
    type PullBlocksStream = ResponseStream<app_data::Block>;
    type PullBlocksToTipStream = ResponseStream<app_data::Block>;
    type GetBlocksStream = ResponseStream<app_data::Block>;
    type PullHeadersStream = ResponseStream<app_data::Header>;
    type GetHeadersStream = ResponseStream<app_data::Header>;
    type SubscriptionStream = SubscriptionStream<BlockEventSubscription>;

    #[instrument(level = "debug", skip(self))]
    async fn tip(&self) -> Result<Header, Error> {
        let (reply_handle, reply_future) = intercom::unary_reply();
        let mbox = self.channels.client_box.clone();
        send_message(mbox, ClientMsg::GetBlockTip(reply_handle)).await?;
        let header = reply_future.await?;
        Ok(header.encode())
    }

    #[instrument(level = "debug", skip(self))]
    async fn pull_blocks(
        &self,
        from: BlockIds,
        to: BlockId,
    ) -> Result<Self::PullBlocksStream, Error> {
        let from = from.decode()?;
        let to = to.decode()?;
        let (handle, future) = intercom::stream_reply(buffer_sizes::outbound::BLOCKS);
        let client_box = self.channels.client_box.clone();
        send_message(client_box, ClientMsg::PullBlocks(from, to, handle)).await?;
        let stream = future.await?;
        Ok(convert::response_stream(stream))
    }

    #[instrument(level = "debug", skip(self))]
    async fn pull_blocks_to_tip(
        &self,
        from: BlockIds,
    ) -> Result<Self::PullBlocksToTipStream, Error> {
        let from = from.decode()?;
        let (handle, future) = intercom::stream_reply(buffer_sizes::outbound::BLOCKS);
        let client_box = self.channels.client_box.clone();
        send_message(client_box, ClientMsg::PullBlocksToTip(from, handle)).await?;
        let stream = future.await?;
        Ok(convert::response_stream(stream))
    }

    #[instrument(level = "debug", skip(self))]
    async fn get_blocks(&self, ids: BlockIds) -> Result<Self::GetBlocksStream, Error> {
        let ids = ids.decode()?;
        let (handle, future) = intercom::stream_reply(buffer_sizes::outbound::BLOCKS);
        let client_box = self.channels.client_box.clone();
        send_message(client_box, ClientMsg::GetBlocks(ids, handle)).await?;
        let stream = future.await?;
        Ok(convert::response_stream(stream))
    }

    #[instrument(level = "debug", skip(self))]
    async fn get_headers(&self, ids: BlockIds) -> Result<Self::GetHeadersStream, Error> {
        let ids = ids.decode()?;
        let (handle, future) = intercom::stream_reply(buffer_sizes::outbound::HEADERS);
        let client_box = self.channels.client_box.clone();
        send_message(client_box, ClientMsg::GetHeaders(ids, handle)).await?;
        let stream = future.await?;
        Ok(convert::response_stream(stream))
    }

    #[instrument(level = "debug", skip(self))]
    async fn pull_headers(
        &self,
        from: BlockIds,
        to: BlockId,
    ) -> Result<Self::PullHeadersStream, Error> {
        let from = from.decode()?;
        let to = to.decode()?;
        let (handle, future) = intercom::stream_reply(buffer_sizes::outbound::HEADERS);
        let client_box = self.channels.client_box.clone();
        send_message(client_box, ClientMsg::PullHeaders(from, to, handle)).await?;
        let stream = future.await?;
        Ok(convert::response_stream(stream))
    }

    #[instrument(level = "debug", skip(self, stream))]
    async fn push_headers(&self, stream: PushStream<Header>) -> Result<(), Error> {
        let (handle, sink, reply) = intercom::stream_request(buffer_sizes::inbound::HEADERS);
        let block_box = self.channels.block_box.clone();
        send_message(block_box, BlockMsg::ChainHeaders(handle)).await?;
        join_streams(stream, sink, reply).await
    }

    #[instrument(level = "debug", skip(self, stream))]
    async fn upload_blocks(&self, stream: PushStream<Block>) -> Result<(), Error> {
        let (handle, sink, reply) = intercom::stream_request(buffer_sizes::inbound::BLOCKS);
        let block_box = self.channels.block_box.clone();
        send_message(block_box, BlockMsg::NetworkBlocks(handle)).await?;
        join_streams(stream, sink, reply).await
    }

    #[instrument(level = "debug", skip_all, fields(addr = %subscriber, id))]
    async fn block_subscription(
        &self,
        subscriber: Peer,
        stream: PushStream<Header>,
    ) -> Result<Self::SubscriptionStream, Error> {
        let peer_id = self.peer_id(subscriber.addr()).await?;
        Span::current().record("id", peer_id.to_string().as_str());
        self.global_state.spawn(
            subscription::process_block_announcements(
                stream,
                self.channels.block_box.clone(),
                peer_id,
                self.global_state.clone(),
            )
            .in_current_span(),
        );

        let outbound = self
            .global_state
            .peers
            .subscribe_to_block_events(&peer_id)
            .await;
        Ok(serve_subscription(outbound)?)
    }
}

#[async_trait]
impl FragmentService for NodeService {
    type GetFragmentsStream = ResponseStream<app_data::Fragment>;
    type SubscriptionStream = SubscriptionStream<FragmentSubscription>;

    async fn get_fragments(&self, _ids: FragmentIds) -> Result<Self::GetFragmentsStream, Error> {
        Err(Error::unimplemented())
    }

    #[instrument(level = "debug", skip_all, fields(direction = "in", addr = %subscriber, id))]
    async fn fragment_subscription(
        &self,
        subscriber: Peer,
        stream: PushStream<Fragment>,
    ) -> Result<Self::SubscriptionStream, Error> {
        let peer_id = self.peer_id(subscriber.addr()).await?;
        Span::current().record("id", peer_id.to_string().as_str());
        self.global_state.spawn(
            subscription::process_fragments(
                stream,
                self.channels.transaction_box.clone(),
                peer_id,
                self.global_state.clone(),
            )
            .in_current_span(),
        );

        let outbound = self
            .global_state
            .peers
            .subscribe_to_fragments(&peer_id)
            .await;
        Ok(serve_subscription(outbound)?)
    }
}

#[async_trait]
impl GossipService for NodeService {
    type SubscriptionStream = SubscriptionStream<GossipSubscription>;

    #[instrument(level = "debug", skip_all, fields(direction = "in", addr = %subscriber, id))]
    async fn gossip_subscription(
        &self,
        subscriber: Peer,
        stream: PushStream<Gossip>,
    ) -> Result<Self::SubscriptionStream, Error> {
        let peer_id = self.peer_id(subscriber.addr()).await?;
        Span::current().record("id", peer_id.to_string().as_str());
        self.global_state.spawn(
            subscription::process_gossip(
                stream,
                self.channels.topology_box.clone(),
                peer_id,
                self.global_state.clone(),
            )
            .in_current_span(),
        );

        let outbound = self.global_state.peers.subscribe_to_gossip(&peer_id).await;
        Ok(serve_subscription(outbound)?)
    }

    #[instrument(level = "debug", skip(self))]
    async fn peers(&self, limit: u32) -> Result<Gossip, Error> {
        let (reply_handle, reply_future) = intercom::unary_reply();
        let mbox = self.channels.topology_box.clone();
        send_message(
            mbox,
            TopologyMsg::View(poldercast::layer::Selection::Any, reply_handle),
        )
        .await?;
        let res = reply_future.await?;
        let gossip = Gossips::from(
            std::iter::once(res.self_node)
                .chain(res.peers.into_iter())
                .take(limit as usize)
                .map(topology::Gossip::from)
                .collect::<Vec<_>>(),
        )
        .encode();
        Ok(gossip)
    }
}