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    fmt::Debug,
21    marker::{Send, Sync},
22    sync::Arc,
23};
24
25use async_trait::async_trait;
26
27use super::{Dht, DhtLookupReply, DhtNode};
28use crate::{net::ChannelPtr, Result};
29
30/// Trait for application-specific behaviors over a [`Dht`]
31#[async_trait]
32pub trait DhtHandler: Send + Sync + Sized {
33    type Value: Clone + Debug;
34    type Node: DhtNode;
35
36    /// The [`Dht`] instance
37    fn dht(&self) -> Arc<Dht<Self>>;
38
39    /// Get our own node
40    async fn node(&self) -> Result<Self::Node>;
41
42    /// Send PING request, which is used to know the node data of a peer
43    /// (and most importantly, its ID/key in the DHT keyspace)
44    async fn ping(&self, channel: ChannelPtr) -> Result<Self::Node>;
45
46    /// Send STORE request to instruct a peer to store a key-value pair
47    async fn store(
48        &self,
49        channel: ChannelPtr,
50        key: &blake3::Hash,
51        value: &Self::Value,
52    ) -> Result<()>;
53
54    /// Send FIND NODES request to a peer to get nodes close to `key`
55    async fn find_nodes(&self, channel: ChannelPtr, key: &blake3::Hash) -> Result<Vec<Self::Node>>;
56
57    /// Send FIND VALUE request to a peer to get a value and/or nodes close to `key`
58    async fn find_value(
59        &self,
60        channel: ChannelPtr,
61        key: &blake3::Hash,
62    ) -> Result<DhtLookupReply<Self::Node, Self::Value>>;
63
64    /// Add a value to our hash table
65    async fn add_value(&self, key: &blake3::Hash, value: &Self::Value);
66
67    /// Defines how keys are printed/logged
68    fn key_to_string(key: &blake3::Hash) -> String;
69}