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
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use asynchronous_codec::{Decoder, Encoder, Framed};
use bytes::{Bytes, BytesMut};
use futures::future;
use futures::io::{AsyncRead, AsyncWrite};
use libp2p::core::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeInfo};
use prost::Message;
use unsigned_varint::codec;
use crate::{
handler::{BitswapHandlerError, HandlerEvent},
message::BitswapMessage,
};
const MAX_BUF_SIZE: usize = 1024 * 1024 * 2;
#[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ProtocolId {
Legacy = 0,
Bitswap100 = 1,
Bitswap110 = 2,
Bitswap120 = 3,
}
impl ProtocolName for ProtocolId {
fn protocol_name(&self) -> &[u8] {
match self {
ProtocolId::Legacy => b"/ipfs/bitswap",
ProtocolId::Bitswap100 => b"/ipfs/bitswap/1.0.0",
ProtocolId::Bitswap110 => b"/ipfs/bitswap/1.1.0",
ProtocolId::Bitswap120 => b"/ipfs/bitswap/1.2.0",
}
}
}
impl ProtocolId {
pub fn try_from(value: impl AsRef<[u8]>) -> Option<Self> {
let value = value.as_ref();
if value == ProtocolId::Legacy.protocol_name() {
Some(ProtocolId::Legacy)
} else if value == ProtocolId::Bitswap100.protocol_name() {
Some(ProtocolId::Bitswap100)
} else if value == ProtocolId::Bitswap110.protocol_name() {
Some(ProtocolId::Bitswap110)
} else if value == ProtocolId::Bitswap120.protocol_name() {
Some(ProtocolId::Bitswap120)
} else {
None
}
}
}
impl ProtocolId {
pub fn supports_have(self) -> bool {
matches!(self, ProtocolId::Bitswap120)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProtocolConfig {
pub protocol_ids: Vec<ProtocolId>,
pub max_transmit_size: usize,
}
impl Default for ProtocolConfig {
fn default() -> Self {
ProtocolConfig {
protocol_ids: vec![
ProtocolId::Bitswap120,
ProtocolId::Bitswap110,
ProtocolId::Bitswap100,
ProtocolId::Legacy,
],
max_transmit_size: MAX_BUF_SIZE,
}
}
}
impl UpgradeInfo for ProtocolConfig {
type Info = ProtocolId;
type InfoIter = Vec<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
self.protocol_ids.clone()
}
}
impl<TSocket> InboundUpgrade<TSocket> for ProtocolConfig
where
TSocket: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
type Output = Framed<TSocket, BitswapCodec>;
type Error = BitswapHandlerError;
#[allow(clippy::type_complexity)]
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
#[inline]
fn upgrade_inbound(self, socket: TSocket, protocol_id: Self::Info) -> Self::Future {
let mut length_codec = codec::UviBytes::default();
length_codec.set_max_len(self.max_transmit_size);
Box::pin(future::ok(Framed::new(
socket,
BitswapCodec::new(length_codec, protocol_id),
)))
}
}
impl<TSocket> OutboundUpgrade<TSocket> for ProtocolConfig
where
TSocket: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
type Output = Framed<TSocket, BitswapCodec>;
type Error = BitswapHandlerError;
#[allow(clippy::type_complexity)]
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
#[inline]
fn upgrade_outbound(self, socket: TSocket, protocol_id: Self::Info) -> Self::Future {
let mut length_codec = codec::UviBytes::default();
length_codec.set_max_len(self.max_transmit_size);
Box::pin(future::ok(Framed::new(
socket,
BitswapCodec::new(length_codec, protocol_id),
)))
}
}
pub struct BitswapCodec {
pub length_codec: codec::UviBytes,
pub protocol: ProtocolId,
}
impl fmt::Debug for BitswapCodec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BitswapCodec")
.field("length_codec", &"unsigned_varint::codec::UviBytes")
.field("protocol", &self.protocol)
.finish()
}
}
impl BitswapCodec {
pub fn new(length_codec: codec::UviBytes, protocol: ProtocolId) -> Self {
BitswapCodec {
length_codec,
protocol,
}
}
}
impl Encoder for BitswapCodec {
type Item = BitswapMessage;
type Error = BitswapHandlerError;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
tracing::trace!("sending message protocol: {:?}\n{:?}", self.protocol, item);
let message = match self.protocol {
ProtocolId::Legacy | ProtocolId::Bitswap100 => item.encode_as_proto_v0(),
ProtocolId::Bitswap110 | ProtocolId::Bitswap120 => item.encode_as_proto_v1(),
};
let mut buf = BytesMut::with_capacity(message.encoded_len());
message.encode(&mut buf).expect("fixed target");
self.length_codec
.encode(Bytes::from(buf), dst)
.map_err(|_| BitswapHandlerError::MaxTransmissionSize)
}
}
impl Decoder for BitswapCodec {
type Item = HandlerEvent;
type Error = BitswapHandlerError;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let packet = match self.length_codec.decode(src).map_err(|e| {
if let std::io::ErrorKind::PermissionDenied = e.kind() {
BitswapHandlerError::MaxTransmissionSize
} else {
BitswapHandlerError::Io(e)
}
})? {
Some(p) => p,
None => return Ok(None),
};
let message = BitswapMessage::try_from(packet.freeze())?;
Ok(Some(HandlerEvent::Message {
message,
protocol: self.protocol,
}))
}
}
#[cfg(test)]
mod tests {
use futures::prelude::*;
use libp2p::core::upgrade;
use tokio::net::{TcpListener, TcpStream};
use tokio_util::compat::*;
use super::*;
#[tokio::test]
async fn test_upgrade() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let listener_addr = listener.local_addr().unwrap();
let server = async move {
let (incoming, _) = listener.accept().await.unwrap();
upgrade::apply_inbound(incoming.compat(), ProtocolConfig::default())
.await
.unwrap();
};
let client = async move {
let stream = TcpStream::connect(&listener_addr).await.unwrap();
upgrade::apply_outbound(
stream.compat(),
ProtocolConfig::default(),
upgrade::Version::V1Lazy,
)
.await
.unwrap();
};
future::select(Box::pin(server), Box::pin(client)).await;
}
#[test]
fn test_ord() {
let mut protocols = [
ProtocolId::Bitswap120,
ProtocolId::Bitswap100,
ProtocolId::Legacy,
];
protocols.sort();
assert_eq!(
protocols,
[
ProtocolId::Legacy,
ProtocolId::Bitswap100,
ProtocolId::Bitswap120
]
);
}
}