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
use cita_cloud_proto::blockchain::raw_transaction::Tx;
use cita_cloud_proto::blockchain::{
Block, CompactBlock, CompactBlockBody, RawTransaction, RawTransactions,
};
use cita_cloud_proto::common::Address;
use status_code::StatusCode;
use std::fs;
use std::path::Path;
use toml::macros::Deserialize;
use toml::Value;
pub const ADDR_BYTES_LEN: usize = 20;
pub const HASH_BYTES_LEN: usize = 32;
pub fn h160_address_check(address: Option<&Address>) -> Result<(), StatusCode> {
match address {
Some(addr) => {
if addr.address.len() == ADDR_BYTES_LEN {
Ok(())
} else {
Err(StatusCode::ProvideAddressError)
}
}
None => Err(StatusCode::NoProvideAddress),
}
}
pub fn get_tx_hash(raw_tx: &RawTransaction) -> Result<&[u8], StatusCode> {
match raw_tx.tx {
Some(Tx::NormalTx(ref normal_tx)) => Ok(&normal_tx.transaction_hash),
Some(Tx::UtxoTx(ref utxo_tx)) => Ok(&utxo_tx.transaction_hash),
None => Err(StatusCode::NoTransaction),
}
}
pub fn get_tx_hash_list(raw_txs: &RawTransactions) -> Result<Vec<Vec<u8>>, StatusCode> {
let mut hashes = Vec::new();
for raw_tx in &raw_txs.body {
hashes.push(get_tx_hash(raw_tx)?.to_vec())
}
Ok(hashes)
}
pub fn extract_compact(block: Block) -> CompactBlock {
let mut compact_body = CompactBlockBody { tx_hashes: vec![] };
if let Some(body) = block.body {
for raw_tx in body.body {
match raw_tx.tx {
Some(Tx::NormalTx(normal_tx)) => {
compact_body.tx_hashes.push(normal_tx.transaction_hash)
}
Some(Tx::UtxoTx(utxo_tx)) => compact_body.tx_hashes.push(utxo_tx.transaction_hash),
None => {}
}
}
}
CompactBlock {
version: block.version,
header: block.header,
body: Some(compact_body),
}
}
pub fn read_toml<'a, T: Deserialize<'a>>(path: impl AsRef<Path>, name: &'a str) -> T {
let s = fs::read_to_string(path).unwrap();
let config: Value = s.parse().unwrap();
T::deserialize(config[name].clone()).unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
struct ExecutorConfig {
port: u16,
}
#[test]
fn it_works() {
let config: ExecutorConfig = read_toml("src/example/sample.toml", "executor");
assert_eq!(config.port, 50002);
}
}