Skip to content

Commit 8edd128

Browse files
authored
[key server] Misc clean ups (#415)
1 parent 75e0e73 commit 8edd128

File tree

8 files changed

+17
-135
lines changed

8 files changed

+17
-135
lines changed

crates/crypto/src/lib.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -132,11 +132,7 @@ pub fn seal_encrypt(
132132
indices, shares, ..
133133
} = split(&mut rng, base_key, threshold, number_of_shares)?;
134134

135-
let services = key_servers
136-
.iter()
137-
.zip(indices)
138-
.map(|(s, i)| (*s, i))
139-
.collect::<Vec<_>>();
135+
let services = key_servers.iter().cloned().zip(indices).collect::<Vec<_>>();
140136

141137
let encrypted_shares = match public_keys {
142138
IBEPublicKeys::BonehFranklinBLS12381(pks) => {

crates/crypto/src/tss.rs

Lines changed: 0 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -114,37 +114,6 @@ pub fn combine<const N: usize>(shares: &[(u8, [u8; N])]) -> FastCryptoResult<[u8
114114
.expect("fixed length"))
115115
}
116116

117-
pub fn split_with_given_shares<const N: usize>(
118-
given_shares: &[[u8; N]],
119-
number_of_shares: u8,
120-
) -> FastCryptoResult<SecretSharing<N>> {
121-
let threshold = given_shares.len();
122-
if threshold > number_of_shares as usize || threshold == 0 {
123-
return Err(InvalidInput);
124-
}
125-
126-
let indices = (1..=number_of_shares).collect_vec();
127-
128-
// Share each byte of the secret individually.
129-
let (secret, byte_shares): (Vec<u8>, Vec<Vec<u8>>) = (0..N)
130-
.map(|i| {
131-
split_byte_with_given_shares(&given_shares.iter().map(|s| s[i]).collect_vec(), &indices)
132-
})
133-
.collect::<FastCryptoResult<Vec<_>>>()?
134-
.into_iter()
135-
.unzip();
136-
137-
// Combine the byte shares into shares.
138-
let shares = transpose(&byte_shares)?;
139-
let secret = secret.try_into().expect("fixed length");
140-
141-
Ok(SecretSharing {
142-
secret,
143-
indices,
144-
shares,
145-
})
146-
}
147-
148117
/// Internal function to share a secret.
149118
/// This is an implementation of Shamir's secret sharing over the Galois field of 256 elements.
150119
/// See https://dl.acm.org/doi/10.1145/359168.359176.
@@ -175,44 +144,6 @@ fn split_byte<R: AllowedRng>(
175144
.collect())
176145
}
177146

178-
/// Create a secret sharing of `num_shares` shares such that at least `threshold` shares are needed
179-
/// to reconstruct the byte and such that the first `threshold` shares will be the given ones.
180-
///
181-
/// The shared secret will be determined by the given shares, and the process is deterministic.
182-
///
183-
/// Returns the secret and a vector of the shares.
184-
fn split_byte_with_given_shares(
185-
given_shares: &[u8],
186-
indices: &[u8],
187-
) -> FastCryptoResult<(u8, Vec<u8>)> {
188-
let number_of_shares = indices.len();
189-
let threshold = given_shares.len() + 1;
190-
assert!(threshold <= number_of_shares && number_of_shares <= 255 && threshold > 0);
191-
assert!(indices.iter().all(|&i| i != 0) && indices.iter().all_unique());
192-
193-
// Construct the polynomial that interpolates the given shares and the secret.
194-
let polynomial = Polynomial::interpolate(
195-
&indices
196-
.iter()
197-
.zip(given_shares)
198-
.map(|(&x, &y)| (x.into(), y.into()))
199-
.collect_vec(),
200-
);
201-
202-
// The secret is the constant term of the polynomial.
203-
let secret = polynomial.0[0].0;
204-
205-
// Evaluate the polynomial at the remaining indices to get the remaining shares.
206-
let remaining_shares = indices[given_shares.len()..]
207-
.iter()
208-
.map(|i| polynomial.evaluate(&i.into()).0)
209-
.collect();
210-
211-
let shares = [given_shares.to_vec(), remaining_shares].concat();
212-
213-
Ok((secret, shares))
214-
}
215-
216147
/// Internal function to reconstruct a secret.
217148
/// This is an implementation of Shamir's secret sharing over the Galois field of 256 elements.
218149
/// See https://dl.acm.org/doi/10.1145/359168.359176.
@@ -324,44 +255,4 @@ mod tests {
324255

325256
assert_ne!(combine(&shares[..1]).unwrap(), expected);
326257
}
327-
328-
#[test]
329-
fn test_split_byte_with_given_shares() {
330-
let given_shares = [5, 19];
331-
let indices = [1, 2, 3, 4, 5];
332-
333-
let (secret, shares) = split_byte_with_given_shares(&given_shares, &indices).unwrap();
334-
335-
let reconstructed = combine_byte(&[
336-
(indices[0], shares[0]),
337-
(indices[2], shares[2]),
338-
(indices[4], shares[4]),
339-
])
340-
.unwrap();
341-
assert_eq!(reconstructed, secret);
342-
}
343-
344-
#[test]
345-
fn test_with_given_shares() {
346-
let given_shares = [
347-
*b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
348-
*b"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
349-
*b"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
350-
];
351-
let threshold = given_shares.len() as u8;
352-
let SecretSharing {
353-
secret,
354-
indices,
355-
shares,
356-
} = split_with_given_shares(&given_shares, 5).unwrap();
357-
358-
assert_eq!(threshold, given_shares.len() as u8);
359-
assert_eq!(shares[0], given_shares[0]);
360-
assert_eq!(shares[1], given_shares[1]);
361-
362-
assert_eq!(
363-
secret,
364-
combine(&(1..4).map(|i| (indices[i], shares[i])).collect_vec()).unwrap()
365-
);
366-
}
367258
}

crates/key-server/src/master_keys.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ impl MasterKeys {
230230
.ok_or(InternalError::InvalidServiceId),
231231
}
232232
}
233+
233234
/// Load committee version to determine which master share to use.
234235
pub(crate) fn get_committee_server_master_share(
235236
&self,

crates/key-server/src/metrics.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,11 +171,11 @@ pub(crate) fn call_with_duration<T>(metrics: Option<&Histogram>, closure: impl F
171171
pub(crate) fn status_callback(metrics: &IntCounterVec) -> impl Fn(bool) + use<> {
172172
let metrics = metrics.clone();
173173
move |status: bool| {
174-
let value = match status {
174+
let label = match status {
175175
true => "success",
176176
false => "failure",
177177
};
178-
metrics.with_label_values(&[value]).inc();
178+
metrics.with_label_values(&[label]).inc();
179179
}
180180
}
181181

crates/key-server/src/metrics_push.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,10 @@ pub async fn push_metrics(
108108

109109
if !response.status().is_success() {
110110
let status = response.status();
111-
let body = match response.text().await {
112-
Ok(body) => body,
113-
Err(error) => format!("couldn't decode response body; {error}"),
114-
};
111+
let body = response
112+
.text()
113+
.await
114+
.unwrap_or_else(|error| format!("couldn't decode response body; {error}"));
115115
return Err(anyhow::anyhow!(
116116
"metrics push failed: [{}]:{}",
117117
status,

crates/key-server/src/server.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,7 @@ impl Server {
554554
fn create_response(
555555
&self,
556556
first_pkg_id: ObjectID,
557-
ids: &[KeyId],
557+
ids: Vec<KeyId>,
558558
enc_key: &ElGamalPublicKey,
559559
) -> FetchKeyResponse {
560560
debug!(
@@ -566,16 +566,13 @@ impl Server {
566566
.get_key_for_package(&first_pkg_id)
567567
.expect("checked already");
568568
let decryption_keys = ids
569-
.iter()
569+
.into_iter()
570570
.map(|id| {
571571
// Requested key
572-
let key = ibe::extract(master_key, id);
572+
let key = ibe::extract(master_key, &id);
573573
// ElGamal encryption of key under the user's public key
574574
let encrypted_key = encrypt(&mut thread_rng(), &key, enc_key);
575-
DecryptionKey {
576-
id: id.to_owned(),
577-
encrypted_key,
578-
}
575+
DecryptionKey { id, encrypted_key }
579576
})
580577
.collect();
581578
FetchKeyResponse { decryption_keys }
@@ -797,7 +794,7 @@ async fn handle_fetch_key(
797794
Json(
798795
app_state
799796
.server
800-
.create_response(first_pkg_id, &full_ids, &payload.enc_key),
797+
.create_response(first_pkg_id, full_ids, &payload.enc_key),
801798
)
802799
})
803800
}

crates/key-server/src/tests/externals.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ pub(crate) async fn get_key(
8080
.map(|(pkg_id, ids)| {
8181
elgamal::decrypt(
8282
&sk,
83-
&server.create_response(pkg_id, &ids, &pk).decryption_keys[0].encrypted_key,
83+
&server.create_response(pkg_id, ids, &pk).decryption_keys[0].encrypted_key,
8484
)
8585
})
8686
}

crates/key-server/src/utils.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,11 @@ macro_rules! git_version {
2929
use crate::types::IbeMasterKey;
3030
use anyhow::anyhow;
3131
use crypto::ibe::MASTER_KEY_LENGTH;
32-
use fastcrypto::encoding::Encoding;
32+
use fastcrypto::encoding::{Encoding, Hex};
3333
use fastcrypto::serde_helpers::ToFromByteArray;
3434
pub use git_version;
3535
use std::env;
36-
use sui_types::base_types::ObjectID;
36+
use sui_types::base_types::{ObjectID, SUI_ADDRESS_LENGTH};
3737

3838
/// Read a byte array from an environment variable and decode it using the specified encoding.
3939
pub fn decode_byte_array<E: Encoding, const N: usize>(env_name: &str) -> anyhow::Result<[u8; N]> {
@@ -57,8 +57,5 @@ pub fn decode_master_key<E: Encoding>(env_name: &str) -> anyhow::Result<IbeMaste
5757

5858
/// Read an ObjectID from an environment variable.
5959
pub fn decode_object_id(env_name: &str) -> anyhow::Result<ObjectID> {
60-
let hex_string =
61-
env::var(env_name).map_err(|_| anyhow!("Environment variable {} must be set", env_name))?;
62-
ObjectID::from_hex_literal(&hex_string)
63-
.map_err(|_| anyhow!("Invalid ObjectID for environment variable {env_name}"))
60+
decode_byte_array::<Hex, SUI_ADDRESS_LENGTH>(env_name).map(ObjectID::new)
6461
}

0 commit comments

Comments
 (0)