summaryrefslogtreecommitdiff
path: root/src/network.rs
blob: fd0362c75d31af5633c5938a3ebaf2091c6f24cb (plain)
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
use std::sync::{Arc, Weak};

use serde::{Deserialize, Serialize};

use futures::{SinkExt, StreamExt};
use tokio::{
    net::{TcpListener, TcpStream},
    spawn,
    sync::Mutex,
};
use tokio_serde::{Framed, formats::Json};
use tokio_util::codec::Framed as TokioFramed;
use tokio_util::codec::LengthDelimitedCodec;

use crate::{
    blocks::{Block, BlockChain},
    client::Client,
};

#[derive(Deserialize, Serialize, Clone)]
pub enum Request {
    Block(Block),
    Ibd(Option<BlockChain>),
}

pub struct Network {
    this: Weak<Mutex<Self>>,
    me: Client,
    listener: Arc<TcpListener>,
    peers: Vec<Arc<Mutex<Peer>>>,
    blockchain: Arc<Mutex<BlockChain>>,
}

impl Network {
    pub async fn new(blockchain: Arc<Mutex<BlockChain>>) -> Arc<Mutex<Self>> {
        let listener = TcpListener::bind("0.0.0.0:6767")
            .await
            .unwrap();
        let this = Arc::new(Mutex::new(Self {
            me: Client::default(),
            this: Weak::new(),
            listener: Arc::new(listener),
            peers: Vec::default(),
            blockchain,
        }));
        this.lock()
            .await
            .this = Arc::downgrade(&this);
        this
    }

    async fn try_peer(&mut self) {
        let peer = Arc::new(Mutex::new(Peer::new(
            self.this
                .clone(),
            TcpStream::connect("192.168.143.90:6767")
                .await
                .unwrap(),
        )));
        self.peers
            .push(Arc::clone(&peer));

        spawn(async move {
            peer.lock()
                .await
                .start()
                .await;
        });
    }

    pub fn start(&self) {
        let this = self
            .this
            .clone();
        let listener = self
            .listener
            .clone();
        spawn(async move {
            loop {
                let (stream, _addr) = listener
                    .accept()
                    .await
                    .unwrap();

                let peer = Arc::new(Mutex::new(Peer::new(this.clone(), stream)));

                if let Some(parent) = this.upgrade() {
                    let mut net = parent
                        .lock()
                        .await;
                    net.peers
                        .push(Arc::clone(&peer));
                }

                spawn({
                    let peer = Arc::clone(&peer);
                    async move {
                        peer.lock()
                            .await
                            .start()
                            .await;
                    }
                });
            }
        });
        let this = self
            .this
            .clone();
        spawn(async move {
            if let Some(parent) = this.upgrade() {
                let mut net = parent
                    .lock()
                    .await;
                net.try_peer()
                    .await;
            }
        });
    }

    pub async fn broadcast(&mut self, data: Request) {
        for p in &self.peers {
            p.lock()
                .await
                .framed
                .send(data.clone())
                .await
                .unwrap();
        }
    }
}

struct Peer {
    parent: Weak<Mutex<Network>>,
    framed: Framed<TokioFramed<TcpStream, LengthDelimitedCodec>, Request, Request, Json<Request, Request>>,
}

impl Peer {
    fn new(parent: Weak<Mutex<Network>>, stream: TcpStream) -> Self {
        Self {
            parent,
            framed: Framed::new(TokioFramed::new(stream, LengthDelimitedCodec::new()), Json::default()),
        }
    }

    async fn start(&mut self) {
        loop {
            while let Some(req) = self
                .framed
                .next()
                .await
            {
                self.handle(req.unwrap())
                    .await;
            }
        }
    }

    async fn handle(&mut self, req: Request) {
        match req {
            Request::Block(mut block) => match block.pow {
                Some(pow) => {
                    if !block.verify_pow() {
                        eprintln!("Rejecting remote block, POW verification failed"); // TODO: log remote IP
                        return;
                    }
                    self.parent
                        .upgrade()
                        .unwrap()
                        .lock()
                        .await
                        .blockchain
                        .lock()
                        .await
                        .store(block)
                }
                None => {
                    block.calc_set_pow();
                    let parent = self
                        .parent
                        .upgrade()
                        .unwrap();
                    let mut parent = parent
                        .lock()
                        .await;
                    parent
                        .broadcast(Request::Block(block))
                        .await;
                }
            },
            Request::Ibd(bc) => match bc {
                Some(bc) => {
                    let parent = self
                        .parent
                        .upgrade()
                        .unwrap();
                    let parent = parent
                        .lock()
                        .await;
                    let mut self_bc = parent
                        .blockchain
                        .lock()
                        .await;
                    // verify if our blocks match theirs
                    if *self_bc != bc {
                        eprintln!("Remote IBD broadcast did not match ours") // TODO: log IP of sender
                        // TODO: verify POWs, prev_hash of theirs(check missing), verify our POWs and if they have more blocks if their's all correct
                        // TODO: maybe queue and see if everybody else's blockchain match and is verified and has more block
                    }
                }
                None => {
                    let parent = self
                        .parent
                        .upgrade()
                        .unwrap();
                    let mut parent = parent
                        .lock()
                        .await;
                    let bc = {
                        let guard = parent
                            .blockchain
                            .lock()
                            .await;
                        guard.clone()
                    };
                    parent
                        .broadcast(Request::Ibd(Some(bc)))
                        .await;
                }
            },
        }
    }
}