#![allow(unused_imports)]
use super::*;
#[derive(Serialize)]
pub(super) struct ChallengeMessage<'a> {
#[serde(rename = "type")]
pub(super) msg_type: &'static str,
pub(super) nonce: &'a str,
}
#[derive(Deserialize)]
pub(super) struct ResponseMessage {
#[serde(rename = "type")]
pub(super) msg_type: String,
pub(super) did: String,
pub(super) signature: String,
}
#[derive(Serialize)]
pub(super) struct RejectedResponse<'a> {
pub(super) status: &'static str,
pub(super) reason: &'a str,
}
#[derive(Serialize)]
pub(super) struct CapabilityDetail {
pub(super) endpoint: String,
pub(super) bucket: String,
pub(super) access: String,
}
#[derive(Serialize)]
pub(super) struct IpfsDetail {
pub(super) gateway: String,
pub(super) folder_cid: String,
}
#[derive(Serialize)]
pub(super) struct WebrtcDetail {
pub(super) relay: String,
}
#[derive(Serialize)]
pub(super) struct CapabilitiesInfo {
pub(super) s3: CapabilityDetail,
pub(super) ipfs: IpfsDetail,
pub(super) webrtc: WebrtcDetail,
}
pub fn generate_random_bytes_pub(len: usize) -> Vec<u8> {
generate_random_bytes(len)
}
pub(super) fn generate_random_bytes(len: usize) -> Vec<u8> {
use std::time::SystemTime;
let seed = format!("{:?}", SystemTime::now());
let ptr_bytes = (&seed as *const _ as usize).to_ne_bytes();
let mut combined = seed.as_bytes().to_vec();
combined.extend_from_slice(&ptr_bytes);
let result = crate::hash::raw_hash_bytes_32(&combined);
result[..len.min(32)].to_vec()
}
#[derive(Serialize)]
pub(super) struct AuthorizedResponse {
pub(super) status: &'static str,
pub(super) capabilities: CapabilitiesInfo,
}
pub(super) async fn handle_node_connection(
mut send_stream: quinn::SendStream,
mut recv_stream: quinn::RecvStream,
db_path: &str,
) -> Result<Option<String>, String> {
let nonce = encode_hex(&generate_random_bytes(16));
let challenge = ChallengeMessage {
msg_type: "challenge",
nonce: &nonce,
};
let challenge_json = serde_json::to_string(&challenge)
.map_err(|e| format!("Failed to serialize challenge: {}", e))?;
send_stream.write_all(challenge_json.as_bytes())
.await
.map_err(|e| format!("Failed to write challenge: {}", e))?;
send_stream.finish()
.map_err(|e| format!("Failed to finish challenge stream: {}", e))?;
let response_buf = recv_stream.read_to_end(1024 * 1024)
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
if response_buf.is_empty() {
return Ok(None);
}
let response_str = String::from_utf8_lossy(&response_buf);
let response: ResponseMessage = match serde_json::from_str(&response_str) {
Ok(msg) => msg,
Err(_) => {
return Ok(None);
}
};
if response.msg_type != "response" {
return Ok(None);
}
println!("[P2P NODE] Verifying EOA credentials for {}...", response.did);
let agent_card = match get_agent_card_from_db(db_path, &response.did)? {
Some(card) => card,
None => {
println!("[P2P NODE] Unauthorized: DID {} not registered in identity registry.", response.did);
return Ok(None);
}
};
let public_key = match VerifyingKey::from_public_key_pem(&agent_card.public_key) {
Ok(key) => key,
Err(e) => {
println!("[P2P NODE] Unauthorized: Public key parse failed for {}: {}", response.did, e);
return Ok(None);
}
};
let signature_bytes = match decode_hex(&response.signature) {
Ok(bytes) => bytes,
Err(_) => {
return Ok(None);
}
};
let signature = match Signature::from_slice(&signature_bytes) {
Ok(sig) => sig,
Err(_) => {
return Ok(None);
}
};
if public_key.verify(nonce.as_bytes(), &signature).is_err() {
println!("[P2P NODE] Cryptographic validation failed for {}.", response.did);
return Ok(None);
}
let has_s3 = agent_card.capabilities.iter().any(|c| c == "s3_access");
let has_ipfs = agent_card.capabilities.iter().any(|c| c == "ipfs_access");
if has_s3 || has_ipfs {
println!("[P2P NODE] Authentication succeeded for {}. Capability access granted.", response.did);
let cap_res = AuthorizedResponse {
status: "authorized",
capabilities: CapabilitiesInfo {
s3: CapabilityDetail {
endpoint: "http://127.0.0.1:9000".to_string(),
bucket: "sprint42-bucket".to_string(),
access: "read-write".to_string(),
},
ipfs: IpfsDetail {
gateway: "http://127.0.0.1:5001".to_string(),
folder_cid: "QmULx3x6FCZiYksGkuK1FQ1t59uAwRtYpuqHAvGqc7s9Ba".to_string(),
},
webrtc: WebrtcDetail {
relay: "http://127.0.0.1:9090".to_string(),
},
},
};
let cap_json = serde_json::to_string(&cap_res)
.map_err(|e| format!("Failed to serialize auth response: {}", e))?;
return Ok(Some(cap_json));
} else {
println!("[P2P NODE] DID {} authenticated but lacks authorized storage capabilities.", response.did);
}
Ok(None)
}
pub fn run_discovery_node(port: u16, db_path: &str) -> Result<(), String> {
use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};
let cert = generate_self_signed_cert("pkc-discovery-node")
.map_err(|e| format!("Failed to generate TLS cert: {}", e))?;
let endpoint = QuicEndpoint::new_server(port, &cert)
.map_err(|e| format!("Failed to bind QUIC endpoint to port {}: {}", port, e))?;
println!("[P2P NODE] Starting discovery node on port {} (QUIC)...", port);
println!("[P2P NODE] Using identity database: {}", db_path);
println!("[P2P NODE] Node is listening on port {} (QUIC/UDP)", port);
let rt = tokio::runtime::Runtime::new()
.map_err(|e| format!("Failed to create tokio runtime: {}", e))?;
rt.block_on(async {
loop {
match endpoint.accept().await {
Ok(conn) => {
let db = db_path.to_string();
tokio::spawn(async move {
match conn.conn.accept_bi().await {
Ok((send_stream, recv_stream)) => {
match handle_node_connection(send_stream, recv_stream, &db).await {
Ok(Some(auth_json)) => {
match conn.conn.open_uni().await {
Ok(mut auth_stream) => {
let _ = auth_stream.write_all(auth_json.as_bytes()).await;
let _ = auth_stream.finish();
}
Err(e) => {
eprintln!("[P2P NODE] Failed to open auth stream: {}", e);
}
}
}
Ok(None) => {
let rej = RejectedResponse { status: "rejected", reason: "unauthorized" };
match conn.conn.open_uni().await {
Ok(mut auth_stream) => {
let rej_json = serde_json::to_string(&rej).unwrap_or_default();
let _ = auth_stream.write_all(rej_json.as_bytes()).await;
let _ = auth_stream.finish();
}
Err(e) => {
eprintln!("[P2P NODE] Failed to open reject stream: {}", e);
}
}
}
Err(e) => {
eprintln!("[P2P NODE] Connection handler error: {}", e);
}
}
}
Err(e) => {
eprintln!("[P2P NODE] Failed to accept bi-stream: {}", e);
}
}
let _ = conn.conn.closed().await;
});
}
Err(e) => {
eprintln!("[P2P NODE] Connection accept failed: {}", e);
}
}
}
})
}
pub fn perform_handshake(
ip: &str,
port: u16,
did: &str,
private_key_path: &str,
) -> Result<serde_json::Value, String> {
use crate::quic_transport::QuicEndpoint;
if !Path::new(private_key_path).exists() {
return Err(format!("Private key file not found at: {}", private_key_path));
}
let private_key_pem = fs::read_to_string(private_key_path)
.map_err(|e| format!("Failed to read private key PEM: {}", e))?;
let signing_key = SigningKey::from_pkcs8_pem(&private_key_pem)
.map_err(|e| format!("Failed to parse private key: {}", e))?;
let rt = tokio::runtime::Runtime::new()
.map_err(|e| format!("Failed to create tokio runtime: {}", e))?;
rt.block_on(async {
let client = QuicEndpoint::new_client()
.map_err(|e| format!("Failed to create QUIC client: {}", e))?;
let server_addr = format!("{}:{}", ip, port);
let conn = client.connect(&server_addr, "pkc-discovery-node")
.await
.map_err(|e| format!("Failed to connect to {}: {}", server_addr, e))?;
let (mut send_stream, mut recv_stream) = conn.conn
.open_bi()
.await
.map_err(|e| format!("Failed to open handshake stream: {}", e))?;
let challenge_buf = recv_stream.read_to_end(1024 * 1024)
.await
.map_err(|e| format!("Failed to read challenge from server: {}", e))?;
let challenge_str = String::from_utf8_lossy(&challenge_buf);
let challenge_msg: serde_json::Value = serde_json::from_str(&challenge_str)
.map_err(|e| format!("Failed to parse challenge JSON: {}", e))?;
if challenge_msg["type"] != "challenge" {
return Err("Protocol mismatch: expected challenge message".to_string());
}
let nonce = challenge_msg["nonce"].as_str()
.ok_or_else(|| "Missing nonce in challenge message".to_string())?;
let signature = signing_key.sign(nonce.as_bytes());
let signature_hex = encode_hex(&signature.to_bytes());
let response = serde_json::json!({
"type": "response",
"did": did,
"signature": signature_hex,
});
let response_bytes = serde_json::to_vec(&response)
.map_err(|e| format!("Failed to serialize response: {}", e))?;
send_stream.write_all(&response_bytes)
.await
.map_err(|e| format!("Failed to write response: {}", e))?;
send_stream.finish()
.map_err(|e| format!("Failed to finish send stream: {}", e))?;
let mut auth_stream = conn.conn.accept_uni()
.await
.map_err(|e| format!("Failed to accept auth stream: {}", e))?;
let auth_buf = auth_stream.read_to_end(1024 * 1024)
.await
.map_err(|e| format!("Failed to read final response from server: {}", e))?;
let auth_str = String::from_utf8_lossy(&auth_buf);
let final_res: serde_json::Value = serde_json::from_str(&auth_str)
.map_err(|e| format!("Failed to parse final response JSON: {}", e))?;
client.close();
Ok(final_res)
})
}