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
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
|
//! The wire format of a message: one byte for the format's version (`VERSION`), one
//! saying what the message is (`MessageKind`), then the message itself in MessagePack, as derived from its type in `transport` (structs as
//! arrays, fields in declaration order). The codecs below make hashes, IDs and bytes
//! compact (MessagePack binaries, not arrays of numbers) and check their lengths.
//!
//! Every change to a message type or a codec is a new version (`VERSION`), and a build
//! speaks several side by side, `OLDEST` to `VERSION`: it reads each, and writes to each
//! node the newest both speak (`choose`), as the node's SPEAKS says, or `OLDEST` until
//! then (`transport::identity`). So releases whose versions meet roll out node by node:
//! a release adds a version and keeps the older ones, and a later one leaves out the
//! oldest. The messages of an older version keep their own types, frozen, encoded and
//! decoded here beside the newest's (`golden_bytes` keeps the bytes of each). The
//! transport's topic says which application a message is for, not which version.
//!
//! Two kinds of messages stand outside the versions, as they are what lets two builds
//! learn what the other speaks:
//!
//! * SPEAKS (`SPEAKS`), its first byte the version none is, laid out as no build changes,
//! saying which versions a node speaks and the newest revision of the federation it
//! knows. A build from before it reads it as a message of another version, and
//! ignores it.
//! * WHO and ME, the proofs of who is at an address (`PROOFS`), laid out in every
//! version as in the first: a build reads them whatever version they say they are in,
//! from that first on, so that two nodes prove themselves to each other before they
//! know what the other speaks.
use thiserror::Error;
use super::{EncodedMessage, MessageKind, ParsedMessage};
/// The wire format's version, the first byte of every payload. Bump it with every change
/// to a message type or a codec (`golden_bytes` fails then).
pub(crate) const VERSION: u8 = 53;
/// The oldest version this build speaks: the messages of every version from it to
/// `VERSION` it reads. Its SPEAKS says so.
pub(crate) const OLDEST: u8 = 52;
/// The first version in which what is a document's kind's goes as bytes the wire doesn't
/// read (`kinds`), and a handshake says the kind.
pub(crate) const KINDS: u8 = 53;
/// The first byte of a SPEAKS, which no version is. Its layout, never to change: that
/// byte, the oldest version the sender speaks, the newest, then the 32 bytes of the ID
/// of the newest revision of the federation it knows, where it knows one. A reader takes
/// those and leaves whatever follows, which a later build may add.
pub(crate) const SPEAKS: u8 = 0;
/// The first version with SPEAKS, as WHO and ME are laid out in every version: their
/// tags and fields never change (a change would be a new kind of message), and a build
/// reads them in any version from this one on, older or newer than its own.
pub(crate) const PROOFS: u8 = 52;
// Whatever this build's versions, a SPEAKS reads as one, and it reads the proofs of
// every build that speaks one of its versions.
const _: () = assert!(SPEAKS < PROOFS && PROOFS <= OLDEST && OLDEST <= VERSION);
/// What the second byte of a payload says.
fn tag(kind: MessageKind) -> u8 {
match kind {
MessageKind::Hello => 0,
MessageKind::HelloReply => 1,
MessageKind::Sync => 2,
MessageKind::Status => 3,
MessageKind::StatusReply => 4,
MessageKind::Blob => 5,
MessageKind::Who => 6,
MessageKind::Me => 7,
MessageKind::Ping => 8,
MessageKind::Pong => 9,
MessageKind::Probe => 12,
MessageKind::ProbeReply => 13,
MessageKind::Prune => 14,
MessageKind::Graft => 15,
MessageKind::Neighbour => 16,
MessageKind::NeighbourReply => 17,
MessageKind::Disconnect => 18,
MessageKind::Refusals => 20,
// None: a SPEAKS has no second byte (`SPEAKS`).
MessageKind::Speaks => u8::MAX,
}
}
#[derive(Error, Debug)]
pub(crate) enum WireError {
#[error("empty payload")]
Empty,
#[error("wire format version {0} (we speak version {VERSION})")]
Version(u8),
#[error("unknown message kind {0}")]
UnknownKind(u8),
#[error("MessagePack serialization failed: {0}")]
Encode(#[from] rmp_serde::encode::Error),
#[error("MessagePack deserialization failed: {0}")]
Decode(#[from] rmp_serde::decode::Error),
}
/// `message` to `peer`, encoded in wire `version` as it goes on the wire alone (no
/// envelope: libp2p, Tor, the simulator); `peer` is its address too.
#[cfg_attr(not(any(feature = "libp2p", feature = "tor", test)), allow(dead_code))]
pub(crate) fn encoded_in(
peer: &str,
message: &ParsedMessage,
version: u8,
) -> anyhow::Result<EncodedMessage> {
let body = encode_in(message, version)?;
Ok(EncodedMessage {
peer: peer.to_owned(),
address: peer.to_owned(),
payload_len: body.len(),
body: body.into(),
kind: message.kind(),
message: None,
})
}
/// The newest wire version a peer speaking `oldest` to `newest` (its SPEAKS) and this
/// build both speak: what this build writes to it. None where they share none.
pub(crate) fn choose(oldest: u8, newest: u8) -> Option<u8> {
let (low, high) = (oldest.max(OLDEST), newest.min(VERSION));
(low <= high).then_some(high)
}
/// The payload of `message` in wire `version`, one of `OLDEST..=VERSION`: of an older one,
/// as a build speaking only that one reads it. A SPEAKS is laid out alike in every one,
/// and so are WHO and ME (`PROOFS`), but for the version they say.
pub(crate) fn encode_in(message: &ParsedMessage, version: u8) -> Result<Vec<u8>, WireError> {
if let ParsedMessage::Speaks(speaks) = message {
let mut payload = vec![SPEAKS, speaks.oldest, speaks.newest];
payload.extend(speaks.revision.iter().flatten());
return Ok(payload);
}
let proof =
matches!(message, ParsedMessage::Who(_) | ParsedMessage::Me(_)) && version >= PROOFS;
if !(OLDEST..=VERSION).contains(&version) && !proof {
return Err(WireError::Version(version));
}
let mut payload = vec![version, tag(message.kind())];
// From `KINDS` on, what is a document's kind's goes as bytes (`kinds`); before, as
// the messages' own types have it, which are Automerge's.
if version >= KINDS && kinds::write(&mut payload, message)? {
return Ok(payload);
}
match message {
ParsedMessage::Hello(hello) => rmp_serde::encode::write(&mut payload, hello)?,
ParsedMessage::HelloReply(reply) => rmp_serde::encode::write(&mut payload, reply)?,
ParsedMessage::Sync(envelope) => rmp_serde::encode::write(&mut payload, envelope)?,
ParsedMessage::Status(status) | ParsedMessage::StatusReply(status) => {
rmp_serde::encode::write(&mut payload, status)?
}
ParsedMessage::Blob(blob) => rmp_serde::encode::write(&mut payload, blob)?,
ParsedMessage::Who(proof) | ParsedMessage::Me(proof) => {
rmp_serde::encode::write(&mut payload, proof)?
}
ParsedMessage::Ping(nonce) => rmp_serde::encode::write(&mut payload, nonce)?,
ParsedMessage::Pong { nonce, at } => rmp_serde::encode::write(&mut payload, &(nonce, at))?,
ParsedMessage::Probe(request) => rmp_serde::encode::write(&mut payload, request)?,
ParsedMessage::ProbeReply(reply) => rmp_serde::encode::write(&mut payload, reply)?,
ParsedMessage::Prune(link) | ParsedMessage::Graft(link) => {
rmp_serde::encode::write(&mut payload, link)?
}
ParsedMessage::Neighbour(request) => rmp_serde::encode::write(&mut payload, request)?,
ParsedMessage::NeighbourReply(answer) | ParsedMessage::Disconnect(answer) => {
rmp_serde::encode::write(&mut payload, answer)?
}
ParsedMessage::Refusals(message) => rmp_serde::encode::write(&mut payload, message)?,
ParsedMessage::Speaks(_) => unreachable!("encoded above"),
}
Ok(payload)
}
/// The payload of `message`, in the newest wire version.
#[cfg(test)]
pub(crate) fn encode(message: &ParsedMessage) -> Result<Vec<u8>, WireError> {
encode_in(message, VERSION)
}
/// The messages that carry what is a document's kind's (`docs/document.md`, Passing on),
/// as the versions from `KINDS` on lay them out: what is the kind's is bytes, which the
/// wire carries and doesn't read. Automerge's bytes are what the version before carried
/// in the messages' own fields, in MessagePack as there.
///
/// * HELLO, HELLO_REPLY: the message as before, then the kind (`document::KIND`).
/// * SYNC: its body, with whether the sender takes it as delivered, as bytes; and what
/// vouches for what it carries, as bytes (the signatures, as before).
/// * STATUS, STATUS_REPLY: where the sender's document stands, as bytes.
/// * BLOB: a request's account of what it asks for in bulk (a delta's heads), as bytes.
mod kinds {
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;
use super::{ParsedMessage, WireError, codec};
use crate::clock::UnixMillis;
use crate::document::replica::Epoch;
use crate::transport::{
BlobBody, BlobId, BlobMessage, DeltaSpec, EpochTag, HeadsSummary, Status, SyncBody,
SyncEnvelope,
};
#[derive(Serialize)]
struct SyncOut<'a> {
epoch: EpochTag,
epoch_seq: u32,
#[serde(with = "serde_bytes")]
body: &'a [u8],
ready: bool,
writer: Option<u64>,
sent: UnixMillis,
#[serde(with = "serde_bytes")]
vouchers: &'a [u8],
}
#[derive(Deserialize)]
struct SyncIn {
epoch: EpochTag,
epoch_seq: u32,
body: ByteBuf,
ready: bool,
writer: Option<u64>,
sent: UnixMillis,
vouchers: ByteBuf,
}
#[derive(Serialize)]
struct StatusOut<'a> {
#[serde(with = "serde_bytes")]
stamp: &'a [u8],
#[serde(with = "codec::epoch")]
epoch: Epoch,
epoch_seq: u32,
ready: bool,
syncs_with_you: bool,
leaving: bool,
announcing: bool,
reaches: &'a Option<Vec<u64>>,
#[serde(with = "serde_bytes")]
round_trips: &'a Option<Vec<u8>>,
}
#[derive(Deserialize)]
struct StatusIn {
stamp: ByteBuf,
#[serde(with = "codec::epoch")]
epoch: Epoch,
epoch_seq: u32,
ready: bool,
syncs_with_you: bool,
leaving: bool,
announcing: bool,
reaches: Option<Vec<u64>>,
#[serde(with = "serde_bytes")]
round_trips: Option<Vec<u8>>,
}
/// Where an Automerge document stands, as its bytes have it.
struct StampOut<'a>(&'a HeadsSummary);
impl Serialize for StampOut<'_> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
codec::heads::serialize(self.0, s)
}
}
#[derive(Deserialize)]
struct StampIn(#[serde(with = "codec::heads")] HeadsSummary);
#[derive(Serialize, Deserialize)]
struct Blob {
#[serde(with = "codec::epoch")]
epoch: Epoch,
epoch_seq: u32,
id: Id,
body: Body,
sent: UnixMillis,
}
/// What a blob is of: a unit by its name, content by its hash, or what a kind offers
/// in bulk by its name for it.
#[derive(Serialize, Deserialize)]
enum Id {
Unit(#[serde(with = "codec::bytes32")] [u8; 32]),
Content(#[serde(with = "codec::bytes32")] [u8; 32]),
Bulk(#[serde(with = "codec::bytes32")] [u8; 32]),
}
/// `BlobBody`, a request saying what it asks for in bulk as bytes.
#[derive(Serialize, Deserialize)]
enum Body {
Request {
chunks: Vec<u32>,
spec: Option<ByteBuf>,
},
Manifest {
size: u64,
chunk_size: u32,
#[serde(with = "codec::hashes32")]
hashes: Vec<[u8; 32]>,
},
Chunk {
index: u32,
#[serde(with = "codec::shared_bytes")]
data: bytes::Bytes,
},
Missing,
DeflatedChunk {
index: u32,
#[serde(with = "codec::shared_bytes")]
data: bytes::Bytes,
},
}
/// Writes `message` after `payload`, where its layout is this module's: whether it is.
pub(super) fn write(payload: &mut Vec<u8>, message: &ParsedMessage) -> Result<bool, WireError> {
match message {
ParsedMessage::Hello(hello) => {
rmp_serde::encode::write(payload, &(hello, hello.kind.as_str()))?
}
ParsedMessage::HelloReply(reply) => {
rmp_serde::encode::write(payload, &(reply, reply.kind.as_str()))?
}
ParsedMessage::Sync(envelope) => {
let body = rmp_serde::to_vec(&(&envelope.body, envelope.delivered))?;
rmp_serde::encode::write(
payload,
&SyncOut {
epoch: envelope.epoch,
epoch_seq: envelope.epoch_seq,
body: &body,
ready: envelope.ready,
writer: envelope.writer,
sent: envelope.sent,
vouchers: &envelope.signatures,
},
)?
}
ParsedMessage::Status(status) | ParsedMessage::StatusReply(status) => {
let stamp = rmp_serde::to_vec(&StampOut(&status.heads))?;
rmp_serde::encode::write(
payload,
&StatusOut {
stamp: &stamp,
epoch: status.epoch,
epoch_seq: status.epoch_seq,
ready: status.ready,
syncs_with_you: status.syncs_with_you,
leaving: status.leaving,
announcing: status.announcing,
reaches: &status.reaches,
round_trips: &status.round_trips,
},
)?
}
ParsedMessage::Blob(blob) => {
let body = match &blob.body {
BlobBody::Request { chunks, delta } => Body::Request {
chunks: chunks.clone(),
spec: match delta {
Some(spec) => Some(ByteBuf::from(rmp_serde::to_vec(spec)?)),
None => None,
},
},
BlobBody::Manifest {
size,
chunk_size,
hashes,
} => Body::Manifest {
size: *size,
chunk_size: *chunk_size,
hashes: hashes.clone(),
},
BlobBody::Chunk { index, data } => Body::Chunk {
index: *index,
data: data.clone(),
},
BlobBody::Missing => Body::Missing,
BlobBody::DeflatedChunk { index, data } => Body::DeflatedChunk {
index: *index,
data: data.clone(),
},
};
rmp_serde::encode::write(
payload,
&Blob {
epoch: blob.epoch,
epoch_seq: blob.epoch_seq,
id: match blob.id {
BlobId::Change(hash) => Id::Unit(hash.0),
BlobId::Content(hash) => Id::Content(hash),
BlobId::Delta(id) => Id::Bulk(id),
},
body,
sent: blob.sent,
},
)?
}
_ => return Ok(false),
}
Ok(true)
}
/// The HELLO in `body`.
pub(super) fn hello(body: &[u8]) -> Result<ParsedMessage, WireError> {
let (mut hello, kind): (crate::transport::HelloRequest, String) =
rmp_serde::from_slice(body)?;
hello.kind = kind;
Ok(ParsedMessage::Hello(hello))
}
/// The HELLO_REPLY in `body`.
pub(super) fn hello_reply(body: &[u8]) -> Result<ParsedMessage, WireError> {
let (mut reply, kind): (crate::transport::HelloReply, String) =
rmp_serde::from_slice(body)?;
reply.kind = kind;
Ok(ParsedMessage::HelloReply(reply))
}
/// The SYNC in `body`.
pub(super) fn sync(body: &[u8]) -> Result<ParsedMessage, WireError> {
let sync: SyncIn = rmp_serde::from_slice(body)?;
let (body, delivered): (SyncBody, bool) = rmp_serde::from_slice(&sync.body)?;
Ok(ParsedMessage::Sync(SyncEnvelope {
epoch: sync.epoch,
epoch_seq: sync.epoch_seq,
body,
ready: sync.ready,
writer: sync.writer,
delivered,
sent: sync.sent,
signatures: sync.vouchers,
}))
}
/// The STATUS, or the STATUS_REPLY, in `body`.
pub(super) fn status(body: &[u8]) -> Result<Status, WireError> {
let status: StatusIn = rmp_serde::from_slice(body)?;
let StampIn(heads) = rmp_serde::from_slice(&status.stamp)?;
Ok(Status {
heads,
epoch: status.epoch,
epoch_seq: status.epoch_seq,
ready: status.ready,
syncs_with_you: status.syncs_with_you,
leaving: status.leaving,
announcing: status.announcing,
reaches: status.reaches,
round_trips: status.round_trips,
})
}
/// The BLOB in `body`.
pub(super) fn blob(body: &[u8]) -> Result<ParsedMessage, WireError> {
let blob: Blob = rmp_serde::from_slice(body)?;
let body = match blob.body {
Body::Request { chunks, spec } => BlobBody::Request {
chunks,
delta: match spec {
Some(spec) => Some(rmp_serde::from_slice::<DeltaSpec>(&spec)?),
None => None,
},
},
Body::Manifest {
size,
chunk_size,
hashes,
} => BlobBody::Manifest {
size,
chunk_size,
hashes,
},
Body::Chunk { index, data } => BlobBody::Chunk { index, data },
Body::Missing => BlobBody::Missing,
Body::DeflatedChunk { index, data } => BlobBody::DeflatedChunk { index, data },
};
Ok(ParsedMessage::Blob(BlobMessage {
epoch: blob.epoch,
epoch_seq: blob.epoch_seq,
id: match blob.id {
Id::Unit(name) => BlobId::Change(crate::document::ChangeHash(name)),
Id::Content(hash) => BlobId::Content(hash),
Id::Bulk(name) => BlobId::Delta(name),
},
body,
sent: blob.sent,
}))
}
}
/// The message in `payload` (as made by [`encode`]).
/// How many senders on another wire version are remembered as already logged
/// (`OtherVersions`).
const MAX_OTHER_VERSIONS: usize = 1024;
/// Senders whose messages are of another wire version (`WireError::Version`), or whose
/// SPEAKS names none this build speaks: each logged once, at warn level, so two builds
/// that don't speak to each other say so, and which of them to upgrade, instead of
/// silently retrying their HELLOs for good. Bounded: anyone can send us anything.
#[derive(Default)]
pub(crate) struct OtherVersions(std::sync::Mutex<std::collections::HashSet<String>>);
impl OtherVersions {
/// A message from `sender` (on the transport `scheme`) was of `version`.
pub(crate) fn note(&self, scheme: &'static str, sender: &str, version: u8) {
self.warn(
&super::Addressed(scheme, sender).to_string(),
version,
version,
);
}
/// A SPEAKS from `address` (as paths keep it) said its build speaks wire versions
/// `oldest` to `newest`: logged where this build speaks none of them, as a message of
/// another version is. The proofs between the two still go (`PROOFS`), nothing else.
pub(crate) fn speaks(&self, address: &str, oldest: u8, newest: u8) {
if choose(oldest, newest).is_none() {
self.warn(address, oldest, newest);
}
}
fn warn(&self, from: &str, oldest: u8, newest: u8) {
let mut known = self
.0
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if known.len() >= MAX_OTHER_VERSIONS {
known.clear();
}
if known.insert(from.to_owned()) {
tracing::warn!(
from = %from,
version = newest,
oldest = OLDEST,
newest = VERSION,
"Peer speaks another wire version: {}; ignoring its messages",
other_build(oldest, newest)
);
}
}
}
/// Of a peer speaking wire versions `oldest` to `newest`, none of which this build
/// speaks, what an operator does: upgrade this node where the peer's build is newer, the
/// peer's where it is older.
fn other_build(oldest: u8, newest: u8) -> String {
let versions = |oldest: u8, newest: u8| {
if oldest == newest {
format!("{oldest}")
} else {
format!("{oldest} to {newest}")
}
};
let (theirs, ours) = (versions(oldest, newest), versions(OLDEST, VERSION));
let plural = if oldest == newest { "" } else { "s" };
if oldest > VERSION {
format!(
"a newer build (wire version{plural} {theirs}; this one speaks {ours}): upgrade this \
node to talk with it"
)
} else {
format!(
"an older build (wire version{plural} {theirs}; this one speaks {ours}): upgrade that \
node"
)
}
}
pub(crate) fn decode(payload: &[u8]) -> Result<ParsedMessage, WireError> {
let (&version, payload) = payload.split_first().ok_or(WireError::Empty)?;
if version == SPEAKS {
let [oldest, newest, rest @ ..] = payload else {
return Err(WireError::Empty);
};
return Ok(ParsedMessage::Speaks(super::Speaks {
oldest: *oldest,
newest: *newest,
revision: rest.get(..32).map(|id| id.try_into().expect("32 bytes")),
}));
}
let (&kind, body) = payload.split_first().ok_or(WireError::Empty)?;
let is = |wanted: MessageKind| kind == tag(wanted);
let proof = version >= PROOFS && (is(MessageKind::Who) || is(MessageKind::Me));
// Each version this build speaks is decoded here: from `KINDS` on, the messages
// carrying what is a document's kind's as that version lays them out (`kinds`).
if !(OLDEST..=VERSION).contains(&version) && !proof {
return Err(WireError::Version(version));
}
if (KINDS..=VERSION).contains(&version) {
if is(MessageKind::Hello) {
return kinds::hello(body);
} else if is(MessageKind::HelloReply) {
return kinds::hello_reply(body);
} else if is(MessageKind::Sync) {
return kinds::sync(body);
} else if is(MessageKind::Status) {
return Ok(ParsedMessage::Status(kinds::status(body)?));
} else if is(MessageKind::StatusReply) {
return Ok(ParsedMessage::StatusReply(kinds::status(body)?));
} else if is(MessageKind::Blob) {
return kinds::blob(body);
}
}
Ok(if is(MessageKind::Hello) {
ParsedMessage::Hello(rmp_serde::from_slice(body)?)
} else if is(MessageKind::HelloReply) {
ParsedMessage::HelloReply(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Sync) {
ParsedMessage::Sync(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Status) {
ParsedMessage::Status(rmp_serde::from_slice(body)?)
} else if is(MessageKind::StatusReply) {
ParsedMessage::StatusReply(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Blob) {
ParsedMessage::Blob(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Who) {
ParsedMessage::Who(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Me) {
ParsedMessage::Me(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Ping) {
ParsedMessage::Ping(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Pong) {
let (nonce, at) = rmp_serde::from_slice(body)?;
ParsedMessage::Pong { nonce, at }
} else if is(MessageKind::Probe) {
ParsedMessage::Probe(rmp_serde::from_slice(body)?)
} else if is(MessageKind::ProbeReply) {
ParsedMessage::ProbeReply(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Prune) {
ParsedMessage::Prune(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Graft) {
ParsedMessage::Graft(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Neighbour) {
ParsedMessage::Neighbour(rmp_serde::from_slice(body)?)
} else if is(MessageKind::NeighbourReply) {
ParsedMessage::NeighbourReply(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Disconnect) {
ParsedMessage::Disconnect(rmp_serde::from_slice(body)?)
} else if is(MessageKind::Refusals) {
ParsedMessage::Refusals(rmp_serde::from_slice(body)?)
} else {
return Err(WireError::UnknownKind(kind));
})
}
/// Field codecs (`#[serde(with = "...")]`) for the message types.
pub(crate) mod codec {
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_bytes::{ByteBuf, Bytes};
/// Exactly `N` bytes, or a decoding error naming `what`.
fn fixed<const N: usize, E: serde::de::Error>(bytes: &[u8], what: &str) -> Result<[u8; N], E> {
bytes
.try_into()
.map_err(|_| E::custom(format!("{what} must be {N} bytes")))
}
/// A run ID (`RunId`).
pub(crate) mod run_id {
use super::*;
pub(crate) fn serialize<S: Serializer>(value: &[u8; 16], s: S) -> Result<S::Ok, S::Error> {
Bytes::new(value).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 16], D::Error> {
fixed(&ByteBuf::deserialize(d)?, "a run id")
}
}
/// A 32-byte hash.
pub(crate) mod bytes32 {
use super::*;
pub(crate) fn serialize<S: Serializer>(value: &[u8; 32], s: S) -> Result<S::Ok, S::Error> {
Bytes::new(value).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 32], D::Error> {
fixed(&ByteBuf::deserialize(d)?, "a hash")
}
}
/// 8 bytes (`EpochTag::prefix`).
pub(crate) mod bytes8 {
use super::*;
pub(crate) fn serialize<S: Serializer>(value: &[u8; 8], s: S) -> Result<S::Ok, S::Error> {
Bytes::new(value).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 8], D::Error> {
fixed(&ByteBuf::deserialize(d)?, "an epoch tag")
}
}
/// A 64-byte signature.
pub(crate) mod bytes64 {
use super::*;
pub(crate) fn serialize<S: Serializer>(value: &[u8; 64], s: S) -> Result<S::Ok, S::Error> {
Bytes::new(value).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 64], D::Error> {
fixed(&ByteBuf::deserialize(d)?, "a signature")
}
}
/// 32-byte hashes.
pub(crate) mod hashes32 {
use super::*;
pub(crate) fn serialize<S: Serializer>(
value: &[[u8; 32]],
s: S,
) -> Result<S::Ok, S::Error> {
s.collect_seq(value.iter().map(|hash| Bytes::new(hash)))
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
d: D,
) -> Result<Vec<[u8; 32]>, D::Error> {
Vec::<ByteBuf>::deserialize(d)?
.iter()
.map(|hash| fixed(hash, "a hash"))
.collect()
}
}
/// An Automerge change hash.
pub(crate) mod change_hash {
use super::*;
use crate::document::ChangeHash;
pub(crate) fn serialize<S: Serializer>(
value: &ChangeHash,
s: S,
) -> Result<S::Ok, S::Error> {
Bytes::new(&value.0).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<ChangeHash, D::Error> {
Ok(ChangeHash(fixed(
&ByteBuf::deserialize(d)?,
"a change hash",
)?))
}
}
/// An epoch: generation and ID.
pub(crate) mod epoch {
use super::*;
use crate::document::replica::Epoch;
pub(crate) fn serialize<S: Serializer>(value: &Epoch, s: S) -> Result<S::Ok, S::Error> {
(value.generation, Bytes::new(&value.id)).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Epoch, D::Error> {
let (generation, id): (u64, ByteBuf) = Deserialize::deserialize(d)?;
Ok(Epoch {
generation,
id: fixed(&id, "an epoch id")?,
})
}
}
/// Heads as a keepalive carries them: listed (at most `MAX_LISTED_HEADS`, digest
/// empty), or as a digest (none listed).
pub(crate) mod heads {
use super::*;
use crate::document::ChangeHash;
use crate::transport::{HeadsSummary, MAX_LISTED_HEADS};
pub(crate) fn serialize<S: Serializer>(
value: &HeadsSummary,
s: S,
) -> Result<S::Ok, S::Error> {
let (listed, digest): (Vec<&Bytes>, &Bytes) = match value {
HeadsSummary::Heads(heads) => (
heads.iter().map(|head| Bytes::new(&head.0)).collect(),
Bytes::new(&[]),
),
HeadsSummary::Digest { digest, sample } => (
sample.iter().map(|head| Bytes::new(&head.0)).collect(),
Bytes::new(digest),
),
};
(listed, digest).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
d: D,
) -> Result<HeadsSummary, D::Error> {
let (listed, digest): (Vec<ByteBuf>, ByteBuf) = Deserialize::deserialize(d)?;
if listed.len() > MAX_LISTED_HEADS {
return Err(D::Error::custom(format!(
"more than {MAX_LISTED_HEADS} heads listed"
)));
}
let listed = listed
.iter()
.map(|head| -> Result<ChangeHash, D::Error> {
Ok(ChangeHash(fixed(head, "a head")?))
})
.collect::<Result<Vec<_>, _>>()?;
if digest.is_empty() {
return Ok(HeadsSummary::Heads(listed));
}
Ok(HeadsSummary::Digest {
digest: fixed(&digest, "a heads digest")?,
sample: listed,
})
}
}
/// Change hashes, each a 32-byte binary.
pub(crate) mod change_hashes {
use super::*;
use crate::document::ChangeHash;
pub(crate) fn serialize<S: Serializer>(
value: &[ChangeHash],
s: S,
) -> Result<S::Ok, S::Error> {
s.collect_seq(value.iter().map(|hash| Bytes::new(&hash.0)))
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
d: D,
) -> Result<Vec<ChangeHash>, D::Error> {
Vec::<ByteBuf>::deserialize(d)?
.iter()
.map(|hash| Ok(ChangeHash(fixed(hash, "a change hash")?)))
.collect()
}
}
/// An Automerge sync message, in Automerge's own encoding (left encoded:
/// `SyncPayload`).
pub(crate) mod sync_message {
use super::*;
use crate::transport::SyncPayload;
pub(crate) fn serialize<S: Serializer>(
value: &SyncPayload,
s: S,
) -> Result<S::Ok, S::Error> {
Bytes::new(&value.0).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
d: D,
) -> Result<SyncPayload, D::Error> {
Ok(SyncPayload(ByteBuf::deserialize(d)?.into_vec().into()))
}
}
/// Shared bytes (`bytes::Bytes`).
pub(crate) mod shared_bytes {
use super::*;
pub(crate) fn serialize<S: Serializer>(
value: &bytes::Bytes,
s: S,
) -> Result<S::Ok, S::Error> {
Bytes::new(value).serialize(s)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
d: D,
) -> Result<bytes::Bytes, D::Error> {
Ok(ByteBuf::deserialize(d)?.into_vec().into())
}
}
}
/// One message of every kind, for the codecs' tests (this one's, and each transport's
/// envelope around it).
#[cfg(test)]
pub(crate) fn samples() -> Vec<ParsedMessage> {
use crate::document::ChangeHash;
use crate::document::replica::Epoch;
use crate::transport::{
BlobBody, BlobId, BlobMessage, DeltaSpec, HeadsSummary, HelloReply, HelloRequest,
IdentityProof, ListedPeer, Status, SyncBody, SyncEnvelope,
};
let epoch = Epoch {
generation: 2,
id: [3; 32],
};
let status = Status {
heads: HeadsSummary::of(vec![ChangeHash([1; 32])]),
epoch,
epoch_seq: 1,
ready: true,
syncs_with_you: true,
leaving: false,
announcing: false,
reaches: None,
round_trips: None,
};
let proof = IdentityProof {
key: [8; 32],
signature: [9; 64],
};
vec![
ParsedMessage::Hello(HelloRequest {
swarm_id: Some("swarm".into()),
epoch,
epoch_seq: 1,
auth: vec![1, 2, 3],
ready: true,
run_id: [4; 16],
handshake: 7,
root: None,
party: None,
kind: crate::document::KIND.to_owned(),
}),
ParsedMessage::HelloReply(HelloReply {
swarm_id: "swarm".into(),
peers: vec![ListedPeer {
id: "p".into(),
addresses: vec!["a".into()],
}],
epoch,
epoch_seq: 1,
auth: Vec::new(),
ready: false,
run_id: [4; 16],
away_ms: Some(5),
sender_run_id: [6; 16],
root: None,
party: None,
kind: crate::document::KIND.to_owned(),
}),
ParsedMessage::Sync(SyncEnvelope {
epoch: crate::transport::EpochTag::of(epoch),
epoch_seq: 1,
body: SyncBody::Delta(DeltaSpec {
from: Vec::new(),
to: vec![ChangeHash([2; 32])],
signatures: Some(crate::transport::DeltaSignatures {
hash: [3; 32],
size: 96,
}),
}),
ready: true,
writer: Some(7),
delivered: true,
sent: crate::clock::UnixMillis(8),
signatures: serde_bytes::ByteBuf::from(vec![9; 96]),
}),
ParsedMessage::Status(status.clone()),
ParsedMessage::StatusReply(status),
ParsedMessage::Blob(BlobMessage {
epoch,
epoch_seq: 1,
id: BlobId::Content([5; 32]),
body: BlobBody::Missing,
sent: crate::clock::UnixMillis(9),
}),
ParsedMessage::Who(proof.clone()),
ParsedMessage::Me(proof),
ParsedMessage::Ping(7),
ParsedMessage::Pong {
nonce: u64::MAX,
at: crate::clock::UnixMillis(5),
},
ParsedMessage::Probe(crate::transport::ProbeRequest {
epoch,
epoch_seq: 1,
nonce: 4,
member: "q".into(),
}),
ParsedMessage::ProbeReply(crate::transport::ProbeReply {
epoch,
epoch_seq: 1,
nonce: 4,
member: "q".into(),
reached: None,
}),
ParsedMessage::Prune(crate::transport::TreeLink {
epoch,
epoch_seq: 1,
writer: 5,
}),
ParsedMessage::Graft(crate::transport::TreeLink {
epoch,
epoch_seq: 1,
writer: 5,
}),
ParsedMessage::Neighbour(crate::transport::NeighbourRequest {
epoch,
epoch_seq: 1,
high: true,
one_short: false,
}),
ParsedMessage::NeighbourReply(crate::transport::NeighbourAnswer {
epoch,
epoch_seq: 1,
agreed: true,
}),
ParsedMessage::Disconnect(crate::transport::NeighbourAnswer {
epoch,
epoch_seq: 1,
agreed: false,
}),
ParsedMessage::Refusals(crate::transport::RefusalsMessage {
epoch,
epoch_seq: 1,
changes: vec![crate::document::ChangeHash([7; 32])],
}),
]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::ChangeHash;
use crate::document::replica::Epoch;
use crate::transport::{
BlobBody, BlobId, BlobMessage, HeadsSummary, HelloReply, HelloRequest, IdentityProof,
ListedPeer, MAX_LISTED_HEADS, Status,
};
/// Each sender on another wire version is remembered once, and no more than
/// `MAX_OTHER_VERSIONS` of them.
#[test]
fn other_versions_are_noted_once_each() {
let other = OtherVersions::default();
other.note("s", "a", VERSION + 1);
other.note("s", "a", VERSION + 1);
assert_eq!(other.0.lock().unwrap().len(), 1);
for i in 0..MAX_OTHER_VERSIONS + 1 {
other.note("s", &i.to_string(), VERSION + 1);
}
assert!(other.0.lock().unwrap().len() <= MAX_OTHER_VERSIONS);
}
/// A peer is written to in the newest version both speak, a version this build doesn't
/// speak never; in the newest one alone, while that is all it speaks.
#[test]
fn the_newest_version_both_speak_is_written() {
assert_eq!(choose(OLDEST, VERSION), Some(VERSION));
assert_eq!(choose(1, VERSION + 5), Some(VERSION));
assert_eq!(choose(OLDEST - 2, OLDEST - 1), None);
assert_eq!(choose(VERSION + 1, VERSION + 2), None);
let ping = ParsedMessage::Ping(7);
assert_eq!(encode_in(&ping, VERSION).unwrap(), encode(&ping).unwrap());
assert!(encode_in(&ping, VERSION + 1).is_err());
assert!(encoded_in("p", &ping, VERSION).is_ok());
}
/// WHO and ME are laid out alike in every version, as in the first with SPEAKS, and
/// read in any version from it on, older or newer than this build's: two builds prove
/// themselves to each other before either knows what the other speaks. These bytes
/// never change.
#[test]
fn proofs_are_read_in_every_version() {
let proof = IdentityProof {
key: [8; 32],
signature: [9; 64],
};
let who = ParsedMessage::Who(proof.clone());
let fields = format!("92c420{}c440{}", "08".repeat(32), "09".repeat(64));
assert_eq!(
hex(&encode_in(&who, PROOFS).unwrap()),
format!("3406{fields}")
);
let me = ParsedMessage::Me(proof);
assert_eq!(
hex(&encode_in(&me, PROOFS).unwrap()),
format!("3407{fields}")
);
for version in [PROOFS, OLDEST, VERSION, VERSION + 1, u8::MAX] {
let who = encode_in(&who, version).unwrap();
assert_eq!(who[0], version);
assert!(
matches!(decode(&who), Ok(ParsedMessage::Who(_))),
"{version}"
);
let me = encode_in(&me, version).unwrap();
assert!(matches!(decode(&me), Ok(ParsedMessage::Me(_))), "{version}");
}
let mut before = encode(&who).unwrap();
before[0] = PROOFS - 1;
assert!(matches!(decode(&before), Err(WireError::Version(_))));
let mut ping = encode(&ParsedMessage::Ping(7)).unwrap();
ping[0] = VERSION + 1;
assert!(matches!(decode(&ping), Err(WireError::Version(_))));
}
/// The warning says which build is the older, the one to upgrade, and both versions.
#[test]
fn the_older_build_is_named() {
let newer = other_build(VERSION + 1, VERSION + 1);
assert!(newer.contains("upgrade this node"), "{newer}");
assert!(
newer.contains(&format!("wire version {}", VERSION + 1)),
"{newer}"
);
assert!(
newer.contains(&format!("speaks {OLDEST} to {VERSION}")),
"{newer}"
);
let older = other_build(OLDEST - 1, OLDEST - 1);
assert!(older.contains("upgrade that node"), "{older}");
let newer = other_build(VERSION + 1, VERSION + 3);
assert!(
newer.contains(&format!("wire versions {} to {}", VERSION + 1, VERSION + 3)),
"{newer}"
);
}
/// Every kind decodes to what was encoded, in every version this build speaks:
/// re-encoded, the same bytes. And what one version carries, another carries too:
/// read from either, a message is written alike.
#[test]
fn every_kind_round_trips() {
let samples = samples();
assert_eq!(samples.len(), 18, "a kind is missing from `samples`");
for message in samples {
for version in OLDEST..=VERSION {
let bytes = encode_in(&message, version).unwrap();
let decoded = decode(&bytes).unwrap();
assert_eq!(decoded.kind(), message.kind());
assert_eq!(
encode_in(&decoded, version).unwrap(),
bytes,
"{version}: {message:?}"
);
for other in OLDEST..=VERSION {
assert_eq!(
encode_in(&decoded, other).unwrap(),
encode_in(&message, other).unwrap(),
"read in {version}, written in {other}: {message:?}"
);
}
}
}
}
/// A request for a blob of changes says which, in every version: as bytes from
/// `KINDS` on.
#[test]
fn a_blob_request_says_what_it_asks_for() {
let spec =
crate::transport::DeltaSpec::new(vec![ChangeHash([1; 32])], vec![ChangeHash([2; 32])]);
let request = ParsedMessage::Blob(BlobMessage {
epoch: Epoch::GENESIS,
epoch_seq: 0,
id: BlobId::Delta(spec.id()),
body: BlobBody::Request {
chunks: vec![0, 2],
delta: Some(spec.clone()),
},
sent: crate::clock::UnixMillis(2),
});
for version in OLDEST..=VERSION {
let decoded = decode(&encode_in(&request, version).unwrap()).unwrap();
let ParsedMessage::Blob(BlobMessage {
body: BlobBody::Request { chunks, delta },
..
}) = decoded
else {
panic!("not a request");
};
assert_eq!(chunks, [0, 2]);
let delta = delta.expect("its spec");
assert_eq!((delta.from, delta.to), (spec.from.clone(), spec.to.clone()));
}
}
/// A handshake says its document's kind from `KINDS` on; one in an older version
/// says none, and is read as of the kind there was then.
#[test]
fn a_handshake_says_its_kind() {
let hello = |kind: &str| {
ParsedMessage::Hello(HelloRequest {
swarm_id: None,
epoch: Epoch::GENESIS,
epoch_seq: 0,
auth: Vec::new(),
ready: true,
run_id: [4; 16],
handshake: 1,
root: None,
party: None,
kind: kind.to_owned(),
})
};
let read = |message: &ParsedMessage, version: u8| match decode(
&encode_in(message, version).unwrap(),
)
.unwrap()
{
ParsedMessage::Hello(hello) => hello.kind,
other => panic!("{other:?}"),
};
assert_eq!(read(&hello("another"), KINDS), "another");
assert_eq!(read(&hello("another"), KINDS - 1), crate::document::KIND);
assert_eq!(
read(&hello(crate::document::KIND), VERSION),
crate::document::KIND
);
}
#[test]
fn handshakes_round_trip() {
let epoch = Epoch {
generation: 2,
id: [3; 32],
};
let hello = ParsedMessage::Hello(HelloRequest {
swarm_id: Some("swarm".into()),
epoch,
epoch_seq: 1,
auth: vec![1, 2, 3],
ready: true,
run_id: [4; 16],
handshake: 7,
root: None,
party: Some("tv".into()),
kind: crate::document::KIND.to_owned(),
});
let ParsedMessage::Hello(decoded) = decode(&encode(&hello).unwrap()).unwrap() else {
panic!("not a HELLO");
};
assert_eq!(decoded.swarm_id.as_deref(), Some("swarm"));
assert_eq!((decoded.epoch, decoded.epoch_seq), (epoch, 1));
assert_eq!(decoded.auth, vec![1, 2, 3]);
assert_eq!(decoded.run_id, [4; 16]);
assert_eq!(decoded.party.as_deref(), Some("tv"));
assert_eq!(decoded.handshake, 7);
let reply = ParsedMessage::HelloReply(HelloReply {
swarm_id: "swarm".into(),
peers: vec![ListedPeer {
id: "p".into(),
addresses: vec!["a".into()],
}],
epoch,
epoch_seq: 1,
auth: Vec::new(),
ready: false,
run_id: [4; 16],
away_ms: Some(5),
sender_run_id: [6; 16],
root: None,
party: None,
kind: crate::document::KIND.to_owned(),
});
let ParsedMessage::HelloReply(decoded) = decode(&encode(&reply).unwrap()).unwrap() else {
panic!("not a HELLO_REPLY");
};
assert_eq!(
decoded.peers,
vec![ListedPeer {
id: "p".into(),
addresses: vec!["a".into()],
}]
);
assert_eq!(decoded.away_ms, Some(5));
assert_eq!(decoded.sender_run_id, [6; 16]);
}
#[test]
fn keepalives_keep_their_kind_and_heads() {
let status = Status {
heads: HeadsSummary::Digest {
digest: [8; 32],
sample: vec![ChangeHash([9; 32])],
},
epoch: Epoch::GENESIS,
epoch_seq: 0,
ready: true,
syncs_with_you: false,
leaving: false,
announcing: false,
reaches: None,
round_trips: None,
};
let decoded =
decode(&encode(&ParsedMessage::StatusReply(status.clone())).unwrap()).unwrap();
let ParsedMessage::StatusReply(decoded) = decoded else {
panic!("not a STATUS_REPLY");
};
assert_eq!(decoded.heads, status.heads);
assert_eq!(decoded.heads.listed(), [ChangeHash([9; 32])]);
}
#[test]
fn too_many_listed_heads_are_refused() {
let status = Status {
heads: HeadsSummary::Heads(
(0..=MAX_LISTED_HEADS as u8)
.map(|n| ChangeHash([n; 32]))
.collect(),
),
epoch: Epoch::GENESIS,
epoch_seq: 0,
ready: true,
syncs_with_you: true,
leaving: false,
announcing: false,
reaches: None,
round_trips: None,
};
assert!(decode(&encode(&ParsedMessage::Status(status)).unwrap()).is_err());
}
#[test]
fn unknown_kinds_and_bad_payloads_are_refused() {
assert!(matches!(decode(&[]), Err(WireError::Empty)));
assert!(matches!(decode(&[VERSION]), Err(WireError::Empty)));
assert!(matches!(
decode(&[VERSION, 99]),
Err(WireError::UnknownKind(99))
));
assert!(matches!(
decode(&[VERSION + 1, 0]),
Err(WireError::Version(version)) if version == VERSION + 1
));
let blob = ParsedMessage::Blob(BlobMessage {
epoch: Epoch::GENESIS,
epoch_seq: 0,
id: BlobId::Content([1; 32]),
body: BlobBody::Missing,
sent: crate::clock::UnixMillis(2),
});
let payload = encode(&blob).unwrap();
assert!(matches!(decode(&payload).unwrap(), ParsedMessage::Blob(_)));
// A payload cut short doesn't decode.
assert!(decode(&payload[..payload.len() - 1]).is_err());
// Nor one of another kind.
let mut relabelled = payload.clone();
relabelled[1] = tag(MessageKind::Hello);
assert!(decode(&relabelled).is_err());
}
fn hex(bytes: &[u8]) -> String {
crate::transport::Hex(bytes).to_string()
}
/// A SPEAKS is laid out as no build changes: its version byte, the oldest and newest
/// version, the revision's ID where there is one; what follows is left.
#[test]
fn speaks_keeps_its_layout() {
let speaks = super::super::Speaks {
oldest: 50,
newest: 52,
revision: Some([7; 32]),
};
let bytes = encode(&ParsedMessage::Speaks(speaks)).unwrap();
assert_eq!(hex(&bytes), format!("003234{}", "07".repeat(32)));
let without = super::super::Speaks {
revision: None,
..speaks
};
assert_eq!(
hex(&encode(&ParsedMessage::Speaks(without)).unwrap()),
"003234"
);
for (payload, read) in [
(bytes.clone(), speaks),
([bytes.as_slice(), b"later"].concat(), speaks),
(vec![0, 50, 52], without),
(vec![0, 50, 52, 1, 2], without),
] {
match decode(&payload) {
Ok(ParsedMessage::Speaks(decoded)) => assert_eq!(decoded, read),
other => panic!("{other:?}"),
}
}
assert!(decode(&[0, 50]).is_err());
}
/// The exact bytes of a few messages, in the version before what is a kind's went
/// as bytes: as builds speaking it alone read and write them.
#[test]
fn golden_bytes() {
// Of version 52, which this build still speaks: never to change.
let v = "34";
let epoch = Epoch {
generation: 2,
id: [3; 32],
};
let epoch_hex = format!("9202c420{}", "03".repeat(32));
let run = |byte: &str| format!("c410{}", byte.repeat(16));
let hello = ParsedMessage::Hello(HelloRequest {
swarm_id: Some("swarm".into()),
epoch,
epoch_seq: 1,
auth: vec![1, 2, 3],
ready: true,
run_id: [4; 16],
handshake: 7,
root: None,
party: None,
kind: crate::document::KIND.to_owned(),
});
assert_eq!(
hex(&encode_in(&hello, 52).unwrap()),
format!(
"{v}0099a5737761726d{epoch_hex}01c403010203c3{}07c0c0",
run("04")
)
);
let reply = ParsedMessage::HelloReply(HelloReply {
swarm_id: "swarm".into(),
peers: vec![ListedPeer {
id: "p".into(),
addresses: vec!["a".into()],
}],
epoch,
epoch_seq: 1,
auth: Vec::new(),
ready: false,
run_id: [4; 16],
away_ms: Some(5),
sender_run_id: [6; 16],
root: None,
party: None,
kind: crate::document::KIND.to_owned(),
});
assert_eq!(
hex(&encode_in(&reply, 52).unwrap()),
format!(
"{v}019ba5737761726d9192a17091a161{epoch_hex}01c400c2{}05{}c0c0",
run("04"),
run("06")
)
);
let status = ParsedMessage::Status(Status {
heads: HeadsSummary::Heads(Vec::new()),
epoch,
epoch_seq: 1,
ready: true,
syncs_with_you: false,
leaving: false,
announcing: true,
reaches: None,
round_trips: None,
});
assert_eq!(
hex(&encode_in(&status, 52).unwrap()),
format!("{v}03999290c400{epoch_hex}01c3c2c2c3c0c0")
);
let who = ParsedMessage::Who(IdentityProof {
key: [8; 32],
signature: [9; 64],
});
assert_eq!(
hex(&encode_in(&who, 52).unwrap()),
format!("{v}0692c420{}c440{}", "08".repeat(32), "09".repeat(64))
);
let ParsedMessage::Me(proof) = decode(
&encode(&ParsedMessage::Me(IdentityProof {
key: [8; 32],
signature: [9; 64],
}))
.unwrap(),
)
.unwrap() else {
panic!("not a ME");
};
assert_eq!((proof.key, proof.signature), ([8; 32], [9; 64]));
assert_eq!(
hex(&encode_in(&ParsedMessage::Ping(7), 52).unwrap()),
format!("{v}0807")
);
let pong = ParsedMessage::Pong {
nonce: u64::MAX,
at: crate::clock::UnixMillis(5),
};
assert_eq!(
hex(&encode_in(&pong, 52).unwrap()),
format!("{v}0992cfffffffffffffffff05")
);
let ParsedMessage::Pong { nonce, at } = decode(&[VERSION, 9, 0x92, 0x2a, 0x07]).unwrap()
else {
panic!("not a PONG");
};
assert_eq!((nonce, at.as_u64()), (42, 7));
}
/// The exact bytes of the messages that carry what is a document's kind's, from
/// `KINDS` on (`kinds`). If this fails after a change to a message type or a codec,
/// the change is a new wire format: bump `VERSION` and take the new bytes.
#[test]
fn golden_bytes_of_kinds() {
let epoch = Epoch {
generation: 2,
id: [3; 32],
};
let epoch_hex = format!("9202c420{}", "03".repeat(32));
let run = |byte: &str| format!("c410{}", byte.repeat(16));
let written = |message: &ParsedMessage| hex(&encode_in(message, KINDS).unwrap());
let hello = ParsedMessage::Hello(HelloRequest {
swarm_id: Some("swarm".into()),
epoch,
epoch_seq: 1,
auth: vec![1, 2, 3],
ready: true,
run_id: [4; 16],
handshake: 7,
root: None,
party: None,
kind: crate::document::KIND.to_owned(),
});
// The message as before, then the kind.
assert_eq!(
written(&hello),
format!(
"35009299a5737761726d{epoch_hex}01c403010203c3{}07c0c0a96175746f6d65726765",
run("04")
)
);
let status = ParsedMessage::Status(Status {
heads: HeadsSummary::Heads(vec![ChangeHash([1; 32])]),
epoch,
epoch_seq: 1,
ready: true,
syncs_with_you: false,
leaving: false,
announcing: true,
reaches: None,
round_trips: None,
});
// Where it stands as bytes: the heads listed, no digest.
assert_eq!(
written(&status),
format!(
"350399c4269291c420{}c400{epoch_hex}01c3c2c2c3c0c0",
"01".repeat(32)
)
);
let sync = ParsedMessage::Sync(crate::transport::SyncEnvelope {
epoch: crate::transport::EpochTag::of(epoch),
epoch_seq: 1,
body: crate::transport::SyncBody::Changes {
heads: vec![ChangeHash([2; 32])],
changes: vec![serde_bytes::ByteBuf::from(vec![5, 6])],
},
ready: true,
writer: Some(7),
delivered: true,
sent: crate::clock::UnixMillis(8),
signatures: serde_bytes::ByteBuf::from(vec![9; 3]),
});
assert_eq!(
written(&sync),
"3502979202c408030303030303030301c4349281a74368616e6765739291c420020202020202020202020202020202020202020202020202020202020202020291c4020506c3c30708c403090909"
);
assert_eq!(
hex(&encode_in(&sync, 52).unwrap()),
"3402989202c40803030303030303030181a74368616e6765739291c420020202020202020202020202020202020202020202020202020202020202020291c4020506c307c308c403090909"
);
let spec = crate::transport::DeltaSpec::new(Vec::new(), vec![ChangeHash([2; 32])]);
let request = ParsedMessage::Blob(BlobMessage {
epoch,
epoch_seq: 1,
id: BlobId::Delta([5; 32]),
body: BlobBody::Request {
chunks: vec![0],
delta: Some(spec),
},
sent: crate::clock::UnixMillis(9),
});
assert_eq!(
written(&request),
"3505959202c42003030303030303030303030303030303030303030303030303030303030303030181a442756c6bc420050505050505050505050505050505050505050505050505050505050505050581a752657175657374929100c426939091c4200202020202020202020202020202020202020202020202020202020202020202c009"
);
assert_eq!(
hex(&encode_in(&request, 52).unwrap()),
"3405959202c42003030303030303030303030303030303030303030303030303030303030303030181a544656c7461c420050505050505050505050505050505050505050505050505050505050505050581a752657175657374929100939091c4200202020202020202020202020202020202020202020202020202020202020202c009"
);
}
}
|