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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use crate::mode::mock::rest::reject::{ForcedErrorCode, GeneralException, InvalidBatch};
use crate::mode::mock::ContextLock;
use chain_core::property::{Deserialize, Fragment as _};
use chain_crypto::PublicKey;
use chain_impl_mockchain::account;
use chain_impl_mockchain::account::{AccountAlg, Identifier};
use chain_impl_mockchain::fragment::{Fragment, FragmentId};
use jormungandr_lib::crypto::hash::Hash;
use jormungandr_lib::interfaces::{AccountVotes, FragmentsBatch, VotePlanId, VotePlanStatus};
use std::str::FromStr;
use tracing::info;
use vit_servicing_station_lib::v0::errors::HandleError;
use vit_servicing_station_lib::v0::result::HandlerResult;
use warp::{Rejection, Reply};

#[tracing::instrument(skip(message, context), name = "REST Api call")]
pub async fn post_message(
    message: hyper::body::Bytes,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let mut context = context.write().unwrap();

    let fragment =
        match Fragment::deserialize(&mut chain_core::packer::Codec::new(message.as_ref())) {
            Ok(fragment) => fragment,
            Err(err) => {
                let code = context.state().error_code;
                info!(
                    "post_message with wrong fragment. Reason '{:?}'... Error code: {}",
                    err, code
                );
                return Err(warp::reject::custom(ForcedErrorCode { code }));
            }
        };

    info!("post_message {}...", fragment.id());

    if let Some(error_code) = context.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    let fragment_id: jormungandr_lib::crypto::hash::Hash =
        context.state_mut().ledger_mut().message(fragment).into();
    Ok(HandlerResult(Ok(fragment_id)))
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn get_node_stats(context: ContextLock) -> Result<impl Reply, Rejection> {
    let context = context.read().unwrap();
    info!("get_node_stats");

    if let Some(error_code) = context.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    Ok(HandlerResult(Ok(context.state().node_stats())))
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn get_settings(context: ContextLock) -> Result<impl Reply, Rejection> {
    let context = context.read().unwrap();

    info!("get_settings");

    if let Some(error_code) = context.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    let settings = context.state().ledger().settings();

    Ok(HandlerResult(Ok(settings)))
}

fn parse_account_id(id_hex: &str) -> Result<account::Identifier, Rejection> {
    PublicKey::<AccountAlg>::from_str(id_hex)
        .map(Into::into)
        .map_err(|_| warp::reject::custom(GeneralException::hex_encoding_malformed()))
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn get_account(
    account_bech32: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let mut context = context.write().unwrap();

    info!("get_account {}...", &account_bech32);

    if let Some(error_code) = context.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    {
        let state = context.state_mut();

        if state.block_account_endpoint() != 0 {
            state.decrement_block_account_endpoint();
            let code = state.error_code;
            info!(
                "block account endpoint mode is on. Rejecting with error code: {}",
                code
            );
            return Err(warp::reject::custom(ForcedErrorCode { code }));
        }
    }

    let account_state: jormungandr_lib::interfaces::AccountState = context
        .state()
        .ledger()
        .accounts()
        .get_state(&parse_account_id(&account_bech32)?)
        .map(Into::into)
        .map_err(|_| warp::reject::custom(GeneralException::account_does_not_exist()))?;

    Ok(HandlerResult(Ok(account_state)))
}

#[derive(serde::Deserialize, Debug)]
pub struct GetMessageStatusesQuery {
    fragment_ids: String,
}

impl GetMessageStatusesQuery {
    pub fn as_fragment_ids(&self) -> Result<Vec<FragmentId>, super::super::Error> {
        let ids = self.fragment_ids.split(',');
        ids.into_iter()
            .map(FragmentId::from_str)
            .collect::<Result<Vec<_>, _>>()
            .map_err(Into::into)
    }
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn get_fragment_statuses(
    query: GetMessageStatusesQuery,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let context = context.read().unwrap();

    info!("get_fragment_statuses");

    if let Some(error_code) = context.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    let ids = query.as_fragment_ids();
    if let Err(err) = ids {
        return Err(warp::reject::custom(err));
    }

    Ok(HandlerResult(Ok(context
        .state()
        .ledger()
        .statuses(ids.unwrap()))))
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn post_fragments(
    batch: FragmentsBatch,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let mut context = context.write().unwrap();

    info!("post_fragments");

    if let Some(error_code) = context.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    let summary = context
        .state_mut()
        .ledger_mut()
        .batch_message(batch.fragments, batch.fail_fast);

    if !summary.rejected.is_empty() {
        Err(warp::reject::custom(InvalidBatch { summary, code: 400 }))
    } else {
        Ok(HandlerResult(Ok(summary)))
    }
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn get_fragment_logs(context: ContextLock) -> Result<impl Reply, Rejection> {
    let context = context.read().unwrap();

    info!("get_fragment_logs");

    if let Some(error_code) = context.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    Ok(HandlerResult(Ok(context.state().ledger().fragment_logs())))
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn get_account_votes_with_plan(
    vote_plan_id: VotePlanId,
    acccount_id_hex: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let context = context.read().unwrap();

    info!("get_account_votes");

    let identifier = into_identifier(acccount_id_hex)?;

    let vote_plan_id: chain_crypto::digest::DigestOf<_, _> = vote_plan_id.into_digest().into();

    if let Some(error_code) = context.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    let maybe_vote_plan = context
        .state()
        .ledger()
        .active_vote_plans()
        .into_iter()
        .find(|x| x.id == vote_plan_id);
    let vote_plan = match maybe_vote_plan {
        Some(vote_plan) => vote_plan,
        None => {
            return Err(warp::reject::custom(GeneralException {
                summary: "".to_string(),
                code: 404,
            }))
        }
    };
    let result: Vec<u8> = vote_plan
        .proposals
        .into_iter()
        .enumerate()
        .filter(|(_, x)| x.votes.contains_key(&identifier))
        .map(|(i, _)| i as u8)
        .collect();

    Ok(HandlerResult(Ok(Some(result))))
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn get_account_votes(
    account_id_hex: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let context_lock = context.read().unwrap();
    info!("get_account_votes");

    let identifier = into_identifier(account_id_hex)?;

    if let Some(error_code) = context_lock.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    let result: Vec<AccountVotes> = context_lock
        .state()
        .ledger()
        .active_vote_plans()
        .iter()
        .map(|vote_plan| {
            let votes: Vec<u8> = vote_plan
                .proposals
                .iter()
                .enumerate()
                .filter(|(_, x)| x.votes.contains_key(&identifier))
                .map(|(i, _)| i as u8)
                .collect();

            AccountVotes {
                vote_plan_id: Hash::from_str(&vote_plan.id.to_string()).unwrap(),
                votes,
            }
        })
        .collect();

    Ok(HandlerResult(Ok(Some(result))))
}

pub fn into_identifier(account_id_hex: String) -> Result<Identifier, Rejection> {
    parse_account_id(&account_id_hex).map_err(|err| {
        warp::reject::custom(GeneralException {
            summary: format!("Cannot parse account id, due to: {:?}", err),
            code: 400,
        })
    })
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn get_active_vote_plans(context: ContextLock) -> Result<impl Reply, Rejection> {
    let context_lock = context.read().unwrap();
    info!("get_active_vote_plans");

    if let Some(error_code) = context_lock.check_if_rest_available() {
        return Err(warp::reject::custom(error_code));
    }

    let vp: Vec<VotePlanStatus> = context_lock
        .state()
        .ledger()
        .active_vote_plans()
        .into_iter()
        .map(VotePlanStatus::from)
        .collect();
    Ok(HandlerResult(Ok(vp)))
}

#[tracing::instrument(skip(context), name = "REST Api call")]
pub async fn debug_message(
    fragment_id: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let context = context.read().unwrap();

    info!("debug_message");

    let id = FragmentId::from_str(&fragment_id).map_err(|_| HandleError::NotFound(fragment_id))?;
    let fragments = context.state().ledger().received_fragments();
    let fragment = fragments
        .iter()
        .find(|x| x.id() == id)
        .ok_or_else(|| HandleError::NotFound(id.to_string()))?;

    Ok(HandlerResult(Ok(format!("{:?}", fragment))))
}