Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add validation for accept-withdrawal-request transactions #555

Merged
merged 26 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
bab7244
Make the serde implementations transparent
djordon Sep 18, 2024
1691c8f
Change the name of a struct
djordon Sep 18, 2024
3862c35
Add validation to the CompleteDepositV1 struct.
djordon Sep 18, 2024
a7c6575
Add integration tests to the validation function
djordon Sep 18, 2024
528fde2
Update a stray comment
djordon Sep 18, 2024
00e5a39
This makes more sense
djordon Sep 18, 2024
5d462c0
minor clean-ups
djordon Sep 18, 2024
3f4e6c4
Update comments, fix typos
djordon Sep 18, 2024
1f1197c
Fix more typos
djordon Sep 18, 2024
5295570
Merge branch 'main' into 479-validate-complete-deposit-sign-requests
djordon Sep 18, 2024
ae8f00b
cargo fmt
djordon Sep 18, 2024
ae6ed9e
Fix typo, and simplify error message variant names
djordon Sep 19, 2024
531727d
Add a todo
djordon Sep 20, 2024
80c010f
cargo fmt
djordon Sep 20, 2024
5c1a27c
Add a SignerVotes type for converting to a bitmap
djordon Sep 21, 2024
59f1b9d
Add an aggregate key field to the
djordon Sep 21, 2024
6ee9ab2
Implement validate for the AcceptWithdrawalV1
djordon Sep 21, 2024
c022f21
Minor clean-up of existing tests
djordon Sep 21, 2024
817ea3f
add integration tests for the validation logic
djordon Sep 21, 2024
002fc51
Address PR comments 1
djordon Sep 23, 2024
92306a4
Factor out frequently used functions
djordon Sep 24, 2024
1542efb
Update integration test comments from PR feedback
djordon Sep 24, 2024
9618ed3
Merge branch 'main' into 477-validate-accept-withdrawal-request-contr…
djordon Sep 24, 2024
ac0e468
Rebase messed this up
djordon Sep 24, 2024
79e63cf
Rename that one wsts test function
djordon Sep 24, 2024
d8a4ad6
cargo fmt
djordon Sep 24, 2024
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
63 changes: 13 additions & 50 deletions signer/src/bitcoin/utxo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,9 @@ use crate::error::Error;
use crate::keys::SignerScriptPubKey as _;
use crate::storage::model;
use crate::storage::model::ScriptPubKey;
use crate::storage::model::SignerVote;
use crate::storage::model::SignerVotes;
use crate::storage::model::StacksBlockHash;
use crate::storage::model::StacksTxId;
use crate::MAX_KEYS;

/// The minimum incremental fee rate in sats per virtual byte for RBF
/// transactions.
Expand Down Expand Up @@ -348,32 +347,12 @@ impl DepositRequest {
pub fn from_model(
request: model::DepositRequest,
signers_public_key: XOnlyPublicKey,
mut votes: Vec<SignerVote>,
votes: SignerVotes,
) -> Self {
let txid = request.txid.into();
let vout = request.output_index;

let mut signer_bitmap = BitArray::ZERO;
djordon marked this conversation as resolved.
Show resolved Hide resolved
votes.sort_by_key(|vote| vote.signer_public_key);
votes
.into_iter()
.enumerate()
.take(signer_bitmap.len().min(MAX_KEYS as usize))
.for_each(|(index, vote)| {
// The BitArray::<[u8; 16]>::set function panics if the
// index is out of bounds but that cannot be the case here
// because we only take 128 values.
//
// Note that the signer bitmap here is true for votes
// *against*, and a missing vote is an implicit vote
// against.
signer_bitmap.set(index, !vote.is_accepted.unwrap_or(false));
});

Self {
outpoint: OutPoint { txid, vout },
outpoint: request.outpoint(),
max_fee: request.max_fee,
signer_bitmap,
signer_bitmap: votes.into(),
amount: request.amount,
deposit_script: ScriptBuf::from_bytes(request.spend_script),
reclaim_script: ScriptBuf::from_bytes(request.reclaim_script),
Expand Down Expand Up @@ -448,29 +427,12 @@ impl WithdrawalRequest {
}

/// Try convert from a model::DepositRequest with some additional info.
pub fn from_model(request: model::WithdrawalRequest, mut votes: Vec<SignerVote>) -> Self {
let mut signer_bitmap = BitArray::ZERO;
votes.sort_by_key(|vote| vote.signer_public_key);
votes
.into_iter()
.enumerate()
.take(signer_bitmap.len().min(MAX_KEYS as usize))
.for_each(|(index, vote)| {
// The BitArray::<[u8; 16]>::set function panics if the
// index is out of bounds but that cannot be the case here
// because we only take 128 values.
//
// Note that the signer bitmap here is true for votes
// *against*, and a missing vote is an implicit vote
// against.
signer_bitmap.set(index, !vote.is_accepted.unwrap_or(false));
});

pub fn from_model(request: model::WithdrawalRequest, votes: SignerVotes) -> Self {
Self {
amount: request.amount,
max_fee: request.max_fee,
script_pubkey: request.recipient,
signer_bitmap,
signer_bitmap: votes.into(),
request_id: request.request_id,
txid: request.txid,
block_hash: request.block_hash,
Expand Down Expand Up @@ -1012,6 +974,7 @@ mod tests {
use bitcoin::CompressedPublicKey;
use bitcoin::Txid;
use fake::Fake as _;
use model::SignerVote;
use rand::distributions::Distribution;
use rand::distributions::Uniform;
use rand::rngs::OsRng;
Expand Down Expand Up @@ -2071,7 +2034,7 @@ mod tests {
/// the model type to the required type here.
#[test]
fn creating_deposit_request_from_model_bitmap_is_right() {
let mut votes = [
let signer_votes = [
SignerVote {
signer_public_key: fake::Faker.fake_with_rng(&mut OsRng),
is_accepted: Some(true),
Expand All @@ -2093,15 +2056,15 @@ mod tests {
is_accepted: None,
},
];
let votes = SignerVotes::from(signer_votes.to_vec());
let request: model::DepositRequest = fake::Faker.fake_with_rng(&mut OsRng);
let signers_public_key: PublicKey = fake::Faker.fake_with_rng(&mut OsRng);
let deposit_request =
DepositRequest::from_model(request, signers_public_key.into(), votes.to_vec());
DepositRequest::from_model(request, signers_public_key.into(), votes.clone());

// One explicit vote against and one implicit vote against.
assert_eq!(deposit_request.votes_against(), 2);
// An appropriately named function ...
votes.sort_by_key(|x| x.signer_public_key);
votes.iter().enumerate().for_each(|(index, vote)| {
let vote_against = *deposit_request.signer_bitmap.get(index).unwrap();
assert_eq!(vote_against, !vote.is_accepted.unwrap_or(false));
Expand All @@ -2112,7 +2075,7 @@ mod tests {
/// the model type to the required type here.
#[test]
fn creating_withdrawal_request_from_model_bitmap_is_right() {
let mut votes = [
let signer_votes = [
SignerVote {
signer_public_key: fake::Faker.fake_with_rng(&mut OsRng),
is_accepted: Some(true),
Expand All @@ -2138,13 +2101,13 @@ mod tests {
is_accepted: None,
},
];
let votes = SignerVotes::from(signer_votes.to_vec());
let request: model::WithdrawalRequest = fake::Faker.fake_with_rng(&mut OsRng);
let withdrawal_request = WithdrawalRequest::from_model(request, votes.to_vec());
let withdrawal_request = WithdrawalRequest::from_model(request, votes.clone());

// One explicit vote against and one implicit vote against.
assert_eq!(withdrawal_request.votes_against(), 3);
// An appropriately named function ...
votes.sort_by_key(|x| x.signer_public_key);
votes.iter().enumerate().for_each(|(index, vote)| {
let vote_against = *withdrawal_request.signer_bitmap.get(index).unwrap();
assert_eq!(vote_against, !vote.is_accepted.unwrap_or(false));
Expand Down
3 changes: 2 additions & 1 deletion signer/src/bitcoin/zmq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ pub fn parse_bitcoin_core_message(message: ZmqMessage) -> Result<BitcoinCoreMess
}
// We do not implement parsing for any other message types but if
// we're here, then we probably have a valid message from
// bitcoin-core. Let's try to note the topic for easier debugging.
// bitcoin-core (we know `data` has three parts). Let's try to note
// the topic for easier debugging.
_ => {
let topic = core::str::from_utf8(data[0]).map(ToString::to_string);
Err(Error::BitcoinCoreZmqUnsupported(topic))
Expand Down
11 changes: 11 additions & 0 deletions signer/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::borrow::Cow;

use blockstack_lib::types::chainstate::StacksBlockId;

use crate::stacks::contracts::DepositValidationError;
use crate::stacks::contracts::WithdrawalAcceptValidationError;
use crate::{codec, ecdsa, network};

/// Top-level signer error
Expand Down Expand Up @@ -91,6 +93,10 @@ pub enum Error {
#[error("could not decode Nakamoto block from tenure with block: {1}; {0}")]
DecodeNakamotoTenure(#[source] blockstack_lib::codec::Error, StacksBlockId),

/// Failed to validate the complete-deposit contract call transaction.
#[error("{0}")]
DepositValidation(#[from] Box<DepositValidationError>),

/// An error when serializing an object to JSON
#[error("{0}")]
JsonSerialize(#[source] serde_json::Error),
Expand Down Expand Up @@ -295,6 +301,11 @@ pub enum Error {
#[error("unexpected public key from signature. key {0}; digest: {1}")]
UnknownPublicKey(crate::keys::PublicKey, secp256k1::Message),

/// The error for when the request to sign a withdrawal-accept
/// transaction fails at the validation step.
#[error("{0}")]
WithdrawalAcceptValidation(#[source] Box<WithdrawalAcceptValidationError>),
cylewitruk marked this conversation as resolved.
Show resolved Hide resolved

/// WSTS error.
#[error("WSTS error: {0}")]
Wsts(#[source] wsts::state_machine::signer::Error),
Expand Down
8 changes: 8 additions & 0 deletions signer/src/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ use crate::error::Error;

/// The public key type for the secp256k1 elliptic curve.
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PublicKey(secp256k1::PublicKey);

impl From<&secp256k1::PublicKey> for PublicKey {
Expand Down Expand Up @@ -182,6 +183,12 @@ impl From<&PublicKey> for stacks_common::util::secp256k1::Secp256k1PublicKey {
}
}

impl From<PublicKey> for stacks_common::util::secp256k1::Secp256k1PublicKey {
fn from(value: PublicKey) -> Self {
Self::from(&value)
}
}

impl From<&stacks_common::util::secp256k1::Secp256k1PublicKey> for PublicKey {
fn from(value: &stacks_common::util::secp256k1::Secp256k1PublicKey) -> Self {
let key = secp256k1::PublicKey::from_slice(&value.to_bytes_compressed())
Expand Down Expand Up @@ -231,6 +238,7 @@ impl std::fmt::Display for PublicKey {

/// A private key type for the secp256k1 elliptic curve.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(transparent)]
pub struct PrivateKey(secp256k1::SecretKey);

impl FromStr for PrivateKey {
Expand Down
Loading
Loading