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
/*
* Copyright (C) 2020  Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
//! the smallest unit/data-structure that can go into the blockchain
//! ## Create a block
//! ```rust
//! use damn_vuln_blockchain::{ asset::AssetLedger, block::{BlockBuilder, Block}, chain::Chain};
//!
//!
//! fn main() {
//!        let chain = Chain::new("My chain"); // create blockchain
//!        let peer_id = "Me";
//!        let mut assets = AssetLedger::generate(peer_id); // generate some assets
//!        let asset = assets.assets.pop().unwrap();
//!
//!        // get the last block of a chain
//!        let prev = chain.get_last_block();
//!
//!        let block = BlockBuilder::default()
//!            .set_tx("Me")
//!            .set_rx("You")
//!            .set_prev(&prev)
//!            .set_asset_id(&asset.get_hash())
//!            .set_validator("Me")
//!            .build();
//!
//!        assert!(!block.is_genesis());
//!        assert_eq!(block.get_tx().unwrap(), "Me");
//!        assert_eq!(block.get_rx().unwrap(), "You");
//! }
//! ```

use derive_more::Display;
use serde::{Deserialize, Serialize};

/// Builder struct for [Block]
// custom  builder is required because
// Option<T> is needed for genesis
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
pub struct BlockBuilder {
    /// previous block's hash
    prev: String,
    /// sender's peer ID
    tx: String,
    /// receiver's peer ID
    rx: String,
    /// asset ID
    asset_id: String,
    /// validator's ID
    validator: String,
}

impl BlockBuilder {
    /// set previous block's hash
    pub fn set_prev(&mut self, prev: &Block) -> &mut Self {
        self.prev = prev.get_hash().into();
        self
    }

    /// set receiver's ID
    pub fn set_rx(&mut self, rx: &str) -> &mut Self {
        self.rx = rx.into();
        self
    }

    /// set sender's ID
    pub fn set_tx(&mut self, tx: &str) -> &mut Self {
        self.tx = tx.into();
        self
    }

    /// set validator's ID
    pub fn set_validator(&mut self, validator: &str) -> &mut Self {
        self.validator = validator.into();
        self
    }

    /// set assset ID
    pub fn set_asset_id(&mut self, assset_id: &str) -> &mut Self {
        self.asset_id = assset_id.into();
        self
    }

    fn hash(&self) -> String {
        use crate::utils::*;
        hasher(&format!("{}{}{}", self.prev, self.rx, self.tx))
    }

    /// Build block, this method must be called at the very end
    pub fn build(&mut self) -> Block {
        use crate::utils::*;
        if self.prev.is_empty()
            || self.rx.is_empty()
            || self.tx.is_empty()
            || self.asset_id.is_empty()
        {
            panic!("Can't create block, one or more fields are empty");
        } else {
            let hash = self.hash();
            Block {
                prev: Some(self.prev.to_owned()),
                tx: Some(self.tx.to_owned()),
                rx: Some(self.rx.to_owned()),
                hash,
                validator: Some(self.validator.to_owned()),
                timesamp: get_current_time(),
                serial_no: None,
                asset_id: Some(self.asset_id.to_owned()),
            }
        }
    }
}

#[derive(Display, Deserialize, Serialize, Clone, Debug, Default)]
#[display(fmt = "{}", hash)]
/// Smallest data-sctructure that can go into [Chain](crate::chain::Chain).
///
/// NOTE: `tx`, `prev`, validator and `rx` are `Option<_>` to accomodate
/// genesis block. Blockchain implementors must check for the
/// existence of genesis block before appending the block to
/// the ledger
pub struct Block {
    prev: Option<String>,
    hash: String,
    tx: Option<String>,
    rx: Option<String>,
    timesamp: String,
    validator: Option<String>,
    serial_no: Option<usize>,
    asset_id: Option<String>,
}

impl Block {
    /// Get block info as string
    #[cfg(not(tarpaulin_include))]
    pub fn to_string(&self) -> String {
        if self.is_genesis() {
            format!("Genesis block \nHash: {}", self.get_hash())
        } else {
            format!(
                "Previous Block: {}\nHash: {}\n Validator: {}\nSender: {}\nReceiver: {}\n",
                &self.get_prev().as_ref().unwrap(),
                &self.get_hash(),
                &self.get_validator().as_ref().unwrap(),
                &self.get_rx().as_ref().unwrap(),
                &self.get_tx().as_ref().unwrap()
            )
        }
    }

    /// creates genesis block
    pub fn genesis() -> Block {
        use crate::utils::*;

        let hash = hasher(&get_rand_string(10));
        Block {
            prev: None,
            tx: None,
            rx: None,
            hash,
            timesamp: get_current_time(),
            validator: None,
            serial_no: Some(0),
            asset_id: None,
        }
    }

    /// checks if the block is a genesis block
    pub fn is_genesis(&self) -> bool {
        if self.prev.is_none() || self.tx.is_none() || self.tx.is_none() || self.rx.is_none() {
            return true;
        }
        false
    }

    /// computes the hash of a block, uses the same logic
    /// for genesis blocks, it simply returns the hash stored
    /// in the block as [genesis()](Block::genesis) computes hash over random
    /// strings
    pub fn hash(&self) -> String {
        use crate::utils::*;
        if self.is_genesis() {
            return self.get_hash().into();
        } else {
            hasher(&format!(
                "{}{}{}",
                self.prev.as_ref().unwrap(),
                self.rx.as_ref().unwrap(),
                self.tx.as_ref().unwrap()
            ))
        }
    }

    /// get hash of previous block
    pub fn get_prev(&self) -> Option<&String> {
        self.prev.as_ref()
    }

    /// get hash of previous block
    pub fn get_asset_id(&self) -> Option<&String> {
        self.asset_id.as_ref()
    }

    /// get hash of block
    pub fn get_hash(&self) -> &str {
        &self.hash
    }

    /// get serial numbr of block
    pub fn get_serial_no(&self) -> Option<usize> {
        self.serial_no
    }

    /// set serial_no of block
    pub fn set_serial_no(&mut self, serial_no: usize) {
        self.serial_no = Some(serial_no);
    }

    /// get receiver involved in the transaction that lead tot
    /// the creation of this block
    pub fn get_rx(&self) -> Option<&String> {
        self.rx.as_ref()
    }

    /// get validator involved in the creation of this block
    pub fn get_validator(&self) -> Option<&String> {
        self.validator.as_ref()
    }

    /// get sender involved in the transaction that lead tot
    /// the creation of this block
    pub fn get_tx(&self) -> Option<&String> {
        self.tx.as_ref()
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn block_works() {
        use crate::asset::AssetLedger;

        let prev = Block::genesis();
        assert_eq!(prev.is_genesis(), true, "Genesis block identified");
        assert_eq!(prev.get_serial_no(), Some(0));

        assert_eq!(prev.hash(), prev.get_hash(), "Genesis block hash works");
        let mut assets = AssetLedger::generate("Me");
        let asset = assets.assets.pop().unwrap();

        let mut block = BlockBuilder::default()
            .set_tx("Me")
            .set_rx("You")
            .set_prev(&prev)
            .set_asset_id(&asset.get_hash())
            .build();

        assert_eq!(block.is_genesis(), false, "non-genesis block identified");
        assert_eq!(block.get_tx().unwrap(), "Me");
        assert_eq!(block.get_rx().unwrap(), "You");
        assert_eq!(block.get_serial_no(), None);

        block.set_serial_no(1);
        assert_eq!(block.get_serial_no(), Some(1));

        assert_eq!(
            block.hash(),
            block.get_hash(),
            "non-genesis block hash works"
        );
    }

    #[test]
    #[should_panic]
    fn block_panic_works() {
        let prev = Block::genesis();

        let _ = BlockBuilder::default()
            .set_rx("You")
            .set_tx("Me")
            .set_prev(&prev)
            .build();
    }

    #[test]
    #[should_panic]
    fn block_panic2_works() {
        let prev = Block::genesis();

        let _ = BlockBuilder::default().set_prev(&prev).build();
    }

    #[test]
    #[should_panic]
    fn block_panic3_works() {
        let _ = BlockBuilder::default().build();
    }
}