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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use async_trait::async_trait;
use bitcoin::consensus::{Decodable, Encodable, ReadExt};
use hex::prelude::*;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::{to_vec, Value};
use std::str::FromStr;

use crate::block::{Block, BlockHash};
use crate::err_string;
use crate::transaction::{Transaction, Txid};

pub static APP_AGENT: &str = concat!(
    "Mozilla/5.0 ck-doge ",
    env!("CARGO_PKG_NAME"),
    "/",
    env!("CARGO_PKG_VERSION"),
);

#[async_trait]
pub trait JsonRPCAgent {
    async fn post(&self, idempotency_key: String, body: Vec<u8>) -> Result<bytes::Bytes, String>;
}

pub struct DogecoinRPC {}

#[derive(Debug, Serialize)]
pub struct RPCRequest<'a> {
    jsonrpc: &'a str,
    method: &'a str,
    params: &'a [Value],
    id: u64,
}

#[derive(Debug, Deserialize)]
pub struct RPCResponse<T> {
    result: Option<T>,
    error: Option<Value>,
    // id: u64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BlockRef {
    pub hash: String,
    pub height: u64,
}

impl From<&BlockRef> for BlockHash {
    fn from(block: &BlockRef) -> Self {
        BlockHash::from_str(&block.hash).expect("invalid block hash")
    }
}

impl DogecoinRPC {
    pub async fn ping(agent: impl JsonRPCAgent, idempotency_key: String) -> Result<(), String> {
        Self::call(agent, idempotency_key, "ping", &[]).await
    }

    pub async fn get_best_blockhash(
        agent: impl JsonRPCAgent,
        idempotency_key: String,
    ) -> Result<BlockHash, String> {
        let hex: String = Self::call(agent, idempotency_key, "getbestblockhash", &[]).await?;
        BlockHash::from_str(&hex).map_err(err_string)
    }

    pub async fn get_blockhash(
        agent: impl JsonRPCAgent,
        idempotency_key: String,
        height: u64,
    ) -> Result<BlockHash, String> {
        let hex: String =
            Self::call(agent, idempotency_key, "getblockhash", &[height.into()]).await?;
        BlockHash::from_str(&hex).map_err(err_string)
    }

    pub async fn get_block(
        agent: impl JsonRPCAgent,
        idempotency_key: String,
        hash: &BlockHash,
    ) -> Result<Block, String> {
        let hex: String = Self::call(
            agent,
            idempotency_key,
            "getblock",
            &[hash.to_string().into(), 0.into()],
        )
        .await?;
        deserialize_hex(&hex)
    }

    pub async fn wait_for_new_block(
        agent: impl JsonRPCAgent,
        idempotency_key: String,
        timeout_ms: u64,
    ) -> Result<BlockRef, String> {
        Self::call(
            agent,
            idempotency_key,
            "waitfornewblock",
            &[timeout_ms.into()],
        )
        .await
    }

    pub async fn get_transaction(
        agent: impl JsonRPCAgent,
        idempotency_key: String,
        hash: &Txid,
    ) -> Result<Transaction, String> {
        let hex: String = Self::call(
            agent,
            idempotency_key,
            "getrawtransaction",
            &[hash.to_string().into(), 0.into()],
        )
        .await?;
        deserialize_hex(&hex)
    }

    pub async fn send_transaction(
        agent: impl JsonRPCAgent,
        idempotency_key: String,
        tx: &Transaction,
    ) -> Result<Txid, String> {
        let hex: String = Self::call(
            agent,
            idempotency_key,
            "sendrawtransaction",
            &[serialize_hex(tx).into()],
        )
        .await?;
        Txid::from_str(&hex).map_err(err_string)
    }

    pub async fn send_rawtransaction(
        agent: impl JsonRPCAgent,
        idempotency_key: String,
        raw: &[u8],
    ) -> Result<Txid, String> {
        let hex: String = Self::call(
            agent,
            idempotency_key,
            "sendrawtransaction",
            &[raw.to_lower_hex_string().into()],
        )
        .await?;
        Txid::from_str(&hex).map_err(err_string)
    }

    pub async fn call<T: DeserializeOwned>(
        agent: impl JsonRPCAgent,
        idempotency_key: String,
        method: &str,
        params: &[Value],
    ) -> Result<T, String> {
        let input = RPCRequest {
            jsonrpc: "1.0",
            method,
            params,
            id: 0,
        };
        let input = to_vec(&input).map_err(err_string)?;
        let data = agent.post(idempotency_key, input).await?;

        let output: RPCResponse<T> = serde_json::from_slice(&data).map_err(err_string)?;

        if let Some(error) = output.error {
            return Err(serde_json::to_string(&error).map_err(err_string)?);
        }

        match output.result {
            Some(result) => Ok(result),
            None => serde_json::from_value(Value::Null).map_err(err_string),
        }
    }
}

pub fn serialize_hex<T: Encodable>(v: &T) -> String {
    let mut buf = Vec::new();
    v.consensus_encode(&mut buf)
        .expect("serialize_hex: encode failed");
    buf.to_lower_hex_string()
}

pub fn deserialize_hex<T: Decodable>(hex: &str) -> Result<T, String> {
    let data = Vec::from_hex(hex).map_err(err_string)?;
    let mut reader = &data[..];
    let object = Decodable::consensus_decode_from_finite_reader(&mut reader).map_err(err_string)?;
    if reader.read_u8().is_ok() {
        Err("decode_hex: data not consumed entirely".to_string())
    } else {
        Ok(object)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine;
    use dotenvy::dotenv;
    use reqwest::{header, Client, ClientBuilder, Url};
    use std::time::Duration;

    pub struct RPCAgent {
        client: Client,
        url: Url,
    }

    impl Default for RPCAgent {
        fn default() -> Self {
            Self::new()
        }
    }

    impl RPCAgent {
        pub fn new() -> Self {
            let rpcurl = std::env::var("RPC_URL").unwrap();
            let rpcuser = std::env::var("RPC_USER").unwrap_or_default();
            let rpcpassword = std::env::var("RPC_PASSWORD").unwrap_or_default();

            let mut common_headers = header::HeaderMap::with_capacity(4);
            common_headers.insert(header::ACCEPT, "application/json".parse().unwrap());
            common_headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
            common_headers.insert(header::ACCEPT_ENCODING, "gzip".parse().unwrap());

            let url = reqwest::Url::parse(&rpcurl).unwrap();
            if !rpcuser.is_empty() && !rpcpassword.is_empty() {
                let auth = format!("{}:{}", rpcuser, rpcpassword);
                let auth = format!(
                    "Basic {}",
                    base64::engine::general_purpose::STANDARD.encode(auth)
                );
                common_headers.insert(header::AUTHORIZATION, auth.parse().unwrap());
            }

            let client = ClientBuilder::new()
                .use_rustls_tls()
                .no_proxy()
                .connect_timeout(Duration::from_secs(10))
                .timeout(Duration::from_secs(30))
                .user_agent(APP_AGENT)
                .default_headers(common_headers)
                .gzip(true)
                .build()
                .unwrap();

            Self { client, url }
        }
    }

    #[async_trait]
    impl JsonRPCAgent for &RPCAgent {
        async fn post(
            &self,
            _idempotency_key: String,
            body: Vec<u8>,
        ) -> Result<bytes::Bytes, String> {
            let req = self.client.post(self.url.clone()).body(body);
            let res = req.send().await.map_err(err_string)?;
            if res.status().is_success() {
                res.bytes().await.map_err(err_string)
            } else {
                Err(format!(
                    "HTTP error: {}, {}",
                    res.status(),
                    res.text().await.unwrap()
                ))
            }
        }
    }

    #[test]
    fn consensus_decode_hex_works() {
        let tx: Transaction = deserialize_hex(
            "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff060340420f0103ffffffff0136bf775ee9000000232102a1b03b741b2f25549de39ee08df766395857b2459edf28675bddb119784c7db7ac00000000",
        )
        .unwrap();
        println!("tx: {:?}", tx);
        assert_eq!(
            tx.compute_txid().to_string(),
            "bc06dcc8c8841728b905fa45e4d21ed460a2e136bb0545fcf2906a149e704bb9"
        );

        let res: Result<Transaction, _> = deserialize_hex(
            "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff060340420f0103ffffffff0136bf775ee9000000232102a1b03b741b2f25549de39ee08df766395857b2459edf28675bddb119784c7db7ac00000000ff",
        );
        assert!(res.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    #[ignore]
    async fn rpc_works() {
        dotenv().expect(".env file not found");

        let agent = RPCAgent::new();
        assert!(DogecoinRPC::ping(&agent, "".to_string()).await.is_ok());

        let best_blockhash = DogecoinRPC::get_best_blockhash(&agent, "".to_string())
            .await
            .unwrap();
        println!("best_blockhash: {:?}", best_blockhash);

        let block = DogecoinRPC::get_block(&agent, "".to_string(), &best_blockhash)
            .await
            .unwrap();
        println!("block: {:?}", block);
    }

    #[tokio::test(flavor = "current_thread")]
    #[ignore]
    async fn check_some_blocks() {
        dotenv().expect(".env file not found");

        let agent = RPCAgent::new();
        assert!(DogecoinRPC::ping(&agent, "".to_string()).await.is_ok());

        let mut height = 5240740u64;
        let mut prev_blockhash =
            BlockHash::from_str("62bba02e84a5b437fcccfacbec309623bfc7479f033e250f93339f981b4ca6c4")
                .unwrap();

        // let mut prev_blockhash = DogecoinRPC::get_best_blockhash(&agent, "").await.unwrap();
        // println!("best_blockhash: {:?}", prev_blockhash);

        let mut i = 10;
        while i > 0 && prev_blockhash != BlockHash::default() {
            i -= 1;
            match DogecoinRPC::get_block(&agent, "".to_string(), &prev_blockhash).await {
                Ok(block) => {
                    println!("Block({}): {:?}", height, prev_blockhash);
                    height -= 1;
                    prev_blockhash = block.header.prev_blockhash;
                }
                Err(err) => {
                    println!("Block({}) Error: {:?}", height, err);
                    break;
                }
            }
        }
    }
}