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
11 changes: 11 additions & 0 deletions book/src/data-model/contested-documents.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ but a poll is hashed from its values, and that hash keys the contest's prefunded
date: two contenders writing the same identifier two ways would otherwise split one contest into
two polls. Before 14 the values are taken as given.

From protocol version 15 every index value is written one way, the way its property's type keys
it: an integer in any integer form as the type's own integer, a date as a `u64`, an integer or a
float of a float property as a float, bytes in any form as bytes, and `"\0"` as the empty string
it shares a key with. That is the value a query of the contest returns. A masternode vote names
its poll by the values it sends, unchanged, and is refused unless a prefunded balance is held
under that poll, so a voter sends the values as the contest query returns them.

A contest under way keeps the poll it was opened under. A contender that joins a contest opened
at an earlier protocol version has its index values written as that version wrote them, so it
funds the same prefunded balance and the contest keeps its end date.

## Resolution 0: masternode vote

The DPNS rule. The choices are a contender, abstain, or **lock**, which gives the value to nobody.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod v0;
mod v1;

use crate::data_contract::document_type::property::DocumentProperty;
use crate::data_contract::document_type::Index;
Expand All @@ -18,6 +19,12 @@ impl Index {
/// its own prefunded balance and end date. `document_properties` are the document type's
/// flattened properties. Before 14 the values are taken as given.
///
/// From protocol version 15 the value of every property is written one way, the way its
/// type keys it: an integer as its type's own integer, an integer or a float of a float
/// property as a float, bytes in any form as bytes, `"\0"` as the empty string it shares
/// a key with. A contest is stored at the path of its index keys, so values with one key
/// are one contest, and they now name one poll.
///
/// # Parameters
/// * `data`: the document's properties.
/// * `document_properties`: the document type's flattened properties.
Expand All @@ -40,9 +47,10 @@ impl Index {
{
None => Ok(self.extract_values(data)),
Some(0) => Ok(self.extract_contested_values_v0(data, document_properties)),
Some(1) => Ok(self.extract_contested_values_v1(data, document_properties)),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Some(version) => Err(ProtocolError::UnknownVersionMismatch {
method: "Index::extract_contested_values".to_string(),
known_versions: vec![0],
known_versions: vec![0, 1],
received: version,
}),
}
Expand Down Expand Up @@ -70,9 +78,190 @@ mod tests {
use super::*;
use crate::data_contract::document_type::index::tests::make_index;
use crate::data_contract::document_type::property::{
ByteArrayPropertySizes, DocumentPropertyType,
ByteArrayPropertySizes, DocumentPropertyType, StringPropertySizes,
};

fn property(property_type: DocumentPropertyType) -> DocumentProperty {
DocumentProperty {
property_type,
required: true,
transient: false,
required_since: None,
distinct_from: None,
encrypted_for: None,
generated_from: None,
revealed_reference: None,
}
}

/// The values a contest over one property of `property_type` names itself by, for a
/// document holding `value`.
fn contest_values(
property_type: &DocumentPropertyType,
value: &Value,
platform_version: &PlatformVersion,
) -> Vec<Value> {
make_index("contested", vec![("value", true)], true)
.extract_contested_values(
&BTreeMap::from([("value".to_string(), value.clone())]),
&IndexMap::from([("value".to_string(), property(property_type.clone()))]),
platform_version,
)
.expect("values")
}

/// From protocol version 15 the forms of a value that share a key in the paths of a vote
/// poll are written one way, so they name one poll: the way a query of the contest decodes
/// that key, so a voter reading the contest names the same poll. Protocol version 14 takes
/// them as given, identifiers apart.
#[test]
fn should_write_contest_values_that_share_a_key_one_way_from_version_15() {
let integer_forms = || vec![Value::U8(5), Value::I16(5), Value::U64(5), Value::I128(5)];
let bytes = ByteArrayPropertySizes {
min_size: None,
max_size: None,
};
let string = StringPropertySizes {
min_length: None,
max_length: None,
max_bytes: None,
};
let float_forms = {
let mut forms = integer_forms();
forms.push(Value::Float(5.0));
forms
};
let cases: Vec<(DocumentPropertyType, Vec<Value>, Value)> = vec![
(DocumentPropertyType::U128, integer_forms(), Value::U128(5)),
(DocumentPropertyType::I128, integer_forms(), Value::I128(5)),
(DocumentPropertyType::U64, integer_forms(), Value::U64(5)),
(DocumentPropertyType::I64, integer_forms(), Value::I64(5)),
(DocumentPropertyType::U32, integer_forms(), Value::U32(5)),
(DocumentPropertyType::I32, integer_forms(), Value::I32(5)),
(DocumentPropertyType::U16, integer_forms(), Value::U16(5)),
(DocumentPropertyType::I16, integer_forms(), Value::I16(5)),
(DocumentPropertyType::U8, integer_forms(), Value::U8(5)),
(DocumentPropertyType::I8, integer_forms(), Value::I8(5)),
(DocumentPropertyType::Date, integer_forms(), Value::U64(5)),
(DocumentPropertyType::F64, float_forms, Value::Float(5.0)),
(
DocumentPropertyType::String(string.clone()),
vec![Value::Text(String::new()), Value::Text("\0".to_string())],
Value::Text(String::new()),
),
(
DocumentPropertyType::String(string),
vec![Value::Text("dash".to_string())],
Value::Text("dash".to_string()),
),
(
DocumentPropertyType::ByteArray(bytes.clone()),
vec![
Value::Bytes(vec![1, 2, 3]),
Value::Array(vec![Value::U8(1), Value::U8(2), Value::U8(3)]),
Value::Text("AQID".to_string()),
],
Value::Bytes(vec![1, 2, 3]),
),
(
DocumentPropertyType::ByteArray(bytes.clone()),
vec![
Value::Bytes(vec![7; 32]),
Value::Bytes32([7; 32]),
Value::Identifier([7; 32]),
],
Value::Bytes(vec![7; 32]),
),
// No bytes have the empty key, as a missing value has
(
DocumentPropertyType::ByteArray(bytes),
vec![Value::Bytes(vec![]), Value::Array(vec![])],
Value::Null,
),
(
DocumentPropertyType::Identifier,
vec![
Value::Identifier([0x7A; 32]),
Value::Bytes32([0x7A; 32]),
Value::Bytes(vec![0x7A; 32]),
Value::Array(vec![Value::U8(0x7A); 32]),
Value::Text(bs58::encode([0x7A; 32]).into_string()),
],
Value::Identifier([0x7A; 32]),
),
(
DocumentPropertyType::Boolean,
vec![Value::Bool(true)],
Value::Bool(true),
),
];
let latest = PlatformVersion::latest();
let version_14 = PlatformVersion::get(14).expect("protocol version 14");

for (property_type, forms, expected) in cases {
for form in forms {
assert_eq!(
contest_values(&property_type, &form, latest),
vec![expected.clone()],
"{property_type:?} {form:?}"
);
let key = property_type
.encode_value_for_tree_keys(&form)
.expect("expected the key of the value");
assert_eq!(
property_type
.decode_value_for_tree_keys(&key)
.expect("expected the value of the key"),
expected,
"{property_type:?} {form:?}"
);
if !matches!(property_type, DocumentPropertyType::Identifier) {
assert_eq!(
contest_values(&property_type, &form, version_14),
vec![form],
"{property_type:?}"
);
}
}
}
}

/// A value its property's type does not key is in no contest, and is left as it is.
#[test]
fn should_leave_a_contest_value_its_type_does_not_key_as_it_is() {
let latest = PlatformVersion::latest();
for (property_type, value) in [
(DocumentPropertyType::U8, Value::I64(-1)),
(DocumentPropertyType::U8, Value::U64(256)),
(DocumentPropertyType::I64, Value::Text("5".to_string())),
(DocumentPropertyType::F64, Value::Text("5".to_string())),
(DocumentPropertyType::Boolean, Value::U8(1)),
(DocumentPropertyType::Identifier, Value::Bytes(vec![1; 31])),
// Longer than any identifier in base 58, so it is not decoded
(
DocumentPropertyType::Identifier,
Value::Text("1".repeat(4096)),
),
(DocumentPropertyType::I64, Value::Null),
] {
assert_eq!(
contest_values(&property_type, &value, latest),
vec![value.clone()],
"{property_type:?} {value:?}"
);
}

// A property path or a system property is no top-level property of the type
let index = make_index("contested", vec![("$ownerId", true)], true);
let data = BTreeMap::from([("$ownerId".to_string(), Value::Bytes(vec![1; 32]))]);
assert_eq!(
index
.extract_contested_values(&data, &IndexMap::new(), latest)
.expect("values"),
vec![Value::Bytes(vec![1; 32])]
);
}

/// From protocol version 14 an identifier index value in any accepted form is written as
/// `Value::Identifier`, so every contender of one contest names it with the same poll; a
/// byte array property keeps its bytes. Before 14 the values are taken as given.
Expand All @@ -83,16 +272,6 @@ mod tests {
vec![("targetContractId", true), ("salt", true)],
true,
);
let property = |property_type| DocumentProperty {
property_type,
required: true,
transient: false,
required_since: None,
distinct_from: None,
encrypted_for: None,
generated_from: None,
revealed_reference: None,
};
let document_properties = IndexMap::from([
(
"targetContractId".to_string(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use super::contested_index_identifier;
use crate::data_contract::document_type::property::{DocumentProperty, DocumentPropertyType};
use crate::data_contract::document_type::Index;
use indexmap::IndexMap;
use platform_value::Value;
use std::collections::BTreeMap;

impl Index {
/// The index values of `data`, each written the one way its property's type writes every
/// value that shares its key in the paths of a vote poll.
#[inline(always)]
pub(super) fn extract_contested_values_v1(
&self,
data: &BTreeMap<String, Value>,
document_properties: &IndexMap<String, DocumentProperty>,
) -> Vec<Value> {
self.properties
.iter()
.zip(self.extract_values(data))
.map(
|(index_property, value)| match document_properties.get(&index_property.name) {
Some(property) => {
canonical_contested_index_value(&property.property_type, value)
}
// Not a top-level property of the type: a contested create reads its
// index values from the document's top-level properties, so it finds
// no value here
None => value,
},
)
.collect()
}
}

/// `value` as a property of `property_type` writes every value with the same key in the paths
/// of a vote poll (`DocumentPropertyType::encode_value_for_tree_keys`), which is also the
/// value a query of the contest decodes from that key. A value the type does not key (one of
/// another kind, or an integer out of the type's range) is returned as it is: no contest holds
/// it.
///
/// Every type is listed, so that a new type states the form it takes.
fn canonical_contested_index_value(property_type: &DocumentPropertyType, value: Value) -> Value {
if value.is_null() {
return value;
}
let canonical = match property_type {
// An integer in any integer form is keyed by its number alone
DocumentPropertyType::U128 => value.to_integer().ok().map(Value::U128),
DocumentPropertyType::I128 => value.to_integer().ok().map(Value::I128),
DocumentPropertyType::U64 => value.to_integer().ok().map(Value::U64),
DocumentPropertyType::I64 => value.to_integer().ok().map(Value::I64),
DocumentPropertyType::U32 | DocumentPropertyType::KeyIdWithReference(_) => {
value.to_integer().ok().map(Value::U32)
}
DocumentPropertyType::I32 => value.to_integer().ok().map(Value::I32),
DocumentPropertyType::U16 => value.to_integer().ok().map(Value::U16),
DocumentPropertyType::I16 => value.to_integer().ok().map(Value::I16),
DocumentPropertyType::U8 => value.to_integer().ok().map(Value::U8),
DocumentPropertyType::I8 => value.to_integer().ok().map(Value::I8),
// A date is keyed as its timestamp
DocumentPropertyType::Date => value.to_integer().ok().map(Value::U64),
// A float is keyed by its bits, and an integer as the float it converts to
DocumentPropertyType::F64 => value.to_float().ok().map(Value::Float),
// Only the empty string and `"\0"` share a key, `[0]`
DocumentPropertyType::String(_) => match &value {
Value::Text(text) if text == "\0" => Some(Value::Text(String::new())),
_ => None,
},
// Bytes in any form are keyed by the bytes alone, and no bytes by the empty key, as
// a missing value is
DocumentPropertyType::ByteArray(_) => value.to_binary_bytes().ok().map(|bytes| {
if bytes.is_empty() {
Value::Null
} else {
Value::Bytes(bytes)
}
}),
// The forms protocol version 14 already wrote as an identifier, then every other
// form keyed by the same 32 bytes. A text is read only when it is short enough to be
// an identifier in base 58: no schema has bounded it yet, and decoding base 58 takes
// time quadratic in its length
DocumentPropertyType::Identifier | DocumentPropertyType::IdentifierWithReference(_) => {
contested_index_identifier(&value)
.or_else(|| {
value
.to_bounded_identifier()
.ok()
.map(|identifier| identifier.to_buffer())
})
.map(Value::Identifier)
}
// Keyed only as a boolean
DocumentPropertyType::Boolean => None,
// Never keyed whole: no index holds an object, and a contested index holds no array
DocumentPropertyType::Object(_)
| DocumentPropertyType::Array(_)
| DocumentPropertyType::VariableTypeArray(_)
| DocumentPropertyType::TypedArray(_) => None,
};
canonical.unwrap_or(value)
}
Original file line number Diff line number Diff line change
Expand Up @@ -418,9 +418,10 @@ pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBa
}
})
.map(|index| {
// Identifier values are written one way from protocol version 14, so every
// contender of a contest names it with the same poll; before 14 they are taken
// as given, as they always were
// Every contender of a contest names it with the same poll: from protocol
// version 15 every index value is written the one way its property's type keys
// it, at protocol version 14 identifier values alone are written one way, and
// before 14 the values are taken as given
let index_values = index.extract_contested_values(
document_properties,
self.flattened_properties(),
Expand Down
Loading
Loading