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
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

pub mod entities;
pub mod error;
pub mod interface;

use std::collections::HashMap;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use wildland_crypto::identity::signing_keypair::PubKey;

use self::entities::ForestManifest;
use self::error::{CatlibError, CatlibResult};
use self::interface::CatLib;
use crate::{ForestIdentity, WildlandIdentity};

#[derive(Serialize, Deserialize)]
pub struct DeviceMetadata {
    pub name: String,
    pub pubkey: PubKey,
}

#[derive(Serialize, Deserialize)]
pub struct ForestMetaData {
    devices: Vec<DeviceMetadata>,
    free_storage_granted: bool,
}

impl ForestMetaData {
    pub fn new(devices: Vec<DeviceMetadata>) -> Self {
        Self {
            devices,
            free_storage_granted: false,
        }
    }

    pub fn get_device_metadata(&self, device_pubkey: PubKey) -> Option<&DeviceMetadata> {
        self.devices.iter().find(|d| d.pubkey == device_pubkey)
    }

    pub fn devices(&self) -> impl Iterator<Item = &DeviceMetadata> {
        self.devices.iter()
    }
}

impl TryFrom<ForestMetaData> for Vec<u8> {
    type Error = CatlibError;

    fn try_from(data: ForestMetaData) -> Result<Self, Self::Error> {
        serde_json::to_vec(&data)
            .map_err(|e| CatlibError::InvalidDataError(format!("Serialization error: {e}")))
    }
}

#[derive(Clone)]
pub struct CatLibService {
    catlib: Arc<dyn CatLib>,
}

impl CatLibService {
    pub fn new(catlib: Arc<dyn CatLib>) -> Result<Self, CatlibError> {
        catlib.is_db_alive()?;
        Ok(Self { catlib })
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub fn add_forest(
        &self,
        forest_identity: &ForestIdentity,
        this_device_identity: &WildlandIdentity,
        data: ForestMetaData,
    ) -> CatlibResult<Arc<dyn ForestManifest>> {
        self.catlib.create_forest(
            forest_identity.keypair.public().into(),
            HashMap::from([(this_device_identity.get_public_key().into(), "".into())]),
            data.try_into()?,
        )
    }

    pub fn mark_free_storage_granted(&self, forest: &Arc<dyn ForestManifest>) -> CatlibResult<()> {
        let mut forest_metadata = self.get_parsed_forest_metadata(forest)?;
        forest_metadata.free_storage_granted = true;
        forest.set_data(forest_metadata.try_into()?)?;
        Ok(())
    }

    pub fn is_free_storage_granted(&self, forest: &Arc<dyn ForestManifest>) -> CatlibResult<bool> {
        let forest_metadata = self.get_parsed_forest_metadata(forest)?;
        Ok(forest_metadata.free_storage_granted)
    }

    pub fn get_forest(&self, owner: &ForestIdentity) -> CatlibResult<Arc<dyn ForestManifest>> {
        self.catlib.get_forest(&owner.keypair.public().into())
    }

    fn get_parsed_forest_metadata(
        &self,
        forest: &Arc<dyn ForestManifest>,
    ) -> CatlibResult<ForestMetaData> {
        serde_json::from_slice(&forest.data()?).map_err(|e| {
            CatlibError::InvalidDataError(format!("Could not deserialize forest metadata {e}"))
        })
    }
}