//! Format version 3 against format version 1, over every system contract and every contract of //! the mainnet and testnet corpus (`tests/fixtures/contract_corpus`): a contract written in //! format version 3, its document types and `$defs` as typed definitions, builds the contract //! its schemas build, records the same validation operations, is refused where they are //! refused, reads back from its bytes and its JSON, and stores as any contract does. use super::DataContractInSerializationFormatV3; use crate::consensus::basic::BasicError; use crate::consensus::ConsensusError; use crate::data_contract::accessors::v0::DataContractV0Getters; use crate::data_contract::accessors::v1::DataContractV1Getters; use crate::data_contract::config::DataContractConfig; use crate::data_contract::document_type::accessors::DocumentTypeV0Getters; use crate::data_contract::document_type::class_methods::written_back_decoy; use crate::data_contract::document_type::definition::{DocumentTypeDefinition, SchemaDefinitions}; use crate::data_contract::document_type::serialized_version::DocumentTypeInSerializationFormat; use crate::data_contract::schema::DataContractSchemaMethodsV0; use crate::data_contract::serialized_version::v1::DataContractInSerializationFormatV1; use crate::data_contract::serialized_version::{ DataContractInSerializationFormat, DataContractMismatch, }; use crate::data_contract::DataContract; use crate::serialization::{ JsonConvertible, PlatformDeserializableWithPotentialValidationFromVersionedStructureTrusted, PlatformDeserializableWithPotentialValidationFromVersionedStructureUntrusted, ValueConvertible, }; use crate::system_data_contracts::{load_system_data_contract, SystemDataContract}; use crate::validation::operations::ProtocolValidationOperation; use crate::ProtocolError; use platform_serialization::PLATFORM_BINCODE_CONFIG; use platform_value::string_encoding::{decode, Encoding}; use platform_value::{platform_value, Identifier, Value}; use platform_version::version::PlatformVersion; use platform_version::TryFromPlatformVersioned; use serde_json::Value as JsonValue; use std::collections::BTreeMap; /// How many contracts the corpus holds, and their document types. const CORPUS_CONTRACTS: usize = 55 + 694; const CORPUS_DOCUMENT_TYPES: usize = 106 + 1397; /// Every contract of the corpus, as Drive loads it at the latest protocol version. pub(super) fn corpus_contracts() -> Vec<(String, DataContract)> { let platform_version = PlatformVersion::latest(); let lines = include_str!("../../../../tests/fixtures/contract_corpus/mainnet.jsonl") .lines() .map(|line| ("mainnet", line)) .chain( include_str!("../../../../tests/fixtures/contract_corpus/testnet.jsonl") .lines() .map(|line| ("testnet", line)), ); lines .map(|(network, line)| { let line: JsonValue = serde_json::from_str(line).expect("expected a JSON corpus line"); let id = line["id"].as_str().expect("expected a contract id"); let bytes = decode( line["data"].as_str().expect("expected contract bytes"), Encoding::Base64, ) .expect("expected base64 contract bytes"); let contract = DataContract::versioned_deserialize_trusted(&bytes, false, platform_version) .expect("expected a corpus contract to load"); (format!("{network} contract {id}"), contract) }) .collect() } /// Every system contract the latest protocol version has. pub(super) fn system_contracts() -> Vec<(String, DataContract)> { let platform_version = PlatformVersion::latest(); SystemDataContract::ALL .into_iter() // A reserved slot, with no contract at any version .filter(|system_contract| *system_contract != SystemDataContract::FeatureFlags) .map(|system_contract| { let contract = load_system_data_contract(system_contract, platform_version) .unwrap_or_else(|error| panic!("{system_contract:?} does not load: {error}")); (format!("system contract {system_contract:?}"), contract) }) .collect() } pub(super) fn every_contract() -> Vec<(String, DataContract)> { let mut contracts = system_contracts(); contracts.extend(corpus_contracts()); contracts } /// `contract` in format version 3 at the latest protocol version. pub(super) fn with_definitions( origin: &str, contract: &DataContract, ) -> DataContractInSerializationFormat { DataContractInSerializationFormat::try_from_data_contract_with_definitions( contract, PlatformVersion::latest(), ) .unwrap_or_else(|error| panic!("{origin} does not write as definitions: {error}")) } /// `contract` in format version 1 at the latest protocol version, as transitions carry it. pub(super) fn with_schemas( origin: &str, contract: &DataContract, ) -> DataContractInSerializationFormat { DataContractInSerializationFormat::try_from_platform_versioned( contract, PlatformVersion::latest(), ) .unwrap_or_else(|error| panic!("{origin} does not write as schemas: {error}")) } /// Builds `format` at the latest protocol version, with the operations it recorded. fn built( format: DataContractInSerializationFormat, full_validation: bool, ) -> ( Result, Vec, ) { let mut operations = Vec::new(); let contract = DataContract::try_from_platform_versioned( format, full_validation, &mut operations, PlatformVersion::latest(), ); (contract, operations) } /// Each document type of `contract` as it compiles, by name. fn compiled(contract: &DataContract) -> BTreeMap { contract .document_types() .iter() .map(|(name, document_type)| { let compiled = DocumentTypeInSerializationFormat::try_from_document_type( document_type.as_ref(), contract.schema_defs(), PlatformVersion::latest(), ) .unwrap_or_else(|error| panic!("{name} does not compile: {error}")); (name.clone(), compiled) }) .collect() } /// What two contracts differ in, of the fields format version 3 carries beside the document /// types, and of their document types as they compile. fn contract_difference( from_schemas: &DataContract, from_definitions: &DataContract, ) -> Option { let fields = [ ("id", from_schemas.id() != from_definitions.id()), ( "owner", from_schemas.owner_id() != from_definitions.owner_id(), ), ( "version", from_schemas.version() != from_definitions.version(), ), ("config", from_schemas.config() != from_definitions.config()), ("groups", from_schemas.groups() != from_definitions.groups()), ("tokens", from_schemas.tokens() != from_definitions.tokens()), ( "keywords", from_schemas.keywords() != from_definitions.keywords(), ), ( "description", from_schemas.description() != from_definitions.description(), ), ]; if let Some((field, _)) = fields.iter().find(|(_, differs)| *differs) { return Some(format!("its {field} differs")); } let (schemas, definitions) = (compiled(from_schemas), compiled(from_definitions)); if !schemas.keys().eq(definitions.keys()) { return Some("its document types are others".to_string()); } schemas .iter() .find(|(name, compiled)| definitions.get(*name) != Some(compiled)) .map(|(name, _)| format!("document type {name} compiles to another")) } /// The operations a parse recorded, the size of each schema left out: a definition is billed /// the bytes it encodes to, where a schema is billed the values it holds. fn without_sizes(operations: &[ProtocolValidationOperation]) -> Vec { operations .iter() .map(|operation| match operation { ProtocolValidationOperation::DocumentTypeSchemaValidationForSize(_) => { ProtocolValidationOperation::DocumentTypeSchemaValidationForSize(0) } operation => operation.clone(), }) .collect() } fn is_json_schema_error(refusal: &ProtocolError) -> bool { matches!( refusal, ProtocolError::ConsensusError(error) if matches!(**error, ConsensusError::BasicError(BasicError::JsonSchemaError(_))) ) } fn is_definition_error(refusal: &ProtocolError) -> bool { matches!( refusal, ProtocolError::ConsensusError(error) if matches!( **error, ConsensusError::BasicError(BasicError::InvalidDocumentTypeDefinitionError(_)) ) ) } /// How the contracts compared, both ways. #[derive(Debug, Default)] struct Tally { contracts: usize, document_types: usize, built: usize, registered: usize, refused_both_ways: usize, refused_by_the_schema_check: usize, operations_compared: usize, operations_recorded: usize, } /// The oracle: every contract built from its format version 3 as from its format version 1, /// without and with full validation, recording the same operations but the sizes, and refused /// the same way where it is refused. #[test] fn should_build_every_contract_from_its_definitions_as_from_its_schemas() { let mut tally = Tally::default(); let mut differences = Vec::new(); for (origin, contract) in every_contract() { tally.contracts += 1; tally.document_types += contract.document_types().len(); let schemas = with_schemas(&origin, &contract); let definitions = with_definitions(&origin, &contract); for full_validation in [false, true] { let at = format!("{origin} (full validation: {full_validation})"); let (from_schemas, schema_operations) = built(schemas.clone(), full_validation); let (from_definitions, definition_operations) = built(definitions.clone(), full_validation); match (&from_schemas, &from_definitions) { (Ok(from_schemas), Ok(from_definitions)) => { if let Some(difference) = contract_difference(from_schemas, from_definitions) { differences.push(format!("{at}: {difference}")); } if full_validation { tally.registered += 1; } else { tally.built += 1; } } (Err(from_schemas), Err(from_definitions)) => { tally.refused_both_ways += 1; if is_json_schema_error(from_schemas) { tally.refused_by_the_schema_check += 1; if !is_definition_error(from_definitions) { differences.push(format!( "{at}: refused by the schema check ({from_schemas}), and from \ its definitions with {from_definitions}" )); } } else if from_schemas.to_string() != from_definitions.to_string() { differences.push(format!( "{at}: refused from its schemas with {from_schemas}, from its \ definitions with {from_definitions}" )); } } (from_schemas, from_definitions) => differences.push(format!( "{at}: from its schemas {:?}, from its definitions {:?}", from_schemas .as_ref() .map(|_| "built") .map_err(ToString::to_string), from_definitions .as_ref() .map(|_| "built") .map_err(ToString::to_string), )), } if from_schemas.is_ok() == from_definitions.is_ok() { tally.operations_compared += 1; tally.operations_recorded += schema_operations.len(); if without_sizes(&schema_operations) != without_sizes(&definition_operations) { differences.push(format!( "{at}: records {schema_operations:?} from its schemas and \ {definition_operations:?} from its definitions" )); } } } } assert!( differences.is_empty(), "{} differences over {tally:?}:\n{}", differences.len(), differences.join("\n") ); let system = SystemDataContract::ALL.len() - 1; assert_eq!(tally.contracts, system + CORPUS_CONTRACTS, "{tally:?}"); assert!(tally.document_types > CORPUS_DOCUMENT_TYPES, "{tally:?}"); // Every contract builds as Drive holds it, and today's rules register all but a few // testnet contracts registered under older ones (8 when this was written, each refused // for the bounds of a summed property) assert_eq!(tally.built, tally.contracts, "{tally:?}"); assert_eq!( tally.registered + tally.refused_both_ways, tally.contracts, "{tally:?}" ); assert!( tally.registered > system + CORPUS_CONTRACTS - 20, "{tally:?}" ); assert!(tally.refused_both_ways > 0, "{tally:?}"); // Every pair that agrees has its operations compared, and registration records some assert_eq!(tally.operations_compared, 2 * tally.contracts, "{tally:?}"); assert!( tally.operations_recorded > tally.document_types, "{tally:?}" ); } /// Every contract built from its definitions is built alike, with the same contract or the same /// refusal and the same operations, when decoys (`written_back_decoy`) stand in for the schema /// and `$defs` each document type's build is handed and for the `$defs` the checks across the /// types are handed. Those checks still see the written-back schema each built document type /// keeps, so this does not show that they leave it unread: the cases of /// `definition_reader_tests` hold each of their readers to the definitions. Under the rules of /// registration and as Drive holds a contract. #[test] fn should_build_every_contract_from_its_definitions_alike_whatever_its_core_parses_are_handed() { let decoys: Vec = vec![ ( Value::from(serde_json::json!({ "type": "object", "properties": { "decoy": { "type": "integer", "position": 0 } }, "required": ["decoy"], "additionalProperties": false, })), Some(BTreeMap::from([( "decoy".to_string(), Value::from(serde_json::json!({ "type": "string", "maxLength": 3 })), )])), ), (Value::Text("no schema".to_string()), None), ]; let mut differences = Vec::new(); let (mut built_alike, mut refused_alike) = (0, 0); for (origin, contract) in every_contract() { let definitions = with_definitions(&origin, &contract); for full_validation in [false, true] { let at = format!("{origin} (full validation: {full_validation})"); let (without, operations) = built(definitions.clone(), full_validation); for decoy in &decoys { let (with, decoy_operations) = written_back_decoy::with_decoy(decoy.clone(), || { built(definitions.clone(), full_validation) }); match (&without, &with) { (Ok(without), Ok(with)) => { if let Some(difference) = contract_difference(without, with) { differences.push(format!("{at}: with a decoy {difference}")); } built_alike += 1; } (Err(without), Err(with)) if without.to_string() == with.to_string() => { refused_alike += 1; } (without, with) => differences.push(format!( "{at}: {:?} without a decoy, {:?} with one", without .as_ref() .map(|_| "built") .map_err(ToString::to_string), with.as_ref().map(|_| "built").map_err(ToString::to_string), )), } if operations != decoy_operations { differences.push(format!( "{at}: records {operations:?} without a decoy and {decoy_operations:?} \ with one" )); } } } } assert!( differences.is_empty(), "{} differences:\n{}", differences.len(), differences.join("\n") ); assert!( built_alike > 2 * CORPUS_CONTRACTS, "{built_alike} built alike" ); assert!(refused_alike > 0, "{refused_alike} refused alike"); } /// A format version 3 contract reads back from its bytes, decoded as anyone's are, and from its /// JSON and its value; and a contract built from it writes the same format version 3 again, /// which proof verification relies on to compare what a client sent with what state holds. #[test] fn should_read_back_every_contract_in_format_version_3_from_its_bytes_and_its_json() { let platform_version = PlatformVersion::latest(); let (mut contracts, mut rewritten) = (0, 0); let (mut values_read, mut values_refused_as_format_version_1) = (0, 0); for (origin, contract) in every_contract() { let format = with_definitions(&origin, &contract); let bytes = bincode::encode_to_vec(&format, PLATFORM_BINCODE_CONFIG) .unwrap_or_else(|error| panic!("{origin} does not encode: {error}")); assert_eq!( bytes.first(), Some(&3), "{origin} is not tagged format version 3" ); let (decoded, read) = bincode::borrow_decode_from_slice_untrusted::< DataContractInSerializationFormat, _, >(&bytes, PLATFORM_BINCODE_CONFIG) .unwrap_or_else(|error| panic!("{origin} does not decode: {error}")); assert_eq!(read, bytes.len(), "{origin}"); assert_eq!(decoded, format, "{origin} changed through its bytes"); decoded .ensure_one_form(&bytes) .unwrap_or_else(|error| panic!("{origin} is not in its one form: {error}")); let json = format .to_json() .unwrap_or_else(|error| panic!("{origin} does not write as JSON: {error}")); assert_eq!(json["$formatVersion"], "3", "{origin}"); assert_eq!( DataContractInSerializationFormat::from_json(json) .unwrap_or_else(|error| panic!("{origin} does not read from JSON: {error}")), format, "{origin} changed through its JSON" ); // Each definition reads back from its value let DataContractInSerializationFormat::V3(v3) = &format else { panic!("{origin} is not in format version 3"); }; for (name, definition) in &v3.document_definitions { let value = platform_value::to_value(definition) .unwrap_or_else(|error| panic!("{origin} {name} does not write: {error}")); assert_eq!( &platform_value::from_value::(value) .unwrap_or_else(|error| panic!("{origin} {name} does not read: {error}")), definition, "{origin} {name} changed through its value" ); } if let Some(definitions) = &v3.definitions { let value = platform_value::to_value(definitions) .unwrap_or_else(|error| panic!("{origin} `$defs` do not write: {error}")); assert_eq!( &platform_value::from_value::(value) .unwrap_or_else(|error| panic!("{origin} `$defs` do not read: {error}")), definitions, "{origin} `$defs` changed through their value" ); } // The whole contract reads back from its value, except where format version 1 does // not either: a value writes the positions of groups and tokens as integers, which // both formats read only as strings let value = format .to_object() .unwrap_or_else(|error| panic!("{origin} does not write as a value: {error}")); let format_v1_value = with_schemas(&origin, &contract) .to_object() .unwrap_or_else(|error| panic!("{origin} does not write as a value: {error}")); match ( DataContractInSerializationFormat::from_object(value), DataContractInSerializationFormat::from_object(format_v1_value), ) { (Ok(read), _) => { assert_eq!(read, format, "{origin} changed through its value"); values_read += 1; } (Err(_), Err(_)) => values_refused_as_format_version_1 += 1, (Err(error), Ok(_)) => { panic!("{origin} does not read from a value, as format version 1 does: {error}") } } // Built as state would build it, it writes the definitions it was built from let from_definitions = DataContract::versioned_deserialize_untrusted(&bytes, false, platform_version) .unwrap_or_else(|error| panic!("{origin} does not build: {error}")); let again = with_definitions(&origin, &from_definitions); assert_eq!( again.first_mismatch(&format), None, "{origin} writes other definitions once built" ); assert_eq!(again, format, "{origin}"); rewritten += 1; contracts += 1; } assert_eq!( contracts, SystemDataContract::ALL.len() - 1 + CORPUS_CONTRACTS ); assert_eq!(rewritten, contracts); assert_eq!(values_read + values_refused_as_format_version_1, contracts); assert!( values_read > values_refused_as_format_version_1, "{values_read} read from their values, {values_refused_as_format_version_1} not" ); } /// A contract built from format version 3 is stored as any contract is, its document types /// compiled from the schemas their definitions write back to, and reads back from its stored /// form as the same contract. #[test] fn should_store_every_contract_built_from_its_definitions_and_read_it_back() { let platform_version = PlatformVersion::latest(); let mut stored = 0; for (origin, contract) in every_contract() { let (from_definitions, _) = built(with_definitions(&origin, &contract), false); let from_definitions = from_definitions.unwrap_or_else(|error| panic!("{origin} does not build: {error}")); let storage_format = DataContractInSerializationFormat::try_from_data_contract_for_storage( &from_definitions, platform_version, ) .unwrap_or_else(|error| panic!("{origin} does not compile: {error}")); assert!( matches!(storage_format, DataContractInSerializationFormat::V2(_)), "{origin} is not stored compiled" ); let (read_back, _) = built(storage_format, false); assert_eq!( read_back.unwrap_or_else(|error| panic!("{origin} does not read back: {error}")), from_definitions, "{origin} changed through its stored form" ); let bytes = from_definitions .serialize_to_storage_bytes(platform_version) .unwrap_or_else(|error| panic!("{origin} does not store: {error}")); assert_eq!( DataContract::versioned_deserialize_trusted(&bytes, false, platform_version) .unwrap_or_else(|error| panic!("{origin} does not load: {error}")), from_definitions, "{origin} changed through its stored bytes" ); stored += 1; } assert_eq!(stored, SystemDataContract::ALL.len() - 1 + CORPUS_CONTRACTS); } /// A definition read from a schema, written back and read again, is the definition it was: /// for every document type and every `$defs` of every contract. #[test] fn should_read_the_definition_a_schema_reads_as_from_the_schema_it_writes_back() { let platform_version = PlatformVersion::latest(); let (mut document_types, mut defs) = (0, 0); let mut differences = Vec::new(); for (origin, contract) in every_contract() { for (name, document_type) in contract.document_types() { document_types += 1; let read = (|| { let definition = DocumentTypeDefinition::try_from_schema( document_type.schema(), platform_version, ) .map_err(|error| format!("not read: {error}"))?; let written = definition .to_schema(platform_version) .map_err(|error| format!("not written: {error}"))?; let again = DocumentTypeDefinition::try_from_schema(&written, platform_version) .map_err(|error| format!("written back, and not read again: {error}"))?; (again == definition) .then_some(()) .ok_or_else(|| "written back, and read as another definition".to_string()) })(); if let Err(difference) = read { differences.push(format!("{origin} {name}: {difference}")); } } if let Some(schema_defs) = contract.schema_defs() { defs += 1; let read = (|| { let definitions = SchemaDefinitions::try_from_schema_defs(schema_defs, platform_version) .map_err(|error| format!("not read: {error}"))?; let written: BTreeMap = definitions .to_schema_defs(platform_version) .map_err(|error| format!("not written: {error}"))?; let again = SchemaDefinitions::try_from_schema_defs(&written, platform_version) .map_err(|error| format!("written back, and not read again: {error}"))?; (again == definitions) .then_some(()) .ok_or_else(|| "written back, and read as other definitions".to_string()) })(); if let Err(difference) = read { differences.push(format!("{origin} $defs: {difference}")); } } } assert!( differences.is_empty(), "{} differences over {document_types} document types and {defs} `$defs`:\n{}", differences.len(), differences.join("\n") ); assert!(document_types > CORPUS_DOCUMENT_TYPES, "{document_types}"); assert!(defs > 10, "{defs}"); } /// Bytes a format version 3 contract does not encode to are refused by the untrusted decoders /// of a contract, though `bincode` reads them as the same contract: an integer in a longer /// form than the one it is written in. #[test] fn should_refuse_a_format_version_3_contract_from_bytes_it_does_not_encode_to() { let platform_version = PlatformVersion::latest(); let (origin, contract) = system_contracts() .into_iter() .find(|(_, contract)| contract.schema_defs().is_none()) .expect("expected a system contract without `$defs`"); let format = with_definitions(&origin, &contract); let DataContractInSerializationFormat::V3(v3) = &format else { panic!("expected format version 3"); }; let mut bytes = bincode::encode_to_vec(&format, PLATFORM_BINCODE_CONFIG).expect("encodes"); // After the tag, the id and the config comes the version: the single byte of a small // integer, written here in the longer form of a marker (251) and a big endian u16 let id = bincode::encode_to_vec(v3.id, PLATFORM_BINCODE_CONFIG).expect("encodes"); let config = bincode::encode_to_vec(&v3.config, PLATFORM_BINCODE_CONFIG).expect("encodes"); let at = 1 + id.len() + config.len(); let version = u8::try_from(v3.version).expect("expected a small contract version"); assert!(version < 251); assert_eq!(bytes[at], version); bytes.splice(at..=at, [251, 0, version]); let (decoded, _) = bincode::borrow_decode_from_slice_untrusted::< DataContractInSerializationFormat, _, >(&bytes, PLATFORM_BINCODE_CONFIG) .expect("expected bincode to read the longer form"); assert_eq!(decoded, format); let error = DataContract::versioned_deserialize_untrusted(&bytes, false, platform_version) .expect_err("expected the longer form to be refused"); assert!( error.to_string().contains("not the ones it is written as"), "{error}" ); } /// Format version 3 is compared field by field, its definitions by equality. #[test] fn should_name_the_first_field_two_format_version_3_contracts_differ_in() { let (origin, contract) = corpus_contracts() .into_iter() .find(|(_, contract)| { contract.schema_defs().is_some() && !contract.document_types().is_empty() }) .expect("expected a corpus contract with `$defs`"); let format = with_definitions(&origin, &contract); let DataContractInSerializationFormat::V3(v3) = format.clone() else { panic!("expected format version 3"); }; assert_eq!(format.first_mismatch(&format), None); let changed = |change: fn(&mut DataContractInSerializationFormatV3)| { let mut other = v3.clone(); change(&mut other); format.first_mismatch(&DataContractInSerializationFormat::V3(other)) }; assert_eq!( changed(|other| other.definitions = None), Some(DataContractMismatch::Definitions) ); assert_eq!( changed(|other| { other.document_definitions.pop_first(); }), Some(DataContractMismatch::DocumentDefinitions) ); assert_eq!( changed(|other| other.version += 1), Some(DataContractMismatch::Version) ); assert_eq!( changed(|other| other.keywords.push("another".to_string())), Some(DataContractMismatch::Keywords) ); let schemas = with_schemas(&origin, &contract); assert_eq!( format.first_mismatch(&schemas), Some(DataContractMismatch::FormatVersionMismatch) ); // The accessors of a format that holds schemas find none here, and say so assert!(format.document_schemas().is_empty()); assert!(format.schema_defs().is_none()); assert!(format.clone().document_schemas_mut().is_err()); assert_eq!( format.document_definitions().map(BTreeMap::len), Some(contract.document_types().len()) ); assert!(format.definitions().is_some()); assert_eq!(schemas.document_definitions(), None); assert_eq!(format.document_type_names(), schemas.document_type_names()); } /// A contract of `document_schemas` and `schema_defs`, in format version 1. fn contract_of( document_schemas: Vec<(&str, Value)>, schema_defs: Option>, ) -> DataContractInSerializationFormatV1 { let collected = |entries: Vec<(&str, Value)>| -> BTreeMap { entries .into_iter() .map(|(name, schema)| (name.to_string(), schema)) .collect() }; DataContractInSerializationFormatV1 { id: Identifier::new([7; 32]), config: DataContractConfig::default_for_version(PlatformVersion::latest()) .expect("expected a default config"), version: 1, owner_id: Identifier::new([9; 32]), schema_defs: schema_defs.map(collected), document_schemas: collected(document_schemas), created_at: None, updated_at: None, created_at_block_height: None, updated_at_block_height: None, created_at_epoch: None, updated_at_epoch: None, groups: BTreeMap::new(), tokens: BTreeMap::new(), keywords: Vec::new(), description: None, } } /// `format_v1` with its schemas read as definitions, which a client writes: built from no /// contract, so that a contract registration refuses can be written too. fn definitions_of( format_v1: &DataContractInSerializationFormatV1, ) -> DataContractInSerializationFormat { let platform_version = PlatformVersion::latest(); DataContractInSerializationFormat::V3(DataContractInSerializationFormatV3 { id: format_v1.id, config: format_v1.config.clone(), version: format_v1.version, owner_id: format_v1.owner_id, definitions: format_v1.schema_defs.as_ref().map(|schema_defs| { SchemaDefinitions::try_from_schema_defs(schema_defs, platform_version) .expect("expected the `$defs` to read") }), document_definitions: format_v1 .document_schemas .iter() .map(|(name, schema)| { let definition = DocumentTypeDefinition::try_from_schema(schema, platform_version) .unwrap_or_else(|error| panic!("{name} does not read: {error}")); (name.clone(), definition) }) .collect(), created_at: format_v1.created_at, updated_at: format_v1.updated_at, created_at_block_height: format_v1.created_at_block_height, updated_at_block_height: format_v1.updated_at_block_height, created_at_epoch: format_v1.created_at_epoch, updated_at_epoch: format_v1.updated_at_epoch, groups: format_v1.groups.clone(), tokens: format_v1.tokens.clone(), keywords: format_v1.keywords.clone(), description: format_v1.description.clone(), }) } /// A document type of `count` string properties, each with `pattern`. fn patterned(count: usize, pattern: &str) -> Value { let properties: Vec<(Value, Value)> = (0..count) .map(|position| { ( Value::Text(format!("p{position}")), platform_value!({ "type": "string", "pattern": pattern, "maxLength": 63, "position": position as u64, }), ) }) .collect(); platform_value!({ "type": "object", "properties": Value::Map(properties), "additionalProperties": false, }) } /// A document type whose `recipientId` refers to an identity key bound to `bound_to`. fn bound_key_reference(bound_to: &str) -> Value { platform_value!({ "type": "object", "properties": { "recipientId": { "type": "array", "byteArray": true, "minItems": 32, "maxItems": 32, "contentMediaType": "application/x.dash.dpp.identifier", "position": 0, "refersTo": { "type": "identityPublicKey", "keyIdProperty": "recipientKeyId", "keyRequirements": { "purpose": "authentication", "boundTo": bound_to } } }, "recipientKeyId": { "type": "integer", "minimum": 0, "position": 1 } }, "additionalProperties": false }) } fn note() -> Value { platform_value!({ "type": "object", "properties": { "text": { "type": "string", "maxLength": 63, "position": 0 } }, "additionalProperties": false }) } /// Registration refuses from definitions what it refuses from schemas, with the same refusal, /// at each step `create_document_types_from_document_schemas_v1` takes: no document type, the /// pattern bound before any parse, a document type's own parse and schema check, and the checks /// across document types after them. #[test] fn should_refuse_from_definitions_what_registration_refuses_from_schemas() { let most_patterns = usize::from( PlatformVersion::latest() .system_limits .max_contract_schema_patterns, ); let cases: Vec<(&str, DataContractInSerializationFormatV1)> = vec![ ("no document type", contract_of(vec![], None)), ( "one pattern too many", contract_of(vec![("note", patterned(most_patterns + 1, "^a$"))], None), ), ( "one pattern too many with `$defs`", contract_of( vec![("note", patterned(most_patterns, "^a$"))], Some(vec![( "word", platform_value!({ "type": "string", "pattern": "^b$", "maxLength": 5 }), )]), ), ), ( "a pattern that does not compile", contract_of(vec![("note", patterned(1, "("))], None), ), ( "an index of a property the type does not have", contract_of( vec![( "note", platform_value!({ "type": "object", "properties": { "text": { "type": "string", "maxLength": 63, "position": 0 } }, "indices": [{ "name": "byMissing", "properties": [{ "missing": "asc" }] }], "additionalProperties": false }), )], None, ), ), ( "an object without properties", contract_of( vec![( "note", platform_value!({ "type": "object", "properties": {}, "additionalProperties": false }), )], None, ), ), ( "a property required twice", contract_of( vec![( "note", platform_value!({ "type": "object", "properties": { "text": { "type": "string", "maxLength": 63, "position": 0 } }, "required": ["text", "text"], "additionalProperties": false }), )], None, ), ), ( "a key bound to a document type the contract does not have", contract_of( vec![ ("request", bound_key_reference("nowhere")), ("note", note()), ], None, ), ), ]; let (mut refused, mut by_the_schema_check, mut across_types) = (0, 0, 0); let mut differences = Vec::new(); for (what, format_v1) in cases { for full_validation in [false, true] { let (from_schemas, schema_operations) = built(format_v1.clone().into(), full_validation); let (from_definitions, definition_operations) = built(definitions_of(&format_v1), full_validation); let at = format!("{what} (full validation: {full_validation})"); match (from_schemas, from_definitions) { (Ok(_), Ok(_)) if !full_validation => {} (Err(from_schemas), Err(from_definitions)) => { refused += 1; if is_json_schema_error(&from_schemas) { by_the_schema_check += 1; if !is_definition_error(&from_definitions) { differences.push(format!( "{at}: refused by the schema check, from its definitions with \ {from_definitions}" )); } } else if from_schemas.to_string() != from_definitions.to_string() { differences.push(format!( "{at}: refused with {from_schemas} and {from_definitions}" )); } if from_schemas.to_string().contains("boundTo") { across_types += 1; } } (from_schemas, from_definitions) => differences.push(format!( "{at}: from its schemas {:?}, from its definitions {:?}", from_schemas .map(|_| "built") .map_err(|error| error.to_string()), from_definitions .map(|_| "built") .map_err(|error| error.to_string()), )), } if without_sizes(&schema_operations) != without_sizes(&definition_operations) { differences.push(format!( "{at}: records {schema_operations:?} and {definition_operations:?}" )); } } } assert!( differences.is_empty(), "{} differences:\n{}", differences.len(), differences.join("\n") ); // Every case is refused under full validation, the contract without document types without // it too; the schema check refuses some, and the check across document types one assert_eq!(refused, 9, "{refused}"); assert!(by_the_schema_check > 0, "{by_the_schema_check}"); assert_eq!(across_types, 1, "{across_types}"); } /// No protocol version before 16 builds a contract from definitions. #[test] fn should_refuse_format_version_3_before_protocol_version_16() { let (origin, contract) = system_contracts() .into_iter() .next() .expect("expected a system contract"); let format = with_definitions(&origin, &contract); for protocol_version in [1, 8, 9, 15] { let platform_version = PlatformVersion::get(protocol_version).expect("a protocol version"); let error = DataContract::try_from_platform_versioned( format.clone(), false, &mut vec![], platform_version, ) .expect_err("expected format version 3 to be refused"); assert!( matches!(error, ProtocolError::NotSupported(_)), "{protocol_version}: {error}" ); } } /// A contract of tokens alone with `schema_defs`, in format version 1. fn tokens_alone_with(schema_defs: Vec<(&str, Value)>) -> DataContractInSerializationFormatV1 { use crate::data_contract::associated_token::token_configuration::v0::TokenConfigurationV0; use crate::data_contract::associated_token::token_configuration::TokenConfiguration; let mut format_v1 = contract_of(vec![], Some(schema_defs)); format_v1.tokens.insert( 0, TokenConfiguration::V0(TokenConfigurationV0::default_most_restrictive()), ); format_v1 } /// The one difference from schemas a contract built from definitions has on purpose: a contract /// of tokens alone holds its `$defs` to the rules a document type would hold them to, so the /// update adding its first document type is never refused over a definition it does not use. /// From schemas such a contract's `$defs` are not checked. An unused definition breaking a rule /// is refused from definitions, named at its place under `$defs`, and registered from schemas; /// one keeping the rules registers both ways, and without full validation both build. #[test] fn should_hold_the_definitions_of_a_contract_of_tokens_alone_to_the_rules_of_a_document_type() { let invalid = tokens_alone_with(vec![( "word", platform_value!({ "type": "string", "maxBytes": 0 }), )]); let (from_schemas, _) = built(invalid.clone().into(), true); from_schemas.expect("expected the contract to register from schemas"); let (from_definitions, _) = built(definitions_of(&invalid), true); let refusal = from_definitions.expect_err("expected the definition to be refused"); assert!( matches!( &refusal, ProtocolError::ConsensusError(error) if matches!( &**error, ConsensusError::BasicError(BasicError::InvalidDocumentTypeDefinitionError(error)) if error.document_type_name().is_empty() && error.path().starts_with("$defs.word") ) ), "{refusal}" ); for format in [invalid.clone().into(), definitions_of(&invalid)] { built(format, false) .0 .expect("expected the contract to build without full validation"); } let valid = tokens_alone_with(vec![( "word", platform_value!({ "type": "string", "maxLength": 5 }), )]); for format in [valid.clone().into(), definitions_of(&valid)] { built(format, true) .0 .expect("expected the contract to register"); } } /// The size operations a parse recorded. fn size_operations(operations: &[ProtocolValidationOperation]) -> Vec { operations .iter() .filter_map(|operation| match operation { ProtocolValidationOperation::DocumentTypeSchemaValidationForSize(size) => Some(*size), _ => None, }) .collect() } /// The bytes the definitions a format version 3 contract carries encode to. fn encoded_definitions_size(format: &DataContractInSerializationFormat) -> u64 { let DataContractInSerializationFormat::V3(v3) = format else { panic!("expected format version 3"); }; let definitions = v3.definitions.as_ref().expect("expected definitions"); bincode::encode_to_vec(definitions, PLATFORM_BINCODE_CONFIG) .expect("expected the definitions to encode") .len() as u64 } /// An object of an integer nested `levels` objects deep: 2 values of JSON a level. fn nested_definition(levels: usize) -> Value { let mut value = platform_value!({ "type": "integer", "position": 0 }); for _ in 0..levels { value = platform_value!({ "type": "object", "properties": { "x": value }, "additionalProperties": false, "position": 0, }); } value } /// A contract of tokens alone holds its definitions to the depth, `$ref` cycle and reference /// walk a document type's schema gets, not only to the rules of a definition: an unresolved /// `$ref` under a `contains`, a cycle among definitions, and a definition that reads but nests /// past the depth of a schema once it sits in one are each refused at registration, with the /// refusal the same contract gets once it has a document type. From schemas such a contract /// registers, the one difference definitions have on purpose. #[test] fn should_refuse_definitions_of_a_contract_of_tokens_alone_as_with_a_document_type() { std::thread::Builder::new() .stack_size(64 * 1024 * 1024) .spawn(|| { let cases: Vec<(&str, Vec<(&str, Value)>)> = vec![ ( "an unresolved reference under a contains", vec![( "w", platform_value!({ "type": "array", "items": { "type": "integer" }, "contains": { "$ref": "#/$defs/missing" }, "maxItems": 5, }), )], ), ( "a cycle among definitions", vec![ ( "a", platform_value!({ "type": "object", "properties": { "b": { "$ref": "#/$defs/b", "position": 0 } }, "additionalProperties": false, }), ), ( "b", platform_value!({ "type": "object", "properties": { "a": { "$ref": "#/$defs/a", "position": 0 } }, "additionalProperties": false, }), ), ], ), ( "a definition nested past the depth of a schema", vec![("d", nested_definition(127))], ), ]; for (what, schema_defs) in cases { let tokens_alone = tokens_alone_with(schema_defs); let carried = definitions_of(&tokens_alone); let (registered, operations) = built(carried.clone(), true); let refusal = registered.expect_err(what).to_string(); // Billed once, with the bytes the definitions encode to, refused as they are assert_eq!( size_operations(&operations), vec![encoded_definitions_size(&carried)], "{what}" ); let mut with_a_type = tokens_alone.clone(); with_a_type .document_schemas .insert("note".to_string(), note()); let (with_a_type, _) = built(definitions_of(&with_a_type), true); assert_eq!(with_a_type.expect_err(what).to_string(), refusal, "{what}"); built(tokens_alone.into(), true) .0 .unwrap_or_else(|error| panic!("{what} registers from schemas: {error}")); } // Within the depth, it registers let (registered, _) = built( definitions_of(&tokens_alone_with(vec![("d", nested_definition(126))])), true, ); registered.expect("expected definitions within the depth to register"); }) .expect("expected the test thread to start") .join() .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); } /// Registration bills the check of a contract of tokens alone's definitions as it bills a /// document type: one size operation, the bytes the definitions encode to, whether they are /// admitted or refused. A contract with a document type records one for the type, which holds /// its definition and the contract's definitions, and none more; an empty `$defs` records none. #[test] fn should_bill_the_definitions_of_a_contract_of_tokens_alone_once() { let admitted = definitions_of(&tokens_alone_with(vec![( "word", platform_value!({ "type": "string", "maxLength": 5 }), )])); let refused = definitions_of(&tokens_alone_with(vec![( "word", platform_value!({ "type": "string", "maxBytes": 0 }), )])); for (format, registers) in [(admitted, true), (refused, false)] { let (registered, operations) = built(format.clone(), true); assert_eq!(registered.is_ok(), registers); assert_eq!( size_operations(&operations), vec![encoded_definitions_size(&format)] ); } let mut with_a_type = tokens_alone_with(vec![( "word", platform_value!({ "type": "string", "maxLength": 5 }), )]); with_a_type .document_schemas .insert("note".to_string(), note()); let (registered, operations) = built(definitions_of(&with_a_type), true); registered.expect("expected the contract to register"); assert_eq!(size_operations(&operations).len(), 1); let (registered, operations) = built(definitions_of(&tokens_alone_with(vec![])), true); registered.expect("expected the contract to register"); assert!(size_operations(&operations).is_empty()); }