p2p、分布式,区块链笔记: libp2p基础

通信密钥 noise::{Keypair, X25519Spec}

  • X25519/Ed25519类似RSA 算法。
  • Noise 用于设计和实现安全通信协议。它允许通信双方在没有预先共享密钥的情况下进行安全的密钥交换,并通过加密和身份验证保护通信内容。libp2p 提供了对 Noise 协议的原生支持,它允许节点之间使用 Noise 协议进行安全的点对点通信。
  • 例:use libp2p::{noise::{Keypair, X25519Spec},identity,};, let local_keys = Keypair::<X25519Spec>::new().into_authentic(&identity::Keypair::generate_ed25519());

identity::Keypair

  • libp2p 中,identity::Keypair 是一个用于管理加密和身份验证密钥的结构体。它允许你生成和管理加密算法(如椭圆曲线加密)所需的公钥和私钥对,以及进行数字签名和验证等操作。
  • 下面是一个简单的示例,展示如何使用 Keypair 生成一个 Ed25519 算法的密钥对,并使用它进行签名和验证:
use libp2p::identity::{
   
   Keypair, ed25519};

fn main() {
   
   
    // 生成一个 Ed25519 类型的密钥对
    let keypair = Keypair::generate_ed25519();

    // 获取公钥和私钥
    let public_key = keypair.public();
    let private_key = keypair.secret();

    // 创建一个消息
    let message = b"Hello, libp2p!";

    // 使用私钥对消息进行签名
    let signature = keypair.sign(message);

    // 使用公钥验证签名
    assert!(public_key.verify(message, &signature).is_ok());

    println!("Message: {:?}", message);
    println!("Signature: {:?}", signature);
}

transport

  • 传输在两个对等方之间提供面向连接的通信 通过有序的数据流(即连接)
  • 负责从一个peer到另一个peer的实际数据的传输
  • 收听和拨号
  • 例如使用let transport = libp2p::development_transport(local_keys).await?;调用libp2p提供的高级API函数development_transport来创建传输。这个函数封装了传输的创建过程,通常会使用一组默认的配置参数和最佳实践,以便快速启动和测试libp2p应用程序。在这种情况下,local_keys是本地密钥,用于加密和身份验证。有关这个API的未来发展可以看这个ISSUE
  • 还可以手动配置和创建传输(transport)。下面的例子使用了TokioTcpConfig作为基础的TCP传输配置,手动指定了协议升级、身份认证和多路复用的配置。这种方式适用于需要精确控制传输行为和配置的场景,允许开发者根据具体需求进行灵活的设置和调整。
    //Creates transport which is a feature of the lib p2p framework
    let transport = TokioTcpConfig::new()
        //Upgrades version of the transport once connection is established as Version 1 of the multi-stream-select protocol is the version that interacts with the noise protocol
        //in short handles protocol negotiation
        .upgrade(upgrade::Version::V1)
        //Authenticates that channel is secure with the noise XX handshake
        .authenticate(libp2p::noise::NoiseConfig::xx(auth_keys).into_authenticated())
        //multiplex transport negotiates multiple sub-streams and/or connections on the authenticated transport
        .multiplex(mplex::MplexConfig::new())
        //boxed allows only output and error types to be captured
        .boxed();

行为控制 Swarm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值