bee_block/unlock/
reference.rs

1// Copyright 2020-2021 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::{unlock::UnlockIndex, Error};
5
6/// An [`Unlock`](crate::unlock::Unlock) that refers to another unlock.
7#[derive(Clone, Debug, Eq, PartialEq, Hash, packable::Packable)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9#[packable(unpack_error = Error, with = Error::InvalidReferenceIndex)]
10pub struct ReferenceUnlock(UnlockIndex);
11
12impl TryFrom<u16> for ReferenceUnlock {
13    type Error = Error;
14
15    fn try_from(index: u16) -> Result<Self, Self::Error> {
16        Self::new(index)
17    }
18}
19
20impl ReferenceUnlock {
21    /// The [`Unlock`](crate::unlock::Unlock) kind of a [`ReferenceUnlock`].
22    pub const KIND: u8 = 1;
23
24    /// Creates a new [`ReferenceUnlock`].
25    #[inline(always)]
26    pub fn new(index: u16) -> Result<Self, Error> {
27        index.try_into().map(Self).map_err(Error::InvalidReferenceIndex)
28    }
29
30    /// Return the index of a [`ReferenceUnlock`].
31    #[inline(always)]
32    pub fn index(&self) -> u16 {
33        self.0.get()
34    }
35}
36
37#[cfg(feature = "dto")]
38#[allow(missing_docs)]
39pub mod dto {
40    use serde::{Deserialize, Serialize};
41
42    /// References a previous unlock in order to substitute the duplication of the same unlock data for inputs which
43    /// unlock through the same data.
44    #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
45    pub struct ReferenceUnlockDto {
46        #[serde(rename = "type")]
47        pub kind: u8,
48        #[serde(rename = "reference")]
49        pub index: u16,
50    }
51}