Skip to content

Commit 5617481

Browse files
laptoumxinden
andauthored
*: Add Serialize and Deserialize to PeerId gossipsub MessageId and kad Key (#2408)
Co-authored-by: Max Inden <[email protected]>
1 parent e19391e commit 5617481

File tree

13 files changed

+142
-0
lines changed

13 files changed

+142
-0
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ wasm-ext-websocket = ["wasm-ext", "libp2p-wasm-ext/websocket"]
6060
websocket = ["libp2p-websocket"]
6161
yamux = ["libp2p-yamux"]
6262
secp256k1 = ["libp2p-core/secp256k1"]
63+
serde = ["libp2p-core/serde", "libp2p-kad/serde", "libp2p-gossipsub/serde"]
6364

6465
[package.metadata.docs.rs]
6566
all-features = true

core/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,13 @@
1111

1212
- Add `ConnectedPoint::is_relayed` (see [PR 2392]).
1313

14+
- Implement `Serialize` and `Deserialize` for `PeerId` (see [PR 2408])
15+
1416
[PR 2339]: https://github.com/libp2p/rust-libp2p/pull/2339
1517
[PR 2350]: https://github.com/libp2p/rust-libp2p/pull/2350
1618
[PR 2352]: https://github.com/libp2p/rust-libp2p/pull/2352
1719
[PR 2392]: https://github.com/libp2p/rust-libp2p/pull/2392
20+
[PR 2408]: https://github.com/libp2p/rust-libp2p/pull/2408
1821

1922
# 0.30.1 [2021-11-16]
2023

core/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ thiserror = "1.0"
3737
unsigned-varint = "0.7"
3838
void = "1"
3939
zeroize = "1"
40+
_serde = { package = "serde", version = "1", optional = true, features = ["derive"] }
4041

4142
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
4243
ring = { version = "0.16.9", features = ["alloc", "std"], default-features = false }
@@ -48,6 +49,8 @@ criterion = "0.3"
4849
libp2p-mplex = { path = "../muxers/mplex" }
4950
libp2p-noise = { path = "../transports/noise" }
5051
libp2p-tcp = { path = "../transports/tcp" }
52+
serde_json = "1.0"
53+
rmp-serde = "0.15"
5154
multihash = { version = "0.14", default-features = false, features = ["arb"] }
5255
quickcheck = "0.9.0"
5356
rand07 = { package = "rand", version = "0.7" }
@@ -59,6 +62,7 @@ prost-build = "0.9"
5962
default = [ "secp256k1", "ecdsa" ]
6063
secp256k1 = [ "libsecp256k1" ]
6164
ecdsa = [ "p256" ]
65+
serde = ["multihash/serde-codec", "_serde"]
6266

6367
[[bench]]
6468
name = "peer_id"

core/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@
3535
//! define how to upgrade each individual substream to use a protocol.
3636
//! See the `upgrade` module.
3737
38+
#[cfg(feature = "serde")]
39+
extern crate _serde as serde;
40+
3841
mod keys_proto {
3942
include!(concat!(env!("OUT_DIR"), "/keys_proto.rs"));
4043
}

core/src/peer_id.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ use rand::Rng;
2424
use std::{convert::TryFrom, fmt, str::FromStr};
2525
use thiserror::Error;
2626

27+
#[cfg(feature = "serde")]
28+
use serde::{Deserialize, Serialize};
29+
2730
/// Public keys with byte-lengths smaller than `MAX_INLINE_KEY_LENGTH` will be
2831
/// automatically used as the peer id using an identity multihash.
2932
const MAX_INLINE_KEY_LENGTH: usize = 42;
@@ -164,6 +167,60 @@ impl From<PeerId> for Vec<u8> {
164167
}
165168
}
166169

170+
#[cfg(feature = "serde")]
171+
impl Serialize for PeerId {
172+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
173+
where
174+
S: _serde::Serializer,
175+
{
176+
if serializer.is_human_readable() {
177+
serializer.serialize_str(&self.to_base58())
178+
} else {
179+
serializer.serialize_bytes(&self.to_bytes()[..])
180+
}
181+
}
182+
}
183+
184+
#[cfg(feature = "serde")]
185+
impl<'de> Deserialize<'de> for PeerId {
186+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
187+
where
188+
D: serde::Deserializer<'de>,
189+
{
190+
use serde::de::*;
191+
192+
struct PeerIdVisitor;
193+
194+
impl<'de> Visitor<'de> for PeerIdVisitor {
195+
type Value = PeerId;
196+
197+
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
198+
write!(f, "valid peer id")
199+
}
200+
201+
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
202+
where
203+
E: Error,
204+
{
205+
PeerId::from_bytes(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
206+
}
207+
208+
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
209+
where
210+
E: Error,
211+
{
212+
PeerId::from_str(v).map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))
213+
}
214+
}
215+
216+
if deserializer.is_human_readable() {
217+
deserializer.deserialize_str(PeerIdVisitor)
218+
} else {
219+
deserializer.deserialize_bytes(PeerIdVisitor)
220+
}
221+
}
222+
}
223+
167224
#[derive(Debug, Error)]
168225
pub enum ParseError {
169226
#[error("base-58 decode error: {0}")]

core/tests/serde.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#![cfg(feature = "serde")]
2+
3+
use std::str::FromStr;
4+
5+
use libp2p_core::PeerId;
6+
7+
extern crate _serde as serde;
8+
9+
#[test]
10+
pub fn serialize_peer_id_json() {
11+
let peer_id = PeerId::from_str("12D3KooWRNw2pJC9748Fmq4WNV27HoSTcX3r37132FLkQMrbKAiC").unwrap();
12+
let json = serde_json::to_string(&peer_id).unwrap();
13+
assert_eq!(
14+
json,
15+
r#""12D3KooWRNw2pJC9748Fmq4WNV27HoSTcX3r37132FLkQMrbKAiC""#
16+
)
17+
}
18+
19+
#[test]
20+
pub fn serialize_peer_id_msgpack() {
21+
let peer_id = PeerId::from_str("12D3KooWRNw2pJC9748Fmq4WNV27HoSTcX3r37132FLkQMrbKAiC").unwrap();
22+
let buf = rmp_serde::to_vec(&peer_id).unwrap();
23+
assert_eq!(
24+
&buf[..],
25+
&[
26+
0xc4, 38, // msgpack buffer header
27+
0x00, 0x24, 0x08, 0x01, 0x12, 0x20, 0xe7, 0x37, 0x0c, 0x66, 0xef, 0xec, 0x80, 0x00,
28+
0xd5, 0x87, 0xfc, 0x41, 0x65, 0x92, 0x8e, 0xe0, 0x75, 0x5f, 0x94, 0x86, 0xcb, 0x5c,
29+
0xf0, 0xf7, 0x80, 0xd8, 0xe0, 0x6c, 0x98, 0xce, 0x7d, 0xa9
30+
]
31+
);
32+
}
33+
34+
#[test]
35+
pub fn deserialize_peer_id_json() {
36+
let peer_id = PeerId::from_str("12D3KooWRNw2pJC9748Fmq4WNV27HoSTcX3r37132FLkQMrbKAiC").unwrap();
37+
let json = r#""12D3KooWRNw2pJC9748Fmq4WNV27HoSTcX3r37132FLkQMrbKAiC""#;
38+
assert_eq!(peer_id, serde_json::from_str(json).unwrap())
39+
}
40+
41+
#[test]
42+
pub fn deserialize_peer_id_msgpack() {
43+
let peer_id = PeerId::from_str("12D3KooWRNw2pJC9748Fmq4WNV27HoSTcX3r37132FLkQMrbKAiC").unwrap();
44+
let buf = &[
45+
0xc4, 38, // msgpack buffer header
46+
0x00, 0x24, 0x08, 0x01, 0x12, 0x20, 0xe7, 0x37, 0x0c, 0x66, 0xef, 0xec, 0x80, 0x00, 0xd5,
47+
0x87, 0xfc, 0x41, 0x65, 0x92, 0x8e, 0xe0, 0x75, 0x5f, 0x94, 0x86, 0xcb, 0x5c, 0xf0, 0xf7,
48+
0x80, 0xd8, 0xe0, 0x6c, 0x98, 0xce, 0x7d, 0xa9,
49+
];
50+
51+
assert_eq!(peer_id, rmp_serde::from_read(&mut &buf[..]).unwrap());
52+
}

protocols/gossipsub/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,14 @@
99
- Improve bandwidth performance by tracking IWANTs and reducing duplicate sends
1010
(see [PR 2327]).
1111

12+
- Implement `Serialize` and `Deserialize` for `MessageId` and `FastMessageId` (see [PR 2408])
13+
1214
- Fix `GossipsubConfigBuilder::build()` requiring `&self` to live for `'static` (see [PR 2409])
1315

1416
[PR 2346]: https://github.com/libp2p/rust-libp2p/pull/2346
1517
[PR 2339]: https://github.com/libp2p/rust-libp2p/pull/2339
1618
[PR 2327]: https://github.com/libp2p/rust-libp2p/pull/2327
19+
[PR 2408]: https://github.com/libp2p/rust-libp2p/pull/2408
1720
[PR 2409]: https://github.com/libp2p/rust-libp2p/pull/2409
1821

1922
# 0.34.0 [2021-11-16]

protocols/gossipsub/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ regex = "1.4.0"
3030
futures-timer = "3.0.2"
3131
pin-project = "1.0.8"
3232
instant = "0.1.11"
33+
serde = { version = "1", optional = true, features = ["derive"] }
3334
# Metrics dependencies
3435
open-metrics-client = "0.14.0"
3536

protocols/gossipsub/src/types.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ use prost::Message;
2727
use std::fmt;
2828
use std::fmt::Debug;
2929

30+
#[cfg(feature = "serde")]
31+
use serde::{Deserialize, Serialize};
32+
3033
#[derive(Debug)]
3134
/// Validation kinds from the application for received messages.
3235
pub enum MessageAcceptance {
@@ -42,6 +45,7 @@ pub enum MessageAcceptance {
4245
/// Macro for declaring message id types
4346
macro_rules! declare_message_id_type {
4447
($name: ident, $name_string: expr) => {
48+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4549
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
4650
pub struct $name(pub Vec<u8>);
4751

protocols/kad/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,11 @@
66

77
- Derive `Clone` for `KademliaEvent` (see [PR 2411])
88

9+
- Derive `Serialize`, `Deserialize` for `store::record::Key` (see [PR 2408])
10+
911
[PR 2339]: https://github.com/libp2p/rust-libp2p/pull/2339
1012
[PR 2411]: https://github.com/libp2p/rust-libp2p/pull/2411
13+
[PR 2408]: https://github.com/libp2p/rust-libp2p/pull/2408
1114

1215
# 0.33.0 [2021-11-16]
1316

protocols/kad/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ unsigned-varint = { version = "0.7", features = ["asynchronous_codec"] }
2929
void = "1.0"
3030
futures-timer = "3.0.2"
3131
instant = "0.1.11"
32+
_serde = { package = "serde", version = "1.0", optional = true, features = ["derive"] }
3233
thiserror = "1"
3334

3435
[dev-dependencies]
@@ -40,3 +41,6 @@ quickcheck = "0.9.0"
4041

4142
[build-dependencies]
4243
prost-build = "0.9"
44+
45+
[features]
46+
serde = ["_serde", "bytes/serde"]

protocols/kad/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
// be useful later for record store
2525
#![allow(dead_code)]
2626

27+
#[cfg(feature = "serde")]
28+
extern crate _serde as serde;
29+
2730
pub mod handler;
2831
pub mod kbucket;
2932
pub mod protocol;

protocols/kad/src/record.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,14 @@ pub mod store;
2525
use bytes::Bytes;
2626
use instant::Instant;
2727
use libp2p_core::{multihash::Multihash, Multiaddr, PeerId};
28+
#[cfg(feature = "serde")]
29+
use serde::{Deserialize, Serialize};
2830
use std::borrow::Borrow;
2931
use std::hash::{Hash, Hasher};
3032

3133
/// The (opaque) key of a record.
34+
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
35+
#[cfg_attr(feature = "serde", serde(crate = "_serde"))]
3236
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
3337
pub struct Key(Bytes);
3438

0 commit comments

Comments
 (0)