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
mod raw;
mod settings;

use crate::jormungandr::{legacy, MemPoolCheck};
use chain_impl_mockchain::{
    block::Block,
    fragment::{Fragment, FragmentId},
    header::HeaderId,
};
use jormungandr_lib::{
    crypto::{account::Identifier, hash::Hash},
    interfaces::{
        AccountState, AccountVotes, Address, EpochRewardsInfo, FragmentLog, FragmentStatus,
        FragmentsProcessingSummary, LeadershipLog, NodeStatsDto, PeerRecord, PeerStats,
        SettingsDto, StakeDistributionDto, UpdateProposalStateDef, Value, VotePlanId,
        VotePlanStatus,
    },
};
pub use raw::RawRest;
pub use settings::RestSettings;
use std::{collections::HashMap, fs::File, io::Read, net::SocketAddr, path::Path};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum RestError {
    #[error("could not deserialize response")]
    CannotDeserialize(#[from] serde_json::Error),
    #[error("could not send reqeuest")]
    RequestError(#[from] reqwest::Error),
    #[error("hash parse error")]
    HashParseError(#[from] chain_crypto::hash::Error),
    #[error("error while polling endpoint")]
    PollError(#[from] jortestkit::process::WaitError),
    #[error("non success error code {status}")]
    NonSuccessErrorCode {
        response: String,
        status: reqwest::StatusCode,
        checks: Vec<MemPoolCheck>,
    },
    #[error(transparent)]
    ReadBytes(#[from] chain_core::property::ReadError),
}

pub fn uri_from_socket_addr(addr: SocketAddr) -> String {
    format!("http://{}/api", addr)
}

/// Specialized rest api
#[derive(Debug, Clone)]
pub struct JormungandrRest {
    inner: legacy::BackwardCompatibleRest,
}

impl JormungandrRest {
    pub fn new(uri: String) -> Self {
        Self {
            inner: legacy::BackwardCompatibleRest::new(uri, Default::default()),
        }
    }

    pub fn new_with_custom_settings(uri: String, settings: RestSettings) -> Self {
        Self {
            inner: legacy::BackwardCompatibleRest::new(uri, settings),
        }
    }

    pub fn address(&self) -> String {
        self.raw().uri()
    }

    pub fn disable_logger(&mut self) {
        self.inner.disable_logger();
    }

    pub fn enable_logger(&mut self) {
        self.inner.enable_logger();
    }

    pub fn inner(&self) -> &legacy::BackwardCompatibleRest {
        &self.inner
    }

    pub fn raw(&self) -> &RawRest {
        self.inner.raw()
    }

    pub fn new_with_cert<P: AsRef<Path>>(uri: String, cert_file: P) -> Self {
        //replace http with https
        //replace localhost ip to localhost
        let url = uri
            .replace("http://", "https://")
            .replace("127.0.0.1", "localhost");

        let settings = RestSettings {
            certificate: Some(Self::extract_certificate(cert_file.as_ref())),
            ..Default::default()
        };
        Self {
            inner: legacy::BackwardCompatibleRest::new(url, settings),
        }
    }

    fn extract_certificate<P: AsRef<Path>>(cert_file: P) -> reqwest::Certificate {
        let mut buf = Vec::new();
        let path = cert_file.as_ref().as_os_str().to_str().unwrap();
        File::open(path).unwrap().read_to_end(&mut buf).unwrap();
        reqwest::Certificate::from_pem(&buf).unwrap()
    }

    pub fn epoch_reward_history(&self, epoch: u32) -> Result<EpochRewardsInfo, RestError> {
        let content = self.inner.epoch_reward_history(epoch)?;
        serde_json::from_str(&content).map_err(RestError::CannotDeserialize)
    }

    pub fn updates(&self) -> Result<HashMap<Hash, UpdateProposalStateDef>, RestError> {
        let content = self.inner.updates()?;
        serde_json::from_str(&content).map_err(RestError::CannotDeserialize)
    }

    pub fn reward_history(&self, length: u32) -> Result<Vec<EpochRewardsInfo>, RestError> {
        serde_json::from_str(&self.inner.reward_history(length)?)
            .map_err(RestError::CannotDeserialize)
    }

    pub fn remaining_rewards(&self) -> Result<Value, RestError> {
        serde_json::from_str(&self.inner.remaining_rewards()?).map_err(RestError::CannotDeserialize)
    }

    pub fn stake_distribution(&self) -> Result<StakeDistributionDto, RestError> {
        serde_json::from_str(&self.inner.stake_distribution()?)
            .map_err(RestError::CannotDeserialize)
    }

    pub fn account_votes(&self, address: Address) -> Result<Option<Vec<AccountVotes>>, RestError> {
        serde_json::from_str(&self.inner.account_votes(address)?)
            .map_err(RestError::CannotDeserialize)
    }

    pub fn account_votes_all(&self) -> Result<HashMap<String, Vec<AccountVotes>>, RestError> {
        serde_json::from_str(&self.inner.account_votes_all()?).map_err(RestError::CannotDeserialize)
    }

    pub fn account_votes_with_plan_id(
        &self,
        vote_plan_id: VotePlanId,
        address: Address,
    ) -> Result<Option<Vec<u8>>, RestError> {
        serde_json::from_str(
            &self
                .inner
                .account_votes_with_plan_id(vote_plan_id, address)?,
        )
        .map_err(RestError::CannotDeserialize)
    }

    pub fn stake_pools(&self) -> Result<Vec<String>, RestError> {
        serde_json::from_str(&self.inner.stake_pools()?).map_err(RestError::CannotDeserialize)
    }

    pub fn stake_distribution_at(&self, epoch: u32) -> Result<StakeDistributionDto, RestError> {
        serde_json::from_str(&self.inner.stake_distribution_at(epoch)?)
            .map_err(RestError::CannotDeserialize)
    }

    pub fn stats(&self) -> Result<NodeStatsDto, RestError> {
        let stats = &self.inner.stats()?;
        serde_json::from_str(stats).map_err(RestError::CannotDeserialize)
    }

    pub fn account_state(&self, id: &Identifier) -> Result<AccountState, RestError> {
        serde_json::from_str(&self.inner.account_state(id)?).map_err(RestError::CannotDeserialize)
    }

    pub fn account_state_by_pk_raw(&self, bech32_str: &str) -> Result<String, RestError> {
        self.inner
            .account_state_by_pk(bech32_str)
            .map_err(Into::into)
    }

    pub fn account_state_by_pk(&self, bech32_str: &str) -> Result<AccountState, RestError> {
        serde_json::from_str(&self.inner.account_state_by_pk(bech32_str)?)
            .map_err(RestError::CannotDeserialize)
    }

    pub fn network_stats(&self) -> Result<Vec<PeerStats>, RestError> {
        serde_json::from_str(&self.inner.network_stats()?).map_err(RestError::CannotDeserialize)
    }

    pub fn p2p_quarantined(&self) -> Result<Vec<PeerRecord>, RestError> {
        serde_json::from_str(&self.inner.p2p_quarantined()?).map_err(RestError::CannotDeserialize)
    }

    pub fn p2p_non_public(&self) -> Result<Vec<PeerRecord>, RestError> {
        serde_json::from_str(&self.inner.p2p_non_public()?).map_err(RestError::CannotDeserialize)
    }

    pub fn p2p_available(&self) -> Result<Vec<PeerRecord>, RestError> {
        serde_json::from_str(&self.inner.p2p_available()?).map_err(RestError::CannotDeserialize)
    }

    pub fn p2p_view(&self) -> Result<Vec<String>, RestError> {
        serde_json::from_str(&self.inner.p2p_view()?).map_err(RestError::CannotDeserialize)
    }

    pub fn tip(&self) -> Result<Hash, RestError> {
        self.inner.tip()
    }

    pub fn fragment_logs(&self) -> Result<HashMap<FragmentId, FragmentLog>, RestError> {
        self.inner.fragment_logs()
    }

    pub fn settings(&self) -> Result<SettingsDto, RestError> {
        serde_json::from_str(&self.inner.settings()?).map_err(RestError::CannotDeserialize)
    }

    pub fn leaders_log(&self) -> Result<Vec<LeadershipLog>, RestError> {
        serde_json::from_str(&self.inner.leaders_log()?).map_err(RestError::CannotDeserialize)
    }

    pub fn send_fragment(&self, fragment: Fragment) -> Result<MemPoolCheck, RestError> {
        self.inner.send_fragment(fragment).map_err(Into::into)
    }

    pub fn send_raw_fragment(&self, bytes: Vec<u8>) -> Result<(), RestError> {
        self.inner.send_raw_fragment(bytes)?;
        Ok(())
    }

    pub fn send_raw_fragments(&self, bytes: Vec<Vec<u8>>) -> Result<(), RestError> {
        self.inner.send_raw_fragments(bytes).map_err(Into::into)
    }

    pub fn block_as_bytes(&self, header_hash: &HeaderId) -> Result<Vec<u8>, RestError> {
        self.inner.block_as_bytes(header_hash).map_err(Into::into)
    }

    pub fn shutdown(&self) -> Result<String, RestError> {
        self.inner.shutdown().map_err(Into::into)
    }

    pub fn block(&self, header_hash: &HeaderId) -> Result<Block, RestError> {
        let bytes = self.block_as_bytes(header_hash)?;
        <Block as chain_core::property::DeserializeFromSlice>::deserialize_from_slice(
            &mut chain_core::packer::Codec::new(bytes.as_slice()),
        )
        .map_err(Into::into)
    }

    pub fn fragments_statuses(
        &self,
        ids: Vec<String>,
    ) -> Result<HashMap<String, FragmentStatus>, RestError> {
        self.inner.fragments_statuses(ids).map_err(Into::into)
    }

    pub fn send_fragment_batch(
        &self,
        fragments: Vec<Fragment>,
        fail_fast: bool,
    ) -> Result<FragmentsProcessingSummary, RestError> {
        self.inner
            .send_fragment_batch(fragments, fail_fast)
            .map_err(Into::into)
    }

    pub fn vote_plan_statuses(&self) -> Result<Vec<VotePlanStatus>, RestError> {
        serde_json::from_str(&self.inner.vote_plan_statuses()?)
            .map_err(RestError::CannotDeserialize)
    }

    pub fn set_origin<S: Into<String>>(&mut self, origin: S) {
        self.inner.set_origin(origin);
    }
}