Refactor commit
This commit is contained in:
parent
ce2c158de2
commit
8eae4408f2
235
src/commit.rs
235
src/commit.rs
@ -1,17 +1,14 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::{Error, Result};
|
||||
|
||||
use hex::FromHex;
|
||||
use log::debug;
|
||||
use sdk_common::pcd::AnkPcdHash;
|
||||
use sdk_common::pcd::Pcd;
|
||||
use sdk_common::silentpayments::create_transaction;
|
||||
use sdk_common::sp_client::spclient::Recipient;
|
||||
use sdk_common::{error::AnkError, network::CommitMessage};
|
||||
use sdk_common::sp_client::bitcoin::consensus::deserialize;
|
||||
use sdk_common::sp_client::bitcoin::{Amount, Transaction, Txid, OutPoint};
|
||||
use sdk_common::process::{Process, ProcessState, CACHEDPROCESSES};
|
||||
use serde_json::Value;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::{lock_freezed_utxos, MutexExt, DAEMON, WALLET};
|
||||
|
||||
@ -19,19 +16,14 @@ pub(crate) fn handle_commit_request(commit_msg: CommitMessage) -> Result<OutPoin
|
||||
// Attempt to deserialize `init_tx` as a `Transaction`
|
||||
if let Ok(tx) = deserialize::<Transaction>(&Vec::from_hex(&commit_msg.init_tx)?) {
|
||||
// This is the first transaction of a chain of commitments
|
||||
|
||||
// Ensure the transaction has only one output
|
||||
if tx.output.len() != 1 {
|
||||
return Err(AnkError::NewTxError(
|
||||
"Transaction must have only one output".to_string(),
|
||||
))?;
|
||||
}
|
||||
// Create the root commitment outpoint
|
||||
let root_commitment = OutPoint::new(tx.txid(), 0);
|
||||
|
||||
// TODO: Check that the output pays us
|
||||
|
||||
// Validation tokens must be empty for the initial transaction
|
||||
if !commit_msg.validation_tokens.is_empty() {
|
||||
return Err(AnkError::NewTxError(
|
||||
return Err(AnkError::GenericError(
|
||||
"Validation tokens must be empty".to_string(),
|
||||
))?;
|
||||
}
|
||||
@ -40,16 +32,30 @@ pub(crate) fn handle_commit_request(commit_msg: CommitMessage) -> Result<OutPoin
|
||||
let daemon = DAEMON.get().unwrap().lock_anyhow()?;
|
||||
daemon.broadcast(&tx)?;
|
||||
|
||||
// Create the root commitment outpoint
|
||||
let root_commitment = OutPoint::new(tx.txid(), 0);
|
||||
let roles = Value::Object(commit_msg.roles.iter().map(|(name, def)| (name.to_owned(), Value::String(serde_json::to_string(def).unwrap()))).collect());
|
||||
|
||||
// put roles in a map
|
||||
let roles_only_map = json!({
|
||||
"roles": roles
|
||||
});
|
||||
|
||||
// We check that for testing but it's useless
|
||||
assert!(commit_msg.roles == roles.extract_roles()?);
|
||||
|
||||
let roles_commitment = roles_only_map.hash_fields(root_commitment)?;
|
||||
|
||||
assert!(roles_commitment.get("roles") == commit_msg.pcd_commitment.get("roles"));
|
||||
|
||||
// We always keep an empty state as the last state
|
||||
let empty_state = ProcessState {
|
||||
commited_in: root_commitment,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Initialize the process state
|
||||
let init_state = ProcessState {
|
||||
commited_in: root_commitment,
|
||||
encrypted_pcd: Value::Object(commit_msg.encrypted_pcd),
|
||||
keys: commit_msg.keys,
|
||||
validation_tokens: vec![],
|
||||
};
|
||||
let mut init_state = empty_state.clone();
|
||||
init_state.encrypted_pcd = roles_only_map;
|
||||
init_state.pcd_commitment = commit_msg.pcd_commitment;
|
||||
|
||||
// Access the cached processes and insert the new commitment
|
||||
let mut commitments = CACHEDPROCESSES
|
||||
@ -59,15 +65,14 @@ pub(crate) fn handle_commit_request(commit_msg: CommitMessage) -> Result<OutPoin
|
||||
// We are confident that `root_commitment` doesn't exist in the map
|
||||
commitments.insert(
|
||||
root_commitment,
|
||||
Process::new(vec![init_state], HashMap::new(), vec![]),
|
||||
Process::new(vec![init_state, empty_state], vec![]),
|
||||
);
|
||||
|
||||
// Add the outpoint to the list of frozen UTXOs
|
||||
let new_root_outpoint = OutPoint::new(tx.txid(), 0);
|
||||
lock_freezed_utxos()?.insert(new_root_outpoint);
|
||||
lock_freezed_utxos()?.insert(root_commitment);
|
||||
|
||||
// Wait for validation tokens to spend the new output and commit the hash
|
||||
Ok(new_root_outpoint)
|
||||
Ok(root_commitment)
|
||||
}
|
||||
// Attempt to deserialize `init_tx` as an `OutPoint`
|
||||
else if let Ok(outpoint) = deserialize::<OutPoint>(&Vec::from_hex(&commit_msg.init_tx)?) {
|
||||
@ -80,121 +85,117 @@ pub(crate) fn handle_commit_request(commit_msg: CommitMessage) -> Result<OutPoin
|
||||
.get_mut(&outpoint)
|
||||
.ok_or(Error::msg("Commitment not found"))?;
|
||||
|
||||
let pcd_hash = AnkPcdHash::from_map(&commit_msg.encrypted_pcd);
|
||||
|
||||
if commit_msg.validation_tokens.is_empty() {
|
||||
// Register a new state if validation tokens are empty
|
||||
|
||||
// Get all the latest concurrent states
|
||||
let concurrent_states = commitment.get_latest_concurrent_states();
|
||||
let concurrent_states = commitment.get_latest_concurrent_states()?;
|
||||
|
||||
let current_outpoint = concurrent_states.first().unwrap().commited_in;
|
||||
let (empty_state, actual_states) = concurrent_states.split_last().unwrap(); // We necessary have 1 state
|
||||
let current_outpoint = empty_state.commited_in;
|
||||
|
||||
// Check for existing states with the same PCD hash
|
||||
if concurrent_states
|
||||
if actual_states
|
||||
.into_iter()
|
||||
.any(|state| AnkPcdHash::from_value(&state.encrypted_pcd) == pcd_hash)
|
||||
.any(|state| state.pcd_commitment == commit_msg.pcd_commitment)
|
||||
{
|
||||
return Err(anyhow::Error::msg("Proposed state already exists"));
|
||||
}
|
||||
|
||||
// Insert the new process state
|
||||
commitment.insert_state(ProcessState {
|
||||
commited_in: current_outpoint,
|
||||
encrypted_pcd: Value::Object(commit_msg.encrypted_pcd),
|
||||
keys: commit_msg.keys,
|
||||
validation_tokens: vec![],
|
||||
let roles = Value::Object(commit_msg.roles.iter().map(|(name, def)| (name.to_owned(), Value::String(serde_json::to_string(def).unwrap()))).collect());
|
||||
|
||||
let roles_only_map = json!({
|
||||
"roles": roles
|
||||
});
|
||||
|
||||
let new_state = ProcessState {
|
||||
commited_in: current_outpoint,
|
||||
pcd_commitment: commit_msg.pcd_commitment,
|
||||
encrypted_pcd: roles_only_map,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Insert the new process state
|
||||
commitment.insert_concurrent_state(new_state)?;
|
||||
|
||||
Ok(current_outpoint)
|
||||
} else {
|
||||
// Validation tokens are provided; process the pending state
|
||||
|
||||
let new_state_commitment = AnkPcdHash::from_map(&commit_msg.encrypted_pcd);
|
||||
|
||||
// Clone the previous state, we'll need it for validation purpose
|
||||
if let Some(mut state_to_validate) = commitment.get_latest_concurrent_states()
|
||||
// Clone the state, we'll need it for validation purpose
|
||||
let mut state_to_validate = commitment.get_latest_concurrent_states()?
|
||||
.into_iter()
|
||||
.find(|s| {
|
||||
AnkPcdHash::from_value(&s.encrypted_pcd) == new_state_commitment
|
||||
.find(|state| {
|
||||
state.pcd_commitment == commit_msg.pcd_commitment
|
||||
})
|
||||
.cloned()
|
||||
{
|
||||
// We update the validation tokens for our clone
|
||||
state_to_validate.validation_tokens = commit_msg.validation_tokens;
|
||||
let previous_state = commitment.get_previous_state(&state_to_validate);
|
||||
if state_to_validate.is_valid(previous_state).is_ok() {
|
||||
// If the new state is valid we commit it in a new transaction that spends the last commited_in
|
||||
// By spending it we also know the next outpoint to monitor for the next state
|
||||
// We add a placeholder state with that information at the tip of the chain
|
||||
// We also remove all concurrent states that didn't get validated
|
||||
let mut freezed_utxos = lock_freezed_utxos()?;
|
||||
let mandatory_input = if freezed_utxos.remove(&state_to_validate.commited_in) {
|
||||
state_to_validate.commited_in
|
||||
} else {
|
||||
// This shoudln't happen, except if we send the commitment message to another relay
|
||||
// We need to think about the case a relay is down
|
||||
// Probably relays should have backups of their keys so that it can be bootstrapped again and resume commiting
|
||||
return Err(Error::msg("Commitment utxo doesn't exist"))
|
||||
};
|
||||
.ok_or(anyhow::Error::msg("Unknown state"))?
|
||||
.clone();
|
||||
|
||||
// TODO we should make this sequence more atomic by handling errors in a way that we get back to the current state if any step fails
|
||||
// We update the validation tokens for our clone
|
||||
state_to_validate.validation_tokens = commit_msg.validation_tokens;
|
||||
// We test the validity of the state with the provided proofs
|
||||
state_to_validate.is_valid(commitment.get_latest_commited_state())?;
|
||||
|
||||
let sp_wallet = WALLET.get().ok_or(Error::msg("Wallet not initialized"))?.get_wallet()?;
|
||||
|
||||
let recipient = Recipient {
|
||||
address: sp_wallet.get_client().get_receiving_address(),
|
||||
amount: Amount::from_sat(1000),
|
||||
nb_outputs: 1
|
||||
};
|
||||
|
||||
let daemon = DAEMON.get().unwrap().lock_anyhow()?;
|
||||
let fee_rate = daemon.estimate_fee(6)?;
|
||||
|
||||
let psbt = create_transaction(
|
||||
vec![mandatory_input],
|
||||
&freezed_utxos,
|
||||
&sp_wallet,
|
||||
vec![recipient],
|
||||
None,
|
||||
fee_rate,
|
||||
None
|
||||
)?;
|
||||
|
||||
let new_tx = psbt.extract_tx()?;
|
||||
|
||||
daemon.test_mempool_accept(&new_tx)?;
|
||||
|
||||
// We're ready to commit, we first update our process states
|
||||
// We remove all concurrent states
|
||||
let rm_states = commitment.remove_latest_concurrent_states();
|
||||
debug!("removed states: {:?}", rm_states);
|
||||
// We push the validated state back
|
||||
commitment.insert_state(state_to_validate);
|
||||
|
||||
// We broadcast transaction
|
||||
let txid = daemon.broadcast(&new_tx)?;
|
||||
|
||||
// We push a new, empty state commited in the newly created output
|
||||
let commited_in = OutPoint::new(txid, 0);
|
||||
|
||||
// Add the newly created outpoint to our list of freezed utxos
|
||||
freezed_utxos.insert(commited_in);
|
||||
|
||||
let empty_state = ProcessState {
|
||||
commited_in,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
commitment.insert_state(empty_state);
|
||||
|
||||
Ok(commited_in)
|
||||
} else {
|
||||
return Err(Error::msg("Invalid state"));
|
||||
}
|
||||
// If the new state is valid we commit it in a new transaction that spends the last commited_in
|
||||
// By spending it we also know the next outpoint to monitor for the next state
|
||||
// We add a placeholder state with that information at the tip of the chain
|
||||
// We also remove all concurrent states that didn't get validated
|
||||
let mut freezed_utxos = lock_freezed_utxos()?;
|
||||
let mandatory_input = if freezed_utxos.remove(&state_to_validate.commited_in) {
|
||||
state_to_validate.commited_in
|
||||
} else {
|
||||
return Err(Error::msg("Unknown proposal, must create it first before sending validations"));
|
||||
}
|
||||
// This shoudln't happen, except if we send the commitment message to another relay
|
||||
// We need to think about the case a relay is down
|
||||
// Probably relays should have backups of their keys so that it can be bootstrapped again and resume commiting
|
||||
return Err(Error::msg("Commitment utxo doesn't exist"))
|
||||
};
|
||||
|
||||
// TODO we should make this sequence more atomic by handling errors in a way that we get back to the current state if any step fails
|
||||
|
||||
let sp_wallet = WALLET.get().ok_or(Error::msg("Wallet not initialized"))?.get_wallet()?;
|
||||
|
||||
let recipient = Recipient {
|
||||
address: sp_wallet.get_client().get_receiving_address(),
|
||||
amount: Amount::from_sat(1000),
|
||||
nb_outputs: 1
|
||||
};
|
||||
|
||||
let daemon = DAEMON.get().unwrap().lock_anyhow()?;
|
||||
let fee_rate = daemon.estimate_fee(6)?;
|
||||
|
||||
let psbt = create_transaction(
|
||||
vec![mandatory_input],
|
||||
&freezed_utxos,
|
||||
&sp_wallet,
|
||||
vec![recipient],
|
||||
None,
|
||||
fee_rate,
|
||||
None
|
||||
)?;
|
||||
|
||||
let new_tx = psbt.extract_tx()?;
|
||||
|
||||
daemon.test_mempool_accept(&new_tx)?;
|
||||
|
||||
// We're ready to commit, we first update our process states
|
||||
// We remove all concurrent states
|
||||
let _ = commitment.remove_all_concurrent_states()?;
|
||||
// debug!("removed states: {:?}", rm_states);
|
||||
// We push the validated state back
|
||||
commitment.insert_concurrent_state(state_to_validate.clone())?;
|
||||
|
||||
// We broadcast transaction
|
||||
let txid = daemon.broadcast(&new_tx)?;
|
||||
|
||||
// We push a new, empty state commited in the newly created output
|
||||
let commited_in = OutPoint::new(txid, 0);
|
||||
|
||||
// Add the newly created outpoint to our list of freezed utxos
|
||||
freezed_utxos.insert(commited_in);
|
||||
|
||||
commitment.update_states_tip(commited_in)?;
|
||||
|
||||
Ok(commited_in)
|
||||
}
|
||||
} else {
|
||||
Err(Error::msg("init_tx must be a valid transaction or txid"))
|
||||
|
Loading…
x
Reference in New Issue
Block a user