hoprd_db_api/
aliases.rs

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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use async_trait::async_trait;
use sea_orm::{ColumnTrait, DbErr, EntityTrait, QueryFilter};

use hoprd_db_entity::{aliases::Column, types::Alias};
use hoprd_migration::OnConflict;

use crate::{db::HoprdDb, errors::Result};

pub const ME_AS_ALIAS: &str = "me";

/// Defines DB API for accessing HOPR settings (mainly aliases for now)
#[async_trait]
pub trait HoprdDbAliasesOperations {
    /// Retrieve the peer id for a given alias
    async fn resolve_alias(&self, alias: String) -> Result<Option<String>>;

    /// Retrieve all aliases
    async fn get_aliases(&self) -> Result<Vec<Alias>>;

    /// Create new key pair value in the db. If peer is already aliased, db entry will be updated with the new alias. If `peer` is node's PeerID, throws an error
    async fn set_alias(&self, peer: String, alias: String) -> Result<()>;

    /// Update aliases. If some peers or aliases are already in the db, db entries will be updated with the new aliases. If node's PeerID is among passed aliases, throws an error
    async fn set_aliases(&self, aliases: Vec<Alias>) -> Result<()>;

    /// Delete alias. If not found, throws an error.
    async fn delete_alias(&self, alias: String) -> Result<()>;

    /// Delete all aliases
    async fn clear_aliases(&self) -> Result<()>;
}

#[async_trait]
impl HoprdDbAliasesOperations for HoprdDb {
    async fn resolve_alias(&self, alias: String) -> Result<Option<String>> {
        let row = hoprd_db_entity::aliases::Entity::find()
            .filter(hoprd_db_entity::aliases::Column::Alias.eq(alias))
            .one(&self.metadata)
            .await?;

        Ok(row.map(|model| model.peer_id))
    }

    async fn get_aliases(&self) -> Result<Vec<Alias>> {
        let rows = hoprd_db_entity::aliases::Entity::find().all(&self.metadata).await?;

        let aliases: Vec<Alias> = rows.into_iter().map(Alias::from).collect();

        Ok(aliases)
    }

    async fn set_aliases(&self, aliases: Vec<Alias>) -> Result<()> {
        match self.resolve_alias(ME_AS_ALIAS.to_string()).await {
            Ok(Some(me)) => {
                if aliases.iter().any(|entry| entry.peer_id == me) {
                    return Err(crate::errors::DbError::LogicalError(
                        "own alias cannot be modified".into(),
                    ));
                }
            }
            Ok(None) => {}
            Err(e) => return Err(e),
        }

        let new_aliases = aliases
            .into_iter()
            .map(|entry| hoprd_db_entity::aliases::ActiveModel {
                id: Default::default(),
                peer_id: sea_orm::ActiveValue::Set(entry.peer_id.clone()),
                alias: sea_orm::ActiveValue::Set(entry.alias.clone()),
            })
            .collect::<Vec<_>>();

        let _ = hoprd_db_entity::aliases::Entity::insert_many(new_aliases)
            .on_conflict(
                OnConflict::new()
                    .update_columns([Column::PeerId, Column::Alias])
                    .to_owned(),
            )
            .exec(&self.metadata)
            .await?;

        Ok(())
    }

    async fn set_alias(&self, peer: String, alias: String) -> Result<()> {
        if let Ok(Some(me)) = self.resolve_alias(ME_AS_ALIAS.to_string()).await {
            if me == peer {
                return Err(crate::errors::DbError::ReAliasingSelfNotAllowed);
            }
        }

        let new_pair = hoprd_db_entity::aliases::ActiveModel {
            id: Default::default(),
            peer_id: sea_orm::ActiveValue::Set(peer),
            alias: sea_orm::ActiveValue::Set(alias),
        };

        match hoprd_db_entity::aliases::Entity::insert(new_pair)
            .on_conflict(OnConflict::new().do_nothing().to_owned())
            .exec(&self.metadata)
            .await
        {
            Ok(_) => Ok(()),
            Err(DbErr::RecordNotInserted) => Err(crate::errors::DbError::AliasOrPeerIdAlreadyExists),
            Err(e) => Err(e.into()),
        }
    }

    async fn delete_alias(&self, alias: String) -> Result<()> {
        let res = hoprd_db_entity::aliases::Entity::delete_many()
            .filter(hoprd_db_entity::aliases::Column::Alias.eq(alias))
            .filter(hoprd_db_entity::aliases::Column::Alias.ne(ME_AS_ALIAS.to_string()))
            .exec(&self.metadata)
            .await?;

        if res.rows_affected > 0 {
            Ok(())
        } else {
            Err(crate::errors::DbError::LogicalError(
                "alias cannot be removed because it does not exist or it is the node's own alias.".into(),
            ))
        }
    }

    async fn clear_aliases(&self) -> Result<()> {
        let _ = hoprd_db_entity::aliases::Entity::delete_many()
            .filter(hoprd_db_entity::aliases::Column::Alias.ne(ME_AS_ALIAS.to_string()))
            .exec(&self.metadata)
            .await?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use libp2p_identity::PeerId;

    #[async_std::test]
    async fn set_alias_should_succeed() {
        let db = HoprdDb::new_in_memory().await;

        db.set_alias(PeerId::random().to_string(), "test_alias".to_string())
            .await
            .expect("should add alias");

        let aliases = db.get_aliases().await.expect("should get aliases");

        assert_eq!(aliases.len(), 1);
    }

    #[async_std::test]
    async fn set_alias_should_set_multiple_aliases_in_a_transaction() -> Result<()> {
        let db: HoprdDb = HoprdDb::new_in_memory().await;
        let entries = vec![
            Alias {
                peer_id: PeerId::random().to_string(),
                alias: "test_alias".to_string(),
            },
            Alias {
                peer_id: PeerId::random().to_string(),
                alias: "test_alias_2".to_string(),
            },
        ];

        db.set_aliases(entries.clone()).await?;

        let aliases = db.get_aliases().await?;

        assert_eq!(aliases.len(), 2);

        Ok(())
    }

    #[async_std::test]
    async fn set_me_among_other_alias_should_fail() {
        let db = HoprdDb::new_in_memory().await;

        let me_peer_id = PeerId::random().to_string();
        let alias = ME_AS_ALIAS.to_string();

        let res = db.set_alias(me_peer_id.clone(), alias.clone()).await;

        assert!(res.is_ok());

        let entries = vec![
            Alias {
                peer_id: me_peer_id.to_string(),
                alias: "test_alias".to_string(),
            },
            Alias {
                peer_id: PeerId::random().to_string(),
                alias: "test_alias_2".to_string(),
            },
        ];

        let res = db.set_aliases(entries.clone()).await;

        assert!(res.is_err());
    }

    #[async_std::test]
    async fn set_me_alias_should_fail_if_set() {
        let db = HoprdDb::new_in_memory().await;

        let me_peer_id = PeerId::random().to_string();
        let alias = ME_AS_ALIAS.to_string();

        let res = db.set_alias(me_peer_id.clone(), alias.clone()).await;

        assert!(res.is_ok());

        let res = db.set_alias(me_peer_id.clone(), alias.clone()).await;

        assert!(res.is_err());
    }

    #[async_std::test]
    async fn set_alias_should_fail_if_the_alias_already_is_assigned_to_any_peer_id() -> anyhow::Result<()> {
        let db = HoprdDb::new_in_memory().await;

        let peer_id = PeerId::random().to_string();
        let peer_id_2 = PeerId::random().to_string();
        let alias = "test_alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone()).await?;

        assert!(db.set_alias(peer_id_2, alias.clone()).await.is_err());

        let aliases = db.get_aliases().await.unwrap();

        assert_eq!(aliases.len(), 1);
        assert_eq!(aliases[0].peer_id, peer_id);

        Ok(())
    }

    #[async_std::test]
    async fn set_alias_should_fail_if_the_peerid_already_is_aliased() -> anyhow::Result<()> {
        let db = HoprdDb::new_in_memory().await;

        let peer_id = PeerId::random().to_string();
        let alias = "test_alias".to_string();
        let alias2 = "alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone()).await?;

        assert!(db.set_alias(peer_id.clone(), alias2.clone()).await.is_err());

        let aliases = db.get_aliases().await.unwrap();

        assert_eq!(aliases.len(), 1);
        assert_eq!(aliases[0].alias, alias);

        Ok(())
    }

    #[async_std::test]
    async fn resolve_alias_should_return_alias() {
        let db = HoprdDb::new_in_memory().await;

        let peer_id = PeerId::random().to_string();
        let alias = "test_alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone())
            .await
            .expect("should add alias");

        let alias = db.resolve_alias(alias).await.expect("should get alias");

        assert!(alias.is_some());
    }

    #[async_std::test]
    async fn resolve_not_stored_alias_should_return_none() {
        let db = HoprdDb::new_in_memory().await;

        let peer_id = PeerId::random().to_string();
        let alias = "test_alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone())
            .await
            .expect("should add alias");

        let alias = db
            .resolve_alias(PeerId::random().to_string())
            .await
            .expect("should get alias");

        assert!(alias.is_none());
    }

    #[async_std::test]
    async fn delete_stored_alias() {
        let db = HoprdDb::new_in_memory().await;

        let peer_id = PeerId::random().to_string();
        let alias = "test_alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone())
            .await
            .expect("should add alias");
        let aliases = db.get_aliases().await.expect("should get aliases");
        assert_eq!(aliases.len(), 1);

        db.delete_alias(alias).await.expect("should delete alias");
        let aliases = db.get_aliases().await.expect("should get aliases");
        assert_eq!(aliases.len(), 0);
    }

    #[async_std::test]
    async fn delete_all_aliases() {
        let db = HoprdDb::new_in_memory().await;

        let me_peer_id = PeerId::random().to_string();
        let peer_id = PeerId::random().to_string();
        let alias = "test_alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone())
            .await
            .expect("should add alias");
        db.set_alias(me_peer_id.clone(), ME_AS_ALIAS.to_string())
            .await
            .expect("should add alias");

        let aliases = db.get_aliases().await.expect("should get aliases");
        assert_eq!(aliases.len(), 2);

        db.clear_aliases()
            .await
            .expect(format!("should clear aliases except '{}'", ME_AS_ALIAS).as_str());
        let aliases = db.get_aliases().await.expect("should get aliases");
        assert_eq!(aliases.len(), 1);
        assert_eq!(aliases[0].peer_id, me_peer_id);
    }

    #[async_std::test]
    async fn set_aliases_with_existing_alias_should_replace_peer_id() {
        let db = HoprdDb::new_in_memory().await;

        let peer_id = PeerId::random().to_string();
        let alias = "test_alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone())
            .await
            .expect("should add alias");

        let new_peer_id = PeerId::random().to_string();
        db.set_aliases(vec![Alias {
            peer_id: new_peer_id.clone(),
            alias: alias.clone(),
        }])
        .await
        .expect("should replace peer_id");

        let aliases = db.get_aliases().await.expect("should get aliases");

        assert_eq!(aliases.len(), 1);
        assert_eq!(aliases[0].peer_id, new_peer_id);
    }

    #[async_std::test]
    async fn set_aliases_with_existing_peer_id_should_replace_alias() {
        let db = HoprdDb::new_in_memory().await;

        let peer_id = PeerId::random().to_string();
        let alias = "test_alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone())
            .await
            .expect("should add alias");

        db.set_aliases(vec![Alias {
            peer_id: peer_id.clone(),
            alias: alias.clone().to_uppercase(),
        }])
        .await
        .expect("should replace alias");

        let aliases = db.get_aliases().await.expect("should get aliases");

        assert_eq!(aliases.len(), 1);
        assert_eq!(aliases[0].alias, alias.to_uppercase());
    }

    #[async_std::test]
    async fn set_aliases_with_existing_entry_should_do_nothing() {
        let db = HoprdDb::new_in_memory().await;

        let peer_id = PeerId::random().to_string();
        let alias = "test_alias".to_string();

        db.set_alias(peer_id.clone(), alias.clone())
            .await
            .expect("should add alias");

        db.set_aliases(vec![Alias {
            peer_id: peer_id.clone(),
            alias: alias.clone(),
        }])
        .await
        .expect("should do nothing");

        let aliases = db.get_aliases().await.expect("should get aliases");

        assert_eq!(aliases.len(), 1);
    }
}