use crate::error::*;
use iota_bundle_preview::{Address, Hash, Tag, Transaction, TransactionField};
use iota_ternary_preview::TryteBuf;
use serde::ser::{Serialize, SerializeSeq, SerializeStruct, Serializer};
#[derive(Serialize)]
pub struct TransactionDef {
payload: String,
address: String,
value: String,
obsolete_tag: String,
timestamp: String,
index: String,
last_index: String,
bundle: Vec<i8>,
trunk: Vec<i8>,
branch: Vec<i8>,
tag: String,
attachment_ts: String,
attachment_lbts: String,
attachment_ubts: String,
nonce: String,
}
impl From<&Transaction> for TransactionDef {
fn from(transaction: &Transaction) -> Self {
TransactionDef {
payload: serde_json::to_string(transaction.payload()).unwrap(),
address: serde_json::to_string(transaction.address()).unwrap(),
value: serde_json::to_string(transaction.value()).unwrap(),
obsolete_tag: serde_json::to_string(transaction.obsolete_tag()).unwrap(),
timestamp: serde_json::to_string(transaction.timestamp()).unwrap(),
index: serde_json::to_string(transaction.index()).unwrap(),
last_index: serde_json::to_string(transaction.last_index()).unwrap(),
bundle: transaction.bundle().as_bytes().to_vec(),
trunk: transaction.trunk().as_bytes().to_vec(),
branch: transaction.branch().as_bytes().to_vec(),
tag: serde_json::to_string(transaction.tag()).unwrap(),
attachment_ts: serde_json::to_string(transaction.attachment_ts()).unwrap(),
attachment_lbts: serde_json::to_string(transaction.attachment_lbts()).unwrap(),
attachment_ubts: serde_json::to_string(transaction.attachment_ubts()).unwrap(),
nonce: serde_json::to_string(transaction.nonce()).unwrap(),
}
}
}
fn transaction_serializer<S>(x: &Vec<Transaction>, s: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = s.serialize_seq(Some(x.len()))?;
for e in x {
seq.serialize_element(&TransactionDef::from(e))?;
}
seq.end()
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AddNeighborsResponse {
#[serde(rename = "addedNeighbors")]
pub added_neighbors: Option<usize>,
}
#[derive(Clone, Debug, Serialize)]
pub struct ConsistencyResponse {
pub state: bool,
pub info: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct ConsistencyResponseBuilder {
state: Option<bool>,
info: Option<String>,
exception: Option<String>,
error: Option<String>,
}
impl ConsistencyResponseBuilder {
pub(crate) async fn build(self) -> Result<ConsistencyResponse> {
let mut state = false;
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
} else if let Some(s) = self.state {
state = s;
}
Ok(ConsistencyResponse {
state: state,
info: self.info,
})
}
}
#[derive(Serialize)]
pub struct AttachToTangleResponse {
#[serde(serialize_with = "transaction_serializer")]
pub trytes: Vec<Transaction>,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct AttachToTangleResponseBuilder {
trytes: Option<Vec<String>>,
error: Option<String>,
exception: Option<String>,
}
impl AttachToTangleResponseBuilder {
pub(crate) async fn build(self) -> Result<AttachToTangleResponse> {
let mut trytes = Vec::new();
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
} else if let Some(s) = self.trytes {
s.iter().for_each(|x| {
trytes.push(
Transaction::from_trits(TryteBuf::try_from_str(&x).unwrap().as_trits())
.unwrap(),
)
});
}
Ok(AttachToTangleResponse { trytes })
}
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct ErrorResponseBuilder {
error: Option<String>,
exception: Option<String>,
}
impl ErrorResponseBuilder {
pub(crate) async fn build(self) -> Result<()> {
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
}
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct FindTransactionsResponse {
pub hashes: Vec<Hash>,
}
impl Serialize for FindTransactionsResponse {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("FindTransactionsResponse", 1)?;
let hashes: Vec<&[i8]> = self.hashes.iter().map(|hash| hash.as_bytes()).collect();
state.serialize_field("hashes", &hashes)?;
state.end()
}
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct FindTransactionsResponseBuilder {
hashes: Option<Vec<String>>,
error: Option<String>,
exception: Option<String>,
}
impl FindTransactionsResponseBuilder {
pub(crate) async fn build(self) -> Result<FindTransactionsResponse> {
let mut hashes: Vec<Hash> = Vec::new();
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
} else if let Some(s) = self.hashes {
hashes = s
.iter()
.map(|s| {
Hash::from_inner_unchecked(
TryteBuf::try_from_str(&s).unwrap().as_trits().encode(),
)
})
.collect::<Vec<Hash>>();
}
Ok(FindTransactionsResponse { hashes })
}
}
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct GetBalancesResponse {
pub balances: Vec<u64>,
pub milestone_index: i64,
pub references: Vec<Hash>,
}
impl Serialize for GetBalancesResponse {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("GetBalancesResponse", 3)?;
state.serialize_field("balances", &self.balances)?;
state.serialize_field("milestone_index", &self.milestone_index)?;
let references: Vec<&[i8]> = self.references.iter().map(|hash| hash.as_bytes()).collect();
state.serialize_field("references", &references)?;
state.end()
}
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GetBalancesResponseBuilder {
balances: Option<Vec<String>>,
#[serde(rename = "milestoneIndex")]
milestone_index: Option<i64>,
references: Option<Vec<String>>,
error: Option<String>,
exception: Option<String>,
}
impl GetBalancesResponseBuilder {
pub(crate) async fn build(self) -> Result<GetBalancesResponse> {
let mut res = GetBalancesResponse {
balances: Vec::new(),
milestone_index: 0,
references: Vec::new(),
};
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
}
if let Some(s) = self.balances {
res.balances = s.into_iter().map(|s| s.parse().unwrap()).collect();
}
if let Some(s) = self.milestone_index {
res.milestone_index = s;
}
if let Some(s) = self.references {
res.references = s
.iter()
.map(|s| {
Hash::from_inner_unchecked(
TryteBuf::try_from_str(&s).unwrap().as_trits().encode(),
)
})
.collect::<Vec<Hash>>();
}
Ok(res)
}
}
#[derive(Clone, Debug, Serialize, Hash, Eq, PartialEq)]
pub struct GetInclusionStatesResponse {
pub states: Vec<bool>,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GetInclusionStatesResponseBuilder {
states: Option<Vec<bool>>,
error: Option<String>,
exception: Option<String>,
}
impl GetInclusionStatesResponseBuilder {
pub(crate) async fn build(self) -> Result<GetInclusionStatesResponse> {
let mut states = Vec::new();
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
} else if let Some(s) = self.states {
states = s;
}
Ok(GetInclusionStatesResponse { states })
}
}
#[derive(Clone, Debug, Serialize)]
pub struct GetNeighborsResponse {
pub neighbors: Vec<NeighborResponse>,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GetNeighborsResponseBuilder {
neighbors: Option<Vec<NeighborResponse>>,
error: Option<String>,
exception: Option<String>,
}
impl GetNeighborsResponseBuilder {
pub(crate) async fn build(self) -> Result<GetNeighborsResponse> {
let mut neighbors = Vec::new();
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
} else if let Some(s) = self.neighbors {
neighbors = s;
}
Ok(GetNeighborsResponse { neighbors })
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetNodeAPIConfigurationResponse {
#[serde(rename = "maxFindTransactions")]
pub max_find_transactions: Option<usize>,
#[serde(rename = "maxRequestsList")]
pub max_requests_list: Option<usize>,
#[serde(rename = "maxGetTrytes")]
pub max_get_trytes: Option<usize>,
#[serde(rename = "maxBodyLength")]
pub max_body_length: Option<usize>,
#[serde(rename = "testNet")]
pub testnet: Option<bool>,
#[serde(rename = "milestoneStartIndex")]
pub milestone_start_index: i64,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetNodeInfoResponse {
#[serde(rename = "appName")]
pub app_name: String,
#[serde(rename = "appVersion")]
pub app_version: String,
#[serde(rename = "jreAvailableProcessors")]
pub jre_available_processors: Option<u16>,
#[serde(rename = "jreFreeMemory")]
pub jre_free_memory: Option<u64>,
#[serde(rename = "jreMaxMemory")]
pub jre_max_memory: Option<u64>,
#[serde(rename = "jreTotalMemory")]
pub jre_total_memory: Option<u64>,
#[serde(rename = "jreVersion")]
pub jre_version: Option<String>,
#[serde(rename = "latestMilestone")]
pub latest_milestone: String,
#[serde(rename = "latestMilestoneIndex")]
pub latest_milestone_index: u32,
#[serde(rename = "latestSolidSubtangleMilestone")]
pub latest_solid_subtangle_milestone: String,
#[serde(rename = "latestSolidSubtangleMilestoneIndex")]
pub latest_solid_subtangle_milestone_index: u32,
#[serde(rename = "milestoneStartIndex")]
pub milestone_start_index: i64,
pub neighbors: u16,
#[serde(rename = "packetsQueueSize")]
pub packets_queue_size: Option<u16>,
pub time: u64,
pub tips: u32,
#[serde(rename = "transactionsToRequest")]
pub transactions_to_request: u32,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetTipsResponse {
pub hashes: Vec<String>,
}
#[derive(Clone, Debug)]
pub struct GTTAResponse {
pub trunk_transaction: Hash,
pub branch_transaction: Hash,
}
impl Serialize for GTTAResponse {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("GTTAResponse", 2)?;
state.serialize_field("trunk_transaction", &self.trunk_transaction.as_bytes())?;
state.serialize_field("branch_transaction", &self.branch_transaction.as_bytes())?;
state.end()
}
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GTTAResponseBuilder {
#[serde(rename = "trunkTransaction")]
trunk_transaction: Option<String>,
#[serde(rename = "branchTransaction")]
branch_transaction: Option<String>,
error: Option<String>,
exception: Option<String>,
}
impl GTTAResponseBuilder {
pub(crate) async fn build(self) -> Result<GTTAResponse> {
let mut res = GTTAResponse {
trunk_transaction: Hash::zeros(),
branch_transaction: Hash::zeros(),
};
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
}
if let Some(s) = self.trunk_transaction {
res.trunk_transaction =
Hash::from_inner_unchecked(TryteBuf::try_from_str(&s).unwrap().as_trits().encode());
}
if let Some(b) = self.branch_transaction {
res.branch_transaction =
Hash::from_inner_unchecked(TryteBuf::try_from_str(&b).unwrap().as_trits().encode());
}
Ok(res)
}
}
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
pub struct NeighborResponse {
pub address: String,
pub domain: String,
#[serde(rename = "numberOfAllTransactions")]
pub number_of_all_transactions: usize,
#[serde(rename = "numberOfInvalidTransactions")]
pub number_of_invalid_transactions: usize,
#[serde(rename = "numberOfNewTransactions")]
pub number_of_new_transactions: usize,
#[serde(rename = "numberOfRandomTransactionRequests")]
pub number_of_random_transactions: usize,
#[serde(rename = "numberOfSentTransactions")]
pub number_of_sent_transactions: usize,
#[serde(rename = "numberOfStaleTransactions")]
pub number_of_stale_transactions: usize,
#[serde(rename = "numberOfDroppedSentPackets")]
pub number_of_dropped_sent_packets: usize,
#[serde(rename = "connectionType")]
pub connection_type: String,
pub connected: bool,
}
#[derive(Serialize)]
pub struct GetTrytesResponse {
#[serde(serialize_with = "transaction_serializer")]
pub trytes: Vec<Transaction>,
}
#[derive(Clone, Deserialize, Debug)]
pub(crate) struct GetTrytesResponseBuilder {
trytes: Option<Vec<String>>,
exception: Option<String>,
error: Option<String>,
}
impl GetTrytesResponseBuilder {
pub(crate) async fn build(self) -> Result<GetTrytesResponse> {
let mut trytes = Vec::new();
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
} else if let Some(s) = self.trytes {
s.iter().for_each(|x| {
trytes.push(
Transaction::from_trits(TryteBuf::try_from_str(&x).unwrap().as_trits())
.unwrap(),
)
});
}
Ok(GetTrytesResponse { trytes })
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RemoveNeighborsResponse {
#[serde(rename = "removedNeighbors")]
pub removed_neighbors: Option<usize>,
}
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct WereAddressesSpentFromResponse {
pub states: Vec<bool>,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct WereAddressesSpentFromResponseBuilder {
states: Option<Vec<bool>>,
exception: Option<String>,
error: Option<String>,
}
impl WereAddressesSpentFromResponseBuilder {
pub(crate) async fn build(self) -> Result<WereAddressesSpentFromResponse> {
let mut states = Vec::new();
if let Some(exception) = self.exception {
return Err(Error::ResponseError(exception));
} else if let Some(error) = self.error {
return Err(Error::ResponseError(error));
} else if let Some(s) = self.states {
states = s;
}
Ok(WereAddressesSpentFromResponse { states })
}
}
#[derive(Clone, Debug, Serialize)]
pub struct Input {
pub(crate) address: Address,
pub(crate) balance: u64,
pub(crate) index: u64,
}
#[derive(Clone, Debug)]
pub struct Transfer {
pub address: Address,
pub value: u64,
pub message: Option<String>,
pub tag: Option<Tag>,
}