bitcoind_client/
convert.rs

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
#![allow(missing_docs)]
use std::convert::{TryFrom, TryInto};
use std::str::FromStr;

use bitcoin::block::Version;
use bitcoin::consensus::encode;
use bitcoin::hashes::hex::FromHex;
use bitcoin::hashes::Hash;
use bitcoin::{Block, BlockHash, CompactTarget, Work};
use bitcoin::blockdata::block::Header as BlockHeader;
use bitcoin::hash_types::TxMerkleNode;
use serde::Deserialize;

use crate::bitcoind_client::BlockHeaderData;

/// Response from RPC calls
pub struct JsonResponse(pub serde_json::Value);

/// Response from getblockchaininfo RPC
#[derive(Debug)]
pub struct BlockchainInfo {
    pub latest_height: usize,
    pub latest_blockhash: BlockHash,
}

impl TryFrom<JsonResponse> for BlockchainInfo {
    type Error = std::io::Error;
    fn try_from(item: JsonResponse) -> std::io::Result<Self> {
        Ok(Self {
            latest_height: item.0["blocks"].as_u64().unwrap() as usize,
            latest_blockhash: BlockHash::from_str(item.0["bestblockhash"].as_str().unwrap())
                .unwrap(),
        })
    }
}

impl TryInto<Option<BlockHash>> for JsonResponse {
    type Error = std::io::Error;

    fn try_into(self) -> Result<Option<BlockHash>, Self::Error> {
        match self.0.as_str() {
            None => Ok(None),
            Some(s) => Ok(Some(BlockHash::from_str(s).unwrap())),
        }
    }
}

// FIXME: check if this is no longer needed
pub fn hex_to_work(hex: &str) -> Result<Work, bitcoin::hashes::hex::HexToArrayError> {
    let bytes = <[u8; 32]>::from_hex(hex)?;
    Ok(Work::from_be_bytes(bytes))
}

/// Response data from `getblockheader` RPC and `headers` REST requests.
#[derive(Deserialize)]
struct GetHeaderResponse {
    pub version: i32,
    pub merkleroot: String,
    pub time: u32,
    pub nonce: u32,
    pub bits: String,
    pub previousblockhash: String,

    pub chainwork: String,
    pub height: u32,
}

/// Converts from `GetHeaderResponse` to `BlockHeaderData`.
impl TryFrom<GetHeaderResponse> for BlockHeaderData {
    type Error = bitcoin::hashes::hex::HexToArrayError;

    fn try_from(response: GetHeaderResponse) -> Result<Self, Self::Error> {
        Ok(BlockHeaderData {
            header: BlockHeader {
                version: Version::from_consensus(response.version),
                prev_blockhash: BlockHash::from_str(&response.previousblockhash)?,
                merkle_root: TxMerkleNode::from_str(&response.merkleroot)?,
                time: response.time,
                bits: CompactTarget::from_unprefixed_hex(&response.bits).expect("error while parsing bits"),
                nonce: response.nonce,
            },
            chainwork: hex_to_work(&response.chainwork)?,
            height: response.height,
        })
    }
}

/// Converts a JSON value into block header data. The JSON value may be an object representing a
/// block header or an array of such objects. In the latter case, the first object is converted.
impl TryInto<BlockHeaderData> for JsonResponse {
    type Error = std::io::Error;

    fn try_into(self) -> std::io::Result<BlockHeaderData> {
        let mut header = match self.0 {
            serde_json::Value::Array(mut array) if !array.is_empty() => {
                array.drain(..).next().unwrap()
            }
            serde_json::Value::Object(_) => self.0,
            _ => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "unexpected JSON type",
                ))
            }
        };

        if !header.is_object() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "expected JSON object",
            ));
        }

        // Add an empty previousblockhash for the genesis block.
        if let None = header.get("previousblockhash") {
            let hash: BlockHash = BlockHash::all_zeros();
            header.as_object_mut().unwrap().insert(
                "previousblockhash".to_string(),
                serde_json::json!(hash.to_string()),
            );
        }

        match serde_json::from_value::<GetHeaderResponse>(header) {
            Err(_) => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "invalid header response",
            )),
            Ok(response) => match response.try_into() {
                Err(_) => Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "invalid header data",
                )),
                Ok(header) => Ok(header),
            },
        }
    }
}

/// Converts a JSON value into a block. Assumes the block is hex-encoded in a JSON string.
impl TryInto<Block> for JsonResponse {
    type Error = std::io::Error;

    fn try_into(self) -> std::io::Result<Block> {
        match self.0.as_str() {
            None => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "expected JSON string",
            )),
            Some(hex_data) => match Vec::<u8>::from_hex(hex_data) {
                Err(_) => Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "invalid hex data",
                )),
                Ok(block_data) => match encode::deserialize(&block_data) {
                    Err(_) => Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "invalid block data",
                    )),
                    Ok(block) => Ok(block),
                },
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::convert::TryFrom;

    #[test]
    fn header_parse_test() {
        let response = GetHeaderResponse {
            bits: "207fffff".to_string(),
            version: 1,
            previousblockhash: "0000000000000000000000000000000000000000000000000000000000000000".to_string(),
            merkleroot: "0000000000000000000000000000000000000000000000000000000000000000".to_string(),
            time: 1231006505,
            nonce: 2083236893,
            chainwork: "000000000000000000000000000000000000000000000000000000000000000f".to_owned(),
            height: 1,
        };

        // Attempt to convert the response, which should panic
        BlockHeaderData::try_from(response).unwrap();
    }
}