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
// SPDX-License-Identifier: AGPL-3.0-or-later

use async_trait::async_trait;

use crate::document::DocumentId;
use crate::entry::SeqNum;
use crate::hash::Hash;
use crate::operation::{AsOperation, AsVerifiedOperation, Operation};
use crate::storage_provider::errors::PublishEntryError;
use crate::storage_provider::traits::{
    AsEntryArgsRequest, AsEntryArgsResponse, AsPublishEntryRequest, AsPublishEntryResponse,
    AsStorageEntry, AsStorageLog, EntryStore, LogStore, OperationStore,
};
use crate::Validate;

/// Trait which handles all high level storage queries and insertions.
///
/// This trait should be implemented on the root storage provider struct. It's definitions make up
/// the high level methods a p2panda client needs when interacting with data storage. It will be
/// used for storing entries (`publish_entry`), getting required entry arguments when creating
/// entries (`get_entry_args`) and all internal storage actions. Methods defined on `EntryStore`
/// and `LogStore` and `OperationStore` are for lower level access to their respective data
/// structures.
///
/// The methods defined here are the minimum required for a working storage backend, additional
/// custom methods can be added per implementation.
///
/// For example: if I wanted to use an SQLite backend, then I would first implement [`LogStore`]
/// and [`EntryStore`] traits with all their required methods defined (they are required traits
/// containing lower level accessors and setters for the respective data structures). With these
/// traits defined [`StorageProvider`] is almost complete as it contains default definitions for
/// most of it's methods (`get_entry_args` and `publish_entry` are defined below). The only one
/// which needs defining is `get_document_by_entry`. It is also possible to over-ride the default
/// definitions for any of the trait methods.
#[async_trait]
pub trait StorageProvider<
    StorageEntry: AsStorageEntry,
    StorageLog: AsStorageLog,
    StorageOperation: AsVerifiedOperation,
>: EntryStore<StorageEntry> + LogStore<StorageLog> + OperationStore<StorageOperation>
{
    /// Params when making a request to get the next entry args for an author and document.
    type EntryArgsRequest: AsEntryArgsRequest + Sync;

    /// Response from a call to get next entry args for an author and document.
    type EntryArgsResponse: AsEntryArgsResponse;

    /// Params when making a request to publish a new entry.
    type PublishEntryRequest: AsPublishEntryRequest + Sync;

    /// Response from a call to publish a new entry.
    type PublishEntryResponse: AsPublishEntryResponse;

    /// Returns the related document for any entry.
    ///
    /// Every entry is part of a document and, through that, associated with a specific log id used
    /// by this document and author. This method returns that document id by looking up the log
    /// that the entry was stored in.
    ///
    /// If the passed entry cannot be found, or it's associated document doesn't exist yet, `None`
    /// is returned.
    async fn get_document_by_entry(
        &self,
        entry_hash: &Hash,
    ) -> Result<Option<DocumentId>, Box<dyn std::error::Error + Send + Sync>>;

    /// Returns required data (backlink and skiplink entry hashes, last sequence number and the
    /// document's log_id) to encode a new bamboo entry.
    async fn get_entry_args(
        &self,
        params: &Self::EntryArgsRequest,
    ) -> Result<Self::EntryArgsResponse, Box<dyn std::error::Error + Send + Sync>> {
        // Validate the entry args request parameters.
        params.validate()?;

        // Determine log_id for this document. If this is the very first operation in the document
        // graph, the `document` value is None and we will return the next free log id
        let log = self
            .find_document_log_id(params.author(), params.document_id().as_ref())
            .await?;

        // Determine backlink and skiplink hashes for the next entry. To do this we need the latest
        // entry in this log
        let entry_latest = self.get_latest_entry(params.author(), &log).await?;

        match entry_latest.clone() {
            // An entry was found which serves as the backlink for the upcoming entry
            Some(entry_backlink) => {
                let entry_latest = entry_latest.unwrap();
                let entry_hash_backlink = entry_backlink.hash();
                // Determine skiplink ("lipmaa"-link) entry in this log
                let entry_hash_skiplink = self.determine_next_skiplink(&entry_latest).await?;

                Ok(Self::EntryArgsResponse::new(
                    Some(entry_hash_backlink.clone()),
                    entry_hash_skiplink,
                    entry_latest.seq_num().clone().next().unwrap(),
                    entry_latest.log_id(),
                ))
            }
            // No entry was given yet, we can assume this is the beginning of the log
            None => Ok(Self::EntryArgsResponse::new(
                None,
                None,
                SeqNum::default(),
                log,
            )),
        }
    }

    /// Stores an author's Bamboo entry with operation payload in database after validating it.
    async fn publish_entry(
        &self,
        params: &Self::PublishEntryRequest,
    ) -> Result<Self::PublishEntryResponse, Box<dyn std::error::Error + Send + Sync>> {
        // Create a storage entry.
        let entry = StorageEntry::new(params.entry_signed(), params.operation_encoded())?;
        // Validate the entry (this also maybe happened in the above constructor)
        entry.validate()?;

        // Every operation refers to a document we need to determine. A document is identified by the
        // hash of its first `CREATE` operation, it is the root operation of every document graph
        let document_id = if entry.operation().is_create() {
            // This is easy: We just use the entry hash directly to determine the document id
            DocumentId::new(entry.hash().into())
        } else {
            // For any other operations which followed after creation we need to either walk the operation
            // graph back to its `CREATE` operation or more easily look up the database since we keep track
            // of all log ids and documents there.
            //
            // We can determine the used document hash by looking at this operations' previous_operations.
            let operation = Operation::from(params.operation_encoded());

            operation.validate()?;

            // Unwrap here as we validated in the previous line which would error if previous_operations wasn't present.
            let previous_operation_id = operation
                .previous_operations()
                .unwrap()
                .into_iter()
                .next()
                // Unwrap as all DocumentViewId's contain at least one OperationId.
                .unwrap();

            self.get_document_by_entry(previous_operation_id.as_hash())
                .await?
                .ok_or_else(|| PublishEntryError::DocumentMissing(entry.hash()))?
        };

        // Determine expected log id for new entry
        let document_log_id = self
            .find_document_log_id(&entry.author(), Some(&document_id))
            .await?;

        // Check if provided log id matches expected log id
        if document_log_id != entry.log_id() {
            return Err(PublishEntryError::InvalidLogId(
                entry.log_id().as_u64(),
                document_log_id.as_u64(),
            )
            .into());
        }

        // Get related bamboo backlink and skiplink entries
        let entry_backlink_bytes = self
            .try_get_backlink(&entry)
            .await?
            .map(|link| link.entry_bytes());

        let entry_skiplink_bytes = self
            .try_get_skiplink(&entry)
            .await?
            .map(|link| link.entry_bytes());

        // Verify bamboo entry integrity, including encoding, signature of the entry correct back-
        // and skiplinks
        bamboo_rs_core_ed25519_yasmf::verify(
            &entry.entry_bytes(),
            Some(&params.operation_encoded().to_bytes()),
            entry_skiplink_bytes.as_deref(),
            entry_backlink_bytes.as_deref(),
        )?;

        // Register log in database when a new document is created
        if entry.operation().is_create() {
            let log = StorageLog::new(
                &entry.author(),
                &entry.operation().schema(),
                &document_id,
                &entry.log_id(),
            );

            self.insert_log(log).await?;
        }

        // Finally insert Entry in database
        self.insert_entry(entry.clone()).await?;

        // Already return arguments for next entry creation
        let entry_latest: StorageEntry = self
            .get_latest_entry(&entry.author(), &entry.log_id())
            .await?
            .unwrap();
        let entry_hash_skiplink = self.determine_next_skiplink(&entry_latest).await?;
        let next_seq_num = entry_latest.seq_num().clone().next().unwrap();

        Ok(Self::PublishEntryResponse::new(
            Some(entry.hash()),
            entry_hash_skiplink,
            next_seq_num,
            entry.log_id(),
        ))
    }
}

#[cfg(test)]
pub mod tests {
    use std::convert::TryFrom;
    use std::sync::{Arc, Mutex};

    use async_trait::async_trait;
    use rstest::rstest;

    use crate::document::DocumentId;
    use crate::entry::{sign_and_encode, Entry, LogId};
    use crate::hash::Hash;
    use crate::identity::KeyPair;
    use crate::operation::{
        AsOperation, OperationEncoded, OperationFields, OperationId, OperationValue,
        VerifiedOperation,
    };
    use crate::storage_provider::traits::test_utils::{
        test_db, EntryArgsRequest, EntryArgsResponse, PublishEntryRequest, PublishEntryResponse,
        SimplestStorageProvider, StorageEntry, StorageLog, TestStore,
    };
    use crate::storage_provider::traits::{
        AsEntryArgsResponse, AsPublishEntryResponse, AsStorageEntry, AsStorageLog,
    };
    use crate::test_utils::fixtures::{entry, key_pair, operation, operation_fields, operation_id};

    use super::StorageProvider;

    #[async_trait]
    impl StorageProvider<StorageEntry, StorageLog, VerifiedOperation> for SimplestStorageProvider {
        type EntryArgsRequest = EntryArgsRequest;

        type EntryArgsResponse = EntryArgsResponse;

        type PublishEntryRequest = PublishEntryRequest;

        type PublishEntryResponse = PublishEntryResponse;

        async fn get_document_by_entry(
            &self,
            entry_hash: &Hash,
        ) -> Result<Option<DocumentId>, Box<dyn std::error::Error + Sync + Send>> {
            let entries = self.entries.lock().unwrap();

            let entry = entries.iter().find(|entry| entry.hash() == *entry_hash);

            let entry = match entry {
                Some(entry) => entry,
                None => return Ok(None),
            };

            let logs = self.logs.lock().unwrap();

            let log = logs
                .iter()
                .find(|log| log.id() == entry.log_id() && log.author() == entry.author());

            Ok(Some(log.unwrap().document_id()))
        }
    }

    #[rstest]
    #[async_std::test]
    async fn can_publish_entries(
        #[from(test_db)]
        #[with(20, 1)]
        #[future]
        db: TestStore,
    ) {
        let db = db.await;
        // Instantiate a new store
        let new_db = SimplestStorageProvider::default();

        let entries = db.store.entries.lock().unwrap().clone();

        for entry in entries.clone() {
            // Publish each test entry in order
            let publish_entry_request = PublishEntryRequest(
                entry.entry_signed(),
                entry.operation_encoded().unwrap().clone(),
            );

            let publish_entry_response = new_db.publish_entry(&publish_entry_request).await;

            // Response should be ok
            assert!(publish_entry_response.is_ok());

            let mut seq_num = entry.seq_num();

            // If this is the highest entry in the db then break here, the test is over
            if seq_num.as_u64() == entries.len() as u64 {
                break;
            };

            // Calculate expected response
            let next_seq_num = seq_num.next().unwrap();
            let skiplink = entries
                .get(next_seq_num.as_u64() as usize - 1)
                .unwrap()
                .skiplink_hash();
            let backlink = entries
                .get(next_seq_num.as_u64() as usize - 1)
                .unwrap()
                .backlink_hash();
            let expected_reponse =
                PublishEntryResponse::new(backlink, skiplink, next_seq_num, LogId::default());

            // Response and expected response should match
            assert_eq!(publish_entry_response.unwrap(), expected_reponse);
        }
    }

    #[rstest]
    #[async_std::test]
    async fn rejects_invalid_backlink(
        key_pair: KeyPair,
        #[from(test_db)]
        #[with(4, 1)]
        #[future]
        db: TestStore,
    ) {
        let db = db.await;
        let new_db = SimplestStorageProvider::default();

        let entries = db.store.entries.lock().unwrap().clone();

        // Publish 3 entries to the new database
        for index in 0..3 {
            let entry = entries.get(index).unwrap();
            let publish_entry_request = PublishEntryRequest(
                entry.entry_signed(),
                entry.operation_encoded().unwrap().clone(),
            );

            new_db.publish_entry(&publish_entry_request).await.unwrap();
        }

        // Retrieve the forth entry
        let entry_four = entries.get(3).unwrap();

        // Reconstruct it with an invalid backlink
        let entry_with_invalid_backlink = Entry::new(
            &entry_four.log_id(),
            Some(&entry_four.operation()),
            entry_four.skiplink_hash().as_ref(),
            Some(&entries.get(1).unwrap().hash()),
            &entry_four.seq_num(),
        )
        .unwrap();

        let entry_signed = sign_and_encode(&entry_with_invalid_backlink, &key_pair).unwrap();

        let publish_entry_request = PublishEntryRequest(
            entry_signed.clone(),
            entry_four.operation_encoded().unwrap(),
        );

        let error_response = new_db.publish_entry(&publish_entry_request).await;

        println!("{:#?}", error_response);
        assert_eq!(
            format!("{}", error_response.unwrap_err()),
            format!(
                "The backlink hash encoded in the entry: {} did not match the expected backlink hash",
                entry_signed.hash()
            )
        )
    }

    #[rstest]
    #[async_std::test]
    async fn rejects_invalid_skiplink(
        key_pair: KeyPair,
        #[from(test_db)]
        #[with(4, 1)]
        #[future]
        db: TestStore,
    ) {
        let db = db.await;
        let new_db = SimplestStorageProvider::default();

        let entries = db.store.entries.lock().unwrap().clone();

        // Publish 3 entries to the new database
        for index in 0..3 {
            let entry = entries.get(index).unwrap();
            let publish_entry_request = PublishEntryRequest(
                entry.entry_signed(),
                entry.operation_encoded().unwrap().clone(),
            );

            new_db.publish_entry(&publish_entry_request).await.unwrap();
        }

        // Retrieve the forth entry
        let entry_four = entries.get(3).unwrap();

        // Reconstruct it with an invalid skiplink
        let entry_with_invalid_backlink = Entry::new(
            &entry_four.log_id(),
            Some(&entry_four.operation()),
            Some(&entries.get(1).unwrap().hash()),
            entry_four.backlink_hash().as_ref(),
            &entry_four.seq_num(),
        )
        .unwrap();

        let entry_signed = sign_and_encode(&entry_with_invalid_backlink, &key_pair).unwrap();

        let publish_entry_request = PublishEntryRequest(
            entry_signed.clone(),
            entry_four.operation_encoded().unwrap(),
        );

        let error_response = new_db.publish_entry(&publish_entry_request).await;

        println!("{:#?}", error_response);
        assert_eq!(
            format!("{}", error_response.unwrap_err()),
            format!(
                "The skiplink hash encoded in the entry: {} did not match the known hash of the skiplink target",
                entry_signed.hash()
            )
        )
    }

    #[rstest]
    #[async_std::test]
    async fn gets_entry_args(
        #[from(test_db)]
        #[with(20, 1)]
        #[future]
        db: TestStore,
    ) {
        let db = db.await;
        // Instantiate a new store
        let new_db = SimplestStorageProvider::default();

        let entries = db.store.entries.lock().unwrap().clone();

        for entry in entries.clone() {
            let is_create = entry.operation().is_create();

            // Determine document id
            let document_id: Option<DocumentId> = match is_create {
                true => None,
                false => Some(entries.get(0).unwrap().hash().into()),
            };

            // Construct entry args request
            let entry_args_request = EntryArgsRequest {
                author: entry.author(),
                document: document_id,
            };

            let entry_args_response = new_db.get_entry_args(&entry_args_request).await;

            // Response should be ok
            assert!(entry_args_response.is_ok());

            // Calculate expected response
            let seq_num = entry.seq_num();
            let backlink = entry.backlink_hash();
            let skiplink = entry.skiplink_hash();

            let expected_reponse =
                EntryArgsResponse::new(backlink, skiplink, seq_num, LogId::default());

            // Response and expected response should match
            assert_eq!(entry_args_response.unwrap(), expected_reponse);

            // Publish each test entry in order before next loop
            let publish_entry_request = PublishEntryRequest(
                entry.entry_signed(),
                entry.operation_encoded().unwrap().clone(),
            );

            new_db.publish_entry(&publish_entry_request).await.unwrap();
        }
    }

    #[rstest]
    #[async_std::test]
    async fn wrong_log_id(
        key_pair: KeyPair,
        #[from(test_db)]
        #[with(2, 1)]
        #[future]
        db: TestStore,
    ) {
        let db = db.await;
        // Instantiate a new store
        let new_db = SimplestStorageProvider::default();

        let entries = db.store.entries.lock().unwrap().clone();

        // Entry request for valid first intry in log 1
        let publish_entry_request = PublishEntryRequest(
            entries.get(0).unwrap().entry_signed(),
            entries.get(0).unwrap().operation_encoded().unwrap(),
        );

        // Publish the first valid entry
        new_db.publish_entry(&publish_entry_request).await.unwrap();

        // Create a new entry with an invalid log id
        let entry_with_wrong_log_id = Entry::new(
            &LogId::new(2), // This is wrong!!
            Some(&entries.get(1).unwrap().operation()),
            entries.get(1).unwrap().skiplink_hash().as_ref(),
            entries.get(1).unwrap().backlink_hash().as_ref(),
            &entries.get(1).unwrap().seq_num(),
        )
        .unwrap();

        let signed_entry_with_wrong_log_id =
            sign_and_encode(&entry_with_wrong_log_id, &key_pair).unwrap();
        let encoded_operation =
            OperationEncoded::try_from(&entries.get(1).unwrap().operation()).unwrap();

        // Create request and publish invalid entry
        let request_with_wrong_log_id =
            PublishEntryRequest(signed_entry_with_wrong_log_id, encoded_operation);

        // Should error as the published entry contains an invalid log
        let error_response = new_db.publish_entry(&request_with_wrong_log_id).await;

        assert_eq!(
            format!("{}", error_response.unwrap_err()),
            "Requested log id 2 does not match expected log id 1"
        )
    }

    #[rstest]
    #[async_std::test]
    async fn skiplink_does_not_exist(
        #[from(test_db)]
        #[with(8, 1)]
        #[future]
        db: TestStore,
    ) {
        let db = db.await;
        let entries = db.store.entries.lock().unwrap().clone();
        let logs = db.store.logs.lock().unwrap().clone();

        // Init database with on document log which has an entry at seq num 4 missing
        let log_entries_with_skiplink_missing = vec![
            entries.get(0).unwrap().clone(),
            entries.get(1).unwrap().clone(),
            entries.get(2).unwrap().clone(),
            entries.get(4).unwrap().clone(),
            entries.get(5).unwrap().clone(),
            entries.get(6).unwrap().clone(),
        ];

        let new_db = SimplestStorageProvider {
            logs: Arc::new(Mutex::new(logs)),
            entries: Arc::new(Mutex::new(log_entries_with_skiplink_missing)),
            operations: Arc::new(Mutex::new(Vec::new())),
        };

        let entry = entries.get(7).unwrap();

        let publish_entry_request =
            PublishEntryRequest(entry.entry_signed(), entry.operation_encoded().unwrap());

        // Should error as an entry at seq num 8 should have a skiplink relation to the missing
        // entry at seq num 4
        let error_response = new_db.publish_entry(&publish_entry_request).await;

        assert_eq!(
            format!("{}", error_response.unwrap_err()),
            format!(
                "Could not find expected skiplink in database for entry with id: {}",
                entry.hash()
            )
        )
    }

    #[rstest]
    #[async_std::test]
    async fn prev_op_does_not_exist(
        #[from(test_db)]
        #[with(4, 1)]
        #[future]
        db: TestStore,
        operation_fields: OperationFields,
        #[from(operation_id)] invalid_prev_op: OperationId,
        key_pair: KeyPair,
    ) {
        let db = db.await;
        let entries = db.store.entries.lock().unwrap().clone();
        let logs = db.store.logs.lock().unwrap().clone();

        // Init database with 3 valid entries
        let three_valid_entries = vec![
            entries.get(0).unwrap().clone(),
            entries.get(1).unwrap().clone(),
            entries.get(2).unwrap().clone(),
        ];

        let new_db = SimplestStorageProvider {
            logs: Arc::new(Mutex::new(logs)),
            entries: Arc::new(Mutex::new(three_valid_entries)),
            operations: Arc::new(Mutex::new(Vec::new())),
        };

        // Get the valid next entry
        let next_entry = entries.get(3).unwrap();

        // Recreate this entry and replace previous_operations to contain invalid OperationId
        let update_operation_with_invalid_previous_operations = operation(
            Some(operation_fields.clone()),
            Some(invalid_prev_op.into()),
            None,
        );

        let update_entry = entry(
            next_entry.seq_num().as_u64(),
            next_entry.log_id().as_u64(),
            next_entry.backlink_hash(),
            next_entry.skiplink_hash(),
            Some(update_operation_with_invalid_previous_operations.clone()),
        );

        let encoded_entry = sign_and_encode(&update_entry, &key_pair).unwrap();
        let encoded_operation =
            OperationEncoded::try_from(&update_operation_with_invalid_previous_operations).unwrap();

        // Publish this entry (which contains an invalid previous_operation)
        let publish_entry_request = PublishEntryRequest(encoded_entry.clone(), encoded_operation);

        let error_response = new_db.publish_entry(&publish_entry_request).await;

        assert_eq!(
            format!("{}", error_response.unwrap_err()),
            format!(
                "Could not find document for entry in database with id: {}",
                encoded_entry.hash()
            )
        )
    }

    #[rstest]
    #[async_std::test]
    async fn invalid_entry_op_pair(
        #[from(test_db)]
        #[with(4, 1)]
        #[future]
        db: TestStore,
    ) {
        let db = db.await;
        let entries = db.store.entries.lock().unwrap().clone();
        let logs = db.store.logs.lock().unwrap().clone();

        // Init database with 3 valid entries
        let three_valid_entries = vec![
            entries.get(0).unwrap().clone(),
            entries.get(1).unwrap().clone(),
            entries.get(2).unwrap().clone(),
        ];

        let new_db = SimplestStorageProvider {
            logs: Arc::new(Mutex::new(logs)),
            entries: Arc::new(Mutex::new(three_valid_entries)),
            operations: Arc::new(Mutex::new(Vec::new())),
        };

        // Get the valid next entry
        let next_entry = entries.get(3).unwrap();

        // Create a new operation which does not match the one contained in the entry hash
        let mismatched_operation = operation(
            Some(operation_fields(vec![(
                "poopy",
                OperationValue::Text("This is the WRONG operation :-(".to_string()),
            )])),
            Some(next_entry.operation_encoded().unwrap().hash().into()),
            None,
        );

        let encoded_operation = OperationEncoded::try_from(&mismatched_operation).unwrap();

        // Publish this entry with an mismatching operation
        let publish_entry_request =
            PublishEntryRequest(next_entry.entry_signed(), encoded_operation);

        let error_response = new_db.publish_entry(&publish_entry_request).await;

        assert_eq!(
            format!("{}", error_response.unwrap_err()),
            "operation needs to match payload hash of encoded entry"
        )
    }
}