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
pub mod error;
#[cfg(test)]
mod test;

use std::str::FromStr;

use error::ContactOperationError;
use ethers::{
    providers::Middleware,
    types::{Address, Bytes, Signature, H160, U256},
};
use lib_didethresolver::{
    did_registry::DIDRegistry,
    types::{VerificationMethodProperties, XmtpAttribute},
    Resolver,
};
use xps_types::{GrantInstallationResult, KeyPackageResult, Status};

pub struct ContactOperations<Middleware> {
    registry: DIDRegistry<Middleware>,
    resolver: Resolver<Middleware>,
}

impl<M> ContactOperations<M>
where
    M: Middleware + 'static,
{
    /// Creates a new ContactOperations instance
    pub fn new(registry: DIDRegistry<M>) -> Self {
        let resolver = registry.clone().into();
        Self { registry, resolver }
    }

    /// Internal function to resolve a DID to an ethereum address
    fn resolve_did_address(&self, did: String) -> Result<H160, ContactOperationError<M>> {
        // for now, we will just assume the DID is a valid ethereum wallet address
        // TODO: Parse or resolve the actual DID

        let address = Address::from_slice(Bytes::from_str(did.as_ref())?.to_vec().as_slice());
        Ok(address)
    }

    /// Fetches key packages for a given DID using [`Resolver::resolve_did`]
    pub async fn fetch_key_packages(
        &self,
        did: String,
    ) -> Result<KeyPackageResult, ContactOperationError<M>> {
        let address = Address::from_str(&did)?;

        let resolution = self
            .resolver
            .resolve_did(address, None)
            .await
            .map_err(|e| ContactOperationError::ResolutionError(e, did))?;

        if resolution.metadata.deactivated {
            return Err(ContactOperationError::DIDDeactivated);
        }

        let document = resolution.document;

        let properties = document
            .verification_method
            .into_iter()
            .filter(|method| {
                method
                    .id
                    .fragment()
                    .map(|f| f.starts_with("xmtp-"))
                    .unwrap_or(false)
                    && method
                        .id
                        .contains_query("meta".into(), "installation".into())
            })
            .filter_map(|method| method.verification_properties)
            .collect::<Vec<VerificationMethodProperties>>();

        Ok(KeyPackageResult {
            status: Status::Success,
            message: "Key packages retrieved".to_string(),
            installation: properties
                .into_iter()
                .map(TryFrom::try_from)
                .collect::<Result<_, _>>()?,
        })
    }

    /// Grants an XMTP installation via the did:ethr registry.
    pub async fn grant_installation(
        &self,
        did: String,
        name: XmtpAttribute,
        value: Vec<u8>,
        signature: Signature,
        validity: U256,
    ) -> Result<GrantInstallationResult, ContactOperationError<M>> {
        let address = self.resolve_did_address(did)?;
        let attribute: [u8; 32] = name.into();
        log::debug!(
            "setting attribute {:#?}",
            String::from_utf8_lossy(&attribute)
        );

        let transaction_receipt = self
            .registry
            .set_attribute_signed(
                address,
                signature.v.try_into()?,
                signature.r.into(),
                signature.s.into(),
                attribute,
                value.into(),
                validity,
            )
            .send()
            .await?
            .await?;

        if let Some(ref receipt) = transaction_receipt {
            log::debug!(
                "Gas Used by transaction {}, Gas used in block {}, effective_price {}",
                receipt.gas_used.unwrap_or(0.into()),
                receipt.cumulative_gas_used,
                receipt.effective_gas_price.unwrap_or(0.into())
            );
        }

        Ok(GrantInstallationResult {
            status: Status::Success,
            message: "Installation request complete.".to_string(),
            transaction: transaction_receipt.map(|r| r.transaction_hash),
        })
    }

    /// Revokes an XMTP installation via the did:ethr registry.
    pub async fn revoke_installation(
        &self,
        did: String,
        name: XmtpAttribute,
        value: Vec<u8>,
        signature: Signature,
    ) -> Result<(), ContactOperationError<M>> {
        let address = self.resolve_did_address(did)?;
        let attribute: [u8; 32] = name.into();
        log::debug!(
            "Revoking attribute {:#?}",
            String::from_utf8_lossy(&attribute)
        );

        let transaction_receipt = self
            .registry
            .revoke_attribute_signed(
                address,
                signature.v.try_into()?,
                signature.r.into(),
                signature.s.into(),
                attribute,
                value.into(),
            )
            .send()
            .await?
            .await?;

        if let Some(ref receipt) = transaction_receipt {
            log::debug!(
                "Gas Used by transaction {}, Gas used in block {}, effective_price {}",
                receipt.gas_used.unwrap_or(0.into()),
                receipt.cumulative_gas_used,
                receipt.effective_gas_price.unwrap_or(0.into())
            );
        }

        Ok(())
    }

    /// get the nonce for a given address from [`DIDRegistry`]
    pub async fn nonce(&self, did: String) -> Result<U256, ContactOperationError<M>> {
        let address = self.resolve_did_address(did)?;
        let nonce = self.registry.nonce(address).await?;
        Ok(nonce)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ethers::{
        abi::AbiEncode,
        providers::{MockProvider, Provider},
    };
    use lib_didethresolver::did_registry::NonceReturn;

    impl ContactOperations<Provider<MockProvider>> {
        pub fn mocked() -> (Self, MockProvider) {
            let (mock_provider, mock) = Provider::mocked();
            let registry = DIDRegistry::new(H160::zero(), mock_provider.into());

            (ContactOperations::new(registry), mock)
        }
    }

    #[test]
    fn test_resolve_address_from_hexstr() {
        let addr = "0x0000000000000000000000000000000000000000";
        let (ops, _) = ContactOperations::mocked();
        assert_eq!(
            ops.resolve_did_address(addr.to_string()).unwrap(),
            H160::zero()
        );

        let addr = "0000000000000000000000000000000000000000";
        assert_eq!(
            ops.resolve_did_address(addr.to_string()).unwrap(),
            H160::zero()
        );
    }

    #[tokio::test]
    async fn test_nonce() {
        let (ops, mock) = ContactOperations::mocked();

        mock.push::<String, String>(NonceReturn(U256::from(212)).encode_hex())
            .unwrap();

        let nonce = ops
            .nonce("0x1111111111111111111111111111111111111111".to_string())
            .await
            .unwrap();

        assert_eq!(nonce, U256::from(212));
    }
}