/
ser_macros.rs
1534 lines (1433 loc) · 58.1 KB
/
ser_macros.rs
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
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Some macros that implement [`Readable`]/[`Writeable`] traits for lightning messages.
//! They also handle serialization and deserialization of TLVs.
//!
//! [`Readable`]: crate::util::ser::Readable
//! [`Writeable`]: crate::util::ser::Writeable
// There are quite a few TLV serialization "types" which behave differently. We currently only
// publicly document the `optional` and `required` types, not supporting anything else publicly and
// changing them at will.
//
// Some of the other types include:
// * (default_value, $default) - reads optionally, reading $default if no TLV is present
// * (static_value, $value) - ignores any TLVs, always using $value
// * required_vec - reads into a Vec without a length prefix, failing if no TLV is present.
// * optional_vec - reads into an Option<Vec> without a length prefix, continuing if no TLV is
// present. Writes from a Vec directly, only if any elements are present. Note
// that the struct deserialization macros return a Vec, not an Option.
// * upgradable_option - reads via MaybeReadable.
// * upgradable_required - reads via MaybeReadable, requiring a TLV be present but may return None
// if MaybeReadable::read() returns None.
/// Implements serialization for a single TLV record.
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _encode_tlv {
($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
$crate::_encode_tlv!($stream, $type, $field, required)
};
($stream: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
let _ = &$field; // Ensure we "use" the $field
};
($stream: expr, $type: expr, $field: expr, required) => {
BigSize($type).write($stream)?;
BigSize($field.serialized_length() as u64).write($stream)?;
$field.write($stream)?;
};
($stream: expr, $type: expr, $field: expr, required_vec) => {
$crate::_encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
};
($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
if let Some(ref field) = $optional_field {
BigSize($optional_type).write($stream)?;
BigSize(field.serialized_length() as u64).write($stream)?;
field.write($stream)?;
}
};
($stream: expr, $type: expr, $field: expr, optional_vec) => {
if !$field.is_empty() {
$crate::_encode_tlv!($stream, $type, $field, required_vec);
}
};
($stream: expr, $type: expr, $field: expr, upgradable_required) => {
$crate::_encode_tlv!($stream, $type, $field, required);
};
($stream: expr, $type: expr, $field: expr, upgradable_option) => {
$crate::_encode_tlv!($stream, $type, $field, option);
};
($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
$crate::_encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
};
($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
$crate::_encode_tlv!($stream, $type, $field, option);
};
($stream: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
// Just a read-mapped type
$crate::_encode_tlv!($stream, $type, $field, option);
};
}
/// Panics if the last seen TLV type is not numerically less than the TLV type currently being checked.
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _check_encoded_tlv_order {
($last_type: expr, $type: expr, (static_value, $value: expr)) => { };
($last_type: expr, $type: expr, $fieldty: tt) => {
if let Some(t) = $last_type {
#[allow(unused_comparisons)] // Note that $type may be 0 making the following comparison always false
(debug_assert!(t < $type))
}
$last_type = Some($type);
};
}
/// Implements the TLVs serialization part in a [`Writeable`] implementation of a struct.
///
/// This should be called inside a method which returns `Result<_, `[`io::Error`]`>`, such as
/// [`Writeable::write`]. It will only return an `Err` if the stream `Err`s or [`Writeable::write`]
/// on one of the fields `Err`s.
///
/// `$stream` must be a `&mut `[`Writer`] which will receive the bytes for each TLV in the stream.
///
/// Fields MUST be sorted in `$type`-order.
///
/// Note that the lightning TLV requirements require that a single type not appear more than once,
/// that TLVs are sorted in type-ascending order, and that any even types be understood by the
/// decoder.
///
/// Any `option` fields which have a value of `None` will not be serialized at all.
///
/// For example,
/// ```
/// # use lightning::encode_tlv_stream;
/// # fn write<W: lightning::util::ser::Writer> (stream: &mut W) -> Result<(), lightning::io::Error> {
/// let mut required_value = 0u64;
/// let mut optional_value: Option<u64> = None;
/// encode_tlv_stream!(stream, {
/// (0, required_value, required),
/// (1, Some(42u64), option),
/// (2, optional_value, option),
/// });
/// // At this point `required_value` has been written as a TLV of type 0, `42u64` has been written
/// // as a TLV of type 1 (indicating the reader may ignore it if it is not understood), and *no*
/// // TLV is written with type 2.
/// # Ok(())
/// # }
/// ```
///
/// [`Writeable`]: crate::util::ser::Writeable
/// [`io::Error`]: crate::io::Error
/// [`Writeable::write`]: crate::util::ser::Writeable::write
/// [`Writer`]: crate::util::ser::Writer
#[macro_export]
macro_rules! encode_tlv_stream {
($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
$crate::_encode_tlv_stream!($stream, {$(($type, $field, $fieldty)),*})
}
}
/// Implementation of [`encode_tlv_stream`].
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _encode_tlv_stream {
($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
$crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, &[])
} };
($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}, $extra_tlvs: expr) => { {
#[allow(unused_imports)]
use $crate::{
ln::msgs::DecodeError,
util::ser,
util::ser::BigSize,
util::ser::Writeable,
};
$(
$crate::_encode_tlv!($stream, $type, $field, $fieldty);
)*
for tlv in $extra_tlvs {
let (typ, value): &(u64, Vec<u8>) = tlv;
$crate::_encode_tlv!($stream, *typ, *value, required_vec);
}
#[allow(unused_mut, unused_variables, unused_assignments)]
#[cfg(debug_assertions)]
{
let mut last_seen: Option<u64> = None;
$(
$crate::_check_encoded_tlv_order!(last_seen, $type, $fieldty);
)*
for tlv in $extra_tlvs {
let (typ, _): &(u64, Vec<u8>) = tlv;
$crate::_check_encoded_tlv_order!(last_seen, *typ, required_vec);
}
}
} };
}
/// Adds the length of the serialized field to a [`LengthCalculatingWriter`].
/// This is exported for use by other exported macros, do not use directly.
///
/// [`LengthCalculatingWriter`]: crate::util::ser::LengthCalculatingWriter
#[doc(hidden)]
#[macro_export]
macro_rules! _get_varint_length_prefixed_tlv_length {
($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
};
($len: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
};
($len: expr, $type: expr, $field: expr, required) => {
BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
let field_len = $field.serialized_length();
BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
$len.0 += field_len;
};
($len: expr, $type: expr, $field: expr, required_vec) => {
$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
};
($len: expr, $optional_type: expr, $optional_field: expr, option) => {
if let Some(ref field) = $optional_field {
BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
let field_len = field.serialized_length();
BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
$len.0 += field_len;
}
};
($len: expr, $type: expr, $field: expr, optional_vec) => {
if !$field.is_empty() {
$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required_vec);
}
};
($len: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
};
($len: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field.map(|f| $encoding(f)), option);
};
($len: expr, $type: expr, $field: expr, upgradable_required) => {
$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required);
};
($len: expr, $type: expr, $field: expr, upgradable_option) => {
$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
};
}
/// See the documentation of [`write_tlv_fields`].
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _encode_varint_length_prefixed_tlv {
($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
$crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*}, &[])
} };
($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}, $extra_tlvs: expr) => { {
extern crate alloc;
use $crate::util::ser::BigSize;
use alloc::vec::Vec;
let len = {
#[allow(unused_mut)]
let mut len = $crate::util::ser::LengthCalculatingWriter(0);
$(
$crate::_get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
)*
for tlv in $extra_tlvs {
let (typ, value): &(u64, Vec<u8>) = tlv;
$crate::_get_varint_length_prefixed_tlv_length!(len, *typ, *value, required_vec);
}
len.0
};
BigSize(len as u64).write($stream)?;
$crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, $extra_tlvs);
} };
}
/// Errors if there are missing required TLV types between the last seen type and the type currently being processed.
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _check_decoded_tlv_order {
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
#[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
if invalid_order {
$field = $default.into();
}
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (static_value, $value: expr)) => {
};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
#[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
if invalid_order {
return Err(DecodeError::InvalidValue);
}
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
$crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
// no-op
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required_vec) => {{
$crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, optional_vec) => {{
// no-op
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{
_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required)
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_option) => {{
// no-op
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
// no-op
}};
($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
// no-op
}};
}
/// Errors if there are missing required TLV types after the last seen type.
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _check_missing_tlv {
($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
#[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
if missing_req_type {
$field = $default.into();
}
}};
($last_seen_type: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
$field = $value;
};
($last_seen_type: expr, $type: expr, $field: ident, required) => {{
#[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
if missing_req_type {
return Err(DecodeError::InvalidValue);
}
}};
($last_seen_type: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
$crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
}};
($last_seen_type: expr, $type: expr, $field: ident, required_vec) => {{
$crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
}};
($last_seen_type: expr, $type: expr, $field: ident, option) => {{
// no-op
}};
($last_seen_type: expr, $type: expr, $field: ident, optional_vec) => {{
// no-op
}};
($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{
_check_missing_tlv!($last_seen_type, $type, $field, required)
}};
($last_seen_type: expr, $type: expr, $field: ident, upgradable_option) => {{
// no-op
}};
($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
// no-op
}};
($last_seen_type: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
// no-op
}};
}
/// Implements deserialization for a single TLV record.
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _decode_tlv {
($outer_reader: expr, $reader: expr, $field: ident, (default_value, $default: expr)) => {{
$crate::_decode_tlv!($outer_reader, $reader, $field, required)
}};
($outer_reader: expr, $reader: expr, $field: ident, (static_value, $value: expr)) => {{
}};
($outer_reader: expr, $reader: expr, $field: ident, required) => {{
$field = $crate::util::ser::Readable::read(&mut $reader)?;
}};
($outer_reader: expr, $reader: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
$field = $trait::read(&mut $reader $(, $read_arg)*)?;
}};
($outer_reader: expr, $reader: expr, $field: ident, required_vec) => {{
let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
$field = f.0;
}};
($outer_reader: expr, $reader: expr, $field: ident, option) => {{
$field = Some($crate::util::ser::Readable::read(&mut $reader)?);
}};
($outer_reader: expr, $reader: expr, $field: ident, optional_vec) => {{
let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
$field = Some(f.0);
}};
// `upgradable_required` indicates we're reading a required TLV that may have been upgraded
// without backwards compat. We'll error if the field is missing, and return `Ok(None)` if the
// field is present but we can no longer understand it.
// Note that this variant can only be used within a `MaybeReadable` read.
($outer_reader: expr, $reader: expr, $field: ident, upgradable_required) => {{
$field = match $crate::util::ser::MaybeReadable::read(&mut $reader)? {
Some(res) => res,
None => {
// If we successfully read a value but we don't know how to parse it, we give up
// and immediately return `None`. However, we need to make sure we read the correct
// number of bytes for this TLV stream, which is implicitly the end of the stream.
// Thus, we consume everything left in the `$outer_reader` here, ensuring that if
// we're being read as a part of another TLV stream we don't spuriously fail to
// deserialize the outer object due to a TLV length mismatch.
$crate::io_extras::copy($outer_reader, &mut $crate::io_extras::sink()).unwrap();
return Ok(None)
},
};
}};
// `upgradable_option` indicates we're reading an Option-al TLV that may have been upgraded
// without backwards compat. $field will be None if the TLV is missing or if the field is present
// but we can no longer understand it.
($outer_reader: expr, $reader: expr, $field: ident, upgradable_option) => {{
$field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
if $field.is_none() {
#[cfg(not(debug_assertions))] {
// In general, MaybeReadable implementations are required to consume all the bytes
// of the object even if they don't understand it, but due to a bug in the
// serialization format for `impl_writeable_tlv_based_enum_upgradable` we sometimes
// don't know how many bytes that is. In such cases, we'd like to spuriously allow
// TLV length mismatches, which we do here by calling `eat_remaining` so that the
// `s.bytes_remain()` check in `_decode_tlv_stream_range` doesn't fail.
$reader.eat_remaining()?;
}
}
}};
($outer_reader: expr, $reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
$field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
}};
($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident, $encoder:ty))) => {{
$crate::_decode_tlv!($outer_reader, $reader, $field, (option, encoding: ($fieldty, $encoding)));
}};
($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
$field = {
let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
Some(field.0)
};
}};
($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
$crate::_decode_tlv!($outer_reader, $reader, $field, option);
}};
}
/// Checks if `$val` matches `$type`.
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _decode_tlv_stream_match_check {
($val: ident, $type: expr, (static_value, $value: expr)) => { false };
($val: ident, $type: expr, $fieldty: tt) => { $val == $type }
}
/// Implements the TLVs deserialization part in a [`Readable`] implementation of a struct.
///
/// This should be called inside a method which returns `Result<_, `[`DecodeError`]`>`, such as
/// [`Readable::read`]. It will either return an `Err` or ensure all `required` fields have been
/// read and optionally read `optional` fields.
///
/// `$stream` must be a [`Read`] and will be fully consumed, reading until no more bytes remain
/// (i.e. it returns [`DecodeError::ShortRead`]).
///
/// Fields MUST be sorted in `$type`-order.
///
/// Note that the lightning TLV requirements require that a single type not appear more than once,
/// that TLVs are sorted in type-ascending order, and that any even types be understood by the
/// decoder.
///
/// For example,
/// ```
/// # use lightning::decode_tlv_stream;
/// # fn read<R: lightning::io::Read> (stream: R) -> Result<(), lightning::ln::msgs::DecodeError> {
/// let mut required_value = 0u64;
/// let mut optional_value: Option<u64> = None;
/// decode_tlv_stream!(stream, {
/// (0, required_value, required),
/// (2, optional_value, option),
/// });
/// // At this point, `required_value` has been overwritten with the TLV with type 0.
/// // `optional_value` may have been overwritten, setting it to `Some` if a TLV with type 2 was
/// // present.
/// # Ok(())
/// # }
/// ```
///
/// [`Readable`]: crate::util::ser::Readable
/// [`DecodeError`]: crate::ln::msgs::DecodeError
/// [`Readable::read`]: crate::util::ser::Readable::read
/// [`Read`]: crate::io::Read
/// [`DecodeError::ShortRead`]: crate::ln::msgs::DecodeError::ShortRead
#[macro_export]
macro_rules! decode_tlv_stream {
($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
let rewind = |_, _| { unreachable!() };
$crate::_decode_tlv_stream_range!($stream, .., rewind, {$(($type, $field, $fieldty)),*});
}
}
/// Similar to [`decode_tlv_stream`] with a custom TLV decoding capabilities.
///
/// `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
/// If it is provided, it will be called with the custom type and the [`FixedLengthReader`] containing
/// the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
/// `Ok(false)` if the message type is unknown, and `Err(`[`DecodeError`]`)` if parsing fails.
///
/// [`FixedLengthReader`]: crate::util::ser::FixedLengthReader
/// [`DecodeError`]: crate::ln::msgs::DecodeError
macro_rules! decode_tlv_stream_with_custom_tlv_decode {
($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
$(, $decode_custom_tlv: expr)?) => { {
let rewind = |_, _| { unreachable!() };
_decode_tlv_stream_range!(
$stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
);
} }
}
#[doc(hidden)]
#[macro_export]
macro_rules! _decode_tlv_stream_range {
($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
$(, $decode_custom_tlv: expr)?) => { {
use $crate::ln::msgs::DecodeError;
let mut last_seen_type: Option<u64> = None;
let mut stream_ref = $stream;
'tlv_read: loop {
use $crate::util::ser;
// First decode the type of this TLV:
let typ: ser::BigSize = {
// We track whether any bytes were read during the consensus_decode call to
// determine whether we should break or return ShortRead if we get an
// UnexpectedEof. This should in every case be largely cosmetic, but its nice to
// pass the TLV test vectors exactly, which require this distinction.
let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
Err(DecodeError::ShortRead) => {
if !tracking_reader.have_read {
break 'tlv_read;
} else {
return Err(DecodeError::ShortRead);
}
},
Err(e) => return Err(e),
Ok(t) => if core::ops::RangeBounds::contains(&$range, &t.0) { t } else {
drop(tracking_reader);
// Assumes the type id is minimally encoded, which is enforced on read.
use $crate::util::ser::Writeable;
let bytes_read = t.serialized_length();
$rewind(stream_ref, bytes_read);
break 'tlv_read;
},
}
};
// Types must be unique and monotonically increasing:
match last_seen_type {
Some(t) if typ.0 <= t => {
return Err(DecodeError::InvalidValue);
},
_ => {},
}
// As we read types, make sure we hit every required type between `last_seen_type` and `typ`:
$({
$crate::_check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
})*
last_seen_type = Some(typ.0);
// Finally, read the length and value itself:
let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
match typ.0 {
$(_t if $crate::_decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
$crate::_decode_tlv!($stream, s, $field, $fieldty);
if s.bytes_remain() {
s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
return Err(DecodeError::InvalidValue);
}
},)*
t => {
$(
if $decode_custom_tlv(t, &mut s)? {
// If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
// continue to the next TLV read.
s.eat_remaining()?;
continue 'tlv_read;
}
)?
if t % 2 == 0 {
return Err(DecodeError::UnknownRequiredFeature);
}
}
}
s.eat_remaining()?;
}
// Make sure we got to each required type after we've read every TLV:
$({
$crate::_check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
})*
} }
}
/// Implements [`Readable`]/[`Writeable`] for a message struct that may include non-TLV and
/// TLV-encoded parts.
///
/// This is useful to implement a [`CustomMessageReader`].
///
/// Currently `$fieldty` may only be `option`, i.e., `$tlvfield` is optional field.
///
/// For example,
/// ```
/// # use lightning::impl_writeable_msg;
/// struct MyCustomMessage {
/// pub field_1: u32,
/// pub field_2: bool,
/// pub field_3: String,
/// pub tlv_optional_integer: Option<u32>,
/// }
///
/// impl_writeable_msg!(MyCustomMessage, {
/// field_1,
/// field_2,
/// field_3
/// }, {
/// (1, tlv_optional_integer, option),
/// });
/// ```
///
/// [`Readable`]: crate::util::ser::Readable
/// [`Writeable`]: crate::util::ser::Writeable
/// [`CustomMessageReader`]: crate::ln::wire::CustomMessageReader
#[macro_export]
macro_rules! impl_writeable_msg {
($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
impl $crate::util::ser::Writeable for $st {
fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
$( self.$field.write(w)?; )*
$crate::encode_tlv_stream!(w, {$(($type, self.$tlvfield.as_ref(), $fieldty)),*});
Ok(())
}
}
impl $crate::util::ser::Readable for $st {
fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
$(let $field = $crate::util::ser::Readable::read(r)?;)*
$($crate::_init_tlv_field_var!($tlvfield, $fieldty);)*
$crate::decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
Ok(Self {
$($field),*,
$($tlvfield),*
})
}
}
}
}
macro_rules! impl_writeable {
($st:ident, {$($field:ident),*}) => {
impl $crate::util::ser::Writeable for $st {
fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
$( self.$field.write(w)?; )*
Ok(())
}
#[inline]
fn serialized_length(&self) -> usize {
let mut len_calc = 0;
$( len_calc += self.$field.serialized_length(); )*
return len_calc;
}
}
impl $crate::util::ser::Readable for $st {
fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
Ok(Self {
$($field: $crate::util::ser::Readable::read(r)?),*
})
}
}
}
}
/// Write out two bytes to indicate the version of an object.
///
/// $this_version represents a unique version of a type. Incremented whenever the type's
/// serialization format has changed or has a new interpretation. Used by a type's reader to
/// determine how to interpret fields or if it can understand a serialized object.
///
/// $min_version_that_can_read_this is the minimum reader version which can understand this
/// serialized object. Previous versions will simply err with a [`DecodeError::UnknownVersion`].
///
/// Updates to either `$this_version` or `$min_version_that_can_read_this` should be included in
/// release notes.
///
/// Both version fields can be specific to this type of object.
///
/// [`DecodeError::UnknownVersion`]: crate::ln::msgs::DecodeError::UnknownVersion
macro_rules! write_ver_prefix {
($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
$stream.write_all(&[$this_version; 1])?;
$stream.write_all(&[$min_version_that_can_read_this; 1])?;
}
}
/// Writes out a suffix to an object as a length-prefixed TLV stream which contains potentially
/// backwards-compatible, optional fields which old nodes can happily ignore.
///
/// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
/// [`DecodeError::UnknownRequiredFeature`] error, with unknown odd fields ignored.
///
/// This is the preferred method of adding new fields that old nodes can ignore and still function
/// correctly.
///
/// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
#[macro_export]
macro_rules! write_tlv_fields {
($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
$crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
}
}
/// Reads a prefix added by [`write_ver_prefix`], above. Takes the current version of the
/// serialization logic for this object. This is compared against the
/// `$min_version_that_can_read_this` added by [`write_ver_prefix`].
macro_rules! read_ver_prefix {
($stream: expr, $this_version: expr) => { {
let ver: u8 = Readable::read($stream)?;
let min_ver: u8 = Readable::read($stream)?;
if min_ver > $this_version {
return Err(DecodeError::UnknownVersion);
}
ver
} }
}
/// Reads a suffix added by [`write_tlv_fields`].
///
/// [`write_tlv_fields`]: crate::write_tlv_fields
#[macro_export]
macro_rules! read_tlv_fields {
($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
$crate::decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
} }
}
/// Initializes the struct fields.
///
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _init_tlv_based_struct_field {
($field: ident, (default_value, $default: expr)) => {
$field.0.unwrap()
};
($field: ident, (static_value, $value: expr)) => {
$field
};
($field: ident, option) => {
$field
};
($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
$crate::_init_tlv_based_struct_field!($field, option)
};
($field: ident, upgradable_required) => {
$field.0.unwrap()
};
($field: ident, upgradable_option) => {
$field
};
($field: ident, required) => {
$field.0.unwrap()
};
($field: ident, required_vec) => {
$field
};
($field: ident, optional_vec) => {
$field.unwrap()
};
}
/// Initializes the variable we are going to read the TLV into.
///
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _init_tlv_field_var {
($field: ident, (default_value, $default: expr)) => {
let mut $field = $crate::util::ser::RequiredWrapper(None);
};
($field: ident, (static_value, $value: expr)) => {
let $field;
};
($field: ident, required) => {
let mut $field = $crate::util::ser::RequiredWrapper(None);
};
($field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {
$crate::_init_tlv_field_var!($field, required);
};
($field: ident, required_vec) => {
let mut $field = Vec::new();
};
($field: ident, option) => {
let mut $field = None;
};
($field: ident, optional_vec) => {
let mut $field = Some(Vec::new());
};
($field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
$crate::_init_tlv_field_var!($field, option);
};
($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
$crate::_init_tlv_field_var!($field, option);
};
($field: ident, upgradable_required) => {
let mut $field = $crate::util::ser::UpgradableRequired(None);
};
($field: ident, upgradable_option) => {
let mut $field = None;
};
}
/// Equivalent to running [`_init_tlv_field_var`] then [`read_tlv_fields`].
///
/// If any unused values are read, their type MUST be specified or else `rustc` will read them as an
/// `i64`.
///
/// This is exported for use by other exported macros, do not use directly.
#[doc(hidden)]
#[macro_export]
macro_rules! _init_and_read_len_prefixed_tlv_fields {
($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
$(
$crate::_init_tlv_field_var!($field, $fieldty);
)*
$crate::read_tlv_fields!($reader, {
$(($type, $field, $fieldty)),*
});
}
}
/// Equivalent to running [`_init_tlv_field_var`] then [`decode_tlv_stream`].
///
/// If any unused values are read, their type MUST be specified or else `rustc` will read them as an
/// `i64`.
macro_rules! _init_and_read_tlv_stream {
($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
$(
$crate::_init_tlv_field_var!($field, $fieldty);
)*
$crate::decode_tlv_stream!($reader, {
$(($type, $field, $fieldty)),*
});
}
}
/// Implements [`Readable`]/[`Writeable`] for a struct storing it as a set of TLVs
/// If `$fieldty` is `required`, then `$field` is a required field that is not an [`Option`] nor a [`Vec`].
/// If `$fieldty` is `(default_value, $default)`, then `$field` will be set to `$default` if not present.
/// If `$fieldty` is `option`, then `$field` is optional field.
/// If `$fieldty` is `optional_vec`, then `$field` is a [`Vec`], which needs to have its individual elements serialized.
/// Note that for `optional_vec` no bytes are written if the vec is empty
///
/// For example,
/// ```
/// # use lightning::impl_writeable_tlv_based;
/// struct LightningMessage {
/// tlv_integer: u32,
/// tlv_default_integer: u32,
/// tlv_optional_integer: Option<u32>,
/// tlv_vec_type_integer: Vec<u32>,
/// }
///
/// impl_writeable_tlv_based!(LightningMessage, {
/// (0, tlv_integer, required),
/// (1, tlv_default_integer, (default_value, 7)),
/// (2, tlv_optional_integer, option),
/// (3, tlv_vec_type_integer, optional_vec),
/// });
/// ```
///
/// [`Readable`]: crate::util::ser::Readable
/// [`Writeable`]: crate::util::ser::Writeable
#[macro_export]
macro_rules! impl_writeable_tlv_based {
($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
impl $crate::util::ser::Writeable for $st {
fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
$crate::write_tlv_fields!(writer, {
$(($type, self.$field, $fieldty)),*
});
Ok(())
}
#[inline]
fn serialized_length(&self) -> usize {
use $crate::util::ser::BigSize;
let len = {
#[allow(unused_mut)]
let mut len = $crate::util::ser::LengthCalculatingWriter(0);
$(
$crate::_get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
)*
len.0
};
let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
len + len_calc.0
}
}
impl $crate::util::ser::Readable for $st {
fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
$crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
$(($type, $field, $fieldty)),*
});
Ok(Self {
$(
$field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
),*
})
}
}
}
}
/// Defines a struct for a TLV stream and a similar struct using references for non-primitive types,
/// implementing [`Readable`] for the former and [`Writeable`] for the latter. Useful as an
/// intermediary format when reading or writing a type encoded as a TLV stream. Note that each field
/// representing a TLV record has its type wrapped with an [`Option`]. A tuple consisting of a type
/// and a serialization wrapper may be given in place of a type when custom serialization is
/// required.
///
/// [`Readable`]: crate::util::ser::Readable
/// [`Writeable`]: crate::util::ser::Writeable
macro_rules! tlv_stream {
($name:ident, $nameref:ident, $range:expr, {
$(($type:expr, $field:ident : $fieldty:tt)),* $(,)*
}) => {
#[derive(Debug)]
pub(super) struct $name {
$(
pub(super) $field: Option<tlv_record_type!($fieldty)>,
)*
}
#[cfg_attr(test, derive(PartialEq))]
#[derive(Debug)]
pub(crate) struct $nameref<'a> {
$(
pub(super) $field: Option<tlv_record_ref_type!($fieldty)>,
)*
}
impl<'a> $crate::util::ser::Writeable for $nameref<'a> {
fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
encode_tlv_stream!(writer, {
$(($type, self.$field, (option, encoding: $fieldty))),*
});
Ok(())
}
}
impl $crate::util::ser::SeekReadable for $name {
fn read<R: $crate::io::Read + $crate::io::Seek>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
$(
_init_tlv_field_var!($field, option);
)*
let rewind = |cursor: &mut R, offset: usize| {
cursor.seek($crate::io::SeekFrom::Current(-(offset as i64))).expect("");
};
_decode_tlv_stream_range!(reader, $range, rewind, {
$(($type, $field, (option, encoding: $fieldty))),*
});
Ok(Self {
$(
$field: $field
),*
})
}
}
}
}
macro_rules! tlv_record_type {
(($type:ty, $wrapper:ident)) => { $type };
(($type:ty, $wrapper:ident, $encoder:ty)) => { $type };
($type:ty) => { $type };
}
macro_rules! tlv_record_ref_type {
(char) => { char };
(u8) => { u8 };
((u16, $wrapper: ident)) => { u16 };
((u32, $wrapper: ident)) => { u32 };
((u64, $wrapper: ident)) => { u64 };
(($type:ty, $wrapper:ident)) => { &'a $type };
(($type:ty, $wrapper:ident, $encoder:ty)) => { $encoder };
($type:ty) => { &'a $type };
}
#[doc(hidden)]
#[macro_export]
macro_rules! _impl_writeable_tlv_based_enum_common {
($st: ident, $(($variant_id: expr, $variant_name: ident) =>
{$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
),* $(,)*;
$(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {