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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use crate::account::DataValue;
use crate::crypto::MuxedAccount;
use crate::error::{Error, Result};
use crate::operations::Operation;
use crate::xdr;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManageDataOperation {
    source_account: Option<MuxedAccount>,
    data_name: String,
    data_value: Option<DataValue>,
}

#[derive(Debug)]
pub struct ManageDataOperationBuilder {
    source_account: Option<MuxedAccount>,
    data_name: Option<String>,
    data_value: Option<DataValue>,
}

impl ManageDataOperation {
    /// Retrieves the operation source account.
    pub fn source_account(&self) -> &Option<MuxedAccount> {
        &self.source_account
    }

    /// Retrieves a reference to the operation source account.
    pub fn source_account_mut(&mut self) -> &mut Option<MuxedAccount> {
        &mut self.source_account
    }

    /// Retrieves the operation data name.
    pub fn data_name(&self) -> &str {
        &self.data_name
    }

    /// Retrieves a mutable reference to the operation data name.
    pub fn data_name_mut(&mut self) -> &mut str {
        &mut self.data_name
    }

    /// Retrieves the operation data value.
    pub fn data_value(&self) -> &Option<DataValue> {
        &self.data_value
    }

    /// Retrieves a mutable reference to the operation data value.
    pub fn data_value_mut(&mut self) -> &mut Option<DataValue> {
        &mut self.data_value
    }

    /// Returns the xdr operation body.
    pub fn to_xdr_operation_body(&self) -> Result<xdr::OperationBody> {
        let data_name = xdr::String64::new(self.data_name.to_string());
        let data_value = self.data_value.as_ref().map(|d| d.to_xdr()).transpose()?;
        let inner = xdr::ManageDataOp {
            data_name,
            data_value,
        };
        Ok(xdr::OperationBody::ManageData(inner))
    }

    /// Creates from the xdr operation body.
    pub fn from_xdr_operation_body(
        source_account: Option<MuxedAccount>,
        x: &xdr::ManageDataOp,
    ) -> Result<ManageDataOperation> {
        let data_name = x.data_name.value.to_string();
        let data_value = x
            .data_value
            .as_ref()
            .map(|d| DataValue::from_xdr(d))
            .transpose()?;

        Ok(ManageDataOperation {
            source_account,
            data_name,
            data_value,
        })
    }
}

impl ManageDataOperationBuilder {
    pub fn new() -> ManageDataOperationBuilder {
        ManageDataOperationBuilder {
            source_account: None,
            data_name: None,
            data_value: None,
        }
    }

    pub fn with_source_account<S>(mut self, source: S) -> ManageDataOperationBuilder
    where
        S: Into<MuxedAccount>,
    {
        self.source_account = Some(source.into());
        self
    }

    pub fn with_data_name(mut self, name: String) -> ManageDataOperationBuilder {
        self.data_name = Some(name);
        self
    }

    pub fn with_data_value(mut self, value: Option<DataValue>) -> ManageDataOperationBuilder {
        self.data_value = value;
        self
    }

    pub fn build(self) -> Result<Operation> {
        let data_name = self
            .data_name
            .ok_or_else(|| Error::InvalidOperation("missing manage data data name".to_string()))?;

        Ok(Operation::ManageData(ManageDataOperation {
            source_account: self.source_account,
            data_name,
            data_value: self.data_value,
        }))
    }
}

#[cfg(test)]
mod tests {
    use crate::account::{AccountFlags, DataValue, TrustLineFlags};
    use crate::amount::{Amount, Price, Stroops};
    use crate::asset::{Asset, CreditAssetType};
    use crate::crypto::KeyPair;
    use crate::memo::Memo;
    use crate::network::Network;
    use crate::operations::Operation;
    use crate::time_bounds::TimeBounds;
    use crate::transaction::{Transaction, TransactionEnvelope, MIN_BASE_FEE};
    use crate::xdr::{XDRDeserialize, XDRSerialize};
    use std::str::FromStr;

    fn keypair0() -> KeyPair {
        // GDQNY3PBOJOKYZSRMK2S7LHHGWZIUISD4QORETLMXEWXBI7KFZZMKTL3
        KeyPair::from_secret_seed("SBPQUZ6G4FZNWFHKUWC5BEYWF6R52E3SEP7R3GWYSM2XTKGF5LNTWW4R")
            .unwrap()
    }

    fn keypair1() -> KeyPair {
        // GAS4V4O2B7DW5T7IQRPEEVCRXMDZESKISR7DVIGKZQYYV3OSQ5SH5LVP
        KeyPair::from_secret_seed("SBMSVD4KKELKGZXHBUQTIROWUAPQASDX7KEJITARP4VMZ6KLUHOGPTYW")
            .unwrap()
    }

    fn keypair2() -> KeyPair {
        // GB7BDSZU2Y27LYNLALKKALB52WS2IZWYBDGY6EQBLEED3TJOCVMZRH7H
        KeyPair::from_secret_seed("SBZVMB74Z76QZ3ZOY7UTDFYKMEGKW5XFJEB6PFKBF4UYSSWHG4EDH7PY")
            .unwrap()
    }

    #[test]
    fn test_manage_data() {
        let kp = keypair0();
        let value = DataValue::from_slice("value value".as_bytes()).unwrap();
        let op = Operation::new_manage_data()
            .with_data_name("TEST TEST".to_string())
            .with_data_value(Some(value))
            .build()
            .unwrap();

        let mut tx = Transaction::builder(kp.public_key().clone(), 3556091187167235, MIN_BASE_FEE)
            .add_operation(op)
            .to_transaction()
            .unwrap();
        tx.sign(&kp, &Network::new_test());
        let envelope = tx.to_envelope();
        let xdr = envelope.xdr_base64().unwrap();
        let expected = "AAAAAgAAAADg3G3hclysZlFitS+s5zWyiiJD5B0STWy5LXCj6i5yxQAAAGQADKI/AAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAKAAAACVRFU1QgVEVTVAAAAAAAAAEAAAALdmFsdWUgdmFsdWUAAAAAAAAAAAHqLnLFAAAAQLxeb1DkXDTXi/rOffnHpyxuJhl8vN/GDMKLtxFFTGn5b99FNHmWUyUoxb4KTE9bBguIe33SEQ/npj32f2vt/gY=";
        assert_eq!(expected, xdr);
        let back = TransactionEnvelope::from_xdr_base64(&xdr).unwrap();
        assert_eq!(envelope, back);
    }

    #[test]
    fn test_manage_data_with_source_account() {
        let kp = keypair0();
        let kp1 = keypair1();
        let value = DataValue::from_slice("value value".as_bytes()).unwrap();
        let op = Operation::new_manage_data()
            .with_source_account(kp1.public_key().clone())
            .with_data_name("TEST TEST".to_string())
            .with_data_value(Some(value))
            .build()
            .unwrap();

        let mut tx = Transaction::builder(kp.public_key().clone(), 3556091187167235, MIN_BASE_FEE)
            .add_operation(op)
            .to_transaction()
            .unwrap();
        tx.sign(&kp, &Network::new_test());
        let envelope = tx.to_envelope();
        let xdr = envelope.xdr_base64().unwrap();
        let expected = "AAAAAgAAAADg3G3hclysZlFitS+s5zWyiiJD5B0STWy5LXCj6i5yxQAAAGQADKI/AAAAAwAAAAAAAAAAAAAAAQAAAAEAAAAAJcrx2g/Hbs/ohF5CVFG7B5JJSJR+OqDKzDGK7dKHZH4AAAAKAAAACVRFU1QgVEVTVAAAAAAAAAEAAAALdmFsdWUgdmFsdWUAAAAAAAAAAAHqLnLFAAAAQBQKnwjKQ1RbYg0rk7G9VV1jHwM29YEp1EoOug960nTVWga6aFmPlQ0mDDudEsbSMq+9G8eYX5mcu9EHTjZUBQI=";
        assert_eq!(expected, xdr);
        let back = TransactionEnvelope::from_xdr_base64(&xdr).unwrap();
        assert_eq!(envelope, back);
    }
}