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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
use crate::{
    blockchain::StorageError,
    intercom::{self, TransactionMsg},
    rest::Context,
};
use chain_crypto::{
    digest::Error as DigestError, hash::Error as HashError, PublicKey, PublicKeyFromStrError,
};
use chain_impl_mockchain::{
    account::{AccountAlg, Identifier},
    fragment::FragmentId,
    transaction::UnspecifiedAccountIdentifier,
    value::ValueError,
};
use futures::{
    channel::mpsc::{SendError, TrySendError},
    prelude::*,
};
use hex::ToHex;
use jormungandr_lib::interfaces::{
    AccountVotes, FragmentLog, FragmentOrigin, FragmentStatus, FragmentsBatch,
    FragmentsProcessingSummary, VotePlanId,
};
use std::{collections::HashMap, convert::TryInto, str::FromStr};
use tracing::{span, Level};
use tracing_futures::Instrument;

#[allow(clippy::large_enum_variant)]
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Context(#[from] crate::context::Error),
    #[error(transparent)]
    PublicKey(#[from] PublicKeyFromStrError),
    #[error(transparent)]
    Intercom(#[from] intercom::Error),
    #[error(transparent)]
    TxMsgSend(#[from] TrySendError<TransactionMsg>),
    #[error(transparent)]
    MsgSend(#[from] SendError),
    #[error("Block value calculation error")]
    Value(#[from] ValueError),
    #[error(transparent)]
    Hash(#[from] HashError),
    #[error(transparent)]
    Digest(#[from] DigestError),
    #[error(transparent)]
    Storage(#[from] StorageError),
    #[error(transparent)]
    Hex(#[from] hex::FromHexError),
    #[error("Could not process all fragments")]
    Fragments(FragmentsProcessingSummary),
}

fn parse_account_id(id_hex: &str) -> Result<Identifier, Error> {
    PublicKey::<AccountAlg>::from_str(id_hex)
        .map(Into::into)
        .map_err(Into::into)
}

pub async fn get_fragment_statuses<'a>(
    context: &Context,
    ids: impl IntoIterator<Item = &'a str>,
) -> Result<HashMap<String, FragmentStatus>, Error> {
    let ids = ids
        .into_iter()
        .map(FragmentId::from_str)
        .collect::<Result<Vec<_>, _>>()?;
    let span = span!(parent: context.span()?, Level::TRACE, "fragment_statuses", request = "message_statuses");
    async move {
        let (reply_handle, reply_future) = intercom::unary_reply();
        let mut mbox = context.try_full()?.transaction_task.clone();
        mbox.send(TransactionMsg::GetStatuses(ids, reply_handle))
            .await
            .map_err(|e| {
                tracing::debug!(reason = %e, "error getting message statuses");
                Error::MsgSend(e)
            })?;
        reply_future
            .await
            .map_err(Into::into)
            .map(|result_intermediate| {
                let mut result = HashMap::new();
                result_intermediate.into_iter().for_each(|(k, v)| {
                    result.insert(k.to_string(), v);
                });
                result
            })
    }
    .instrument(span)
    .await
}

pub async fn post_fragments(
    context: &Context,
    batch: FragmentsBatch,
) -> Result<FragmentsProcessingSummary, Error> {
    let mut msgbox = context.try_full()?.transaction_task.clone();
    let (reply_handle, reply_future) = intercom::unary_reply();
    let msg = TransactionMsg::SendTransactions {
        origin: FragmentOrigin::Rest,
        fragments: batch.fragments,
        fail_fast: batch.fail_fast,
        reply_handle,
    };
    msgbox.try_send(msg)?;
    let reply = reply_future.await?;
    if reply.is_error() {
        Err(Error::Fragments(reply))
    } else {
        Ok(reply)
    }
}

pub async fn get_fragment_logs(context: &Context) -> Result<Vec<FragmentLog>, Error> {
    let span =
        span!(parent: context.span()?, Level::TRACE, "fragment_logs", request = "fragment_logs");
    async move {
        let (reply_handle, reply_future) = intercom::unary_reply();
        let mut mbox = context.try_full()?.transaction_task.clone();
        mbox.send(TransactionMsg::GetLogs(reply_handle))
            .await
            .map_err(|e| {
                tracing::debug!(reason = %e, "error getting fragment logs");
                Error::MsgSend(e)
            })?;
        reply_future.await.map_err(Into::into)
    }
    .instrument(span)
    .await
}

pub async fn get_account_votes_with_plan(
    context: &Context,
    vote_plan_id: VotePlanId,
    account_id_hex: String,
) -> Result<Option<Vec<u8>>, Error> {
    let span = span!(parent: context.span()?, Level::TRACE, "get_account_votes_with_plan", request = "get_account_votes_with_plan");

    let identifier = parse_account_id(&account_id_hex)?;

    async move {
        let maybe_vote_plan = context
            .blockchain_tip()?
            .get_ref()
            .await
            .ledger()
            .active_vote_plans()
            .into_iter()
            .find(|x| x.id == vote_plan_id.into_digest().into());
        let vote_plan = match maybe_vote_plan {
            Some(vote_plan) => vote_plan,
            None => return Ok(None),
        };
        let result = vote_plan
            .proposals
            .into_iter()
            .enumerate()
            .filter(|(_, x)| x.votes.contains_key(&identifier))
            .map(|(i, _)| i.try_into().unwrap())
            .collect();
        Ok(Some(result))
    }
    .instrument(span)
    .await
}

pub async fn get_account_votes(
    context: &Context,
    account_id_hex: String,
) -> Result<Option<Vec<AccountVotes>>, Error> {
    let span = span!(parent: context.span()?, Level::TRACE, "get_account_votes", request = "get_account_votes");

    let identifier = parse_account_id(&account_id_hex)?;

    async {
        let result = context
            .blockchain_tip()?
            .get_ref()
            .await
            .ledger()
            .active_vote_plans()
            .into_iter()
            .map(|vote_plan| {
                let votes = vote_plan
                    .proposals
                    .into_iter()
                    .enumerate()
                    .filter(|(_, x)| x.votes.contains_key(&identifier))
                    .map(|(i, _)| i.try_into().unwrap())
                    .collect();

                AccountVotes {
                    vote_plan_id: vote_plan.id.into(),
                    votes,
                }
            })
            .collect();

        Ok(Some(result))
    }
    .instrument(span)
    .await
}

pub async fn get_accounts_votes_all(
    context: &Context,
) -> Result<HashMap<String, Vec<AccountVotes>>, Error> {
    let span = span!(parent: context.span()?, Level::TRACE, "get_accounts_votes", request = "get_accounts_votes");

    async {
        let mut result = HashMap::<String, HashMap<VotePlanId, Vec<u8>>>::new();
        for vote_plan in context
            .blockchain_tip()?
            .get_ref()
            .await
            .ledger()
            .active_vote_plans()
            .into_iter()
        {
            for (i, status) in vote_plan.proposals.into_iter().enumerate() {
                for (account, _) in status.votes.iter() {
                    result
                        .entry(
                            UnspecifiedAccountIdentifier::from_single_account(account.clone())
                                .encode_hex(),
                        )
                        .or_default()
                        .entry(vote_plan.id.clone().into())
                        .or_default()
                        .push(i.try_into().expect("too many proposals in voteplan"));
                }
            }
        }

        Ok(result
            .into_iter()
            .map(|(account, votes)| {
                (
                    account,
                    votes
                        .into_iter()
                        .map(|(vote_plan_id, votes)| AccountVotes {
                            vote_plan_id,
                            votes,
                        })
                        .collect::<Vec<_>>(),
                )
            })
            .collect())
    }
    .instrument(span)
    .await
}