Fixes bug with incorrect conversion of JsonValue to Txid.
[rust-lightning] / lightning-block-sync / src / convert.rs
1 use crate::http::{BinaryResponse, JsonResponse};
2 use crate::utils::hex_to_work;
3 use crate::{BlockHeaderData, BlockSourceError};
4
5 use bitcoin::blockdata::block::{Block, Header};
6 use bitcoin::consensus::encode;
7 use bitcoin::hash_types::{BlockHash, TxMerkleNode, Txid};
8 use bitcoin::hashes::hex::FromHex;
9 use bitcoin::Transaction;
10
11 use serde_json;
12
13 use std::convert::From;
14 use std::convert::TryFrom;
15 use std::convert::TryInto;
16 use std::str::FromStr;
17 use bitcoin::hashes::Hash;
18
19 impl TryInto<serde_json::Value> for JsonResponse {
20         type Error = std::io::Error;
21         fn try_into(self) -> Result<serde_json::Value, std::io::Error> { Ok(self.0) }
22 }
23
24 /// Conversion from `std::io::Error` into `BlockSourceError`.
25 impl From<std::io::Error> for BlockSourceError {
26         fn from(e: std::io::Error) -> BlockSourceError {
27                 match e.kind() {
28                         std::io::ErrorKind::InvalidData => BlockSourceError::persistent(e),
29                         std::io::ErrorKind::InvalidInput => BlockSourceError::persistent(e),
30                         _ => BlockSourceError::transient(e),
31                 }
32         }
33 }
34
35 /// Parses binary data as a block.
36 impl TryInto<Block> for BinaryResponse {
37         type Error = std::io::Error;
38
39         fn try_into(self) -> std::io::Result<Block> {
40                 match encode::deserialize(&self.0) {
41                         Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid block data")),
42                         Ok(block) => Ok(block),
43                 }
44         }
45 }
46
47 /// Parses binary data as a block hash.
48 impl TryInto<BlockHash> for BinaryResponse {
49         type Error = std::io::Error;
50
51         fn try_into(self) -> std::io::Result<BlockHash> {
52                 BlockHash::from_slice(&self.0).map_err(|_|
53                         std::io::Error::new(std::io::ErrorKind::InvalidData, "bad block hash length")
54                 )
55         }
56 }
57
58 /// Converts a JSON value into block header data. The JSON value may be an object representing a
59 /// block header or an array of such objects. In the latter case, the first object is converted.
60 impl TryInto<BlockHeaderData> for JsonResponse {
61         type Error = std::io::Error;
62
63         fn try_into(self) -> std::io::Result<BlockHeaderData> {
64                 let header = match self.0 {
65                         serde_json::Value::Array(mut array) if !array.is_empty() => array.drain(..).next().unwrap(),
66                         serde_json::Value::Object(_) => self.0,
67                         _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "unexpected JSON type")),
68                 };
69
70                 if !header.is_object() {
71                         return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON object"));
72                 }
73
74                 // Add an empty previousblockhash for the genesis block.
75                 match header.try_into() {
76                         Err(_) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid header data")),
77                         Ok(header) => Ok(header),
78                 }
79         }
80 }
81
82 impl TryFrom<serde_json::Value> for BlockHeaderData {
83         type Error = ();
84
85         fn try_from(response: serde_json::Value) -> Result<Self, ()> {
86                 macro_rules! get_field { ($name: expr, $ty_access: tt) => {
87                         response.get($name).ok_or(())?.$ty_access().ok_or(())?
88                 } }
89
90                 Ok(BlockHeaderData {
91                         header: Header {
92                                 version: bitcoin::blockdata::block::Version::from_consensus(
93                                         get_field!("version", as_i64).try_into().map_err(|_| ())?
94                                 ),
95                                 prev_blockhash: if let Some(hash_str) = response.get("previousblockhash") {
96                                                 BlockHash::from_str(hash_str.as_str().ok_or(())?).map_err(|_| ())?
97                                         } else { BlockHash::all_zeros() },
98                                 merkle_root: TxMerkleNode::from_str(get_field!("merkleroot", as_str)).map_err(|_| ())?,
99                                 time: get_field!("time", as_u64).try_into().map_err(|_| ())?,
100                                 bits: bitcoin::CompactTarget::from_consensus(
101                                         u32::from_be_bytes(<[u8; 4]>::from_hex(get_field!("bits", as_str)).map_err(|_| ())?)
102                                 ),
103                                 nonce: get_field!("nonce", as_u64).try_into().map_err(|_| ())?,
104                         },
105                         chainwork: hex_to_work(get_field!("chainwork", as_str)).map_err(|_| ())?,
106                         height: get_field!("height", as_u64).try_into().map_err(|_| ())?,
107                 })
108         }
109 }
110
111 /// Converts a JSON value into a block. Assumes the block is hex-encoded in a JSON string.
112 impl TryInto<Block> for JsonResponse {
113         type Error = std::io::Error;
114
115         fn try_into(self) -> std::io::Result<Block> {
116                 match self.0.as_str() {
117                         None => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON string")),
118                         Some(hex_data) => match Vec::<u8>::from_hex(hex_data) {
119                                 Err(_) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
120                                 Ok(block_data) => match encode::deserialize(&block_data) {
121                                         Err(_) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid block data")),
122                                         Ok(block) => Ok(block),
123                                 },
124                         },
125                 }
126         }
127 }
128
129 /// Converts a JSON value into the best block hash and optional height.
130 impl TryInto<(BlockHash, Option<u32>)> for JsonResponse {
131         type Error = std::io::Error;
132
133         fn try_into(self) -> std::io::Result<(BlockHash, Option<u32>)> {
134                 if !self.0.is_object() {
135                         return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON object"));
136                 }
137
138                 let hash = match &self.0["bestblockhash"] {
139                         serde_json::Value::String(hex_data) => match BlockHash::from_str(&hex_data) {
140                                 Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
141                                 Ok(block_hash) => block_hash,
142                         },
143                         _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON string")),
144                 };
145
146                 let height = match &self.0["blocks"] {
147                         serde_json::Value::Null => None,
148                         serde_json::Value::Number(height) => match height.as_u64() {
149                                 None => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid height")),
150                                 Some(height) => match height.try_into() {
151                                         Err(_) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid height")),
152                                         Ok(height) => Some(height),
153                                 }
154                         },
155                         _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON number")),
156                 };
157
158                 Ok((hash, height))
159         }
160 }
161
162 impl TryInto<Txid> for JsonResponse {
163         type Error = std::io::Error;
164         fn try_into(self) -> std::io::Result<Txid> {
165                 let hex_data = self.0.as_str().ok_or(Self::Error::new(std::io::ErrorKind::InvalidData, "expected JSON string" ))?;
166                 Txid::from_str(hex_data).map_err(|err|Self::Error::new(std::io::ErrorKind::InvalidData, err.to_string() ))
167         }
168 }
169
170 /// Converts a JSON value into a transaction. WATCH OUT! this cannot be used for zero-input transactions
171 /// (e.g. createrawtransaction). See <https://github.com/rust-bitcoin/rust-bitcoincore-rpc/issues/197>
172 impl TryInto<Transaction> for JsonResponse {
173         type Error = std::io::Error;
174         fn try_into(self) -> std::io::Result<Transaction> {
175                 let hex_tx = if self.0.is_object() {
176                         // result is json encoded
177                         match &self.0["hex"] {
178                                 // result has hex field
179                                 serde_json::Value::String(hex_data) => match self.0["complete"] {
180                                         // result may or may not be signed (e.g. signrawtransactionwithwallet)
181                                         serde_json::Value::Bool(x) => {
182                                                 if x == false {
183                                                         let reason = match &self.0["errors"][0]["error"] {
184                                                                 serde_json::Value::String(x) => x.as_str(),
185                                                                 _ => "Unknown error",
186                                                         };
187
188                                                         return Err(std::io::Error::new(
189                                                                 std::io::ErrorKind::InvalidData,
190                                                                 format!("transaction couldn't be signed. {}", reason),
191                                                         ));
192                                                 } else {
193                                                         hex_data
194                                                 }
195                                         }
196                                         // result is a complete transaction (e.g. getrawtranaction verbose)
197                                         _ => hex_data,
198                                 },
199                                 _ => return Err(std::io::Error::new(
200                                                         std::io::ErrorKind::InvalidData,
201                                                         "expected JSON string",
202                                         )),
203                         }
204                 } else {
205                         // result is plain text (e.g. getrawtransaction no verbose)
206                         match self.0.as_str() {
207                                 Some(hex_tx) => hex_tx,
208                                 None => {
209                                         return Err(std::io::Error::new(
210                                                 std::io::ErrorKind::InvalidData,
211                                                 "expected JSON string",
212                                         ))
213                                 }
214                         }
215                 };
216
217                 match Vec::<u8>::from_hex(hex_tx) {
218                         Err(_) => Err(std::io::Error::new(
219                                 std::io::ErrorKind::InvalidData,
220                                 "invalid hex data",
221                         )),
222                         Ok(tx_data) => match encode::deserialize(&tx_data) {
223                                 Err(_) => Err(std::io::Error::new(
224                                         std::io::ErrorKind::InvalidData,
225                                         "invalid transaction",
226                                 )),
227                                 Ok(tx) => Ok(tx),
228                         },
229                 }
230         }
231 }
232
233 impl TryInto<BlockHash> for JsonResponse {
234         type Error = std::io::Error;
235
236         fn try_into(self) -> std::io::Result<BlockHash> {
237                 match self.0.as_str() {
238                         None => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON string")),
239                         Some(hex_data) if hex_data.len() != 64 =>
240                                 Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hash length")),
241                         Some(hex_data) => BlockHash::from_str(hex_data)
242                                 .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid hex data")),
243                 }
244         }
245 }
246
247 /// The REST `getutxos` endpoint retuns a whole pile of data we don't care about and one bit we do
248 /// - whether the `hit bitmap` field had any entries. Thus we condense the result down into only
249 /// that.
250 pub(crate) struct GetUtxosResponse {
251         pub(crate) hit_bitmap_nonempty: bool
252 }
253
254 impl TryInto<GetUtxosResponse> for JsonResponse {
255         type Error = std::io::Error;
256
257         fn try_into(self) -> std::io::Result<GetUtxosResponse> {
258                 let bitmap_str =
259                         self.0.as_object().ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected an object"))?
260                         .get("bitmap").ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "missing bitmap field"))?
261                         .as_str().ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "bitmap should be an str"))?;
262                         let mut hit_bitmap_nonempty = false;
263                         for c in bitmap_str.chars() {
264                                 if c < '0' || c > '9' {
265                                         return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid byte"));
266                                 }
267                                 if c > '0' { hit_bitmap_nonempty = true; }
268                         }
269                         Ok(GetUtxosResponse { hit_bitmap_nonempty })
270         }
271 }
272
273 #[cfg(test)]
274 pub(crate) mod tests {
275         use super::*;
276         use bitcoin::blockdata::constants::genesis_block;
277         use bitcoin::hashes::Hash;
278         use bitcoin::network::constants::Network;
279         use hex::DisplayHex;
280         use serde_json::value::Number;
281         use serde_json::Value;
282
283         /// Converts from `BlockHeaderData` into a `GetHeaderResponse` JSON value.
284         impl From<BlockHeaderData> for serde_json::Value {
285                 fn from(data: BlockHeaderData) -> Self {
286                         let BlockHeaderData { chainwork, height, header } = data;
287                         serde_json::json!({
288                                 "chainwork": chainwork.to_be_bytes().as_hex().to_string(),
289                                 "height": height,
290                                 "version": header.version.to_consensus(),
291                                 "merkleroot": header.merkle_root.to_string(),
292                                 "time": header.time,
293                                 "nonce": header.nonce,
294                                 "bits": header.bits.to_consensus().to_be_bytes().as_hex().to_string(),
295                                 "previousblockhash": header.prev_blockhash.to_string(),
296                         })
297                 }
298         }
299
300         #[test]
301         fn into_block_header_from_json_response_with_unexpected_type() {
302                 let response = JsonResponse(serde_json::json!(42));
303                 match TryInto::<BlockHeaderData>::try_into(response) {
304                         Err(e) => {
305                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
306                                 assert_eq!(e.get_ref().unwrap().to_string(), "unexpected JSON type");
307                         },
308                         Ok(_) => panic!("Expected error"),
309                 }
310         }
311
312         #[test]
313         fn into_block_header_from_json_response_with_unexpected_header_type() {
314                 let response = JsonResponse(serde_json::json!([42]));
315                 match TryInto::<BlockHeaderData>::try_into(response) {
316                         Err(e) => {
317                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
318                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON object");
319                         },
320                         Ok(_) => panic!("Expected error"),
321                 }
322         }
323
324         #[test]
325         fn into_block_header_from_json_response_with_invalid_header_response() {
326                 let block = genesis_block(Network::Bitcoin);
327                 let mut response = JsonResponse(BlockHeaderData {
328                         chainwork: block.header.work(),
329                         height: 0,
330                         header: block.header
331                 }.into());
332                 response.0["chainwork"].take();
333
334                 match TryInto::<BlockHeaderData>::try_into(response) {
335                         Err(e) => {
336                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
337                                 assert_eq!(e.get_ref().unwrap().to_string(), "invalid header data");
338                         },
339                         Ok(_) => panic!("Expected error"),
340                 }
341         }
342
343         #[test]
344         fn into_block_header_from_json_response_with_invalid_header_data() {
345                 let block = genesis_block(Network::Bitcoin);
346                 let mut response = JsonResponse(BlockHeaderData {
347                         chainwork: block.header.work(),
348                         height: 0,
349                         header: block.header
350                 }.into());
351                 response.0["chainwork"] = serde_json::json!("foobar");
352
353                 match TryInto::<BlockHeaderData>::try_into(response) {
354                         Err(e) => {
355                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
356                                 assert_eq!(e.get_ref().unwrap().to_string(), "invalid header data");
357                         },
358                         Ok(_) => panic!("Expected error"),
359                 }
360         }
361
362         #[test]
363         fn into_block_header_from_json_response_with_valid_header() {
364                 let block = genesis_block(Network::Bitcoin);
365                 let response = JsonResponse(BlockHeaderData {
366                         chainwork: block.header.work(),
367                         height: 0,
368                         header: block.header
369                 }.into());
370
371                 match TryInto::<BlockHeaderData>::try_into(response) {
372                         Err(e) => panic!("Unexpected error: {:?}", e),
373                         Ok(data) => {
374                                 assert_eq!(data.chainwork, block.header.work());
375                                 assert_eq!(data.height, 0);
376                                 assert_eq!(data.header, block.header);
377                         },
378                 }
379         }
380
381         #[test]
382         fn into_block_header_from_json_response_with_valid_header_array() {
383                 let genesis_block = genesis_block(Network::Bitcoin);
384                 let best_block_header = Header {
385                         prev_blockhash: genesis_block.block_hash(),
386                         ..genesis_block.header
387                 };
388                 let chainwork = genesis_block.header.work() + best_block_header.work();
389                 let response = JsonResponse(serde_json::json!([
390                                 serde_json::Value::from(BlockHeaderData {
391                                         chainwork, height: 1, header: best_block_header,
392                                 }),
393                                 serde_json::Value::from(BlockHeaderData {
394                                         chainwork: genesis_block.header.work(), height: 0, header: genesis_block.header,
395                                 }),
396                 ]));
397
398                 match TryInto::<BlockHeaderData>::try_into(response) {
399                         Err(e) => panic!("Unexpected error: {:?}", e),
400                         Ok(data) => {
401                                 assert_eq!(data.chainwork, chainwork);
402                                 assert_eq!(data.height, 1);
403                                 assert_eq!(data.header, best_block_header);
404                         },
405                 }
406         }
407
408         #[test]
409         fn into_block_header_from_json_response_without_previous_block_hash() {
410                 let block = genesis_block(Network::Bitcoin);
411                 let mut response = JsonResponse(BlockHeaderData {
412                         chainwork: block.header.work(),
413                         height: 0,
414                         header: block.header
415                 }.into());
416                 response.0.as_object_mut().unwrap().remove("previousblockhash");
417
418                 match TryInto::<BlockHeaderData>::try_into(response) {
419                         Err(e) => panic!("Unexpected error: {:?}", e),
420                         Ok(BlockHeaderData { chainwork: _, height: _, header }) => {
421                                 assert_eq!(header, block.header);
422                         },
423                 }
424         }
425
426         #[test]
427         fn into_block_from_invalid_binary_response() {
428                 let response = BinaryResponse(b"foo".to_vec());
429                 match TryInto::<Block>::try_into(response) {
430                         Err(_) => {},
431                         Ok(_) => panic!("Expected error"),
432                 }
433         }
434
435         #[test]
436         fn into_block_from_valid_binary_response() {
437                 let genesis_block = genesis_block(Network::Bitcoin);
438                 let response = BinaryResponse(encode::serialize(&genesis_block));
439                 match TryInto::<Block>::try_into(response) {
440                         Err(e) => panic!("Unexpected error: {:?}", e),
441                         Ok(block) => assert_eq!(block, genesis_block),
442                 }
443         }
444
445         #[test]
446         fn into_block_from_json_response_with_unexpected_type() {
447                 let response = JsonResponse(serde_json::json!({ "result": "foo" }));
448                 match TryInto::<Block>::try_into(response) {
449                         Err(e) => {
450                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
451                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON string");
452                         },
453                         Ok(_) => panic!("Expected error"),
454                 }
455         }
456
457         #[test]
458         fn into_block_from_json_response_with_invalid_hex_data() {
459                 let response = JsonResponse(serde_json::json!("foobar"));
460                 match TryInto::<Block>::try_into(response) {
461                         Err(e) => {
462                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
463                                 assert_eq!(e.get_ref().unwrap().to_string(), "invalid hex data");
464                         },
465                         Ok(_) => panic!("Expected error"),
466                 }
467         }
468
469         #[test]
470         fn into_block_from_json_response_with_invalid_block_data() {
471                 let response = JsonResponse(serde_json::json!("abcd"));
472                 match TryInto::<Block>::try_into(response) {
473                         Err(e) => {
474                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
475                                 assert_eq!(e.get_ref().unwrap().to_string(), "invalid block data");
476                         },
477                         Ok(_) => panic!("Expected error"),
478                 }
479         }
480
481         #[test]
482         fn into_block_from_json_response_with_valid_block_data() {
483                 let genesis_block = genesis_block(Network::Bitcoin);
484                 let response = JsonResponse(serde_json::json!(encode::serialize_hex(&genesis_block)));
485                 match TryInto::<Block>::try_into(response) {
486                         Err(e) => panic!("Unexpected error: {:?}", e),
487                         Ok(block) => assert_eq!(block, genesis_block),
488                 }
489         }
490
491         #[test]
492         fn into_block_hash_from_json_response_with_unexpected_type() {
493                 let response = JsonResponse(serde_json::json!("foo"));
494                 match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
495                         Err(e) => {
496                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
497                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON object");
498                         },
499                         Ok(_) => panic!("Expected error"),
500                 }
501         }
502
503         #[test]
504         fn into_block_hash_from_json_response_with_unexpected_bestblockhash_type() {
505                 let response = JsonResponse(serde_json::json!({ "bestblockhash": 42 }));
506                 match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
507                         Err(e) => {
508                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
509                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON string");
510                         },
511                         Ok(_) => panic!("Expected error"),
512                 }
513         }
514
515         #[test]
516         fn into_block_hash_from_json_response_with_invalid_hex_data() {
517                 let response = JsonResponse(serde_json::json!({ "bestblockhash": "foobar"} ));
518                 match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
519                         Err(e) => {
520                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
521                                 assert_eq!(e.get_ref().unwrap().to_string(), "invalid hex data");
522                         },
523                         Ok(_) => panic!("Expected error"),
524                 }
525         }
526
527         #[test]
528         fn into_block_hash_from_json_response_without_height() {
529                 let block = genesis_block(Network::Bitcoin);
530                 let response = JsonResponse(serde_json::json!({
531                         "bestblockhash": block.block_hash().to_string(),
532                 }));
533                 match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
534                         Err(e) => panic!("Unexpected error: {:?}", e),
535                         Ok((hash, height)) => {
536                                 assert_eq!(hash, block.block_hash());
537                                 assert!(height.is_none());
538                         },
539                 }
540         }
541
542         #[test]
543         fn into_block_hash_from_json_response_with_unexpected_blocks_type() {
544                 let block = genesis_block(Network::Bitcoin);
545                 let response = JsonResponse(serde_json::json!({
546                         "bestblockhash": block.block_hash().to_string(),
547                         "blocks": "foo",
548                 }));
549                 match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
550                         Err(e) => {
551                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
552                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON number");
553                         },
554                         Ok(_) => panic!("Expected error"),
555                 }
556         }
557
558         #[test]
559         fn into_block_hash_from_json_response_with_invalid_height() {
560                 let block = genesis_block(Network::Bitcoin);
561                 let response = JsonResponse(serde_json::json!({
562                         "bestblockhash": block.block_hash().to_string(),
563                         "blocks": std::u64::MAX,
564                 }));
565                 match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
566                         Err(e) => {
567                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
568                                 assert_eq!(e.get_ref().unwrap().to_string(), "invalid height");
569                         },
570                         Ok(_) => panic!("Expected error"),
571                 }
572         }
573
574         #[test]
575         fn into_block_hash_from_json_response_with_height() {
576                 let block = genesis_block(Network::Bitcoin);
577                 let response = JsonResponse(serde_json::json!({
578                         "bestblockhash": block.block_hash().to_string(),
579                         "blocks": 1,
580                 }));
581                 match TryInto::<(BlockHash, Option<u32>)>::try_into(response) {
582                         Err(e) => panic!("Unexpected error: {:?}", e),
583                         Ok((hash, height)) => {
584                                 assert_eq!(hash, block.block_hash());
585                                 assert_eq!(height.unwrap(), 1);
586                         },
587                 }
588         }
589
590         #[test]
591         fn into_txid_from_json_response_with_unexpected_type() {
592                 let response = JsonResponse(serde_json::json!({ "result": "foo" }));
593                 match TryInto::<Txid>::try_into(response) {
594                         Err(e) => {
595                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
596                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON string");
597                         }
598                         Ok(_) => panic!("Expected error"),
599                 }
600         }
601
602         #[test]
603         fn into_txid_from_json_response_with_invalid_hex_data() {
604                 let response = JsonResponse(serde_json::json!("foobar"));
605                 match TryInto::<Txid>::try_into(response) {
606                         Err(e) => {
607                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
608                                 assert_eq!(e.get_ref().unwrap().to_string(), "bad hex string length 6 (expected 64)");
609                         }
610                         Ok(_) => panic!("Expected error"),
611                 }
612         }
613
614         #[test]
615         fn into_txid_from_json_response_with_invalid_txid_data() {
616                 let response = JsonResponse(serde_json::json!("abcd"));
617                 match TryInto::<Txid>::try_into(response) {
618                         Err(e) => {
619                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
620                                 assert_eq!(e.get_ref().unwrap().to_string(), "bad hex string length 4 (expected 64)");
621                         }
622                         Ok(_) => panic!("Expected error"),
623                 }
624         }
625
626         #[test]
627         fn into_txid_from_json_response_with_valid_txid_data() {
628                 let target_txid = Txid::from_slice(&[1; 32]).unwrap();
629                 let response = JsonResponse(serde_json::json!(encode::serialize_hex(&target_txid)));
630                 match TryInto::<Txid>::try_into(response) {
631                         Err(e) => panic!("Unexpected error: {:?}", e),
632                         Ok(txid) => assert_eq!(txid, target_txid),
633                 }
634         }
635
636         #[test]
637         fn into_txid_from_bitcoind_rpc_json_response() {
638                 let mut rpc_response = serde_json::json!(
639             {"error": "", "id": "770", "result": "7934f775149929a8b742487129a7c3a535dfb612f0b726cc67bc10bc2628f906"}
640
641         );
642         let r: std::io::Result<Txid> = JsonResponse(rpc_response.get_mut("result").unwrap().take())
643             .try_into();
644         assert_eq!(
645             r.unwrap().to_string(),
646             "7934f775149929a8b742487129a7c3a535dfb612f0b726cc67bc10bc2628f906"
647         );
648         }
649
650         // TryInto<Transaction> can be used in two ways, first with plain hex response where data is
651         // the hex encoded transaction (e.g. as a result of getrawtransaction) or as a JSON object
652         // where the hex encoded transaction can be found in the hex field of the object (if present)
653         // (e.g. as a result of signrawtransactionwithwallet).
654
655         // plain hex transaction
656
657         #[test]
658         fn into_tx_from_json_response_with_invalid_hex_data() {
659                 let response = JsonResponse(serde_json::json!("foobar"));
660                 match TryInto::<Transaction>::try_into(response) {
661                         Err(e) => {
662                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
663                                 assert_eq!(e.get_ref().unwrap().to_string(), "invalid hex data");
664                         }
665                         Ok(_) => panic!("Expected error"),
666                 }
667         }
668
669         #[test]
670         fn into_tx_from_json_response_with_invalid_data_type() {
671                 let response = JsonResponse(Value::Number(Number::from_f64(1.0).unwrap()));
672                 match TryInto::<Transaction>::try_into(response) {
673                         Err(e) => {
674                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
675                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON string");
676                         }
677                         Ok(_) => panic!("Expected error"),
678                 }
679         }
680
681         #[test]
682         fn into_tx_from_json_response_with_invalid_tx_data() {
683                 let response = JsonResponse(serde_json::json!("abcd"));
684                 match TryInto::<Transaction>::try_into(response) {
685                         Err(e) => {
686                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
687                                 assert_eq!(e.get_ref().unwrap().to_string(), "invalid transaction");
688                         }
689                         Ok(_) => panic!("Expected error"),
690                 }
691         }
692
693         #[test]
694         fn into_tx_from_json_response_with_valid_tx_data_plain() {
695                 let genesis_block = genesis_block(Network::Bitcoin);
696                 let target_tx = genesis_block.txdata.get(0).unwrap();
697                 let response = JsonResponse(serde_json::json!(encode::serialize_hex(&target_tx)));
698                 match TryInto::<Transaction>::try_into(response) {
699                         Err(e) => panic!("Unexpected error: {:?}", e),
700                         Ok(tx) => assert_eq!(&tx, target_tx),
701                 }
702         }
703
704         #[test]
705         fn into_tx_from_json_response_with_valid_tx_data_hex_field() {
706                 let genesis_block = genesis_block(Network::Bitcoin);
707                 let target_tx = genesis_block.txdata.get(0).unwrap();
708                 let response = JsonResponse(serde_json::json!({"hex": encode::serialize_hex(&target_tx)}));
709                 match TryInto::<Transaction>::try_into(response) {
710                         Err(e) => panic!("Unexpected error: {:?}", e),
711                         Ok(tx) => assert_eq!(&tx, target_tx),
712                 }
713         }
714
715         // transaction in hex field of JSON object
716
717         #[test]
718         fn into_tx_from_json_response_with_no_hex_field() {
719                 let response = JsonResponse(serde_json::json!({ "error": "foo" }));
720                 match TryInto::<Transaction>::try_into(response) {
721                         Err(e) => {
722                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
723                                 assert_eq!(
724                                         e.get_ref().unwrap().to_string(),
725                                         "expected JSON string"
726                                 );
727                         }
728                         Ok(_) => panic!("Expected error"),
729                 }
730         }
731
732         #[test]
733         fn into_tx_from_json_response_not_signed() {
734                 let response = JsonResponse(serde_json::json!({ "hex": "foo", "complete": false }));
735                 match TryInto::<Transaction>::try_into(response) {
736                         Err(e) => {
737                                 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
738                                 assert!(
739                                         e.get_ref().unwrap().to_string().contains(
740                                         "transaction couldn't be signed")
741                                 );
742                         }
743                         Ok(_) => panic!("Expected error"),
744                 }
745         }
746 }