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
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use core::mem::size_of;

use packable::{
    error::{UnpackError, UnpackErrorExt},
    packer::Packer,
    unpacker::Unpacker,
    Packable,
};

use crate::{output::OutputId, payload::milestone::MilestoneIndex, BlockId, Error};

const DEFAULT_BYTE_COST: u32 = 500;
const DEFAULT_BYTE_COST_FACTOR_KEY: u8 = 10;
const DEFAULT_BYTE_COST_FACTOR_DATA: u8 = 1;

type ConfirmationUnixTimestamp = u32;

/// Builder for a [`RentStructure`].
#[derive(Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[must_use]
pub struct RentStructureBuilder {
    #[cfg_attr(feature = "serde", serde(alias = "vByteCost"))]
    v_byte_cost: Option<u32>,
    #[cfg_attr(feature = "serde", serde(alias = "vByteFactorKey"))]
    v_byte_factor_key: Option<u8>,
    #[cfg_attr(feature = "serde", serde(alias = "vByteFactorData"))]
    v_byte_factor_data: Option<u8>,
}

impl RentStructureBuilder {
    /// Returns a new [`RentStructureBuilder`].
    pub fn new() -> Self {
        Default::default()
    }

    /// Sets the byte cost for the storage deposit.
    pub fn byte_cost(mut self, byte_cost: u32) -> Self {
        self.v_byte_cost.replace(byte_cost);
        self
    }

    /// Sets the virtual byte weight for the key fields.
    pub fn key_factor(mut self, weight: u8) -> Self {
        self.v_byte_factor_key.replace(weight);
        self
    }

    /// Sets the virtual byte weight for the data fields.
    pub fn data_factor(mut self, weight: u8) -> Self {
        self.v_byte_factor_data.replace(weight);
        self
    }

    /// Returns the built [`RentStructure`].
    pub fn finish(self) -> RentStructure {
        let v_byte_factor_key = self.v_byte_factor_key.unwrap_or(DEFAULT_BYTE_COST_FACTOR_KEY);
        let v_byte_factor_data = self.v_byte_factor_data.unwrap_or(DEFAULT_BYTE_COST_FACTOR_DATA);
        let v_byte_offset = v_byte_offset(v_byte_factor_key, v_byte_factor_data);

        RentStructure {
            v_byte_cost: self.v_byte_cost.unwrap_or(DEFAULT_BYTE_COST),
            v_byte_factor_key,
            v_byte_factor_data,
            v_byte_offset,
        }
    }
}

/// Specifies the current parameters for the byte cost computation.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RentStructure {
    /// Cost in tokens per virtual byte.
    pub v_byte_cost: u32,
    /// The weight factor used for key fields in the outputs.
    pub v_byte_factor_key: u8,
    /// The weight factor used for data fields in the outputs.
    pub v_byte_factor_data: u8,
    /// The offset in addition to the other fields.
    v_byte_offset: u32,
}

impl RentStructure {
    /// Returns a builder for this config.
    pub fn build() -> RentStructureBuilder {
        RentStructureBuilder::new()
    }
}

impl Packable for RentStructure {
    type UnpackError = Error;

    fn pack<P: Packer>(&self, packer: &mut P) -> Result<(), P::Error> {
        self.v_byte_cost.pack(packer)?;
        self.v_byte_factor_key.pack(packer)?;
        self.v_byte_factor_data.pack(packer)?;

        Ok(())
    }

    fn unpack<U: Unpacker, const VERIFY: bool>(
        unpacker: &mut U,
    ) -> Result<Self, UnpackError<Self::UnpackError, U::Error>> {
        let v_byte_cost = u32::unpack::<_, VERIFY>(unpacker).coerce()?;
        let v_byte_factor_key = u8::unpack::<_, VERIFY>(unpacker).coerce()?;
        let v_byte_factor_data = u8::unpack::<_, VERIFY>(unpacker).coerce()?;
        let v_byte_offset = v_byte_offset(v_byte_factor_key, v_byte_factor_data);

        Ok(Self {
            v_byte_cost,
            v_byte_factor_key,
            v_byte_factor_data,
            v_byte_offset,
        })
    }
}

/// A trait to facilitate the computation of the byte cost of block outputs, which is central to dust protection.
pub trait Rent {
    /// Different fields in a type lead to different storage requirements for the ledger state.
    fn weighted_bytes(&self, config: &RentStructure) -> u64;

    /// Computes the rent cost given a [`RentStructure`].
    fn rent_cost(&self, config: &RentStructure) -> u64 {
        config.v_byte_cost as u64 * (self.weighted_bytes(config) + config.v_byte_offset as u64)
    }
}

impl<T: Rent, const N: usize> Rent for [T; N] {
    fn weighted_bytes(&self, config: &RentStructure) -> u64 {
        self.iter().map(|elem| elem.weighted_bytes(config)).sum()
    }
}

fn v_byte_offset(v_byte_factor_key: u8, v_byte_factor_data: u8) -> u32 {
    size_of::<OutputId>() as u32 * v_byte_factor_key as u32
        + size_of::<BlockId>() as u32 * v_byte_factor_data as u32
        + size_of::<MilestoneIndex>() as u32 * v_byte_factor_data as u32
        + size_of::<ConfirmationUnixTimestamp>() as u32 * v_byte_factor_data as u32
}