Add new and update_value to ProcessState
This commit is contained in:
parent
de93b1e568
commit
0d8aaefd12
@ -26,6 +26,52 @@ pub struct ProcessState {
|
||||
}
|
||||
|
||||
impl ProcessState {
|
||||
pub fn new(commited_in: OutPoint, clear_state: Map<String, Value>) -> anyhow::Result<Self> {
|
||||
let mut keys = Map::new();
|
||||
let mut encrypted = Map::new();
|
||||
|
||||
let clear_pcd = Value::Object(clear_state);
|
||||
let commitments = clear_pcd.hash_all_fields(commited_in)?;
|
||||
|
||||
let keys_to_encrypt: Vec<String> = commitments.keys().map(|k| k.clone()).collect();
|
||||
clear_pcd.encrypt_fields(&keys_to_encrypt, &mut keys, &mut encrypted)?;
|
||||
|
||||
let res = Self {
|
||||
commited_in,
|
||||
pcd_commitment: Value::Object(commitments),
|
||||
encrypted_pcd: Value::Object(encrypted),
|
||||
keys,
|
||||
validation_tokens: vec![],
|
||||
};
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn update_value(&mut self, key: &str, new_value: Value) -> anyhow::Result<()> {
|
||||
// First decrypt values
|
||||
let mut clear_pcd = self.decrypt_pcd()?;
|
||||
if let Some(value) = clear_pcd.get_mut(key) {
|
||||
// We can only update a value we can decrypt
|
||||
if let None = self.keys.get(key) {
|
||||
return Err(anyhow::Error::msg("Trying to update a value we can't access"));
|
||||
}
|
||||
// We replace the clear value by the new_value
|
||||
*value = new_value;
|
||||
} else {
|
||||
return Err(anyhow::Error::msg(format!("{} doesn't exist", key)))
|
||||
}
|
||||
|
||||
// Update the commitment
|
||||
self.pcd_commitment = Value::Object(clear_pcd.hash_all_fields(self.commited_in)?);
|
||||
|
||||
// Todo for now we rehash everything, which is a bit wasteful but fine for a proto
|
||||
|
||||
// Update the encrypted value
|
||||
clear_pcd.encrypt_fields(&[key.to_string()], &mut self.keys, self.encrypted_pcd.as_object_mut().unwrap())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn decrypt_pcd(&self) -> anyhow::Result<Value> {
|
||||
let mut fields2plain = Map::new();
|
||||
let fields2commit = self.pcd_commitment.to_value_object()?;
|
||||
|
Loading…
x
Reference in New Issue
Block a user