Skip to content

Commit 762c182

Browse files
committed
Apply review comments
1 parent 1e37af6 commit 762c182

File tree

5 files changed

+58
-37
lines changed

5 files changed

+58
-37
lines changed

mithril-common/src/chain_observer/cli_observer.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,13 @@ impl CardanoCliRunner {
4747
}
4848
}
4949

50-
fn random_out_file() -> PathBuf {
50+
fn random_out_file() -> Result<PathBuf, Box<dyn Error + Sync + Send>> {
5151
let mut rng = rand_core::OsRng;
52-
std::env::temp_dir()
53-
.join("cardano-cli-runner")
54-
.join(format!("{}", rng.next_u64()))
52+
let dir = std::env::temp_dir().join("cardano-cli-runner");
53+
if !dir.exists() {
54+
fs::create_dir_all(&dir)?;
55+
}
56+
Ok(dir.join(format!("{}.out", rng.next_u64())))
5557
}
5658

5759
fn command_for_utxo(&self, address: &str, out_file: PathBuf) -> Command {
@@ -136,14 +138,14 @@ impl CardanoCliRunner {
136138
#[async_trait]
137139
impl CliRunner for CardanoCliRunner {
138140
async fn launch_utxo(&self, address: &str) -> Result<String, Box<dyn Error + Sync + Send>> {
139-
let out_file = Self::random_out_file();
141+
let out_file = Self::random_out_file()?;
140142
let output = self
141143
.command_for_utxo(address, out_file.clone())
142144
.output()
143145
.await?;
144146

145147
if output.status.success() {
146-
Ok(std::str::from_utf8(&output.stdout)?.trim().to_string())
148+
Ok(fs::read_to_string(out_file)?.trim().to_string())
147149
} else {
148150
let message = String::from_utf8_lossy(&output.stderr);
149151

mithril-common/src/chain_observer/model.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,20 @@ pub enum TxDatumError {
2222
pub struct TxDatum(pub String);
2323

2424
impl TxDatum {
25-
/// Retrieves the ith field of the datum with given type
26-
pub fn get_field_raw_value(
25+
/// Retrieves the nth field of the datum with given type
26+
pub fn get_nth_field_by_type(
2727
&self,
2828
type_name: &str,
2929
index: usize,
3030
) -> Result<Value, Box<dyn StdError>> {
3131
let tx_datum_raw = &self.0;
32+
// 1- Parse the Utxo raw data to a hashmap
3233
let v: HashMap<String, Value> = serde_json::from_str(tx_datum_raw).map_err(|e| {
3334
TxDatumError::InvalidContent(
3435
format!("Error: {e:?}, tx datum was = '{tx_datum_raw}'").into(),
3536
)
3637
})?;
38+
// 2- Convert the 'fields' entry to a vec of json objects
3739
let fields = v.get("fields").ok_or_else(|| {
3840
TxDatumError::InvalidContent(
3941
format!("Error: missing 'fields' entry, tx datum was = '{tx_datum_raw}'").into(),
@@ -43,6 +45,7 @@ impl TxDatum {
4345
format!("Error: 'fields' entry is not correctly structured, tx datum was = '{tx_datum_raw}'").into(),
4446
)
4547
})?;
48+
// 3- Filter the vec (keep the ones that match the given type), and retrieve the nth entry of this filtered vec
4649
let field_value = fields
4750
.iter()
4851
.filter(|&field| field.get(type_name).is_some())
@@ -76,29 +79,29 @@ mod test {
7679
assert_eq!(
7780
"bytes0",
7881
tx_datum
79-
.get_field_raw_value("bytes", 0)
82+
.get_nth_field_by_type("bytes", 0)
8083
.unwrap()
8184
.as_str()
8285
.unwrap()
8386
);
8487
assert_eq!(
8588
"bytes1",
8689
tx_datum
87-
.get_field_raw_value("bytes", 1)
90+
.get_nth_field_by_type("bytes", 1)
8891
.unwrap()
8992
.as_str()
9093
.unwrap()
9194
);
9295
assert_eq!(
9396
"bytes2",
9497
tx_datum
95-
.get_field_raw_value("bytes", 2)
98+
.get_nth_field_by_type("bytes", 2)
9699
.unwrap()
97100
.as_str()
98101
.unwrap()
99102
);
100103
tx_datum
101-
.get_field_raw_value("bytes", 100)
104+
.get_nth_field_by_type("bytes", 100)
102105
.expect_err("should have returned an error");
103106
}
104107

@@ -108,29 +111,29 @@ mod test {
108111
assert_eq!(
109112
0,
110113
tx_datum
111-
.get_field_raw_value("int", 0)
114+
.get_nth_field_by_type("int", 0)
112115
.unwrap()
113116
.as_u64()
114117
.unwrap()
115118
);
116119
assert_eq!(
117120
1,
118121
tx_datum
119-
.get_field_raw_value("int", 1)
122+
.get_nth_field_by_type("int", 1)
120123
.unwrap()
121124
.as_u64()
122125
.unwrap()
123126
);
124127
assert_eq!(
125128
2,
126129
tx_datum
127-
.get_field_raw_value("int", 2)
130+
.get_nth_field_by_type("int", 2)
128131
.unwrap()
129132
.as_u64()
130133
.unwrap()
131134
);
132135
tx_datum
133-
.get_field_raw_value("int", 100)
136+
.get_nth_field_by_type("int", 100)
134137
.expect_err("should have returned an error");
135138
}
136139
}

mithril-common/src/crypto_helper/era.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,7 @@ pub enum EraMarkersVerifierError {
2121
SignatureVerification(#[from] SignatureError),
2222
}
2323

24-
/// A protocol Signer that is responsible for signing the
25-
/// [Certificate](https://mithril.network/doc/mithril/mithril-protocol/certificates#the-certificate-chain-design)
24+
/// A cryptographic signer that is responsible for signing the [EreMarker]s
2625
#[derive(Debug, Serialize, Deserialize)]
2726
pub struct EraMarkersSigner {
2827
pub(crate) secret_key: EraMarkersVerifierSecretKey,
@@ -84,7 +83,7 @@ impl EraMarkersSigner {
8483
}
8584
}
8685

87-
/// An era merkers Verifier
86+
/// An era markers verifier that checks the authenticity of era markers stored on the chain
8887
#[derive(Debug, Serialize, Deserialize, Clone)]
8988
pub struct EraMarkersVerifier {
9089
pub(crate) verification_key: EraMarkersVerifierVerificationKey,

mithril-common/src/era/adapters/cardano_chain.rs

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ pub enum EraMarkersPayloadError {
2828
#[error("could not deserialize signature: {0}")]
2929
DeserializeSignature(GeneralError),
3030

31+
/// Error raised when the signature is missing
32+
#[error("could not verify signature: signature is missing")]
33+
MissingSignature,
34+
3135
/// Error raised when the signature is invalid
3236
#[error("could not verify signature: {0}")]
3337
VerifySignature(GeneralError),
@@ -37,45 +41,57 @@ pub enum EraMarkersPayloadError {
3741
CreateSignature(GeneralError),
3842
}
3943

44+
/// Era markers payload
4045
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41-
struct EraMarkersPayload {
46+
pub struct EraMarkersPayload {
4247
markers: Vec<EraMarker>,
43-
signature: HexEncodeEraMarkerSignature,
48+
signature: Option<HexEncodeEraMarkerSignature>,
4449
}
4550

4651
impl EraMarkersPayload {
47-
fn message_to_sign(&self) -> Result<Vec<u8>, EraMarkersPayloadError> {
52+
fn message_to_bytes(&self) -> Result<Vec<u8>, EraMarkersPayloadError> {
4853
serde_json::to_vec(&self.markers)
4954
.map_err(|e| EraMarkersPayloadError::SerializeMessage(e.into()))
5055
}
5156

52-
fn verify_signature(
57+
fn deserialize_signature(&self) -> Result<EraMarkersVerifierSignature, EraMarkersPayloadError> {
58+
EraMarkersVerifierSignature::from_bytes(
59+
&Vec::from_hex(
60+
self.signature
61+
.as_ref()
62+
.ok_or(EraMarkersPayloadError::MissingSignature)?,
63+
)
64+
.map_err(|e| EraMarkersPayloadError::DeserializeSignature(e.into()))?,
65+
)
66+
.map_err(|e| EraMarkersPayloadError::DeserializeSignature(e.into()))
67+
}
68+
69+
/// Verify the signature an era markers payload
70+
pub fn verify_signature(
5371
&self,
5472
verification_key: EraMarkersVerifierVerificationKey,
5573
) -> Result<(), EraMarkersPayloadError> {
56-
let signature = EraMarkersVerifierSignature::from_bytes(
57-
&Vec::from_hex(&self.signature)
58-
.map_err(|e| EraMarkersPayloadError::DeserializeSignature(e.into()))?,
59-
)
60-
.map_err(|e| EraMarkersPayloadError::DeserializeSignature(e.into()))?;
6174
let markers_verifier = EraMarkersVerifier::from_verification_key(verification_key);
75+
6276
markers_verifier
63-
.verify(&self.message_to_sign()?, &signature)
77+
.verify(&self.message_to_bytes()?, &self.deserialize_signature()?)
6478
.map_err(|e| EraMarkersPayloadError::VerifySignature(e.into()))
6579
}
6680

67-
#[cfg(any(test, feature = "test_only"))]
68-
fn sign(self, signer: &EraMarkersSigner) -> Result<Self, EraMarkersPayloadError> {
81+
/// Sign an era markers payload
82+
#[allow(dead_code)]
83+
pub fn sign(self, signer: &EraMarkersSigner) -> Result<Self, EraMarkersPayloadError> {
6984
let signature = signer
7085
.sign(
7186
&self
72-
.message_to_sign()
87+
.message_to_bytes()
7388
.map_err(|e| EraMarkersPayloadError::CreateSignature(e.into()))?,
7489
)
7590
.encode_hex::<String>();
91+
7692
Ok(Self {
7793
markers: self.markers,
78-
signature,
94+
signature: Some(signature),
7995
})
8096
}
8197
}
@@ -111,7 +127,7 @@ impl EraReaderAdapter for CardanoChainAdapter {
111127
.await?;
112128
let markers_list = tx_datums
113129
.into_iter()
114-
.filter_map(|datum| datum.get_field_raw_value("bytes", 0).ok())
130+
.filter_map(|datum| datum.get_nth_field_by_type("bytes", 0).ok())
115131
.filter_map(|field_value| field_value.as_str().map(|s| s.to_string()))
116132
.filter_map(|field_value_str| key_decode_hex(&field_value_str).ok())
117133
.filter_map(|era_markers_payload: EraMarkersPayload| {
@@ -121,6 +137,7 @@ impl EraReaderAdapter for CardanoChainAdapter {
121137
.map(|_| era_markers_payload.markers)
122138
})
123139
.collect::<Vec<Vec<EraMarker>>>();
140+
124141
Ok(markers_list.first().unwrap_or(&Vec::new()).to_owned())
125142
}
126143
}
@@ -154,14 +171,14 @@ mod test {
154171
EraMarker::new("thales", Some(Epoch(1))),
155172
EraMarker::new("pythagoras", None),
156173
],
157-
signature: "".to_string(),
174+
signature: None,
158175
};
159176
let era_marker_payload_2 = EraMarkersPayload {
160177
markers: vec![
161178
EraMarker::new("thales", Some(Epoch(1))),
162179
EraMarker::new("pythagoras", Some(Epoch(2))),
163180
],
164-
signature: "".to_string(),
181+
signature: None,
165182
};
166183
let mut fake_datums = dummy_tx_datums_from_markers_payload(vec![
167184
era_marker_payload_1,

mithril-test-lab/mithril-devnet/devnet-mkfiles.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1004,7 +1004,7 @@ done
10041004
NODE_IX=0
10051005
for NODE in ${POOL_NODES}; do
10061006
NODE_ID=$(( $NODE_IX + 1))
1007-
if [ `expr $NODE_IX % 2` == 0 || -z "${WITH_UNCERTIFIED_SIGNERS}" ]; then
1007+
if [ `expr $NODE_IX % 2` == 0 ] || [ -z "${WITH_UNCERTIFIED_SIGNERS}" ]; then
10081008
# 50% of signers with key certification
10091009
cat >> ${NODE}/info.json <<EOF
10101010
{

0 commit comments

Comments
 (0)