use async_trait::async_trait;
use hedera_proto::services;
use hedera_proto::services::file_service_client::FileServiceClient;
use time::{
Duration,
OffsetDateTime,
};
use tonic::transport::Channel;
use crate::entity_id::AutoValidateChecksum;
use crate::protobuf::ToProtobuf;
use crate::transaction::{
AnyTransactionData,
ToTransactionDataProtobuf,
TransactionExecute,
};
use crate::{
AccountId,
Error,
FileId,
Key,
KeyList,
LedgerId,
Transaction,
TransactionId,
};
pub type FileUpdateTransaction = Transaction<FileUpdateTransactionData>;
#[cfg_attr(feature = "ffi", serde_with::skip_serializing_none)]
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "ffi", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "ffi", serde(rename_all = "camelCase"))]
pub struct FileUpdateTransactionData {
file_id: Option<FileId>,
file_memo: Option<String>,
#[cfg_attr(feature = "ffi", serde(default))]
keys: Option<KeyList>,
#[cfg_attr(
feature = "ffi",
serde(with = "serde_with::As::<Option<serde_with::base64::Base64>>")
)]
contents: Option<Vec<u8>>,
#[cfg_attr(
feature = "ffi",
serde(with = "serde_with::As::<Option<serde_with::TimestampNanoSeconds>>")
)]
expiration_time: Option<OffsetDateTime>,
auto_renew_account_id: Option<AccountId>,
auto_renew_period: Option<Duration>,
}
impl FileUpdateTransaction {
pub fn file_id(&mut self, id: impl Into<FileId>) -> &mut Self {
self.body.data.file_id = Some(id.into());
self
}
pub fn file_memo(&mut self, memo: impl Into<String>) -> &mut Self {
self.body.data.file_memo = Some(memo.into());
self
}
pub fn contents(&mut self, contents: Vec<u8>) -> &mut Self {
self.body.data.contents = Some(contents);
self
}
pub fn keys<K: Into<Key>>(&mut self, keys: impl IntoIterator<Item = K>) -> &mut Self {
self.body.data.keys = Some(keys.into_iter().map(Into::into).collect());
self
}
pub fn expiration_time(&mut self, at: OffsetDateTime) -> &mut Self {
self.body.data.expiration_time = Some(at);
self
}
pub fn auto_renew_account_id(&mut self, id: AccountId) -> &mut Self {
self.body.data.auto_renew_account_id = Some(id);
self
}
pub fn auto_renew_period(&mut self, duration: Duration) -> &mut Self {
self.body.data.auto_renew_period = Some(duration);
self
}
}
#[async_trait]
impl TransactionExecute for FileUpdateTransactionData {
fn validate_checksums_for_ledger_id(&self, ledger_id: &LedgerId) -> Result<(), Error> {
self.file_id.validate_checksum_for_ledger_id(ledger_id)
}
async fn execute(
&self,
channel: Channel,
request: services::Transaction,
) -> Result<tonic::Response<services::TransactionResponse>, tonic::Status> {
FileServiceClient::new(channel).update_file(request).await
}
}
impl ToTransactionDataProtobuf for FileUpdateTransactionData {
fn to_transaction_data_protobuf(
&self,
_node_account_id: AccountId,
_transaction_id: &TransactionId,
) -> services::transaction_body::Data {
let file_id = self.file_id.to_protobuf();
let expiration_time = self.expiration_time.to_protobuf();
let keys = self.keys.to_protobuf().unwrap_or_default();
services::transaction_body::Data::FileUpdate(services::FileUpdateTransactionBody {
file_id,
expiration_time,
auto_renew_account: self.auto_renew_account_id.to_protobuf(),
auto_renew_period: self.auto_renew_period.to_protobuf(),
keys: Some(keys),
contents: self.contents.clone().unwrap_or_default(),
memo: self.file_memo.clone(),
})
}
}
impl From<FileUpdateTransactionData> for AnyTransactionData {
fn from(transaction: FileUpdateTransactionData) -> Self {
Self::FileUpdate(transaction)
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "ffi")]
mod ffi {
use std::str::FromStr;
use assert_matches::assert_matches;
use time::OffsetDateTime;
use crate::transaction::{
AnyTransaction,
AnyTransactionData,
};
use crate::{
FileId,
FileUpdateTransaction,
Key,
PublicKey,
};
const FILE_UPDATE_TRANSACTION_JSON: &str = r#"{
"$type": "fileUpdate",
"fileId": "0.0.1001",
"fileMemo": "File memo",
"keys": {
"keys": [
{
"single": "302a300506032b6570032100d1ad76ed9b057a3d3f2ea2d03b41bcd79aeafd611f941924f0f6da528ab066fd"
}
]
},
"contents": "SGVsbG8sIHdvcmxkIQ==",
"expirationTime": 1656352251277559886
}"#;
const SIGN_KEY: &str =
"302a300506032b6570032100d1ad76ed9b057a3d3f2ea2d03b41bcd79aeafd611f941924f0f6da528ab066fd";
#[test]
fn it_should_serialize() -> anyhow::Result<()> {
let mut transaction = FileUpdateTransaction::new();
transaction
.file_id(FileId::from(1001))
.file_memo("File memo")
.keys([PublicKey::from_str(SIGN_KEY)?])
.contents("Hello, world!".into())
.expiration_time(OffsetDateTime::from_unix_timestamp_nanos(1656352251277559886)?);
let transaction_json = serde_json::to_string_pretty(&transaction)?;
assert_eq!(transaction_json, FILE_UPDATE_TRANSACTION_JSON);
Ok(())
}
#[test]
fn it_should_deserialize() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(FILE_UPDATE_TRANSACTION_JSON)?;
let data = assert_matches!(transaction.body.data, AnyTransactionData::FileUpdate(transaction) => transaction);
assert_eq!(data.file_id.unwrap(), FileId::from(1001));
assert_eq!(data.file_memo.unwrap(), "File memo");
assert_eq!(
data.expiration_time.unwrap(),
OffsetDateTime::from_unix_timestamp_nanos(1656352251277559886)?
);
let sign_key = assert_matches!(data.keys.unwrap().remove(0), Key::Single(public_key) => public_key);
assert_eq!(sign_key, PublicKey::from_str(SIGN_KEY)?);
let bytes: Vec<u8> = "Hello, world!".into();
assert_eq!(data.contents.unwrap(), bytes);
Ok(())
}
}
}