Skip to main content

sc_network_bitswap/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Substrate.
3// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
5// Substrate is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9
10// Substrate is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14
15// You should have received a copy of the GNU General Public License
16// along with Substrate. If not, see <https://www.gnu.org/licenses/>.
17
18//! Bitswap client and server.
19
20use cid::Version as CidVersion;
21
22mod handle;
23mod metrics;
24mod service;
25
26pub use cid::Cid;
27pub(crate) use handle::BitswapCommand;
28pub use handle::{BitswapError, BitswapHandle, FetchItem};
29pub use service::start;
30
31pub(crate) const LOG_TARGET: &str = "sub-libp2p::bitswap";
32
33/// Maximum entries per Bitswap message.
34pub const MAX_WANTED_BLOCKS: usize = 16;
35
36/// IPFS raw multicodec used for indexed transaction payload bytes.
37pub const RAW_CODEC: u64 = 0x55;
38
39/// Multihash code for BLAKE2b-256, per the multicodec table.
40pub const BLAKE2B_256_MULTIHASH_CODE: u64 = 0xb220;
41
42/// Multihash code for SHA2-256, per the multicodec table.
43pub const SHA2_256_MULTIHASH_CODE: u64 = 0x12;
44
45/// Multihash code for Keccak-256, per the multicodec table.
46pub const KECCAK_256_MULTIHASH_CODE: u64 = 0x1b;
47
48/// Returns whether Bitswap supports a CID.
49pub fn is_cid_supported(cid: &Cid) -> bool {
50	cid.version() != CidVersion::V0 &&
51		cid.hash().size() == 32 &&
52		matches!(
53			cid.hash().code(),
54			BLAKE2B_256_MULTIHASH_CODE | SHA2_256_MULTIHASH_CODE | KECCAK_256_MULTIHASH_CODE
55		)
56}
57
58#[cfg(test)]
59mod tests {
60	use super::*;
61
62	#[test]
63	fn is_cid_supported_accepts_all_three_supported_hashings() {
64		use cid::multihash::Multihash;
65		for multihash_code in
66			[BLAKE2B_256_MULTIHASH_CODE, SHA2_256_MULTIHASH_CODE, KECCAK_256_MULTIHASH_CODE]
67		{
68			let digest = [9u8; 32];
69			let mh = Multihash::<64>::wrap(multihash_code, &digest).unwrap();
70			let cid = Cid::new_v1(RAW_CODEC, mh);
71			assert!(is_cid_supported(&cid), "{multihash_code} CID should be supported");
72		}
73	}
74
75	#[test]
76	fn is_cid_supported_rejects_unknown_multihash_code() {
77		use cid::multihash::Multihash;
78		let digest = [9u8; 32];
79		let mh = Multihash::<64>::wrap(0x99, &digest).unwrap();
80		let cid = Cid::new_v1(RAW_CODEC, mh);
81		assert!(!is_cid_supported(&cid));
82	}
83}