Skip to content

Commit

Permalink
feat(engine)!: owner and resource-based access rules
Browse files Browse the repository at this point in the history
  • Loading branch information
sdbondi committed Oct 26, 2023
1 parent 3b32a82 commit b788655
Show file tree
Hide file tree
Showing 124 changed files with 4,421 additions and 1,191 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ where TTemplateProvider: TemplateProvider<Template = LoadedTemplate>
};

let initial_cost = 0;
let modules: Vec<Arc<dyn RuntimeModule<TTemplateProvider>>> =
vec![Arc::new(FeeModule::new(initial_cost, self.fee_table.clone()))];
let modules: Vec<Arc<dyn RuntimeModule>> = vec![Arc::new(FeeModule::new(initial_cost, self.fee_table.clone()))];

let processor = TransactionProcessor::new(
self.template_provider.clone(),
Expand All @@ -80,7 +79,7 @@ where TTemplateProvider: TemplateProvider<Template = LoadedTemplate>
let result = match processor.execute(transaction.clone()) {
Ok(result) => result,
Err(err) => ExecuteResult {
finalize: FinalizeResult::new_rejectted(tx_id, RejectReason::ExecutionFailure(err.to_string())),
finalize: FinalizeResult::new_rejected(tx_id, RejectReason::ExecutionFailure(err.to_string())),
transaction_failure: None,
fee_receipt: None,
},
Expand Down
94 changes: 46 additions & 48 deletions applications/tari_dan_wallet_daemon/src/services/account_monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use tari_dan_wallet_sdk::{
DanWalletSdk,
};
use tari_engine_types::{
indexed_value::{IndexedValue, IndexedValueVisitorError},
indexed_value::{IndexedValue, IndexedValueError},
non_fungible::NonFungibleContainer,
resource::Resource,
substate::{Substate, SubstateAddress, SubstateDiff, SubstateValue},
Expand Down Expand Up @@ -261,63 +261,61 @@ where
account_addr,
balance
);
if let Some(outputs) = vault.get_confidential_outputs() {
if let Some(commitments) = vault.get_confidential_commitments() {
info!(
target: LOG_TARGET,
"🔒️ vault {} in account {} has {} confidential outputs",
"🔒️ vault {} in account {} has {} confidential commitments",
vault.vault_id(),
account_addr,
outputs.len()
commitments.len()
);
self.wallet_sdk
.confidential_outputs_api()
.verify_and_update_confidential_outputs(account_addr, &vault_addr, outputs)?;
.verify_and_update_confidential_outputs(account_addr, &vault_addr, commitments.values())?;
}

if let Some(nft_ids) = vault.get_non_fungible_ids() {
for id in nft_ids {
let nft = match nfts.get(id) {
Some(nft) => *nft,
None => {
error!(
target: LOG_TARGET,
"NonFungible ID {} is found in the vault, but not found in substate diff", id
);
continue;
},
};
for id in vault.get_non_fungible_ids() {
let nft = match nfts.get(id) {
Some(nft) => *nft,
None => {
error!(
target: LOG_TARGET,
"NonFungible ID {} is found in the vault, but not found in substate diff", id
);
continue;
},
};

let is_burned = nft.contents().is_none();
let nft_contents = if let Some(contents) = nft.contents() {
contents
} else {
// TODO: in this case, we are burning an nft, make sure to update the database in that case`
let is_burned = nft.contents().is_none();
let nft_contents = if let Some(contents) = nft.contents() {
contents
} else {
// TODO: in this case, we are burning an nft, make sure to update the database in that case`
continue;
};
let metadata = match nft_contents.decode_data() {
Ok(data) => data,
Err(e) => {
error!(
target: LOG_TARGET,
"Failed to decode non fungible metadata, with error: {}", e
);
continue;
};
let metadata = match nft_contents.decode_data() {
Ok(data) => data,
Err(e) => {
error!(
target: LOG_TARGET,
"Failed to decode non fungible metadata, with error: {}", e
);
continue;
},
};
let resource_address = vault.resource_address();
let resource = self.fetch_resource(*resource_address).await?;
let token_symbol = resource.token_symbol();

let non_fungible = NonFungibleToken {
is_burned,
vault_id: *vault.vault_id(),
nft_id: id.clone(),
metadata,
token_symbol: String::from(token_symbol),
};

non_fungibles_api.store_new_nft(&non_fungible)?;
}
},
};
let resource_address = vault.resource_address();
let resource = self.fetch_resource(*resource_address).await?;
let token_symbol = resource.token_symbol();

let non_fungible = NonFungibleToken {
is_burned,
vault_id: *vault.vault_id(),
nft_id: id.clone(),
metadata,
token_symbol: String::from(token_symbol),
};

non_fungibles_api.store_new_nft(&non_fungible)?;
}
Ok(())
}
Expand Down Expand Up @@ -543,7 +541,7 @@ pub enum AccountMonitorError {
#[error("Non Fungibles API error: {0}")]
NonFungibleTokens(#[from] NonFungibleTokensApiError),
#[error("Failed to decode binary value: {0}")]
DecodeValueFailed(#[from] IndexedValueVisitorError),
DecodeValueFailed(#[from] IndexedValueError),
#[error("Unexpected substate: {0}")]
UnexpectedSubstate(String),
#[error("Monitor service is not running")]
Expand Down
24 changes: 21 additions & 3 deletions applications/tari_validator_node/src/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,11 @@ use tari_indexer_lib::substate_scanner::SubstateScanner;
use tari_shutdown::ShutdownSignal;
use tari_state_store_sqlite::SqliteStateStore;
use tari_template_lib::{
auth::ResourceAccessRules,
constants::{CONFIDENTIAL_TARI_RESOURCE_ADDRESS, PUBLIC_IDENTITY_RESOURCE_ADDRESS},
crypto::RistrettoPublicKeyBytes,
models::Metadata,
prelude::ResourceType,
prelude::{OwnerRule, ResourceType},
};
use tari_transaction::Transaction;
use tari_validator_node_rpc::client::TariCommsValidatorNodeClientFactory;
Expand Down Expand Up @@ -375,7 +377,15 @@ where
SubstateRecord {
address,
version: 0,
substate_value: Resource::new(ResourceType::NonFungible, "ID".to_string(), Default::default()).into(),
substate_value: Resource::new(
ResourceType::NonFungible,
RistrettoPublicKeyBytes::default(),
OwnerRule::None,
ResourceAccessRules::new(),
"ID".to_string(),
Default::default(),
)
.into(),
state_hash: Default::default(),
created_by_transaction: Default::default(),
created_justify: *genesis_block.justify().id(),
Expand All @@ -393,7 +403,15 @@ where
SubstateRecord {
address,
version: 0,
substate_value: Resource::new(ResourceType::Confidential, "tXTR2".to_string(), Metadata::new()).into(),
substate_value: Resource::new(
ResourceType::Confidential,
RistrettoPublicKeyBytes::default(),
OwnerRule::None,
ResourceAccessRules::new(),
"tXTR2".to_string(),
Metadata::new(),
)
.into(),
state_hash: Default::default(),
created_by_transaction: Default::default(),
created_justify: *genesis_block.justify().id(),
Expand Down
4 changes: 2 additions & 2 deletions clients/wallet_daemon_client/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use tari_engine_types::{
};
use tari_template_lib::{
args::Arg,
auth::AccessRules,
auth::ComponentAccessRules,
models::{Amount, ConfidentialOutputProof, NonFungibleId, ResourceAddress},
prelude::{ConfidentialWithdrawProof, ResourceType},
};
Expand Down Expand Up @@ -193,7 +193,7 @@ pub struct KeysCreateResponse {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AccountsCreateRequest {
pub account_name: Option<String>,
pub custom_access_rules: Option<AccessRules>,
pub custom_access_rules: Option<ComponentAccessRules>,
pub fee: Option<Amount>,
pub is_default: bool,
pub key_id: Option<u64>,
Expand Down
1 change: 1 addition & 0 deletions dan_layer/consensus_tests/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ async fn multi_shard_propose_blocks_with_new_transactions_until_all_committed()
test.assert_clean_shutdown().await;
}

#[ignore = "FIXME: This test is very flaky"]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn foreign_shard_decides_to_abort() {
setup_logger();
Expand Down
20 changes: 4 additions & 16 deletions dan_layer/consensus_tests/src/support/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use tari_dan_storage::consensus_models::{Decision, ExecutedTransaction};
use tari_engine_types::{
commit_result::{ExecuteResult, FinalizeResult, RejectReason, TransactionResult},
fees::{FeeCostBreakdown, FeeReceipt},
resource_container::ResourceContainer,
substate::SubstateDiff,
};
use tari_transaction::Transaction;
Expand Down Expand Up @@ -43,13 +42,7 @@ pub fn build_transaction_from(
transaction_failure: None,
fee_receipt: Some(FeeReceipt {
total_fee_payment: fee.try_into().unwrap(),
fee_resource: ResourceContainer::Confidential {
address: "resource_0000000000000000000000000000000000000000000000000000000000000000"
.parse()
.unwrap(),
commitments: Default::default(),
revealed_amount: fee.try_into().unwrap(),
},
total_fees_paid: fee.try_into().unwrap(),
cost_breakdown: vec![],
}),
},
Expand All @@ -75,19 +68,14 @@ pub fn build_transaction(decision: Decision, fee: u64, num_shards: usize, num_co
}

pub fn change_decision(tx: ExecutedTransaction, new_decision: Decision) -> ExecutedTransaction {
let total_fees_charged = tx
let total_fees_paid = tx
.result()
.fee_receipt
.as_ref()
.unwrap()
.total_fees_paid()
.total_allocated_fee_payments()
.as_u64_checked()
.unwrap();
let resulting_outputs = tx.resulting_outputs().to_vec();
build_transaction_from(
tx.into_transaction(),
new_decision,
total_fees_charged,
resulting_outputs,
)
build_transaction_from(tx.into_transaction(), new_decision, total_fees_paid, resulting_outputs)
}
27 changes: 22 additions & 5 deletions dan_layer/engine/src/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,29 @@ use tari_engine_types::{
substate::{Substate, SubstateAddress},
};
use tari_template_lib::{
auth::{AccessRule, ResourceAccessRules},
constants::{CONFIDENTIAL_TARI_RESOURCE_ADDRESS, PUBLIC_IDENTITY_RESOURCE_ADDRESS},
crypto::RistrettoPublicKeyBytes,
models::Metadata,
prelude::ResourceType,
prelude::{OwnerRule, ResourceType},
};

use crate::state_store::{StateStoreError, StateWriter};

pub fn bootstrap_state<T: StateWriter>(state_db: &mut T) -> Result<(), StateStoreError> {
let address = SubstateAddress::Resource(PUBLIC_IDENTITY_RESOURCE_ADDRESS);
// Create the resource for badges
state_db.set_state(
&address,
&SubstateAddress::Resource(PUBLIC_IDENTITY_RESOURCE_ADDRESS),
Substate::new(
0,
Resource::new(ResourceType::NonFungible, "ID".to_string(), Default::default()),
Resource::new(
ResourceType::NonFungible,
RistrettoPublicKeyBytes::default(),
OwnerRule::None,
ResourceAccessRules::deny_all(),
"ID".to_string(),
Default::default(),
),
),
)?;

Expand All @@ -33,7 +41,16 @@ pub fn bootstrap_state<T: StateWriter>(state_db: &mut T) -> Result<(), StateStor
&address,
Substate::new(
0,
Resource::new(ResourceType::Confidential, "tXTR2".to_string(), metadata),
Resource::new(
ResourceType::Confidential,
RistrettoPublicKeyBytes::default(),
OwnerRule::None,
ResourceAccessRules::new()
.withdrawable(AccessRule::AllowAll)
.depositable(AccessRule::AllowAll),
"tXTR2".to_string(),
metadata,
),
),
)?;

Expand Down
18 changes: 5 additions & 13 deletions dan_layer/engine/src/fees/fee_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,13 @@
use std::{collections::HashMap, io};

use tari_bor::encode_into;
use tari_dan_common_types::services::template_provider::TemplateProvider;
use tari_engine_types::{
fees::FeeSource,
substate::{SubstateAddress, SubstateValue},
};

use super::FeeTable;
use crate::{
packager::LoadedTemplate,
runtime::{RuntimeModule, RuntimeModuleError, StateTracker},
};
use crate::runtime::{RuntimeModule, RuntimeModuleError, StateTracker};

pub struct FeeModule {
initial_cost: u64,
Expand All @@ -30,24 +26,20 @@ impl FeeModule {
}
}

impl<TTemplateProvider: TemplateProvider<Template = LoadedTemplate>> RuntimeModule<TTemplateProvider> for FeeModule {
fn on_initialize(&self, track: &StateTracker<TTemplateProvider>) -> Result<(), RuntimeModuleError> {
impl RuntimeModule for FeeModule {
fn on_initialize(&self, track: &StateTracker) -> Result<(), RuntimeModuleError> {
track.add_fee_charge(FeeSource::Initial, self.initial_cost);
Ok(())
}

fn on_runtime_call(
&self,
track: &StateTracker<TTemplateProvider>,
_call: &'static str,
) -> Result<(), RuntimeModuleError> {
fn on_runtime_call(&self, track: &StateTracker, _call: &'static str) -> Result<(), RuntimeModuleError> {
track.add_fee_charge(FeeSource::RuntimeCall, self.fee_table.per_module_call_cost());
Ok(())
}

fn on_before_finalize(
&self,
track: &StateTracker<TTemplateProvider>,
track: &StateTracker,
changes: &HashMap<SubstateAddress, SubstateValue>,
) -> Result<(), RuntimeModuleError> {
let total_storage = changes
Expand Down
9 changes: 2 additions & 7 deletions dan_layer/engine/src/flow/flow_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,12 @@ use std::{collections::HashMap, sync::Arc};

use tari_dan_common_types::services::template_provider::TemplateProvider;

use crate::{
function_definitions::FunctionArgDefinition,
packager::LoadedTemplate,
runtime::{AuthorizationScope, Runtime},
};
use crate::{function_definitions::FunctionArgDefinition, packager::LoadedTemplate, runtime::Runtime};

pub struct FlowContext<TTemplateProvider: TemplateProvider<Template = LoadedTemplate>> {
pub template_provider: Arc<TTemplateProvider>,
pub runtime: Runtime,
pub auth_scope: AuthorizationScope,
pub args: HashMap<String, (Vec<u8>, FunctionArgDefinition)>,
pub args: HashMap<String, (tari_bor::Value, FunctionArgDefinition)>,
pub recursion_depth: usize,
pub max_recursion_depth: usize,
}
Loading

0 comments on commit b788655

Please sign in to comment.