Skip to main content

dpp/decision_proposal/
mod.rs

1//! Decision proposals (protocol version 15).
2//!
3//! A decision proposal is a yes/no question any identity puts to the masternodes: a `proposal`
4//! document of the decision proposals system contract. Creating one opens a yes/no vote poll
5//! ([`YesNoVotePoll`]) whose purpose is the proposal ([`YesNoVotePollPurpose::DecisionProposal`])
6//! and whose rule is the one the proposal states, and funds the poll's votes with the decision
7//! proposal fund, which the proposer pays. Proposals are signaling only: nothing acts on a
8//! result, which stays in the poll's stored info.
9//!
10//! [`DecisionProposalVotePoll::from_proposal`] reads the poll a proposal opens from its id and
11//! properties. Consensus uses it to open the poll, and clients to name the poll they query.
12//!
13//! A multiple choice proposal opens no yes/no poll: its choices contend in a masternode vote
14//! among documents, which [`multiple_choice`] names for clients.
15
16pub mod multiple_choice;
17
18use crate::balances::credits::Credits;
19use crate::consensus::basic::decision_proposal::InvalidDecisionProposalRuleError;
20use crate::prelude::TimestampMillis;
21use crate::validation::ConsensusValidationResult;
22use crate::voting::vote_polls::yes_no_vote_poll::{
23    VotingPowerRounding, YesNoMinimumVotingPower, YesNoVotePoll, YesNoVotePollPurpose,
24};
25use crate::ProtocolError;
26use platform_value::btreemap_extensions::BTreeValueMapPathHelper;
27use platform_value::{Identifier, IdentifierBytes32, Value};
28use platform_version::version::PlatformVersion;
29use std::collections::BTreeMap;
30
31/// The id of the decision proposals system contract, `3iNyoNwjCTkb7XS3RHyWUtLx7pgC6AFAEQNNDHzxqngF`.
32///
33/// Spelled here so that consensus code can name the contract without the optional contract
34/// crates; the crate's own constant is pinned to this one by a test.
35pub const DECISION_PROPOSALS_CONTRACT_ID: Identifier = Identifier(IdentifierBytes32([
36    40, 81, 10, 2, 166, 107, 62, 218, 6, 184, 111, 202, 230, 218, 170, 157, 181, 119, 102, 211,
37    195, 114, 92, 200, 90, 88, 205, 30, 174, 49, 203, 200,
38]));
39
40/// The name of the proposal document type.
41pub const PROPOSAL_DOCUMENT_TYPE_NAME: &str = "proposal";
42
43/// The name a proposal's create states its fund under, in its prefunded voting balance: the
44/// proposal's own type. A contested create names its contested index there instead.
45pub const DECISION_PROPOSAL_FUND_NAME: &str = PROPOSAL_DOCUMENT_TYPE_NAME;
46
47/// The name of the multiple choice proposal document type: a question whose answers are the
48/// choices entered for it, which contend in a masternode vote the first choice opens.
49pub const MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME: &str = "multipleChoiceProposal";
50
51/// The properties of a proposal.
52pub mod properties {
53    /// The question, in one line. Editable for a day after the proposal is created.
54    pub const TITLE: &str = "title";
55    /// What a yes and a no mean. Editable for a day after the proposal is created.
56    pub const DESCRIPTION: &str = "description";
57    /// Where the proposal is discussed; optional. Editable for a day after the proposal is
58    /// created.
59    pub const URL: &str = "url";
60    /// The proposal passes when yes is strictly more than this percent of yes plus no.
61    pub const PASS_PERCENT: &str = "passPercent";
62    /// The least yes plus no voting power the proposal needs, as a percent of the masternode
63    /// list's total voting power when the poll closes, rounded up.
64    pub const MINIMUM_TURNOUT_PERCENT: &str = "minimumTurnoutPercent";
65    /// When voting closes, in milliseconds since the Unix epoch: from a week to four weeks
66    /// after the block that creates the proposal.
67    pub const END_DATE: &str = "endDate";
68}
69
70/// Whether a document of `document_type_name` in the contract `contract_id` is a decision
71/// proposal: a `proposal` of the decision proposals contract. Its create opens a yes/no poll and
72/// states the decision proposal fund instead of a contest's.
73pub fn is_decision_proposal(contract_id: &Identifier, document_type_name: &str) -> bool {
74    *contract_id == DECISION_PROPOSALS_CONTRACT_ID
75        && document_type_name == PROPOSAL_DOCUMENT_TYPE_NAME
76}
77
78/// The fund a decision proposal's create must state, exactly: the fee version's
79/// `decision_proposal_fund_required_amount`. It prefunds the votes on the poll; what is left
80/// when the poll ends goes to processing fees.
81pub fn decision_proposal_required_fund(platform_version: &PlatformVersion) -> Credits {
82    platform_version
83        .fee_version
84        .vote_resolution_fund_fees
85        .decision_proposal_fund_required_amount
86}
87
88/// Whether a document of `document_type_name` in the contract `contract_id` is a multiple
89/// choice proposal: a `multipleChoiceProposal` of the decision proposals contract. Its create
90/// opens no poll and states no fund; it pays the multiple choice proposal processing fee.
91pub fn is_multiple_choice_proposal(contract_id: &Identifier, document_type_name: &str) -> bool {
92    *contract_id == DECISION_PROPOSALS_CONTRACT_ID
93        && document_type_name == MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME
94}
95
96/// What creating one multiple choice proposal adds to the processing fee of its batch: the
97/// fee version's `multiple_choice_proposal_processing_fee`. Unlike a yes/no proposal's fund
98/// it prefunds no votes, since the proposal opens no poll: it goes to the processing fee
99/// pools, and the create does not state it. 0 before protocol version 15.
100pub fn multiple_choice_proposal_processing_fee(platform_version: &PlatformVersion) -> Credits {
101    platform_version
102        .fee_version
103        .vote_resolution_fund_fees
104        .multiple_choice_proposal_processing_fee
105}
106
107/// The id of the yes/no poll the proposal `document_id` opens: the id of the purpose
108/// [`YesNoVotePollPurpose::DecisionProposal`], which a vote on the proposal names and the poll
109/// queries take. Known from the proposal's id alone, before or after the poll opens.
110///
111/// # Parameters
112/// - `document_id`: the proposal's id.
113/// - `platform_version`: the platform version, which selects how the id is derived.
114///
115/// # Returns
116/// The poll's id, or an error before protocol version 15.
117pub fn decision_proposal_vote_poll_id(
118    document_id: Identifier,
119    platform_version: &PlatformVersion,
120) -> Result<Identifier, ProtocolError> {
121    YesNoVotePollPurpose::DecisionProposal { document_id }.unique_id(platform_version)
122}
123
124/// The yes/no poll a decision proposal opens and when it closes.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct DecisionProposalVotePoll {
127    /// The poll: the proposal as its purpose, the proposal's rule.
128    pub vote_poll: YesNoVotePoll,
129    /// The proposal's `endDate`: when the poll closes.
130    pub end_date: TimestampMillis,
131}
132
133impl DecisionProposalVotePoll {
134    /// The poll the proposal with `document_id` and `properties` opens, by the rule the
135    /// platform version selects (`dpp.voting_versions.decision_proposal_vote_poll`).
136    ///
137    /// The properties are expected to have passed the proposal's schema. A rule that makes no
138    /// poll the system limits allow is refused with [`InvalidDecisionProposalRuleError`]; the
139    /// end date is judged against the opening block by the caller
140    /// ([`YesNoVotePoll::end_date_window`]).
141    ///
142    /// # Parameters
143    /// - `document_id`: the proposal's id, the poll's purpose.
144    /// - `properties`: the proposal's properties.
145    /// - `platform_version`: the platform version, whose system limits bound the rule.
146    ///
147    /// # Returns
148    /// The poll and its end date, or the consensus error refusing the rule.
149    pub fn from_proposal(
150        document_id: Identifier,
151        properties: &BTreeMap<String, Value>,
152        platform_version: &PlatformVersion,
153    ) -> Result<ConsensusValidationResult<Self>, ProtocolError> {
154        match platform_version
155            .dpp
156            .voting_versions
157            .decision_proposal_vote_poll
158        {
159            Some(0) => Ok(Self::from_proposal_v0(
160                document_id,
161                properties,
162                platform_version,
163            )),
164            Some(version) => Err(ProtocolError::UnknownVersionMismatch {
165                method: "DecisionProposalVotePoll::from_proposal".to_string(),
166                known_versions: vec![0],
167                received: version,
168            }),
169            None => Err(ProtocolError::UnknownVersionError(
170                "DecisionProposalVotePoll::from_proposal is not active before protocol version 15"
171                    .to_string(),
172            )),
173        }
174    }
175
176    /// Version 0: the poll passes when yes is strictly more than `passPercent` percent of yes
177    /// plus no (a supermajority of `passPercent / 100`), with yes plus no at least
178    /// `minimumTurnoutPercent` percent of the masternode list's total voting power when it
179    /// closes, rounded up. The rule is held to [`YesNoVotePoll::validate_parameters`]; the
180    /// contract's schema holds the percentages to 50 to 80 and 0 to 50.
181    fn from_proposal_v0(
182        document_id: Identifier,
183        properties: &BTreeMap<String, Value>,
184        platform_version: &PlatformVersion,
185    ) -> ConsensusValidationResult<Self> {
186        let read = || -> Result<Self, String> {
187            let percent = |path: &str| -> Result<u8, String> {
188                let value = properties
189                    .get_optional_integer_at_path::<u64>(path)
190                    .map_err(|error| format!("`{path}` is not a whole number: {error}"))?
191                    .ok_or_else(|| format!("`{path}` is required"))?;
192                u8::try_from(value).map_err(|_| format!("`{path}` is at most 255, got {value}"))
193            };
194            let pass_percent = percent(properties::PASS_PERCENT)?;
195            let minimum_turnout_percent = percent(properties::MINIMUM_TURNOUT_PERCENT)?;
196            let end_date = properties
197                .get_optional_integer_at_path::<u64>(properties::END_DATE)
198                .map_err(|error| {
199                    format!("`{}` is not a whole number: {error}", properties::END_DATE)
200                })?
201                .ok_or_else(|| format!("`{}` is required", properties::END_DATE))?;
202            let vote_poll = YesNoVotePoll {
203                purpose: YesNoVotePollPurpose::DecisionProposal { document_id },
204                supermajority_numerator: pass_percent,
205                supermajority_denominator: 100,
206                minimum_voting_power: YesNoMinimumVotingPower::FractionOfTotal {
207                    numerator: minimum_turnout_percent,
208                    denominator: 100,
209                    rounding: VotingPowerRounding::Up,
210                },
211            };
212            vote_poll
213                .validate_parameters(platform_version)
214                .map_err(|error| match error {
215                    ProtocolError::VoteError(reason) => reason,
216                    other => other.to_string(),
217                })?;
218            Ok(Self {
219                vote_poll,
220                end_date,
221            })
222        };
223        match read() {
224            Ok(decision_proposal_vote_poll) => {
225                ConsensusValidationResult::new_with_data(decision_proposal_vote_poll)
226            }
227            Err(reason) => ConsensusValidationResult::new_with_error(
228                InvalidDecisionProposalRuleError::new(document_id, reason).into(),
229            ),
230        }
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use crate::consensus::basic::BasicError;
238    use crate::consensus::ConsensusError;
239
240    fn proposal(pass_percent: u8, minimum_turnout_percent: u8) -> BTreeMap<String, Value> {
241        BTreeMap::from([
242            (
243                "title".to_string(),
244                Value::Text("Raise the limit?".to_string()),
245            ),
246            (
247                properties::PASS_PERCENT.to_string(),
248                Value::U8(pass_percent),
249            ),
250            (
251                properties::MINIMUM_TURNOUT_PERCENT.to_string(),
252                Value::U8(minimum_turnout_percent),
253            ),
254            (properties::END_DATE.to_string(), Value::U64(5_000)),
255        ])
256    }
257
258    fn refusal(result: ConsensusValidationResult<DecisionProposalVotePoll>) -> String {
259        match result.errors.as_slice() {
260            [ConsensusError::BasicError(BasicError::InvalidDecisionProposalRuleError(error))] => {
261                error.reason().to_string()
262            }
263            other => panic!("expected one invalid rule error, got {other:?}"),
264        }
265    }
266
267    #[test]
268    fn should_read_the_poll_a_proposal_opens() {
269        let platform_version = PlatformVersion::latest();
270        let document_id = Identifier::new([7; 32]);
271        let result = DecisionProposalVotePoll::from_proposal(
272            document_id,
273            &proposal(60, 10),
274            platform_version,
275        )
276        .expect("active at 15");
277        assert_eq!(
278            result.into_data().expect("a valid rule"),
279            DecisionProposalVotePoll {
280                vote_poll: YesNoVotePoll {
281                    purpose: YesNoVotePollPurpose::DecisionProposal { document_id },
282                    supermajority_numerator: 60,
283                    supermajority_denominator: 100,
284                    minimum_voting_power: YesNoMinimumVotingPower::FractionOfTotal {
285                        numerator: 10,
286                        denominator: 100,
287                        rounding: VotingPowerRounding::Up,
288                    },
289                },
290                end_date: 5_000,
291            }
292        );
293    }
294
295    /// Yes must be strictly more than the percent: at 50, a tie fails and one more yes passes.
296    #[test]
297    fn should_pass_only_strictly_above_the_pass_percent() {
298        let platform_version = PlatformVersion::latest();
299        let vote_poll = DecisionProposalVotePoll::from_proposal(
300            Identifier::new([7; 32]),
301            &proposal(50, 0),
302            platform_version,
303        )
304        .expect("active at 15")
305        .into_data()
306        .expect("a valid rule")
307        .vote_poll;
308        let passes = |yes, no| {
309            vote_poll
310                .passes(yes, no, 1_000, platform_version)
311                .expect("15")
312        };
313        assert!(!passes(5, 5));
314        assert!(passes(6, 5));
315        // A turnout minimum of 10% of 95 rounds up to 10
316        let vote_poll = DecisionProposalVotePoll::from_proposal(
317            Identifier::new([7; 32]),
318            &proposal(50, 10),
319            platform_version,
320        )
321        .expect("active at 15")
322        .into_data()
323        .expect("a valid rule")
324        .vote_poll;
325        assert_eq!(
326            vote_poll
327                .required_voting_power(95, platform_version)
328                .expect("15"),
329            10
330        );
331    }
332
333    #[test]
334    fn should_refuse_a_rule_outside_the_limits() {
335        let platform_version = PlatformVersion::latest();
336        let document_id = Identifier::new([7; 32]);
337        let read = |properties: BTreeMap<String, Value>| {
338            DecisionProposalVotePoll::from_proposal(document_id, &properties, platform_version)
339                .expect("active at 15")
340        };
341        // The schema holds a proposal to 50-80 and 0-50; the poll's own rules still refuse what
342        // no poll may run with, whatever a schema allows.
343        assert!(refusal(read(proposal(49, 0))).contains("at least 50%"));
344        assert!(refusal(read(proposal(100, 0))).contains("below its denominator"));
345        assert!(refusal(read(proposal(60, 51))).contains("at most 50%"));
346        assert!(read(proposal(50, 50)).is_valid());
347        let mut no_turnout = proposal(60, 0);
348        no_turnout.remove(properties::MINIMUM_TURNOUT_PERCENT);
349        assert!(refusal(read(no_turnout)).contains("is required"));
350    }
351
352    /// The poll id read from the proposal's id alone is the id of the poll the proposal opens.
353    #[test]
354    fn should_name_the_poll_of_a_proposal_by_its_id_alone() {
355        let platform_version = PlatformVersion::latest();
356        let document_id = Identifier::new([7; 32]);
357        let opened = DecisionProposalVotePoll::from_proposal(
358            document_id,
359            &proposal(60, 10),
360            platform_version,
361        )
362        .expect("active at 15")
363        .into_data()
364        .expect("a valid rule")
365        .vote_poll;
366        assert_eq!(
367            decision_proposal_vote_poll_id(document_id, platform_version).expect("active at 15"),
368            opened.unique_id(platform_version).expect("active at 15")
369        );
370        assert_ne!(
371            decision_proposal_vote_poll_id(Identifier::new([8; 32]), platform_version)
372                .expect("active at 15"),
373            opened.unique_id(platform_version).expect("active at 15")
374        );
375        assert!(matches!(
376            decision_proposal_vote_poll_id(
377                document_id,
378                PlatformVersion::get(14).expect("expected protocol version 14")
379            ),
380            Err(ProtocolError::UnknownVersionError(_))
381        ));
382    }
383
384    #[test]
385    fn should_not_be_active_before_protocol_version_15() {
386        let platform_version = PlatformVersion::get(14).expect("expected protocol version 14");
387        assert!(matches!(
388            DecisionProposalVotePoll::from_proposal(
389                Identifier::new([7; 32]),
390                &proposal(60, 10),
391                platform_version,
392            ),
393            Err(ProtocolError::UnknownVersionError(_))
394        ));
395    }
396
397    #[test]
398    fn should_recognize_only_the_proposal_of_the_decision_proposals_contract() {
399        assert!(is_decision_proposal(
400            &DECISION_PROPOSALS_CONTRACT_ID,
401            PROPOSAL_DOCUMENT_TYPE_NAME
402        ));
403        assert!(!is_decision_proposal(
404            &DECISION_PROPOSALS_CONTRACT_ID,
405            "other"
406        ));
407        assert!(!is_decision_proposal(
408            &Identifier::new([1; 32]),
409            PROPOSAL_DOCUMENT_TYPE_NAME
410        ));
411    }
412
413    #[cfg(feature = "decision-proposals-contract")]
414    #[test]
415    fn should_name_the_contract_as_its_crate_does() {
416        use data_contracts::decision_proposals_contract;
417        use decision_proposals_contract::v1::document_types::proposal;
418
419        assert_eq!(
420            DECISION_PROPOSALS_CONTRACT_ID,
421            decision_proposals_contract::ID
422        );
423        assert_eq!(PROPOSAL_DOCUMENT_TYPE_NAME, proposal::NAME);
424        assert_eq!(properties::TITLE, proposal::properties::TITLE);
425        assert_eq!(properties::DESCRIPTION, proposal::properties::DESCRIPTION);
426        assert_eq!(properties::URL, proposal::properties::URL);
427        assert_eq!(properties::PASS_PERCENT, proposal::properties::PASS_PERCENT);
428        assert_eq!(
429            properties::MINIMUM_TURNOUT_PERCENT,
430            proposal::properties::MINIMUM_TURNOUT_PERCENT
431        );
432        assert_eq!(properties::END_DATE, proposal::properties::END_DATE);
433    }
434
435    /// A proposal's title, description and url freeze a day after it is created, or after a
436    /// fifth of the time it runs if that is shorter (which the one-week minimum makes it never
437    /// is today); its rule never changes.
438    #[cfg(feature = "decision-proposals-contract")]
439    #[test]
440    fn should_freeze_the_text_of_a_proposal_after_a_day_or_a_fifth_of_its_run() {
441        use crate::data_contract::accessors::v0::DataContractV0Getters;
442        use crate::data_contract::document_type::accessors::{
443            DocumentTypeV0Getters, DocumentTypeV2Getters,
444        };
445        use crate::data_contract::document_type::property_constraints::DocumentSystemValues;
446        use crate::system_data_contracts::{load_system_data_contract, SystemDataContract};
447
448        const DAY_MS: u64 = 86_400_000;
449        let platform_version = PlatformVersion::latest();
450        let contract =
451            load_system_data_contract(SystemDataContract::DecisionProposals, platform_version)
452                .expect("the contract loads at 15");
453        let document_type = contract
454            .document_type_for_name(PROPOSAL_DOCUMENT_TYPE_NAME)
455            .expect("the proposal type");
456        let created_at = 1_000;
457        let frozen = |property: &str, run: u64, edited_after: u64| {
458            document_type.immutable_field_conditions()[property]
459                .holds(
460                    &Value::Map(vec![(
461                        Value::Text(properties::END_DATE.to_string()),
462                        Value::U64(created_at + run),
463                    )]),
464                    &DocumentSystemValues {
465                        created_at: Some(created_at),
466                        updated_at: Some(created_at + edited_after),
467                        ..Default::default()
468                    },
469                )
470                .expect("the condition evaluates")
471        };
472        for property in ["title", "description", "url"] {
473            // Two weeks: a fifth is 2.8 days, so a day comes first
474            assert!(
475                !frozen(property, 14 * DAY_MS, DAY_MS),
476                "{property} at a day"
477            );
478            assert!(
479                frozen(property, 14 * DAY_MS, DAY_MS + 1),
480                "{property} after a day"
481            );
482            // Two days: a fifth, 9.6 hours, comes first
483            let fifth = 2 * DAY_MS / 5;
484            assert!(
485                !frozen(property, 2 * DAY_MS, fifth),
486                "{property} at a fifth"
487            );
488            assert!(
489                frozen(property, 2 * DAY_MS, fifth + 1),
490                "{property} after a fifth"
491            );
492        }
493        for property in [
494            properties::PASS_PERCENT,
495            properties::MINIMUM_TURNOUT_PERCENT,
496            properties::END_DATE,
497        ] {
498            assert!(
499                document_type.immutable_fields().contains(property)
500                    && !document_type
501                        .immutable_field_conditions()
502                        .contains_key(property),
503                "{property} never changes"
504            );
505        }
506        assert!(document_type.documents_mutable());
507        assert!(document_type.documents_keep_history());
508    }
509
510    /// A create built from a proposal document, as the SDKs build one, states the decision
511    /// proposal fund under the proposal's name.
512    #[cfg(feature = "decision-proposals-contract")]
513    #[test]
514    fn should_state_the_decision_proposal_fund_on_a_proposal_create() {
515        use crate::data_contract::accessors::v0::DataContractV0Getters;
516        use crate::data_contract::document_type::methods::DocumentTypeV0Methods;
517        use crate::document::{Document, DocumentV0};
518        use crate::system_data_contracts::{load_system_data_contract, SystemDataContract};
519
520        let platform_version = PlatformVersion::latest();
521        let contract =
522            load_system_data_contract(SystemDataContract::DecisionProposals, platform_version)
523                .expect("the contract loads at 15");
524        let document_type = contract
525            .document_type_for_name(PROPOSAL_DOCUMENT_TYPE_NAME)
526            .expect("the proposal type");
527        let document: Document = DocumentV0 {
528            properties: proposal(60, 10),
529            ..Default::default()
530        }
531        .into();
532        assert_eq!(
533            document_type
534                .prefunded_voting_balance_for_document(&document, platform_version)
535                .expect("active"),
536            Some((DECISION_PROPOSAL_FUND_NAME.to_string(), 50_000_000_000))
537        );
538    }
539}