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
use crate::config::Config;
use crate::mode::mock::rest::reject::GeneralException;
use crate::mode::mock::{ContextLock, FragmentRecieveStrategy, LedgerState, NetworkCongestionMode};
use crate::mode::service::manager::file_lister::dump_json;
use jortestkit::web::api_token::{APIToken, APITokenManager, TokenError};
use mainnet_lib::wallet_state::{build_default, MainnetWalletState};
use mainnet_lib::SnapshotParameters;
use mainnet_tools::snapshot::MainnetWalletStateExtension;
use tracing::{info, trace};
use vit_servicing_station_lib::db::models::funds::Fund;
use vit_servicing_station_lib::v0::errors::HandleError;
use vit_servicing_station_lib::v0::result::HandlerResult;
use warp::{Rejection, Reply};

#[tracing::instrument(skip(context), name = "control")]
pub async fn file_lister_handler(context: ContextLock) -> Result<impl Reply, Rejection> {
    info!("get files command");
    let context_lock = context.read().unwrap();
    Ok(dump_json(context_lock.working_dir())?).map(|r| warp::reply::json(&r))
}

#[tracing::instrument(skip(context, config), name = "mock control command received")]
pub async fn command_reset_mock(
    context: ContextLock,
    config: Config,
) -> Result<impl Reply, Rejection> {
    info!("reset voting command received");
    context.write().unwrap().reset(config)?;
    Ok(warp::reply())
}

#[tracing::instrument(skip(context), name = "mock control command received")]
pub async fn command_available(
    available: bool,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    info!("set mock availability command");
    context.write().unwrap().state_mut().available = available;
    Ok(warp::reply())
}

#[tracing::instrument(skip(context), name = "mock control command received")]
pub async fn command_block_account(
    block_account_endpoint_counter: u32,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    info!("block account command");
    context
        .write()
        .unwrap()
        .state_mut()
        .set_block_account_endpoint(block_account_endpoint_counter);
    Ok(warp::reply())
}

#[tracing::instrument(skip(context), name = "mock control command received")]
pub async fn command_reset_block_account(context: ContextLock) -> Result<impl Reply, Rejection> {
    info!("reset block account command");
    context
        .write()
        .unwrap()
        .state_mut()
        .reset_block_account_endpoint();
    Ok(warp::reply())
}

#[tracing::instrument(skip(ledger_state), name = "mock control command received")]
pub fn update_fragment_id(
    fragment_id: String,
    ledger_state: &mut LedgerState,
    fragment_strategy: FragmentRecieveStrategy,
) -> Result<impl Reply, Rejection> {
    info!("update fragment id command");
    if fragment_id.to_uppercase() == *"LAST".to_string() {
        trace!("updating last fragment to {}", fragment_strategy);
        let _ = ledger_state.set_status_for_recent_fragment(fragment_strategy);
    } else {
        trace!(
            "updating fragment with id '{}' to be: {}",
            fragment_id,
            fragment_strategy
        );
        ledger_state
            .set_status_for_fragment_id(fragment_id, fragment_strategy)
            .map_err(|err| GeneralException {
                summary: err.to_string(),
                code: 404,
            })?;
    }
    Ok(warp::reply())
}

pub async fn command_update_forget(
    fragment_id: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let mut context_lock = context.write().unwrap();
    let ledger = context_lock.state_mut().ledger_mut();
    update_fragment_id(fragment_id, ledger, FragmentRecieveStrategy::Forget)
}

pub async fn command_update_reject(
    fragment_id: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let mut context_lock = context.write().unwrap();
    let ledger = context_lock.state_mut().ledger_mut();
    update_fragment_id(fragment_id, ledger, FragmentRecieveStrategy::Reject)
}

pub async fn command_update_accept(
    fragment_id: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let mut context_lock = context.write().unwrap();
    let ledger = context_lock.state_mut().ledger_mut();
    update_fragment_id(fragment_id, ledger, FragmentRecieveStrategy::Accept)
}

pub async fn command_update_pending(
    fragment_id: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    let mut context_lock = context.write().unwrap();
    let ledger = context_lock.state_mut().ledger_mut();
    update_fragment_id(fragment_id, ledger, FragmentRecieveStrategy::Pending)
}

#[tracing::instrument(skip(context), name = "mock control command received")]
pub async fn command_error_code(
    error_code: u16,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    info!("always return error code for REST Api call");
    let mut context_lock = context.write().unwrap();
    context_lock.state_mut().error_code = error_code;
    Ok(warp::reply())
}

pub async fn command_fund_id(id: i32, context: ContextLock) -> Result<impl Reply, Rejection> {
    context.write().unwrap().state_mut().set_fund_id(id);
    Ok(warp::reply())
}

pub async fn command_update_fund(
    fund: Fund,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    context.write().unwrap().state_mut().update_fund(fund);
    Ok(warp::reply())
}

pub async fn command_version(
    version: String,
    context: ContextLock,
) -> Result<impl Reply, Rejection> {
    context.write().unwrap().state_mut().set_version(version);
    Ok(warp::reply())
}

pub async fn command_congestion_normal(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .set_congestion(NetworkCongestionMode::Normal);
    Ok(warp::reply())
}

pub async fn command_congestion_jammed(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .set_congestion(NetworkCongestionMode::Jammed);
    Ok(warp::reply())
}

pub async fn command_congestion_moderate(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .set_congestion(NetworkCongestionMode::Moderate);
    Ok(warp::reply())
}

pub async fn command_congestion_reset(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .set_congestion(NetworkCongestionMode::Disabled);
    Ok(warp::reply())
}

pub async fn command_reject(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .ledger_mut()
        .set_fragment_strategy(FragmentRecieveStrategy::Reject);
    Ok(warp::reply())
}

pub async fn command_accept(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .ledger_mut()
        .set_fragment_strategy(FragmentRecieveStrategy::Accept);
    Ok(warp::reply())
}
pub async fn command_pending(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .ledger_mut()
        .set_fragment_strategy(FragmentRecieveStrategy::Pending);
    Ok(warp::reply())
}
pub async fn command_reset(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .ledger_mut()
        .set_fragment_strategy(FragmentRecieveStrategy::None);
    Ok(warp::reply())
}

pub async fn command_forget(context: ContextLock) -> Result<impl Reply, Rejection> {
    context
        .write()
        .unwrap()
        .state_mut()
        .ledger_mut()
        .set_fragment_strategy(FragmentRecieveStrategy::Forget);
    Ok(warp::reply())
}

pub async fn command_create_snapshot(
    config: mainnet_lib::Initials,
) -> Result<impl Reply, Rejection> {
    let states: Vec<MainnetWalletState> = build_default(config.content)
        .await
        .map_err(|e| HandleError::InternalError(e.to_string()))?;
    println!("{:#?}", states);
    let request = states
        .try_into_raw_snapshot_request(SnapshotParameters::default())
        .map_err(|e| HandleError::InternalError(e.to_string()));
    Ok(HandlerResult(request))
}

pub async fn authorize_token(token: String, context: ContextLock) -> Result<(), Rejection> {
    let context = context.read().unwrap();
    let api_token = APIToken::from_string(token).map_err(warp::reject::custom)?;

    if context.api_token().is_none() {
        return Ok(());
    }

    let manager =
        APITokenManager::new(context.api_token().unwrap()).map_err(warp::reject::custom)?;

    if !manager.is_token_valid(api_token) {
        return Err(warp::reject::custom(TokenError::UnauthorizedToken));
    }
    Ok(())
}