Skip to content

Commit d05786f

Browse files
Replace Multiaddr & related types with substrate-specific types (#4198)
This PR introduces custom types / substrate wrappers for `Multiaddr`, `multiaddr::Protocol`, `Multihash`, `ed25519::*` and supplementary types like errors and iterators. This is needed to unblock `libp2p` upgrade PR #1631 after #2944 was merged. `libp2p` and `litep2p` currently depend on different versions of `multiaddr` crate, and introduction of this "common ground" types is needed to support independent version upgrades of `multiaddr` and dependent crates in `libp2p` & `litep2p`. While being just convenient to not tie versions of `libp2p` & `litep2p` dependencies together, it's currently not even possible to keep `libp2p` & `litep2p` dependencies updated to the same versions as `multiaddr` in `libp2p` depends on `libp2p-identity` that we can't include as a dependency of `litep2p`, which has it's own `PeerId` type. In the future, to keep things updated on `litep2p` side, we will likely need to fork `multiaddr` and make it use `litep2p` `PeerId` as a payload of `/p2p/...` protocol. With these changes, common code in substrate uses these custom types, and `litep2p` & `libp2p` backends use corresponding libraries types.
1 parent e0e1f2d commit d05786f

33 files changed

Lines changed: 1343 additions & 147 deletions

File tree

Cargo.lock

Lines changed: 9 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

prdoc/pr_4198.prdoc

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0
2+
# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json
3+
4+
title: Replace `Multiaddr` & related types with substrate-specific types
5+
6+
doc:
7+
- audience: Node Dev
8+
description: |
9+
Introduce custom types / substrate wrappers for `Multiaddr`, `multiaddr::Protocol`,
10+
`Multihash`, `ed25519::*` and supplementary types like errors and iterators.
11+
12+
Common code in substrate uses these custom types, while `libp2p` & `litep2p` network
13+
backends use their corresponding libraries types.
14+
15+
This is needed to independently upgrade `libp2p` & `litep2p` dependencies.
16+
17+
crates:
18+
- name: sc-network-types
19+
bump: minor
20+
- name: sc-network
21+
bump: minor
22+
- name: sc-network-sync
23+
bump: minor
24+
- name: sc-authority-discovery
25+
bump: minor
26+
- name: sc-cli
27+
bump: patch
28+
- name: sc-mixnet
29+
bump: patch
30+
- name: sc-telemetry
31+
bump: patch

substrate/client/authority-discovery/src/error.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ pub enum Error {
3535
VerifyingDhtPayload,
3636

3737
#[error("Failed to hash the authority id to be used as a dht key.")]
38-
HashingAuthorityId(#[from] sc_network::multiaddr::multihash::Error),
38+
HashingAuthorityId(#[from] sc_network_types::multihash::Error),
3939

4040
#[error("Failed calling into the Substrate runtime: {0}")]
4141
CallingRuntime(#[from] sp_blockchain::Error),
@@ -53,7 +53,7 @@ pub enum Error {
5353
EncodingDecodingScale(#[from] codec::Error),
5454

5555
#[error("Failed to parse a libp2p multi address.")]
56-
ParsingMultiaddress(#[from] sc_network::multiaddr::Error),
56+
ParsingMultiaddress(#[from] sc_network::multiaddr::ParseError),
5757

5858
#[error("Failed to parse a libp2p key: {0}")]
5959
ParsingLibp2pIdentity(String),

substrate/client/authority-discovery/src/worker.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ use addr_cache::AddrCache;
3535
use codec::{Decode, Encode};
3636
use ip_network::IpNetwork;
3737
use linked_hash_set::LinkedHashSet;
38-
use multihash::{Code, Multihash, MultihashDigest};
3938

4039
use log::{debug, error, log_enabled};
4140
use prometheus_endpoint::{register, Counter, CounterVec, Gauge, Opts, U64};
@@ -46,7 +45,10 @@ use sc_network::{
4645
event::DhtEvent, multiaddr, KademliaKey, Multiaddr, NetworkDHTProvider, NetworkSigner,
4746
NetworkStateInfo,
4847
};
49-
use sc_network_types::PeerId;
48+
use sc_network_types::{
49+
multihash::{Code, Multihash},
50+
PeerId,
51+
};
5052
use sp_api::{ApiError, ProvideRuntimeApi};
5153
use sp_authority_discovery::{
5254
AuthorityDiscoveryApi, AuthorityId, AuthorityPair, AuthoritySignature,

substrate/client/authority-discovery/src/worker/addr_cache.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,8 +176,8 @@ fn addresses_to_peer_ids(addresses: &HashSet<Multiaddr>) -> HashSet<PeerId> {
176176
mod tests {
177177
use super::*;
178178

179-
use multihash::{self, Multihash};
180179
use quickcheck::{Arbitrary, Gen, QuickCheck, TestResult};
180+
use sc_network_types::multihash::Multihash;
181181

182182
use sp_authority_discovery::{AuthorityId, AuthorityPair};
183183
use sp_core::crypto::Pair;

substrate/client/authority-discovery/src/worker/tests.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,15 @@ use futures::{
2929
sink::SinkExt,
3030
task::LocalSpawn,
3131
};
32-
use libp2p::{core::multiaddr, identity::SigningError, kad::record::Key as KademliaKey, PeerId};
32+
use libp2p::{identity::SigningError, kad::record::Key as KademliaKey};
3333
use prometheus_endpoint::prometheus::default_registry;
3434

3535
use sc_client_api::HeaderBackend;
3636
use sc_network::{service::signature::Keypair, Signature};
37+
use sc_network_types::{
38+
multiaddr::{Multiaddr, Protocol},
39+
PeerId,
40+
};
3741
use sp_api::{ApiRef, ProvideRuntimeApi};
3842
use sp_keystore::{testing::MemoryKeystore, Keystore};
3943
use sp_runtime::traits::{Block as BlockT, NumberFor, Zero};
@@ -168,7 +172,7 @@ impl NetworkSigner for TestNetwork {
168172
let public_key = libp2p::identity::PublicKey::try_decode_protobuf(&public_key)
169173
.map_err(|error| error.to_string())?;
170174
let peer_id: PeerId = peer_id.into();
171-
let remote: libp2p::PeerId = public_key.to_peer_id();
175+
let remote: PeerId = public_key.to_peer_id().into();
172176

173177
Ok(peer_id == remote && public_key.verify(message, signature))
174178
}
@@ -435,7 +439,7 @@ fn dont_stop_polling_dht_event_stream_after_bogus_event() {
435439
let peer_id = PeerId::random();
436440
let address: Multiaddr = "/ip6/2001:db8:0:0:0:0:0:1/tcp/30333".parse().unwrap();
437441

438-
address.with(multiaddr::Protocol::P2p(peer_id.into()))
442+
address.with(Protocol::P2p(peer_id.into()))
439443
};
440444
let remote_key_store = MemoryKeystore::new();
441445
let remote_public_key: AuthorityId = remote_key_store

substrate/client/cli/src/params/node_key_params.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
// along with this program. If not, see <https://www.gnu.org/licenses/>.
1818

1919
use clap::Args;
20-
use sc_network::config::{identity::ed25519, NodeKeyConfig};
20+
use sc_network::config::{ed25519, NodeKeyConfig};
2121
use sc_service::Role;
2222
use sp_core::H256;
2323
use std::{path::PathBuf, str::FromStr};
@@ -148,7 +148,7 @@ fn parse_ed25519_secret(hex: &str) -> error::Result<sc_network::config::Ed25519S
148148
mod tests {
149149
use super::*;
150150
use clap::ValueEnum;
151-
use libp2p_identity::ed25519;
151+
use sc_network::config::ed25519;
152152
use std::fs::{self, File};
153153
use tempfile::TempDir;
154154

@@ -194,11 +194,7 @@ mod tests {
194194
.into_keypair()
195195
.expect("Creates node key pair");
196196

197-
if let Ok(pair) = node_key.try_into_ed25519() {
198-
if pair.secret().as_ref() != key.as_ref() {
199-
panic!("Invalid key")
200-
}
201-
} else {
197+
if node_key.secret().as_ref() != key.as_ref() {
202198
panic!("Invalid key")
203199
}
204200
}

substrate/client/mixnet/src/sync_with_runtime.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,10 @@ use mixnet::core::{
2525
Mixnet, Mixnode as CoreMixnode, MixnodesErr as CoreMixnodesErr, RelSessionIndex,
2626
SessionPhase as CoreSessionPhase, SessionStatus as CoreSessionStatus,
2727
};
28-
use multiaddr::{multiaddr, Multiaddr, Protocol};
29-
use sc_network_types::PeerId;
28+
use sc_network_types::{
29+
multiaddr::{multiaddr, Multiaddr, Protocol},
30+
PeerId,
31+
};
3032
use sp_api::{ApiError, ApiRef};
3133
use sp_mixnet::{
3234
runtime_api::MixnetApi,
@@ -196,7 +198,6 @@ where
196198
#[cfg(test)]
197199
mod tests {
198200
use super::*;
199-
use multiaddr::multiaddr;
200201

201202
#[test]
202203
fn fixup_empty_external_addresses() {

substrate/client/network/src/config.rs

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,11 @@ pub use crate::{
3535
types::ProtocolName,
3636
};
3737

38-
pub use libp2p::{
39-
build_multiaddr,
40-
identity::{self, ed25519, Keypair},
41-
multiaddr, Multiaddr,
38+
pub use sc_network_types::{build_multiaddr, ed25519};
39+
use sc_network_types::{
40+
multiaddr::{self, Multiaddr},
41+
PeerId,
4242
};
43-
use sc_network_types::PeerId;
4443

4544
use crate::service::{ensure_addresses_consistent_with_transport, traits::NetworkBackend};
4645
use codec::Encode;
@@ -100,7 +99,7 @@ impl fmt::Debug for ProtocolId {
10099
/// # Example
101100
///
102101
/// ```
103-
/// # use libp2p::{Multiaddr, PeerId};
102+
/// # use sc_network_types::{multiaddr::Multiaddr, PeerId};
104103
/// use sc_network::config::parse_str_addr;
105104
/// let (peer_id, addr) = parse_str_addr(
106105
/// "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV"
@@ -131,7 +130,7 @@ pub fn parse_addr(mut addr: Multiaddr) -> Result<(PeerId, Multiaddr), ParseErr>
131130
/// # Example
132131
///
133132
/// ```
134-
/// # use libp2p::{Multiaddr, PeerId};
133+
/// # use sc_network_types::{multiaddr::Multiaddr, PeerId};
135134
/// use sc_network::config::MultiaddrWithPeerId;
136135
/// let addr: MultiaddrWithPeerId =
137136
/// "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse().unwrap();
@@ -187,7 +186,7 @@ impl TryFrom<String> for MultiaddrWithPeerId {
187186
#[derive(Debug)]
188187
pub enum ParseErr {
189188
/// Error while parsing the multiaddress.
190-
MultiaddrParse(multiaddr::Error),
189+
MultiaddrParse(multiaddr::ParseError),
191190
/// Multihash of the peer ID is invalid.
192191
InvalidPeerId,
193192
/// The peer ID is missing from the address.
@@ -214,8 +213,8 @@ impl std::error::Error for ParseErr {
214213
}
215214
}
216215

217-
impl From<multiaddr::Error> for ParseErr {
218-
fn from(err: multiaddr::Error) -> ParseErr {
216+
impl From<multiaddr::ParseError> for ParseErr {
217+
fn from(err: multiaddr::ParseError) -> ParseErr {
219218
Self::MultiaddrParse(err)
220219
}
221220
}
@@ -343,10 +342,10 @@ impl NodeKeyConfig {
343342
///
344343
/// * If the secret is configured to be new, it is generated and the corresponding keypair is
345344
/// returned.
346-
pub fn into_keypair(self) -> io::Result<Keypair> {
345+
pub fn into_keypair(self) -> io::Result<ed25519::Keypair> {
347346
use NodeKeyConfig::*;
348347
match self {
349-
Ed25519(Secret::New) => Ok(Keypair::generate_ed25519()),
348+
Ed25519(Secret::New) => Ok(ed25519::Keypair::generate()),
350349

351350
Ed25519(Secret::Input(k)) => Ok(ed25519::Keypair::from(k).into()),
352351

@@ -365,8 +364,7 @@ impl NodeKeyConfig {
365364
ed25519::SecretKey::generate,
366365
|b| b.as_ref().to_vec(),
367366
)
368-
.map(ed25519::Keypair::from)
369-
.map(Keypair::from),
367+
.map(ed25519::Keypair::from),
370368
}
371369
}
372370
}
@@ -887,7 +885,7 @@ impl<B: BlockT + 'static, H: ExHashT, N: NetworkBackend<B, H>> FullNetworkConfig
887885
.find(|o| o.peer_id != bootnode.peer_id)
888886
{
889887
Err(crate::error::Error::DuplicateBootnode {
890-
address: bootnode.multiaddr.clone(),
888+
address: bootnode.multiaddr.clone().into(),
891889
first_id: bootnode.peer_id.into(),
892890
second_id: other.peer_id.into(),
893891
})
@@ -947,14 +945,8 @@ mod tests {
947945
tempfile::Builder::new().prefix(prefix).tempdir().unwrap()
948946
}
949947

950-
fn secret_bytes(kp: Keypair) -> Vec<u8> {
951-
kp.try_into_ed25519()
952-
.expect("ed25519 keypair")
953-
.secret()
954-
.as_ref()
955-
.iter()
956-
.cloned()
957-
.collect()
948+
fn secret_bytes(kp: ed25519::Keypair) -> Vec<u8> {
949+
kp.secret().to_bytes().into()
958950
}
959951

960952
#[test]

substrate/client/network/src/error.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
2121
use crate::{config::TransportConfig, types::ProtocolName};
2222

23-
use libp2p::{Multiaddr, PeerId};
23+
use sc_network_types::{multiaddr::Multiaddr, PeerId};
2424

2525
use std::fmt;
2626

0 commit comments

Comments
 (0)