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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
|
//! Changes as bytes, to send and to load (`swarm::blob` moves them): one change by its
//! hash, checked against it when it arrives, and a delta, the changes between two sets
//! of heads, the same bytes on every node holding them.
use std::collections::{HashMap, HashSet};
use anyhow::{Result, anyhow, bail};
use super::{ActorId, Change, ChangeHash, Document, ExpandedChange, ReadDoc};
/// Whether `doc` has applied the change `hash`. Without `get_change_by_hash`, which
/// builds the change again from the document's operations, at a cost growing with its
/// history: by its missing dependencies, which look the hash up. One `doc` holds is
/// none of them; nor is one it has queued, waiting for its own, which are: with none
/// missing, nothing is queued, and `hash` is applied; with some, it is asked the slow
/// way (rarely: changes wait in the document only as a sync message or a file brought
/// them, `sync`, `file`).
pub(crate) fn holds(doc: &impl ReadDoc, hash: &ChangeHash) -> bool {
let missing = doc.get_missing_deps(std::slice::from_ref(hash));
if missing.contains(hash) {
return false;
}
missing.is_empty() || doc.get_change_by_hash(hash).is_some()
}
/// Whether `doc` has every change of `heads`.
pub(crate) fn holds_all(doc: &impl ReadDoc, heads: &[ChangeHash]) -> bool {
heads.iter().all(|head| holds(doc, head))
}
/// Whether the history of `theirs` (of them, those `doc` has) holds all of `ours`
/// (heads of `doc`): a peer at `theirs` has every change we have.
pub(crate) fn covers(doc: &Document, theirs: &[ChangeHash], ours: &[ChangeHash]) -> bool {
let known: Vec<ChangeHash> = theirs
.iter()
.copied()
.filter(|head| holds(doc, head))
.collect();
if known.is_empty() {
return ours.is_empty();
}
let beyond: std::collections::HashSet<ChangeHash> = doc
.get_changes_meta(&known)
.into_iter()
.map(|change| change.hash)
.collect();
ours.iter().all(|head| !beyond.contains(head))
}
/// Those of `heads` that `doc` doesn't have.
pub(crate) fn missing(doc: &impl ReadDoc, heads: &[ChangeHash]) -> Vec<ChangeHash> {
heads
.iter()
.copied()
.filter(|head| !holds(doc, head))
.collect()
}
/// The changes after `since`, walked once: their hashes; who wrote them (the authors
/// their writers set, a node's ID, `replica::authored`), each once, with the hashes of
/// their changes, and whether any has none (a snapshot, or a change of a node that set
/// none); and when they were committed, in Unix milliseconds by their writers' clocks
/// (`Replica::transact`), changes without a time (snapshots) left out.
pub(crate) struct Since {
pub(crate) hashes: Vec<ChangeHash>,
pub(crate) authors: Vec<(String, Vec<ChangeHash>)>,
pub(crate) unauthored: bool,
pub(crate) times: Vec<i64>,
}
pub(crate) fn since(doc: &Document, since: &[ChangeHash]) -> Since {
let mut found = Since {
hashes: Vec::new(),
authors: Vec::new(),
unauthored: false,
times: Vec::new(),
};
for change in doc.get_changes_meta(since) {
found.hashes.push(change.hash);
if change.timestamp > 0 {
found.times.push(change.timestamp);
}
match change
.author
.as_ref()
.and_then(|author| std::str::from_utf8(author.as_bytes()).ok())
{
Some(author) => match found.authors.iter_mut().find(|(known, _)| known == author) {
Some((_, hashes)) => hashes.push(change.hash),
None => found.authors.push((author.to_owned(), vec![change.hash])),
},
None => found.unauthored = true,
}
}
found
}
/// When the changes after `since` were committed (`Since::times`).
pub(crate) fn commit_times(doc: &Document, since: &[ChangeHash]) -> Vec<i64> {
self::since(doc, since).times
}
/// Who wrote the changes after `since` (`Since::authors`, `Since::unauthored`).
#[cfg(test)]
pub(crate) fn authors_since(
doc: &Document,
since: &[ChangeHash],
) -> (Vec<(String, Vec<ChangeHash>)>, bool) {
let found = self::since(doc, since);
(found.authors, found.unauthored)
}
/// The change `hash` as the document encodes it; None if `doc` doesn't have it.
pub(crate) fn change_bytes(doc: &Document, hash: &ChangeHash) -> Option<Vec<u8>> {
doc.get_change_by_hash(hash)
.map(|change| change.raw_bytes().to_vec())
}
/// The change in `bytes`, if it is the change `hash`.
pub(crate) fn change_from_bytes(bytes: Vec<u8>, hash: ChangeHash) -> Result<Change> {
let change = Change::from_bytes(bytes)
.map_err(|error| anyhow!("change {hash} doesn't load: {error}"))?;
if change.hash() != hash {
bail!("change has hash {}, not {hash}", change.hash());
}
Ok(change)
}
/// The bytes of the delta from `from` to `to` in `doc`: the changes in the history of
/// `to` but not of `from`, each as encoded, sorted by hash and concatenated
/// (`load_delta` reads that). The same on every node holding `to` and `from`, whatever
/// else it has. None if `doc` lacks part of either: without one of `from`, the delta
/// would carry that one's history too, where `to` shares it, and differ from another
/// node's (a download takes chunks from several, checked against one's manifest).
pub(crate) fn delta_bytes(
doc: &Document,
from: &[ChangeHash],
to: &[ChangeHash],
) -> Option<Vec<u8>> {
if !missing(doc, to).is_empty() || !missing(doc, from).is_empty() {
return None;
}
let since: HashMap<ChangeHash, (Vec<ChangeHash>, Vec<u8>)> = doc
.get_changes(from)
.iter()
.map(|change| {
(
change.hash(),
(change.deps().to_vec(), change.raw_bytes().to_vec()),
)
})
.collect();
// Of those, the ones `to` depends on: what we have beyond `to` stays out.
let mut included: HashSet<ChangeHash> = HashSet::new();
let mut pending: Vec<ChangeHash> = to.to_vec();
while let Some(hash) = pending.pop() {
if let Some((deps, _)) = since.get(&hash)
&& included.insert(hash)
{
pending.extend(deps.iter().copied());
}
}
let mut hashes: Vec<ChangeHash> = included.into_iter().collect();
hashes.sort_unstable();
let mut bytes = Vec::new();
for hash in hashes {
bytes.extend_from_slice(&since[&hash].1);
}
Some(bytes)
}
/// Loads a delta (`delta_bytes`) into `doc`, unjudged: for tests; a node screens what it
/// downloads (`access::screen::apply_bytes`).
#[cfg(test)]
pub(crate) fn load_delta(doc: &mut Document, bytes: &[u8]) -> Result<()> {
use anyhow::Context as _;
if let Some(misplaced) = misplaced_author(bytes) {
bail!("Refused the downloaded changes: {misplaced}");
}
doc.load_incremental(bytes)
.context("Loading the downloaded changes")?;
Ok(())
}
/// A change that names an author although it isn't its actor's first (`misplaced_author`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MisplacedAuthor {
pub(crate) author: Vec<u8>,
pub(crate) actor: super::ActorId,
pub(crate) seq: u64,
}
impl std::fmt::Display for MisplacedAuthor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"change {} of actor {} names an author ({}), which only an actor's first change may",
self.seq,
self.actor,
String::from_utf8_lossy(&self.author)
)
}
}
/// The first change among those in `data` (chunks as `load_incremental` takes them:
/// changes, compressed changes, bundles, documents) that names an author although it
/// isn't its actor's first change. Automerge records an author on an actor's first change
/// only, and applying a later one that carries an author trips an assertion in Automerge
/// 0.12 (`ChangeGraph::add_changes`) halfway through updating the document: the task
/// panics, and the document is left inconsistent. No honest node makes such a change, so
/// whatever comes from elsewhere is looked at here first, until Automerge refuses such
/// changes itself. Data that doesn't parse is left to Automerge, which refuses it.
///
/// A document chunk is loaded on its own to read its changes (no assertion on that
/// path): about as much work again as applying it, paid for documents in sync messages
/// (Automerge sends one when a peer lacks a third of the history or more).
pub(crate) fn misplaced_author(mut data: &[u8]) -> Option<MisplacedAuthor> {
const MAGIC: [u8; 4] = [0x85, 0x6f, 0x4a, 0x83];
// Magic bytes, checksum, chunk type, then the body's length (LEB128) and the body.
const HEADER: usize = 9;
while data.len() > HEADER && data[..4] == MAGIC {
let kind = data[8];
let (length, read) = uleb128(&data[HEADER..])?;
let end = HEADER
.checked_add(read)?
.checked_add(usize::try_from(length).ok()?)?;
let chunk = data.get(..end)?;
data = &data[end..];
let found = match kind {
// A change, or a compressed one.
1 | 2 => Change::try_from(chunk)
.ok()
.and_then(|change| misplaced_in(&change)),
3 => automerge::Bundle::try_from(chunk)
.ok()
.and_then(|bundle| bundle.to_changes().ok())
.and_then(|changes| changes.iter().find_map(misplaced_in)),
0 => Document::load(chunk).ok().and_then(|doc| {
doc.get_changes_meta(&[]).into_iter().find_map(|meta| {
(meta.seq != 1)
.then(|| author_footer(&meta.extra))
.flatten()
.map(|author| MisplacedAuthor {
author,
actor: meta.actor.into_owned(),
seq: meta.seq,
})
})
}),
_ => None,
};
if found.is_some() {
return found;
}
}
None
}
/// The changes in `data`, chunks as sync messages and downloads carry them: changes,
/// compressed or not, bundles, documents. None if a chunk doesn't load.
pub(crate) fn changes_in(mut data: &[u8]) -> Option<Vec<Change>> {
const MAGIC: [u8; 4] = [0x85, 0x6f, 0x4a, 0x83];
const HEADER: usize = 9;
let mut changes = Vec::new();
while !data.is_empty() {
if data.len() <= HEADER || data[..4] != MAGIC {
return None;
}
let kind = data[8];
let (length, read) = uleb128(&data[HEADER..])?;
let end = HEADER
.checked_add(read)?
.checked_add(usize::try_from(length).ok()?)?;
let chunk = data.get(..end)?;
data = &data[end..];
match kind {
1 | 2 => changes.push(Change::try_from(chunk).ok()?),
3 => changes.extend(automerge::Bundle::try_from(chunk).ok()?.to_changes().ok()?),
0 => changes.extend(Document::load(chunk).ok()?.get_changes(&[])),
_ => return None,
}
}
Some(changes)
}
/// `change`, decoded; without operations where Automerge panics decoding it (an
/// operation naming an actor its change doesn't list), which [`Written::check`] then
/// refuses: encoded again, it isn't the change that came.
pub(crate) fn decode(change: &Change) -> ExpandedChange {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| change.decode())).unwrap_or_else(
|_| ExpandedChange {
operations: Vec::new(),
actor_id: change.actor_id().clone(),
hash: None,
seq: change.seq(),
start_op: change.start_op(),
time: change.timestamp(),
message: change.message().map(str::to_owned),
author: None,
deps: change.deps().to_vec(),
extra_bytes: change.extra_bytes().to_vec(),
},
)
}
/// What an operation is, as the operations after it may name it.
#[derive(Clone)]
struct Made {
/// The change it is of.
change: ChangeHash,
obj: automerge::legacy::ObjectId,
key: automerge::legacy::Key,
/// It put an element into a list.
insert: bool,
/// The object it made, if it made one.
makes: Option<automerge::ObjType>,
}
impl Made {
fn of(change: ChangeHash, op: &automerge::legacy::Op) -> Self {
Made {
change,
obj: op.obj.clone(),
key: op.key.clone(),
insert: op.insert,
makes: match &op.action {
automerge::legacy::OpType::Make(kind) => Some(*kind),
_ => None,
},
}
}
}
/// A change of a batch that passed [`Written::check`].
struct Passed {
deps: Vec<ChangeHash>,
actor: ActorId,
seq: u64,
max_op: u64,
/// The changes of the document its history reaches first: its own dependencies
/// there, and those of the batch's changes it builds on.
doc_heads: Vec<ChangeHash>,
}
/// The history of a change being checked, walked back from its dependencies as far as
/// a question needs: newest first, by the operations' counters.
struct History {
queue: std::collections::BinaryHeap<(u64, ChangeHash)>,
seen: std::collections::HashSet<ChangeHash>,
}
/// What the changes of a batch made that passed [`Written::check`] and were taken
/// ([`Written::taken`]): those after them in the batch build on them before the
/// document holds them.
#[derive(Default)]
pub(crate) struct Written {
passed: HashMap<ChangeHash, Passed>,
/// The last change that passed, until it is taken: one refused after (a fork, the
/// rules) must not stand in for what the document holds.
checked: Option<(ChangeHash, Passed)>,
/// The operations they made.
ops: HashMap<(ActorId, u64), Made>,
/// Changes of the document, decoded to see what an operation of theirs is.
decoded: HashMap<ChangeHash, Option<ExpandedChange>>,
}
impl Written {
/// Why `change` (`expanded`: it, decoded) is none that Automerge writes, building
/// on `doc` and the changes checked before it; None if it is one, which is then
/// among those. Automerge 0.12 applies changes that aren't, and is broken by them:
/// it then gives back another change than the one it was given and saves a
/// document that doesn't load, or panics. No honest node makes such a change, so
/// each from elsewhere is looked at first.
///
/// Everything asked is asked of the change and its own history, never of what
/// else the document holds: two nodes that hold a change's history come to the
/// same, whatever reached them besides and in whatever order.
///
/// * Its bytes are the ones Automerge encodes for it. (One listing an actor none
/// of its operations names loads, with another hash than its own encoding has.)
/// * Its first operation is numbered one after the highest of its dependencies, 1
/// without any: what a transaction at the document's heads gives it. (One
/// numbered below them saves to a document that doesn't load; one numbered
/// near 2^32 makes the next write panic.)
/// * It is its actor's first, or builds on the one before it: a transaction names
/// its actor's last change among its dependencies. (A gap in an actor's numbers
/// makes Automerge panic.)
/// * Every operation it names was made in its history, or before in the change
/// itself, and is what it is named as: the object written into an object of
/// that kind, the element of that list, the operation replaced one at that
/// place. (One naming an operation elsewhere marks an unrelated value gone, and
/// the document then gives back another change under this one's hash.)
///
/// A change that passes is among those the next are checked against only once
/// it is [`Written::taken`].
pub(crate) fn check(
&mut self,
doc: &Document,
change: &Change,
expanded: &ExpandedChange,
) -> Option<String> {
use automerge::legacy::{ElementId, Key, ObjectId, OpId};
self.checked = None;
let hash = change.hash();
let again = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
Change::from(expanded.clone()).hash()
}));
if again.ok() != Some(hash) {
return Some("its bytes aren't the ones Automerge encodes for it".to_owned());
}
let start = change.start_op().get();
let last = change.max_op();
let actor = change.actor_id();
// Its dependencies: those of the batch, and those the document holds. One
// that is neither isn't ready, and Automerge doesn't apply the change (callers
// judge those whose dependencies they hold): nothing is asked of it.
let mut before = 0;
let mut follows = change.seq() == 1;
let mut doc_heads: Vec<ChangeHash> = Vec::new();
for dep in change.deps() {
let (dep_actor, seq, max_op) = if let Some(passed) = self.passed.get(dep) {
doc_heads.extend(&passed.doc_heads);
(passed.actor.clone(), passed.seq, passed.max_op)
} else {
let meta = doc.get_change_meta_by_hash(dep)?;
doc_heads.push(*dep);
(meta.actor.into_owned(), meta.seq, meta.max_op)
};
before = before.max(max_op);
follows |= &dep_actor == actor && seq + 1 == change.seq();
}
doc_heads.sort_unstable();
doc_heads.dedup();
if start != before + 1 {
return Some(format!(
"its first operation is numbered {start}, not {}, one after the highest of its dependencies",
before + 1
));
}
if !follows {
return Some(format!(
"it is its actor's change {}, and doesn't build on the one before",
change.seq()
));
}
let mut history = History {
queue: Default::default(),
seen: change.deps().iter().copied().collect(),
};
for dep in change.deps() {
if let Some(max_op) = self.max_op(doc, dep) {
history.queue.push((max_op, *dep));
}
}
let exid = |OpId(counter, by): &OpId| automerge::ObjId::Id(*counter, by.clone(), 0);
for (index, op) in expanded.operations.iter().enumerate() {
let this = start + index as u64;
// What `id` is, if it was made before this operation: in the change
// itself, or in its history.
let mut made = |written: &mut Self, id: &OpId| -> Option<Made> {
let OpId(counter, by) = id;
if by == actor && (start..this).contains(counter) {
let op = &expanded.operations[(counter - start) as usize];
return Some(Made::of(hash, op));
}
if *counter >= start {
return None;
}
// Made by a change of the batch taken before, or of the document: the
// one this change's history holds.
[written.made_in_batch(id), written.made_in_doc(doc, id)]
.into_iter()
.flatten()
.find(|made| written.reaches(doc, &mut history, made.change, *counter))
};
// The object written into: one, of the kind the key is for.
let in_list = matches!(op.key, Key::Seq(_));
let fits = |kind: automerge::ObjType| {
in_list == matches!(kind, automerge::ObjType::List | automerge::ObjType::Text)
};
// Whether the object is one the document held at `doc_heads`, for what
// can then be read there.
let mut held = false;
match &op.obj {
ObjectId::Root => {
if in_list {
return Some("it writes a list's element into the root".to_owned());
}
held = true;
}
ObjectId::Id(id) => {
let object = exid(id);
// Seen where its parent holds it, at the document's changes this
// one builds on: made in its history, with nothing walked.
let seen = !doc_heads.is_empty()
&& !self.ops.contains_key(&(id.1.clone(), id.0))
&& doc.object_type(&object).is_ok_and(fits)
&& doc
.parents(&object)
.ok()
.and_then(|mut parents| parents.next())
.is_some_and(|parent| match parent.prop {
automerge::Prop::Map(key) => doc
.get_all_at(&parent.obj, key, &doc_heads)
.is_ok_and(|held| held.iter().any(|(_, id)| *id == object)),
automerge::Prop::Seq(_) => false,
});
if seen {
held = true;
} else if !made(self, id).is_some_and(|made| made.makes.is_some_and(fits)) {
let OpId(counter, by) = id;
return Some(format!(
"it writes into {counter}@{by}, no object of that kind made before it"
));
}
}
}
// The element of a list: one put into that list.
let element = match &op.key {
Key::Seq(ElementId::Id(id)) => Some(id),
Key::Seq(ElementId::Head) | Key::Map(_) => None,
};
if let Some(id) = element
&& !made(self, id).is_some_and(|made| made.insert && made.obj == op.obj)
{
let OpId(counter, by) = id;
return Some(format!(
"it names {counter}@{by}, no element of that list put there before it"
));
}
// What it replaces: operations at its place.
let there: Vec<automerge::ObjId> = match (&op.key, held, op.pred.is_empty()) {
// Those the document holds there, at the changes this one builds on:
// in its history, with nothing walked.
(Key::Map(key), true, false) if !doc_heads.is_empty() => {
let object = match &op.obj {
ObjectId::Root => automerge::ROOT,
ObjectId::Id(id) => exid(id),
};
doc.get_all_at(&object, key.as_str(), &doc_heads)
.map(|held| held.into_iter().map(|(_, id)| id).collect())
.unwrap_or_default()
}
_ => Vec::new(),
};
for id in op.pred.iter() {
let at_its_place = there.contains(&exid(id))
|| (element == Some(id))
|| made(self, id).is_some_and(|made| made.obj == op.obj && made.key == op.key);
if !at_its_place {
let OpId(counter, by) = id;
return Some(format!(
"it replaces {counter}@{by}, no operation at that place made before it"
));
}
}
}
self.checked = Some((
hash,
Passed {
deps: change.deps().to_vec(),
actor: actor.clone(),
seq: change.seq(),
max_op: last,
doc_heads,
},
));
None
}
/// `change` (`expanded`: it, decoded), the last that passed [`Written::check`],
/// taken: those after it are checked against what it made.
pub(crate) fn taken(&mut self, change: &Change, expanded: &ExpandedChange) {
let hash = change.hash();
let Some((checked, passed)) = self.checked.take() else {
return;
};
if checked != hash {
return;
}
let start = change.start_op().get();
for (index, op) in expanded.operations.iter().enumerate() {
self.ops.insert(
(change.actor_id().clone(), start + index as u64),
Made::of(hash, op),
);
}
self.passed.insert(hash, passed);
}
/// The highest operation counter of a change of the batch or the document.
fn max_op(&self, doc: &Document, hash: &ChangeHash) -> Option<u64> {
self.passed
.get(hash)
.map(|passed| passed.max_op)
.or_else(|| doc.get_change_meta_by_hash(hash).map(|meta| meta.max_op))
}
/// What the operation `id` is, made by a change of the batch taken before.
fn made_in_batch(&self, id: &automerge::legacy::OpId) -> Option<Made> {
let automerge::legacy::OpId(counter, by) = id;
self.ops.get(&(by.clone(), *counter)).cloned()
}
/// What the operation `id` is, made by a change of the document.
fn made_in_doc(&mut self, doc: &Document, id: &automerge::legacy::OpId) -> Option<Made> {
let automerge::legacy::OpId(counter, by) = id;
let hash = doc.hash_for_opid(&automerge::ObjId::Id(*counter, by.clone(), 0))?;
let change = self
.decoded
.entry(hash)
.or_insert_with(|| doc.get_change_by_hash(&hash).map(|change| decode(&change)))
.as_ref()?;
let index = counter.checked_sub(change.start_op.get())?;
let op = change.operations.get(usize::try_from(index).ok()?)?;
Some(Made::of(hash, op))
}
/// Whether `target`, a change with an operation numbered `counter`, is in the
/// history `history` walks. A change's operations are numbered above those of
/// all it builds on, so the walk goes no further back than `counter`.
fn reaches(
&self,
doc: &Document,
history: &mut History,
target: ChangeHash,
counter: u64,
) -> bool {
while let Some((max_op, _)) = history.queue.peek()
&& *max_op >= counter
&& !history.seen.contains(&target)
{
let (_, hash) = history.queue.pop().expect("peeked");
let deps = match self.passed.get(&hash) {
Some(passed) => passed.deps.clone(),
None => doc
.get_change_meta_by_hash(&hash)
.map(|meta| meta.deps)
.unwrap_or_default(),
};
for dep in deps {
if history.seen.insert(dep)
&& let Some(max_op) = self.max_op(doc, &dep)
{
history.queue.push((max_op, dep));
}
}
}
history.seen.contains(&target)
}
}
/// `change`, if it names an author but isn't its actor's first (`misplaced_author`).
fn misplaced_in(change: &Change) -> Option<MisplacedAuthor> {
let author = change.author()?;
(change.seq() != 1).then(|| MisplacedAuthor {
author: author.as_bytes().to_vec(),
actor: change.actor_id().clone(),
seq: change.seq(),
})
}
/// The author in a change's extra bytes: footers, each its kind (LEB128; 1 is the
/// author), its length (LEB128) and its bytes.
fn author_footer(mut extra: &[u8]) -> Option<Vec<u8>> {
while !extra.is_empty() {
let (kind, read) = uleb128(extra)?;
let (length, more) = uleb128(&extra[read..])?;
let start = read + more;
let end = start.checked_add(usize::try_from(length).ok()?)?;
let bytes = extra.get(start..end)?;
if kind == 1 {
return Some(bytes.to_vec());
}
extra = &extra[end..];
}
None
}
/// An unsigned LEB128 number at the start of `bytes`, and how many bytes it took.
fn uleb128(bytes: &[u8]) -> Option<(u64, usize)> {
let mut value = 0u64;
for (i, byte) in bytes.iter().enumerate().take(10) {
value |= u64::from(byte & 0x7f) << (7 * i);
if byte & 0x80 == 0 {
return Some((value, i + 1));
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::testing::change;
use automerge::{ActorId, ROOT, transaction::Transactable};
fn random_write(rng: &mut crate::testrand::Rng, doc: &mut Document) {
let key = format!("k{}", rng.below(6));
let value = rng.below(100) as i64;
change(doc, |doc| doc.put(ROOT, key, value).unwrap());
}
fn sorted(mut heads: Vec<ChangeHash>) -> Vec<ChangeHash> {
heads.sort_unstable();
heads
}
/// Held: a change applied; not one never seen, nor one queued, waiting for the one
/// before it, until that comes.
#[test]
fn holds_applied_changes_only() {
let mut theirs = Document::new();
change(&mut theirs, |doc| doc.put(ROOT, "k", 1).unwrap());
let first = theirs.get_heads()[0];
change(&mut theirs, |doc| doc.put(ROOT, "k", 2).unwrap());
let second = theirs.get_heads()[0];
let mut ours = Document::new();
assert!(!holds(&ours, &first));
ours.apply_changes([theirs.get_change_by_hash(&second).unwrap()])
.unwrap();
assert!(!holds(&ours, &second), "queued");
assert!(!holds(&ours, &first));
ours.apply_changes([theirs.get_change_by_hash(&first).unwrap()])
.unwrap();
assert!(holds(&ours, &first));
assert!(holds(&ours, &second));
assert!(holds_all(&ours, &[first, second]));
}
/// Over random histories: two nodes that reached the same heads through different
/// merge orders, one with more on top, produce the same bytes for a delta to those
/// heads; a document at `from` that loads them is at `to`.
#[test]
fn delta_bytes_are_the_same_everywhere_and_complete() {
crate::testrand::for_seeds(200, |rng| {
let actor = |i: u8| ActorId::from(&[i; 16][..]);
let mut base = Document::new().with_actor(actor(0));
for _ in 0..rng.between(0, 5) {
random_write(rng, &mut base);
}
let from = base.get_heads();
let mut writers: Vec<Document> = (1..=rng.between(1, 3))
.map(|i| base.fork().with_actor(actor(i as u8)))
.collect();
for _ in 0..rng.between(1, 15) {
let writer = rng.below(writers.len());
random_write(rng, &mut writers[writer]);
}
let mut one = base.fork().with_actor(actor(10));
let mut two = base.fork().with_actor(actor(11));
for writer in writers.iter_mut() {
one.merge(writer).unwrap();
}
for writer in writers.iter_mut().rev() {
two.merge(writer).unwrap();
}
let to = one.get_heads();
assert_eq!(sorted(to.clone()), sorted(two.get_heads()));
// Beyond `to`: must stay out of the delta.
random_write(rng, &mut two);
let bytes = delta_bytes(&one, &from, &to).unwrap();
assert_eq!(delta_bytes(&two, &from, &to).unwrap(), bytes);
let mut behind = base.fork();
load_delta(&mut behind, &bytes).unwrap();
assert_eq!(sorted(behind.get_heads()), sorted(to));
});
}
/// Heads cover ours when their history holds all of ours: as far as ours, or
/// further; not when behind or beside; heads we don't know count for nothing.
#[test]
fn heads_that_cover_ours() {
let mut doc = Document::new();
change(&mut doc, |doc| doc.put(ROOT, "a", 1_i64).unwrap());
let early = doc.get_heads();
change(&mut doc, |doc| doc.put(ROOT, "b", 2_i64).unwrap());
let ours = doc.get_heads();
let mut further = doc.fork();
change(&mut further, |doc| doc.put(ROOT, "c", 3_i64).unwrap());
doc.merge(&mut further.clone()).unwrap();
let unknown = ChangeHash([7; 32]);
assert!(covers(&doc, &ours, &ours));
assert!(covers(&doc, &further.get_heads(), &ours), "further");
assert!(!covers(&doc, &early, &ours), "behind");
assert!(!covers(&doc, &[unknown], &ours), "unknown");
assert!(
covers(&doc, &[unknown, ours[0]], &ours),
"the known one does"
);
}
#[test]
fn no_delta_without_its_heads() {
let mut doc = Document::new();
change(&mut doc, |doc| doc.put(ROOT, "k", 1_i64).unwrap());
let heads = doc.get_heads();
assert!(delta_bytes(&doc, &[], &[ChangeHash([7; 32])]).is_none());
assert!(
delta_bytes(&doc, &[ChangeHash([7; 32])], &heads).is_none(),
"nor without where it starts"
);
}
/// A change loads from its bytes only as the change it was asked for.
#[test]
fn a_change_is_checked_against_its_hash() {
let mut doc = Document::new();
change(&mut doc, |doc| doc.put(ROOT, "k", 1_i64).unwrap());
let hash = doc.get_heads()[0];
let bytes = change_bytes(&doc, &hash).unwrap();
assert_eq!(change_from_bytes(bytes.clone(), hash).unwrap().hash(), hash);
assert!(change_from_bytes(bytes, ChangeHash([7; 32])).is_err());
assert!(change_bytes(&doc, &ChangeHash([7; 32])).is_none());
}
/// The authors of the changes after some heads: each node that wrote some, once,
/// however their changes were merged; a change without an author is told apart.
#[test]
fn authors_of_the_changes_since() {
use crate::clock::UnixMillis;
use crate::document::replica::{Writer, transact};
let write = |doc: &mut Document, node: &str, key: &str| {
let writer = Writer { node, user: None };
transact(doc, UnixMillis(1), &writer, |doc| doc.put(ROOT, key, 1)).unwrap();
};
let mut base = Document::new();
write(&mut base, "node-a", "base");
let since = base.get_heads();
assert_eq!(authors_since(&base, &since), (Vec::new(), false));
let mut a = base.fork();
write(&mut a, "node-a", "a1");
write(&mut a, "node-a", "a2");
let mut b = base.fork();
write(&mut b, "node-b", "b1");
let mut merged = a.clone();
merged.merge(&mut b).unwrap();
let (mut authors, unknown) = authors_since(&merged, &since);
authors.sort();
let counts: Vec<(&str, usize)> = authors
.iter()
.map(|(author, hashes)| (author.as_str(), hashes.len()))
.collect();
assert_eq!(counts, [("node-a", 2), ("node-b", 1)]);
assert!(!unknown);
// A change no node authored (a snapshot's, say).
let mut snapshot = Document::new();
snapshot.merge(&mut merged.clone()).unwrap();
change(&mut snapshot, |doc| doc.put(ROOT, "s", 1).unwrap());
let (_, unknown) = authors_since(&snapshot, &merged.get_heads());
assert!(unknown);
}
/// An actor without an author, and its two changes: the second as made, and with an
/// author footer it mustn't carry.
fn misplaced() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
let mut doc = Document::new().with_actor(ActorId::from(b"writer".to_vec()));
change(&mut doc, |tx| tx.put(ROOT, "x", 1).unwrap());
change(&mut doc, |tx| tx.put(ROOT, "x", 2).unwrap());
let changes = doc.get_changes(&[]);
let (first, second) = (
changes[0].raw_bytes().to_vec(),
changes[1].raw_bytes().to_vec(),
);
let crafted = crate::document::testing::with_author_footer(&second, b"mallory");
(first, second, crafted)
}
#[test]
fn an_author_on_a_later_change_is_found() {
let (first, second, crafted) = misplaced();
assert_eq!(misplaced_author(&[first.clone(), second].concat()), None);
let found = misplaced_author(&[first.clone(), crafted.clone()].concat()).unwrap();
assert_eq!(found.seq, 2);
assert_eq!(found.author, b"mallory");
assert_eq!(found.actor, ActorId::from(b"writer".to_vec()));
// Honest authors (on first changes) and whole documents pass.
let mut authored = Document::new();
authored.set_author(Some(automerge::Author::from(b"node".to_vec())));
change(&mut authored, |tx| tx.put(ROOT, "a", 1).unwrap());
change(&mut authored, |tx| tx.put(ROOT, "a", 2).unwrap());
assert_eq!(misplaced_author(&authored.save()), None);
let bytes: Vec<u8> = authored
.get_changes(&[])
.iter()
.flat_map(|change| change.raw_bytes().to_vec())
.collect();
assert_eq!(misplaced_author(&bytes), None);
// What isn't chunks is left to Automerge.
assert_eq!(misplaced_author(b"not a chunk"), None);
}
#[test]
fn a_delta_with_a_misplaced_author_is_refused_and_the_document_kept() {
let (first, _, crafted) = misplaced();
let mut doc = Document::new();
load_delta(&mut doc, &first).unwrap();
let heads = doc.get_heads();
assert!(load_delta(&mut doc, &crafted).is_err());
assert_eq!(doc.get_heads(), heads);
// Still whole: it saves and loads.
crate::document::load(&doc.save()).unwrap();
}
/// A document written the ways the store writes: maps within maps, lists, text,
/// values replaced and deleted, by two nodes at once.
fn written() -> Document {
use automerge::ObjType;
let mut doc = Document::new();
let (map, list) = change(&mut doc, |doc| {
let map = doc.put_object(ROOT, "map", ObjType::Map).unwrap();
doc.put(&map, "k", "v").unwrap();
let list = doc.put_object(&map, "list", ObjType::List).unwrap();
doc.insert(&list, 0, 1).unwrap();
doc.insert(&list, 1, "two").unwrap();
(map, list)
});
change(&mut doc, |doc| {
doc.put(&map, "k", vec![1u8, 2, 3]).unwrap();
doc.delete(&list, 0).unwrap();
doc.insert(&list, 1, true).unwrap();
let text = doc.put_object(ROOT, "text", ObjType::Text).unwrap();
doc.splice_text(&text, 0, 0, "hello").unwrap();
});
let mut other = doc.fork();
change(&mut other, |doc| doc.put(&map, "k", 2.5).unwrap());
change(&mut other, |doc| doc.delete(&map, "list").unwrap());
change(&mut doc, |doc| doc.put(&map, "k", ()).unwrap());
change(&mut doc, |doc| doc.delete(ROOT, "text").unwrap());
doc.merge(&mut other).unwrap();
change(&mut doc, |doc| doc.put(&map, "k", "merged").unwrap());
doc
}
/// What Automerge writes passes: checked against a document taking the changes
/// one by one, and as one batch against an empty one.
#[test]
fn changes_automerge_writes_pass() {
let theirs = written();
let changes = theirs.get_changes(&[]);
let mut ours = Document::new();
for change in &changes {
assert_eq!(
Written::default().check(&ours, change, &change.decode()),
None
);
ours.apply_changes([change.clone()]).unwrap();
}
let empty = Document::new();
let mut written = Written::default();
for change in &changes {
let expanded = change.decode();
assert_eq!(written.check(&empty, change, &expanded), None);
written.taken(change, &expanded);
}
}
/// Bytes that load as a change and aren't Automerge's encoding of it: refused.
#[test]
fn bytes_automerge_wouldnt_encode_are_refused() {
let mut theirs = Document::new();
change(&mut theirs, |doc| doc.put(ROOT, "k", 1).unwrap());
let honest = theirs.get_changes(&[]).remove(0);
let ours = Document::new();
assert_eq!(
Written::default().check(&ours, &honest, &honest.decode()),
None
);
let crafted = crate::document::testing::with_spare_actor(honest.raw_bytes(), &[0xab; 16]);
let crafted = Change::try_from(&crafted[..]).expect("it loads");
assert_ne!(crafted.hash(), honest.hash());
let why = Written::default()
.check(&ours, &crafted, &crafted.decode())
.expect("refused");
assert!(why.contains("encodes"), "{why}");
}
/// A first operation numbered ahead of the dependencies', or below them: refused.
#[test]
fn operations_numbered_against_their_dependencies_are_refused() {
let mut theirs = Document::new();
change(&mut theirs, |doc| doc.put(ROOT, "k", 1).unwrap());
change(&mut theirs, |doc| doc.put(ROOT, "k", 2).unwrap());
let mut ours = Document::new();
ours.apply_changes(theirs.get_changes(&[])).unwrap();
change(&mut theirs, |doc| doc.put(ROOT, "other", 3).unwrap());
let honest = theirs.get_last_local_change().unwrap();
assert_eq!(honest.start_op().get(), 3);
for start in [1, 2, 4, (1 << 32) - 1] {
let mut expanded = honest.decode();
expanded.start_op = std::num::NonZeroU64::new(start).unwrap();
expanded.hash = None;
let crafted = Change::from(expanded);
let why = Written::default()
.check(&ours, &crafted, &crafted.decode())
.expect("refused");
assert!(why.contains("numbered"), "{start}: {why}");
}
assert_eq!(
Written::default().check(&ours, &honest, &honest.decode()),
None
);
// A root: numbered 1.
let root = theirs.get_changes(&[]).remove(0);
let mut expanded = root.decode();
expanded.start_op = std::num::NonZeroU64::new(7).unwrap();
expanded.hash = None;
let crafted = Change::from(expanded);
assert!(
Written::default()
.check(&Document::new(), &crafted, &crafted.decode())
.is_some()
);
}
/// An operation on an object nobody made, by an actor the document doesn't hold or
/// at a counter its actor never reached: refused.
#[test]
fn operations_naming_what_nobody_made_are_refused() {
use automerge::legacy::{ObjectId, OpId};
let mut theirs = Document::new();
let map = change(&mut theirs, |doc| {
doc.put_object(ROOT, "map", automerge::ObjType::Map)
.unwrap()
});
change(&mut theirs, |doc| doc.put(ROOT, "k", 1).unwrap());
let mut ours = Document::new();
ours.apply_changes(theirs.get_changes(&[])).unwrap();
change(&mut theirs, |doc| doc.put(&map, "k", 2).unwrap());
let honest = theirs.get_last_local_change().unwrap();
assert_eq!(
Written::default().check(&ours, &honest, &honest.decode()),
None
);
let known = theirs.get_actor().clone();
for object in [
OpId(1, ActorId::from([0xab; 16])),
OpId(honest.start_op().get() + 5, known.clone()),
OpId(honest.start_op().get(), ActorId::from([0xab; 16])),
] {
let mut expanded = honest.decode();
expanded.operations[0].obj = ObjectId::Id(object.clone());
expanded.hash = None;
let crafted = Change::from(expanded);
let why = Written::default()
.check(&ours, &crafted, &crafted.decode())
.expect("refused");
assert!(why.contains("no object"), "{object:?}: {why}");
}
}
/// `honest` with `edit` made to it, as a change of its own.
fn crafted(honest: &Change, edit: impl FnOnce(&mut ExpandedChange)) -> Change {
let mut expanded = honest.decode();
edit(&mut expanded);
expanded.hash = None;
Change::from(expanded)
}
/// An operation named as replaced that is elsewhere, or that put no object where
/// one is written into: refused, though it was made before.
#[test]
fn operations_named_at_the_wrong_place_are_refused() {
use automerge::legacy::{ObjectId, OpId};
let mut theirs = Document::new();
change(&mut theirs, |doc| doc.put(ROOT, "a", 1).unwrap());
change(&mut theirs, |doc| doc.put(ROOT, "b", 2).unwrap());
let mut ours = Document::new();
ours.apply_changes(theirs.get_changes(&[])).unwrap();
let actor = theirs.get_actor().clone();
change(&mut theirs, |doc| doc.put(ROOT, "b", 3).unwrap());
let honest = theirs.get_last_local_change().unwrap();
assert_eq!(
Written::default().check(&ours, &honest, &honest.decode()),
None
);
// It replaces what wrote `a`.
let elsewhere = crafted(&honest, |change| {
change.operations[0].pred = vec![OpId(1, actor.clone())].into();
});
let why = Written::default()
.check(&ours, &elsewhere, &elsewhere.decode())
.expect("refused");
assert!(why.contains("at that place"), "{why}");
// It writes into what put a number.
let no_object = crafted(&honest, |change| {
change.operations[0].obj = ObjectId::Id(OpId(1, actor.clone()));
change.operations[0].pred = Vec::new().into();
});
let why = Written::default()
.check(&ours, &no_object, &no_object.decode())
.expect("refused");
assert!(why.contains("no object"), "{why}");
}
/// An operation named that the document holds, made by a change this one doesn't
/// build on: refused, as by a node that doesn't hold it yet.
#[test]
fn operations_outside_a_changes_history_are_refused() {
use automerge::legacy::OpId;
let mut theirs = Document::new();
change(&mut theirs, |doc| doc.put(ROOT, "k", 1).unwrap());
let mut other = theirs.fork();
change(&mut other, |doc| doc.put(ROOT, "k", 2).unwrap());
let aside = other.get_last_local_change().unwrap();
change(&mut theirs, |doc| doc.put(ROOT, "k", 3).unwrap());
let honest = theirs.get_last_local_change().unwrap();
// It also replaces what the other wrote, which it never saw.
let reaching = crafted(&honest, |change| {
let mut pred: Vec<OpId> = change.operations[0].pred.iter().cloned().collect();
pred.push(OpId(aside.start_op().get(), aside.actor_id().clone()));
change.operations[0].pred = pred.into();
});
// Whether we hold the other's change or not.
let mut without = Document::new();
without
.apply_changes(theirs.get_changes(&[]).into_iter().take(1))
.unwrap();
let mut with = without.clone();
with.apply_changes([aside.clone()]).unwrap();
for ours in [&without, &with] {
assert_eq!(
Written::default().check(ours, &honest, &honest.decode()),
None
);
let why = Written::default()
.check(ours, &reaching, &reaching.decode())
.expect("refused");
assert!(why.contains("at that place"), "{why}");
}
}
/// A change that isn't its actor's first and doesn't build on the one before it:
/// refused.
#[test]
fn a_gap_in_an_actors_changes_is_refused() {
let mut theirs = Document::new();
change(&mut theirs, |doc| doc.put(ROOT, "k", 1).unwrap());
let mut ours = Document::new();
ours.apply_changes(theirs.get_changes(&[])).unwrap();
change(&mut theirs, |doc| doc.put(ROOT, "k", 2).unwrap());
let honest = theirs.get_last_local_change().unwrap();
assert_eq!(honest.seq(), 2);
assert_eq!(
Written::default().check(&ours, &honest, &honest.decode()),
None
);
for seq in [3, 7] {
let gap = crafted(&honest, |change| change.seq = seq);
let why = Written::default()
.check(&ours, &gap, &gap.decode())
.expect("refused");
assert!(why.contains("the one before"), "{seq}: {why}");
}
// A first change of another actor numbered 2.
let mut stranger = ours.fork().with_actor(ActorId::from([0xcd; 16]));
change(&mut stranger, |doc| doc.put(ROOT, "k", 9).unwrap());
let first = stranger.get_last_local_change().unwrap();
let second = crafted(&first, |change| change.seq = 2);
assert!(
Written::default()
.check(&ours, &second, &second.decode())
.is_some()
);
}
/// Changes of one batch building on each other pass, each checked against those
/// before it; one naming what a change of the batch wrote elsewhere doesn't.
#[test]
fn a_batch_is_checked_against_itself() {
use automerge::legacy::OpId;
let theirs = written();
let changes = theirs.get_changes(&[]);
let half = changes.len() / 2;
let mut ours = Document::new();
ours.apply_changes(changes[..half].iter().cloned()).unwrap();
let mut written = Written::default();
for change in &changes[half..] {
let expanded = change.decode();
assert_eq!(written.check(&ours, change, &expanded), None);
written.taken(change, &expanded);
}
// The last put `k` in the map: have it replace what made the map.
let last = changes.last().unwrap();
let first = &changes[0];
let elsewhere = crafted(last, |change| {
change.operations[0].pred =
vec![OpId(first.start_op().get(), first.actor_id().clone())].into();
});
let mut written = Written::default();
for change in &changes[..changes.len() - 1] {
let expanded = change.decode();
assert_eq!(written.check(&Document::new(), change, &expanded), None);
written.taken(change, &expanded);
}
assert!(
written
.check(&Document::new(), &elsewhere, &elsewhere.decode())
.is_some()
);
}
/// A fork of a change the document holds, checked before an honest change of the
/// same batch and refused after (as forged): it doesn't stand in for the change the
/// document holds, and the honest change passes.
#[test]
fn a_change_refused_after_its_check_stands_in_for_nothing() {
let mut theirs = Document::new();
let map = change(&mut theirs, |doc| {
doc.put_object(ROOT, "map", automerge::ObjType::Map)
.unwrap()
});
let made = theirs.get_last_local_change().unwrap();
let mut ours = Document::new();
ours.apply_changes([made.clone()]).unwrap();
change(&mut theirs, |doc| doc.put(&map, "k", 1).unwrap());
let honest = theirs.get_last_local_change().unwrap();
// The same actor and counters as the change that made the map, putting a
// number where the map was made.
let fork = crafted(&made, |change| {
change.operations[0].action = automerge::legacy::OpType::Put(1.into());
});
assert_ne!(fork.hash(), made.hash());
let mut written = Written::default();
assert_eq!(written.check(&ours, &fork, &fork.decode()), None);
// Not taken: screening refuses it as forged.
assert_eq!(written.check(&ours, &honest, &honest.decode()), None);
}
}
|