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: contract acceptance signatures are submitted and validated #4269

Merged
merged 17 commits into from
Jul 7, 2022
Merged
Show file tree
Hide file tree
Changes from 11 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
34 changes: 11 additions & 23 deletions applications/tari_validator_node/src/contract_worker_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,17 @@ use std::{
};

use log::*;
use rand::rngs::OsRng;
use tari_common_types::types::{FixedHash, FixedHashSizeError, HashDigest, PrivateKey, Signature};
use tari_common_types::types::{FixedHash, FixedHashSizeError};
use tari_comms::{types::CommsPublicKey, NodeIdentity};
use tari_comms_dht::Dht;
use tari_core::{consensus::ConsensusHashWriter, transactions::transaction_components::ContractConstitution};
use tari_crypto::{
keys::SecretKey,
tari_utilities::{hex::Hex, message_format::MessageFormat, ByteArray},
};
use tari_core::transactions::transaction_components::ContractConstitution;
use tari_crypto::tari_utilities::{hex::Hex, message_format::MessageFormat, ByteArray};
use tari_dan_core::{
models::{AssetDefinition, BaseLayerMetadata, Committee},
services::{
AcceptanceManager,
BaseNodeClient,
ConcreteAcceptanceManager,
ConcreteAssetProcessor,
ConcreteCheckpointManager,
ConcreteCommitteeManager,
Expand All @@ -49,7 +47,6 @@ use tari_dan_core::{
NodeIdentitySigningService,
TariDanPayloadProcessor,
TariDanPayloadProvider,
WalletClient,
},
storage::{
global::{ContractState, GlobalDb, GlobalDbMetadataKey},
Expand Down Expand Up @@ -88,7 +85,7 @@ pub struct ContractWorkerManager {
last_scanned_height: u64,
last_scanned_hash: Option<FixedHash>,
base_node_client: GrpcBaseNodeClient,
wallet_client: GrpcWalletClient,
acceptance_manager: ConcreteAcceptanceManager<GrpcWalletClient, GrpcBaseNodeClient>,
identity: Arc<NodeIdentity>,
active_workers: HashMap<FixedHash, Arc<AtomicBool>>,
mempool: MempoolServiceHandle,
Expand All @@ -113,7 +110,7 @@ impl ContractWorkerManager {
identity: Arc<NodeIdentity>,
global_db: GlobalDb<SqliteGlobalDbBackendAdapter>,
base_node_client: GrpcBaseNodeClient,
wallet_client: GrpcWalletClient,
acceptance_manager: ConcreteAcceptanceManager<GrpcWalletClient, GrpcBaseNodeClient>,
mempool: MempoolServiceHandle,
handles: ServiceHandles,
subscription_factory: SubscriptionFactory,
Expand All @@ -126,7 +123,7 @@ impl ContractWorkerManager {
last_scanned_height: 0,
last_scanned_hash: None,
base_node_client,
wallet_client,
acceptance_manager,
identity,
mempool,
handles,
Expand Down Expand Up @@ -444,13 +441,10 @@ impl ContractWorkerManager {
}

async fn post_contract_acceptance(&mut self, contract: &ActiveContract) -> Result<(), WorkerManagerError> {
let nonce = PrivateKey::random(&mut OsRng);
let challenge = generate_constitution_challenge(&contract.constitution);
let signature = Signature::sign(self.identity.secret_key().clone(), nonce, challenge.as_slice()).unwrap();
let mut acceptance_manager = self.acceptance_manager.clone();

let tx_id = self
.wallet_client
.submit_contract_acceptance(&contract.contract_id, self.identity.public_key(), &signature)
let tx_id = acceptance_manager
.publish_acceptance(&self.identity, &contract.contract_id)
.await?;
info!(
"Contract {} acceptance submitted with id={}",
Expand All @@ -474,12 +468,6 @@ impl ContractWorkerManager {
}
}

fn generate_constitution_challenge(constitution: &ContractConstitution) -> [u8; 32] {
ConsensusHashWriter::new(HashDigest::with_params(&[], &[], b"tari/vn/constsig"))
.chain(constitution)
.finalize()
}

#[derive(Debug, thiserror::Error)]
pub enum WorkerManagerError {
#[error(transparent)]
Expand Down
8 changes: 6 additions & 2 deletions applications/tari_validator_node/src/dan_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ use std::sync::Arc;

use tari_common::exit_codes::{ExitCode, ExitError};
use tari_comms::NodeIdentity;
use tari_dan_core::{services::MempoolServiceHandle, storage::global::GlobalDb};
use tari_dan_core::{
services::{ConcreteAcceptanceManager, MempoolServiceHandle},
storage::global::GlobalDb,
};
use tari_dan_storage_sqlite::{global::SqliteGlobalDbBackendAdapter, SqliteDbFactory};
use tari_p2p::comms_connector::SubscriptionFactory;
use tari_service_framework::ServiceHandles;
Expand Down Expand Up @@ -68,12 +71,13 @@ impl DanNode {
) -> Result<(), ExitError> {
let base_node_client = GrpcBaseNodeClient::new(self.config.base_node_grpc_address);
let wallet_client = GrpcWalletClient::new(self.config.wallet_grpc_address);
let acceptance_manager = ConcreteAcceptanceManager::new(wallet_client, base_node_client.clone());
let workers = ContractWorkerManager::new(
self.config.clone(),
self.identity.clone(),
self.global_db.clone(),
base_node_client,
wallet_client,
acceptance_manager,
mempool_service,
handles,
subscription_factory,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use tari_common_types::types::PublicKey;
use tari_dan_core::{
models::{domain_events::ConsensusWorkerDomainEvent, TariDanPayload},
services::{
ConcreteAcceptanceManager,
ConcreteAssetProcessor,
ConcreteAssetProxy,
ConcreteCheckpointManager,
Expand Down Expand Up @@ -57,6 +58,7 @@ use crate::{
pub struct DefaultServiceSpecification;

impl ServiceSpecification for DefaultServiceSpecification {
type AcceptanceManager = ConcreteAcceptanceManager<Self::WalletClient, Self::BaseNodeClient>;
type Addr = PublicKey;
type AssetProcessor = ConcreteAssetProcessor;
type AssetProxy = ConcreteAssetProxy<Self>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,37 @@ impl BaseNodeClient for GrpcBaseNodeClient {
.collect()
}

async fn get_contract_utxos(
mrnaveira marked this conversation as resolved.
Show resolved Hide resolved
&mut self,
contract_id: FixedHash,
output_type: OutputType,
) -> Result<Vec<UtxoMinedInfo>, DigitalAssetError> {
let conn = self.connection().await?;
let request = grpc::GetCurrentContractOutputsRequest {
contract_id: contract_id.to_vec(),
output_type: u32::from(output_type.as_byte()),
};
let result = conn.get_current_contract_outputs(request).await?.into_inner();

let mut outputs = vec![];
for mined_info in result.outputs {
let output = mined_info
.output
.map(TryInto::try_into)
.transpose()
.map_err(DigitalAssetError::ConversionError)?
.ok_or_else(|| DigitalAssetError::InvalidPeerMessage("Mined info contained no output".to_string()))?;

outputs.push(UtxoMinedInfo {
output: PrunedOutput::NotPruned { output },
mmr_position: mined_info.mmr_position,
mined_height: mined_info.mined_height,
header_hash: mined_info.header_hash,
});
}
Ok(outputs)
}

async fn get_constitutions(
&mut self,
start_block_hash: Option<FixedHash>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use tari_common_types::types::{FixedHash, PublicKey, Signature};
use tari_comms::NodeIdentity;
use tari_crypto::tari_utilities::ByteArray;
use tari_dan_core::{
services::{AssetProcessor, AssetProxy, ServiceSpecification, WalletClient},
services::{AcceptanceManager, AssetProcessor, AssetProxy, ServiceSpecification, WalletClient},
storage::DbFactory,
};
use tari_dan_engine::instructions::Instruction;
Expand All @@ -45,6 +45,7 @@ pub struct ValidatorNodeGrpcServer<TServiceSpecification: ServiceSpecification>
asset_processor: TServiceSpecification::AssetProcessor,
asset_proxy: TServiceSpecification::AssetProxy,
wallet_client: TServiceSpecification::WalletClient,
acceptance_manager: TServiceSpecification::AcceptanceManager,
}

impl<TServiceSpecification: ServiceSpecification> ValidatorNodeGrpcServer<TServiceSpecification> {
Expand All @@ -54,13 +55,15 @@ impl<TServiceSpecification: ServiceSpecification> ValidatorNodeGrpcServer<TServi
asset_processor: TServiceSpecification::AssetProcessor,
asset_proxy: TServiceSpecification::AssetProxy,
wallet_client: TServiceSpecification::WalletClient,
acceptance_manager: TServiceSpecification::AcceptanceManager,
) -> Self {
Self {
node_identity,
db_factory,
asset_processor,
asset_proxy,
wallet_client,
acceptance_manager,
}
}
}
Expand All @@ -75,15 +78,13 @@ impl<TServiceSpecification: ServiceSpecification + 'static> rpc::validator_node_
&self,
request: tonic::Request<rpc::PublishContractAcceptanceRequest>,
) -> Result<Response<rpc::PublishContractAcceptanceResponse>, tonic::Status> {
let mut wallet_client = self.wallet_client.clone();
let mut acceptance_manager = self.acceptance_manager.clone();
let request = request.into_inner();
let contract_id =
FixedHash::try_from(request.contract_id).map_err(|err| tonic::Status::invalid_argument(err.to_string()))?;
let validator_node_public_key = self.node_identity.public_key();
let signature = Signature::default();

match wallet_client
.submit_contract_acceptance(&contract_id, validator_node_public_key, &signature)
match acceptance_manager
.publish_acceptance(&self.node_identity, &contract_id)
.await
{
Ok(tx_id) => Ok(Response::new(rpc::PublishContractAcceptanceResponse {
Expand Down
13 changes: 11 additions & 2 deletions applications/tari_validator_node/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,13 @@ use tari_comms::{
};
use tari_comms_dht::Dht;
use tari_dan_core::{
services::{ConcreteAssetProcessor, ConcreteAssetProxy, MempoolServiceHandle, ServiceSpecification},
services::{
ConcreteAcceptanceManager,
ConcreteAssetProcessor,
ConcreteAssetProxy,
MempoolServiceHandle,
ServiceSpecification,
},
storage::{global::GlobalDb, DbFactory},
};
use tari_dan_storage_sqlite::{global::SqliteGlobalDbBackendAdapter, SqliteDbFactory};
Expand Down Expand Up @@ -141,20 +147,23 @@ async fn run_node(config: &ApplicationConfig) -> Result<(), ExitError> {
let asset_processor = ConcreteAssetProcessor::default();
let validator_node_client_factory =
TariCommsValidatorNodeClientFactory::new(handles.expect_handle::<Dht>().dht_requester());
let base_node_client = GrpcBaseNodeClient::new(config.validator_node.base_node_grpc_address);
let asset_proxy: ConcreteAssetProxy<DefaultServiceSpecification> = ConcreteAssetProxy::new(
GrpcBaseNodeClient::new(config.validator_node.base_node_grpc_address),
base_node_client.clone(),
validator_node_client_factory,
5,
mempool_service.clone(),
db_factory.clone(),
);
let wallet_client = GrpcWalletClient::new(config.validator_node.wallet_grpc_address);
let acceptance_manager = ConcreteAcceptanceManager::new(wallet_client.clone(), base_node_client);
let grpc_server: ValidatorNodeGrpcServer<DefaultServiceSpecification> = ValidatorNodeGrpcServer::new(
node_identity.as_ref().clone(),
db_factory.clone(),
asset_processor,
asset_proxy,
wallet_client,
acceptance_manager,
);

if let Some(address) = config.validator_node.grpc_address.clone() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// 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.

use digest::Digest;
use tari_common_types::types::{Commitment, FixedHash, HashDigest};
use tari_utilities::ByteArray;

#[derive(Debug, Clone, Copy)]
pub struct ContractAcceptanceChallenge(FixedHash);

impl ContractAcceptanceChallenge {
pub fn new(constiution_commitment: &Commitment, contract_id: &FixedHash) -> Self {
// TODO: Use new tari_crypto domain-separated hashing
let hash = HashDigest::new()
.chain(constiution_commitment.as_bytes())
.chain(contract_id.as_slice())
.finalize()
.into();
Self(hash)
}
}

impl AsRef<[u8]> for ContractAcceptanceChallenge {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
mod contract_acceptance;
pub use contract_acceptance::ContractAcceptance;

mod contract_acceptance_challenge;
pub use contract_acceptance_challenge::ContractAcceptanceChallenge;

mod contract_constitution;
pub use contract_constitution::{
CheckpointParameters,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

use std::io;

use digest::Digest;
use digest::{Digest, Output};
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
use tari_common_types::types::{HashDigest, PrivateKey, PublicKey, Signature};
Expand All @@ -45,15 +45,30 @@ impl SignerSignature {
pub fn sign<C: AsRef<[u8]>>(signer_secret: &PrivateKey, challenge: C) -> Self {
let signer = PublicKey::from_secret_key(signer_secret);
let (nonce, public_nonce) = PublicKey::random_keypair(&mut OsRng);

let final_challenge = Self::build_final_challenge(&signer, challenge, &public_nonce);
let signature =
Signature::sign(signer_secret.clone(), nonce, &*final_challenge).expect("challenge is the correct length");
Self { signer, signature }
}

pub fn verify<C: AsRef<[u8]>>(signature: &Signature, signer: &PublicKey, challenge: C) -> bool {
let public_nonce = signature.get_public_nonce();
let final_challenge = Self::build_final_challenge(signer, challenge, public_nonce);
signature.verify_challenge(signer, &final_challenge)
}

fn build_final_challenge<C: AsRef<[u8]>>(
signer: &PublicKey,
challenge: C,
public_nonce: &PublicKey,
) -> Output<HashDigest> {
// TODO: Use domain-seperated hasher from tari_crypto
let final_challenge = HashDigest::new()
HashDigest::new()
.chain(signer.as_bytes())
.chain(public_nonce.as_bytes())
.chain(challenge)
.finalize();
let signature =
Signature::sign(signer_secret.clone(), nonce, &*final_challenge).expect("challenge is the correct length");
Self { signer, signature }
.finalize()
}

pub fn signer(&self) -> &PublicKey {
Expand Down
Loading