Skip to content

Commit

Permalink
Fix out-of-order upstream merges
Browse files Browse the repository at this point in the history
  • Loading branch information
0xA001113 committed Oct 23, 2024
1 parent a694aa6 commit ba4ae26
Show file tree
Hide file tree
Showing 11 changed files with 20 additions and 171 deletions.
59 changes: 0 additions & 59 deletions cli/src/wizards/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,62 +144,3 @@ pub(crate) async fn multisig_watch(ctx: &Arc<SpectreCli>, name: Option<&str>) ->
wallet.select(Some(&account)).await?;
Ok(())
}

pub(crate) async fn bip32_watch(ctx: &Arc<SpectreCli>, name: Option<&str>) -> Result<()> {
let term = ctx.term();
let wallet = ctx.wallet();

let name = if let Some(name) = name {
Some(name.to_string())
} else {
Some(term.ask(false, "Please enter account name (optional, press <enter> to skip): ").await?.trim().to_string())
};

let mut xpub_keys = Vec::with_capacity(1);
let xpub_key = term.ask(false, "Enter extended public key: ").await?;
xpub_keys.push(xpub_key.trim().to_owned());

let wallet_secret = Secret::new(term.ask(true, "Enter wallet password: ").await?.trim().as_bytes().to_vec());
if wallet_secret.as_ref().is_empty() {
return Err(Error::WalletSecretRequired);
}

let account_create_args_bip32_watch = AccountCreateArgsBip32Watch::new(name, xpub_keys);
let account = wallet.create_account_bip32_watch(&wallet_secret, account_create_args_bip32_watch).await?;

tprintln!(ctx, "\naccount created: {}\n", account.get_list_string()?);
wallet.select(Some(&account)).await?;
Ok(())
}

pub(crate) async fn multisig_watch(ctx: &Arc<SpectreCli>, name: Option<&str>) -> Result<()> {
let term = ctx.term();

let account_name = if let Some(name) = name {
Some(name.to_string())
} else {
Some(term.ask(false, "Please enter account name (optional, press <enter> to skip): ").await?.trim().to_string())
};

let term = ctx.term();
let wallet = ctx.wallet();
let (wallet_secret, _) = ctx.ask_wallet_secret(None).await?;
let minimum_signatures: u16 = term.ask(false, "Enter the minimum number of signatures required: ").await?.parse()?;

let prv_key_data_args = Vec::with_capacity(0);

let answer = term.ask(false, "Enter the number of extended public keys: ").await?.trim().to_string(); //.parse()?;
let xpub_keys_len: usize = if answer.is_empty() { 0 } else { answer.parse()? };

let mut xpub_keys = Vec::with_capacity(xpub_keys_len);
for i in 1..=xpub_keys_len {
let xpub_key = term.ask(false, &format!("Enter extended public {i} key: ")).await?;
xpub_keys.push(xpub_key.trim().to_owned());
}
let account =
wallet.create_account_multisig(&wallet_secret, prv_key_data_args, xpub_keys, account_name, minimum_signatures).await?;

tprintln!(ctx, "\naccount created: {}\n", account.get_list_string()?);
wallet.select(Some(&account)).await?;
Ok(())
}
4 changes: 2 additions & 2 deletions consensus/core/src/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,9 @@ pub fn sign_with_multiple_v2(mut mutable_tx: SignableTransaction, privkeys: &[[u

/// Sign a transaction input with a sighash_type using schnorr
pub fn sign_input(tx: &impl VerifiableTransaction, input_index: usize, private_key: &[u8; 32], hash_type: SigHashType) -> Vec<u8> {
let mut reused_values = SigHashReusedValues::new();
let reused_values = SigHashReusedValuesUnsync::new();

let hash = calc_schnorr_signature_hash(tx, input_index, hash_type, &mut reused_values);
let hash = calc_schnorr_signature_hash(tx, input_index, hash_type, &reused_values);
let msg = secp256k1::Message::from_digest_slice(hash.as_bytes().as_slice()).unwrap();
let schnorr_key = secp256k1::Keypair::from_seckey_slice(secp256k1::SECP256K1, private_key).unwrap();
let sig: [u8; 64] = *schnorr_key.sign_schnorr(msg).as_ref();
Expand Down
66 changes: 0 additions & 66 deletions consensus/core/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,28 +244,6 @@ impl Transaction {
self.set_mass(mass);
self
}

pub fn with_mass(self, mass: u64) -> Self {
self.set_mass(mass);
self
}
}

impl MemSizeEstimator for Transaction {
fn estimate_mem_bytes(&self) -> usize {
// Calculates mem bytes of the transaction (for cache tracking purposes)
size_of::<Self>()
+ self.payload.len()
+ self
.inputs
.iter()
.map(|i| i.signature_script.len() + size_of::<TransactionInput>())
.chain(self.outputs.iter().map(|o| {
// size_of::<TransactionOutput>() already counts SCRIPT_VECTOR_SIZE bytes within, so we only add the delta
o.script_public_key.script().len().saturating_sub(SCRIPT_VECTOR_SIZE) + size_of::<TransactionOutput>()
}))
.sum::<usize>()
}
}

impl MemSizeEstimator for Transaction {
Expand Down Expand Up @@ -489,50 +467,6 @@ impl<T: AsRef<Transaction>> MutableTransaction<T> {
pub fn has_parent_in_set(&self, possible_parents: &HashSet<TransactionId>) -> bool {
self.tx.as_ref().inputs.iter().any(|x| possible_parents.contains(&x.previous_outpoint.transaction_id))
}

/// Returns the calculated feerate. The feerate is calculated as the amount of fee
/// this transactions pays per gram of the full contextual (compute & storage) mass. The
/// function returns a value when calculated fee exists and the contextual mass is greater
/// than zero, otherwise `None` is returned.
pub fn calculated_feerate(&self) -> Option<f64> {
let contextual_mass = self.tx.as_ref().mass();
if contextual_mass > 0 {
self.calculated_fee.map(|fee| fee as f64 / contextual_mass as f64)
} else {
None
}
}

/// A function for estimating the amount of memory bytes used by this transaction (dedicated to mempool usage).
/// We need consistency between estimation calls so only this function should be used for this purpose since
/// `estimate_mem_bytes` is sensitive to pointer wrappers such as Arc
pub fn mempool_estimated_bytes(&self) -> usize {
self.estimate_mem_bytes()
}

pub fn has_parent(&self, possible_parent: TransactionId) -> bool {
self.tx.as_ref().inputs.iter().any(|x| x.previous_outpoint.transaction_id == possible_parent)
}

pub fn has_parent_in_set(&self, possible_parents: &HashSet<TransactionId>) -> bool {
self.tx.as_ref().inputs.iter().any(|x| possible_parents.contains(&x.previous_outpoint.transaction_id))
}
}

impl<T: AsRef<Transaction>> MemSizeEstimator for MutableTransaction<T> {
fn estimate_mem_bytes(&self) -> usize {
size_of::<Self>()
+ self
.entries
.iter()
.map(|op| {
// size_of::<Option<UtxoEntry>>() already counts SCRIPT_VECTOR_SIZE bytes within, so we only add the delta
size_of::<Option<UtxoEntry>>()
+ op.as_ref().map_or(0, |e| e.script_public_key.script().len().saturating_sub(SCRIPT_VECTOR_SIZE))
})
.sum::<usize>()
+ self.tx.as_ref().estimate_mem_bytes()
}
}

impl<T: AsRef<Transaction>> MemSizeEstimator for MutableTransaction<T> {
Expand Down
6 changes: 0 additions & 6 deletions consensus/core/src/tx/script_public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,12 +336,6 @@ extern "C" {
pub type ScriptPublicKeyT;
}

#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "ScriptPublicKey | HexString")]
pub type ScriptPublicKeyT;
}

#[wasm_bindgen]
impl ScriptPublicKey {
#[wasm_bindgen(constructor)]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use super::BlockBodyProcessor;
use crate::{
errors::{BlockProcessResult, RuleError},
model::{
services::reachability::ReachabilityService,
stores::{ghostdag::GhostdagStoreReader, pruning::PruningStoreReader, statuses::StatusesStoreReader},
},
model::stores::{ghostdag::GhostdagStoreReader, statuses::StatusesStoreReader},
processes::window::WindowManager,
};
use spectre_consensus_core::block::Block;
Expand Down
12 changes: 4 additions & 8 deletions consensus/src/pipeline/virtual_processor/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -778,14 +778,10 @@ impl VirtualStateProcessor {
let virtual_utxo_view = &virtual_read.utxo_set;
let virtual_daa_score = virtual_state.daa_score;
let virtual_past_median_time = virtual_state.past_median_time;
if mutable_tx.tx.inputs.len() > 1 {
// use pool to apply par_iter to inputs
self.thread_pool.install(|| {
self.validate_mempool_transaction_impl(mutable_tx, virtual_utxo_view, virtual_daa_score, virtual_past_median_time)
})
} else {
self.validate_mempool_transaction_impl(mutable_tx, virtual_utxo_view, virtual_daa_score, virtual_past_median_time)
}
// Run within the thread pool since par_iter might be internally applied to inputs
self.thread_pool.install(|| {
self.validate_mempool_transaction_impl(mutable_tx, virtual_utxo_view, virtual_daa_score, virtual_past_median_time, args)
})
}

pub fn validate_mempool_transactions_in_parallel(
Expand Down
6 changes: 0 additions & 6 deletions consensus/src/processes/reachability/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,6 @@ impl From<(u64, &[u64])> for DagBlock {
}
}

impl From<(u64, &[u64])> for DagBlock {
fn from(value: (u64, &[u64])) -> Self {
Self::new(value.0.into(), value.1.iter().map(|&i| i.into()).collect())
}
}

/// A struct with fluent API to streamline DAG building
pub struct DagBuilder<'a, T: ReachabilityStore + ?Sized, S: RelationsStore + ChildrenStore + ?Sized> {
reachability: &'a mut T,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use spectre_consensus_core::hashing::sighash::{SigHashReusedValues, SigHashReuse
use spectre_consensus_core::{
hashing::sighash::SigHashReusedValuesUnsync,
mass::Kip9Version,
tx::VerifiableTransaction,
tx::{TransactionInput, VerifiableTransaction},
};
use spectre_core::warn;
use spectre_txscript::caches::Cache;
Expand Down Expand Up @@ -223,14 +223,6 @@ fn map_script_err(script_err: TxScriptError, input: &TransactionInput) -> TxRule
}
}

fn map_script_err(script_err: TxScriptError, input: &TransactionInput) -> TxRuleError {
if input.signature_script.is_empty() {
TxRuleError::SignatureEmpty(script_err)
} else {
TxRuleError::SignatureInvalid(script_err)
}
}

#[cfg(test)]
mod tests {
use super::super::errors::TxRuleError;
Expand Down
8 changes: 4 additions & 4 deletions wallet/core/src/account/pssb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use secp256k1::schnorr;
use secp256k1::{Message, PublicKey};
use spectre_bip32::{DerivationPath, KeyFingerprint, PrivateKey};
use spectre_consensus_client::UtxoEntry as ClientUTXO;
use spectre_consensus_core::hashing::sighash::{calc_schnorr_signature_hash, SigHashReusedValues};
use spectre_consensus_core::hashing::sighash::{calc_schnorr_signature_hash, SigHashReusedValuesUnsync};
use spectre_consensus_core::tx::VerifiableTransaction;
use spectre_consensus_core::tx::{TransactionInput, UtxoEntry};
use spectre_txscript::extract_script_pub_key_address;
Expand Down Expand Up @@ -160,7 +160,7 @@ pub async fn pssb_signer_for_address(
key_fingerprint: KeyFingerprint,
) -> Result<Bundle, Error> {
let mut signed_bundle = Bundle::new();
let mut reused_values = SigHashReusedValues::new();
let reused_values = SigHashReusedValuesUnsync::new();

// If set, sign-for address is used for signing.
// Else, all addresses from inputs are.
Expand All @@ -186,15 +186,15 @@ pub async fn pssb_signer_for_address(
for psst_inner in bundle.iter().cloned() {
let psst: PSST<Signer> = PSST::from(psst_inner);

let mut sign = |signer_psst: PSST<Signer>| {
let sign = |signer_psst: PSST<Signer>| {
signer_psst
.pass_signature_sync(|tx, sighash| -> Result<Vec<SignInputOk>, String> {
tx.tx
.inputs
.iter()
.enumerate()
.map(|(idx, _input)| {
let hash = calc_schnorr_signature_hash(&tx.as_verifiable(), idx, sighash[idx], &mut reused_values);
let hash = calc_schnorr_signature_hash(&tx.as_verifiable(), idx, sighash[idx], &reused_values);
let msg = secp256k1::Message::from_digest_slice(hash.as_bytes().as_slice()).unwrap();

// When address represents a locked UTXO, no private key is available.
Expand Down
8 changes: 4 additions & 4 deletions wallet/psst/examples/multisig.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use secp256k1::{rand::thread_rng, Keypair};
use spectre_consensus_core::{
hashing::sighash::{calc_schnorr_signature_hash, SigHashReusedValues},
hashing::sighash::{calc_schnorr_signature_hash, SigHashReusedValuesUnsync},
tx::{TransactionId, TransactionOutpoint, UtxoEntry},
};
use spectre_txscript::{multisig_redeem_script, opcodes::codes::OpData65, pay_to_script_hash_script, script_builder::ScriptBuilder};
Expand Down Expand Up @@ -51,8 +51,8 @@ fn main() {
println!("Serialized after setting sequence: {}", ser_updated);

let signer_psst: PSST<Signer> = serde_json::from_str(&ser_updated).expect("Failed to deserialize");
let mut reused_values = SigHashReusedValues::new();
let mut sign = |signer_psst: PSST<Signer>, kp: &Keypair| {
let reused_values = SigHashReusedValuesUnsync::new();
let sign = |signer_psst: PSST<Signer>, kp: &Keypair| {
signer_psst
.pass_signature_sync(|tx, sighash| -> Result<Vec<SignInputOk>, String> {
let tx = dbg!(tx);
Expand All @@ -61,7 +61,7 @@ fn main() {
.iter()
.enumerate()
.map(|(idx, _input)| {
let hash = calc_schnorr_signature_hash(&tx.as_verifiable(), idx, sighash[idx], &mut reused_values);
let hash = calc_schnorr_signature_hash(&tx.as_verifiable(), idx, sighash[idx], &reused_values);
let msg = secp256k1::Message::from_digest_slice(hash.as_bytes().as_slice()).unwrap();
Ok(SignInputOk {
signature: Signature::Schnorr(kp.sign_schnorr(msg)),
Expand Down
7 changes: 4 additions & 3 deletions wallet/psst/src/psst.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use spectre_bip32::{secp256k1, DerivationPath, KeyFingerprint};
use spectre_consensus_core::hashing::sighash::SigHashReusedValuesUnsync;
use std::{collections::BTreeMap, fmt::Display, fmt::Formatter, future::Future, marker::PhantomData, ops::Deref};

pub use crate::error::Error;
Expand All @@ -14,7 +15,7 @@ pub use crate::output::{Output, OutputBuilder};
pub use crate::role::{Combiner, Constructor, Creator, Extractor, Finalizer, Signer, Updater};
use spectre_consensus_core::tx::UtxoEntry;
use spectre_consensus_core::{
hashing::{sighash::SigHashReusedValues, sighash_type::SigHashType},
hashing::sighash_type::SigHashType,
subnets::SUBNETWORK_ID_NATIVE,
tx::{MutableTransaction, SignableTransaction, Transaction, TransactionId, TransactionInput, TransactionOutput},
};
Expand Down Expand Up @@ -432,10 +433,10 @@ impl PSST<Extractor> {
{
let tx = tx.as_verifiable();
let cache = Cache::new(10_000);
let mut reused_values = SigHashReusedValues::new();
let reused_values = SigHashReusedValuesUnsync::new();

tx.populated_inputs().enumerate().try_for_each(|(idx, (input, entry))| {
TxScriptEngine::from_transaction_input(&tx, input, idx, entry, &mut reused_values, &cache)?.execute()?;
TxScriptEngine::from_transaction_input(&tx, input, idx, entry, &reused_values, &cache)?.execute()?;
<Result<(), ExtractError>>::Ok(())
})?;
}
Expand Down

0 comments on commit ba4ae26

Please sign in to comment.