darkfi/dht/handler.rs
1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2025 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use std::{
20 marker::{Send, Sync},
21 sync::Arc,
22};
23
24use async_trait::async_trait;
25
26use super::{Dht, DhtLookupReply, DhtNode};
27use crate::{net::ChannelPtr, Result};
28
29/// Trait for application-specific behaviors over a [`Dht`]
30#[async_trait]
31pub trait DhtHandler: Send + Sync + Sized {
32 type Value: Clone;
33 type Node: DhtNode;
34
35 /// The [`Dht`] instance
36 fn dht(&self) -> Arc<Dht<Self>>;
37
38 /// Get our own node
39 async fn node(&self) -> Self::Node;
40
41 /// Send a DHT ping request, which is used to know the node data of a peer
42 /// (and most importantly, its ID/key in the DHT keyspace)
43 async fn ping(&self, channel: ChannelPtr) -> Result<Self::Node>;
44
45 /// Triggered when we find a new node
46 async fn on_new_node(&self, node: &Self::Node) -> Result<()>;
47
48 /// Send FIND NODES request to a peer to get nodes close to `key`
49 async fn find_nodes(&self, node: &Self::Node, key: &blake3::Hash) -> Result<Vec<Self::Node>>;
50
51 /// Send FIND VALUE request to a peer to get a value and/or nodes close to `key`
52 async fn find_value(
53 &self,
54 node: &Self::Node,
55 key: &blake3::Hash,
56 ) -> Result<DhtLookupReply<Self::Node, Self::Value>>;
57
58 /// Add a value to our hash table
59 async fn add_value(&self, key: &blake3::Hash, value: &Self::Value);
60
61 /// Defines how keys are printed/logged
62 fn key_to_string(key: &blake3::Hash) -> String;
63}