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
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@

# Set to true to enable auto registration for each epoch (default = true)
#auto_register = true
[validator_node.consensus]
# Disable evictions for now
enable_eviction_proposal = false

#[validator_node.database]
## The type of database ("rocksdb" or "sqlite") to use (default = "sqlite")
Expand Down
1 change: 1 addition & 0 deletions applications/tari_validator_node/src/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ pub async fn spawn_services(
let signing_service = consensus::TariSignatureService::new(keypair.clone());
let (consensus_join_handle, consensus_handle) = consensus::spawn(
config.network,
&config.validator_node.consensus,
sidechain_id,
state_store.clone(),
local_address,
Expand Down
20 changes: 20 additions & 0 deletions applications/tari_validator_node/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ pub struct ValidatorNodeConfig {
pub burnt_utxo_sidechain_id: Option<RistrettoPublicKey>,
/// The path to store layer-one transactions.
pub layer_one_transaction_path: PathBuf,
/// Consensus configuration
pub consensus: ConsensusConfig,
}

impl ValidatorNodeConfig {
Expand Down Expand Up @@ -159,6 +161,7 @@ impl Default for ValidatorNodeConfig {
template_sidechain_id: None,
burnt_utxo_sidechain_id: None,
layer_one_transaction_path: PathBuf::from("data/layer_one_transactions"),
consensus: ConsensusConfig::default(),
}
}
}
Expand All @@ -168,3 +171,20 @@ impl SubConfigPath for ValidatorNodeConfig {
"validator_node"
}
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct ConsensusConfig {
/// Enable proposing evictions for inactive validators. If disabled, this validator will still vote on eviction
/// proposals from other validators, including voting in the affirmative if applicable, but will never propose
/// evictions itself.
pub enable_eviction_proposal: bool,
}

impl Default for ConsensusConfig {
fn default() -> Self {
Self {
enable_eviction_proposal: true,
}
}
}
4 changes: 3 additions & 1 deletion applications/tari_validator_node/src/consensus/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ use tari_consensus::{consensus_constants::ConsensusConstants, hotstuff::Hotstuff
use tari_template_lib::prelude::RistrettoPublicKeyBytes;
use tari_template_manager::interface::TemplateManagerHandle;

use crate::{consensus::spec::ValidatorNodeStateStore, p2p::NopLogger};
use crate::{config::ConsensusConfig, consensus::spec::ValidatorNodeStateStore, p2p::NopLogger};

pub type ConsensusTransactionValidator = BoxedValidator<ValidationContext, Transaction, TransactionValidationError>;

pub async fn spawn(
network: Network,
consensus_config: &ConsensusConfig,
sidechain_id: Option<RistrettoPublicKeyBytes>,
store: ValidatorNodeStateStore,
local_addr: PeerAddress,
Expand Down Expand Up @@ -80,6 +81,7 @@ pub async fn spawn(
// TODO: make these configurable (defaults should probably be longer than 1 hour)
state_tree_cleanup_interval: Duration::from_secs(60 * 60),
epoch_gc_interval: Duration::from_secs(60 * 60),
enable_eviction_proposal: consensus_config.enable_eviction_proposal,
};

let hotstuff_worker = HotstuffWorker::<TariConsensusSpec>::new(
Expand Down
7 changes: 7 additions & 0 deletions applications/tari_walletd/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,13 @@ pub enum Subcommand {
#[clap(long, alias = "output", short = 'o')]
output_path: Option<PathBuf>,
},
#[clap(about = "Generate a key to use for resources with viewable balances")]
NewViewableBalanceKey {
#[clap(long, alias = "key")]
key_index: u64,
#[clap(long, alias = "output", short = 'o')]
output_path: Option<PathBuf>,
},
#[clap(
name = "seed-words",
about = "Get current seed words of wallet (used for wallet retrieval)"
Expand Down
1 change: 1 addition & 0 deletions applications/tari_walletd/src/handlers/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -972,6 +972,7 @@ pub async fn handle_stealth_transfer(
input_selection: req.input_selection,
resource_address: req.resource_address,
max_fee: req.max_fee,
badge_usage: req.badge_usage,
outputs: req
.transfers
.into_iter()
Expand Down
42 changes: 25 additions & 17 deletions applications/tari_walletd/src/handlers/stealth_utxos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use tari_wallet_daemon_client::{
UtxoInfo,
},
};
use tokio::{task::block_in_place, time::Instant};
use tokio::{task::spawn_blocking, time::Instant};

use crate::handlers::{helpers::invalid_params, HandlerContext};

Expand Down Expand Up @@ -99,29 +99,37 @@ pub async fn handle_decrypt_value(
.collect::<IndexMap<_, _>>();

let timer = Instant::now();
let balances = match context.config().value_lookup_table_file.as_ref() {
let elgamal_proofs = proofs.values().copied().cloned().collect::<Vec<_>>();
let sdk = sdk.clone();
let balances = match context.config().value_lookup_table_file.clone() {
Some(file) => {
let mut file = fs::File::open(file)
.map_err(|e| anyhow!("Unable to load value lookup file '{}': {e}", file.display()))?;
let mut lookup = IoReaderValueLookup::load(&mut file)?;
spawn_blocking(move || {
let mut file = fs::File::open(&file)
.map_err(|e| anyhow!("Unable to load value lookup file '{}': {e}", file.display()))?;
let mut lookup = IoReaderValueLookup::load(&mut file)?;

block_in_place(|| {
sdk.viewable_balance_api().try_brute_force_commitment_balances(
let balance = sdk.viewable_balance_api().try_brute_force_commitment_balances(
&view_key.key,
proofs.values().copied(), // Copying the reference, not the ElgamalVerifiableBalanceBytes
elgamal_proofs.iter(),
value_range,
&mut lookup,
)?;

anyhow::Ok(balance)
})
.await??
},
None => {
spawn_blocking(move || {
sdk.viewable_balance_api().try_brute_force_commitment_balances(
&view_key.key,
elgamal_proofs.iter(),
value_range,
&mut AlwaysMissLookupTable,
)
})?
})
.await??
},
None => block_in_place(|| {
sdk.viewable_balance_api().try_brute_force_commitment_balances(
&view_key.key,
proofs.values().copied(),
value_range,
&mut AlwaysMissLookupTable,
)
})?,
};

info!(target: LOG_TARGET, "Brute force balance lookup took {:.2?}", timer.elapsed());
Expand Down
37 changes: 37 additions & 0 deletions applications/tari_walletd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,43 @@ async fn main() -> Result<(), anyhow::Error> {

return Ok(());
},
Some(Subcommand::NewViewableBalanceKey { key_index, output_path }) => {
let wallet_store = init_wallet_store(&config)?;
let mut sdk = initialize_wallet_sdk(&config, wallet_store)?;
sdk.initialize_cipher_seed(
cli.wallet_restore
.seed_words
.as_ref()
.map(CipherSeedRestore::FromSeedWords)
.unwrap_or_default(),
)?;
let km = sdk.key_manager_api();
let key = km.get_elgamal_encrypted_view_key(*key_index)?;
let public_key = key.to_public_key().to_byte_type();

let json = json!({
"viewable_balance_public_key": public_key,
"viewable_balance_private_key": hex::encode(key.key.as_bytes()),
"key_index": key_index,
});
match output_path {
Some(path) => {
let mut file = fs::File::options()
.create(true)
.write(true)
.truncate(true)
.open(path)
.context("failed to open file for writing")?;
serde_json::to_writer_pretty(&mut file, &json).context("failed to encode key json to file")?;
println!("Key written to {}", path.display());
},
None => {
println!("{}", json);
},
}

return Ok(());
},
Some(Subcommand::SeedWords) => {
let wallet_store = init_wallet_store(&config)?;
let mut sdk = initialize_wallet_sdk(&config, wallet_store)?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ import { useAccountsGetBalances, useAccountsTransfer } from "@api/hooks/useAccou
import useAccountStore from "@store/accountStore";
import { SelectChangeEvent } from "@mui/material/Select/Select";
import {
BadgeUsage,
BalanceEntry,
ConfidentialTransferInputSelection,
rejectReasonToString,
ResourceAddress,
ResourceType,
substateIdToString,
Expand Down Expand Up @@ -195,7 +197,7 @@ export function SendMoneyDialog(props: SendMoneyDialogProps) {
resourceType: props.resource_type,
output_to_revealed: !transferFormState.outputToConfidential,
input_selection: transferFormState.inputSelection as ConfidentialTransferInputSelection,
badge: transferFormState.badge,
badge_usage: transferFormState.badge ? { Resource: transferFormState.badge } : ("None" as BadgeUsage),
output_memo: transferFormState.memo ? { Message: transferFormState.memo } : undefined,
};

Expand All @@ -206,11 +208,11 @@ export function SendMoneyDialog(props: SendMoneyDialogProps) {
if (!transactionResult) {
throw new Error("Fee estimation failed");
}
if ("Rejected" in transactionResult) {
throw new Error(`Transaction rejected: ${transactionResult.Rejected}`);
if ("Reject" in transactionResult) {
throw new Error(`Transaction rejected: ${rejectReasonToString(transactionResult.Reject)}`);
}
if ("AcceptFeeRejectRest" in transactionResult) {
throw new Error(`Transaction rejected: ${transactionResult.AcceptFeeRejectRest[1]}`);
throw new Error(`Transaction rejected: ${rejectReasonToString(transactionResult.AcceptFeeRejectRest[1])}`);
}

let fee = resp.final_fee;
Expand Down Expand Up @@ -270,7 +272,8 @@ export function SendMoneyDialog(props: SendMoneyDialogProps) {
resourceType: props.resource_type,
output_to_revealed: !transferFormState.outputToConfidential,
input_selection: transferFormState.inputSelection as ConfidentialTransferInputSelection,
badge: transferFormState.badge,
// TODO: support for other types of BadgeUsage
badge_usage: transferFormState.badge ? { Resource: transferFormState.badge } : ("None" as BadgeUsage),
output_memo: transferFormState.memo ? { Message: transferFormState.memo } : undefined,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,6 @@ export default function FormStep({
}
placeholder={isEstimatingFee ? "Estimating..." : "Auto-calculated"}
onChange={onFormValueChange}
disabled={true}
style={{ flexGrow: 1 }}
InputProps={{
endAdornment:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Copyright 2022. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import Typography from "@mui/material/Typography";
import TextField from "@mui/material/TextField";
import { useState } from "react";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import { useTheme } from "@mui/material/styles";
import { Divider } from "@mui/material";
import { stealthDecryptUtxoBalance } from "../../../utils/json_rpc";
import { StealthUtxosDecryptValueRequest } from "@tari-project/typescript-bindings";

function DecryptUtxoBalanceForm() {
const [formState, setFormState] = useState({
resourceAddress: null,
utxoId: null,
minimumExpectedValue: null,
maximumExpectedValue: null,
keyId: 0,
});
const [balance, setBalance] = useState<any>(null);

const onViewBalanceClicked = async () => {
const resp = await stealthDecryptUtxoBalance({
resource_address: formState.resourceAddress!,
ids: [formState.utxoId!],
minimum_expected_value: formState.minimumExpectedValue ? BigInt(formState.minimumExpectedValue) : null,
maximum_expected_value: formState.maximumExpectedValue ? BigInt(formState.maximumExpectedValue) : null,
view_key_id: BigInt(formState.keyId),
} as StealthUtxosDecryptValueRequest);

setBalance(resp);
};

const balances =
balance &&
Object.keys(balance?.balances).map((key) => {
return (
<Box key={key}>
<Typography>
{key}: {balance.balances[key] || "Failed not decrypt value"}
</Typography>
</Box>
);
});

const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormState({
...formState,
[e.target.name]: e.target.value,
});
};

return (
<>
<Box className="flex-container" sx={{ marginBottom: 4 }}>
<TextField name="keyId" label="Key ID" value={formState.keyId} onChange={onChange} style={{ flexGrow: 1 }} />
<TextField
name="resourceAddress"
label="Resource Address"
value={formState.resourceAddress}
onChange={onChange}
style={{ flexGrow: 1 }}
/>
<TextField name="utxoId" label="UTXO ID" value={formState.utxoId} onChange={onChange} style={{ flexGrow: 1 }} />
<TextField
name="minimumExpectedValue"
label="Minimum Expected Value"
value={formState.minimumExpectedValue}
onChange={onChange}
style={{ flexGrow: 1 }}
/>
<TextField
name="maximumExpectedValue"
label="Maximum Expected Value"
value={formState.maximumExpectedValue}
onChange={onChange}
style={{ flexGrow: 1 }}
/>

<Button variant="contained" onClick={onViewBalanceClicked} disabled={!formState.resourceAddress}>
Decrypt
</Button>
</Box>
{balances && (
<>
<Typography variant="h3">Balances</Typography>
{balances}
</>
)}
</>
);
}

function DecryptUtxoBalance() {
const theme = useTheme();
return (
<Box
style={{
display: "flex",
flexDirection: "column",
gap: theme.spacing(3),
paddingTop: theme.spacing(3),
}}
>
<p>
Brute force a UTXO balance using a secret view key. This applies to resources that have the view key enabled.
</p>
<Box>
<DecryptUtxoBalanceForm />
</Box>
<Divider />
</Box>
);
}

export default DecryptUtxoBalance;
Loading
Loading