use std::cmp;
use std::num::NonZeroUsize;
use hedera_proto::services;
use hedera_proto::services::file_service_client::FileServiceClient;
use tonic::transport::Channel;
use crate::protobuf::{
FromProtobuf,
ToProtobuf,
};
use crate::transaction::{
AnyTransactionData,
ChunkData,
ChunkInfo,
ChunkedTransactionData,
ToSchedulableTransactionDataProtobuf,
ToTransactionDataProtobuf,
TransactionData,
TransactionExecute,
TransactionExecuteChunked,
};
use crate::{
BoxGrpcFuture,
Error,
FileId,
LedgerId,
Transaction,
ValidateChecksums,
};
pub type FileAppendTransaction = Transaction<FileAppendTransactionData>;
#[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", default))]
pub struct FileAppendTransactionData {
file_id: Option<FileId>,
#[cfg_attr(feature = "ffi", serde(flatten))]
chunk_data: ChunkData,
}
impl FileAppendTransaction {
#[must_use]
pub fn get_file_id(&self) -> Option<FileId> {
self.data().file_id
}
pub fn file_id(&mut self, id: impl Into<FileId>) -> &mut Self {
self.data_mut().file_id = Some(id.into());
self
}
pub fn get_contents(&self) -> Option<&[u8]> {
Some(self.data().chunk_data.data.as_slice())
}
pub fn contents(&mut self, contents: impl Into<Vec<u8>>) -> &mut Self {
self.data_mut().chunk_data.data = contents.into();
self
}
}
impl TransactionData for FileAppendTransactionData {
fn maybe_chunk_data(&self) -> Option<&ChunkData> {
Some(self.chunk_data())
}
fn wait_for_receipt(&self) -> bool {
true
}
}
impl ChunkedTransactionData for FileAppendTransactionData {
fn chunk_data(&self) -> &ChunkData {
&self.chunk_data
}
fn chunk_data_mut(&mut self) -> &mut ChunkData {
&mut self.chunk_data
}
}
impl TransactionExecute for FileAppendTransactionData {
fn execute(
&self,
channel: Channel,
request: services::Transaction,
) -> BoxGrpcFuture<'_, services::TransactionResponse> {
Box::pin(async { FileServiceClient::new(channel).append_content(request).await })
}
}
impl TransactionExecuteChunked for FileAppendTransactionData {}
impl ValidateChecksums for FileAppendTransactionData {
fn validate_checksums(&self, ledger_id: &LedgerId) -> Result<(), Error> {
self.file_id.validate_checksums(ledger_id)
}
}
impl ToTransactionDataProtobuf for FileAppendTransactionData {
fn to_transaction_data_protobuf(
&self,
chunk_info: &ChunkInfo,
) -> services::transaction_body::Data {
services::transaction_body::Data::FileAppend(services::FileAppendTransactionBody {
file_id: self.file_id.to_protobuf(),
contents: self.chunk_data.message_chunk(chunk_info).to_vec(),
})
}
}
impl ToSchedulableTransactionDataProtobuf for FileAppendTransactionData {
fn to_schedulable_transaction_data_protobuf(
&self,
) -> services::schedulable_transaction_body::Data {
assert!(self.chunk_data.used_chunks() == 1);
services::schedulable_transaction_body::Data::FileAppend(
services::FileAppendTransactionBody {
file_id: self.file_id.to_protobuf(),
contents: self.chunk_data.data.clone(),
},
)
}
}
impl From<FileAppendTransactionData> for AnyTransactionData {
fn from(transaction: FileAppendTransactionData) -> Self {
Self::FileAppend(transaction)
}
}
impl FromProtobuf<services::FileAppendTransactionBody> for FileAppendTransactionData {
fn from_protobuf(pb: services::FileAppendTransactionBody) -> crate::Result<Self> {
Self::from_protobuf(Vec::from([pb]))
}
}
impl FromProtobuf<Vec<services::FileAppendTransactionBody>> for FileAppendTransactionData {
fn from_protobuf(pb: Vec<services::FileAppendTransactionBody>) -> crate::Result<Self> {
let total_chunks = pb.len();
let mut iter = pb.into_iter();
let pb_first = iter.next().expect("Empty transaction (should've been handled earlier)");
let file_id = Option::from_protobuf(pb_first.file_id)?;
let mut largest_chunk_size = pb_first.contents.len();
let mut contents = pb_first.contents;
for item in iter {
largest_chunk_size = cmp::max(largest_chunk_size, item.contents.len());
contents.extend_from_slice(&item.contents);
}
Ok(Self {
file_id,
chunk_data: ChunkData {
max_chunks: total_chunks,
chunk_size: NonZeroUsize::new(largest_chunk_size)
.unwrap_or_else(|| NonZeroUsize::new(1).unwrap()),
data: contents,
},
})
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "ffi")]
mod ffi {
use assert_matches::assert_matches;
use crate::transaction::{
AnyTransaction,
AnyTransactionData,
};
use crate::{
FileAppendTransaction,
FileId,
};
const FILE_APPEND_TRANSACTION_JSON: &str = r#"{
"$type": "fileAppend",
"fileId": "0.0.1001",
"data": "QXBwZW5kaW5nIHRoZXNlIGJ5dGVzIHRvIGZpbGUgMTAwMQ=="
}"#;
#[test]
fn it_should_serialize() -> anyhow::Result<()> {
let mut transaction = FileAppendTransaction::new();
transaction
.file_id(FileId::from(1001))
.contents(b"Appending these bytes to file 1001".to_vec());
let transaction_json = serde_json::to_string_pretty(&transaction)?;
assert_eq!(transaction_json, FILE_APPEND_TRANSACTION_JSON);
Ok(())
}
#[test]
fn it_should_deserialize() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(FILE_APPEND_TRANSACTION_JSON)?;
let data = assert_matches!(transaction.into_body().data, AnyTransactionData::FileAppend(transaction) => transaction);
assert_eq!(data.file_id.unwrap(), FileId::from(1001));
let bytes: Vec<u8> = "Appending these bytes to file 1001".into();
assert_eq!(data.chunk_data.data, bytes);
Ok(())
}
}
}