p2panda-rs 0.4.0

All the things a panda needs
Documentation
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Mock p2panda node.
//!
//! This node mocks functionality which would be implemented in a real world p2panda node. It does
//! so in a simplistic manner and should only be used in a testing environment or demo environment.
//!
//! ## Example
//!
//! ```
//! use p2panda_rs::operation::OperationValue;
//! use p2panda_rs::schema::SchemaId;
//! use p2panda_rs::test_utils::constants::TEST_SCHEMA_ID;
//! use p2panda_rs::test_utils::mocks::{send_to_node, Client, Node};
//! use p2panda_rs::test_utils::fixtures::{
//!     create_operation, delete_operation, schema, random_key_pair, operation_fields, update_operation,
//! };
//!
//! // Instantiate a new mock node
//! let mut node = Node::new();
//!
//! // Instantiate one client named "panda"
//! let panda = Client::new("panda".to_string(), random_key_pair());
//!
//! // Panda creates a new chat document by publishing a CREATE operation
//! let (document1_hash_id, _) = send_to_node(
//!     &mut node,
//!     &panda,
//!     &create_operation(
//!         &[(
//!             "message",
//!             OperationValue::Text("Ohh, my first message!".to_string()),
//!         )],
//!     )
//! )
//! .unwrap();
//!
//! // Panda updates the document by publishing an UPDATE operation
//! let (entry2_hash, _) = send_to_node(
//!     &mut node,
//!     &panda,
//!     &update_operation(
//!         &[(
//!             "message",
//!             OperationValue::Text("Which I now update.".to_string()),
//!         )],
//!         &document1_hash_id.clone().into(),
//!     )
//! )
//! .unwrap();
//!
//! // Panda deletes their document by publishing a DELETE operation
//! send_to_node(
//!     &mut node,
//!     &panda,
//!     &delete_operation(
//!         &entry2_hash.into()
//!     )
//! )
//! .unwrap();
//!
//! // Panda creates another chat document by publishing a new CREATE operation
//! send_to_node(
//!     &mut node,
//!     &panda,
//!     &create_operation(
//!         &[(
//!             "message",
//!             OperationValue::Text("Let's try that again.".to_string()),
//!         )],
//!     )
//! )
//! .unwrap();
//!
//! // Get all entries published to this node
//! let entries = node.all_entries();
//!
//! // There should be 4 entries
//! entries.len(); // => 4
//! ```
use bamboo_rs_core_ed25519_yasmf::entry::is_lipmaa_required;
use log::{debug, info};

use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;

use crate::document::{Document, DocumentBuilder};
use crate::entry::{decode_entry, EntrySigned, SeqNum};
use crate::hash::Hash;
use crate::identity::Author;
use crate::operation::{
    AsOperation, AsVerifiedOperation, Operation, OperationEncoded, VerifiedOperation,
};
use crate::test_utils::mocks::logs::{AuthorLogs, LogEntry};
use crate::test_utils::mocks::utils::Result;
use crate::test_utils::mocks::Client;
use crate::test_utils::utils::NextEntryArgs;

/// Helper method signing and encoding entry and sending it to node backend.
pub fn send_to_node(
    node: &mut Node,
    client: &Client,
    operation: &Operation,
) -> Result<(Hash, NextEntryArgs)> {
    // We need to establish which document this operation is targeting before proceeding.
    // First we check if this is a create message, which would mean no document exists yet.
    let document_id = if operation.is_create() {
        None
    } else {
        // If this isn't a create message, then there must be an existing document
        // this operation to be valid.

        // We get the previous_operations field first.
        let previous_operations = operation
            .previous_operations()
            .expect("UPDATE / DELETE operations must contain previous_operations");

        // Using the first previous operation in the list we retrieve the associated document
        // id from the database.
        let document_id = node
            .get_document_id_by_entry(previous_operations.into_iter().next().unwrap().as_hash());

        Some(document_id.expect("This node does not contain the required document"))
    };

    // Here we can retrieve the correct entry arguments for constructing an entry.
    let entry_args = node.get_next_entry_args(&client.author(), document_id.as_ref(), None)?;

    // The entry is constructed, signed and encoded.
    let entry_encoded = client.signed_encoded_entry(operation.to_owned(), entry_args);

    // The operation is also encoded.
    let operation_encoded = OperationEncoded::try_from(operation).unwrap();

    // Both are published to the node.
    let next_entry_args = node.publish_entry(&entry_encoded, &operation_encoded)?;

    // Return entry hash so we can use it to perform UPDATE and DELETE operations later.
    // @TODO: We really want to return the next entry args here which would include
    // the document graph tips. This requires integrating Document into the test utils.
    Ok((entry_encoded.hash(), next_entry_args))
}

/// Calculate the skiplink and backlink at a certain point in a log of entries.
fn calculate_links(seq_num: &SeqNum, log: &[LogEntry]) -> (Option<Hash>, Option<Hash>) {
    // Next skiplink hash
    let skiplink = match seq_num.skiplink_seq_num() {
        Some(seq) if is_lipmaa_required(seq_num.as_u64()) => Some(
            log.get(seq.as_u64() as usize - 1)
                .expect("Skiplink missing!")
                .hash(),
        ),
        _ => None,
    };

    // Next backlink hash
    let backlink = seq_num.backlink_seq_num().map(|seq| {
        log.get(seq.as_u64() as usize - 1)
            .expect("Backlink missing!")
            .hash()
    });
    (backlink, skiplink)
}

/// Mock database type.
///
/// Maps the public key of an author against a map of their logs identified by log id.
pub type Database = HashMap<String, AuthorLogs>;

/// This node mocks functionality which would be implemented in a real world p2panda node.
///
/// It does so in a simplistic manner and should only be used in a testing environment or demo
/// environment.
#[derive(Debug, Default)]
pub struct Node {
    /// Internal database structure.
    db: Database,
}

impl Node {
    /// Create a new mock Node.
    pub fn new() -> Self {
        Self {
            db: Database::new(),
        }
    }

    /// Return the entire database.
    pub fn db(&self) -> Database {
        self.db.clone()
    }

    /// Return an array of authors who publish to this node.
    pub fn get_authors(&self) -> Vec<&String> {
        self.db.keys().into_iter().collect()
    }

    /// Get a mutable map of all logs published by a certain author.
    fn get_author_logs_mut(&mut self, author: &Author) -> Option<&mut AuthorLogs> {
        self.db.get_mut(author.as_str())
    }

    /// Get a map of all logs published by a certain author.
    fn get_author_logs(&self, author: &Author) -> Option<&AuthorLogs> {
        self.db.get(author.as_str())
    }

    /// Get entry by id
    pub fn get_entry(&self, id: &Hash) -> LogEntry {
        self.all_entries()
            .iter()
            .find(|entry| &entry.hash() == id)
            .unwrap()
            .to_owned()
    }

    /// Get the document id associated with the passed entry hash.
    fn get_document_id_by_entry(&self, entry: &Hash) -> Option<Hash> {
        let mut document_id = None;
        self.db.iter().any(|(_author, logs)| {
            let document_log = logs.find_document_log_by_entry(entry);
            match document_log {
                Some(log) => {
                    document_id = Some(log.document());
                    true
                }
                None => false,
            }
        });
        document_id
    }

    /// Get an array of all entries in database.
    pub fn all_entries(&self) -> Vec<LogEntry> {
        let mut all_entries: Vec<LogEntry> = Vec::new();
        self.db.iter().for_each(|(_id, author_logs)| {
            author_logs
                .iter()
                .for_each(|log| all_entries.append(log.entries().as_mut()))
        });
        all_entries
    }

    /// Public wrapper with logging for private next_entry_args method.
    ///
    /// Returns the log id, sequence number, skiplink and backlink hash for a given author and
    /// document. All of this information is needed to create and sign a new entry.
    ///
    /// If a value for the optional seq_num parameter is passed then next entry args *at that
    /// point* in this log are returned. This is helpful when generating test data and wanting to
    /// test the flow from requesting entry args through to publishing an entry.
    pub fn get_next_entry_args(
        &self,
        author: &Author,
        document_id: Option<&Hash>,
        seq_num: Option<&SeqNum>,
    ) -> Result<NextEntryArgs> {
        info!(
            "[next_entry_args] REQUEST: next entry args for author {} document {} {}",
            author.as_str(),
            document_id.map(|id| id.as_str()).unwrap_or("not provided"),
            seq_num
                .map(|seq_num| format!("at sequence number {}", seq_num.as_u64()))
                .unwrap_or_else(|| "".into())
        );

        debug!("\n{:?}\n{:?}\n{:?}", author, document_id, seq_num);

        let next_entry_args = self.next_entry_args(author, document_id, seq_num)?;

        info!(
            "[next_entry_args] RESPONSE: log id: {} seq num: {} backlink: {} skiplink: {}",
            next_entry_args.log_id.as_u64(),
            next_entry_args.seq_num.as_u64(),
            next_entry_args
                .backlink
                .as_ref()
                .map(|hash| hash.as_str())
                .unwrap_or("none"),
            next_entry_args
                .skiplink
                .as_ref()
                .map(|hash| hash.as_str())
                .unwrap_or("none"),
        );

        debug!("\n{:?}", next_entry_args);

        Ok(next_entry_args)
    }

    /// Returns the log id, sequence number, skiplink and backlink hash for a given author and
    /// document. All of this information is needed to create and sign a new entry.
    ///
    /// If a value for the optional seq_num parameter is passed then next entry args *at that
    /// point* in this log are returned. This is helpful when generating test data and wanting to
    /// test the flow from requesting entry args through to publishing an entry.
    fn next_entry_args(
        &self,
        author: &Author,
        document_id: Option<&Hash>,
        seq_num: Option<&SeqNum>,
    ) -> Result<NextEntryArgs> {
        // Get or instantiate a collection of logs for this author.
        let author_logs = match self.get_author_logs(author) {
            Some(logs) => logs.clone(),
            None => AuthorLogs::new(),
        };

        // Find the log for this document and author if it exists.
        let document_log = match document_id {
            Some(document_id) => author_logs.get_log_by_document_id(document_id),
            None => None,
        };

        // Construct the next entry args.
        let entry_args = match document_log {
            Some(log) => {
                // If a document log already we retrieve all the entries.
                let mut entries = log.entries();
                // If a seq num was passed to this method it means we are
                // requesting entry args for a specific point in this log.
                // NB: This is a functionality only implemented in the mock node
                //for testing purposes.
                let seq_num_inner = match seq_num {
                    // If a sequence number was passed ...
                    Some(s) => {
                        // ... trim the log to the point in time we are interested in
                        entries = entries[..s.as_u64() as usize - 1].to_owned();
                        // ... and return the sequence number.
                        *s
                    }
                    None => {
                        // If no sequence number was passed calculate and return the next sequence
                        // number for this log
                        log.next_seq_num()
                    }
                };

                // Calculate backlink and skiplink.
                let (backlink, skiplink) = calculate_links(&seq_num_inner, &entries);

                // Construct the next entry args.
                NextEntryArgs {
                    log_id: log.id(),
                    seq_num: seq_num_inner,
                    skiplink,
                    backlink,
                }
            }
            // This document log doesn't exist yet, so we construct next entry args
            // based on the next log id for the author.
            None => NextEntryArgs {
                log_id: author_logs.next_log_id(),
                seq_num: SeqNum::default(),
                skiplink: None,
                backlink: None,
            },
        };

        Ok(entry_args)
    }

    /// Store an entry in the database and return the hash of the newly created entry.
    pub fn publish_entry(
        &mut self,
        entry_encoded: &EntrySigned,
        operation_encoded: &OperationEncoded,
    ) -> Result<NextEntryArgs> {
        let entry = decode_entry(entry_encoded, Some(operation_encoded))?;
        let log_id = entry.log_id();
        let author = entry_encoded.author();
        let operation = entry.operation().unwrap();

        info!(
            "[publish_entry] REQUEST: publish entry: {} from author: {}",
            entry_encoded.hash().as_str(),
            author.as_str()
        );

        debug!("\n{:?}\n{:?}", entry_encoded, operation_encoded);

        let document_id = if !operation.is_create() {
            let previous_operations = operation.previous_operations().unwrap_or_else(|| {
                panic!(
                    "Document log for entry {} not found on node",
                    entry_encoded.hash().as_str()
                )
            });
            let document_id = self
                .get_document_id_by_entry(previous_operations.into_iter().next().unwrap().as_hash())
                .unwrap_or_else(|| {
                    panic!(
                        "Document log for entry {} not found on node",
                        entry_encoded.hash().as_str()
                    )
                });
            info!("Document found with id {}", document_id.as_str());
            document_id
        } else {
            info!(
                "Creating new document with id {}",
                entry_encoded.hash().as_str()
            );

            entry_encoded.hash()
        };

        // Get all logs by this author.
        let author_logs = match self.get_author_logs_mut(&author) {
            Some(logs) => logs,
            // If there aren't any, then instantiate a new log collection
            // and insert it into the db.
            None => {
                self.db.insert(author.as_str().into(), AuthorLogs::new());
                self.get_author_logs_mut(&author).unwrap()
            }
        };

        // Get the log for this document from the author logs.
        match author_logs.get_log_mut(log_id) {
            Some(_) if operation.is_create() => {
                // If this is a create message the assigned log id should be free.
                return Err(format!("Log with id: {} already exists.", log_id.as_u64()).into());
            }
            Some(log) => {
                // If there is one, insert this new entry.
                log.add_entry(LogEntry::new(entry_encoded, operation_encoded));
            }
            None => {
                // If there isn't one, then create and insert it.

                // First checking if the passed log id matches what we expect the next log
                // id for this log to be.
                let expected_log_id = author_logs.next_log_id();

                if *log_id != expected_log_id {
                    return Err(format!(
                        "Passed log id {} does not match expected log id {}",
                        log_id.as_u64(),
                        expected_log_id.as_u64()
                    )
                    .into());
                };

                // If it matches then we now create and insert the new log with it's
                // first entry included.
                author_logs.create_new_log(document_id.clone(), entry_encoded, operation_encoded);
            }
        };

        let next_entry_args = self.next_entry_args(&author, Some(&document_id), None)?;

        info!(
            "[publish_entry] RESPONSE: succesfully published entry: {} to log: {} and returning next entry args",
            entry_encoded.hash().as_str(),
            log_id.as_u64()
        );

        debug!("\n{:?}", next_entry_args);

        Ok(next_entry_args)
    }

    /// Returns all of a documents entries from this node. Includes entries from all authors.
    pub fn get_document_entries(&self, id: &Hash) -> Vec<LogEntry> {
        self.db()
            .iter()
            .flat_map(|(_, author_logs)| author_logs.iter().filter(|log| log.document() == *id))
            .flat_map(|log| log.entries())
            .collect()
    }

    /// Get a single resolved document from the node.
    pub fn get_document(&self, id: &Hash) -> Document {
        let entries = self.get_document_entries(id);
        let operations = entries
            .iter()
            .map(|entry| {
                VerifiedOperation::new_from_entry(
                    &entry.entry_encoded(),
                    &entry.operation_encoded(),
                )
                .unwrap()
            })
            .collect();
        DocumentBuilder::new(operations).build().unwrap()
    }

    /// Get all documents in their resolved state from the node.
    pub fn get_documents(&self) -> Vec<Document> {
        let mut documents = HashSet::new();
        for (_author, author_logs) in self.db() {
            author_logs.iter().for_each(|log| {
                documents.insert(log.document().as_str().to_string());
            });
        }
        documents
            .iter()
            .map(|x| self.get_document(&Hash::new(x).unwrap()))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use crate::document::DocumentViewId;
    use crate::entry::{LogId, SeqNum};
    use crate::identity::KeyPair;
    use crate::operation::OperationValue;
    use crate::test_utils::fixtures::{create_operation, key_pair, private_key, update_operation};
    use crate::test_utils::mocks::client::Client;
    use crate::test_utils::utils::NextEntryArgs;

    use super::{send_to_node, Node};

    #[rstest]
    fn publishing_entries(private_key: String) {
        let panda = Client::new("panda".to_string(), key_pair(&private_key));
        let mut node = Node::new();

        // This is an empty node which has no author logs.
        let next_entry_args = node
            .get_next_entry_args(&panda.author(), None, None)
            .unwrap();

        // These are the next_entry_args we would expect to get when making a request to this node.
        let mut expected_next_entry_args = NextEntryArgs {
            log_id: LogId::new(1),
            seq_num: SeqNum::new(1).unwrap(),
            backlink: None,
            skiplink: None,
        };

        assert_eq!(next_entry_args.log_id, expected_next_entry_args.log_id);
        assert_eq!(next_entry_args.seq_num, expected_next_entry_args.seq_num);
        assert_eq!(next_entry_args.backlink, expected_next_entry_args.backlink);
        assert_eq!(next_entry_args.skiplink, expected_next_entry_args.skiplink);

        // Panda publishes a create operation.
        // This instantiates a new document.
        //
        // PANDA  : [1]
        let (panda_entry_1_hash, next_entry_args) = send_to_node(
            &mut node,
            &panda,
            &create_operation(&[(
                "message",
                OperationValue::Text("Ohh, my first message! [Panda]".to_string()),
            )]),
        )
        .unwrap();

        // The seq_num has incremented to 2 because panda already published one entry.
        expected_next_entry_args = NextEntryArgs {
            log_id: LogId::new(1),
            seq_num: SeqNum::new(2).unwrap(),
            backlink: Some(panda_entry_1_hash.clone()),
            skiplink: None,
        };

        assert_eq!(next_entry_args.log_id, expected_next_entry_args.log_id);
        assert_eq!(next_entry_args.seq_num, expected_next_entry_args.seq_num);
        assert_eq!(next_entry_args.backlink, expected_next_entry_args.backlink);
        assert_eq!(next_entry_args.skiplink, expected_next_entry_args.skiplink);

        // The database contains one author now.
        assert_eq!(node.get_authors().len(), 1);
        // Who has one log.
        assert_eq!(node.get_author_logs(&panda.author()).unwrap().len(), 1);

        // Panda publishes an update operation.
        // It contains the hash of the current graph tip in it's `previous_operations`.
        //
        // PANDA  : [1] <-- [2]
        let (panda_entry_2_hash, next_entry_args) = send_to_node(
            &mut node,
            &panda,
            &update_operation(
                &[(
                    "message",
                    OperationValue::Text("Which I now update. [Panda]".to_string()),
                )],
                &panda_entry_1_hash.clone().into(),
            ),
        )
        .unwrap();

        expected_next_entry_args = NextEntryArgs {
            log_id: LogId::new(1),
            seq_num: SeqNum::new(3).unwrap(),
            backlink: Some(panda_entry_2_hash.clone()),
            skiplink: None,
        };

        assert_eq!(next_entry_args.log_id, expected_next_entry_args.log_id);
        assert_eq!(next_entry_args.seq_num, expected_next_entry_args.seq_num);
        assert_eq!(next_entry_args.backlink, expected_next_entry_args.backlink);
        assert_eq!(next_entry_args.skiplink, expected_next_entry_args.skiplink);

        assert_eq!(node.get_authors().len(), 1);
        assert_eq!(node.get_author_logs(&panda.author()).unwrap().len(), 1);

        let penguin = Client::new("penguin".to_string(), KeyPair::new());

        let next_entry_args = node
            .next_entry_args(&penguin.author(), Some(&panda_entry_1_hash), None)
            .unwrap();

        expected_next_entry_args = NextEntryArgs {
            log_id: LogId::new(1),
            seq_num: SeqNum::new(1).unwrap(),
            backlink: None,
            skiplink: None,
        };

        assert_eq!(next_entry_args.log_id, expected_next_entry_args.log_id);
        assert_eq!(next_entry_args.seq_num, expected_next_entry_args.seq_num);
        assert_eq!(next_entry_args.backlink, expected_next_entry_args.backlink);
        assert_eq!(next_entry_args.skiplink, expected_next_entry_args.skiplink);

        // Penguin publishes an update operation which refers to panda's last operation
        // as the graph tip.
        //
        // PANDA  : [1] <--[2]
        // PENGUIN:           \--[1]
        let (penguin_entry_1_hash, next_entry_args) = send_to_node(
            &mut node,
            &penguin,
            &update_operation(
                &[(
                    "message",
                    OperationValue::Text("My turn to update. [Penguin]".to_string()),
                )],
                &panda_entry_2_hash.into(),
            ),
        )
        .unwrap();

        expected_next_entry_args = NextEntryArgs {
            log_id: LogId::new(1),
            seq_num: SeqNum::new(2).unwrap(),
            backlink: Some(penguin_entry_1_hash.clone()),
            skiplink: None,
        };

        assert_eq!(next_entry_args.log_id, expected_next_entry_args.log_id);
        assert_eq!(next_entry_args.seq_num, expected_next_entry_args.seq_num);
        assert_eq!(next_entry_args.backlink, expected_next_entry_args.backlink);
        assert_eq!(next_entry_args.skiplink, expected_next_entry_args.skiplink);

        assert_eq!(node.get_authors().len(), 2);
        assert_eq!(node.get_author_logs(&penguin.author()).unwrap().len(), 1);

        // Penguin publishes another update operation refering to their own previous operation
        // as the graph tip.
        //
        // PANDA  : [1] <--[2]
        // PENGUIN:           \--[1] <--[2]
        let (penguin_entry_2_hash, next_entry_args) = send_to_node(
            &mut node,
            &penguin,
            &update_operation(
                &[(
                    "message",
                    OperationValue::Text("And again. [Penguin]".to_string()),
                )],
                &penguin_entry_1_hash.into(),
            ),
        )
        .unwrap();

        expected_next_entry_args = NextEntryArgs {
            log_id: LogId::new(1),
            seq_num: SeqNum::new(3).unwrap(),
            backlink: Some(penguin_entry_2_hash),
            skiplink: None,
        };

        assert_eq!(next_entry_args.log_id, expected_next_entry_args.log_id);
        assert_eq!(next_entry_args.seq_num, expected_next_entry_args.seq_num);
        assert_eq!(next_entry_args.backlink, expected_next_entry_args.backlink);
        assert_eq!(next_entry_args.skiplink, expected_next_entry_args.skiplink);

        // Now there are 2 authors publishing ot the node.
        assert_eq!(node.get_authors().len(), 2);
        assert_eq!(node.get_author_logs(&penguin.author()).unwrap().len(), 1);

        // We can query the node for the current document state.
        let document = node.get_document(&panda_entry_1_hash);
        let document_view_value = document.view().unwrap().get("message").unwrap();
        // It was last updated by Penguin, this writes over previous values.
        assert_eq!(
            document_view_value.value(),
            &OperationValue::Text("And again. [Penguin]".to_string())
        );
        // There should only be one document in the database.
        assert_eq!(node.get_documents().len(), 1);

        // Panda publishes another create operation.
        // This again instantiates a new document.
        //
        // PANDA  : [1]
        let (panda_entry_1_hash, next_entry_args) = send_to_node(
            &mut node,
            &panda,
            &create_operation(&[(
                "message",
                OperationValue::Text("Ohh, my first message in a new document!".to_string()),
            )]),
        )
        .unwrap();

        expected_next_entry_args = NextEntryArgs {
            log_id: LogId::new(2),
            seq_num: SeqNum::new(2).unwrap(),
            backlink: Some(panda_entry_1_hash),
            skiplink: None,
        };

        assert_eq!(next_entry_args.log_id, expected_next_entry_args.log_id);
        assert_eq!(next_entry_args.seq_num, expected_next_entry_args.seq_num);
        assert_eq!(next_entry_args.backlink, expected_next_entry_args.backlink);
        assert_eq!(next_entry_args.skiplink, expected_next_entry_args.skiplink);

        assert_eq!(node.get_authors().len(), 2);
        // Now panda has 2 document logs.
        assert_eq!(node.get_author_logs(&panda.author()).unwrap().len(), 2);
        // There should be 2 document in the database.
        assert_eq!(node.get_documents().len(), 2);
    }

    #[rstest]
    fn next_entry_args_at_specific_seq_num(private_key: String) {
        let panda = Client::new("panda".to_string(), key_pair(&private_key));
        let mut node = Node::new();

        // Publish a CREATE operation
        let (entry1_hash, _) = send_to_node(
            &mut node,
            &panda,
            &create_operation(&[(
                "message",
                OperationValue::Text("Ohh, my first message!".to_string()),
            )]),
        )
        .unwrap();

        // Publish an UPDATE operation
        send_to_node(
            &mut node,
            &panda,
            &update_operation(
                &[(
                    "message",
                    OperationValue::Text("Which I now update.".to_string()),
                )],
                &entry1_hash.clone().into(),
            ),
        )
        .unwrap();

        // For testig, we can request entry args for a specific entry in an authors log.
        let next_entry_args = node
            .next_entry_args(
                &panda.author(),
                Some(&entry1_hash),
                // Here we request the entry args required for publishing the second entry of the log.
                Some(&SeqNum::new(2).unwrap()),
            )
            .unwrap();

        let expected_next_entry_args = NextEntryArgs {
            log_id: LogId::new(1),
            seq_num: SeqNum::new(2).unwrap(),
            backlink: Some(entry1_hash),
            skiplink: None,
        };

        assert_eq!(next_entry_args.log_id, expected_next_entry_args.log_id);
        assert_eq!(next_entry_args.seq_num, expected_next_entry_args.seq_num);
        assert_eq!(next_entry_args.backlink, expected_next_entry_args.backlink);
        assert_eq!(next_entry_args.skiplink, expected_next_entry_args.skiplink);
    }

    #[rstest]
    fn concurrent_updates(private_key: String) {
        let panda = Client::new("panda".to_string(), key_pair(&private_key));
        let penguin = Client::new(
            "penguin".to_string(),
            key_pair("eb852fefa703901e42f17cdc2aa507947f392a72101b2c1a6d30023af14f75e3"),
        );
        let mut node = Node::new();

        // Publish a CREATE operation
        //
        // PANDA  : [1]
        let (panda_entry_1_hash, _) = send_to_node(
            &mut node,
            &panda,
            &create_operation(&[
                (
                    "cafe_name",
                    OperationValue::Text("Polar Pear Cafe".to_string()),
                ),
                (
                    "address",
                    OperationValue::Text("1, Polar Bear Rise, Panda Town".to_string()),
                ),
            ]),
        )
        .unwrap();

        let document = node.get_document(&panda_entry_1_hash);
        let document_view_value = document.view().unwrap().get("cafe_name").unwrap();
        assert_eq!(
            document_view_value.value(),
            &OperationValue::Text("Polar Pear Cafe".to_string())
        );

        // Publish an UPDATE operation
        //
        // PANDA  : [1] <--[2]
        let (panda_entry_2_hash, _) = send_to_node(
            &mut node,
            &panda,
            &update_operation(
                &[(
                    "cafe_name",
                    OperationValue::Text("Polar Bear Cafe".to_string()),
                )],
                &panda_entry_1_hash.clone().into(),
            ),
        )
        .unwrap();

        let document = node.get_document(&panda_entry_1_hash);
        let document_view_value = document.view().unwrap().get("cafe_name").unwrap();
        assert_eq!(
            document_view_value.value(),
            &OperationValue::Text("Polar Bear Cafe".to_string())
        );

        // Penguin publishes an UPDATE operation, but they haven't seen Panda's most recent entry [2]
        // making this a concurrent update which forks the document graph.
        //
        // PANDA  : [1] <--[2]
        //            \
        // PENGUIN:    [1]
        let (penguin_entry_1_hash, _) = send_to_node(
            &mut node,
            &penguin,
            &update_operation(
                &[(
                    "address",
                    OperationValue::Text("1, Polar Bear rd, Panda Town".to_string()),
                )],
                &panda_entry_1_hash.clone().into(),
            ),
        )
        .unwrap();

        let document = node.get_document(&panda_entry_1_hash);
        let document_view_value = document.view().unwrap().get("cafe_name").unwrap();
        assert_eq!(
            document_view_value.value(),
            &OperationValue::Text("Polar Bear Cafe".to_string())
        );

        // Penguin publishes another UPDATE operation, this time they have replicated all entries
        // and refer to the two existing document graph tips in the previous_operation fields.
        //
        // PANDA  : [1] <-- [2]
        //            \        \
        // PENGUIN:    [1] <-- [2]
        let (_penguin_entry_2_hash, _) = send_to_node(
            &mut node,
            &penguin,
            &update_operation(
                &[(
                    "cafe_name",
                    OperationValue::Text("Polar Bear Café".to_string()),
                )],
                &DocumentViewId::new(&[penguin_entry_1_hash.into(), panda_entry_2_hash.into()])
                    .unwrap(),
            ),
        )
        .unwrap();

        let document = node.get_document(&panda_entry_1_hash);

        let document_view_value = document.view().unwrap().get("cafe_name").unwrap();
        assert_eq!(
            document_view_value.value(),
            &OperationValue::Text("Polar Bear Café".to_string())
        );

        // As more operations are published, the graph could look like this:
        //
        // PANDA  : [1] <--[2]          [3] <--[4] <--[5]
        //            \       \         /
        // PENGUIN:    [1] <--[2] <--[3]
    }
}