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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#![allow(unused_imports)]
use log::{info, error, debug};

use serde::{Serialize, Deserialize};

use crate::session::{Session, SessionProperty};

use super::crypto::*;
use super::compact::*;
use super::lint::*;
use super::transform::*;
use super::meta::*;
use super::error::*;
use super::transaction::*;
use super::pipe::*;
use super::chain::*;

use super::conf::*;
use super::header::*;
use super::validator::*;
use super::event::*;
use super::index::*;
use super::lint::*;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::rc::Rc;

use std::io::Write;
use super::redo::*;
use bytes::Bytes;

use super::event::*;
use super::crypto::Hash;
use fxhash::FxHashMap;
use super::spec::*;

/// Unique key that represents this chain-of-trust. The design must
/// partition their data space into seperate chains to improve scalability
/// and performance as a single chain will reside on a single node within
/// the cluster.
#[allow(dead_code)]
#[derive(Serialize, Deserialize, Debug, Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ChainKey {
    pub name: String,
    #[serde(skip)]
    pub hash: Option<Hash>,
}

impl std::fmt::Display
for ChainKey {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.name)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntegrityMode
{
    Centralized,
    Distributed
}

impl std::fmt::Display
for IntegrityMode {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            IntegrityMode::Centralized => write!(f, "centralized"),
            IntegrityMode::Distributed => write!(f, "distributed")
        }
    }
}

impl ChainKey {
    #[allow(dead_code)]
    pub fn new(mut val: String) -> ChainKey {
        if val.starts_with("/") == false {
            val = format!("/{}", val);
        }
        
        ChainKey {
            hash: Some(Hash::from_bytes(val.as_bytes())),
            name: val,
        }
    }

    #[allow(dead_code)]
    pub fn with_name(&self, val: String) -> ChainKey
    {
        let mut ret = self.clone();
        ret.name = val;
        ret
    }

    #[allow(dead_code)]
    pub fn with_temp_name(&self, val: String) -> ChainKey
    {
        let mut ret = self.clone();
        ret.name = format!("{}_{}", val, PrimaryKey::generate().as_hex_string());
        ret
    }

    pub fn hash(&self) -> Hash
    {
        match &self.hash {
            Some(a) => a.clone(),
            None => Hash::from_bytes(self.name.as_bytes())
        }
    }

    pub fn hash64(&self) -> u64
    {
        match &self.hash {
            Some(a) => a.to_u64(),
            None => Hash::from_bytes(self.name.as_bytes()).to_u64()
        }
    }

    pub fn to_string(&self) -> String
    {
        self.name.clone()
    }

    pub fn from_url(url: &url::Url) -> ChainKey
    {
        ChainKey::new(url.path().to_string())
    }
}

impl From<String>
for ChainKey
{
    fn from(val: String) -> ChainKey {
        ChainKey::new(val)
    }
}

impl From<&'static str>
for ChainKey
{
    fn from(val: &'static str) -> ChainKey {
        ChainKey::new(val.to_string())
    }
}

impl From<u64>
for ChainKey
{
    fn from(val: u64) -> ChainKey {
        ChainKey::new(val.to_string())
    }
}

#[allow(dead_code)]
pub(crate) struct ChainOfTrust
{
    pub(super) key: ChainKey,
    pub(super) redo: RedoLog,
    pub(super) history_offset: u64,
    pub(super) history_reverse: FxHashMap<Hash, u64>,
    pub(super) history: BTreeMap<u64, EventHeaderRaw>,
    pub(super) pointers: BinaryTreeIndexer,
    pub(super) compactors: Vec<Box<dyn EventCompactor>>,
}

#[derive(Debug, Clone)]
pub struct LoadResult
{
    pub(crate) offset: u64,
    pub header: EventHeaderRaw,
    pub data: EventData,
    pub leaf: EventLeaf,
}

impl<'a> ChainOfTrust
{
    pub(super) async fn load(&self, leaf: EventLeaf) -> Result<LoadResult, LoadError> {
        let data = self.redo.load(leaf.record.clone()).await?;
        Ok(LoadResult {
            offset: data.offset,
            header: data.header,
            data: data.data,
            leaf: leaf,
        })
    }

    pub(super) async fn load_many(&self, leafs: Vec<EventLeaf>) -> Result<Vec<LoadResult>, LoadError>
    {
        let mut ret = Vec::new();

        let mut futures = Vec::new();
        for leaf in leafs.into_iter() {
            let data = self.redo.load(leaf.record.clone());
            futures.push((data, leaf));
        }

        for (join, leaf) in futures.into_iter() {
            let data = join.await?;
            ret.push(LoadResult {
                offset: data.offset,
                header: data.header,
                data: data.data,
                leaf,
            });
        }

        Ok(ret)
    }

    pub(super) fn lookup_primary(&self, key: &PrimaryKey) -> Option<EventLeaf>
    {
        self.pointers.lookup_primary(key)
    }

    pub(super) fn lookup_parent(&self, key: &PrimaryKey) -> Option<MetaParent> {
        self.pointers.lookup_parent(key)
    }

    pub(super) fn lookup_secondary(&self, key: &MetaCollection) -> Option<Vec<EventLeaf>>
    {
        self.pointers.lookup_secondary(key)
    }

    pub(super) fn lookup_secondary_raw(&self, key: &MetaCollection) -> Option<Vec<PrimaryKey>>
    {
        self.pointers.lookup_secondary_raw(key)
    }

    pub(super) async fn flush(&mut self) -> Result<(), tokio::io::Error> {
        self.redo.flush().await
    }

    #[allow(dead_code)]
    pub(super) async fn destroy(&mut self) -> Result<(), tokio::io::Error> {
        self.redo.destroy()
    }

    #[allow(dead_code)]
    pub(crate) fn name(&self) -> String {
        self.key.name.clone()
    }

    pub(crate) fn add_history(&mut self, header: &EventHeader) {
        let raw = header.raw.clone();
        if header.meta.include_in_history() {
            let offset = self.history_offset;
            self.history_offset = self.history_offset + 1;
            self.history_reverse.insert(raw.event_hash.clone(), offset);
            self.history.insert(offset, raw);
        }
    }
}

#[cfg(test)]
pub(crate) async fn create_test_chain(mock_cfg: &mut ConfAte, chain_name: String, temp: bool, barebone: bool, root_public_key: Option<PublicSignKey>) ->
    (Arc<Chain>, Arc<ChainOfTrustBuilder>)
{
    // Create the chain-of-trust and a validator
    let mock_chain_key = match temp {
        true => ChainKey::default().with_temp_name(chain_name),
        false => ChainKey::default().with_name(chain_name),
    };

    let mut builder = match barebone {
        true => {
            mock_cfg.configured_for(ConfiguredFor::Barebone);
            mock_cfg.log_format.meta = SerializationFormat::Bincode;
            mock_cfg.log_format.data = SerializationFormat::Json;

            ChainOfTrustBuilder::new(&mock_cfg)
                .await
                .add_validator(Box::new(RubberStampValidator::default()))
                .add_data_transformer(Box::new(StaticEncryptionTransformer::new(&EncryptKey::from_seed_string("test".to_string(), KeySize::Bit192))))
                .add_metadata_linter(Box::new(EventAuthorLinter::default()))
        },
        false => {
            mock_cfg.configured_for(ConfiguredFor::Balanced);
            mock_cfg.log_format.meta = SerializationFormat::Json;
            mock_cfg.log_format.data = SerializationFormat::Json;

            ChainOfTrustBuilder::new(&mock_cfg).await
        }
    };        

    if let Some(key) = root_public_key {
        builder = builder.add_root_public_key(&key);
    }

    let builder = builder.build();

    (
        builder.open(&mock_chain_key).await.unwrap(),
        builder
    )
}

#[tokio::main]
#[test]
async fn test_chain() {
    crate::utils::bootstrap_env();
    //env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();

    let key1 = PrimaryKey::generate();
    let key2 = PrimaryKey::generate();
    let chain_name;

    let mut evt1;
    let mut evt2;

    {
        debug!("creating test chain");
        let mut mock_cfg = crate::conf::mock_test_config();
        let (chain, _builder) = create_test_chain(&mut mock_cfg, "test_chain".to_string(), true, true, None).await;
        chain_name = chain.name().await;
        
        evt1 = EventData::new(key1.clone(), Bytes::from(vec!(1; 1)), mock_cfg.log_format);
        evt2 = EventData::new(key2.clone(), Bytes::from(vec!(2; 1)), mock_cfg.log_format);

        {
            let lock = chain.multi().await;
            assert_eq!(0, lock.count().await);
            
            // Push the first events into the chain-of-trust
            let mut evts = Vec::new();
            evts.push(evt1.clone());
            evts.push(evt2.clone());

            debug!("feeding two events into the chain");
            let trans = Transaction::from_events(evts, Scope::Local, false);
            lock.pipe.feed(trans).await.expect("The event failed to be accepted");
            
            drop(lock);
            assert_eq!(2, chain.count().await);
        }

        {
            let lock = chain.multi().await;

            // Make sure its there in the chain
            debug!("checking event1 is in the chain");
            let test_data = lock.lookup_primary(&key1).await.expect("Failed to find the entry after the flip");
            let test_data = lock.load(test_data.clone()).await.expect("Could not load the data for the entry");
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(1; 1))));

            // The other event we added should also still be there
            debug!("checking event2 is in the chain");
            let test_data = lock.lookup_primary(&key2).await.expect("Failed to find the entry after the compact");
            let test_data = lock.load(test_data.clone()).await.unwrap();
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(2; 1))));
        }
    }

    {
        // Reload the chain from disk and check its integrity
        debug!("reloading the chain");
        let mut mock_cfg = crate::conf::mock_test_config();
        let (chain, _builder) = create_test_chain(&mut mock_cfg, chain_name.clone(), false, true, None).await;
            
        {
            let lock = chain.multi().await;

            // Make sure its there in the chain
            debug!("checking event1 is in the chain");
            let test_data = lock.lookup_primary(&key1).await.expect("Failed to find the entry after the reload");
            let test_data = lock.load(test_data.clone()).await.expect("Could not load the data for the entry");
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(1; 1))));

            // The other event we added should also still be there
            debug!("checking event2 is in the chain");
            let test_data = lock.lookup_primary(&key2).await.expect("Failed to find the entry after the reload");
            let test_data = lock.load(test_data.clone()).await.unwrap();
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(2; 1))));

            // Duplicate one of the event so the compactor has something to clean
            evt1.data_bytes = Some(Bytes::from(vec!(10; 1)));
            
            debug!("feeding new version of event1 into the chain");
            let mut evts = Vec::new();
            evts.push(evt1.clone());
            let trans = Transaction::from_events(evts, Scope::Local, false);
            lock.pipe.feed(trans).await.expect("The event failed to be accepted");

            drop(lock);
            assert_eq!(3, chain.count().await);
        }

        // Now compact the chain-of-trust which should reduce the duplicate event
        debug!("compacting the log and checking the counts");
        assert_eq!(3, chain.count().await);
        chain.compact().await.expect("Failed to compact the log");
        assert_eq!(2, chain.count().await);

        {
            let lock = chain.multi().await;

            // Read the event and make sure its the second one that results after compaction
            debug!("checking event1 is in the chain");
            let test_data = lock.lookup_primary(&key1).await.expect("Failed to find the entry after the compact");
            let test_data = lock.load(test_data.clone()).await.unwrap();
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(10; 1))));

            // The other event we added should also still be there
            debug!("checking event2 is in the chain");
            let test_data = lock.lookup_primary(&key2).await.expect("Failed to find the entry after the compact");
            let test_data = lock.load(test_data.clone()).await.unwrap();
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(2; 1))));
        }
    }

    {
        // Reload the chain from disk and check its integrity
        debug!("reloading the chain");
        let mut mock_cfg = crate::conf::mock_test_config();
        let (chain, _builder) = create_test_chain(&mut mock_cfg, chain_name.clone(), false, true, None).await;

        {
            let lock = chain.multi().await;

            // Read the event and make sure its the second one that results after compaction
            debug!("checking event1 is in the chain");
            let test_data = lock.lookup_primary(&key1).await.expect("Failed to find the entry after the compact");
            let test_data = lock.load(test_data.clone()).await.unwrap();
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(10; 1))));

            // The other event we added should also still be there
            debug!("checking event2 is in the chain");
            let test_data = lock.lookup_primary(&key2).await.expect("Failed to find the entry after the compact");
            let test_data = lock.load(test_data.clone()).await.unwrap();
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(2; 1))));
        }

        {
            let lock = chain.multi().await;

            // Now lets tombstone the second event
            debug!("tombstoning event2");
            evt2.meta.add_tombstone(key2);
            
            debug!("feeding the tombstone into the chain");
            let mut evts = Vec::new();
            evts.push(evt2.clone());
            let trans = Transaction::from_events(evts, Scope::Local, false);
            lock.pipe.feed(trans).await.expect("The event failed to be accepted");
            
            // Number of events should have gone up by one even though there should be one less item
            drop(lock);
            assert_eq!(3, chain.count().await);
        }

        // Searching for the item we should not find it
        debug!("checking event2 is gone from the chain");
        match chain.multi().await.lookup_primary(&key2).await {
            Some(_) => panic!("The item should not be visible anymore"),
            None => {}
        }
        
        // Now compact the chain-of-trust which should remove one of the events and its tombstone
        debug!("compacting the chain");
        chain.compact().await.expect("Failed to compact the log");
        assert_eq!(1, chain.count().await);
    }

    {
        // Reload the chain from disk and check its integrity
        debug!("reloading the chain");
        let mut mock_cfg = crate::conf::mock_test_config();
        let (chain, _builder) = create_test_chain(&mut mock_cfg, chain_name.clone(), false, true, None).await;

        {
            let lock = chain.multi().await;

            // Read the event and make sure its the second one that results after compaction
            debug!("checking event1 is in the chain");
            let test_data = lock.lookup_primary(&key1).await.expect("Failed to find the entry after we reloaded the chain");
            let test_data = lock.load(test_data).await.unwrap();
            assert_eq!(test_data.data.data_bytes, Some(Bytes::from(vec!(10; 1))));
        }

        // Destroy the chain
        debug!("destroying the chain");
        chain.single().await.destroy().await.unwrap();
    }
}