Skip to content

Commit

Permalink
Merge branch 'development' into st-allow-grpc
Browse files Browse the repository at this point in the history
  • Loading branch information
SWvheerden authored Mar 5, 2024
2 parents bc7b75b + 464f2c3 commit 65dd095
Show file tree
Hide file tree
Showing 22 changed files with 318 additions and 146 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,9 @@ async fn set_base_node_peer(
) -> Result<(CommsPublicKey, Multiaddr), CommandError> {
println!("Setting base node peer...");
println!("{}::{}", public_key, address);
wallet.set_base_node_peer(public_key.clone(), address.clone()).await?;
wallet
.set_base_node_peer(public_key.clone(), Some(address.clone()))
.await?;
Ok((public_key, address))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ impl wallet_server::Wallet for WalletGrpcServer {
println!("{}::{}", public_key, net_address);
let mut wallet = self.wallet.clone();
wallet
.set_base_node_peer(public_key.clone(), net_address.clone())
.set_base_node_peer(public_key.clone(), Some(net_address.clone()))
.await
.map_err(|e| Status::internal(format!("{:?}", e)))?;

Expand Down
2 changes: 1 addition & 1 deletion applications/minotari_console_wallet/src/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ pub async fn start_wallet(
.ok_or_else(|| ExitError::new(ExitCode::ConfigError, "Configured base node has no address!"))?;

wallet
.set_base_node_peer(base_node.public_key.clone(), net_address.address().clone())
.set_base_node_peer(base_node.public_key.clone(), Some(net_address.address().clone()))
.await
.map_err(|e| {
ExitError::new(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,7 @@ impl<B: Backend> Component<B> for TransactionsTab {
error!(target: LOG_TARGET, "Error rebroadcasting transactions: {}", e);
}
},
'a' => app_state.toggle_abandoned_coinbase_filter(),
'\n' => match self.selected_tx_list {
SelectedTransactionList::None => {},
SelectedTransactionList::PendingTxs => {
Expand Down
31 changes: 27 additions & 4 deletions applications/minotari_console_wallet/src/ui/state/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ pub struct AppState {
inner: Arc<RwLock<AppStateInner>>,
cached_data: AppStateData,
cache_update_cooldown: Option<Instant>,
completed_tx_filter: TransactionFilter,
config: AppStateConfig,
wallet_config: WalletConfig,
wallet_connectivity: WalletConnectivityHandle,
Expand All @@ -121,6 +122,7 @@ impl AppState {
cached_data,
cache_update_cooldown: None,
config: AppStateConfig::default(),
completed_tx_filter: TransactionFilter::AbandonedCoinbases,
wallet_connectivity,
balance_enquiry_debouncer: BalanceEnquiryDebouncer::new(
inner,
Expand Down Expand Up @@ -185,6 +187,13 @@ impl AppState {
Ok(())
}

pub fn toggle_abandoned_coinbase_filter(&mut self) {
self.completed_tx_filter = match self.completed_tx_filter {
TransactionFilter::AbandonedCoinbases => TransactionFilter::None,
TransactionFilter::None => TransactionFilter::AbandonedCoinbases,
};
}

pub async fn update_cache(&mut self) {
let update = match self.cache_update_cooldown {
Some(last_update) => last_update.elapsed() > self.config.cache_update_cooldown,
Expand Down Expand Up @@ -556,7 +565,15 @@ impl AppState {
}

pub fn get_completed_txs(&self) -> Vec<&CompletedTransactionInfo> {
self.cached_data.completed_txs.iter().collect()
if self.completed_tx_filter == TransactionFilter::AbandonedCoinbases {
self.cached_data
.completed_txs
.iter()
.filter(|tx| !matches!(tx.status, TransactionStatus::CoinbaseNotInBlockChain))
.collect()
} else {
self.cached_data.completed_txs.iter().collect()
}
}

pub fn get_confirmations(&self, tx_id: TxId) -> Option<&u64> {
Expand Down Expand Up @@ -1033,7 +1050,7 @@ impl AppStateInner {
self.wallet
.set_base_node_peer(
peer.public_key.clone(),
peer.addresses.best().ok_or(UiError::NoAddress)?.address().clone(),
Some(peer.addresses.best().ok_or(UiError::NoAddress)?.address().clone()),
)
.await?;

Expand All @@ -1058,7 +1075,7 @@ impl AppStateInner {
self.wallet
.set_base_node_peer(
peer.public_key.clone(),
peer.addresses.best().ok_or(UiError::NoAddress)?.address().clone(),
Some(peer.addresses.best().ok_or(UiError::NoAddress)?.address().clone()),
)
.await?;

Expand Down Expand Up @@ -1096,7 +1113,7 @@ impl AppStateInner {
self.wallet
.set_base_node_peer(
previous.public_key.clone(),
previous.addresses.best().ok_or(UiError::NoAddress)?.address().clone(),
Some(previous.addresses.best().ok_or(UiError::NoAddress)?.address().clone()),
)
.await?;

Expand Down Expand Up @@ -1370,3 +1387,9 @@ impl Default for AppStateConfig {
}
}
}

#[derive(Clone, PartialEq)]
pub enum TransactionFilter {
None,
AbandonedCoinbases,
}
47 changes: 36 additions & 11 deletions applications/minotari_console_wallet/src/ui/state/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,18 +257,19 @@ pub async fn send_burn_transaction_task(
// burning minotari
// ----------------------------------------------------------------------------

let (burn_tx_id, original_proof) = transaction_service_handle
let (burn_tx_id, original_proof) = match transaction_service_handle
.burn_tari(amount, selection_criteria, fee_per_gram, message, claim_public_key)
.await
.map_err(|err| {
log::error!("failed to burn minotari: {:?}", err);

{
Ok((burn_tx_id, original_proof)) => (burn_tx_id, original_proof),
Err(e) => {
error!(target: LOG_TARGET, "failed to burn minotari: {:?}", e);
result_tx
.send(UiTransactionBurnStatus::Error(UiError::from(err).to_string()))
.send(UiTransactionBurnStatus::Error(format!("burn error: {}", e)))
.unwrap();
})
.unwrap();

return;
},
};
// ----------------------------------------------------------------------------
// starting a feedback loop to wait for the answer from the transaction service
// ----------------------------------------------------------------------------
Expand All @@ -292,14 +293,38 @@ pub async fn send_burn_transaction_task(
range_proof: original_proof.range_proof.0,
};

let serialized_proof =
serde_json::to_string_pretty(&wrapped_proof).expect("failed to serialize burn proof");
let serialized_proof = match serde_json::to_string_pretty(&wrapped_proof) {
Ok(proof) => proof,
Err(e) => {
error!(target: LOG_TARGET, "failed to serialize burn proof: {:?}", e);
result_tx
.send(UiTransactionBurnStatus::Error(format!(
"failure to create proof {:?}",
e
)))
.unwrap();
return;
},
};

let proof_id = random::<u32>();

let filepath =
burn_proof_filepath.unwrap_or_else(|| PathBuf::from(format!("{}.json", proof_id)));

std::fs::write(filepath, serialized_proof.as_bytes()).expect("failed to save burn proof");
match std::fs::write(filepath, serialized_proof.as_bytes()) {
Ok(()) => {},
Err(e) => {
error!(target: LOG_TARGET, "failed to write burn proof: {:?}", e);
result_tx
.send(UiTransactionBurnStatus::Error(format!(
"failure to write proof {:?}",
e
)))
.unwrap();
return;
},
};

let result = db.create_burnt_proof(
proof_id,
Expand Down
43 changes: 42 additions & 1 deletion base_layer/core/src/blocks/genesis_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub fn get_genesis_block(network: Network) -> ChainBlock {
NextNet => get_nextnet_genesis_block(),
Igor => get_igor_genesis_block(),
Esmeralda => get_esmeralda_genesis_block(),
LocalNet => get_esmeralda_genesis_block(),
LocalNet => get_localnet_genesis_block(),
}
}

Expand Down Expand Up @@ -321,6 +321,40 @@ fn get_esmeralda_genesis_block_raw() -> Block {
get_raw_block(&genesis_timestamp, &not_before_proof.to_vec())
}

pub fn get_localnet_genesis_block() -> ChainBlock {
// lets get the block
let block = crate::blocks::genesis_block::get_localnet_genesis_block_raw();
let accumulated_data = BlockHeaderAccumulatedData {
hash: block.hash(),
total_kernel_offset: block.header.total_kernel_offset.clone(),
achieved_difficulty: Difficulty::min(),
total_accumulated_difficulty: 1.into(),
accumulated_randomx_difficulty: AccumulatedDifficulty::min(),
accumulated_sha3x_difficulty: AccumulatedDifficulty::min(),
target_difficulty: Difficulty::min(),
};
ChainBlock::try_construct(Arc::new(block), accumulated_data).unwrap()
}

fn get_localnet_genesis_block_raw() -> Block {
// Set genesis timestamp
let genesis_timestamp = DateTime::parse_from_rfc2822("20 Feb 2024 08:01:00 +0200").expect("parse may not fail");
// Let us add a "not before" proof to the genesis block
let not_before_proof =
b"as I sip my drink, thoughts of esmeralda consume my mind, like a refreshing nourishing draught \
\
The New York Times , 2000/01/01 \
\
Lorem Ipsum \
\
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore \
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo \
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla \
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id \
est laborum.";
get_raw_block(&genesis_timestamp, &not_before_proof.to_vec())
}

fn get_raw_block(genesis_timestamp: &DateTime<FixedOffset>, not_before_proof: &[u8]) -> Block {
// Note: Use 'print_new_genesis_block_values' in core/tests/helpers/block_builders.rs to generate the required
// fields below
Expand Down Expand Up @@ -418,6 +452,13 @@ mod test {
check_block(Network::Igor, &block, 0, 0);
}

#[test]
fn localnet_genesis_sanity_check() {
// Note: If outputs and kernels are added, this test will fail unless you explicitly check that network == Igor
let block = get_localnet_genesis_block();
check_block(Network::LocalNet, &block, 0, 0);
}

fn check_block(network: Network, block: &ChainBlock, expected_outputs: usize, expected_kernels: usize) {
assert!(block.block().body.inputs().is_empty());
assert_eq!(block.block().body.kernels().len(), expected_kernels);
Expand Down
40 changes: 8 additions & 32 deletions base_layer/core/src/chain_storage/blockchain_database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2522,7 +2522,6 @@ mod test {
create_new_blockchain,
create_orphan_chain,
create_test_blockchain_db,
rewind_smt,
update_block_and_smt,
TempDatabase,
},
Expand Down Expand Up @@ -2602,11 +2601,9 @@ mod test {
])
.await;
// Create reorg chain
// we only need a smt, this one will not be technically correct, but due to the use of mockvalidators(true),
// they will pass all mr tests
let mut smt = db.fetch_tip_smt().unwrap();
let d_block = mainchain.get("D").unwrap().clone();
rewind_smt(d_block, &mut smt);
let c_block = mainchain.get("C").unwrap().clone();
rewind_smt(c_block, &mut smt);
let fork_root = mainchain.get("B").unwrap().clone();
let (_, reorg_chain) = create_orphan_chain(
&db,
Expand Down Expand Up @@ -2722,7 +2719,6 @@ mod test {
#[tokio::test]
async fn it_correctly_detects_strongest_orphan_tips() {
let db = create_new_blockchain();
let mut gen_smt = db.fetch_tip_smt().unwrap();
let validator = MockValidator::new(true);
let (_, main_chain) = create_main_chain(&db, &[
("A->GB", 1, 120),
Expand All @@ -2737,20 +2733,9 @@ mod test {

// Fork 1 (with 3 blocks)
let fork_root_1 = main_chain.get("A").unwrap().clone();
// we only need a smt, this one will not be technically correct, but due to the use of mockvalidators(true),
// they will pass all mr tests
let mut smt = db.fetch_tip_smt().unwrap();
let g_block = main_chain.get("G").unwrap().clone();
rewind_smt(g_block, &mut smt);
let f_block = main_chain.get("F").unwrap().clone();
rewind_smt(f_block, &mut smt);
let e_block = main_chain.get("E").unwrap().clone();
rewind_smt(e_block, &mut smt);
let d_block = main_chain.get("D").unwrap().clone();
rewind_smt(d_block, &mut smt);
let c_block = main_chain.get("C").unwrap().clone();
rewind_smt(c_block, &mut smt);
let mut c_smt = smt.clone();
let b_block = main_chain.get("B").unwrap().clone();
rewind_smt(b_block, &mut smt);

let (_, orphan_chain_1) = create_chained_blocks(
&[("B2->GB", 1, 120), ("C2->B2", 1, 120), ("D2->C2", 1, 120)],
Expand All @@ -2761,11 +2746,11 @@ mod test {

// Fork 2 (with 1 block)
let fork_root_2 = main_chain.get("GB").unwrap().clone();
let (_, orphan_chain_2) = create_chained_blocks(&[("B3->GB", 1, 120)], fork_root_2, &mut gen_smt).await;
let (_, orphan_chain_2) = create_chained_blocks(&[("B3->GB", 1, 120)], fork_root_2, &mut smt).await;

// Fork 3 (with 1 block)
let fork_root_3 = main_chain.get("B").unwrap().clone();
let (_, orphan_chain_3) = create_chained_blocks(&[("B4->GB", 1, 120)], fork_root_3, &mut c_smt).await;
let (_, orphan_chain_3) = create_chained_blocks(&[("B4->GB", 1, 120)], fork_root_3, &mut smt).await;

// Add blocks to db
let mut access = db.db_write_access().unwrap();
Expand Down Expand Up @@ -2852,13 +2837,6 @@ mod test {
)
.await;

let b6_block = main_chain.get("6b").unwrap().clone();
rewind_smt(b6_block, &mut smt);
let b5_block = main_chain.get("5b").unwrap().clone();
rewind_smt(b5_block, &mut smt);
let b4_block = main_chain.get("4b").unwrap().clone();
rewind_smt(b4_block, &mut smt);

// Add orphans out of height order
for name in ["5b", "3b", "4b", "6b"] {
let block = orphan_chain_b.get(name).unwrap();
Expand All @@ -2875,8 +2853,6 @@ mod test {
)
.await;

let c7_block = main_chain.get("7c").unwrap().clone();
rewind_smt(c7_block, &mut smt);
for name in ["7c", "5c", "6c", "4c"] {
let block = orphan_chain_c.get(name).unwrap();
let result = test.handle_possible_reorg(block.to_arc_block()).unwrap();
Expand Down Expand Up @@ -3270,9 +3246,9 @@ mod test {

let mock_validator = MockValidator::new(true);
let chain_strength_comparer = strongest_chain().by_sha3x_difficulty().build();
// we only need a smt, this one will not be technically correct, but due to the use of mockvalidators(true),
// they will pass all mr tests
let mut smt = db.fetch_tip_smt().unwrap();
let d_block = mainchain.get("D").unwrap().clone();
rewind_smt(d_block, &mut smt);
let fork_block = mainchain.get("C").unwrap().clone();
let (_, reorg_chain) =
create_chained_blocks(&[("D2->GB", 1, 120), ("E2->D2", 2, 120)], fork_block, &mut smt).await;
Expand Down
16 changes: 0 additions & 16 deletions base_layer/core/src/chain_storage/tests/blockchain_database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,22 +477,6 @@ mod prepare_new_block {
mod fetch_header_containing_kernel_mmr {
use super::*;
use crate::transactions::key_manager::create_memory_db_key_manager;

#[test]
fn it_returns_genesis() {
let db = setup();
let genesis = db.fetch_block(0, true).unwrap();
assert_eq!(genesis.block().body.kernels().len(), 1);
let mut mmr_position = 0;
genesis.block().body.kernels().iter().for_each(|_| {
let header = db.fetch_header_containing_kernel_mmr(mmr_position).unwrap();
assert_eq!(header.height(), 0);
mmr_position += 1;
});
let err = db.fetch_header_containing_kernel_mmr(mmr_position).unwrap_err();
matches!(err, ChainStorageError::ValueNotFound { .. });
}

#[tokio::test]
async fn it_returns_corresponding_header() {
let db = setup();
Expand Down
2 changes: 1 addition & 1 deletion base_layer/core/src/consensus/consensus_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ impl ConsensusConstants {
max_randomx_seed_height: u64::MAX,
max_extra_field_size: 200,
proof_of_work: algos,
faucet_value: ESMERALDA_FAUCET_VALUE.into(), // The esmeralda genesis block is re-used for localnet
faucet_value: 0.into(),
transaction_weight: TransactionWeight::latest(),
max_script_byte_size: 2048,
input_version_range,
Expand Down
Loading

0 comments on commit 65dd095

Please sign in to comment.