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
// Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use super::role::{ElderRole, Role};
use crate::{
    capacity::{AdultsStorageInfo, Capacity, RateLimit},
    metadata::{adult_reader::AdultReader, Metadata},
    node_ops::NodeDuty,
    section_funds::{reward_wallets::RewardWallets, SectionFunds},
    transfers::{
        get_replicas::{replica_info, transfer_replicas},
        Transfers,
    },
    Node, Result,
};
use log::info;
use sn_data_types::{ActorHistory, NodeAge, PublicKey};
use sn_messaging::client::DataExchange;
use sn_routing::XorName;
use std::collections::BTreeMap;

impl Node {
    /// If we are an oldie we'll have a transfer instance,
    /// This updates the replica info on it.
    pub async fn update_replicas(&mut self) -> Result<()> {
        let elder = self.role.as_elder_mut()?;
        let info = replica_info(&self.network_api).await?;
        elder.transfers.update_replica_info(info);
        Ok(())
    }

    /// Level up a newbie to an oldie on promotion
    pub async fn level_up(&mut self) -> Result<()> {
        self.used_space.reset().await?;

        //
        // start handling metadata
        let adult_storage_info = AdultsStorageInfo::new();
        let reader = AdultReader::new(self.network_api.clone());
        let capacity = self.used_space.max_capacity().await;
        let meta_data = Metadata::new(
            &self.node_info.path(),
            capacity,
            adult_storage_info.clone(),
            reader,
        )
        .await?;

        //
        // start handling transfers
        let rate_limit =
            RateLimit::new(self.network_api.clone(), Capacity::new(adult_storage_info));
        let user_wallets = BTreeMap::<PublicKey, ActorHistory>::new();
        let replicas = transfer_replicas(&self.node_info, &self.network_api, user_wallets).await?;
        let transfers = Transfers::new(replicas, rate_limit);

        //
        // start handling node rewards
        let section_funds = SectionFunds::KeepingNodeWallets(RewardWallets::new(BTreeMap::<
            XorName,
            (NodeAge, PublicKey),
        >::new()));

        self.role = Role::Elder(ElderRole {
            meta_data,
            transfers,
            section_funds,
            received_initial_sync: false,
        });

        Ok(())
    }

    /// Continue the level up and handle more responsibilities.
    pub async fn synch_state(
        &mut self,
        node_wallets: BTreeMap<XorName, (NodeAge, PublicKey)>,
        user_wallets: BTreeMap<PublicKey, ActorHistory>,
        metadata: DataExchange,
    ) -> Result<NodeDuty> {
        let elder = self.role.as_elder_mut()?;

        if elder.received_initial_sync {
            info!("We are already received the initial sync from our section. Ignoring update");
            return Ok(NodeDuty::NoOp);
        }

        // --------- merge in provided user wallets ---------
        elder.transfers.merge(user_wallets).await?;
        // --------- merge in provided node reward stages ---------
        for (key, (age, wallet)) in &node_wallets {
            elder.section_funds.set_node_wallet(*key, *wallet, *age)
        }
        // --------- merge in provided metadata ---------
        elder.meta_data.update(metadata).await?;

        elder.received_initial_sync = true;

        let node_id = self.network_api.our_name().await;
        let no_wallet_found = node_wallets.get(&node_id).is_none();

        if no_wallet_found {
            info!(
                "Registering wallet of node: {} (since not found in received state)",
                node_id,
            );
            Ok(NodeDuty::Send(self.register_wallet().await))
        } else {
            Ok(NodeDuty::NoOp)
        }
    }
}