Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/pset/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ pub enum PsetBlindError {
InputSecretsOutOfBounds(usize),
/// Input secrets do not open the commitments of the input's witness utxo
InputSecretsMismatch(usize),
/// Blinding mode given for an output which this blinder does not blind
UnusedBlindingMode(usize),
/// Atleast one output should have its value blinded
NoValueBlindedOutput,
}

impl fmt::Display for PsetBlindError {
Expand Down Expand Up @@ -270,6 +274,12 @@ impl fmt::Display for PsetBlindError {
PsetBlindError::InputSecretsMismatch(i) => {
write!(f, "Secrets for input index {} do not open its witness utxo", i)
}
PsetBlindError::UnusedBlindingMode(i) => {
write!(f, "Blinding mode given for output index {}, which this blinder does not blind", i)
}
PsetBlindError::NoValueBlindedOutput => {
write!(f, "Atleast one output should have its value blinded")
}
}
}
}
Expand Down
288 changes: 288 additions & 0 deletions src/pset/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,173 @@ impl PartiallySignedTransaction {
}
Ok(ret)
}

/// Blind the pset as the last blinder role, as [`Self::blind_last`] does,
/// but blind only the parts of each output that its [`BlindingMode`] selects.
///
/// An output without a mode has both its asset and its value blinded.
/// At least one output must have its value blinded, to balance the blinding factors.
/// The `blinding_key` of an output that is not fully blinded is removed,
/// as a pset cannot hold a partially blinded output that is marked for blinding.
/// On error, the pset is left unchanged.
///
/// # Parameters
///
/// * `inp_txout_sec`: [`TxOutSecrets`] corresponding to owned inputs
/// * `modes`: [`BlindingMode`] of the outputs to blind, by output index
///
/// # Returns
///
/// The [`TxOutSecrets`] of each blinded output by output index,
/// and the ephemeral secret key if its value was blinded
pub fn blind_last_with_modes<C: secp256k1_zkp::Signing, R: RngCore + CryptoRng>(
&mut self,
rng: &mut R,
secp: &secp256k1_zkp::Secp256k1<C>,
inp_txout_sec: &HashMap<usize, TxOutSecrets>,
modes: &BTreeMap<usize, BlindingMode>,
) -> Result<BTreeMap<usize, (TxOutSecrets, Option<SecretKey>)>, PsetBlindError> {
let (inp_secrets, mut outs_to_blind) = self.blind_checks(secp, inp_txout_sec)?;

if let Some(&i) = modes.keys().find(|i| !outs_to_blind.contains(i)) {
return Err(PsetBlindError::UnusedBlindingMode(i));
}
if outs_to_blind.is_empty() {
// Atleast one output must be marked for blinding for pset blind_last
return Err(PsetBlindError::AtleastOneOutputBlind);
}

let mode_of = |i: usize| modes.get(&i).copied().unwrap_or_default();
// The last output with a blinded value balances the blinding factors, so blind it after the others
let last_out_index = outs_to_blind
.iter()
.copied()
.rfind(|&i| mode_of(i).blind_value)
.ok_or(PsetBlindError::NoValueBlindedOutput)?;
outs_to_blind.retain(|&i| i != last_out_index);
outs_to_blind.push(last_out_index);

let surject_inputs = self.surjection_inputs(inp_txout_sec)?;
// Blind a copy of the outputs, so that the pset is left unchanged on error
let mut outputs = self.outputs.clone();
let mut out_secrets = vec![];
let mut ret = BTreeMap::new();
for i in outs_to_blind {
let mode = mode_of(i);
let out = &mut outputs[i];
let asset_id = out.asset.ok_or(PsetBlindError::MustHaveExplicitTxOut(i))?;
let value = out.amount.ok_or(PsetBlindError::MustHaveExplicitTxOut(i))?;
let receiver_blinding_pk = out
.blinding_key
.ok_or(PsetBlindError::MustHaveExplicitTxOut(i))?;
if mode != BlindingMode::FULL {
out.blinding_key = None;
}

let out_abf = if mode.blind_asset {
AssetBlindingFactor::new(rng)
} else {
AssetBlindingFactor::zero()
};
let out_vbf = if i == last_out_index {
let mut final_vbf =
ValueBlindingFactor::last(secp, value, out_abf, &inp_secrets, &out_secrets);
// Add all the scalars
for value_diff in &self.global.scalars {
final_vbf += ValueBlindingFactor(*value_diff);
}
final_vbf
} else if mode.blind_value {
ValueBlindingFactor::new(rng)
} else {
ValueBlindingFactor::zero()
};
out_secrets.push((value, out_abf, out_vbf));

if mode.blind_asset {
let exp_asset = confidential::Asset::Explicit(asset_id);
let blind_res = exp_asset.blind(rng, secp, out_abf, &surject_inputs);
let (out_asset_commitment, surjection_proof) =
blind_res.map_err(|e| PsetBlindError::ConfidentialTxOutError(i, e))?;

out.asset_comm = out_asset_commitment.commitment();
out.asset_surjection_proof = Some(surjection_proof);
out.blind_asset_proof = Some(
SurjectionProof::blind_asset_proof(rng, secp, asset_id, out_abf)
.map_err(|e| PsetBlindError::BlindingProofsCreationError(i, e))?,
);
}

let mut ephemeral_sk = None;
if mode.blind_value {
let sk = SecretKey::new(rng);
let msg = RangeProofMessage::new(asset_id, out_abf);
let exp_value = confidential::Value::Explicit(value);
let blind_res = exp_value.blind(
secp,
out_vbf,
receiver_blinding_pk.inner,
sk,
&out.script_pubkey,
&msg,
);
let (value_commitment, nonce, rangeproof) =
blind_res.map_err(|e| PsetBlindError::ConfidentialTxOutError(i, e))?;
let asset_gen = msg.commitment(secp);
let value_comm = value_commitment
.commitment()
.expect("Blinding proof successful");

out.value_rangeproof = Some(rangeproof);
out.amount_comm = Some(value_comm);
out.ecdh_pubkey = nonce.commitment().map(|pk| bitcoin::PublicKey {
inner: pk,
compressed: true,
});
out.blind_value_proof = Some(
RangeProof::blind_value_proof(rng, secp, value, value_comm, asset_gen, out_vbf)
.map_err(|e| PsetBlindError::BlindingProofsCreationError(i, e))?,
);
ephemeral_sk = Some(sk);
}

if mode != BlindingMode::EXPLICIT {
let secrets = TxOutSecrets::new(asset_id, out_abf, value, out_vbf);
ret.insert(i, (secrets, ephemeral_sk));
}
}

// mutate the pset
self.outputs = outputs;
self.global.scalars.clear();
Ok(ret)
}
}

/// The parts of an output that [`PartiallySignedTransaction::blind_last_with_modes`] blinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BlindingMode {
/// Blind the asset
pub blind_asset: bool,
/// Blind the value
pub blind_value: bool,
}

impl BlindingMode {
/// Blind both the asset and the value
pub const FULL: Self = Self { blind_asset: true, blind_value: true };
/// Blind only the asset
pub const ASSET_ONLY: Self = Self { blind_asset: true, blind_value: false };
/// Blind only the value
pub const VALUE_ONLY: Self = Self { blind_asset: false, blind_value: true };
/// Blind neither the asset nor the value
pub const EXPLICIT: Self = Self { blind_asset: false, blind_value: false };
}

impl Default for BlindingMode {
fn default() -> Self {
Self::FULL
}
}

impl Encodable for PartiallySignedTransaction {
Expand Down Expand Up @@ -1148,4 +1315,125 @@ mod tests {
let err = pset.blind_checks(&secp, &HashMap::from([(1, secrets)])).unwrap_err();
assert_eq!(err, PsetBlindError::InputSecretsOutOfBounds(1));
}

#[test]
fn blind_last_with_modes() {
use rand::{self, SeedableRng};

let secp = secp256k1_zkp::Secp256k1::new();
let mut rng = rand::rngs::StdRng::seed_from_u64(0);

let asset = crate::AssetId::from_byte_array([1; 32]);
let blinding_sk = SecretKey::from_slice(&[7; 32]).unwrap();
let pk = bitcoin::PublicKey::new(blinding_sk.public_key(&secp));
let script =
crate::Script::from_hex_no_prefix("0014d2bcde17e7744f6377466ca1bd35d212954674c8").unwrap();

// Two confidential inputs, each owned by its own blinder
let mut pset = PartiallySignedTransaction::new_v2();
let mut utxos = vec![];
let mut secrets = vec![];
for value in [10_000, 5_000] {
let abf = AssetBlindingFactor::new(&mut rng);
let vbf = ValueBlindingFactor::new(&mut rng);
let utxo = TxOut {
asset: confidential::Asset::new_confidential(&secp, asset, abf),
value: confidential::Value::new_confidential_from_assetid(&secp, value, asset, vbf, abf),
..TxOut::default()
};
let mut input = Input::from_prevout(OutPoint::default());
input.witness_utxo = Some(utxo.clone());
pset.add_input(input);
utxos.push(utxo);
secrets.push(TxOutSecrets::new(asset, abf, value, vbf));
}
// Output 0 is blinded by the owner of input 1, outputs 1 to 4 by the owner of input 0
for (amount, blinder_index) in [(5_000, 1), (1_000, 0), (3_000, 0), (3_000, 0), (2_500, 0)] {
let mut output = Output::new_explicit(script.clone(), amount, asset, Some(pk));
output.blinder_index = Some(blinder_index);
pset.add_output(output);
}
// Add fee
pset.add_output(Output::new_explicit(crate::Script::new(), 500, asset, None));
pset.blind_non_last(&mut rng, &secp, &HashMap::from([(1, secrets[1])])).unwrap();
let inp_txout_sec = HashMap::from([(0, secrets[0])]);

// A mode cannot be given for an output that this blinder does not blind
let modes = BTreeMap::from([(0, BlindingMode::VALUE_ONLY)]);
let err = pset.blind_last_with_modes(&mut rng, &secp, &inp_txout_sec, &modes).unwrap_err();
assert_eq!(err, PsetBlindError::UnusedBlindingMode(0));

// Without a blinded value nothing balances the blinding factors
let modes = BTreeMap::from([
(1, BlindingMode::ASSET_ONLY),
(2, BlindingMode::EXPLICIT),
(3, BlindingMode::ASSET_ONLY),
(4, BlindingMode::EXPLICIT),
]);
let err = pset.blind_last_with_modes(&mut rng, &secp, &inp_txout_sec, &modes).unwrap_err();
assert_eq!(err, PsetBlindError::NoValueBlindedOutput);

// Output 2 has no mode, so it is fully blinded
let modes = BTreeMap::from([
(1, BlindingMode::VALUE_ONLY),
(3, BlindingMode::ASSET_ONLY),
(4, BlindingMode::EXPLICIT),
]);

// A zero value cannot be blinded, and output 2 is blinded after the others.
// The pset is left unchanged
let mut zero = pset.clone();
zero.outputs_mut()[2].amount = Some(0);
let unchanged = zero.clone();
let err = zero.blind_last_with_modes(&mut rng, &secp, &inp_txout_sec, &modes).unwrap_err();
assert!(matches!(err, PsetBlindError::ConfidentialTxOutError(2, _)));
assert_eq!(zero, unchanged);

let blinds = pset.blind_last_with_modes(&mut rng, &secp, &inp_txout_sec, &modes).unwrap();
assert_eq!(blinds.keys().copied().collect::<Vec<_>>(), [1, 2, 3]);
assert!(pset.global.scalars.is_empty());

let tx = pset.extract_tx().unwrap();
tx.verify_tx_amt_proofs(&secp, &utxos).unwrap();
let pset_bytes = encode::serialize(&pset);
let pset_des = encode::deserialize(&pset_bytes).unwrap();
assert_eq!(pset, pset_des);

let expected_modes = [
(1, BlindingMode::VALUE_ONLY),
(2, BlindingMode::FULL),
(3, BlindingMode::ASSET_ONLY),
(4, BlindingMode::EXPLICIT),
];
for (i, mode) in expected_modes {
let out = &pset.outputs()[i];
assert_eq!(out.asset_comm.is_some(), mode.blind_asset);
assert_eq!(out.asset_surjection_proof.is_some(), mode.blind_asset);
assert_eq!(out.blind_asset_proof.is_some(), mode.blind_asset);
assert_eq!(out.amount_comm.is_some(), mode.blind_value);
assert_eq!(out.value_rangeproof.is_some(), mode.blind_value);
assert_eq!(out.ecdh_pubkey.is_some(), mode.blind_value);
assert_eq!(out.blind_value_proof.is_some(), mode.blind_value);
// Only a fully blinded output keeps its blinding key
assert_eq!(out.blinding_key.is_some(), mode == BlindingMode::FULL);

if let Some((out_secrets, ephemeral_sk)) = blinds.get(&i) {
assert!(out_secrets.opens(&secp, &tx.output[i]));
let ephemeral_pk = ephemeral_sk.map(|sk| bitcoin::PublicKey::new(sk.public_key(&secp)));
assert_eq!(ephemeral_pk, out.ecdh_pubkey);
}

// The blind proofs are for the explicit asset and amount
let asset_gen = tx.output[i].asset.into_asset_gen(&secp).unwrap();
if let Some(proof) = &out.blind_asset_proof {
assert!(proof.blind_asset_proof_verify(&secp, asset, asset_gen));
}
if let Some(proof) = &out.blind_value_proof {
assert!(proof.blind_value_proof_verify(&secp, out.amount.unwrap(), asset_gen, out.amount_comm.unwrap()));
}
}

// The receiver can unblind the fully blinded output
assert_eq!(tx.output[2].unblind(&secp, blinding_sk).unwrap(), blinds[&2].0);
}
}
Loading