hopr_db_sql/
registry.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
use async_trait::async_trait;
use hopr_db_entity::{network_eligibility, network_registry};
use hopr_primitive_types::prelude::{Address, ToHex};
use sea_orm::{ColumnTrait, DbErr, EntityTrait, QueryFilter, Set};
use sea_query::OnConflict;

use crate::db::HoprDb;
use crate::errors::{DbSqlError, Result};
use crate::{HoprDbGeneralModelOperations, OptTx};

/// Defines DB access API for network registry operations.
#[async_trait]
pub trait HoprDbRegistryOperations {
    /// Sets the given node as allowed or denied in network registry.
    async fn set_access_in_network_registry<'a>(&'a self, tx: OptTx<'a>, address: Address, allowed: bool)
        -> Result<()>;

    /// Returns `true` if the given node is allowed in network registry.
    async fn is_allowed_in_network_registry<'a>(&'a self, tx: OptTx<'a>, address: Address) -> Result<bool>;

    /// Sets or unsets Safe NR eligibility.
    async fn set_safe_eligibility<'a>(&'a self, tx: OptTx<'a>, address: Address, eligible: bool) -> Result<()>;

    /// Returns `true` if the given Safe is NR eligible.
    async fn is_safe_eligible<'a>(&'a self, tx: OptTx<'a>, address: Address) -> Result<bool>;
}

#[async_trait]
impl HoprDbRegistryOperations for HoprDb {
    async fn set_access_in_network_registry<'a>(
        &'a self,
        tx: OptTx<'a>,
        address: Address,
        allowed: bool,
    ) -> Result<()> {
        self.nest_transaction(tx)
            .await?
            .perform(|tx| {
                Box::pin(async move {
                    if allowed {
                        let entry = network_registry::ActiveModel {
                            chain_address: Set(address.to_hex()),
                            ..Default::default()
                        };

                        match network_registry::Entity::insert(entry)
                            .on_conflict(
                                OnConflict::column(network_registry::Column::ChainAddress)
                                    .do_nothing()
                                    .to_owned(),
                            )
                            .exec(tx.as_ref())
                            .await
                        {
                            Ok(_) | Err(DbErr::RecordNotInserted) => Ok::<_, DbSqlError>(()),
                            Err(e) => Err(e.into()),
                        }
                    } else {
                        network_registry::Entity::delete_many()
                            .filter(network_registry::Column::ChainAddress.eq(address.to_hex()))
                            .exec(tx.as_ref())
                            .await?;
                        Ok::<_, DbSqlError>(())
                    }
                })
            })
            .await
    }

    async fn is_allowed_in_network_registry<'a>(&'a self, tx: OptTx<'a>, address: Address) -> Result<bool> {
        self.nest_transaction(tx)
            .await?
            .perform(|tx| {
                Box::pin(async move {
                    Ok::<_, DbSqlError>(
                        network_registry::Entity::find()
                            .filter(network_registry::Column::ChainAddress.eq(address.to_hex()))
                            .one(tx.as_ref())
                            .await?
                            .is_some(),
                    )
                })
            })
            .await
    }

    async fn set_safe_eligibility<'a>(&'a self, tx: OptTx<'a>, address: Address, eligible: bool) -> Result<()> {
        self.nest_transaction(tx)
            .await?
            .perform(|tx| {
                Box::pin(async move {
                    if eligible {
                        let new_entry = network_eligibility::ActiveModel {
                            safe_address: Set(address.to_hex()),
                            ..Default::default()
                        };

                        match network_eligibility::Entity::insert(new_entry)
                            .on_conflict(
                                OnConflict::column(network_eligibility::Column::SafeAddress)
                                    .do_nothing()
                                    .to_owned(),
                            )
                            .exec(tx.as_ref())
                            .await
                        {
                            Ok(_) | Err(DbErr::RecordNotInserted) => Ok::<_, DbSqlError>(()),
                            Err(e) => Err(e.into()),
                        }
                    } else {
                        network_eligibility::Entity::delete_many()
                            .filter(network_eligibility::Column::SafeAddress.eq(address.to_hex()))
                            .exec(tx.as_ref())
                            .await?;
                        Ok::<_, DbSqlError>(())
                    }
                })
            })
            .await
    }

    async fn is_safe_eligible<'a>(&'a self, tx: OptTx<'a>, address: Address) -> Result<bool> {
        self.nest_transaction(tx)
            .await?
            .perform(|tx| {
                Box::pin(async move {
                    Ok::<_, DbSqlError>(
                        network_eligibility::Entity::find()
                            .filter(network_eligibility::Column::SafeAddress.eq(address.to_hex()))
                            .one(tx.as_ref())
                            .await?
                            .is_some(),
                    )
                })
            })
            .await
    }
}

#[cfg(test)]
mod tests {
    use crate::db::HoprDb;
    use crate::registry::HoprDbRegistryOperations;
    use hopr_crypto_types::keypairs::ChainKeypair;
    use hopr_crypto_types::prelude::Keypair;
    use hopr_primitive_types::prelude::Address;
    use lazy_static::lazy_static;

    lazy_static! {
        static ref ADDR_1: Address = "4331eaa9542b6b034c43090d9ec1c2198758dbc3"
            .parse()
            .expect("lazy static address should be valid");
        static ref ADDR_2: Address = "47d1677e018e79dcdd8a9c554466cb1556fa5007"
            .parse()
            .expect("lazy static address should be valid");
    }

    #[async_std::test]
    async fn test_network_registry_db() -> anyhow::Result<()> {
        let db = HoprDb::new_in_memory(ChainKeypair::random()).await?;

        assert!(!db.is_allowed_in_network_registry(None, *ADDR_1).await?);
        assert!(!db.is_allowed_in_network_registry(None, *ADDR_2).await?);

        db.set_access_in_network_registry(None, *ADDR_1, true).await?;

        assert!(db.is_allowed_in_network_registry(None, *ADDR_1).await?);
        assert!(!db.is_allowed_in_network_registry(None, *ADDR_2).await?);

        db.set_access_in_network_registry(None, *ADDR_1, true).await?;

        assert!(db.is_allowed_in_network_registry(None, *ADDR_1).await?);
        assert!(!db.is_allowed_in_network_registry(None, *ADDR_2).await?);

        db.set_access_in_network_registry(None, *ADDR_1, false).await?;

        assert!(!db.is_allowed_in_network_registry(None, *ADDR_1).await?);
        assert!(!db.is_allowed_in_network_registry(None, *ADDR_2).await?);

        db.set_access_in_network_registry(None, *ADDR_1, false).await?;

        assert!(!db.is_allowed_in_network_registry(None, *ADDR_1).await?);
        assert!(!db.is_allowed_in_network_registry(None, *ADDR_2).await?);
        Ok(())
    }

    #[async_std::test]
    async fn test_network_eligiblity_db() -> anyhow::Result<()> {
        let db = HoprDb::new_in_memory(ChainKeypair::random()).await?;

        assert!(!db.is_safe_eligible(None, *ADDR_1).await?);
        assert!(!db.is_safe_eligible(None, *ADDR_2).await?);

        db.set_safe_eligibility(None, *ADDR_1, true).await?;

        assert!(db.is_safe_eligible(None, *ADDR_1).await?);
        assert!(!db.is_safe_eligible(None, *ADDR_2).await?);

        db.set_safe_eligibility(None, *ADDR_1, true).await?;

        assert!(db.is_safe_eligible(None, *ADDR_1).await?);
        assert!(!db.is_safe_eligible(None, *ADDR_2).await?);

        db.set_safe_eligibility(None, *ADDR_1, false).await?;

        assert!(!db.is_safe_eligible(None, *ADDR_1).await?);
        assert!(!db.is_safe_eligible(None, *ADDR_2).await?);

        db.set_safe_eligibility(None, *ADDR_1, false).await?;

        assert!(!db.is_safe_eligible(None, *ADDR_1).await?);
        assert!(!db.is_safe_eligible(None, *ADDR_2).await?);
        Ok(())
    }
}