Skip to content
Merged
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
94 changes: 87 additions & 7 deletions base_layer/transaction_components/src/multisig/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,46 @@
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use tari_common_types::types::{CompressedPublicKey, PrivateKey, UncompressedPublicKey};
use tari_crypto::keys::{PublicKey, SecretKey};
use tari_script::{Opcode, TariScript};
use tari_script::{MAX_MULTISIG_LIMIT, Opcode, TariScript};

use crate::{
key_manager::{TariKeyId, TransactionKeyManagerInterface},
transaction_components::{TransactionError, one_sided::diffie_hellman_stealth_domain_hasher},
};

/// Validates that a multisig spend supplies exactly the script's threshold `m` signatures and returns `m`.
///
/// Every supplied signature is pushed onto the input stack and `CheckMultiSigVerify` consumes exactly `m` of them,
/// so any excess is left on the stack and consensus rejects the spend.
pub fn validate_multisig_spend_signature_count(
script: &TariScript,
signature_count: usize,
) -> Result<u8, TransactionError> {
let (_keys, threshold) = get_multi_sig_script_components(script)
.ok_or_else(|| TransactionError::BuilderError("no keys found".to_string()))?;
if signature_count != usize::from(threshold) {
return Err(TransactionError::BuilderError(format!(
"Invalid signature count for multisig spend: expected exactly {}, got {}",
threshold, signature_count
)));
}
Ok(threshold)
}

pub fn is_multisig_utxo(tari_script: &TariScript) -> bool {
tari_script
.as_slice()
.iter()
.any(|op| matches!(op, Opcode::CheckMultiSigVerify(..)))
get_multi_sig_script_components(tari_script).is_some()
}

/// The keys and threshold of a script's `CheckMultiSigVerify`, or `None` if the opcode is one consensus can never
/// execute (`m = 0`, `m > n`, `n` not matching the key list, or `n > MAX_MULTISIG_LIMIT`).
///
/// This is the spend-side rule, so it accepts everything consensus accepts. New deposits use the stricter
/// `validate_multisig_threshold`, which also caps the script size.
pub fn get_multi_sig_script_components(script: &TariScript) -> Option<(Vec<CompressedPublicKey>, u8)> {
for op in script.as_slice() {
if let Opcode::CheckMultiSigVerify(m, _n, keys, _msg) = op {
return Some((keys.clone(), *m));
if let Opcode::CheckMultiSigVerify(m, n, keys, _msg) = op {
let executable = *m >= 1 && m <= n && usize::from(*n) == keys.len() && *n <= MAX_MULTISIG_LIMIT;
return executable.then(|| (keys.clone(), *m));
}
}

Expand Down Expand Up @@ -108,6 +130,64 @@ mod test {
use super::*;
use crate::key_manager::KeyManager;

fn sample_keys(count: usize) -> Vec<CompressedPublicKey> {
(1..=count)
.map(|i| CompressedPublicKey::from_secret_key(&PrivateKey::from(i as u64)))
.collect()
}

fn multisig_script(m: u8, n: u8, keys: Vec<CompressedPublicKey>) -> TariScript {
TariScript::new(vec![Opcode::CheckMultiSigVerify(m, n, keys, Box::new([0u8; 32]))]).unwrap()
}

#[test]
fn spend_signature_count_must_equal_threshold() {
let script = multisig_script(2, 3, sample_keys(3));
assert_eq!(validate_multisig_spend_signature_count(&script, 2).unwrap(), 2);
for count in [1, 3] {
let err = validate_multisig_spend_signature_count(&script, count)
.unwrap_err()
.to_string();
assert!(err.contains(&format!("expected exactly 2, got {count}")), "{err}");
}
let not_multisig = TariScript::new(vec![Opcode::Nop]).unwrap();
let err = validate_multisig_spend_signature_count(&not_multisig, 1)
.unwrap_err()
.to_string();
assert!(err.contains("no keys found"), "{err}");
}

#[test]
fn get_multi_sig_script_components_rejects_unexecutable_opcodes() {
let keys = sample_keys(2);
let valid = multisig_script(2, 2, keys.clone());
assert!(is_multisig_utxo(&valid));
assert_eq!(get_multi_sig_script_components(&valid), Some((keys.clone(), 2)));

let limit = usize::from(MAX_MULTISIG_LIMIT);
for script in [
multisig_script(0, 2, keys.clone()),
multisig_script(3, 2, keys.clone()),
multisig_script(2, MAX_MULTISIG_LIMIT + 1, sample_keys(limit + 1)),
] {
assert!(!is_multisig_utxo(&script));
assert_eq!(get_multi_sig_script_components(&script), None);
}

// Consensus accepts repeated keys and up to 32 keys, so existing outputs of that shape stay spendable.
let repeated = keys.first().unwrap().clone();
let duplicate = multisig_script(2, 2, vec![repeated.clone(), repeated.clone()]);
assert_eq!(
get_multi_sig_script_components(&duplicate),
Some((vec![repeated.clone(), repeated], 2))
);
let at_limit = sample_keys(limit);
assert_eq!(
get_multi_sig_script_components(&multisig_script(2, MAX_MULTISIG_LIMIT, at_limit.clone())),
Some((at_limit, 2))
);
}

#[test]
fn co_signer_key_is_the_creator_ephemeral_key_and_verifies_the_signature() {
let creator = KeyManager::new_random().unwrap();
Expand Down
69 changes: 57 additions & 12 deletions base_layer/transaction_components/src/multisig/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use crate::{
consensus::ConsensusConstants,
fee::{Fee, addressed_output_memo, recipient_output_features_and_scripts_size},
key_manager::TransactionKeyManagerInterface,
multisig::script::get_multi_sig_script_components,
multisig::script::validate_multisig_spend_signature_count,
offline_signing::one_sided_signer::validate_multisig_threshold,
transaction_builder::{FinalizedTransaction, RecipientSpec},
transaction_components::{
Expand Down Expand Up @@ -137,17 +137,9 @@ where TKeyManagerInterface: TransactionKeyManagerInterface
output: WalletOutput,
consensus_constants: &ConsensusConstants,
) -> Result<(FinalizedTransaction, MemoField, MicroMinotari), TransactionBuilderError> {
// Enforce correct signature count and ordering for the multisig script
let (_ephemeral_pubkeys, threshold) = get_multi_sig_script_components(output.script())
.ok_or(TransactionError::BuilderError("no keys found".to_string()))?;
if signatures.len() < threshold as usize {
return Err(TransactionError::BuilderError(format!(
"Insufficient signatures: need at least {}, got {}",
threshold,
signatures.len()
))
.into());
}
// `CheckMultiSigVerify` consumes exactly `m` signatures; any extra would fail the spend with
// NonUnitLengthStack.
validate_multisig_spend_signature_count(output.script(), signatures.len())?;

let mut input_stack = ExecutionStack::default();
for sig in signatures {
Expand Down Expand Up @@ -352,4 +344,57 @@ mod test {
assert!(err.contains("invalid multisig threshold"), "{m} of {n}: {err}");
}
}

#[test]
fn spend_multisig_utxo_requires_exact_signature_count() {
let rules = create_consensus_manager();
let consensus_constants = rules.consensus_constants(0);
let key_manager = KeyManager::new_random().unwrap();
let recipient_key_manager = KeyManager::new_random().unwrap();
let recipient = TariAddress::new_dual_address(
recipient_key_manager.get_view_key().pub_key,
recipient_key_manager.get_spend_key().pub_key,
Network::LocalNet,
TariAddressFeatures::create_one_sided_only(),
None,
)
.unwrap();
let session = MultisigSession::new(key_manager.clone());

// Excess signatures (> threshold) must be rejected before building a transaction that would fail with
// NonUnitLengthStack
let amount = MicroMinotari(100_000);
let (commitment_mask, script_key) = key_manager.get_next_commitment_mask_and_script_key().unwrap();
let party_key = key_manager.get_random_key(None, None).unwrap();
let sender_offset = key_manager.get_random_key(None, None).unwrap();
let script = TariScript::new(vec![
Opcode::CheckMultiSigVerify(1, 1, vec![party_key.pub_key], Box::new([0u8; 32])),
Opcode::PushPubKey(Box::new(script_key.pub_key)),
])
.unwrap();
let input = WalletOutputBuilder::new(amount, commitment_mask.key_id)
.with_script(script)
.with_features(OutputFeatures::default())
.with_input_data(ExecutionStack::default())
.encrypt_data_for_recovery(&key_manager, None, MemoField::default())
.unwrap()
.with_script_key(script_key.key_id)
.with_sender_offset_public_key(sender_offset.pub_key)
.sign_metadata_signature(&key_manager, &sender_offset.key_id)
.unwrap()
.try_build(&key_manager)
.unwrap();

let excess_sigs = vec![
CompressedCheckSigSchnorrSignature::default(),
CompressedCheckSigSchnorrSignature::default(),
];
let spend_err = session
.spend_multisig_utxo(excess_sigs, recipient, input, consensus_constants)
.unwrap_err();
assert!(
spend_err.to_string().contains("expected exactly 1, got 2"),
"expected excess signatures to be rejected, got {spend_err:?}"
);
}
}
20 changes: 7 additions & 13 deletions base_layer/wallet/src/transaction_service/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ use tari_transaction_components::{
fee::{Fee, addressed_output_memo, recipient_output_features_and_scripts_size},
helpers::borsh::SerializedSize,
key_manager::{RecoveryProvenance, SecretTransactionKeyManagerInterface, SerializedKeyString, TariKeyId},
multisig::{script::get_multi_sig_script_components, session::MultisigSession, types::GetMultisigUtxoDataOutput},
multisig::{
script::validate_multisig_spend_signature_count,
session::MultisigSession,
types::GetMultisigUtxoDataOutput,
},
offline_signing::{
models::{PaymentRecipient, SignedOneSidedTransactionResult},
offline_signer::{
Expand Down Expand Up @@ -633,18 +637,8 @@ where

let signatures = request.signatures;

// Enforce correct signature count and ordering for the multisig script
let (_ephemeral_pubkeys, threshold) =
get_multi_sig_script_components(selected_utxo.wallet_output.script())
.ok_or(TransactionError::BuilderError("no keys found".to_string()))?;

if signatures.len() < threshold as usize {
return Err(TransactionServiceError::Other(format!(
"Insufficient signatures: need at least {}, got {}",
threshold,
signatures.len()
)));
}
// Same rule as `MultisigSession::spend_multisig_utxo`: exactly `m` signatures.
validate_multisig_spend_signature_count(selected_utxo.wallet_output.script(), signatures.len())?;

let mut input_stack = ExecutionStack::default();
for sig in signatures.clone() {
Expand Down
Loading