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

[featue] move events module to sbtc crate #1144

Merged
merged 20 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from 13 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
1 change: 0 additions & 1 deletion emily/handler/src/database/entries/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,6 @@ impl DepositUpdatePackage {
mod tests {
use super::*;
use test_case::test_case;
use testing_emily_client::models::fulfillment;

#[test]
fn deposit_update_should_be_unnecessary_when_event_is_present() {
Expand Down
48 changes: 20 additions & 28 deletions signer/src/stacks/events.rs → sbtc/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use std::collections::BTreeMap;

use bitcoin::hashes::Hash;
use bitcoin::hex::DisplayHex;
use bitcoin::BlockHash as BitcoinBlockHash;
use bitcoin::OutPoint;
use bitcoin::PubkeyHash;
Expand All @@ -19,8 +20,6 @@ use bitcoin::ScriptHash;
use bitcoin::Txid as BitcoinTxid;
use bitcoin::WitnessProgram;
use bitcoin::WitnessVersion;
use bitvec::array::BitArray;
use blockstack_lib::burnchains::Txid as StacksTxid;
use clarity::vm::types::CharType;
use clarity::vm::types::PrincipalData;
use clarity::vm::types::SequenceData;
Expand All @@ -30,6 +29,18 @@ use clarity::vm::Value as ClarityValue;
use secp256k1::PublicKey;
use stacks_common::types::chainstate::StacksBlockId;

use std::fmt::Display;

/// Stacks transaction identifier. Wrapper over a 32 byte array.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StacksTxid(pub [u8; 32]);

impl Display for StacksTxid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", &self.0.to_hex_string(bitcoin::hex::Case::Lower))
}
}

/// This trait adds a function for converting bytes from little-endian byte
/// order into a bitcoin hash types. This is because the signers convert
/// [`bitcoin::Txid`] and [`bitcoin::BlockHash`] bytes into little-endian
Expand Down Expand Up @@ -232,7 +243,7 @@ pub struct WithdrawalAcceptEvent {
/// The bitmap of how the signers voted for the withdrawal request.
/// Here, a 1 (or true) implies that the signer did *not* vote to
/// accept the request.
pub signer_bitmap: BitArray<[u8; 16]>,
pub signer_bitmap: u128,
/// This is the outpoint for the bitcoin transaction that serviced the
/// request.
pub outpoint: OutPoint,
Expand Down Expand Up @@ -263,7 +274,7 @@ pub struct WithdrawalRejectEvent {
/// The bitmap of how the signers voted for the withdrawal request.
/// Here, a 1 (or true) implies that the signer did *not* vote to
/// accept the request.
pub signer_bitmap: BitArray<[u8; 16]>,
pub signer_bitmap: u128,
}

/// This is the event that is emitted from the `rotate-keys`
Expand Down Expand Up @@ -626,7 +637,7 @@ impl RawTupleData {
// This shouldn't error for the reasons noted in
// [`withdrawal_create`].
request_id: u64::try_from(request_id).map_err(EventError::ClarityIntConversion)?,
signer_bitmap: BitArray::new(bitmap.to_le_bytes()),
signer_bitmap: bitmap,
outpoint: OutPoint {
// This shouldn't error, this is set from a proper [`Txid`] in
// a contract call.
Expand Down Expand Up @@ -677,7 +688,7 @@ impl RawTupleData {
// This shouldn't error for the reasons noted in
// [`withdrawal_create`].
request_id: u64::try_from(request_id).map_err(EventError::ClarityIntConversion)?,
signer_bitmap: BitArray::new(bitmap.to_le_bytes()),
signer_bitmap: bitmap,
}))
}

Expand Down Expand Up @@ -733,7 +744,6 @@ mod tests {

use bitcoin::key::CompressedPublicKey;
use bitcoin::key::TweakedPublicKey;
use bitvec::field::BitField as _;
use clarity::vm::types::ListData;
use clarity::vm::types::ListTypeData;
use clarity::vm::types::BUFF_33;
Expand All @@ -749,24 +759,6 @@ mod tests {
block_id: StacksBlockId([0; 32]),
};

#[test]
fn signer_bitmap_conversion() {
// This test checks that converting from an integer to the bitmap
// works the way that we expect.
let bitmap_number: u128 = 3;
let bitmap: BitArray<[u8; 16]> = BitArray::new(bitmap_number.to_le_bytes());

assert_eq!(bitmap.load_le::<u128>(), bitmap_number);

// This is basically a test of the same thing as the above, except
// that we explicitly create the signer bitmap.
let mut bitmap: BitArray<[u8; 16]> = BitArray::ZERO;
bitmap.set(0, true);
bitmap.set(1, true);

assert_eq!(bitmap.load_le::<u128>(), bitmap_number);
}

#[test]
fn complete_deposit_event() {
let amount = 123654789;
Expand Down Expand Up @@ -802,7 +794,7 @@ mod tests {
assert_eq!(event.outpoint.vout, 3);
assert_eq!(
event.sweep_block_hash,
BitcoinBlockHash::from_byte_array([2; 32])
BitcoinBlockHash::from_byte_array([2; 32]),
);
assert_eq!(event.sweep_block_height, 139);
assert_eq!(event.sweep_txid, BitcoinTxid::from_byte_array([3; 32]));
Expand Down Expand Up @@ -922,7 +914,7 @@ mod tests {
// let res = transform_value(value, NetworkKind::Regtest).unwrap();
match RegistryEvent::try_new(value, TX_INFO).unwrap() {
RegistryEvent::WithdrawalAccept(event) => {
let expected_bitmap = BitArray::<[u8; 16]>::new(bitmap.to_le_bytes());
let expected_bitmap = bitmap;
assert_eq!(event.request_id, request_id as u64);
assert_eq!(event.outpoint.txid, BitcoinTxid::from_byte_array([1; 32]));
assert_eq!(event.outpoint.vout, vout as u32);
Expand Down Expand Up @@ -964,7 +956,7 @@ mod tests {
// let res = transform_value(value, NetworkKind::Regtest).unwrap();
match RegistryEvent::try_new(value, TX_INFO).unwrap() {
RegistryEvent::WithdrawalReject(event) => {
let expected_bitmap = BitArray::<[u8; 16]>::new(bitmap.to_le_bytes());
let expected_bitmap = bitmap;
assert_eq!(event.request_id, request_id as u64);
assert_eq!(event.signer_bitmap, expected_bitmap);
}
Expand Down
1 change: 1 addition & 0 deletions sbtc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use bitcoin::XOnlyPublicKey;

pub mod deposits;
pub mod error;
pub mod events;

#[cfg(any(test, feature = "testing"))]
pub mod testing;
Expand Down
64 changes: 34 additions & 30 deletions signer/src/api/new_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,21 @@ use crate::emily_client::EmilyInteract;
use crate::error::Error;
use crate::metrics::Metrics;
use crate::metrics::STACKS_BLOCKCHAIN;
use crate::stacks::events::CompletedDepositEvent;
use crate::stacks::events::KeyRotationEvent;
use crate::stacks::events::RegistryEvent;
use crate::stacks::events::TxInfo;
use crate::stacks::events::WithdrawalAcceptEvent;
use crate::stacks::events::WithdrawalCreateEvent;
use crate::stacks::events::WithdrawalRejectEvent;
use crate::stacks::webhooks::NewBlockEvent;
use crate::storage::model::BitcoinBlockHash;
use crate::storage::model::CompletedDepositEvent;
use crate::storage::model::RotateKeysTransaction;
use crate::storage::model::StacksBlock;
use crate::storage::model::StacksBlockHash;
use crate::storage::model::StacksTxId;
use crate::storage::model::WithdrawalAcceptEvent;
use crate::storage::model::WithdrawalCreateEvent;
use crate::storage::model::WithdrawalRejectEvent;
use crate::storage::DbRead;
use crate::storage::DbWrite;
use sbtc::events::KeyRotationEvent;
use sbtc::events::RegistryEvent;
use sbtc::events::TxInfo;

use super::ApiState;
use super::SBTC_REGISTRY_CONTRACT_NAME;
Expand Down Expand Up @@ -132,25 +132,28 @@ pub async fn new_block_handler(state: State<ApiState<impl Context>>, body: Strin
let mut created_withdrawals = Vec::new();

for (ev, txid) in events {
let tx_info = TxInfo { txid, block_id };
let tx_info = TxInfo {
txid: sbtc::events::StacksTxid(txid.0),
block_id,
};
let res = match RegistryEvent::try_new(ev.value, tx_info) {
Ok(RegistryEvent::CompletedDeposit(event)) => {
handle_completed_deposit(&api.ctx, event, &stacks_chaintip)
handle_completed_deposit(&api.ctx, event.into(), &stacks_chaintip)
.await
.map(|x| completed_deposits.push(x))
}
Ok(RegistryEvent::WithdrawalAccept(event)) => {
handle_withdrawal_accept(&api.ctx, event, &stacks_chaintip)
handle_withdrawal_accept(&api.ctx, event.into(), &stacks_chaintip)
.await
.map(|x| updated_withdrawals.push(x))
}
Ok(RegistryEvent::WithdrawalReject(event)) => {
handle_withdrawal_reject(&api.ctx, event, &stacks_chaintip)
handle_withdrawal_reject(&api.ctx, event.into(), &stacks_chaintip)
.await
.map(|x| updated_withdrawals.push(x))
}
Ok(RegistryEvent::WithdrawalCreate(event)) => {
handle_withdrawal_create(&api.ctx, event, stacks_chaintip.block_height)
handle_withdrawal_create(&api.ctx, event.into(), stacks_chaintip.block_height)
.await
.map(|x| created_withdrawals.push(x))
}
Expand Down Expand Up @@ -401,7 +404,6 @@ mod tests {
use super::*;

use bitcoin::OutPoint;
use bitcoin::ScriptBuf;
use bitvec::array::BitArray;
use clarity::vm::types::PrincipalData;
use emily_client::models::UpdateDepositsResponse;
Expand All @@ -413,7 +415,9 @@ mod tests {
use test_case::test_case;

use crate::storage::in_memory::Store;
use crate::storage::model::BitcoinTxId;
use crate::storage::model::DepositRequest;
use crate::storage::model::ScriptPubKey;
use crate::storage::model::StacksPrincipal;
use crate::testing::context::*;
use crate::testing::storage::model::TestData;
Expand Down Expand Up @@ -613,12 +617,12 @@ mod tests {

let event = CompletedDepositEvent {
outpoint: deposit_request.outpoint(),
txid: *stacks_txid,
block_id: *stacks_chaintip.block_hash,
txid: StacksTxId(*stacks_txid),
block_id: StacksBlockHash(*stacks_chaintip.block_hash),
amount: deposit_request.amount - btc_fee,
sweep_block_hash: *bitcoin_block.block_hash,
sweep_block_hash: BitcoinBlockHash(*bitcoin_block.block_hash),
sweep_block_height: bitcoin_block.block_height,
sweep_txid: *txid,
sweep_txid: BitcoinTxId(*txid),
};
let expectation = DepositUpdate {
bitcoin_tx_output_index: event.outpoint.vout,
Expand Down Expand Up @@ -677,12 +681,12 @@ mod tests {
let outpoint = OutPoint { txid: *txid, vout: 0 };
let event = CompletedDepositEvent {
outpoint: outpoint.clone(),
txid: *stacks_txid,
block_id: *stacks_chaintip.block_hash,
txid: StacksTxId(*stacks_txid),
block_id: StacksBlockHash(*stacks_chaintip.block_hash),
amount: 100,
sweep_block_hash: *bitcoin_block.block_hash,
sweep_block_hash: BitcoinBlockHash(*bitcoin_block.block_hash),
sweep_block_height: bitcoin_block.block_height,
sweep_txid: *txid,
sweep_txid: BitcoinTxId(*txid),
};
let res = handle_completed_deposit(&ctx, event, stacks_chaintip).await;
assert!(res.is_err());
Expand Down Expand Up @@ -730,13 +734,13 @@ mod tests {
let event = WithdrawalAcceptEvent {
request_id: 1,
outpoint: OutPoint { txid: *txid, vout: 0 },
txid: *stacks_tx.txid,
block_id: *stacks_tx.block_hash,
txid: StacksTxId(*stacks_tx.txid),
block_id: StacksBlockHash(*stacks_tx.block_hash),
fee: 1,
signer_bitmap: BitArray::<_>::ZERO,
sweep_block_hash: *bitcoin_block.block_hash,
sweep_block_hash: BitcoinBlockHash(*bitcoin_block.block_hash),
sweep_block_height: bitcoin_block.block_height,
sweep_txid: *txid,
sweep_txid: BitcoinTxId(*txid),
};

// Expected struct to be added to the accepted_withdrawals vector
Expand Down Expand Up @@ -795,11 +799,11 @@ mod tests {

let event = WithdrawalCreateEvent {
request_id: 1,
block_id: *stacks_first_tx.block_hash,
block_id: StacksBlockHash(*stacks_first_tx.block_hash),
amount: 100,
max_fee: 1,
recipient: ScriptBuf::default(),
txid: *stacks_first_tx.txid,
recipient: ScriptPubKey::from_bytes(vec![]),
txid: StacksTxId::from(stacks_first_tx.txid.0),
sender: PrincipalData::Standard(StandardPrincipalData::transient()),
block_height: test_data.bitcoin_blocks[0].block_height,
};
Expand Down Expand Up @@ -857,8 +861,8 @@ mod tests {

let event = WithdrawalRejectEvent {
request_id: 1,
block_id: *stacks_chaintip.block_hash,
txid: *test_data.stacks_transactions[0].txid,
block_id: StacksBlockHash(*stacks_chaintip.block_hash),
txid: StacksTxId::from(*test_data.stacks_transactions[0].txid),
signer_bitmap: BitArray::<_>::ZERO,
};

Expand Down
2 changes: 1 addition & 1 deletion signer/src/request_decider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ where

let msg = SignerWithdrawalDecision {
request_id: withdrawal_request.request_id,
block_hash: withdrawal_request.block_hash.0,
block_hash: withdrawal_request.block_hash.0 .0,
djordon marked this conversation as resolved.
Show resolved Hide resolved
accepted: is_accepted,
txid: withdrawal_request.txid,
};
Expand Down
1 change: 0 additions & 1 deletion signer/src/stacks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
/// Contains an interface for interacting with a stacks node.
pub mod api;
pub mod contracts;
pub mod events;
/// Contains structs for signing stacks transactions using the signers'
/// multi-sig wallet.
pub mod wallet;
Expand Down
8 changes: 4 additions & 4 deletions signer/src/storage/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ use crate::error::Error;
use crate::keys::PublicKey;
use crate::keys::PublicKeyXOnly;
use crate::keys::SignerScriptPubKey as _;
use crate::stacks::events::CompletedDepositEvent;
use crate::stacks::events::WithdrawalAcceptEvent;
use crate::stacks::events::WithdrawalCreateEvent;
use crate::stacks::events::WithdrawalRejectEvent;
use crate::storage::model;
use crate::storage::model::CompletedDepositEvent;
use crate::storage::model::WithdrawalAcceptEvent;
use crate::storage::model::WithdrawalCreateEvent;
use crate::storage::model::WithdrawalRejectEvent;
use crate::DEPOSIT_LOCKTIME_BLOCK_BUFFER;

use super::util::get_utxo;
Expand Down
8 changes: 4 additions & 4 deletions signer/src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ use crate::bitcoin::validation::WithdrawalRequestReport;
use crate::error::Error;
use crate::keys::PublicKey;
use crate::keys::PublicKeyXOnly;
use crate::stacks::events::CompletedDepositEvent;
use crate::stacks::events::WithdrawalAcceptEvent;
use crate::stacks::events::WithdrawalCreateEvent;
use crate::stacks::events::WithdrawalRejectEvent;
use crate::storage::model::CompletedDepositEvent;
use crate::storage::model::WithdrawalAcceptEvent;
use crate::storage::model::WithdrawalCreateEvent;
use crate::storage::model::WithdrawalRejectEvent;

/// Represents the ability to read data from the signer storage.
pub trait DbRead {
Expand Down
Loading
Loading