postchain-client 0.0.5

Just another Chromia Postchain client implemented in Rust.
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! Client module for interacting with Postchain blockchain nodes via REST API.
//! 
//! This module provides functionality for:
//! - Querying blockchain nodes
//! - Managing transactions
//! - Handling REST API communication
//! - Error handling

extern crate serde_json;
extern crate url;

use reqwest::{header::CONTENT_TYPE, Client};
use url::Url;

use serde_json::Value;
use std::{error::Error, time::Duration};

use crate::utils::transaction::{Transaction, TransactionConfirmationProofData, TransactionStatus};

/// A REST client for interacting with Postchain blockchain nodes.
/// 
/// This client handles communication with blockchain nodes, including:
/// - Transaction submission and status checking
/// - Node discovery and management
/// - Query execution
/// - Error handling
#[derive(Debug)]
pub struct RestClient<'a> {
    /// List of node URLs to connect to
    pub node_url: Vec<&'a str>,
    /// Request timeout in seconds
    pub request_time_out: u64,
    /// Number of attempts to poll for transaction status
    pub poll_attemps: u64,
    /// Interval between poll attempts in seconds
    pub poll_attemp_interval_time: u64
}

/// Response types that can be returned from REST API calls.
#[derive(Debug)]
pub enum RestResponse {
    /// Plain text response
    String(String),
    /// JSON response
    Json(Value),
    /// Binary response
    Bytes(Vec<u8>),
}

/// HTTP methods supported by the REST client.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum RestRequestMethod {
    /// HTTP GET method
    GET,
    /// HTTP POST method
    POST,
}

impl<'a> Default for RestClient<'a> {
    fn default() -> Self {
        RestClient {
            node_url: vec!["http://localhost:7740"],
            request_time_out: 30,
            poll_attemps: 5,
            poll_attemp_interval_time: 5
        }
    }
}

/// Types of errors that can occur during REST operations
#[derive(Debug)]
pub enum TypeError {
    /// Error from the reqwest client
    FromReqClient,
    /// Error from the REST API
    FromRestApi,
}

/// Error type for REST operations
#[derive(Debug)]
pub struct RestError {
    /// HTTP status code if available
    pub status_code: Option<String>,
    /// Error message if available
    pub error_str: Option<String>,
    /// JSON error response if available
    pub error_json: Option<Value>,
    /// Type of error that occurred
    pub type_error: TypeError,
}

impl Error for RestError {}

impl Default for RestError {
    fn default() -> Self {
        RestError {
            status_code: None,
            error_str: None,
            error_json: None,
            type_error: TypeError::FromRestApi,
        }
    }
}

impl std::fmt::Display for RestError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut hsc = "N/A".to_string();
        let mut err_str = "N/A".to_string();

        if let Some(val) = &self.status_code {
            hsc = val.clone();
        }

        if let Some(val) = &self.error_str {
            err_str = val.clone();
        }

        write!(f, "{:?} {} {}", self.type_error, hsc, err_str)
    }
}

impl<'a> RestClient<'a> {
    /// Retrieves a list of node URLs from the blockchain directory.
    ///
    /// # Arguments
    /// * `brid` - Blockchain RID (Resource Identifier)
    ///
    /// # Returns
    /// * `Result<Vec<String>, RestError>` - List of node URLs on success, or error on failure
    ///
    /// # Example
    /// ```no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = RestClient::default();
    /// let nodes = client.get_nodes_from_directory("blockchain_rid").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_nodes_from_directory(&self, brid: &str) -> Result<Vec<String>, RestError> {
        let directory_brid = self.get_blockchain_rid(0).await?;

        let path_segments = &["query", &directory_brid];
        let query_params = vec![
            ("type", "cm_get_blockchain_api_urls"),
            ("blockchain_rid", brid),
        ];
        let query_body_json = None;
        let query_body_raw = None;

        let resp = self
            .postchain_rest_api(
                RestRequestMethod::GET,
                Some(path_segments),
                Some(&query_params),
                query_body_json,
                query_body_raw
            )
            .await;

        match resp {
            Ok(RestResponse::Json(json_val)) => {
                let list_of_nodes = json_val
                    .as_array()
                    .unwrap()
                    .iter()
                    .filter_map(|value| value.as_str().map(String::from))
                    .collect();
                Ok(list_of_nodes)
            }
            Ok(RestResponse::String(str_val)) => Ok(vec![str_val]),
            Ok(_) => Ok(vec!["nop".to_string()]),
            Err(error) => {
                tracing::error!("Can't get API urls from DC chain: {} because of error: {:?}", brid, error);
                Err(error)
            }
        }
    }

    /// Retrieves the blockchain RID for a given blockchain IID.
    ///
    /// # Arguments
    /// * `blockchain_iid` - Blockchain Instance Identifier
    ///
    /// # Returns
    /// * `Result<String, RestError>` - Blockchain RID on success, or error on failure
    pub async fn get_blockchain_rid(&self, blockchain_iid: u8) -> Result<String, RestError> {
        let resp: Result<RestResponse, RestError> = self
            .postchain_rest_api(
                RestRequestMethod::GET,
                Some(&[&format!("/brid/iid_{blockchain_iid}")]),
                None,
                None,
                None
            )
            .await;

        if let Err(error) = resp {
            tracing::error!("Can't get blockchain RID with IID = {} because of error: {:?}", blockchain_iid, error);
            return Err(error);
        }

        let resp_val: RestResponse = resp.unwrap();

        match resp_val {
            RestResponse::String(val) => Ok(val.to_string()),
            _ => Ok("".to_string()),
        }
    }

    /// Prints error information and determines if the error should be ignored.
    ///
    /// # Arguments
    /// * `error` - The REST error to print
    /// * `ignore_all_errors` - Whether to ignore all errors
    ///
    /// # Returns
    /// * `bool` - Whether the error should stop execution
    pub fn print_error(&self, error: &RestError, ignore_all_errors: bool) -> bool {
        println!(">> Error(s)");

        if let Some(error_str) = &error.error_str {
            println!("{error_str}");
        } else {
            let val = &error.error_json.as_ref().unwrap();
            let pprint = serde_json::to_string_pretty(val).unwrap();
            println!("{pprint}");
        }

        if ignore_all_errors {
            println!("Allow ignore this error");
            return false
        }

        true
    }

    /// Detects the Merkle hash version used by a blockchain.
    ///
    /// This function queries the blockchain's configuration to determine which version
    /// of the Merkle hash algorithm is being used. If the query fails or the version
    /// information is not available, it defaults to version 1.
    ///
    /// # Arguments
    /// * `brid` - The blockchain RID (Resource Identifier) as a hex-encoded string
    ///
    /// # Returns
    /// * `u8` - The Merkle hash version number (defaults to 1 if not specified)
    ///
    /// # Example
    /// ```no_run
    /// # use postchain_client::transport::RestClient;
    /// # async fn example() {
    /// let client = RestClient::default();
    /// let brid = "DCE5D72ED7E1675291AFE7F9D649D898C8D3E7411E52882D03D1B3D240BDD91B";
    /// let hash_version = client.detect_merkle_hash_version(brid).await;
    /// println!("Blockchain uses Merkle hash version {}", hash_version);
    /// # }
    /// ```
    pub async fn detect_merkle_hash_version(&self, brid: &str) -> u8 {
        tracing::info!("Detecting merkle hash version of blockchain: {}", brid); 

        let mut merkle_hash_version = 1;

        if let Ok(RestResponse::Json(json_val)) = self.postchain_rest_api(
            RestRequestMethod::GET,
            Some(&["config", brid, "features"]),
            None,
            None,
            None
        ).await {
            if let Some(version) = json_val["merkle_hash_version"].as_u64() {
                merkle_hash_version = version as u8;
                tracing::info!("Found merkle hash version = {}", merkle_hash_version);
                return merkle_hash_version;
            }
        }

        tracing::warn!("Failed to detect merkle hash version, using default version = {}", merkle_hash_version);
        merkle_hash_version
    }

    /// Updates the list of node URLs used by the client.
    ///
    /// # Arguments
    /// * `node_urls` - New list of node URLs to use
    pub fn update_node_urls(&mut self, node_urls: &'a [String]) {
        self.node_url = node_urls.iter().map(String::as_str).collect();
    }

    // Transaction status
    // GET /tx/{blockchain_rid}/{transaction_rid}/status
    /// Gets the status of a transaction without polling.
    ///
    /// # Arguments
    /// * `blockchain_rid` - Blockchain RID
    /// * `tx_rid` - Transaction RID
    ///
    /// # Returns
    /// * `Result<TransactionStatus, RestError>` - Transaction status or error
    pub async fn get_transaction_status(&self, blockchain_rid: &str, tx_rid: &str) -> Result<TransactionStatus, RestError> {
        self.get_transaction_status_with_poll(blockchain_rid, tx_rid, 0).await
    }

/// Fetches and parses transaction-related data from the Postchain node.
    ///
    /// This is a generic helper function to retrieve data associated with a transaction
    /// (like confirmation proofs or raw transaction data) from a Postchain node.
    /// It handles the common logic of making the REST API call, extracting a specific
    /// string field from the JSON response, and then parsing that string using a provided
    /// parsing function.
    ///
    /// # Type Parameters
    ///
    /// * `R`: The expected return type after parsing the extracted string (e.g., `Transaction` or `TransactionConfirmationProofData`).
    /// * `F`: A closure type that takes a string slice (`&str`) and returns a `Result<R, String>`.
    ///   This closure encapsulates the specific parsing logic (e.g., `Transaction::from_raw_data` or `Transaction::confirmation_proof`).
    ///
    /// # Arguments
    ///
    /// * `blockchain_rid` - A string slice representing the Blockchain RID.
    /// * `tx_rid` - A string slice representing the Transaction RID.
    /// * `endpoint_suffix` - An optional string slice that will be appended to the base
    ///   transaction path (`/tx/{blockchain_rid}/{tx_rid}`). For example, use "confirmationProof"
    ///   to get the confirmation proof, or `None` to get the raw transaction data.
    /// * `field_name` - The name of the JSON field to extract the data from (e.g., "proof" or "tx").
    /// * `parser_fn` - A closure or function pointer that takes the extracted string slice
    ///   and attempts to parse it into the desired return type `R`.
    ///
    /// # Returns
    ///
    /// A `Result<R, RestError>`:
    /// - `Ok(R)`: On successful retrieval and parsing of the data.
    /// - `Err(RestError)`: If the request fails, the response is not JSON, the specified
    ///   `field_name` is missing or invalid, or the `parser_fn` returns an error.
    ///
    /// # Errors
    ///
    /// This function can return a `RestError` in the following cases:
    /// - If the underlying `postchain_rest_api` call fails (e.g., network issues).
    /// - If the response from the node is not a JSON object.
    /// - If the JSON response does not contain the `field_name`, or if its value is not a string.
    /// - If the `parser_fn` fails to parse the extracted string.
    ///
    /// # Example (Conceptual Usage within other methods)
    ///
    /// ```rust
    /// # use postchain_client::transport::{RestClient, RestError};
    /// # use postchain_client::utils::transaction::{Transaction, TransactionConfirmationProofData};
    /// # async fn _example_usage(client: &RestClient<'_>, blockchain_rid: &str, tx_rid: &str) -> Result<(), RestError> {
    /// // How `get_confirmation_proof` would now use this generic function:
    /// let proof_data: TransactionConfirmationProofData = client.get_transaction_data(
    ///     blockchain_rid,
    ///     tx_rid,
    ///     Some("confirmationProof"),
    ///     "proof",
    ///     |s| Transaction::confirmation_proof(s),
    /// ).await?;
    ///
    /// // How `get_raw_transaction_data` would now use this generic function:
    /// let raw_tx_data: Transaction = client.get_transaction_data(
    ///     blockchain_rid,
    ///     tx_rid,
    ///     None, // No suffix for raw transaction data
    ///     "tx",
    ///     |s| Transaction::from_raw_data(s),
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    async fn get_transaction_data<R, F>(&self, blockchain_rid: &str, tx_rid: &str, endpoint_suffix: Option<&str>, field_name: &str, parser_fn: F ) -> Result<R, RestError>
    where
        F: FnOnce(&str) -> Result<R, String>,
    {
        let mut path_segments = vec!["tx", blockchain_rid, tx_rid];
        if let Some(suffix) = endpoint_suffix {
            path_segments.push(suffix);
        }

        let resp = self
            .postchain_rest_api(
                RestRequestMethod::GET,
                Some(path_segments.as_slice()),
                None,
                None,
                None,
            )
            .await?;

        match resp {
            RestResponse::Json(json_val) => {
                match json_val.get(field_name).and_then(|v| v.as_str()) {
                    Some(data_str) => {
                        parser_fn(data_str).map_err(|e| RestError {
                            error_str: Some(format!(
                                "Failed to parse '{field_name}' field: {e}"
                            )),
                            ..RestError::default()
                        })
                    }
                    None => Err(RestError {
                        error_str: Some(format!(
                            "Missing or invalid '{field_name}' field in response"
                        )),
                        ..RestError::default()
                    }),
                }
            }
            _ => Err(RestError {
                error_str: Some(format!("Expected JSON response with '{field_name}' field")),
                ..RestError::default()
            }),
        }
    }

    /// Retrieves the confirmation proof for a given transaction.
    ///
    /// This function makes a GET request to the `/tx/{blockchain_rid}/{tx_rid}/confirmationProof`
    /// endpoint of the Postchain node to fetch the cryptographic proof that a transaction
    /// has been confirmed on the blockchain.
    ///
    /// # Arguments
    /// * `blockchain_rid` - A string slice representing the Blockchain RID (Resource Identifier)
    /// * `tx_rid` - A string slice representing the Transaction RID (Resource Identifier)
    ///
    /// # Returns
    /// * `Result<TransactionConfirmationProofData, RestError>` - Returns `Ok(TransactionConfirmationProofData)`
    ///   on successful retrieval and parsing of the proof, or `Err(RestError)` if the request fails,
    ///   the response is not JSON, or the 'proof' field is missing/invalid.
    ///
    /// # Errors
    /// This function can return a `RestError` in the following cases:
    /// - If the underlying `postchain_rest_api` call fails (e.g., network issues, node unreachable).
    /// - If the response from the node is not a JSON object.
    /// - If the JSON response does not contain a "proof" field, or if the "proof" field is not a string.
    /// - If the string value of the "proof" field cannot be successfully parsed into a `TransactionConfirmationProofData` struct.
    ///
    /// # Example
    /// ```no_run
    /// # use postchain_client::transport::RestClient;
    /// # use postchain_client::utils::transaction::TransactionConfirmationProofData;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = RestClient::default();
    /// let blockchain_rid = "your_blockchain_rid_hex_string"; // Replace with actual blockchain RID
    /// let tx_rid = "your_transaction_rid_hex_string";     // Replace with actual transaction RID
    ///
    /// match client.get_confirmation_proof(blockchain_rid, tx_rid).await {
    ///     Ok(proof_data) => {
    ///         println!("Successfully retrieved confirmation proof:");
    ///         println!("Block height: {}", proof_data.block_height);
    ///         // Further processing of proof_data...
    ///     },
    ///     Err(e) => {
    ///         eprintln!("Failed to get confirmation proof: {}", e);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_confirmation_proof(&self, blockchain_rid: &str, tx_rid: &str) -> Result<TransactionConfirmationProofData, RestError> {
        self.get_transaction_data(
            blockchain_rid,
            tx_rid,
            Some("confirmationProof"),
            "proof",
            Transaction::confirmation_proof,
        ).await
    }

    /// Retrieves the raw transaction data for a given transaction.
    ///
    /// This function makes a GET request to the `/tx/{blockchain_rid}/{tx_rid}` endpoint
    /// of the Postchain node to fetch the raw hexadecimal representation of a transaction.
    ///
    /// # Arguments
    /// * `blockchain_rid` - A string slice representing the Blockchain RID.
    /// * `tx_rid` - A string slice representing the Transaction RID.
    ///
    /// # Returns
    /// * `Result<Transaction, RestError>` - Returns `Ok(Transaction)` on successful retrieval
    ///   and parsing of the raw transaction data, or `Err(RestError)` if the request fails,
    ///   the response is not JSON, or the 'tx' field is missing/invalid.
    ///
    /// # Errors
    /// This function can return a `RestError` in the following cases:
    /// - If the underlying `postchain_rest_api` call fails (e.g., network issues, node unreachable).
    /// - If the response from the node is not a JSON object.
    /// - If the JSON response does not contain a "tx" field, or if the "tx" field is not a string.
    /// - If the string value of the "tx" field cannot be successfully parsed into a `Transaction` struct
    ///   by `Transaction::from_raw_data`.
    ///
    /// # Example
    /// ```no_run
    /// # use postchain_client::transport::RestClient;
    /// # use postchain_client::utils::transaction::Transaction;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = RestClient::default();
    /// let blockchain_rid = "your_blockchain_rid_hex_string"; // Replace with actual blockchain RID
    /// let tx_rid = "your_transaction_rid_hex_string";     // Replace with actual transaction RID
    ///
    /// match client.get_raw_transaction_data(blockchain_rid, tx_rid).await {
    ///     Ok(transaction) => {
    ///         println!("Successfully retrieved raw transaction data: {:?}", transaction);
    ///         // Further processing of transaction object...
    ///     },
    ///     Err(e) => {
    ///         eprintln!("Failed to get raw transaction data: {}", e);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_raw_transaction_data(&self, blockchain_rid: &str, tx_rid: &str) -> Result<Transaction, RestError>{
        self.get_transaction_data(blockchain_rid, tx_rid, None, "tx", |s| {
            Transaction::from_raw_data(s)
        }).await
    }

    /// Gets the status of a transaction with polling for confirmation.
    ///
    /// # Arguments
    /// * `blockchain_rid` - Blockchain RID
    /// * `tx_rid` - Transaction RID
    /// * `attempts` - Number of polling attempts made so far
    ///
    /// # Returns
    /// * `Result<TransactionStatus, RestError>` - Transaction status or error
    pub async fn get_transaction_status_with_poll(&self, blockchain_rid: &str, tx_rid: &str, attempts: u64) -> Result<TransactionStatus, RestError> {
        tracing::info!("Waiting for transaction status of blockchain RID: {} with tx: {} | attempt: {}", blockchain_rid, tx_rid, attempts);

        if attempts >= self.poll_attemps {
            tracing::warn!("Transaction status still in waiting status after {} attempts", attempts);
            return Ok(TransactionStatus::WAITING);
        }

        let resp = self.postchain_rest_api(RestRequestMethod::GET,
            Some(&["tx", blockchain_rid, tx_rid, "status"]),
            None,
            None,
            None).await?;
        match resp {
            RestResponse::Json(val) => {
                let status: serde_json::Map<String, Value> = serde_json::from_value(val).unwrap();
                if let Some(status_value) = status.get("status") {
                    let status_value = status_value.as_str();
                    match status_value {
                        Some("waiting") => {
                            // Waiting for transaction rejected or confirmed!!!
                            // Interval time = 5 secs on each attempt
                            // Break after 5 attempts
                            tokio::time::sleep(Duration::from_secs(self.poll_attemp_interval_time)).await;
                            return Box::pin(self.get_transaction_status_with_poll(blockchain_rid, tx_rid, attempts + 1)).await;
                        },
                        Some("confirmed") => {
                            tracing::info!("Transaction confirmed!");
                            return Ok(TransactionStatus::CONFIRMED)
                        },
                        Some("rejected") => {
                            tracing::warn!("Transaction rejected!");
                            return Ok(TransactionStatus::REJECTED)
                        },
                        _ => return Ok(TransactionStatus::UNKNOWN)
                    };
                }
                Ok(TransactionStatus::UNKNOWN)
            }
            _ => {
                Ok(TransactionStatus::UNKNOWN)
            }
        }
    }

    // Submit transaction
    // POST /tx/{blockchainRid}
    /// Sends a transaction to the blockchain.
    ///
    /// # Arguments
    /// * `tx` - Transaction to send
    ///
    /// # Returns
    /// * `Result<RestResponse, RestError>` - Response from the blockchain or error
    pub async fn send_transaction(&self, tx: &Transaction) -> Result<RestResponse, RestError> {
        let txe = tx.gvt_hex_encoded();

        let resq_body: serde_json::Map<String, Value> =
            vec![("tx".to_string(), serde_json::json!(txe))]
                .into_iter()
                .collect();

        let blockchain_rid = hex::encode(tx.blockchain_rid.clone()).as_str().to_owned();

        tracing::info!("Sending transaction to {}", blockchain_rid); 

        self
            .postchain_rest_api(
                RestRequestMethod::POST,
                Some(&["tx", &blockchain_rid]),
                None,
                Some(serde_json::json!(resq_body)),
                None
            )
            .await
    }

    // Make a query with GTV encoded response
    // POST /query_gtv/{blockchainRid}
    /// Executes a query on the blockchain.
    ///
    /// # Arguments
    /// * `brid` - Blockchain RID
    /// * `query_prefix` - Optional prefix for the query endpoint
    /// * `query_type` - Type of query to execute
    /// * `query_params` - Optional query parameters
    /// * `query_args` - Optional query arguments
    ///
    /// # Returns
    /// * `Result<RestResponse, RestError>` - Query response or error
    pub async fn query<T: AsRef<str>>(
        &self,
        brid: &str,
        query_prefix: Option<&str>,
        query_type: &'a str,
        query_params: Option<&'a mut Vec<(&'a str, &'a str)>>,
        query_args: Option<&'a mut Vec<(T, crate::utils::operation::Params)>>,
    ) -> Result<RestResponse, RestError> {
        let query_prefix_str = query_prefix.unwrap_or("query_gtv");

        let mut query_args_converted: Option<Vec<(&str, crate::utils::operation::Params)>> = query_args.map(|args| {
            args.iter()
                .map(|(key, params)| (key.as_ref(), params.clone()))
                .collect()
        });

        let encode_str = crate::encoding::gtv::encode(query_type, query_args_converted.as_mut());      
        
        tracing::info!("Querying {} to {}", query_type, brid); 

        self.postchain_rest_api(
            RestRequestMethod::POST,
            Some(&[query_prefix_str, brid]),
            query_params.as_deref(),
            None,
            Some(encode_str)
        ).await
    }

    /// Makes a REST API request to a Postchain node.
    ///
    /// # Arguments
    /// * `method` - HTTP method to use
    /// * `path_segments` - URL path segments
    /// * `query_params` - Query parameters
    /// * `query_body_json` - JSON request body
    /// * `query_body_raw` - Raw request body
    ///
    /// # Returns
    /// * `Result<RestResponse, RestError>` - API response or error
    async fn postchain_rest_api(
        &self,
        method: RestRequestMethod,
        path_segments: Option<&[&str]>,
        query_params: Option<&'a Vec<(&'a str, &'a str)>>,
        query_body_json: Option<Value>,
        query_body_raw: Option<Vec<u8>>
    ) -> Result<RestResponse, RestError> {
        let mut node_index: usize = 0;
        loop {
            let result = self.postchain_rest_api_with_poll(method,
                path_segments, query_params,
                query_body_json.clone(), query_body_raw.clone(), node_index).await;

            if let Err(ref error) = result {
                node_index += 1;

                if node_index >= self.node_url.len() || error.status_code.is_some() {
                    return result;
                }
                tracing::info!("The API endpoint can't be reached; will try another one!");
                continue;
            }
            return result;
        }
    }

    /// Makes a REST API request with retry logic for failed nodes.
    ///
    /// # Arguments
    /// * `method` - HTTP method to use
    /// * `path_segments` - URL path segments
    /// * `query_params` - Query parameters
    /// * `query_body_json` - JSON request body
    /// * `query_body_raw` - Raw request body
    /// * `node_index` - Index of the node to try
    ///
    /// # Returns
    /// * `Result<RestResponse, RestError>` - API response or error
    async fn postchain_rest_api_with_poll(
        &self,
        method: RestRequestMethod,
        path_segments: Option<&[&str]>,
        query_params: Option<&'a Vec<(&'a str, &'a str)>>,
        query_body_json: Option<Value>,
        query_body_raw: Option<Vec<u8>>,
        node_index: usize,
    ) -> Result<RestResponse, RestError> {

        let mut url = Url::parse(self.node_url[node_index]).unwrap();

        tracing::info!("Requesting on API endpoint: {}", url);

        if let Some(ps) = path_segments {
            if !ps.is_empty() {
                let psj = ps.join("/");
                url.set_path(&psj);
            }
        }

        if let Some(qp) = query_params {
            if !qp.is_empty() {
                for (name, value) in qp {
                    url.query_pairs_mut().append_pair(name, value);
                }
            }
        }

        if method == RestRequestMethod::POST
            && query_body_json.is_none()
            && query_body_raw.is_none()
        {
            let error_str = "Error: POST request need a body [json or binary].".to_string();

            tracing::error!(error_str);

            return Err(RestError {
                type_error: TypeError::FromRestApi,
                error_str: Some(error_str),
                status_code: None,
                ..Default::default()
            });
        }

        let rest_client = Client::new();

        let req_result = match method {
            RestRequestMethod::GET => {
                rest_client
                    .get(url.clone())
                    .timeout(Duration::from_secs(self.request_time_out))
                    .send()
                    .await
            }

            RestRequestMethod::POST => {
                if let Some(qb) = query_body_json {
                    rest_client
                        .post(url.clone())
                        .timeout(Duration::from_secs(self.request_time_out))
                        .json(&qb)
                        .send()
                        .await
                } else {
                    let r_body = reqwest::Body::from(query_body_raw.unwrap());
                    rest_client
                        .post(url.clone())
                        .timeout(Duration::from_secs(self.request_time_out))
                        .body(r_body)
                        .send()
                        .await
                }
            }
        };

        let req_result_match = match req_result {
            Ok(resp) => {
                let http_status_code = resp.status().to_string();
                let http_resp_header = resp.headers().get(CONTENT_TYPE).unwrap().to_str().unwrap();
                let json_resp = http_resp_header.contains("application/json");
                let octet_stream_resp = http_resp_header.contains("application/octet-stream");

                if http_status_code.starts_with('4') || http_status_code.starts_with('5') {
                    let mut err = RestError {
                        status_code: Some(http_status_code),
                        type_error: TypeError::FromRestApi,
                        ..Default::default()
                    };

                    if json_resp {
                        let error_json = resp.json().await.unwrap();
                        err.error_json = Some(error_json);
                    } else {
                        let error_str = resp.text().await.unwrap();
                        err.error_str = Some(error_str);
                    }

                    tracing::error!("{:?}", err);

                    return Err(err);
                }

                let rest_resp: RestResponse;

                if json_resp {
                    let val = resp.json().await.unwrap();
                    rest_resp = RestResponse::Json(val);
                } else if octet_stream_resp {
                    let bytes = resp.bytes().await.unwrap();
                    rest_resp = RestResponse::Bytes(bytes.to_vec());
                } else {
                    let val = resp.text().await.unwrap();
                    rest_resp = RestResponse::String(val);
                }

                Ok(rest_resp)
            }
            Err(error) => {
                let rest_error = RestError {
                    error_str: Some(error.to_string()),
                    type_error: TypeError::FromReqClient,
                    ..Default::default()};

                tracing::error!("{:?}", rest_error);

                Err(rest_error)
            },
        };

        req_result_match
    }
}

#[tokio::test]
async fn client_detect_merkle_hash_version() {
    let rc = RestClient{
        node_url: vec!["https://node11.devnet1.chromia.dev:7740"],
        ..Default::default()
    };

    let blockchain_rid = "DCE5D72ED7E1675291AFE7F9D649D898C8D3E7411E52882D03D1B3D240BDD91B";

    let merkle_hash_version = rc.detect_merkle_hash_version(blockchain_rid).await;

    assert_eq!(merkle_hash_version, 2);
}