feat: add ratchet, streaming, SU3 reseed, and router floodfill
- Add ratchet/ with ECIES-X25519-AEAD-Ratchet (Proposal 144), Garlic cloves, and ECIES DatabaseLookup replies - Add streaming/ with Ed25519-signed I2P Streaming (SYN/ACK/NACK/CLOSE/RESET, retransmit, window) and Repliable/Raw Datagrams - Add common/su3.mbt to parse and verify reseed .su3 bundles - Add Elligator2 encoding in crypto/ and OfflineSignature support in LeaseSet2 (flags bit 0) - Router: NTCP2 peer pool, floodfill NetDB crawl, transit tunnel relay, and Garlic/Streaming bridge - cmd/router: add --peer-dir, --su3, --reseed, --floodfill, --no-clock-skew - cmd/client: add --dest for persistent destination keys - Mark Phase 6 complete in README and document the transport scope (NTCP2 only, no SSU2)
This commit is contained in:
1 parent
8eafa11b22
commit
ae72b00323
54 files changed
+9607
-704
No files matched your search
@@ -0,0 +1,122 @@
|
||||
///|
|
||||
/// Canonical I2P Repliable Datagrams (I2CP protocol 17) and Raw Datagrams (I2CP protocol 18).
|
||||
|
||||
///|
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct RepliableDatagram {
|
||||
sender : @common.Destination
|
||||
signature : Bytes
|
||||
payload : Bytes
|
||||
}
|
||||
|
||||
///|
|
||||
/// Signs `payload` directly with Ed25519 `seed` (per I2P Repliable Datagram spec for non-DSA_SHA1).
|
||||
pub fn RepliableDatagram::sign_ed25519(
|
||||
sender : @common.Destination,
|
||||
seed : Bytes,
|
||||
payload : Bytes,
|
||||
) -> RepliableDatagram raise StreamingError {
|
||||
if sender.inner.signing_type() != EdDsaSha512Ed25519 {
|
||||
raise InvalidFormat(
|
||||
"RepliableDatagram sender signing type must be EdDsaSha512Ed25519",
|
||||
)
|
||||
}
|
||||
let signature = @crypto.ed25519_sign(seed, payload) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
{ sender, signature, payload, }
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn RepliableDatagram::verify(self : RepliableDatagram) -> Bool {
|
||||
match self.sender.inner.signing_type() {
|
||||
EdDsaSha512Ed25519 =>
|
||||
@crypto.ed25519_verify(
|
||||
self.sender.inner.signing_public_key(),
|
||||
self.payload,
|
||||
self.signature,
|
||||
)
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn RepliableDatagram::encode(self : RepliableDatagram) -> Bytes {
|
||||
let w = @encoding.Writer::new(
|
||||
capacity=391 + self.signature.length() + self.payload.length(),
|
||||
)
|
||||
self.sender.encode(w)
|
||||
w.write_bytes(self.signature)
|
||||
w.write_bytes(self.payload)
|
||||
w.to_bytes()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn RepliableDatagram::decode(
|
||||
data : Bytes,
|
||||
) -> RepliableDatagram raise StreamingError {
|
||||
let r = @encoding.Reader::new(data)
|
||||
let sender = @common.Destination::decode(r) catch { e => raise Common(e) }
|
||||
let sig_len = sender.inner.signing_type().signature_length()
|
||||
if sig_len <= 0 {
|
||||
raise InvalidFormat("unsupported RepliableDatagram signing type")
|
||||
}
|
||||
let signature = r.read_bytes(sig_len) catch { e => raise Encoding(e) }
|
||||
let payload = r.read_remaining()
|
||||
{ sender, signature, payload, }
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn RepliableDatagram::to_i2cp_bytes(
|
||||
self : RepliableDatagram,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
) -> Bytes {
|
||||
@encoding.i2cp_gzip_wrap(
|
||||
self.encode(),
|
||||
from_port~,
|
||||
to_port~,
|
||||
protocol=b'\x11',
|
||||
)
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn RepliableDatagram::from_i2cp_bytes(
|
||||
i2cp_bytes : Bytes,
|
||||
) -> (@encoding.I2cpGzipHeader, RepliableDatagram) raise StreamingError {
|
||||
let (hdr, raw) = @encoding.i2cp_gzip_unwrap(i2cp_bytes) catch {
|
||||
e => raise Encoding(e)
|
||||
}
|
||||
if hdr.protocol != b'\x11' {
|
||||
raise InvalidFormat(
|
||||
"expected I2CP protocol 17 (Repliable Datagram), got \{hdr.protocol.to_int()}",
|
||||
)
|
||||
}
|
||||
(hdr, RepliableDatagram::decode(raw))
|
||||
}
|
||||
|
||||
///|
|
||||
/// Wraps a raw (non-repliable) datagram in an I2CP Gzip envelope (`protocol = 18`).
|
||||
pub fn encode_raw_datagram(
|
||||
payload : Bytes,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
) -> Bytes {
|
||||
@encoding.i2cp_gzip_wrap(payload, from_port~, to_port~, protocol=b'\x12')
|
||||
}
|
||||
|
||||
///|
|
||||
/// Unwraps an I2CP Gzip raw datagram (`protocol = 18`).
|
||||
pub fn decode_raw_datagram(
|
||||
i2cp_bytes : Bytes,
|
||||
) -> (@encoding.I2cpGzipHeader, Bytes) raise StreamingError {
|
||||
let (hdr, raw) = @encoding.i2cp_gzip_unwrap(i2cp_bytes) catch {
|
||||
e => raise Encoding(e)
|
||||
}
|
||||
if hdr.protocol != b'\x12' {
|
||||
raise InvalidFormat(
|
||||
"expected I2CP protocol 18 (Raw Datagram), got \{hdr.protocol.to_int()}",
|
||||
)
|
||||
}
|
||||
(hdr, raw)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import {
|
||||
"experiments/moon_i2p/encoding",
|
||||
"experiments/moon_i2p/crypto",
|
||||
"experiments/moon_i2p/common",
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
///|
|
||||
/// Canonical I2P Streaming Protocol Packet codec (protocol 6 inside I2CP Gzip envelope).
|
||||
|
||||
///|
|
||||
#derive(Eq, Debug)
|
||||
pub suberror StreamingError {
|
||||
Encoding(@encoding.EncodingError)
|
||||
Common(@common.CommonError)
|
||||
Crypto(@crypto.CryptoError)
|
||||
InvalidFormat(String)
|
||||
InvalidLength(String)
|
||||
InvalidSignature
|
||||
ProtocolError(String)
|
||||
}
|
||||
|
||||
///|
|
||||
pub let flag_synchronize : UInt32 = 0x0001U
|
||||
|
||||
///|
|
||||
pub let flag_close : UInt32 = 0x0002U
|
||||
|
||||
///|
|
||||
pub let flag_reset : UInt32 = 0x0004U
|
||||
|
||||
///|
|
||||
pub let flag_signature_included : UInt32 = 0x0008U
|
||||
|
||||
///|
|
||||
pub let flag_signature_requested : UInt32 = 0x0010U
|
||||
|
||||
///|
|
||||
pub let flag_from_included : UInt32 = 0x0020U
|
||||
|
||||
///|
|
||||
pub let flag_delay_requested : UInt32 = 0x0040U
|
||||
|
||||
///|
|
||||
pub let flag_max_packet_size_included : UInt32 = 0x0080U
|
||||
|
||||
///|
|
||||
pub let flag_profile_interactive : UInt32 = 0x0100U
|
||||
|
||||
///|
|
||||
pub let flag_echo : UInt32 = 0x0200U
|
||||
|
||||
///|
|
||||
pub let flag_no_ack : UInt32 = 0x0400U
|
||||
|
||||
///|
|
||||
pub let flag_offline_signature : UInt32 = 0x0800U
|
||||
|
||||
///|
|
||||
/// Canonical I2P Streaming Packet.
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct StreamingPacket {
|
||||
send_stream_id : UInt32
|
||||
recv_stream_id : UInt32
|
||||
sequence_num : UInt32
|
||||
ack_through : UInt32
|
||||
nacks : Array[UInt32]
|
||||
resend_delay : Byte
|
||||
flags : UInt32
|
||||
delay_requested : UInt32? // Option Order 1 (0x0040)
|
||||
from_dest : @common.Destination? // Option Order 2 (0x0020)
|
||||
max_packet_size : UInt32? // Option Order 3 (0x0080)
|
||||
offline_sig : @common.OfflineSignature? // Option Order 4 (0x0800)
|
||||
signature : Bytes? // Option Order 5 (0x0008)
|
||||
payload : Bytes
|
||||
}
|
||||
|
||||
///|
|
||||
fn serialize_options(
|
||||
pkt : StreamingPacket,
|
||||
zero_sig_len~ : Int32 = -1,
|
||||
) -> Bytes raise StreamingError {
|
||||
let ow = @encoding.Writer::new(capacity=512)
|
||||
if (pkt.flags & flag_delay_requested) != 0U {
|
||||
let d = match pkt.delay_requested {
|
||||
Some(v) => v
|
||||
None =>
|
||||
raise InvalidFormat("DELAY_REQUESTED flag set without delay_requested")
|
||||
}
|
||||
ow.write_u16_be(d)
|
||||
}
|
||||
if (pkt.flags & flag_from_included) != 0U {
|
||||
let dest = match pkt.from_dest {
|
||||
Some(d) => d
|
||||
None => raise InvalidFormat("FROM_INCLUDED flag set without from_dest")
|
||||
}
|
||||
dest.encode(ow)
|
||||
}
|
||||
if (pkt.flags & flag_max_packet_size_included) != 0U {
|
||||
let m = match pkt.max_packet_size {
|
||||
Some(v) => v
|
||||
None =>
|
||||
raise InvalidFormat(
|
||||
"MAX_PACKET_SIZE_INCLUDED flag set without max_packet_size",
|
||||
)
|
||||
}
|
||||
ow.write_u16_be(m)
|
||||
}
|
||||
if (pkt.flags & flag_offline_signature) != 0U {
|
||||
let os = match pkt.offline_sig {
|
||||
Some(o) => o
|
||||
None =>
|
||||
raise InvalidFormat("OFFLINE_SIGNATURE flag set without offline_sig")
|
||||
}
|
||||
os.encode(ow)
|
||||
}
|
||||
if (pkt.flags & flag_signature_included) != 0U {
|
||||
if zero_sig_len > 0 {
|
||||
ow.write_bytes(Bytes::make(zero_sig_len, b'\x00'))
|
||||
} else {
|
||||
let sig = match pkt.signature {
|
||||
Some(s) => s
|
||||
None =>
|
||||
raise InvalidFormat("SIGNATURE_INCLUDED flag set without signature")
|
||||
}
|
||||
ow.write_bytes(sig)
|
||||
}
|
||||
}
|
||||
ow.to_bytes()
|
||||
}
|
||||
|
||||
///|
|
||||
fn encode_with_opt_zero_sig(
|
||||
pkt : StreamingPacket,
|
||||
zero_sig_len~ : Int32 = -1,
|
||||
) -> Bytes raise StreamingError {
|
||||
let opts = serialize_options(pkt, zero_sig_len~)
|
||||
if pkt.nacks.length() > 255 {
|
||||
raise InvalidLength("StreamingPacket nacks exceed 255")
|
||||
}
|
||||
let w = @encoding.Writer::new(
|
||||
capacity=22 + pkt.nacks.length() * 4 + opts.length() + pkt.payload.length(),
|
||||
)
|
||||
w.write_u32_be(pkt.send_stream_id)
|
||||
w.write_u32_be(pkt.recv_stream_id)
|
||||
w.write_u32_be(pkt.sequence_num)
|
||||
w.write_u32_be(pkt.ack_through)
|
||||
w.write_u8(pkt.nacks.length().to_byte())
|
||||
for n in pkt.nacks {
|
||||
w.write_u32_be(n)
|
||||
}
|
||||
w.write_u8(pkt.resend_delay)
|
||||
w.write_u16_be(pkt.flags)
|
||||
w.write_u16_be(opts.length().reinterpret_as_uint())
|
||||
w.write_bytes(opts)
|
||||
w.write_bytes(pkt.payload)
|
||||
w.to_bytes()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn StreamingPacket::encode(
|
||||
self : StreamingPacket,
|
||||
) -> Bytes raise StreamingError {
|
||||
encode_with_opt_zero_sig(self)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Signs the `StreamingPacket` using an Ed25519 32-byte `seed` (over the full packet
|
||||
/// with the 64-byte signature slot zeroed out).
|
||||
pub fn StreamingPacket::sign_ed25519(
|
||||
self : StreamingPacket,
|
||||
seed : Bytes,
|
||||
) -> StreamingPacket raise StreamingError {
|
||||
let with_flag : StreamingPacket = {
|
||||
send_stream_id: self.send_stream_id,
|
||||
recv_stream_id: self.recv_stream_id,
|
||||
sequence_num: self.sequence_num,
|
||||
ack_through: self.ack_through,
|
||||
nacks: self.nacks,
|
||||
resend_delay: self.resend_delay,
|
||||
flags: self.flags | flag_signature_included,
|
||||
delay_requested: self.delay_requested,
|
||||
from_dest: self.from_dest,
|
||||
max_packet_size: self.max_packet_size,
|
||||
offline_sig: self.offline_sig,
|
||||
signature: Some(Bytes::make(64, b'\x00')),
|
||||
payload: self.payload,
|
||||
}
|
||||
let to_sign = encode_with_opt_zero_sig(with_flag, zero_sig_len=64)
|
||||
let sig = @crypto.ed25519_sign(seed, to_sign) catch { e => raise Crypto(e) }
|
||||
{
|
||||
send_stream_id: with_flag.send_stream_id,
|
||||
recv_stream_id: with_flag.recv_stream_id,
|
||||
sequence_num: with_flag.sequence_num,
|
||||
ack_through: with_flag.ack_through,
|
||||
nacks: with_flag.nacks,
|
||||
resend_delay: with_flag.resend_delay,
|
||||
flags: with_flag.flags,
|
||||
delay_requested: with_flag.delay_requested,
|
||||
from_dest: with_flag.from_dest,
|
||||
max_packet_size: with_flag.max_packet_size,
|
||||
offline_sig: with_flag.offline_sig,
|
||||
signature: Some(sig),
|
||||
payload: with_flag.payload,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Verifies the Ed25519 signature of a `StreamingPacket` against `sender_dest`
|
||||
/// (or the embedded `offline_sig.transient_pub_key` when `FLAG_OFFLINE_SIGNATURE` is set).
|
||||
pub fn StreamingPacket::verify_signature(
|
||||
self : StreamingPacket,
|
||||
sender_dest : @common.Destination,
|
||||
) -> Bool {
|
||||
if (self.flags & flag_signature_included) == 0U {
|
||||
return false
|
||||
}
|
||||
let sig = match self.signature {
|
||||
Some(s) => s
|
||||
None => return false
|
||||
}
|
||||
let verify_key = if (self.flags & flag_offline_signature) != 0U {
|
||||
match self.offline_sig {
|
||||
Some(os) => {
|
||||
if os.transient_sig_type != EdDsaSha512Ed25519 ||
|
||||
sender_dest.inner.signing_type() != EdDsaSha512Ed25519 {
|
||||
return false
|
||||
}
|
||||
if !os.verify_ed25519(sender_dest.inner.signing_public_key()) {
|
||||
return false
|
||||
}
|
||||
os.transient_pub_key
|
||||
}
|
||||
None => return false
|
||||
}
|
||||
} else {
|
||||
if sender_dest.inner.signing_type() != EdDsaSha512Ed25519 {
|
||||
return false
|
||||
}
|
||||
sender_dest.inner.signing_public_key()
|
||||
}
|
||||
let to_verify = encode_with_opt_zero_sig(self, zero_sig_len=sig.length()) catch {
|
||||
_ => return false
|
||||
}
|
||||
@crypto.ed25519_verify(verify_key, to_verify, sig)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Decodes a canonical I2P Streaming Packet.
|
||||
/// Pass `peer_sig_type` if `FROM_INCLUDED` is not set in the packet so the signature length is known.
|
||||
pub fn StreamingPacket::decode(
|
||||
data : Bytes,
|
||||
peer_sig_type~ : @common.SigningPublicKeyType = EdDsaSha512Ed25519,
|
||||
) -> StreamingPacket raise StreamingError {
|
||||
if data.length() < 22 {
|
||||
raise InvalidLength(
|
||||
"StreamingPacket shorter than 22 bytes: \{data.length()}",
|
||||
)
|
||||
}
|
||||
let r = @encoding.Reader::new(data)
|
||||
let send_stream_id = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
let recv_stream_id = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
let sequence_num = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
let ack_through = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
let nack_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
|
||||
let nacks : Array[UInt32] = Array(capacity=nack_count)
|
||||
for _i = 0; _i < nack_count; _i = _i + 1 {
|
||||
nacks.push(r.read_u32_be() catch { e => raise Encoding(e) })
|
||||
}
|
||||
let resend_delay = r.read_u8() catch { e => raise Encoding(e) }
|
||||
let flags = r.read_u16_be() catch { e => raise Encoding(e) }
|
||||
let opt_size = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
|
||||
let opt_bytes = r.read_bytes(opt_size) catch { e => raise Encoding(e) }
|
||||
let payload = r.read_remaining()
|
||||
|
||||
let or = @encoding.Reader::new(opt_bytes)
|
||||
let delay_requested = if (flags & flag_delay_requested) != 0U {
|
||||
Some(or.read_u16_be() catch { e => raise Encoding(e) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let from_dest = if (flags & flag_from_included) != 0U {
|
||||
Some(@common.Destination::decode(or) catch { e => raise Common(e) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let max_packet_size = if (flags & flag_max_packet_size_included) != 0U {
|
||||
Some(or.read_u16_be() catch { e => raise Encoding(e) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let effective_sig_type = match from_dest {
|
||||
Some(d) => d.inner.signing_type()
|
||||
None => peer_sig_type
|
||||
}
|
||||
let offline_sig = if (flags & flag_offline_signature) != 0U {
|
||||
Some(
|
||||
@common.OfflineSignature::decode(or, effective_sig_type) catch {
|
||||
e => raise Common(e)
|
||||
},
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let signature = if (flags & flag_signature_included) != 0U {
|
||||
let sig_len = match offline_sig {
|
||||
Some(os) => os.transient_sig_type.signature_length()
|
||||
None => effective_sig_type.signature_length()
|
||||
}
|
||||
if sig_len <= 0 {
|
||||
Some(or.read_remaining())
|
||||
} else {
|
||||
Some(or.read_bytes(sig_len) catch { e => raise Encoding(e) })
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
{
|
||||
send_stream_id,
|
||||
recv_stream_id,
|
||||
sequence_num,
|
||||
ack_through,
|
||||
nacks,
|
||||
resend_delay,
|
||||
flags,
|
||||
delay_requested,
|
||||
from_dest,
|
||||
max_packet_size,
|
||||
offline_sig,
|
||||
signature,
|
||||
payload,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Wraps a `StreamingPacket` inside an I2CP Gzip envelope (`protocol = 6`).
|
||||
pub fn encode_i2cp_streaming(
|
||||
pkt : StreamingPacket,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
) -> Bytes raise StreamingError {
|
||||
let raw = pkt.encode()
|
||||
@encoding.i2cp_gzip_wrap(raw, from_port~, to_port~, protocol=b'\x06')
|
||||
}
|
||||
|
||||
///|
|
||||
/// Unwraps an I2CP Gzip envelope and decodes a `StreamingPacket` (verifying `protocol == 6`).
|
||||
pub fn decode_i2cp_streaming(
|
||||
i2cp_bytes : Bytes,
|
||||
peer_sig_type~ : @common.SigningPublicKeyType = EdDsaSha512Ed25519,
|
||||
) -> (@encoding.I2cpGzipHeader, StreamingPacket) raise StreamingError {
|
||||
let (hdr, raw) = @encoding.i2cp_gzip_unwrap(i2cp_bytes) catch {
|
||||
e => raise Encoding(e)
|
||||
}
|
||||
if hdr.protocol != b'\x06' {
|
||||
raise InvalidFormat(
|
||||
"expected I2CP protocol 6 (Streaming), got \{hdr.protocol.to_int()}",
|
||||
)
|
||||
}
|
||||
(hdr, StreamingPacket::decode(raw, peer_sig_type~))
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "experiments/moon_i2p/streaming"
|
||||
|
||||
import {
|
||||
"experiments/moon_i2p/common",
|
||||
"experiments/moon_i2p/crypto",
|
||||
"experiments/moon_i2p/encoding",
|
||||
"moonbitlang/core/debug",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub fn decode_i2cp_streaming(Bytes, peer_sig_type? : @common.SigningPublicKeyType) -> (@encoding.I2cpGzipHeader, StreamingPacket) raise StreamingError
|
||||
|
||||
pub fn decode_raw_datagram(Bytes) -> (@encoding.I2cpGzipHeader, Bytes) raise StreamingError
|
||||
|
||||
pub fn encode_i2cp_streaming(StreamingPacket, from_port? : UInt32, to_port? : UInt32) -> Bytes raise StreamingError
|
||||
|
||||
pub fn encode_raw_datagram(Bytes, from_port? : UInt32, to_port? : UInt32) -> Bytes
|
||||
|
||||
pub let flag_close : UInt32
|
||||
|
||||
pub let flag_delay_requested : UInt32
|
||||
|
||||
pub let flag_echo : UInt32
|
||||
|
||||
pub let flag_from_included : UInt32
|
||||
|
||||
pub let flag_max_packet_size_included : UInt32
|
||||
|
||||
pub let flag_no_ack : UInt32
|
||||
|
||||
pub let flag_offline_signature : UInt32
|
||||
|
||||
pub let flag_profile_interactive : UInt32
|
||||
|
||||
pub let flag_reset : UInt32
|
||||
|
||||
pub let flag_signature_included : UInt32
|
||||
|
||||
pub let flag_signature_requested : UInt32
|
||||
|
||||
pub let flag_synchronize : UInt32
|
||||
|
||||
// Errors
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub suberror StreamingError {
|
||||
Encoding(@encoding.EncodingError)
|
||||
Common(@common.CommonError)
|
||||
Crypto(@crypto.CryptoError)
|
||||
InvalidFormat(String)
|
||||
InvalidLength(String)
|
||||
InvalidSignature
|
||||
ProtocolError(String)
|
||||
}
|
||||
|
||||
// Types and methods
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) struct RepliableDatagram {
|
||||
sender : @common.Destination
|
||||
signature : Bytes
|
||||
payload : Bytes
|
||||
}
|
||||
pub fn RepliableDatagram::decode(Bytes) -> Self raise StreamingError
|
||||
pub fn RepliableDatagram::encode(Self) -> Bytes
|
||||
pub fn RepliableDatagram::from_i2cp_bytes(Bytes) -> (@encoding.I2cpGzipHeader, Self) raise StreamingError
|
||||
pub fn RepliableDatagram::sign_ed25519(@common.Destination, Bytes, Bytes) -> Self raise StreamingError
|
||||
pub fn RepliableDatagram::to_i2cp_bytes(Self, from_port? : UInt32, to_port? : UInt32) -> Bytes
|
||||
pub fn RepliableDatagram::verify(Self) -> Bool
|
||||
|
||||
pub struct StreamConnection {
|
||||
local_dest : @common.Destination
|
||||
local_ed_seed : Bytes
|
||||
mut remote_dest : @common.Destination?
|
||||
mut remote_hash : @common.Hash
|
||||
from_port : UInt32
|
||||
to_port : UInt32
|
||||
send_stream_id : UInt32
|
||||
mut recv_stream_id : UInt32
|
||||
mut state : StreamState
|
||||
mut next_send_seq : UInt32
|
||||
mut highest_acked_seq : UInt32
|
||||
mut has_acked : Bool
|
||||
mut next_recv_seq : UInt32
|
||||
mut ack_through : UInt32
|
||||
mut has_recv_syn : Bool
|
||||
mut max_packet_size : UInt32
|
||||
window_size : Int32
|
||||
ooo_recv : Array[(UInt32, Bytes)]
|
||||
recv_buf : Array[Byte]
|
||||
mut peer_closed : Bool
|
||||
out_queue : Array[Bytes]
|
||||
// private fields
|
||||
}
|
||||
pub fn StreamConnection::accept_syn(@common.Destination, Bytes, StreamingPacket, UInt32, UInt64, from_port? : UInt32, to_port? : UInt32) -> Self raise StreamingError
|
||||
pub fn StreamConnection::close(Self, UInt64) -> Unit raise StreamingError
|
||||
pub fn StreamConnection::connect(@common.Destination, Bytes, @common.Hash, UInt32, UInt64, from_port? : UInt32, to_port? : UInt32, max_packet_size? : UInt32) -> Self raise StreamingError
|
||||
pub fn StreamConnection::drain_outbound(Self) -> Array[Bytes]
|
||||
pub fn StreamConnection::has_unacked(Self) -> Bool
|
||||
pub fn StreamConnection::is_eof(Self) -> Bool
|
||||
pub fn StreamConnection::on_packet(Self, StreamingPacket, UInt64) -> Unit raise StreamingError
|
||||
pub fn StreamConnection::poll_retransmits(Self, UInt64, rto_ms? : UInt64) -> Unit raise StreamingError
|
||||
pub fn StreamConnection::read_available(Self) -> Bytes
|
||||
pub fn StreamConnection::write(Self, Bytes, UInt64) -> Int32 raise StreamingError
|
||||
|
||||
pub struct StreamManager {
|
||||
local_dest : @common.Destination
|
||||
local_ed_seed : Bytes
|
||||
mut next_stream_id : UInt32
|
||||
streams : Array[StreamConnection]
|
||||
pending_accept : Array[StreamConnection]
|
||||
incoming_datagrams : Array[RepliableDatagram]
|
||||
}
|
||||
pub fn StreamManager::accept_next(Self) -> StreamConnection?
|
||||
pub fn StreamManager::connect(Self, @common.Hash, UInt64, from_port? : UInt32, to_port? : UInt32) -> StreamConnection raise StreamingError
|
||||
pub fn StreamManager::handle_incoming_i2cp(Self, Bytes, UInt64) -> StreamConnection? raise StreamingError
|
||||
pub fn StreamManager::new(@common.Destination, Bytes, initial_stream_id? : UInt32) -> Self
|
||||
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) enum StreamState {
|
||||
SynSent
|
||||
SynReceived
|
||||
Established
|
||||
Closing
|
||||
Closed
|
||||
Reset
|
||||
}
|
||||
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) struct StreamingPacket {
|
||||
send_stream_id : UInt32
|
||||
recv_stream_id : UInt32
|
||||
sequence_num : UInt32
|
||||
ack_through : UInt32
|
||||
nacks : Array[UInt32]
|
||||
resend_delay : Byte
|
||||
flags : UInt32
|
||||
delay_requested : UInt32?
|
||||
from_dest : @common.Destination?
|
||||
max_packet_size : UInt32?
|
||||
offline_sig : @common.OfflineSignature?
|
||||
signature : Bytes?
|
||||
payload : Bytes
|
||||
}
|
||||
pub fn StreamingPacket::decode(Bytes, peer_sig_type? : @common.SigningPublicKeyType) -> Self raise StreamingError
|
||||
pub fn StreamingPacket::encode(Self) -> Bytes raise StreamingError
|
||||
pub fn StreamingPacket::sign_ed25519(Self, Bytes) -> Self raise StreamingError
|
||||
pub fn StreamingPacket::verify_signature(Self, @common.Destination) -> Bool
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,673 @@
|
||||
///|
|
||||
/// Reliable sliding-window I2P Streaming connection & session stream manager.
|
||||
|
||||
///|
|
||||
#derive(Eq, Debug)
|
||||
pub(all) enum StreamState {
|
||||
SynSent
|
||||
SynReceived
|
||||
Established
|
||||
Closing
|
||||
Closed
|
||||
Reset
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct UnackedPacket {
|
||||
seq : UInt32
|
||||
pkt : StreamingPacket
|
||||
mut last_sent_ms : UInt64
|
||||
}
|
||||
|
||||
///|
|
||||
/// Single reliable bidirectional I2P Streaming connection.
|
||||
pub struct StreamConnection {
|
||||
local_dest : @common.Destination
|
||||
local_ed_seed : Bytes
|
||||
mut remote_dest : @common.Destination?
|
||||
mut remote_hash : @common.Hash
|
||||
from_port : UInt32
|
||||
to_port : UInt32
|
||||
send_stream_id : UInt32
|
||||
mut recv_stream_id : UInt32
|
||||
mut state : StreamState
|
||||
mut next_send_seq : UInt32
|
||||
mut highest_acked_seq : UInt32
|
||||
mut has_acked : Bool
|
||||
mut next_recv_seq : UInt32
|
||||
mut ack_through : UInt32
|
||||
mut has_recv_syn : Bool
|
||||
mut max_packet_size : UInt32
|
||||
window_size : Int32
|
||||
priv unacked : Array[UnackedPacket]
|
||||
ooo_recv : Array[(UInt32, Bytes)]
|
||||
recv_buf : Array[Byte]
|
||||
mut peer_closed : Bool
|
||||
out_queue : Array[Bytes]
|
||||
}
|
||||
|
||||
///|
|
||||
fn slice_bytes(data : Bytes, start : Int32, len : Int32) -> Bytes {
|
||||
let out = FixedArray::make(len, b'\x00')
|
||||
for i = 0; i < len; i = i + 1 {
|
||||
out[i] = data[start + i]
|
||||
}
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamConnection::queue_packet(
|
||||
self : StreamConnection,
|
||||
pkt : StreamingPacket,
|
||||
now_ms : UInt64,
|
||||
track_unacked~ : Bool = true,
|
||||
) -> Unit raise StreamingError {
|
||||
if track_unacked {
|
||||
self.unacked.push({ seq: pkt.sequence_num, pkt, last_sent_ms: now_ms, })
|
||||
}
|
||||
self.out_queue.push(
|
||||
encode_i2cp_streaming(pkt, from_port=self.from_port, to_port=self.to_port),
|
||||
)
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamConnection::current_nacks(self : StreamConnection) -> Array[UInt32] {
|
||||
if self.ooo_recv.length() == 0 {
|
||||
return []
|
||||
}
|
||||
let mut max_seen = self.next_recv_seq
|
||||
for entry in self.ooo_recv {
|
||||
if entry.0 > max_seen {
|
||||
max_seen = entry.0
|
||||
}
|
||||
}
|
||||
let nacks : Array[UInt32] = []
|
||||
let mut s = self.next_recv_seq
|
||||
while s < max_seen && nacks.length() < 32 {
|
||||
let mut found = false
|
||||
for entry in self.ooo_recv {
|
||||
if entry.0 == s {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
nacks.push(s)
|
||||
}
|
||||
s = s + 1U
|
||||
}
|
||||
nacks
|
||||
}
|
||||
|
||||
///|
|
||||
/// Creates a new outbound `StreamConnection` and queues its signed `SYN` packet.
|
||||
pub fn StreamConnection::connect(
|
||||
local_dest : @common.Destination,
|
||||
local_ed_seed : Bytes,
|
||||
remote_hash : @common.Hash,
|
||||
send_stream_id : UInt32,
|
||||
now_ms : UInt64,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
max_packet_size~ : UInt32 = 1730U,
|
||||
) -> StreamConnection raise StreamingError {
|
||||
let conn : StreamConnection = {
|
||||
local_dest,
|
||||
local_ed_seed,
|
||||
remote_dest: None,
|
||||
remote_hash,
|
||||
from_port,
|
||||
to_port,
|
||||
send_stream_id,
|
||||
recv_stream_id: 0U,
|
||||
state: SynSent,
|
||||
next_send_seq: 1U,
|
||||
highest_acked_seq: 0U,
|
||||
has_acked: false,
|
||||
next_recv_seq: 0U,
|
||||
ack_through: 0U,
|
||||
has_recv_syn: false,
|
||||
max_packet_size,
|
||||
window_size: 16,
|
||||
unacked: [],
|
||||
ooo_recv: [],
|
||||
recv_buf: [],
|
||||
peer_closed: false,
|
||||
out_queue: [],
|
||||
}
|
||||
let syn : StreamingPacket = {
|
||||
send_stream_id,
|
||||
recv_stream_id: 0U,
|
||||
sequence_num: 0U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
resend_delay: b'\x00',
|
||||
flags: flag_synchronize |
|
||||
flag_from_included |
|
||||
flag_signature_included |
|
||||
flag_max_packet_size_included |
|
||||
flag_no_ack,
|
||||
delay_requested: None,
|
||||
from_dest: Some(local_dest),
|
||||
max_packet_size: Some(max_packet_size),
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"",
|
||||
}
|
||||
let signed_syn = syn.sign_ed25519(local_ed_seed)
|
||||
conn.queue_packet(signed_syn, now_ms)
|
||||
conn
|
||||
}
|
||||
|
||||
///|
|
||||
/// Creates an inbound `StreamConnection` from a verified incoming `SYN` packet and queues `SYN-ACK`.
|
||||
pub fn StreamConnection::accept_syn(
|
||||
local_dest : @common.Destination,
|
||||
local_ed_seed : Bytes,
|
||||
syn_pkt : StreamingPacket,
|
||||
send_stream_id : UInt32,
|
||||
now_ms : UInt64,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
) -> StreamConnection raise StreamingError {
|
||||
let peer_dest = match syn_pkt.from_dest {
|
||||
Some(d) => d
|
||||
None => raise InvalidFormat("incoming SYN missing FROM_INCLUDED")
|
||||
}
|
||||
if !syn_pkt.verify_signature(peer_dest) {
|
||||
raise InvalidSignature
|
||||
}
|
||||
let peer_mtu = match syn_pkt.max_packet_size {
|
||||
Some(m) if m >= 512U && m <= 1730U => m
|
||||
_ => 1730U
|
||||
}
|
||||
let conn : StreamConnection = {
|
||||
local_dest,
|
||||
local_ed_seed,
|
||||
remote_dest: Some(peer_dest),
|
||||
remote_hash: peer_dest.hash(),
|
||||
from_port,
|
||||
to_port,
|
||||
send_stream_id,
|
||||
recv_stream_id: syn_pkt.send_stream_id,
|
||||
state: Established,
|
||||
next_send_seq: 1U,
|
||||
highest_acked_seq: 0U,
|
||||
has_acked: false,
|
||||
next_recv_seq: 1U,
|
||||
ack_through: 0U,
|
||||
has_recv_syn: true,
|
||||
max_packet_size: peer_mtu,
|
||||
window_size: 16,
|
||||
unacked: [],
|
||||
ooo_recv: [],
|
||||
recv_buf: [],
|
||||
peer_closed: false,
|
||||
out_queue: [],
|
||||
}
|
||||
if syn_pkt.payload.length() > 0 {
|
||||
for i = 0; i < syn_pkt.payload.length(); i = i + 1 {
|
||||
conn.recv_buf.push(syn_pkt.payload[i])
|
||||
}
|
||||
}
|
||||
let syn_ack : StreamingPacket = {
|
||||
send_stream_id,
|
||||
recv_stream_id: syn_pkt.send_stream_id,
|
||||
sequence_num: 0U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
resend_delay: b'\x00',
|
||||
flags: flag_synchronize |
|
||||
flag_from_included |
|
||||
flag_signature_included |
|
||||
flag_max_packet_size_included,
|
||||
delay_requested: None,
|
||||
from_dest: Some(local_dest),
|
||||
max_packet_size: Some(peer_mtu),
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"",
|
||||
}
|
||||
let signed_ack = syn_ack.sign_ed25519(local_ed_seed)
|
||||
conn.queue_packet(signed_ack, now_ms)
|
||||
conn
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamConnection::process_acks(
|
||||
self : StreamConnection,
|
||||
pkt : StreamingPacket,
|
||||
now_ms : UInt64,
|
||||
) -> Unit raise StreamingError {
|
||||
if (pkt.flags & flag_no_ack) != 0U {
|
||||
return
|
||||
}
|
||||
let ack_through = pkt.ack_through
|
||||
if !self.has_acked || ack_through > self.highest_acked_seq {
|
||||
self.has_acked = true
|
||||
self.highest_acked_seq = ack_through
|
||||
}
|
||||
let mut i = 0
|
||||
while i < self.unacked.length() {
|
||||
let seq = self.unacked[i].seq
|
||||
if seq <= ack_through {
|
||||
let mut is_nacked = false
|
||||
for n in pkt.nacks {
|
||||
if n == seq {
|
||||
is_nacked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !is_nacked {
|
||||
let _ = self.unacked.remove(i)
|
||||
continue
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
// Retransmit explicitly NACKed packets immediately
|
||||
for n in pkt.nacks {
|
||||
for u in self.unacked {
|
||||
if u.seq == n {
|
||||
u.last_sent_ms = now_ms
|
||||
self.out_queue.push(
|
||||
encode_i2cp_streaming(
|
||||
u.pkt,
|
||||
from_port=self.from_port,
|
||||
to_port=self.to_port,
|
||||
),
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamConnection::drain_ooo_in_order(self : StreamConnection) -> Unit {
|
||||
while true {
|
||||
let mut matched = -1
|
||||
for i = 0; i < self.ooo_recv.length(); i = i + 1 {
|
||||
if self.ooo_recv[i].0 == self.next_recv_seq {
|
||||
matched = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched < 0 {
|
||||
break
|
||||
}
|
||||
let chunk = self.ooo_recv[matched].1
|
||||
let _ = self.ooo_recv.remove(matched)
|
||||
for j = 0; j < chunk.length(); j = j + 1 {
|
||||
self.recv_buf.push(chunk[j])
|
||||
}
|
||||
self.ack_through = self.next_recv_seq
|
||||
self.next_recv_seq = self.next_recv_seq + 1U
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamConnection::send_ack(
|
||||
self : StreamConnection,
|
||||
now_ms : UInt64,
|
||||
) -> Unit raise StreamingError {
|
||||
let ack_pkt : StreamingPacket = {
|
||||
send_stream_id: self.send_stream_id,
|
||||
recv_stream_id: self.recv_stream_id,
|
||||
sequence_num: 0U,
|
||||
ack_through: self.ack_through,
|
||||
nacks: self.current_nacks(),
|
||||
resend_delay: b'\x00',
|
||||
flags: 0U,
|
||||
delay_requested: None,
|
||||
from_dest: None,
|
||||
max_packet_size: None,
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"",
|
||||
}
|
||||
self.queue_packet(ack_pkt, now_ms, track_unacked=false)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Processes an incoming decoded `StreamingPacket` addressed to this stream.
|
||||
pub fn StreamConnection::on_packet(
|
||||
self : StreamConnection,
|
||||
pkt : StreamingPacket,
|
||||
now_ms : UInt64,
|
||||
) -> Unit raise StreamingError {
|
||||
if (pkt.flags & flag_reset) != 0U {
|
||||
match self.remote_dest {
|
||||
Some(d) =>
|
||||
if (pkt.flags & flag_signature_included) != 0U &&
|
||||
!pkt.verify_signature(d) {
|
||||
raise InvalidSignature
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
self.state = Reset
|
||||
self.peer_closed = true
|
||||
return
|
||||
}
|
||||
if (pkt.flags & flag_synchronize) != 0U && self.state == SynSent {
|
||||
let peer_dest = match pkt.from_dest {
|
||||
Some(d) => d
|
||||
None => raise InvalidFormat("SYN-ACK missing FROM_INCLUDED")
|
||||
}
|
||||
if !pkt.verify_signature(peer_dest) {
|
||||
raise InvalidSignature
|
||||
}
|
||||
self.remote_dest = Some(peer_dest)
|
||||
self.remote_hash = peer_dest.hash()
|
||||
self.recv_stream_id = pkt.send_stream_id
|
||||
match pkt.max_packet_size {
|
||||
Some(m) if m >= 512U && m < self.max_packet_size =>
|
||||
self.max_packet_size = m
|
||||
_ => ()
|
||||
}
|
||||
self.has_recv_syn = true
|
||||
self.ack_through = 0U
|
||||
self.next_recv_seq = 1U
|
||||
self.state = Established
|
||||
self.process_acks(pkt, now_ms)
|
||||
if pkt.payload.length() > 0 {
|
||||
for i = 0; i < pkt.payload.length(); i = i + 1 {
|
||||
self.recv_buf.push(pkt.payload[i])
|
||||
}
|
||||
}
|
||||
self.send_ack(now_ms)
|
||||
return
|
||||
}
|
||||
|
||||
self.process_acks(pkt, now_ms)
|
||||
|
||||
if (pkt.flags & flag_close) != 0U {
|
||||
match self.remote_dest {
|
||||
Some(d) => if !pkt.verify_signature(d) { raise InvalidSignature }
|
||||
None => ()
|
||||
}
|
||||
self.peer_closed = true
|
||||
if self.state == Closing {
|
||||
self.state = Closed
|
||||
}
|
||||
}
|
||||
|
||||
let seq = pkt.sequence_num
|
||||
let has_data = pkt.payload.length() > 0 || (pkt.flags & flag_close) != 0U
|
||||
if seq > 0U && has_data {
|
||||
if seq == self.next_recv_seq {
|
||||
for i = 0; i < pkt.payload.length(); i = i + 1 {
|
||||
self.recv_buf.push(pkt.payload[i])
|
||||
}
|
||||
self.ack_through = seq
|
||||
self.next_recv_seq = seq + 1U
|
||||
self.drain_ooo_in_order()
|
||||
self.send_ack(now_ms)
|
||||
} else if seq > self.next_recv_seq {
|
||||
let mut dup = false
|
||||
for e in self.ooo_recv {
|
||||
if e.0 == seq {
|
||||
dup = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !dup {
|
||||
self.ooo_recv.push((seq, pkt.payload))
|
||||
}
|
||||
self.send_ack(now_ms)
|
||||
} else {
|
||||
// Duplicate old seq: re-ACK so sender stops retransmitting
|
||||
self.send_ack(now_ms)
|
||||
}
|
||||
} else if (pkt.flags & flag_close) != 0U {
|
||||
self.send_ack(now_ms)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Queues application `data` split into `max_packet_size` Streaming packets.
|
||||
pub fn StreamConnection::write(
|
||||
self : StreamConnection,
|
||||
data : Bytes,
|
||||
now_ms : UInt64,
|
||||
) -> Int32 raise StreamingError {
|
||||
if self.state != Established && self.state != SynSent {
|
||||
raise ProtocolError("cannot write on closed or reset stream")
|
||||
}
|
||||
if data.length() == 0 {
|
||||
return 0
|
||||
}
|
||||
let mtu = self.max_packet_size.reinterpret_as_int()
|
||||
let mut off = 0
|
||||
while off < data.length() && self.unacked.length() < self.window_size {
|
||||
let rem = data.length() - off
|
||||
let take = if rem < mtu { rem } else { mtu }
|
||||
let chunk = slice_bytes(data, off, take)
|
||||
let seq = self.next_send_seq
|
||||
self.next_send_seq = seq + 1U
|
||||
let flags = if self.has_recv_syn { 0U } else { flag_no_ack }
|
||||
let pkt : StreamingPacket = {
|
||||
send_stream_id: self.send_stream_id,
|
||||
recv_stream_id: self.recv_stream_id,
|
||||
sequence_num: seq,
|
||||
ack_through: self.ack_through,
|
||||
nacks: self.current_nacks(),
|
||||
resend_delay: b'\x00',
|
||||
flags,
|
||||
delay_requested: None,
|
||||
from_dest: None,
|
||||
max_packet_size: None,
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: chunk,
|
||||
}
|
||||
self.queue_packet(pkt, now_ms)
|
||||
off += take
|
||||
}
|
||||
off
|
||||
}
|
||||
|
||||
///|
|
||||
/// Drains all in-order received bytes available for the application.
|
||||
pub fn StreamConnection::read_available(self : StreamConnection) -> Bytes {
|
||||
if self.recv_buf.length() == 0 {
|
||||
return b""
|
||||
}
|
||||
let out = Bytes::from_array(self.recv_buf)
|
||||
self.recv_buf.clear()
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
/// Returns `true` if the peer has closed/reset and all buffered incoming bytes have been read.
|
||||
pub fn StreamConnection::is_eof(self : StreamConnection) -> Bool {
|
||||
self.peer_closed && self.recv_buf.length() == 0
|
||||
}
|
||||
|
||||
///|
|
||||
/// Queues a signed `CLOSE` packet.
|
||||
pub fn StreamConnection::close(
|
||||
self : StreamConnection,
|
||||
now_ms : UInt64,
|
||||
) -> Unit raise StreamingError {
|
||||
if self.state == Closed || self.state == Reset {
|
||||
return
|
||||
}
|
||||
let seq = self.next_send_seq
|
||||
self.next_send_seq = seq + 1U
|
||||
let pkt : StreamingPacket = {
|
||||
send_stream_id: self.send_stream_id,
|
||||
recv_stream_id: self.recv_stream_id,
|
||||
sequence_num: seq,
|
||||
ack_through: self.ack_through,
|
||||
nacks: self.current_nacks(),
|
||||
resend_delay: b'\x00',
|
||||
flags: flag_close |
|
||||
flag_signature_included |
|
||||
(if self.has_recv_syn { 0U } else { flag_no_ack }),
|
||||
delay_requested: None,
|
||||
from_dest: None,
|
||||
max_packet_size: None,
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"",
|
||||
}
|
||||
let signed = pkt.sign_ed25519(self.local_ed_seed)
|
||||
self.queue_packet(signed, now_ms)
|
||||
self.state = if self.peer_closed { Closed } else { Closing }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Re-queues any unacked packets whose RTO has expired.
|
||||
pub fn StreamConnection::poll_retransmits(
|
||||
self : StreamConnection,
|
||||
now_ms : UInt64,
|
||||
rto_ms~ : UInt64 = 1500UL,
|
||||
) -> Unit raise StreamingError {
|
||||
for u in self.unacked {
|
||||
if now_ms >= u.last_sent_ms + rto_ms {
|
||||
u.last_sent_ms = now_ms
|
||||
self.out_queue.push(
|
||||
encode_i2cp_streaming(
|
||||
u.pkt,
|
||||
from_port=self.from_port,
|
||||
to_port=self.to_port,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Drains all outbound I2CP-wrapped Streaming packets queued by this connection.
|
||||
pub fn StreamConnection::drain_outbound(
|
||||
self : StreamConnection,
|
||||
) -> Array[Bytes] {
|
||||
let out : Array[Bytes] = Array(capacity=self.out_queue.length())
|
||||
for p in self.out_queue {
|
||||
out.push(p)
|
||||
}
|
||||
self.out_queue.clear()
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
/// Per-destination stream & repliable datagram multiplexer.
|
||||
pub struct StreamManager {
|
||||
local_dest : @common.Destination
|
||||
local_ed_seed : Bytes
|
||||
mut next_stream_id : UInt32
|
||||
streams : Array[StreamConnection]
|
||||
pending_accept : Array[StreamConnection]
|
||||
incoming_datagrams : Array[RepliableDatagram]
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn StreamManager::new(
|
||||
local_dest : @common.Destination,
|
||||
local_ed_seed : Bytes,
|
||||
initial_stream_id~ : UInt32 = 1000U,
|
||||
) -> StreamManager {
|
||||
{
|
||||
local_dest,
|
||||
local_ed_seed,
|
||||
next_stream_id: initial_stream_id,
|
||||
streams: [],
|
||||
pending_accept: [],
|
||||
incoming_datagrams: [],
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamManager::alloc_stream_id(self : StreamManager) -> UInt32 {
|
||||
let id = self.next_stream_id
|
||||
self.next_stream_id = id + 1U
|
||||
if self.next_stream_id == 0U {
|
||||
self.next_stream_id = 1U
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
///|
|
||||
/// Returns `true` if any unacknowledged outbound packets remain pending.
|
||||
pub fn StreamConnection::has_unacked(self : StreamConnection) -> Bool {
|
||||
self.unacked.length() > 0
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn StreamManager::connect(
|
||||
self : StreamManager,
|
||||
remote_hash : @common.Hash,
|
||||
now_ms : UInt64,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
) -> StreamConnection raise StreamingError {
|
||||
let sid = self.alloc_stream_id()
|
||||
let conn = StreamConnection::connect(
|
||||
self.local_dest,
|
||||
self.local_ed_seed,
|
||||
remote_hash,
|
||||
sid,
|
||||
now_ms,
|
||||
from_port~,
|
||||
to_port~,
|
||||
)
|
||||
self.streams.push(conn)
|
||||
conn
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn StreamManager::accept_next(self : StreamManager) -> StreamConnection? {
|
||||
if self.pending_accept.length() == 0 {
|
||||
return None
|
||||
}
|
||||
Some(self.pending_accept.remove(0))
|
||||
}
|
||||
|
||||
///|
|
||||
/// Dispatches an incoming I2CP Gzip-wrapped payload (Streaming proto 6 or Repliable Datagram proto 17)
|
||||
/// and returns the matching `StreamConnection` if it belongs to a stream.
|
||||
pub fn StreamManager::handle_incoming_i2cp(
|
||||
self : StreamManager,
|
||||
i2cp_bytes : Bytes,
|
||||
now_ms : UInt64,
|
||||
) -> StreamConnection? raise StreamingError {
|
||||
let (hdr, raw) = @encoding.i2cp_gzip_unwrap(i2cp_bytes) catch {
|
||||
e => raise Encoding(e)
|
||||
}
|
||||
if hdr.protocol == b'\x11' {
|
||||
let dg = RepliableDatagram::decode(raw)
|
||||
if dg.verify() {
|
||||
self.incoming_datagrams.push(dg)
|
||||
}
|
||||
return None
|
||||
}
|
||||
if hdr.protocol != b'\x06' {
|
||||
return None
|
||||
}
|
||||
let pkt = StreamingPacket::decode(raw)
|
||||
if pkt.recv_stream_id != 0U {
|
||||
for s in self.streams {
|
||||
if s.send_stream_id == pkt.recv_stream_id {
|
||||
s.on_packet(pkt, now_ms)
|
||||
return Some(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pkt.flags & flag_synchronize) != 0U && pkt.recv_stream_id == 0U {
|
||||
let sid = self.alloc_stream_id()
|
||||
let conn = StreamConnection::accept_syn(
|
||||
self.local_dest,
|
||||
self.local_ed_seed,
|
||||
pkt,
|
||||
sid,
|
||||
now_ms,
|
||||
from_port=hdr.to_port,
|
||||
to_port=hdr.from_port,
|
||||
)
|
||||
self.streams.push(conn)
|
||||
self.pending_accept.push(conn)
|
||||
return Some(conn)
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
///|
|
||||
fn make_test_identity(seed_byte : Byte) -> (@common.Destination, Bytes) {
|
||||
let ed_seed = Bytes::make(32, seed_byte)
|
||||
let ed_pub = try! @crypto.ed25519_public_key(ed_seed)
|
||||
let x_pub = try! @crypto.x25519_public_key(
|
||||
Bytes::make(32, (seed_byte.to_int() ^ 0x33).to_byte()),
|
||||
)
|
||||
let dest = try! @common.Destination::new_x25519_ed25519(x_pub, ed_pub)
|
||||
(dest, ed_seed)
|
||||
}
|
||||
|
||||
///|
|
||||
test "StreamingPacket Ed25519 sign/verify, option order, and I2CP gzip wrap" {
|
||||
let (dest, ed_seed) = make_test_identity(b'\x11')
|
||||
let pkt : @streaming.StreamingPacket = {
|
||||
send_stream_id: 100U,
|
||||
recv_stream_id: 200U,
|
||||
sequence_num: 0U,
|
||||
ack_through: 0U,
|
||||
nacks: [1U, 3U],
|
||||
resend_delay: b'\x02',
|
||||
flags: @streaming.flag_synchronize |
|
||||
@streaming.flag_from_included |
|
||||
@streaming.flag_delay_requested |
|
||||
@streaming.flag_max_packet_size_included |
|
||||
@streaming.flag_no_ack,
|
||||
delay_requested: Some(50U),
|
||||
from_dest: Some(dest),
|
||||
max_packet_size: Some(1730U),
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"syn-payload",
|
||||
}
|
||||
let signed = pkt.sign_ed25519(ed_seed)
|
||||
assert_eq(signed.verify_signature(dest), true)
|
||||
|
||||
let i2cp = @streaming.encode_i2cp_streaming(
|
||||
signed,
|
||||
from_port=4000U,
|
||||
to_port=8080U,
|
||||
)
|
||||
let (hdr, dec) = @streaming.decode_i2cp_streaming(i2cp)
|
||||
assert_eq(hdr.from_port, 4000U)
|
||||
assert_eq(hdr.to_port, 8080U)
|
||||
assert_eq(hdr.protocol, b'\x06')
|
||||
assert_eq(dec, signed)
|
||||
assert_eq(dec.verify_signature(dest), true)
|
||||
|
||||
// Tampering payload invalidates signature
|
||||
let tampered : @streaming.StreamingPacket = {
|
||||
send_stream_id: dec.send_stream_id,
|
||||
recv_stream_id: dec.recv_stream_id,
|
||||
sequence_num: dec.sequence_num,
|
||||
ack_through: dec.ack_through,
|
||||
nacks: dec.nacks,
|
||||
resend_delay: dec.resend_delay,
|
||||
flags: dec.flags,
|
||||
delay_requested: dec.delay_requested,
|
||||
from_dest: dec.from_dest,
|
||||
max_packet_size: dec.max_packet_size,
|
||||
offline_sig: dec.offline_sig,
|
||||
signature: dec.signature,
|
||||
payload: b"tampered!",
|
||||
}
|
||||
assert_eq(tampered.verify_signature(dest), false)
|
||||
}
|
||||
|
||||
///|
|
||||
test "Streaming full SYN -> SYN-ACK -> Data with drop/NACK/retransmit -> CLOSE" {
|
||||
let (alice_dest, alice_seed) = make_test_identity(b'\x21')
|
||||
let (bob_dest, bob_seed) = make_test_identity(b'\x22')
|
||||
let alice_mgr = @streaming.StreamManager::new(
|
||||
alice_dest,
|
||||
alice_seed,
|
||||
initial_stream_id=100U,
|
||||
)
|
||||
let bob_mgr = @streaming.StreamManager::new(
|
||||
bob_dest,
|
||||
bob_seed,
|
||||
initial_stream_id=200U,
|
||||
)
|
||||
|
||||
let a_stream = alice_mgr.connect(
|
||||
bob_dest.hash(),
|
||||
1000UL,
|
||||
from_port=1111U,
|
||||
to_port=80U,
|
||||
)
|
||||
// Deliver SYN to Bob
|
||||
for msg in a_stream.drain_outbound() {
|
||||
let _ = bob_mgr.handle_incoming_i2cp(msg, 1010UL)
|
||||
}
|
||||
let b_stream = match bob_mgr.accept_next() {
|
||||
Some(s) => s
|
||||
None => fail("expected Bob to accept incoming SYN stream")
|
||||
}
|
||||
assert_eq(b_stream.remote_hash, alice_dest.hash())
|
||||
|
||||
// Deliver SYN-ACK to Alice, then Alice's ACK back to Bob
|
||||
for msg in b_stream.drain_outbound() {
|
||||
let _ = alice_mgr.handle_incoming_i2cp(msg, 1020UL)
|
||||
}
|
||||
assert_eq(a_stream.state, Established)
|
||||
for msg in a_stream.drain_outbound() {
|
||||
let _ = bob_mgr.handle_incoming_i2cp(msg, 1025UL)
|
||||
}
|
||||
|
||||
// Alice writes 4000 bytes (3 packets at 1730B MTU); drop packet #1 to force NACK & retransmit!
|
||||
let buf = FixedArray::make(4000, b'\x00')
|
||||
for i = 0; i < 4000; i = i + 1 {
|
||||
buf[i] = ((i * 17 + 3) & 0xFF).to_byte()
|
||||
}
|
||||
let msg_data = Bytes::from_array(buf)
|
||||
let written = a_stream.write(msg_data, 1030UL)
|
||||
assert_eq(written, 4000)
|
||||
let pkts = a_stream.drain_outbound()
|
||||
assert_eq(pkts.length(), 3)
|
||||
// Deliver packet 0 and packet 2 (drop packet 1)
|
||||
let _ = bob_mgr.handle_incoming_i2cp(pkts[0], 1040UL)
|
||||
let _ = bob_mgr.handle_incoming_i2cp(pkts[2], 1041UL)
|
||||
// Bob emits ACK+NACK for seq 2; deliver to Alice so Alice retransmits seq 2
|
||||
for ack in b_stream.drain_outbound() {
|
||||
let _ = alice_mgr.handle_incoming_i2cp(ack, 1050UL)
|
||||
}
|
||||
for retx in a_stream.drain_outbound() {
|
||||
let _ = bob_mgr.handle_incoming_i2cp(retx, 1060UL)
|
||||
}
|
||||
assert_eq(b_stream.read_available(), msg_data)
|
||||
|
||||
// Bob replies and closes
|
||||
assert_eq(b_stream.write(b"HTTP/1.1 200 OK\r\n\r\n", 1070UL), 19)
|
||||
b_stream.close(1071UL)
|
||||
for msg in b_stream.drain_outbound() {
|
||||
let _ = alice_mgr.handle_incoming_i2cp(msg, 1080UL)
|
||||
}
|
||||
assert_eq(a_stream.read_available(), b"HTTP/1.1 200 OK\r\n\r\n")
|
||||
assert_eq(a_stream.is_eof(), true)
|
||||
}
|
||||
|
||||
///|
|
||||
test "RepliableDatagram (Ed25519 raw payload) and RawDatagram I2CP round-trip" {
|
||||
let (dest, seed) = make_test_identity(b'\x33')
|
||||
let dg = @streaming.RepliableDatagram::sign_ed25519(
|
||||
dest, seed, b"ping-datagram",
|
||||
)
|
||||
assert_eq(dg.verify(), true)
|
||||
let i2cp = dg.to_i2cp_bytes(from_port=5000U, to_port=5001U)
|
||||
let (hdr, dec) = @streaming.RepliableDatagram::from_i2cp_bytes(i2cp)
|
||||
assert_eq(hdr.from_port, 5000U)
|
||||
assert_eq(hdr.to_port, 5001U)
|
||||
assert_eq(hdr.protocol, b'\x11')
|
||||
assert_eq(dec, dg)
|
||||
assert_eq(dec.verify(), true)
|
||||
|
||||
let raw_i2cp = @streaming.encode_raw_datagram(
|
||||
b"unauth-raw",
|
||||
from_port=9U,
|
||||
to_port=10U,
|
||||
)
|
||||
let (rh, rbody) = @streaming.decode_raw_datagram(raw_i2cp)
|
||||
assert_eq(rh.protocol, b'\x12')
|
||||
assert_eq(rbody, b"unauth-raw")
|
||||
}
|
||||
Reference in new issue
Block a user