use hedera_proto::services;
use hedera_proto::services::file_service_client::FileServiceClient;
use time::{
Duration,
OffsetDateTime,
};
use tonic::transport::Channel;
use crate::entity_id::ValidateChecksums;
use crate::protobuf::{
FromProtobuf,
ToProtobuf,
};
use crate::transaction::{
AnyTransactionData,
ChunkInfo,
ToSchedulableTransactionDataProtobuf,
ToTransactionDataProtobuf,
TransactionData,
TransactionExecute,
};
use crate::{
AccountId,
BoxGrpcFuture,
Key,
KeyList,
LedgerId,
Transaction,
};
pub type FileCreateTransaction = Transaction<FileCreateTransactionData>;
#[cfg_attr(feature = "ffi", serde_with::skip_serializing_none)]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "ffi", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "ffi", serde(default, rename_all = "camelCase"))]
pub struct FileCreateTransactionData {
#[cfg_attr(feature = "ffi", serde(skip_serializing_if = "String::is_empty"))]
file_memo: String,
keys: Option<KeyList>,
#[cfg_attr(
feature = "ffi",
serde(with = "serde_with::As::<Option<serde_with::base64::Base64>>")
)]
contents: Option<Vec<u8>>,
auto_renew_period: Option<Duration>,
auto_renew_account_id: Option<AccountId>,
#[cfg_attr(
feature = "ffi",
serde(with = "serde_with::As::<Option<serde_with::TimestampNanoSeconds>>")
)]
expiration_time: Option<OffsetDateTime>,
}
impl Default for FileCreateTransactionData {
fn default() -> Self {
Self {
file_memo: String::new(),
keys: None,
contents: None,
auto_renew_period: None,
auto_renew_account_id: None,
expiration_time: Some(OffsetDateTime::now_utc() + Duration::days(90)),
}
}
}
impl FileCreateTransaction {
#[must_use]
pub fn get_file_memo(&self) -> &str {
&self.data().file_memo
}
pub fn file_memo(&mut self, memo: impl Into<String>) -> &mut Self {
self.data_mut().file_memo = memo.into();
self
}
#[must_use]
pub fn get_contents(&self) -> Option<&[u8]> {
self.data().contents.as_deref()
}
pub fn contents(&mut self, contents: impl Into<Vec<u8>>) -> &mut Self {
self.data_mut().contents = Some(contents.into());
self
}
#[must_use]
pub fn get_keys(&self) -> Option<&KeyList> {
self.data().keys.as_ref()
}
pub fn keys<K: Into<Key>>(&mut self, keys: impl IntoIterator<Item = K>) -> &mut Self {
self.data_mut().keys = Some(keys.into_iter().map(Into::into).collect());
self
}
#[must_use]
pub fn get_auto_renew_period(&self) -> Option<Duration> {
self.data().auto_renew_period
}
pub fn auto_renew_period(&mut self, duration: Duration) -> &mut Self {
self.data_mut().auto_renew_period = Some(duration);
self
}
#[must_use]
pub fn get_auto_renew_account_id(&self) -> Option<AccountId> {
self.data().auto_renew_account_id
}
pub fn auto_renew_account_id(&mut self, id: AccountId) -> &mut Self {
self.data_mut().auto_renew_account_id = Some(id);
self
}
#[must_use]
pub fn get_expiration_time(&self) -> Option<OffsetDateTime> {
self.data().expiration_time
}
pub fn expiration_time(&mut self, at: OffsetDateTime) -> &mut Self {
self.require_not_frozen();
self.data_mut().expiration_time = Some(at);
self
}
}
impl TransactionData for FileCreateTransactionData {}
impl TransactionExecute for FileCreateTransactionData {
fn execute(
&self,
channel: Channel,
request: services::Transaction,
) -> BoxGrpcFuture<'_, services::TransactionResponse> {
Box::pin(async { FileServiceClient::new(channel).create_file(request).await })
}
}
impl ValidateChecksums for FileCreateTransactionData {
fn validate_checksums(&self, ledger_id: &LedgerId) -> crate::Result<()> {
self.auto_renew_account_id.validate_checksums(ledger_id)?;
Ok(())
}
}
impl ToTransactionDataProtobuf for FileCreateTransactionData {
fn to_transaction_data_protobuf(
&self,
chunk_info: &ChunkInfo,
) -> services::transaction_body::Data {
let _ = chunk_info.assert_single_transaction();
services::transaction_body::Data::FileCreate(self.to_protobuf())
}
}
impl ToSchedulableTransactionDataProtobuf for FileCreateTransactionData {
fn to_schedulable_transaction_data_protobuf(
&self,
) -> services::schedulable_transaction_body::Data {
services::schedulable_transaction_body::Data::FileCreate(self.to_protobuf())
}
}
impl From<FileCreateTransactionData> for AnyTransactionData {
fn from(transaction: FileCreateTransactionData) -> Self {
Self::FileCreate(transaction)
}
}
impl FromProtobuf<services::FileCreateTransactionBody> for FileCreateTransactionData {
fn from_protobuf(pb: services::FileCreateTransactionBody) -> crate::Result<Self> {
Ok(Self {
file_memo: pb.memo,
keys: Option::from_protobuf(pb.keys)?,
contents: Some(pb.contents),
auto_renew_period: pb.auto_renew_period.map(Into::into),
auto_renew_account_id: Option::from_protobuf(pb.auto_renew_account)?,
expiration_time: pb.expiration_time.map(Into::into),
})
}
}
impl ToProtobuf for FileCreateTransactionData {
type Protobuf = services::FileCreateTransactionBody;
fn to_protobuf(&self) -> Self::Protobuf {
services::FileCreateTransactionBody {
auto_renew_period: self.auto_renew_period.to_protobuf(),
auto_renew_account: self.auto_renew_account_id.to_protobuf(),
expiration_time: self.expiration_time.to_protobuf(),
keys: self.keys.to_protobuf(),
contents: self.contents.clone().unwrap_or_default(),
shard_id: None,
realm_id: None,
new_realm_admin_key: None,
memo: self.file_memo.clone(),
}
}
}
#[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::{
FileCreateTransaction,
Key,
PublicKey,
};
const FILE_CREATE_EMPTY: &str = r#"{
"$type": "fileCreate"
}"#;
const FILE_CREATE_TRANSACTION_JSON: &str = r#"{
"$type": "fileCreate",
"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 = FileCreateTransaction::new();
transaction
.file_memo("File memo")
.keys([PublicKey::from_str(SIGN_KEY)?])
.contents("Hello, world!")
.expiration_time(OffsetDateTime::from_unix_timestamp_nanos(1656352251277559886)?);
let transaction_json = serde_json::to_string_pretty(&transaction)?;
assert_eq!(transaction_json, FILE_CREATE_TRANSACTION_JSON);
Ok(())
}
#[test]
fn it_should_deserialize() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(FILE_CREATE_TRANSACTION_JSON)?;
let data = assert_matches!(transaction.into_body().data, AnyTransactionData::FileCreate(transaction) => transaction);
assert_eq!(data.file_memo, "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(())
}
#[test]
fn it_should_deserialize_empty() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(FILE_CREATE_EMPTY)?;
assert_matches!(transaction.data(), AnyTransactionData::FileCreate(transaction) => transaction);
Ok(())
}
}
}