Rust网络通信库tor-units的使用,tor-units为Tor网络提供高效单元处理与协议支持
tor-units - 原始数字类型的安全包装器
概述
这个crate是Arti项目的一部分,为Arti其他部分使用的原始数字类型提供了安全的包装器。具体功能包括:
- 一个有界i32类型,带有边界检查和钳制功能
- 整数毫秒和秒的包装器,可转换为标准Duration
- 百分比包装器,避免忘记除以100的错误
- 仅用于比较的SendMeVersion类型
编译特性
memquota-memcost
- 为多种类型实现内存成本追踪接口full
- 启用所有特性
许可证:MIT 或 Apache-2.0
示例代码
use tor_units::{BoundedInt32, IntegerMilliseconds, IntegerSeconds, Percentage};
fn main() {
// 使用BoundedInt32
let bounded = BoundedInt32::new(100).expect("Value within bounds");
println!("Bounded i32: {}", bounded.get());
// 使用IntegerMilliseconds
let ms = IntegerMilliseconds::new(1500);
let duration = ms.to_duration();
println!("1500 ms = {:?}", duration);
// 使用IntegerSeconds
let sec = IntegerSeconds::new(3);
let duration = sec.to_duration();
println!("3 sec = {:?}", duration);
// 使用Percentage
let pct = Percentage::new(75);
let fraction = pct.as_fraction();
println!("75% = {}", fraction);
}
完整示例代码
use std::time::Duration;
use tor_units::{BoundedInt32, IntegerMilliseconds, IntegerSeconds, Percentage, SendMeVersion};
fn main() {
// 1. 有界整数示例
match BoundedInt32::new(500) {
Ok(bounded) => println!("有效的有界i32: {}", bounded.get()),
Err(e) => println!("错误: {}", e),
}
// 2. 时间单位转换示例
let sleep_time_ms = IntegerMilliseconds::new(2000);
std::thread::sleep(sleep_time_ms.to_duration());
let timeout_sec = IntegerSeconds::new(5);
println!("超时时间: {:?}", timeout_sec.to_duration());
// 3. 百分比计算示例
let disk_usage = Percentage::new(85);
if disk_usage.as_fraction() > 0.9 {
println!("警告: 磁盘空间不足!");
} else {
println!("磁盘使用率: {}%", disk_usage.get());
}
// 4. 版本比较示例
let v1 = SendMeVersion::new(1);
let v2 = SendMeVersion::new(2);
if v1 < v2 {
println!("版本 {} 比版本 {} 旧", v1.get(), v2.get());
}
}
使用说明
在Cargo.toml中添加依赖:
[dependencies]
tor-units = "0.32.0"
这个库主要提供以下功能:
- 安全的有界整数处理
- 时间单位的便捷转换
- 百分比的安全处理
- 版本号的比较功能
1 回复
Rust网络通信库tor-units的使用指南
tor-units是一个为Tor网络提供高效单元处理与协议支持的Rust库,它简化了与Tor网络的交互过程,提供了构建Tor客户端和服务器的必要组件。
主要特性
- 提供Tor协议的核心单元(CELL)处理功能
- 支持高效的数据序列化和反序列化
- 实现Tor网络协议的关键部分
- 线程安全的设计
- 良好的错误处理机制
安装方法
在Cargo.toml中添加依赖:
[dependencies]
tor-units = "0.3"
基本使用方法
1. 创建和解析Tor单元
use tor_units::{Cell, CellType, Command};
// 创建一个新的单元
let mut cell = Cell::new(CellType::Relay, Command::RelayData);
// 添加数据到单元
cell.append_data(b"Hello Tor network!");
// 序列化单元
let encoded = cell.encode().unwrap();
// 反序列化单元
let decoded_cell = Cell::decode(&encoded).unwrap();
2. 构建简单的Tor客户端
use tor_units::{ClientHandshake, TorVersion};
use std::net::TcpStream;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 连接到Tor中继
let stream = TcpStream::connect("127.0.0.1:9050")?;
// 初始化客户端握手
let mut handshake = ClientHandshake::new(TorVersion::new(3, 0, 0));
// 执行握手过程
let mut session = handshake.perform(stream)?;
// 现在可以使用session发送和接收Tor单元
Ok(())
}
3. 处理Relay单元
use tor_units::{RelayCell, RelayCommand};
// 创建Relay单元
let relay_cell = RelayCell::new(
RelayCommand::Data,
42, // 流ID
Some(b"Payload data".to_vec())
);
// 处理接收到的Relay单元
match relay_cell.command() {
RelayCommand::Data => {
println!("Received data: {:?}", relay_cell.payload());
}
RelayCommand::Connected => {
println!("Stream connected!");
}
_ => {}
}
高级用法
自定义单元处理器
use tor_units::{CellProcessor, Cell, ProcessResult};
struct MyCellProcessor;
impl CellProcessor for MyCellProcessor {
fn process_cell(&mut self, cell: Cell) -> ProcessResult {
println!("Processing cell of type: {:?}", cell.cell_type());
// 在这里添加自定义处理逻辑
ProcessResult::Continue
}
}
// 使用自定义处理器
let processor = MyCellProcessor;
let mut connection = tor_units::Connection::new(stream, processor);
connection.run()?;
加密通信
tor-units内置了与Tor网络兼容的加密功能:
use tor_units::crypto::{TorKey, TorCipher};
// 创建加密密钥
let key = TorKey::new(b"secret_key_material");
// 初始化加密器
let mut cipher = TorCipher::new(key);
// 加密数据
let plaintext = b"confidential message";
let ciphertext = cipher.encrypt(plaintext);
// 解密数据
let decrypted = cipher.decrypt(&ciphertext);
assert_eq!(plaintext, decrypted.as_slice());
错误处理
tor-units提供了详细的错误类型:
use tor_units::error::TorUnitsError;
match some_tor_units_operation() {
Ok(_) => println!("Success!"),
Err(TorUnitsError::ProtocolError(e)) => eprintln!("Protocol error: {}", e),
Err(TorUnitsError::CryptoError(e)) => eprintln!("Crypto error: {}", e),
Err(e) => eprintln!("Other error: {}", e),
}
性能提示
- 复用Cell对象以减少内存分配
- 对于高性能场景,考虑使用
CellBuffer
进行批量处理 - 异步运行时可以使用
async
特性
tor-units为构建Tor网络应用提供了坚实的基础,无论是开发隐私增强工具还是研究网络协议,它都能提供强大的支持。
完整示例代码
下面是一个完整的Tor客户端示例,演示了如何使用tor-units库建立连接并发送数据:
use tor_units::{ClientHandshake, TorVersion, Cell, CellType, Command};
use std::net::TcpStream;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. 连接到Tor中继
let stream = TcpStream::connect("127.0.0.1:9050")?;
// 2. 执行客户端握手
let mut handshake = ClientHandshake::new(TorVersion::new(3, 0, 0));
let mut session = handshake.perform(stream)?;
// 3. 创建并发送CELL单元
let mut cell = Cell::new(CellType::Relay, Command::RelayData);
cell.append_data(b"Test message for Tor network");
session.send_cell(cell)?;
// 4. 接收并处理响应
if let Some(response) = session.recv_cell()? {
println!("Received response cell: {:?}", response);
}
Ok(())
}
这个完整示例演示了:
- 建立到Tor中继的TCP连接
- 完成客户端握手过程
- 创建并发送包含测试消息的CELL单元
- 接收并处理来自Tor网络的响应