bee_block/input/
utxo.rs

1// Copyright 2020-2021 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use core::str::FromStr;
5
6use derive_more::From;
7
8use crate::{output::OutputId, payload::transaction::TransactionId, Error};
9
10/// Represents an input referencing an output.
11#[derive(Clone, Eq, PartialEq, Hash, Ord, PartialOrd, From, packable::Packable)]
12pub struct UtxoInput(OutputId);
13
14impl UtxoInput {
15    /// The input kind of a [`UtxoInput`].
16    pub const KIND: u8 = 0;
17
18    /// Creates a new [`UtxoInput`].
19    pub fn new(id: TransactionId, index: u16) -> Result<Self, Error> {
20        Ok(Self(OutputId::new(id, index)?))
21    }
22
23    /// Returns the output id of a [`UtxoInput`].
24    pub fn output_id(&self) -> &OutputId {
25        &self.0
26    }
27}
28
29#[cfg(feature = "serde")]
30string_serde_impl!(UtxoInput);
31
32impl FromStr for UtxoInput {
33    type Err = Error;
34
35    fn from_str(s: &str) -> Result<Self, Self::Err> {
36        Ok(UtxoInput(OutputId::from_str(s)?))
37    }
38}
39
40impl core::fmt::Display for UtxoInput {
41    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
42        write!(f, "{}", self.0)
43    }
44}
45
46impl core::fmt::Debug for UtxoInput {
47    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
48        write!(f, "UtxoInput({})", self.0)
49    }
50}
51
52#[cfg(feature = "dto")]
53#[allow(missing_docs)]
54pub mod dto {
55    use serde::{Deserialize, Serialize};
56
57    use super::*;
58    use crate::error::dto::DtoError;
59
60    /// Describes an input which references an unspent transaction output to consume.
61    #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
62    pub struct UtxoInputDto {
63        #[serde(rename = "type")]
64        pub kind: u8,
65        #[serde(rename = "transactionId")]
66        pub transaction_id: String,
67        #[serde(rename = "transactionOutputIndex")]
68        pub transaction_output_index: u16,
69    }
70
71    impl From<&UtxoInput> for UtxoInputDto {
72        fn from(value: &UtxoInput) -> Self {
73            UtxoInputDto {
74                kind: UtxoInput::KIND,
75                transaction_id: value.output_id().transaction_id().to_string(),
76                transaction_output_index: value.output_id().index(),
77            }
78        }
79    }
80
81    impl TryFrom<&UtxoInputDto> for UtxoInput {
82        type Error = DtoError;
83
84        fn try_from(value: &UtxoInputDto) -> Result<Self, Self::Error> {
85            Ok(UtxoInput::new(
86                value
87                    .transaction_id
88                    .parse::<TransactionId>()
89                    .map_err(|_| DtoError::InvalidField("transactionId"))?,
90                value.transaction_output_index,
91            )?)
92        }
93    }
94}