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(wasm-dpp): integration tests validate data contract update transition #812

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
@@ -1,4 +1,4 @@
use std::convert::TryInto;
use std::convert::{TryFrom, TryInto};

use anyhow::anyhow;
use anyhow::Context;
Expand All @@ -7,7 +7,6 @@ use lazy_static::lazy_static;
use serde_json::{json, Value as JsonValue};
use std::sync::Arc;

use crate::state_transition::state_transition_execution_context::StateTransitionExecutionContext;
use crate::{
consensus::basic::BasicError,
data_contract::{
Expand All @@ -21,6 +20,10 @@ use crate::{
version::ProtocolVersionValidator,
DashPlatformProtocolInitError, ProtocolError,
};
use crate::{
consensus::ConsensusError,
state_transition::state_transition_execution_context::StateTransitionExecutionContext,
};

use super::schema_compatibility_validator::validate_schema_compatibility;
use super::schema_compatibility_validator::DiffVAlidatorError;
Expand Down Expand Up @@ -73,9 +76,18 @@ where
return Ok(result);
}

let protocol_version = raw_state_transition
let protocol_version = match raw_state_transition
.get_u64(property_names::PROTOCOL_VERSION)
.with_context(|| "invalid protocol version")? as u32;
.and_then(|x| u32::try_from(x).map_err(Into::into))
{
Ok(v) => v,
Err(parsing_error) => {
return Ok(SimpleValidationResult::new(Some(vec![
ConsensusError::ProtocolVersionParsingError { parsing_error },
])))
}
};

let result = self.protocol_version_validator.validate(protocol_version)?;
if !result.is_valid() {
return Ok(result);
Expand Down Expand Up @@ -123,7 +135,10 @@ where
let raw_existing_data_contract = existing_data_contract.to_object(false)?;

let mut old_base_data_contract = raw_existing_data_contract;
old_base_data_contract.remove(contract_property_names::DEFINITIONS)?;

old_base_data_contract
.remove(contract_property_names::DEFINITIONS)
.ok();
old_base_data_contract.remove(contract_property_names::DOCUMENTS)?;
old_base_data_contract.remove(contract_property_names::VERSION)?;

Expand All @@ -136,7 +151,9 @@ where
)?;

let mut new_base_data_contract = raw_data_contract.clone();
new_base_data_contract.remove(contract_property_names::DEFINITIONS)?;
new_base_data_contract
.remove(contract_property_names::DEFINITIONS)
.ok();
new_base_data_contract.remove(contract_property_names::DOCUMENTS)?;
new_base_data_contract.remove(contract_property_names::VERSION)?;

Expand All @@ -162,19 +179,6 @@ where
return Ok(validation_result);
}

// check indices are not changes
let new_documents = raw_data_contract
.get_value("documents")?
.as_object()
.ok_or_else(|| anyhow!("the 'documents' property is not an array"))?;
let result = validate_indices_are_backward_compatible(
existing_data_contract.documents(),
new_documents,
)?;
if !result.is_valid() {
return Ok(result);
}

// Schema should be backward compatible
let old_schema = existing_data_contract.documents();
let new_schema = raw_data_contract.get_value("documents")?;
Expand All @@ -201,6 +205,23 @@ where
}
}

if !validation_result.is_valid() {
fominok marked this conversation as resolved.
Show resolved Hide resolved
return Ok(validation_result);
}

// check indices are not changed
let new_documents = raw_data_contract
.get_value("documents")?
.as_object()
.ok_or_else(|| anyhow!("the 'documents' property is not an array"))?;
let result = validate_indices_are_backward_compatible(
existing_data_contract.documents(),
new_documents,
)?;
if !result.is_valid() {
return Ok(result);
}

Ok(validation_result)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::sync::Arc;
use test_case::test_case;

use crate::{
consensus::basic::BasicError,
consensus::{basic::BasicError, ConsensusError},
data_contract::state_transition::{
data_contract_update_transition::validation::basic::DataContractUpdateTransitionBasicValidator,
property_names, DataContractUpdateTransition,
Expand Down Expand Up @@ -143,8 +143,12 @@ async fn protocol_version_should_be_valid() {
let result = validator
.validate(&raw_state_transition, &Default::default())
.await
.expect_err("err should be returned");
assert_eq!("invalid protocol version", result.to_string())
.expect("validation result should be returned");

assert!(matches!(
result.errors.iter().next(),
Some(ConsensusError::ProtocolVersionParsingError { .. })
));
}

#[tokio::test]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
mod apply;
mod validation;

use std::collections::HashMap;

pub use apply::*;
pub use validation::*;

Expand All @@ -15,8 +17,10 @@ use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;

use crate::{
buffer::Buffer, errors::from_dpp_err, identifier::IdentifierWrapper, with_js_error,
DataContractParameters, DataContractWasm, StateTransitionExecutionContextWasm,
buffer::Buffer,
errors::{from_dpp_err, protocol_error::from_protocol_error},
identifier::IdentifierWrapper,
with_js_error, DataContractParameters, DataContractWasm, StateTransitionExecutionContextWasm,
};

#[derive(Clone)]
Expand All @@ -38,15 +42,14 @@ impl From<DataContractUpdateTransitionWasm> for DataContractUpdateTransition {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DataContractUpdateTransitionParameters {
protocol_version: u32,
#[serde(skip_serializing_if = "Option::is_none", default)]
data_contract: Option<DataContractParameters>,
#[serde(skip_serializing_if = "Option::is_none", default)]
entropy: Option<Vec<u8>>,
#[serde(skip_serializing_if = "Option::is_none", default)]
signature_public_key_id: Option<KeyID>,
#[serde(skip_serializing_if = "Option::is_none", default)]
signature: Option<Vec<u8>>,
#[serde(flatten)]
extra: HashMap<String, serde_json::Value>,
}

#[wasm_bindgen(js_class=DataContractUpdateTransition)]
Expand Down Expand Up @@ -144,4 +147,15 @@ impl DataContractUpdateTransitionWasm {
.map_err(from_dpp_err)?;
Ok(Buffer::from_bytes(&bytes))
}

#[wasm_bindgen(js_name=toObject)]
pub fn to_object(&self, skip_signature: Option<bool>) -> Result<JsValue, JsValue> {
let serde_object = self
.0
.to_object(skip_signature.unwrap_or(false))
.map_err(from_protocol_error)?;
serde_object
.serialize(&serde_wasm_bindgen::Serializer::json_compatible())
.map_err(|e| e.into())
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
use std::collections::BTreeMap;
use std::{collections::BTreeMap, sync::Arc};

use dpp::data_contract::state_transition::data_contract_update_transition::validation::{
basic::validate_indices_are_backward_compatible as dpp_validate_indices_are_backward_compatible,
state::validate_data_contract_update_transition_state::validate_data_contract_update_transition_state as dpp_validate_data_contract_update_transition_state,
use dpp::{
data_contract::state_transition::data_contract_update_transition::validation::{
basic::{
validate_indices_are_backward_compatible as dpp_validate_indices_are_backward_compatible,
DataContractUpdateTransitionBasicValidator,
},
state::validate_data_contract_update_transition_state::validate_data_contract_update_transition_state as dpp_validate_data_contract_update_transition_state,
},
version::ProtocolVersionValidator,
};
use wasm_bindgen::prelude::*;

use crate::{
data_contract::state_transition::data_contract_update_transition::DataContractUpdateTransitionParameters,
errors::{from_dpp_err, protocol_error::from_protocol_error},
state_repository::{ExternalStateRepositoryLike, ExternalStateRepositoryLikeWrapper},
validation::ValidationResultWasm,
DataContractUpdateTransitionWasm,
DataContractUpdateTransitionWasm, StateTransitionExecutionContextWasm,
};

#[wasm_bindgen(js_name=validateDataContractUpdateTransitionState)]
Expand Down Expand Up @@ -47,3 +54,28 @@ pub fn validate_indices_are_backward_compatible(

Ok(result.map(|_| JsValue::undefined()).into())
}

#[wasm_bindgen(js_name=validateDataContractUpdateTransitionBasic)]
pub async fn validate_data_contract_update_transition_basic(
state_repository: ExternalStateRepositoryLike,
raw_parameters: JsValue,
execution_context: &StateTransitionExecutionContextWasm,
) -> Result<ValidationResultWasm, JsError> {
let parameters: DataContractUpdateTransitionParameters =
serde_wasm_bindgen::from_value(raw_parameters)?;

let validator: DataContractUpdateTransitionBasicValidator<ExternalStateRepositoryLikeWrapper> =
DataContractUpdateTransitionBasicValidator::new(
Arc::new(ExternalStateRepositoryLikeWrapper::new(state_repository)),
Arc::new(ProtocolVersionValidator::default()),
)?;

let validation_result = validator
.validate(
&serde_json::to_value(&parameters)?,
&execution_context.into(),
)
.await?;

Ok(validation_result.map(|_| JsValue::undefined()).into())
}
Loading