1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use std::borrow::{Borrow, Cow};
use std::sync::Arc;

use anyhow::Result;
use tl_proto::BoxedConstructor;

use super::futures::StoreValue;
use super::node::Node;
use super::streams::DhtValuesStream;
use crate::adnl;
use crate::proto;
use crate::utils::now;

#[must_use]
#[derive(Copy, Clone)]
pub struct Entry<'a> {
    dht: &'a Arc<Node>,
    id: &'a [u8; 32],
    name: &'a str,
    key_index: u32,
}

impl<'a> Entry<'a> {
    pub(super) fn new<T>(dht: &'a Arc<Node>, id: &'a T, name: &'a str) -> Self
    where
        T: Borrow<[u8; 32]>,
    {
        Self {
            dht,
            id: id.borrow(),
            name,
            key_index: 0,
        }
    }

    /// Sets the key index. Default: `0`
    pub fn with_key_index(mut self, idx: u32) -> Self {
        self.key_index = idx;
        self
    }

    /// Creates a new builder which can store the value in the DHT.
    ///
    /// See [`Entry::with_data_raw`] for raw API
    pub fn with_data<T>(self, data: T) -> EntryWithData<'a>
    where
        T: tl_proto::TlWrite<Repr = tl_proto::Boxed>,
    {
        EntryWithData {
            inner: self,
            data: Cow::Owned(tl_proto::serialize(data)),
            expire_at: None,
        }
    }

    /// Creates a new builder which can store the value in the DHT.
    ///
    /// See [`Entry::with_data`] for more convenient API
    pub fn with_data_raw(self, data: &'a [u8]) -> EntryWithData<'a> {
        EntryWithData {
            inner: self,
            data: Cow::Borrowed(data),
            expire_at: None,
        }
    }

    /// Returns a stream of values for this entry.
    pub fn values<T>(self) -> DhtValuesStream<T>
    where
        for<'tl> T: tl_proto::TlRead<'tl, Repr = tl_proto::Boxed> + Send + 'static,
    {
        DhtValuesStream::new(self.dht.clone(), self.key())
    }

    /// Queries a value from the given peer.
    pub async fn value_from<T>(
        self,
        peer_id: &adnl::NodeIdShort,
    ) -> Result<Option<(proto::dht::KeyDescriptionOwned, T)>>
    where
        for<'tl> T: tl_proto::TlRead<'tl, Repr = tl_proto::Boxed> + Send + 'static,
    {
        let key_id = tl_proto::hash_as_boxed(self.key());
        let query = tl_proto::serialize(proto::rpc::DhtFindValue { key: &key_id, k: 6 }).into();

        match self.dht.query_raw(peer_id, query).await? {
            Some(result) => self.dht.parse_value_result(&result),
            None => Ok(None),
        }
    }

    /// Returns TL representation of the entry key.
    pub fn key(&self) -> proto::dht::Key<'a> {
        proto::dht::Key {
            id: self.id,
            name: self.name.as_bytes(),
            idx: self.key_index,
        }
    }
}

pub struct EntryWithData<'a> {
    inner: Entry<'a>,
    data: Cow<'a, [u8]>,
    expire_at: Option<u32>,
}

impl<'a> EntryWithData<'a> {
    /// Sets the expiration time for the value.
    pub fn expire_at(mut self, timestamp: u32) -> Self {
        self.expire_at = Some(timestamp);
        self
    }

    /// Sets expiration time for the value as `now + ttl`
    pub fn with_ttl(mut self, ttl: u32) -> Self {
        self.expire_at = Some(now() + ttl);
        self
    }

    /// Creates signed TL representation of the entry.
    pub fn sign(self, key: &adnl::Key) -> proto::dht::ValueOwned {
        let mut value = self.make_value(key);

        let key_signature = key.sign(value.key.as_boxed());
        value.key.signature = &key_signature;

        let value_signature = key.sign(value.as_boxed());
        value.signature = &value_signature;

        value.as_equivalent_owned()
    }

    /// Creates signed TL representation of the entry and stores it in the DHT.
    ///
    /// See [`DhtStoreValue`]
    pub fn sign_and_store(self, key: &adnl::Key) -> Result<StoreValue> {
        let mut value = self.make_value(key);

        let key_signature = key.sign(value.key.as_boxed());
        value.key.signature = &key_signature;

        let value_signature = key.sign(value.as_boxed());
        value.signature = &value_signature;

        StoreValue::new(self.inner.dht.clone(), value)
    }

    fn make_value<'b>(&'b self, key: &'b adnl::Key) -> proto::dht::Value<'b>
    where
        'a: 'b,
    {
        proto::dht::Value {
            key: proto::dht::KeyDescription {
                key: self.inner.key(),
                id: key.full_id().as_tl(),
                update_rule: proto::dht::UpdateRule::Signature,
                signature: Default::default(),
            },
            value: &self.data,
            ttl: self
                .expire_at
                .unwrap_or_else(|| now() + self.inner.dht.options().value_ttl_sec),
            signature: Default::default(),
        }
    }
}