This repository has been archived by the owner on Nov 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
lib.rs
1255 lines (1111 loc) · 42.8 KB
/
lib.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
//! # Ethereum Node Record (ENR)
//!
//! This crate contains an implementation of an Ethereum Node Record (ENR) as specified by
//! [EIP-778](https://eips.ethereum.org/EIPS/eip-778) extended to allow for the use of ed25519 keys.
//!
//! An ENR is a signed, key-value record which has an associated [`NodeId`] (a 32-byte identifier).
//! Updating/modifying an ENR requires an [`EnrKey`] in order to re-sign the recrd with the
//! associated key-pair.
//!
//! ENR's are identified by their sequence number. When updating an ENR, the sequence number is
//! increased.
//!
//! Different identity schemes can be used to define the node id and signatures. Currently only the
//! "v4" identity is supported and is set by default.
//!
//! ## Signing Algorithms
//!
//! User's wishing to implement their own singing algorithms simply need to
//! implement the [`EnrKey`] trait and apply it to an [`Enr`].
//!
//! By default, `k256::SigningKey` implement [`EnrKey`] and can be used to sign and
//! verify ENR records. This library also implements [`EnrKey`] for `ed25519_dalek::Keypair` via the `ed25519`
//! feature flag.
//!
//! Furthermore, a [`CombinedKey`] is provided if the `ed25519` feature flag is set, which provides an
//! ENR type that can support both `secp256k1` and `ed25519` signed ENR records. Examples of the
//! use of each of these key types is given below.
//!
//! ## Features
//!
//! This crate supports a number of features.
//!
//! - `serde`: Allows for serde serialization and deserialization for ENRs.
//! - `ed25519`: Provides support for `ed25519_dalek` keypair types.
//! - `k256`: Uses `k256` for secp256k1 keys.
//! - `rust-secp256k1`: Uses `rust-secp256k1` for secp256k1 keys.
//!
//! These can be enabled via adding the feature flag in your `Cargo.toml`
//!
//! ```toml
//! enr = { version = "*", features = ["serde", "ed25519"] }
//! ```
//!
//! ## Examples
//!
//! To build an ENR, an [`EnrBuilder`] is provided.
//!
//! ### Building an ENR with the default `k256` `secp256k1` key type
//!
//! ```rust
//! use enr::{EnrBuilder, k256};
//! use std::net::Ipv4Addr;
//! use rand::thread_rng;
//!
//! // generate a random secp256k1 key
//! let mut rng = thread_rng();
//! let key = k256::ecdsa::SigningKey::random(&mut rng);
//!
//! let ip = Ipv4Addr::new(192,168,0,1);
//! let enr = EnrBuilder::new("v4").ip4(ip).tcp4(8000).build(&key).unwrap();
//!
//! assert_eq!(enr.ip4(), Some("192.168.0.1".parse().unwrap()));
//! assert_eq!(enr.id(), Some("v4".into()));
//! ```
//!
//! ### Building an ENR with the `CombinedKey` type (support for multiple signing
//! algorithms).
//!
//! Note the `ed25519` feature flag must be set. This makes use of the
//! [`EnrBuilder`] struct.
//! ```rust
//! # #[cfg(feature = "ed25519")] {
//! use enr::{EnrBuilder, CombinedKey};
//! use std::net::Ipv4Addr;
//!
//! // create a new secp256k1 key
//! let key = CombinedKey::generate_secp256k1();
//!
//! // or create a new ed25519 key
//! let key = CombinedKey::generate_ed25519();
//!
//! let ip = Ipv4Addr::new(192,168,0,1);
//! let enr = EnrBuilder::new("v4").ip4(ip).tcp4(8000).build(&key).unwrap();
//!
//! assert_eq!(enr.ip4(), Some("192.168.0.1".parse().unwrap()));
//! assert_eq!(enr.id(), Some("v4".into()));
//! # }
//! ```
//!
//! ### Modifying an [`Enr`]
//!
//! ENR fields can be added and modified using the getters/setters on [`Enr`]. A custom field
//! can be added using [`insert`] and retrieved with [`get`].
//!
//! ```rust
//! use enr::{EnrBuilder, k256::ecdsa::SigningKey, Enr};
//! use std::net::Ipv4Addr;
//! use rand::thread_rng;
//!
//! // specify the type of ENR
//! type DefaultEnr = Enr<SigningKey>;
//!
//! // generate a random secp256k1 key
//! let mut rng = thread_rng();
//! let key = SigningKey::random(&mut rng);
//!
//! let ip = Ipv4Addr::new(192,168,0,1);
//! let mut enr = EnrBuilder::new("v4").ip4(ip).tcp4(8000).build(&key).unwrap();
//!
//! enr.set_tcp4(8001, &key);
//! // set a custom key
//! enr.insert("custom_key", &vec![0,0,1], &key);
//!
//! // encode to base64
//! let base_64_string = enr.to_base64();
//!
//! // decode from base64
//! let decoded_enr: DefaultEnr = base_64_string.parse().unwrap();
//!
//! assert_eq!(decoded_enr.ip4(), Some("192.168.0.1".parse().unwrap()));
//! assert_eq!(decoded_enr.id(), Some("v4".into()));
//! assert_eq!(decoded_enr.tcp4(), Some(8001));
//! assert_eq!(decoded_enr.get("custom_key"), Some(vec![0,0,1].as_slice()));
//! ```
//!
//! ### Encoding/Decoding ENR's of various key types
//!
//! ```rust
//! # #[cfg(feature = "ed25519")] {
//! use enr::{EnrBuilder, k256::ecdsa::SigningKey, Enr, ed25519_dalek::Keypair, CombinedKey};
//! use std::net::Ipv4Addr;
//! use rand::thread_rng;
//! use rand::Rng;
//!
//! // generate a random secp256k1 key
//! let mut rng = thread_rng();
//! let key = SigningKey::random(&mut rng);
//! let ip = Ipv4Addr::new(192,168,0,1);
//! let enr_secp256k1 = EnrBuilder::new("v4").ip4(ip).tcp4(8000).build(&key).unwrap();
//!
//! // encode to base64
//! let base64_string_secp256k1 = enr_secp256k1.to_base64();
//!
//! // generate a random ed25519 key
//! # let mut rng = rand::thread_rng();
//! let key = Keypair::generate(&mut rng);
//! let enr_ed25519 = EnrBuilder::new("v4").ip4(ip).tcp4(8000).build(&key).unwrap();
//!
//! // encode to base64
//! let base64_string_ed25519 = enr_ed25519.to_base64();
//!
//! // decode base64 strings of varying key types
//! // decode the secp256k1 with default Enr
//! let decoded_enr_secp256k1: Enr<k256::ecdsa::SigningKey> = base64_string_secp256k1.parse().unwrap();
//! // decode ed25519 ENRs
//! let decoded_enr_ed25519: Enr<ed25519_dalek::Keypair> = base64_string_ed25519.parse().unwrap();
//!
//! // use the combined key to be able to decode either
//! let decoded_enr: Enr<CombinedKey> = base64_string_secp256k1.parse().unwrap();
//! let decoded_enr: Enr<CombinedKey> = base64_string_ed25519.parse().unwrap();
//! # }
//! ```
//!
//!
//! [`CombinedKey`]: enum.CombinedKey.html
//! [`EnrKey`]: trait.EnrKey.html
//! [`Enr`]: struct.EnrBase.html
//! [`EnrBuilder`]: struct.EnrBuilderBase.html
//! [`NodeId`]: struct.NodeId.html
//! [`insert`]: struct.Enr.html#method.insert
//! [`get`]: struct.Enr.html#method.get
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(
clippy::map_err_ignore,
clippy::missing_errors_doc,
clippy::module_name_repetitions
)]
mod builder;
mod keys;
mod node_id;
use bytes::{Bytes, BytesMut};
use log::debug;
use rlp::{DecoderError, Rlp, RlpStream};
use std::{
collections::BTreeMap,
net::{SocketAddrV4, SocketAddrV6},
};
#[cfg(feature = "serde")]
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use sha3::{Digest, Keccak256};
use std::{
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
str::FromStr,
};
pub use builder::EnrBuilder;
#[cfg(feature = "k256")]
pub use keys::k256;
#[cfg(feature = "rust-secp256k1")]
pub use keys::secp256k1;
#[cfg(all(feature = "ed25519", feature = "k256"))]
pub use keys::{ed25519_dalek, CombinedKey, CombinedPublicKey};
pub use keys::{EnrKey, EnrKeyUnambiguous, EnrPublicKey};
pub use node_id::NodeId;
use std::marker::PhantomData;
/// The "key" in an ENR record can be arbitrary bytes.
type Key = Vec<u8>;
const MAX_ENR_SIZE: usize = 300;
/// The ENR, allowing for arbitrary signing algorithms.
///
/// This struct will always have a valid signature, known public key type, sequence number and `NodeId`. All other parameters are variable/optional.
pub struct Enr<K: EnrKey> {
/// ENR sequence number.
seq: u64,
/// The `NodeId` of the ENR record.
node_id: NodeId,
/// Key-value contents of the ENR. A BTreeMap is used to get the keys in sorted order, which is
/// important for verifying the signature of the ENR.
/// Everything is stored as raw RLP bytes.
content: BTreeMap<Key, Bytes>,
/// The signature of the ENR record, stored as bytes.
signature: Vec<u8>,
/// Marker to pin the generic.
phantom: PhantomData<K>,
}
impl<K: EnrKey> Enr<K> {
// getters //
/// The `NodeId` for the record.
#[must_use]
pub const fn node_id(&self) -> NodeId {
self.node_id
}
/// The current sequence number of the ENR record.
#[must_use]
pub const fn seq(&self) -> u64 {
self.seq
}
/// Reads a custom key from the record if it exists.
pub fn get(&self, key: impl AsRef<[u8]>) -> Option<&[u8]> {
self.get_raw_rlp(key).map(|rlp_data| {
rlp::Rlp::new(rlp_data)
.data()
.expect("All data is sanitized")
})
}
/// Reads a custom key from the record if it exists as raw RLP bytes.
pub fn get_raw_rlp(&self, key: impl AsRef<[u8]>) -> Option<&[u8]> {
self.content.get(key.as_ref()).map(AsRef::as_ref)
}
/// Returns an iterator over all key/value pairs in the ENR.
pub fn iter(&self) -> impl Iterator<Item = (&Key, &[u8])> {
self.content.iter().map(|(k, v)| (k, v.as_ref()))
}
/// Returns the IPv4 address of the ENR record if it is defined.
#[must_use]
pub fn ip4(&self) -> Option<Ipv4Addr> {
if let Some(ip_bytes) = self.get("ip") {
return match ip_bytes.len() {
4 => {
let mut ip = [0_u8; 4];
ip.copy_from_slice(ip_bytes);
Some(Ipv4Addr::from(ip))
}
_ => None,
};
}
None
}
/// Returns the IPv6 address of the ENR record if it is defined.
#[must_use]
pub fn ip6(&self) -> Option<Ipv6Addr> {
if let Some(ip_bytes) = self.get("ip6") {
return match ip_bytes.len() {
16 => {
let mut ip = [0_u8; 16];
ip.copy_from_slice(ip_bytes);
Some(Ipv6Addr::from(ip))
}
_ => None,
};
}
None
}
/// The `id` of ENR record if it is defined.
#[must_use]
pub fn id(&self) -> Option<String> {
if let Some(id_bytes) = self.get("id") {
return Some(String::from_utf8_lossy(id_bytes).to_string());
}
None
}
/// The TCP port of ENR record if it is defined.
#[must_use]
pub fn tcp4(&self) -> Option<u16> {
if let Some(tcp_bytes) = self.get("tcp") {
if tcp_bytes.len() <= 2 {
let mut tcp = [0_u8; 2];
tcp[2 - tcp_bytes.len()..].copy_from_slice(tcp_bytes);
return Some(u16::from_be_bytes(tcp));
}
}
None
}
/// The IPv6-specific TCP port of ENR record if it is defined.
#[must_use]
pub fn tcp6(&self) -> Option<u16> {
if let Some(tcp_bytes) = self.get("tcp6") {
if tcp_bytes.len() <= 2 {
let mut tcp = [0_u8; 2];
tcp[2 - tcp_bytes.len()..].copy_from_slice(tcp_bytes);
return Some(u16::from_be_bytes(tcp));
}
}
None
}
/// The UDP port of ENR record if it is defined.
#[must_use]
pub fn udp4(&self) -> Option<u16> {
if let Some(udp_bytes) = self.get("udp") {
if udp_bytes.len() <= 2 {
let mut udp = [0_u8; 2];
udp[2 - udp_bytes.len()..].copy_from_slice(udp_bytes);
return Some(u16::from_be_bytes(udp));
}
}
None
}
/// The IPv6-specific UDP port of ENR record if it is defined.
#[must_use]
pub fn udp6(&self) -> Option<u16> {
if let Some(udp_bytes) = self.get("udp6") {
if udp_bytes.len() <= 2 {
let mut udp = [0_u8; 2];
udp[2 - udp_bytes.len()..].copy_from_slice(udp_bytes);
return Some(u16::from_be_bytes(udp));
}
}
None
}
/// Provides a socket (based on the UDP port), if the IPv4 and UDP fields are specified.
#[must_use]
pub fn udp4_socket(&self) -> Option<SocketAddrV4> {
if let Some(ip) = self.ip4() {
if let Some(udp) = self.udp4() {
return Some(SocketAddrV4::new(ip, udp));
}
}
None
}
/// Provides a socket (based on the UDP port), if the IPv4 and UDP fields are specified.
#[must_use]
pub fn udp6_socket(&self) -> Option<SocketAddrV6> {
if let Some(ip6) = self.ip6() {
if let Some(udp6) = self.udp6() {
return Some(SocketAddrV6::new(ip6, udp6, 0, 0));
}
}
None
}
/// Provides a socket (based on the TCP port), if the IP and TCP fields are specified.
#[must_use]
pub fn tcp4_socket(&self) -> Option<SocketAddrV4> {
if let Some(ip) = self.ip4() {
if let Some(tcp) = self.tcp4() {
return Some(SocketAddrV4::new(ip, tcp));
}
}
None
}
/// Provides a socket (based on the TCP port), if the IPv6 and TCP6 fields are specified.
#[must_use]
pub fn tcp6_socket(&self) -> Option<SocketAddrV6> {
if let Some(ip6) = self.ip6() {
if let Some(tcp6) = self.tcp6() {
return Some(SocketAddrV6::new(ip6, tcp6, 0, 0));
}
}
None
}
/// The signature of the ENR record.
#[must_use]
pub fn signature(&self) -> &[u8] {
&self.signature
}
/// Returns the public key of the ENR record.
#[must_use]
pub fn public_key(&self) -> K::PublicKey {
K::enr_to_public(&self.content).expect("ENR's can only be created with supported keys")
}
/// Verify the signature of the ENR record.
#[must_use]
pub fn verify(&self) -> bool {
let pubkey = self.public_key();
match self.id() {
Some(ref id) if id == "v4" => pubkey.verify_v4(&self.rlp_content(), &self.signature),
// unsupported identity schemes
_ => false,
}
}
/// Provides the URL-safe base64 encoded "text" version of the ENR prefixed by "enr:".
#[must_use]
pub fn to_base64(&self) -> String {
let hex = base64::encode_config(&rlp::encode(self), base64::URL_SAFE_NO_PAD);
format!("enr:{}", hex)
}
/// Returns the current size of the ENR.
#[must_use]
pub fn size(&self) -> usize {
self.rlp_content().len()
}
// Setters //
/// Allows setting the sequence number to an arbitrary value.
pub fn set_seq(&mut self, seq: u64, key: &K) -> Result<(), EnrError> {
self.seq = seq;
// sign the record
self.sign(key)?;
// update the node id
self.node_id = NodeId::from(key.public());
// check the size of the record
if self.size() > MAX_ENR_SIZE {
return Err(EnrError::ExceedsMaxSize);
}
Ok(())
}
/// Adds or modifies a key/value to the ENR record. A `EnrKey` is required to re-sign the record once
/// modified.
///
/// Returns the previous value in the record if it exists.
pub fn insert(
&mut self,
key: impl AsRef<[u8]>,
value: &[u8],
enr_key: &K,
) -> Result<Option<Bytes>, EnrError> {
self.insert_raw_rlp(key, rlp::encode(&value).freeze(), enr_key)
}
/// Adds or modifies a key/value to the ENR record. A `EnrKey` is required to re-sign the record once
/// modified. The value here is interpreted as raw RLP data.
///
/// Returns the previous value in the record if it exists.
pub fn insert_raw_rlp(
&mut self,
key: impl AsRef<[u8]>,
value: Bytes,
enr_key: &K,
) -> Result<Option<Bytes>, EnrError> {
// currently only support "v4" identity schemes
if key.as_ref() == b"id" && &*value != b"v4" {
return Err(EnrError::UnsupportedIdentityScheme);
}
let previous_value = self.content.insert(key.as_ref().to_vec(), value);
// add the new public key
let public_key = enr_key.public();
let previous_key = self.content.insert(
public_key.enr_key(),
rlp::encode(&public_key.encode().as_ref()).freeze(),
);
// check the size of the record
if self.size() > MAX_ENR_SIZE {
// if the size of the record is too large, revert and error
// revert the public key
if let Some(key) = previous_key {
self.content.insert(public_key.enr_key(), key);
} else {
self.content.remove(&public_key.enr_key());
}
// revert the content
if let Some(prev_value) = previous_value {
self.content.insert(key.as_ref().to_vec(), prev_value);
} else {
self.content.remove(key.as_ref());
}
return Err(EnrError::ExceedsMaxSize);
}
// increment the sequence number
self.seq = self
.seq
.checked_add(1)
.ok_or(EnrError::SequenceNumberTooHigh)?;
// sign the record
self.sign(enr_key)?;
// update the node id
self.node_id = NodeId::from(enr_key.public());
if self.size() > MAX_ENR_SIZE {
// in case the signature size changes, inform the user the size has exceeded the maximum
return Err(EnrError::ExceedsMaxSize);
}
Ok(previous_value)
}
/// Sets the `ip` field of the ENR. Returns any pre-existing IP address in the record.
pub fn set_ip(&mut self, ip: IpAddr, key: &K) -> Result<Option<IpAddr>, EnrError> {
match ip {
IpAddr::V4(addr) => {
let prev_value = self.insert("ip", &addr.octets(), key)?;
if let Some(bytes) = prev_value {
if bytes.len() == 4 {
let mut v = [0_u8; 4];
v.copy_from_slice(&bytes);
return Ok(Some(IpAddr::V4(Ipv4Addr::from(v))));
}
}
}
IpAddr::V6(addr) => {
let prev_value = self.insert("ip6", &addr.octets(), key)?;
if let Some(bytes) = prev_value {
if bytes.len() == 16 {
let mut v = [0_u8; 16];
v.copy_from_slice(&bytes);
return Ok(Some(IpAddr::V6(Ipv6Addr::from(v))));
}
}
}
}
Ok(None)
}
/// Sets the `udp` field of the ENR. Returns any pre-existing UDP port in the record.
pub fn set_udp4(&mut self, udp: u16, key: &K) -> Result<Option<u16>, EnrError> {
if let Some(udp_bytes) = self.insert("udp", &udp.to_be_bytes(), key)? {
if udp_bytes.len() <= 2 {
let mut v = [0_u8; 2];
v[2 - udp_bytes.len()..].copy_from_slice(&udp_bytes);
return Ok(Some(u16::from_be_bytes(v)));
}
}
Ok(None)
}
/// Sets the `udp6` field of the ENR. Returns any pre-existing UDP port in the record.
pub fn set_udp6(&mut self, udp: u16, key: &K) -> Result<Option<u16>, EnrError> {
if let Some(udp_bytes) = self.insert("udp6", &udp.to_be_bytes(), key)? {
if udp_bytes.len() <= 2 {
let mut v = [0_u8; 2];
v[2 - udp_bytes.len()..].copy_from_slice(&udp_bytes);
return Ok(Some(u16::from_be_bytes(v)));
}
}
Ok(None)
}
/// Sets the `tcp` field of the ENR. Returns any pre-existing tcp port in the record.
pub fn set_tcp4(&mut self, tcp: u16, key: &K) -> Result<Option<u16>, EnrError> {
if let Some(tcp_bytes) = self.insert("tcp", &tcp.to_be_bytes(), key)? {
if tcp_bytes.len() <= 2 {
let mut v = [0_u8; 2];
v[2 - tcp_bytes.len()..].copy_from_slice(&tcp_bytes);
return Ok(Some(u16::from_be_bytes(v)));
}
}
Ok(None)
}
/// Sets the `tcp6` field of the ENR. Returns any pre-existing tcp6 port in the record.
pub fn set_tcp6(&mut self, tcp: u16, key: &K) -> Result<Option<u16>, EnrError> {
if let Some(tcp_bytes) = self.insert("tcp6", &tcp.to_be_bytes(), key)? {
if tcp_bytes.len() <= 2 {
let mut v = [0_u8; 2];
v[2 - tcp_bytes.len()..].copy_from_slice(&tcp_bytes);
return Ok(Some(u16::from_be_bytes(v)));
}
}
Ok(None)
}
/// Sets the IP and UDP port in a single update with a single increment in sequence number.
pub fn set_udp_socket(&mut self, socket: SocketAddr, key: &K) -> Result<(), EnrError> {
self.set_socket(socket, key, false)
}
/// Sets the IP and TCP port in a single update with a single increment in sequence number.
pub fn set_tcp_socket(&mut self, socket: SocketAddr, key: &K) -> Result<(), EnrError> {
self.set_socket(socket, key, true)
}
/// Helper function for `set_tcp_socket()` and `set_udp_socket`.
fn set_socket(&mut self, socket: SocketAddr, key: &K, is_tcp: bool) -> Result<(), EnrError> {
let (port_string, port_v6_string): (Key, Key) = if is_tcp {
("tcp".into(), "tcp6".into())
} else {
("udp".into(), "udp6".into())
};
let (prev_ip, prev_port) = match socket.ip() {
IpAddr::V4(addr) => (
self.content.insert(
"ip".into(),
rlp::encode(&(&addr.octets() as &[u8])).freeze(),
),
self.content.insert(
port_string.clone(),
rlp::encode(&(&socket.port().to_be_bytes() as &[u8])).freeze(),
),
),
IpAddr::V6(addr) => (
self.content.insert(
"ip6".into(),
rlp::encode(&(&addr.octets() as &[u8])).freeze(),
),
self.content.insert(
port_v6_string.clone(),
rlp::encode(&(&socket.port().to_be_bytes() as &[u8])).freeze(),
),
),
};
let public_key = key.public();
let previous_key = self.content.insert(
public_key.enr_key(),
rlp::encode(&public_key.encode().as_ref()).freeze(),
);
// check the size and revert on failure
if self.size() > MAX_ENR_SIZE {
// if the size of the record is too large, revert and error
// revert the public key
if let Some(key) = previous_key {
self.content.insert(public_key.enr_key(), key);
} else {
self.content.remove(&public_key.enr_key());
}
// revert the content
match socket.ip() {
IpAddr::V4(_) => {
if let Some(ip) = prev_ip {
self.content.insert("ip".into(), ip);
} else {
self.content.remove(b"ip".as_ref());
}
if let Some(udp) = prev_port {
self.content.insert(port_string, udp);
} else {
self.content.remove(&port_string);
}
}
IpAddr::V6(_) => {
if let Some(ip) = prev_ip {
self.content.insert("ip6".into(), ip);
} else {
self.content.remove(b"ip6".as_ref());
}
if let Some(udp) = prev_port {
self.content.insert(port_v6_string, udp);
} else {
self.content.remove(&port_v6_string);
}
}
}
return Err(EnrError::ExceedsMaxSize);
}
// increment the sequence number
self.seq = self
.seq
.checked_add(1)
.ok_or(EnrError::SequenceNumberTooHigh)?;
// sign the record
self.sign(key)?;
// update the node id
self.node_id = NodeId::from(key.public());
Ok(())
}
/// Sets a new public key for the record.
pub fn set_public_key(&mut self, public_key: &K::PublicKey, key: &K) -> Result<(), EnrError> {
self.insert(&public_key.enr_key(), public_key.encode().as_ref(), key)
.map(|_| {})
}
// Private Functions //
/// Evaluates the RLP-encoding of the content of the ENR record.
fn rlp_content(&self) -> BytesMut {
let mut stream = RlpStream::new_with_buffer(BytesMut::with_capacity(MAX_ENR_SIZE));
stream.begin_list(self.content.len() * 2 + 1);
stream.append(&self.seq);
for (k, v) in &self.content {
// Keys are bytes
stream.append(k);
// Values are raw RLP encoded data
stream.append_raw(v, 1);
}
stream.out()
}
/// Signs the ENR record based on the identity scheme. Currently only "v4" is supported.
fn sign(&mut self, key: &K) -> Result<(), EnrError> {
self.signature = {
match self.id() {
Some(ref id) if id == "v4" => key
.sign_v4(&self.rlp_content())
.map_err(|_| EnrError::SigningError)?,
// other identity schemes are unsupported
_ => return Err(EnrError::SigningError),
}
};
Ok(())
}
}
// traits //
impl<K: EnrKey> Clone for Enr<K> {
fn clone(&self) -> Self {
Self {
seq: self.seq,
node_id: self.node_id,
content: self.content.clone(),
signature: self.signature.clone(),
phantom: self.phantom,
}
}
}
impl<K: EnrKey> std::cmp::Eq for Enr<K> {}
impl<K: EnrKey> PartialEq for Enr<K> {
fn eq(&self, other: &Self) -> bool {
self.seq == other.seq && self.node_id == other.node_id && self.signature == other.signature
}
}
impl<K: EnrKey> std::fmt::Display for Enr<K> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"ENR: NodeId: {}, IpV4 Socket: {:?} IpV6 Socket: {:?}",
self.node_id(),
self.udp4_socket(),
self.udp6_socket()
)
}
}
impl<K: EnrKey> std::fmt::Debug for Enr<K> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.to_base64())
}
}
/// Convert a URL-SAFE base64 encoded ENR into an ENR.
impl<K: EnrKey> FromStr for Enr<K> {
type Err = String;
fn from_str(base64_string: &str) -> Result<Self, Self::Err> {
if base64_string.len() < 4 {
return Err("Invalid ENR string".to_string());
}
// support both enr prefix and not
let mut decode_string = base64_string;
if base64_string.starts_with("enr:") {
decode_string = decode_string
.get(4..)
.ok_or_else(|| "Invalid ENR string".to_string())?;
}
let bytes = base64::decode_config(decode_string, base64::URL_SAFE_NO_PAD)
.map_err(|e| format!("Invalid base64 encoding: {:?}", e))?;
rlp::decode(&bytes).map_err(|e| format!("Invalid ENR: {:?}", e))
}
}
#[cfg(any(feature = "serde"))]
impl<K: EnrKey> Serialize for Enr<K> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_base64())
}
}
#[cfg(any(feature = "serde"))]
impl<'de, K: EnrKey> Deserialize<'de> for Enr<K> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
Self::from_str(&s).map_err(D::Error::custom)
}
}
impl<K: EnrKey> rlp::Encodable for Enr<K> {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(self.content.len() * 2 + 2);
s.append(&self.signature);
s.append(&self.seq);
// must use rlp_content to preserve ordering.
for (k, v) in &self.content {
// Keys are byte data
s.append(k);
// Values are raw RLP encoded data
s.append_raw(v, 1);
}
}
}
impl<K: EnrKey> rlp::Decodable for Enr<K> {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
if !rlp.is_list() {
debug!("Failed to decode ENR. Not an RLP list: {}", rlp);
return Err(DecoderError::RlpExpectedToBeList);
}
let mut rlp_iter = rlp.iter();
if rlp_iter.len() == 0 || rlp_iter.len() % 2 != 0 {
debug!("Failed to decode ENR. List size is not a multiple of 2.");
return Err(DecoderError::Custom("List not a multiple of two"));
}
let signature = rlp_iter
.next()
.ok_or(DecoderError::Custom("List is empty"))?
.data()?;
let seq_bytes = rlp_iter
.next()
.ok_or(DecoderError::Custom("List has only one item"))?
.data()?;
if seq_bytes.len() > 8 {
debug!("Failed to decode ENR. Sequence number is not a u64.");
return Err(DecoderError::Custom("Invalid Sequence number"));
}
// build u64 from big endian vec<u8>
let mut seq: [u8; 8] = [0; 8];
seq[8 - seq_bytes.len()..].copy_from_slice(seq_bytes);
let seq = u64::from_be_bytes(seq);
let mut content = BTreeMap::new();
let mut prev: Option<&[u8]> = None;
while let Some(key) = rlp_iter.next() {
let key = key.data()?;
let item = rlp_iter
.next()
.ok_or(DecoderError::Custom("List not a multiple of 2"))?;
// Sanitize the data
let _ = item.data()?;
let value = item.as_raw();
if prev.is_some() && prev >= Some(key) {
return Err(DecoderError::Custom("Unsorted keys"));
}
prev = Some(key);
content.insert(key.to_vec(), Bytes::copy_from_slice(value));
}
// verify we know the signature type
let public_key = K::enr_to_public(&content)?;
// calculate the node id
let node_id = NodeId::from(public_key);
let enr = Self {
seq,
node_id,
signature: signature.into(),
content,
phantom: PhantomData,
};
// verify the signature before returning
// if the public key is of an unknown type, this will fail.
// An ENR record will always have a valid public-key and therefore node-id
if !enr.verify() {
return Err(DecoderError::Custom("Invalid Signature"));
}
Ok(enr)
}
}
#[derive(Clone, Debug)]
/// An error type for handling various ENR operations.
pub enum EnrError {
/// The ENR is too large.
ExceedsMaxSize,
/// The sequence number is too large.
SequenceNumberTooHigh,
/// There was an error with signing an ENR record.
SigningError,
/// The identity scheme is not supported.
UnsupportedIdentityScheme,
/// The entered RLP data is invalid.
InvalidRlpData(String),
}
pub(crate) fn digest(b: &[u8]) -> [u8; 32] {
let mut output = [0_u8; 32];
output.copy_from_slice(&Keccak256::digest(b));
output
}
#[cfg(test)]
#[cfg(feature = "k256")]
mod tests {
use super::*;
use std::net::Ipv4Addr;
type DefaultEnr = Enr<k256::ecdsa::SigningKey>;
#[cfg(feature = "k256")]
#[test]
fn test_vector_k256() {
let valid_record = hex::decode("f884b8407098ad865b00a582051940cb9cf36836572411a47278783077011599ed5cd16b76f2635f4e234738f30813a89eb9137e3e3df5266e3a1f11df72ecf1145ccb9c01826964827634826970847f00000189736563703235366b31a103ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31388375647082765f").unwrap();
let signature = hex::decode("7098ad865b00a582051940cb9cf36836572411a47278783077011599ed5cd16b76f2635f4e234738f30813a89eb9137e3e3df5266e3a1f11df72ecf1145ccb9c").unwrap();
let expected_pubkey =
hex::decode("03ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd3138")
.unwrap();
let enr = rlp::decode::<DefaultEnr>(&valid_record).unwrap();
let pubkey = enr.public_key().encode();
assert_eq!(enr.ip4(), Some(Ipv4Addr::new(127, 0, 0, 1)));
assert_eq!(enr.id(), Some(String::from("v4")));
assert_eq!(enr.udp4(), Some(30303));
assert_eq!(enr.tcp4(), None);
assert_eq!(enr.signature(), &signature[..]);
assert_eq!(pubkey.to_vec(), expected_pubkey);
assert!(enr.verify());
}
#[cfg(feature = "k256")]
#[test]
fn test_vector_2() {
let text = "enr:-IS4QHCYrYZbAKWCBRlAy5zzaDZXJBGkcnh4MHcBFZntXNFrdvJjX04jRzjzCBOonrkTfj499SZuOh8R33Ls8RRcy5wBgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPKY0yuDUmstAHYpMa2_oxVtw0RW_QAdpzBQA8yWM0xOIN1ZHCCdl8";
let signature = hex::decode("7098ad865b00a582051940cb9cf36836572411a47278783077011599ed5cd16b76f2635f4e234738f30813a89eb9137e3e3df5266e3a1f11df72ecf1145ccb9c").unwrap();
let expected_pubkey =
hex::decode("03ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd3138")
.unwrap();
let expected_node_id =
hex::decode("a448f24c6d18e575453db13171562b71999873db5b286df957af199ec94617f7")
.unwrap();
let enr = text.parse::<DefaultEnr>().unwrap();
let pubkey = enr.public_key().encode();
assert_eq!(enr.ip4(), Some(Ipv4Addr::new(127, 0, 0, 1)));
assert_eq!(enr.ip6(), None);
assert_eq!(enr.id(), Some(String::from("v4")));
assert_eq!(enr.udp4(), Some(30303));
assert_eq!(enr.udp6(), None);
assert_eq!(enr.tcp4(), None);
assert_eq!(enr.tcp6(), None);
assert_eq!(enr.signature(), &signature[..]);
assert_eq!(pubkey.to_vec(), expected_pubkey);