diff --git a/book/src/contract-keywords/deletion.md b/book/src/contract-keywords/deletion.md index 3c2f85fd23a..098d338564d 100644 --- a/book/src/contract-keywords/deletion.md +++ b/book/src/contract-keywords/deletion.md @@ -126,7 +126,7 @@ All refusals below are `InvalidContractStructure` (10231), checked on every pars - Only on a type whose documents are mutable: without a replace there is nothing to retract with. - Only on a contract that keeps a banlist or a suspension list: otherwise no owner is ever barred. -- The condition reads what an `immutable` entry's `when` may read: declared properties of the right kind, neither transient nor inside a transient object, the system times and heights the type lists in `required`, and the stored document through `$old.`. It reads no `countOf` or `sumOf`. When a contract is registered or updated, it also stays within the node limit of a rule and lists no condition twice. +- The condition reads what an `immutable` entry's `when` may read: declared properties of the right kind, neither transient nor inside a transient object, the system times and heights the type lists in `required`, `$revision`, and the stored document through `$old.`: its properties, owner, times, heights and revision. It reads no `countOf` or `sumOf`. When a contract is registered or updated, it also stays within the node limit of a rule and lists no condition twice. ## `deleteConstraints` @@ -183,7 +183,7 @@ Without the keyword, the poll had to be undeletable for its votes to be sure it ### How it works - **The owner's delete.** When the owner deletes a document, consensus fetches it, checks the owner, then checks every rule in name order against the stored document, and refuses the delete at the first rule it breaks with `DocumentDeleteConstraintViolatedError` (40147). The error names the document, the rule, and why it failed, with the reasons of [`propertyConstraints`](property-constraints.md#how-it-works). It is a state error, so the delete is paid for and the nonce is spent, and the document stays. -- **What a rule reads.** The stored document's properties, its `$ownerId` (the owner deleting it), and the times and heights the type lists in `required`, as stored. A `countOf` or `sumOf` reads a total from state as it will be once the document is gone: a total over the type's own documents no longer counts it, so `{ "greaterThanOrEqual": [{ "countOf": ["address", { "$ownerId": "$ownerId" }] }, 1] }` keeps the last address of each owner. Each total is a billed read. +- **What a rule reads.** The stored document's properties, its `$ownerId` (the owner deleting it), the times and heights the type lists in `required`, and its `$revision` on a type that keeps one, as stored, by their plain paths: the rule is judged on the stored document itself, so `$old.` is refused. A `countOf` or `sumOf` reads a total from state as it will be once the document is gone: a total over the type's own documents no longer counts it, so `{ "greaterThanOrEqual": [{ "countOf": ["address", { "$ownerId": "$ownerId" }] }, 1] }` keeps the last address of each owner. Each total is a billed read. - **`$id` in a filter.** A filter may match a key by the document's own id, `"$id"`, which is what makes "while no vote points at it" a rule. The key must be an identifier property of the counted type. `$id` is a filter value in `propertyConstraints` too, as the example shows; it is not an operand anywhere else. - **Only the owner's delete.** The contract's moderators delete as their abilities allow, and a `ttl` expires documents on time, whatever the rules say. A `refersTo` with `consume` may not target the type, since a consume deletes without a delete transition to judge. A banned or suspended owner, who may still delete its documents, is held to the rules like any other. - **The totals are those of the block.** Each state transition of a block is applied before the next is validated, so a vote earlier in the block counts, and a vote later in the block finds the poll gone (`ReferencedEntityNotFoundError`, 40120). @@ -194,7 +194,7 @@ Without the keyword, the poll had to be undeletable for its votes to be sure it All refusals below are `InvalidContractStructure` (10231) unless noted. - Only on a type whose owner deletes its stored documents: not `canBeDeleted: false` or `"onlyWhenConsumed"`, where there is no delete to gate, and not `indexOnly`, whose delete carries the row's values and is judged by its `propertyConstraints`. Checked on every parse. -- The grammar, the shape and the reads are those of a `propertyConstraints` rule (see [Rules at registration](property-constraints.md#rules-at-registration)): every path names a stored property of the kind it is read as, a time or height the type lists in `required`, no `$old.` path. Every `countOf` and `sumOf` counts a type of the contract with a tree that keeps the total. Unlike a `propertyConstraints` rule, a delete rule may total its own type when that type has a contested index: the total it reads at the delete is the stored one, which an awarded document is in like any other. +- The grammar, the shape and the reads are those of a `propertyConstraints` rule (see [Rules at registration](property-constraints.md#rules-at-registration)): every path names a stored property of the kind it is read as, a time or height the type lists in `required`, or `$revision` on a type that keeps one, and none starts with `$old.`, which the refusal says to drop, since the plain path already reads the stored document. Every `countOf` and `sumOf` counts a type of the contract with a tree that keeps the total. Unlike a `propertyConstraints` rule, a delete rule may total its own type when that type has a contested index: the total it reads at the delete is the stored one, which an awarded document is in like any other. - The same limits, counted apart from `propertyConstraints`: at most 16 rules, each of at most 32 nodes, reading at most 4 distinct totals. - A `refersTo` with `consume` may not target a type that declares the keyword. diff --git a/book/src/contract-keywords/moderator-abilities.md b/book/src/contract-keywords/moderator-abilities.md index 0d2c42554d4..0fa1b20a808 100644 --- a/book/src/contract-keywords/moderator-abilities.md +++ b/book/src/contract-keywords/moderator-abilities.md @@ -67,11 +67,11 @@ A user files a report and can never edit it. A report starts with no `status`: t ### How it works - A moderator changes the fields with the contract user moderation transition's `changeDocumentFields` action, naming the document type, the document id, the new value of each field (`null` removes one; in the JavaScript SDKs a field set to `undefined` is left out, as JSON leaves it out) and a reason. -- The transition is checked in this order, each refusal paid: the document type exists (`InvalidDocumentTypeError`, 10406); every field named is listed under `changeFields` (41123); the signer is a moderator of the contract (41101), and for a seated team the declaration gives it `changeDocumentFields` on the type (41201) and the reason names a reason document its proposal lists (41203); the document exists (40101) and has not expired (`DocumentExpiredError`, 40140); and the document as changed is still one of its type: its schema (`JsonSchemaError`, 10101), its `propertyConstraints` and its unique indexes (`DuplicateUniqueIndexError`, 40105). A change naming no field, or a system property, is refused before any state is read (10905). +- The transition is checked in this order, each refusal paid: the document type exists (`InvalidDocumentTypeError`, 10406); every field named is listed under `changeFields` (41123); the signer is a moderator of the contract (41101), and for a seated team the declaration gives it `changeDocumentFields` on the type (41201) and the reason names a reason document its proposal lists (41203); the document exists (40101) and has not expired (`DocumentExpiredError`, 40140); and the document as changed is still one of its type: its schema (`JsonSchemaError`, 10101), the [`propertyConstraints`](property-constraints.md#how-it-works) rules that read a field the change moves (directly or through `$old.`, which reads the document as stored before the change), `$revision` or a total (`DocumentPropertyConstraintViolatedError`, 10422), and its unique indexes (`DuplicateUniqueIndexError`, 40105). The other rules read only what the owner last wrote, and gave their verdict then. A change naming no field, or a system property, is refused before any state is read (10905). - Whoever owns the document may have it changed, the contract owner and the moderators included: the fields are the moderators', not the owner's, so the protection that keeps moderators from deleting each other's documents does not apply. - The document records who wrote the fields last, and when: [`$moderatedAt` and `$moderatedBy`](system-properties.md#moderatedat-and-moderatedby), which an index of the type may name to find what the moderators handled. -- The document is updated in place. Every other property stays as its owner wrote it, `$updatedAt` among them, so a change never opens a [`deleteWithin`](deletion.md#moderatorabilitiesdeletewithin) window again. `$revision` goes up by one, so a replace its owner built on the earlier revision is refused (`InvalidDocumentRevisionError`, 40106) rather than writing over the change. -- References are not checked again: no field a moderator writes holds one or is read by one (see the rules below). A report whose post a moderator has already deleted can still be marked handled. +- The document is updated in place. Every other property stays as it was, `$updatedAt` among them, so a change never opens a [`deleteWithin`](deletion.md#moderatorabilitiesdeletewithin) window again. `$revision` goes up by one, so a replace its owner built on the earlier revision is refused (`InvalidDocumentRevisionError`, 40106) rather than writing over the change. +- References are not checked again: no field a moderator writes holds one or is read by one (see the rules below). A report whose post a moderator has already deleted can still be marked handled. Nor is a `propertyConstraints` rule reading a referenced document judged: registration keeps such a rule from reading anything the change can break. - The moderator pays for the transition and the bytes it adds. Storage the change frees, or index entries it moves, are refunded to the document's owner, who paid for them. Nothing the type prices is charged: a moderator's change is no action of the owner's. - A change that changes nothing, every field already holding the value named, is refused (10905): it would bump `$revision` for nothing. - A change needs a listed reason from a seated team, but does not count toward the team's action share: changes of one document have no bound, as deletions of the content that exists do, so counting them would let a member farm the share. diff --git a/book/src/contract-keywords/mutability.md b/book/src/contract-keywords/mutability.md index 3522bd4e277..c4b8141beb6 100644 --- a/book/src/contract-keywords/mutability.md +++ b/book/src/contract-keywords/mutability.md @@ -98,8 +98,8 @@ The top-level properties a replace may not change, on a type whose documents can ### How it works - On every replace, each property that differs from the stored document is checked against the list. A property listed by name is refused with `DocumentImmutablePropertyChangedError` (40128). A property listed with a condition is refused with the same error when its condition holds for this replace. "Differs" covers a changed value, a value the stored document did not have, and a value the replace leaves out. -- A condition takes the grammar of a [`propertyConstraints`](property-constraints.md) rule: comparisons, arithmetic, `in`, `present`, `absent`, `anyOf`, `allOf`, `not`, `ifThen`, `ifThenElse`, the system times and heights the type records, and `$ownerId`. It is judged, as a rule judges a replace, on the document the replace writes: its properties as the replace sets them, the stored `$createdAt` and `$transferredAt`, and the replace's block as `$updatedAt`. -- A path starting with `$old.` reads the stored document instead: `$old.status` is the status before the replace. Only a condition of `immutable`, or a type's [`retractedWhen`](deletion.md#retractedwhen), may read it, and only a schema property through it. +- A condition takes the grammar of a [`propertyConstraints`](property-constraints.md) rule: comparisons, arithmetic, `in`, `present`, `absent`, `anyOf`, `allOf`, `not`, `ifThen`, `ifThenElse`, the system times and heights the type records, `$revision`, and `$ownerId`. It is judged, as a rule judges a replace, on the document the replace writes: its properties as the replace sets them, the stored `$createdAt` and `$transferredAt`, the replace's block as `$updatedAt`, and the replace's revision. +- A path starting with `$old.` reads the stored document instead: `$old.status` is the status before the replace, `$old.$updatedAt` the time of the previous update, `$old.$revision` the previous revision. A [`propertyConstraints`](property-constraints.md#the-stored-version-old) rule and a type's [`retractedWhen`](deletion.md#retractedwhen) read it the same way; a [`deleteConstraints`](deletion.md#deleteconstraints) rule, judged on the stored document itself, does not. - A property is frozen while its condition holds. If what the condition reads can change back, the property can become editable again: with `body` frozen by `$old.status`, a replace setting `status` back to `draft` still reads the stored `published`, so `body` stays frozen in that replace, and the next replace, reading the stored `draft`, may change it. For a freeze that lasts, list what the condition reads as well, or use a condition that cannot turn back, as a document's age or a filled-in value cannot. - A condition is evaluated only when its property changes. A condition that faults, dividing by zero or overflowing, counts as holding: a fault never frees a property. - Values are compared by their data, not their bytes: the order of an object's members and the width an integer is stored in do not count as changes. Freezing an object freezes everything inside it. @@ -115,7 +115,7 @@ All refusals below are `InvalidContractStructure` (10231). The shape of the list - Every entry is a string or an object with exactly `property` and `when`, and no property is listed twice. - Every listed property is a declared top-level property. System properties (`$ownerId`, `$createdAt` and the rest) are refused, since the platform manages them. Nested paths such as `meta.author` are refused: list the object that contains them. - No listed property may be `transient`: it is never stored, so every replace that supplies it while it is frozen would count as a change. -- A condition reads what a `propertyConstraints` rule may read of the type: declared properties of the right kind, neither transient nor inside a transient object, and system times and heights the type lists in `required`. It stays within the node limit of a rule, and lists no condition twice. +- A condition reads what a `propertyConstraints` rule may read of the type: declared properties of the right kind, neither transient nor inside a transient object, system times and heights the type lists in `required`, `$revision`, and any of them under `$old.`. It stays within the node limit of a rule, and lists no condition twice. - A condition may not read a `countOf` or `sumOf` total: it reads the document alone, so a replace judges it without reading state. - `immutableAllowSetting`, which earlier builds used to let a frozen property be filled in once, is refused and names the replacement: `{ "property": "p", "when": { "present": "$old.p" } }`. - An immutable property may not hold a `deletableDocument` reference that a replace could not clear: a typed array of them, one inside an object, or one found by `findBy` whose key no function computes. A single reference by id held directly by the property is allowed, but only without a condition: once cleared, a replace the condition leaves free could set it to another document. diff --git a/book/src/contract-keywords/ownership-and-trading.md b/book/src/contract-keywords/ownership-and-trading.md index e7425908526..653a272f94f 100644 --- a/book/src/contract-keywords/ownership-and-trading.md +++ b/book/src/contract-keywords/ownership-and-trading.md @@ -65,7 +65,7 @@ Whether an owner may give a document to another identity. - The owner sends a transfer transition naming the document, the recipient and a `$revision` one higher than the stored one (`InvalidDocumentRevisionError`, 40106). Only the owner may transfer (`DocumentOwnerIdMismatchError`, 40102). The recipient does not have to agree. - The document gets the recipient as its `$ownerId` and a new `$revision`. A price it was listed at is removed, so a transferred document is no longer for sale. When the type lists `$transferredAt` in `required`, it is set to the block's time, and likewise `$transferredAtBlockHeight` and `$transferredAtCoreBlockHeight` to the block heights. - A transfer carries no property values, and `$creatorId` keeps naming the identity that created the document. The one change the platform makes itself: from protocol version 13, a DPNS `domain` that is transferred or sold has its `records.identity` pointed at the new owner. -- The document is checked as it will be stored, with its new owner: against the type's unique indexes (`DuplicateUniqueIndexError`, 40105), against a `distinctFrom: "$ownerId"` property (`DocumentPropertyNotDistinctError`, 10419), and against `propertyConstraints` rules that read `$ownerId` (`DocumentPropertyConstraintViolatedError`, 10422). +- The document is checked as it will be stored, with its new owner: against the type's unique indexes (`DuplicateUniqueIndexError`, 40105), against a `distinctFrom: "$ownerId"` property (`DocumentPropertyNotDistinctError`, 10419), and against the `propertyConstraints` rules that read what a transfer changes: `$ownerId`, `$transferredAt` and its heights or `$revision`, of the document or, through `$old.`, of the version before the transfer, or a total that depends on the owner (`DocumentPropertyConstraintViolatedError`, 10422; see [propertyConstraints](property-constraints.md#how-it-works)). - On a moderated contract, a transfer to a banned or suspended identity is refused (`ContractModerationCounterpartyBarredError`, 41114). - A transfer of a document past its `ttl` expiry is refused (`DocumentExpiredError`, 40140). - With `keepsTransferHistory: true`, each transfer is also recorded in the document history contract. See [History](history.md). @@ -88,7 +88,7 @@ Whether documents of the type can be sold through the platform's built-in market - **Listing.** The owner sends a price update transition with a price in credits and the next `$revision`. Only the owner may set the price (40102). The price is stored with the document, the revision goes up, and `$updatedAt` is set when the type lists it in `required`. - **Buying.** Any identity other than the owner sends a purchase transition naming the document, the next `$revision` and the price. A document with no price set is not for sale (`DocumentNotForSaleError`, 40108), and the price in the transition must equal the listed price exactly (`DocumentIncorrectPurchasePriceError`, 40109). An owner cannot buy its own document (10404). - **What a purchase does.** The price moves from the buyer's credit balance to the seller's. The document gets the buyer as its `$ownerId` and a new `$revision`, the listing is removed, and `$transferredAt` is set when the type lists it in `required`. The buyer's credit balance must cover the price. -- The new owner is checked exactly as for a transfer: unique indexes (40105), `distinctFrom: "$ownerId"` (10419) and `propertyConstraints` rules that read `$ownerId` (10422). +- The new owner is checked exactly as for a transfer: unique indexes (40105), `distinctFrom: "$ownerId"` (10419) and the `propertyConstraints` rules that read `$ownerId`, `$transferredAt` and its heights or `$revision`, of either version, or a total that depends on the owner (10422). - On a moderated contract, a banned or suspended buyer is refused like any barred writer, and so is a purchase from a banned or suspended seller (`ContractModerationCounterpartyBarredError`, 41114). - A price update or a purchase of a document past its `ttl` expiry is refused (`DocumentExpiredError`, 40140). - With `keepsPricingHistory` and `keepsPurchaseHistory`, each price update and each purchase is also recorded in the document history contract. See [History](history.md). diff --git a/book/src/contract-keywords/property-constraints.md b/book/src/contract-keywords/property-constraints.md index 1c7e3e4f62c..9cb3dd01958 100644 --- a/book/src/contract-keywords/property-constraints.md +++ b/book/src/contract-keywords/property-constraints.md @@ -1,6 +1,6 @@ # propertyConstraints -`propertyConstraints` holds named rules that every created or replaced document of a type must meet. JSON Schema bounds one property at a time; these rules relate properties to each other: a deposit that covers price times quantity, percentages that add up to 100, a closed order that carries its closing time, a second party who is not the owner, a payment address whose first byte names a known type. Each rule is a small tree of comparisons, arithmetic and logic that consensus evaluates against the document. A rule can also read a total of other documents, how many there are or what an integer property adds up to, from the count and sum trees their indexes keep (see [Totals of other documents](#totals-of-other-documents)), and a value of the document one of its references points at, which the reference's check reads anyway (see [Values of a referenced document](#values-of-a-referenced-document)). +`propertyConstraints` holds named rules that every created or replaced document of a type must meet. JSON Schema bounds one property at a time; these rules relate properties to each other: a deposit that covers price times quantity, percentages that add up to 100, a closed order that carries its closing time, a second party who is not the owner, a payment address whose first byte names a known type. Each rule is a small tree of comparisons, arithmetic and logic that consensus evaluates against the document. A rule can also read a total of other documents, how many there are or what an integer property adds up to, from the count and sum trees their indexes keep (see [Totals of other documents](#totals-of-other-documents)), a value of the document one of its references points at, which the reference's check reads anyway (see [Values of a referenced document](#values-of-a-referenced-document)), and the stored version a write replaces, through `$old.` (see [The stored version](#the-stored-version-old)). | | | |---|---| @@ -47,14 +47,15 @@ ## How it works -- **Create and replace.** The rules run after the JSON schema validation of the document's properties (and after [maxBytes](max-bytes.md)), so every value a rule reads has passed its property's schema. A replace is judged on the whole new document, not only on what changed. +- **Create and replace.** The rules run after the JSON schema validation of the document's properties (and after [maxBytes](max-bytes.md)), so every value a rule reads has passed its property's schema. A replace is judged on the whole new document, not only on what changed, with the document it replaces under `$old.`; a create has none. - **Name order, first failure.** Rules are checked in the order of their names, and the first rule the document breaks refuses the transition with `DocumentPropertyConstraintViolatedError` (10422). The error names the document type, the rule, and why it failed (below). -- **Transfer and purchase.** These change only the owner and the transfer's time and heights. Rules that read `$ownerId`, `$transferredAt…` or a total that depends on the owner are judged again, against the stored document with its new owner and transfer values; other rules are not, since nothing they read changed. A transfer or purchase that would break such a rule is refused with 10422. A rule reading a referenced document is never among them (see [Values of a referenced document](#values-of-a-referenced-document)). -- **Price updates** change only the update's time and heights, so the rules that read `$updatedAt…` are judged again the same way; other rules are not. -- **Moderator restores.** Every rule of the restored type is judged on the retained document, with its original owner, times and heights, except a rule reading a referenced document: a restore checks no reference, and registration keeps such a rule from reading a total over the restored type's own documents. Totals include the restored document as an insertion into the live trees; its removal record is not counted. Another write while it was deleted may make a cap, lower bound or cross-type prerequisite fail. Uniqueness is checked first. A refusal in a block charges the moderator and consumes its nonce, while the document stays deleted and its removal record stays unrestored. Mempool admission refuses the same invalid restore without persisting fees or a nonce change. Restore does not revalidate the full property schema or judge `deleteConstraints`. -- **Immutable properties.** The same grammar is the condition of an [`immutable`](mutability.md#immutable) entry, which freezes a property while it holds. Only such a condition may read the stored document, through `$old.`; a rule judges creates too, which have none. -- **Deletes** are not judged, with one exception: a delete of an [index-only](index-only.md) document carries the row's values, which are validated like a create's, rules included. The delete carries neither the owner nor any time or height, which is why an index-only type may not have a rule reading `$ownerId` or a system time or height. What may be deleted is the job of [`deleteConstraints`](deletion.md#deleteconstraints), rules in this grammar the stored document must meet for its owner to delete it. -- **State and fees.** A rule reads the document, its owner and its times and heights, and a `countOf` or `sumOf` reads a total from state. Each such total is a state read billed with the write; nothing else a rule does adds a fee, and it changes nothing stored. A value of a referenced document comes from the read the reference's check makes. The limits below bound its cost. SDKs that validate a document before sending it apply the same rules, except those reading a total or a referenced document, which they cannot read. +- **Transfer and purchase.** These change only the owner, the transfer's time and heights, and `$revision`. Rules that read `$ownerId`, `$transferredAt…`, `$revision` or a total that depends on the owner, of the document or of the stored version under `$old.`, are judged again, against the stored document with its new owner and transfer values, `$old.` reading it as it was before; other rules are not, since nothing they read changed. A transfer or purchase that would break such a rule is refused with 10422. A rule reading a referenced document is never among them (see [Values of a referenced document](#values-of-a-referenced-document)). +- **Price updates** change only the update's time and heights and `$revision`, so the rules that read `$updatedAt…` or `$revision`, of either version, are judged again the same way; other rules are not. +- **Moderator field changes.** A moderator's change of the fields the type keeps for its moderators (see [moderatorAbilities.changeFields](moderator-abilities.md#changefields)) is judged as a replace is, with the document it changes under `$old.`, but only against the rules that read a field it changes, of either version, `$revision`, which it moves, or a total, and never against a rule reading a referenced document, which registration keeps from reading anything the change can break. It keeps the document's owner, times and heights. The other rules read only what the owner last wrote, and gave their verdict then. +- **Moderator restores.** The rules of the restored type that read a total are judged on the retained document, with its original owner, times, heights and revision, and `$old.` reading the retained document itself, except a rule reading a referenced document: a restore checks no reference, and registration keeps such a rule from reading any total on a type whose moderators' deletions keep records. Totals include the restored document as an insertion into the live trees; its removal record is not counted. Another write while it was deleted may make a cap, lower bound or cross-type prerequisite fail. The other rules read only what the document held when it was last written, and gave their verdict then: a type's rules never change once it is registered. Uniqueness is checked first. A refusal in a block charges the moderator and consumes its nonce, while the document stays deleted and its removal record stays unrestored. Mempool admission refuses the same invalid restore without persisting fees or a nonce change. Restore does not revalidate the full property schema or judge `deleteConstraints`. +- **Immutable properties.** The same grammar is the condition of an [`immutable`](mutability.md#immutable) entry, which freezes a property while it holds. It reads the stored document through `$old.` as a rule does. +- **Deletes** are not judged, with one exception: a delete of an [index-only](index-only.md) document carries the row's values, which are validated like a create's, rules included. The delete carries neither the owner nor any time, height or revision, which is why an index-only type may not have a rule reading `$ownerId`, a system time or height, `$revision` or `$old.`. What may be deleted is the job of [`deleteConstraints`](deletion.md#deleteconstraints), rules in this grammar the stored document must meet for its owner to delete it, which read it by their plain paths. +- **State and fees.** A rule reads the document, its owner, its times, heights and revision, and the stored version the write replaces, which the write has already fetched; a `countOf` or `sumOf` reads a total from state. Each such total is a state read billed with the write; nothing else a rule does adds a fee, and it changes nothing stored. A value of a referenced document comes from the read the reference's check makes. The limits below bound its cost. SDKs that validate a document before sending it apply the same rules, except those reading a total or a referenced document, which they cannot read, and those reading the stored version when they are not given it (see [The stored version](#the-stored-version-old)). Why a rule fails, as the error reports it: @@ -133,7 +134,7 @@ Two more forms appear only in string and identifier comparisons, never inside ar | `{ "const": "closed" }` | A string constant, or, compared with an identifier property or `$ownerId`, a base58 identifier, or, tested against a byte array property, hex digits | | `{ "ifAbsent": ["status", "open"] }` | A string property, read as the given string when the document leaves it out | -A bare JSON string is always a path and a bare JSON number always a value, so a constant string needs `{ "const": ... }`. The values an `in` lists are literals and need no wrapper. A path is a property name, or names joined by dots for a nested property (`"rewardSplit.leader"`); the only `$` names a rule accepts are `$ownerId`, the times and heights below, and, as the value a [total's filter](#totals-of-other-documents) matches by, `$id`. A `{ "referenced": [reference, field] }` stands wherever a path does. +A bare JSON string is always a path and a bare JSON number always a value, so a constant string needs `{ "const": ... }`. The values an `in` lists are literals and need no wrapper. A path is a property name, or names joined by dots for a nested property (`"rewardSplit.leader"`); the only `$` names a rule accepts are `$ownerId`, the times and heights below, `$revision`, a path or any of those after `$old.`, which reads the stored version (see [The stored version](#the-stored-version-old)), and, as the value a [total's filter](#totals-of-other-documents) matches by, `$id`. A `{ "referenced": [reference, field] }` stands wherever a path does. A `number` property (a float) cannot be read by a rule, which keeps every result exact. @@ -182,7 +183,7 @@ The index is a literal integer from 0 to 65535, never an expression, and a byte When the property declares `maxItems`, an index at or past it, or a constant longer than it, is refused at registration, since the byte or the bytes are never there. -A rule reading bytes is judged on create and replace like any other; the `$old.` paths of an [`immutable`](mutability.md#immutable) condition or `retractedWhen` read the stored array's bytes (`{ "byteAt": ["$old.address", 0] }`), and a [`deleteConstraints`](deletion.md#deleteconstraints) rule the stored document's. Reading bytes does not make a transfer, a purchase or a price update judge a rule, since none of them changes a byte array. +A rule reading bytes is judged on create and replace like any other; a path through `$old.` reads the stored array's bytes (`{ "byteAt": ["$old.address", 0] }`), and a [`deleteConstraints`](deletion.md#deleteconstraints) rule the stored document's by the plain path. Reading bytes does not make a transfer, a purchase or a price update judge a rule, since none of them changes a byte array. ## Times and heights @@ -200,7 +201,66 @@ A rule can read when the document was created, last updated and last transferred A rule may read one only when the document type records it by listing it in `required`, so every stored document holds it. None takes an `ifAbsent` default, `present` and `absent` refuse them, and an [index-only](index-only.md) type reads none. Each write is judged with the values the stored document ends up with: a create with its block's time and heights for all three events; a replace with the stored creation and transfer values and its block's as the update; a price update with its block's as the update; a transfer or a purchase with its block's as the transfer. -SDK pre-checks run before the block exists: they use the device clock for the times a write records, and do not judge a rule reading a block height, which is unknown until the block. +SDK pre-checks run before the block exists: they use the device clock for the times a write records, and do not judge a rule reading a block height the write records, which is unknown until the block: on a create every height read without `$old.`, on a replace the update's. A stored height read through `$old.` is judged: it reads 0 on a create, and the stored document's height on a replace the JavaScript check is given the stored document for. + +`$revision` is an integer operand too, on a type that keeps a revision: one whose documents are mutable, transferable, sold at a price their owner sets, or keep fields for their moderators. It is 1 on a create and one more for each later write: a replace, a transfer, a purchase, a price update or a moderator's change of fields; a moderator's restore keeps it. `{ "lessThanOrEqual": ["$revision", 6] }` allows five writes after the create. It counts every write, not only the owner's edits, so a transfer and a price update are judged against a rule reading it. To count edits alone, keep a counter (see [The stored version](#the-stored-version-old)). + +## The stored version (`$old.`) + +A path under `$old.` reads the stored version of the document a write replaces instead of the version it writes. A rule can then compare the two. On an `order` type that is mutable and transferable, requires `edits`, `$updatedAt` and `$transferredAt`, and whose `dispute` type keeps a countable index by `orderId`: + +```json +"propertyConstraints": { + "counterNeverDrops": { + "greaterThanOrEqual": ["counter", { "ifAbsent": ["$old.counter", 0] }] + }, + "closedStaysClosed": { + "ifThen": [ + { "equal": ["$old.status", { "const": "closed" }] }, + { "equal": ["status", { "const": "closed" }] } + ] + }, + "editsAnHourApart": { + "greaterThanOrEqual": [{ "subtract": ["$updatedAt", "$old.$updatedAt"] }, 3600000] + }, + "noResaleWithinADay": { + "ifThen": [ + { "notEqual": ["$ownerId", "$old.$ownerId"] }, + { "greaterThanOrEqual": [{ "subtract": ["$transferredAt", "$old.$transferredAt"] }, 86400000] } + ] + }, + "statusChangesOnlyWithoutDisputes": { + "ifThen": [ + { "notEqual": ["status", "$old.status"] }, + { "equal": [{ "countOf": ["dispute", { "orderId": "$id" }] }, 0] } + ] + }, + "editsCounted": { + "equal": ["edits", { "add": [{ "ifAbsent": ["$old.edits", -1] }, 1] }] + } +} +``` + +`counterNeverDrops` lets a counter rise or stay, from any value at or above 0 on a create. `closedStaysClosed` keeps a closed order closed. `editsAnHourApart` spaces a document's replaces, and its price updates, an hour apart. `noResaleWithinADay` refuses a transfer or a purchase less than a day after the last one. `statusChangesOnlyWithoutDisputes` lets the status change only while no dispute points at the document. `editsCounted` starts `edits` at 0 and moves it by one on each replace, a count of edits that, unlike `$revision`, transfers and price updates leave alone. Unlike an [`immutable`](mutability.md#immutable) condition, which refuses a replace with 40128 naming the property, each of these refuses the write with 10422 naming the rule, and can read a total. + +What `$old.` reads on each write, and which rules the write is judged against: + +| Write | `$old.` | `$old.$ownerId`, a stored time, height or `$old.$revision` | Rules judged | +|---|---|---|---| +| Create | Nothing: it reads as a property the document leaves out does (0 or its `ifAbsent` value in an integer expression, absent to `present`, equal to no string or identifier) | No owner, which equals no identifier; 0 | Every rule | +| Replace | The stored document's | The stored document's: its owner (the writer), the previous update's time and heights, the previous revision | Every rule | +| Transfer, purchase | The stored document's, which are the document's | The previous owner, the previous transfer's time and heights, the previous revision | Those reading the owner, a transfer time or height, `$revision`, or a total depending on the owner, of either version | +| Price update | The stored document's, which are the document's | The previous update's time and heights, the previous revision | Those reading an update time or height or `$revision`, of either version | +| Moderator field change | The stored document's | The stored document's | Those reading a field it changes, of either version, `$revision`, or a total | +| Moderator restore | The restored document's own | The restored document's own | Those reading a total | + +A write that changes no property is not judged against a rule that compares properties alone: it would compare each with itself, and a rule demanding a change, such as `{ "greaterThan": ["counter", "$old.counter"] }`, would refuse every transfer. + +- `$old.` goes in front of any path a rule reads: in an integer expression, an `ifAbsent`, a size, a `byteAt` or a `countPresent`, in `present` and `absent`, in a comparison of strings, identifiers or byte arrays, in an `in`, and in a `contains`, on either side. The path after it is checked as any path is. `$old.$ownerId` compares as `$ownerId` does, and a stored time, height or revision is an integer operand, read only on a type that records it. +- A create reads every `$old.` value as absent, so a rule a create must pass guards it: `{ "ifAbsent": ["$old.counter", 0] }`, `{ "absent": "$old.status" }` in an `anyOf`, or `$old.$revision` reading 0. `{ "lessThanOrEqual": ["price", "$old.price"] }` alone refuses every create with a price above 0. +- A rule demanding a change is judged on every replace: `{ "greaterThan": ["counter", "$old.counter"] }` refuses a replace that leaves the counter alone. +- A moderator's change of fields keeps `$updatedAt`, so `editsAnHourApart` is not judged against it. +- SDK pre-checks read no state. Each rule's descriptor reports `readsStored` when it reads `$old.`. The create pre-check (`dash_sdk_data_contract_check_property_constraints`, under Swift and Kotlin) judges such a rule as a create, with nothing under `$old.`. The JavaScript `checkDocumentPropertyConstraints(document, storedDocument)` takes the stored document for a replace, `null` for a create, and with `undefined` does not judge such a rule. ## Totals of other documents @@ -228,7 +288,7 @@ A filter maps each key, a property of the counted type or `$ownerId`, to the val - **As it will be after the write.** The total is the stored one with the write applied. When the counted type is the rule's own, a create or moderator restore adds the document, a replace swaps its stored version for the new one, and a transfer or purchase moves it to its new owner. So `atMostTenListings`, declared on `listing`, keeps every owner at ten or fewer, and a replace of one of ten is allowed. - **Judged when the rule's own type is written.** A rule is never judged on writes of the type it counts. On its own type it holds for good, since every write that could raise the total is judged; a type with a contested index cannot total its own documents, since a document a contest awards is stored without any rule judged. On another type it is only checked when its own type is written, and can go stale later: deleting a `profile` does not undo a `post` that needed one. Deletes are not judged, so a lower bound can be broken by deleting documents, unless the counted type's [`deleteConstraints`](deletion.md#deleteconstraints) hold it. -- **Transfers, purchases and price updates.** A total that depends on the owner (a filter value of `$ownerId`, or a `$ownerId` key on the rule's own type) is read again for a transfer or purchase, the document counted toward its new owner. A rule a price update judges, one reading `$updatedAt…`, reads its totals too. +- **Transfers, purchases and price updates.** A total that depends on the owner (a filter value of `$ownerId`, or a `$ownerId` key on the rule's own type) is read again for a transfer or purchase, the document counted toward its new owner. A rule a transfer, purchase or price update judges for another read (`$transferredAt…`, `$updatedAt…` or `$revision`, of either version) reads its totals too. - **Billed.** Each total is a state read billed with the write. A total two rules read alike is read once. - **Every earlier write counts.** A document batch carries one transition, and each state transition of a block is applied before the next is validated, so a total includes every write before it. - **SDK pre-checks** cannot read state, so they do not judge a rule reading a total. @@ -259,7 +319,7 @@ A bid meets its auction's reserve price, a review names an order that was delive **When it is judged.** A rule reading a referenced document is judged once the type's references hold, with the documents their checks read, after the type's other rules; a missing target refuses the write with `ReferencedEntityNotFoundError` (40120) before it. A broken rule is `DocumentPropertyConstraintViolatedError` (10422), as any rule. Every replace judges every rule, so a reference a rule reads through is [checked again on every replace](refers-to.md#on-replace), its `where` included, and the rule reads the document as it is at the replace: a `permanentDocument` target replaced since is read with its new values. Each such check costs the read the reference's first check made, billed the same way. A kept `moderatedDocument` reference whose document a moderator removed is read from the removal record. -Transfers, purchases, price updates, a moderator's change of fields and a moderator's restore check no reference, and do not judge such a rule. Registration keeps that sound: on a type whose documents can be transferred or traded, a rule reading a referenced document may not read what those writes change (`$ownerId`, `$transferredAt` and its heights, a total depending on the owner, and on a tradeable type `$updatedAt` and its heights), and it may not depend on a field the type keeps for its [moderators to change](moderator-abilities.md#changefields): neither read it nor total the type's own documents by it, as a key of a `countOf` or `sumOf` over them, since a moderator's change moves such a total. On a type whose moderators' deletions keep records it may read no `countOf` or `sumOf` over the type's own documents at all: a restore brings a document back into those totals. +Transfers, purchases, price updates, a moderator's change of fields and a moderator's restore check no reference, and do not judge such a rule. Registration keeps that sound by refusing a rule reading a referenced document that one of those writes could break. On a type whose documents can be transferred or traded, it may not read what a transfer or purchase changes: `$ownerId`, `$transferredAt` and its heights or `$revision`, of either version, or a total depending on the owner. On a type whose prices can be set, it may not read what a price update changes: `$updatedAt` and its heights or `$revision`, of either version. On a type with fields its [moderators change](moderator-abilities.md#changefields), it may not read anything their change can break: one of those fields or `$revision`, of either version, or any `countOf` or `sumOf`, since a total may have moved since the document was last written. On a type whose moderators' deletions keep records, so that a restore can bring a document back, it may read no `countOf` or `sumOf` at all. **Time against a referenced value.** A create records its block for every time and height; a replace keeps the stored creation and transfer and records its block as the update. So `$createdAt` below a referenced `endsAt` holds the create to the deadline and lets a later replace through, while `$updatedAt` holds every write to it: a vote that may be changed only while its poll is open reads `$updatedAt`. On a type whose documents are never replaced the two are the same. @@ -314,7 +374,7 @@ The meta-schema checks the shape (`JsonSchemaError`, 10101): - every condition and every operator object has exactly one key; - a comparison, `subtract`, `divide`, `modulo` and `power` take exactly two operands; `add` and `multiply` two or more; `anyOf` and `allOf` two or more conditions, no two alike; an `in` two or more distinct values, all integers or all strings; a `countPresent` two or more distinct paths; - no `anyOf` or `allOf` holds its own kind directly, and no `not` holds a `not` or a `notIn`; -- a path matches `$ownerId`, one of the nine [times and heights](#times-and-heights), or dotted names of 1 to 64 letters, digits or underscores, so `$revision` and other system properties are refused; a `referenced` lists a property name, then a dotted path, `$id`, `$ownerId`, `$creatorId` or a time or height; +- a path matches `$ownerId`, `$revision`, one of the nine [times and heights](#times-and-heights), or dotted names of 1 to 64 letters, digits or underscores, any of them optionally after `$old.`, so `$id` and other system properties are refused; a `referenced` lists a property name, then a dotted path, `$id`, `$ownerId`, `$creatorId` or a time or height; - a `byteAt` lists a path and an integer index from 0 to 65535; - a `countOf` lists a type name and optionally a filter, and a `sumOf` a type name, a property and optionally a filter; a filter has one or more keys, each `$ownerId` or a dotted path, and each value is a path, `$ownerId`, `$id`, an integer or a `{ "const": ... }` string. @@ -326,14 +386,16 @@ The parser then checks the rules against the document type (`InvalidContractStru - strings and identifiers are compared only with `equal`, `notEqual` and `in`; a string is never compared with an identifier; a byte array is tested only by `startsWith` and `endsWith`, against hex constants (an even number of hex digits) and other byte arrays, never a string or an identifier, and takes no default; a property is never compared with itself; - string constants and `ifAbsent` defaults are in the property's `enum` when it has one; identifier constants are base58 identifiers of 32 bytes; - no literal divisor is 0 and no literal exponent is negative; -- every time or height a rule reads is one the type lists in `required`, and takes no `ifAbsent` default; -- `present`, `absent` and `countPresent` do not name `$ownerId` or a time or height, and an index-only type has no rule reading any of them; +- every time or height a rule reads, of either version, is one the type lists in `required`, and takes no `ifAbsent` default, nor does `$revision`; +- `present`, `absent` and `countPresent` do not name `$ownerId`, a time, a height or `$revision`, of either version, and an index-only type has no rule reading any of them or anything under `$old.`; +- a rule reads `$revision`, or anything under `$old.`, only on a type that keeps a revision: its documents are mutable, transferable, sold at a price their owner sets, or keep fields for their moderators. On any other a create is the only write a rule judges, with no stored version and the first revision; +- no `countOf` or `sumOf` filter takes a value under `$old.`; - no `anyOf` or `allOf` lists two conditions that parse alike, such as `1` and `1.0`, or two `in` conditions listing the same values in another order, and no `ifThen` or `ifThenElse` holds two alike conditions; - no condition or operand nests more than 64 levels deep; - once every document type of the contract is parsed, every `countOf` and `sumOf` counts a type of the contract that is not index-only, and not its own type when that has a contested index, with a tree that keeps the total as set out in [Totals of other documents](#totals-of-other-documents). A unique, contested, ranked, time-range, integer-range or index-only-terminal index keeps no such total, nor does one with more properties than the filter has keys; - every key of a filter is `$ownerId` or an integer, string or identifier property of the counted type, and its value is of the same kind (`$ownerId` and `$id` are identifiers); a string constant is in the key's `enum` when it has one, and an identifier constant is base58; - every property a filter value reads is listed in `required`, with every object around it, so a write always has the value; an index-only type has no rule reading a total; -- a `referenced` reads through a property of the type holding one reference to one document, as set out in [Values of a referenced document](#values-of-a-referenced-document), only in `propertyConstraints` (not `deleteConstraints`, an `immutable` condition or `retractedWhen`, whose writes check no reference), not on an index-only type, not beside what a transfer, purchase or price update of the type changes, not beside a field the type keeps for its moderators to change, read or deciding a total over the type's own documents, and, on a type whose moderators' deletions keep records, not beside a total over the type's own documents; +- a `referenced` reads through a property of the type holding one reference to one document, as set out in [Values of a referenced document](#values-of-a-referenced-document), only in `propertyConstraints` (not `deleteConstraints`, an `immutable` condition or `retractedWhen`, whose writes check no reference), not on an index-only type, and not beside what a write checking no reference changes: what a transfer or purchase of the type changes (`$ownerId`, `$transferredAt` and its heights or `$revision`, of either version, or a total depending on the owner), what a price update of the type changes (`$updatedAt` and its heights or `$revision`, of either version), on a type keeping fields for its moderators one of those fields or `$revision`, of either version, or any total, and, on a type whose moderators' deletions keep records, any total; - once every document type of the contract is parsed, what a rule reads of a referenced type of the same contract is a field that type gives it: one it has, stored, of the kind the rule reads, a time or height it records, a `$creatorId` it records, a constant its `enum` lists, and through a `moderatedDocument` reference a field its removal record keeps. A referenced type of another contract is checked at registration against the stored contract, refused with `ReferencedDocumentRuleReadInvalidError` (40148). Three limits come from the protocol version 14 `SystemLimits`, and a rule over one is refused the same way: diff --git a/book/src/contract-keywords/system-properties.md b/book/src/contract-keywords/system-properties.md index f21bcdc5833..077d1e09a4b 100644 --- a/book/src/contract-keywords/system-properties.md +++ b/book/src/contract-keywords/system-properties.md @@ -63,7 +63,7 @@ The owner is the identity that created the document, until a transfer or a purch `$ownerId` may be indexed, and several keywords read it, where it usually stands for the writer of the document: - [`distinctFrom`](distinct-from.md): `"$ownerId"` makes a property differ from the owner. -- [`propertyConstraints`](property-constraints.md): a rule may compare an identifier property with `$ownerId`. +- [`propertyConstraints`](property-constraints.md): a rule may compare an identifier property with `$ownerId`, or with `$old.$ownerId`, the owner of the [stored version](property-constraints.md#the-stored-version-old) a write replaces, and a transfer or purchase is judged against such a rule. - [References](refers-to.md): a `where` entry, a `findBy` source and `identityProperty` may name it, and [`ownerRefersTo`](owner-refers-to.md) checks the owner itself. - [`encryptedFor`](encrypted-for.md): `"recipient": "$ownerId"` marks a message the writer encrypts to themself. @@ -77,7 +77,7 @@ The owner is the identity that created the document, until a transfer or a purch | **Since** | protocol version 1 | | **Errors** | `InvalidDocumentRevisionError` (40106): a transition whose revision is not the stored one plus one | -A new document has revision 1. Every replace, transfer, price update and purchase raises it by one, and the transition must state the new revision: the stored revision plus one. A transition built against an older copy of the document is refused, rather than silently overwriting a newer one. A moderator's change of the fields a type keeps for its moderators raises it by one too; the moderation transition states no revision, the platform sets it, and an owner's replace built before the change is refused. A type whose documents can never change after creation carries no revision. `$revision` is not one of the system properties an index may name. +A new document has revision 1. Every replace, transfer, price update and purchase raises it by one, and the transition must state the new revision: the stored revision plus one. A transition built against an older copy of the document is refused, rather than silently overwriting a newer one. A moderator's change of the fields a type keeps for its moderators raises it by one too; the moderation transition states no revision, the platform sets it, and an owner's replace built before the change is refused. A type whose documents can never change after creation carries no revision. `$revision` is not one of the system properties an index may name. A [`propertyConstraints`](property-constraints.md#times-and-heights) rule may read it as an integer, and `$old.$revision`, the revision of the stored version a write replaces; a moderator's restore keeps it. ## Timestamps diff --git a/book/src/data-model/contract-moderation.md b/book/src/data-model/contract-moderation.md index 01158e7297a..ba1d296e458 100644 --- a/book/src/data-model/contract-moderation.md +++ b/book/src/data-model/contract-moderation.md @@ -178,7 +178,7 @@ ContractUserModerationAction::RestoreDocument { } ``` -It names no identity and no id: the document is inside the bytes, and its id and owner with it. The transform checks, in order and each refusal paid: the document type exists (10406) and carries `moderatorAbilities.delete` (41115, only such a type keeps records), the signer is the owner or a moderator (41101, whoever deleted), the bytes decode under the type (a basic decoding error, never an execution error: the bytes are the signer's), the document has a removal record (`ContractDocumentRemovalNotFoundError`, 41119) that is not marked restored (`ContractDocumentAlreadyRestoredError`, 41122: the document is live), block time is within `SystemLimits::contract_document_restore_window_ms` of the removal, a week, the last millisecond included (`DocumentRestoreWindowElapsedError`, 41120), the bytes hash to what the record holds (`DocumentRestoreHashMismatchError`, 41121: the document as it was, not an edit of it), and no other document of the type holds a value of one of its unique indexes (`DuplicateUniqueIndexError`, 40105: the value was free while the document was gone, and someone may have taken it). The record read is billed; the hash pins everything else, so the owner, the revision, the timestamps, the references and the schema are not checked again. Whether the document's owner is banned is not asked either: a ban stops writes, it never removed documents. +It names no identity and no id: the document is inside the bytes, and its id and owner with it. The transform checks, in order and each refusal paid: the document type exists (10406) and carries `moderatorAbilities.delete` (41115, only such a type keeps records), the signer is the owner or a moderator (41101, whoever deleted), the bytes decode under the type (a basic decoding error, never an execution error: the bytes are the signer's), the document has a removal record (`ContractDocumentRemovalNotFoundError`, 41119) that is not marked restored (`ContractDocumentAlreadyRestoredError`, 41122: the document is live), block time is within `SystemLimits::contract_document_restore_window_ms` of the removal, a week, the last millisecond included (`DocumentRestoreWindowElapsedError`, 41120), the bytes hash to what the record holds (`DocumentRestoreHashMismatchError`, 41121: the document as it was, not an edit of it), and no other document of the type holds a value of one of its unique indexes (`DuplicateUniqueIndexError`, 40105: the value was free while the document was gone, and someone may have taken it), and the type's `propertyConstraints` rules that read a `countOf` or `sumOf` total still hold (`DocumentPropertyConstraintViolatedError`, 10422: other writes may have moved a total while the document was gone), judged with the totals as they will be once it is back (`read_property_constraint_aggregates_for_restore`) and `$old.` reading the restored document itself (`validate_property_constraints_for_system_change`, `SystemChange::Restore`). A rule reading a referenced document is not judged: a restore checks no reference, and registration keeps such a rule from reading any total on a type whose deletions keep records. The record read is billed, and so is each total; the hash pins everything else, so the owner, the revision, the timestamps, the references, the schema and the rules reading no total are not checked again. Whether the document's owner is banned is not asked either: a ban stops writes, it never removed documents. The action carries the contract, the decoded document and the record marked restored by the signer at the block's time, so Drive puts the document back through the ordinary insert (`DocumentOperationType::AddDocument`, every index and aggregate of the type included) and replaces the record in place, without reading again. The restored document's storage flags name its owner, as they did before the deletion: the signer pays for the bytes, and the refund of a later deletion is the owner's, as it always was. Nothing the document type prices is charged, neither its creation token cost nor its `actionFees` creation fee, and no fee agreement is asked: a moderator undoes a moderation, it does not create content. The restore is proved by the record, now marked restored and holding the hash of the bytes the transition carried; the verifier reads the document's id out of those bytes under the contract's document type, so it needs the contract, which the SDKs register with their context provider before broadcasting. @@ -258,7 +258,7 @@ ContractUserModerationAction::ChangeDocumentFields { } ``` -Basic structure refuses one that names no field or a system property (`InvalidContractModerationDocumentFieldsError`, 10905, unpaid). The transform (`transform_document_fields_change_v0`) checks, in order and each refusal paid: the document type exists (10406), every field is one it keeps for its moderators (`DocumentFieldNotChangeableByModeratorsError`, 41123), the signer moderates the contract (41101) and a seated team holds `changeDocumentFields` on the type (41201) and names a listed reason (41203), the document exists (40101) and has not expired (40140). It then builds the changed document: the stored one with each field set or removed, compared as a replace compares (`Value::equal_underlying_data`, so an integer sent at another width than the stored one is no change), `$revision` one higher (`OverflowError`, 10700, at `u64::MAX`), `$moderatedAt` the block's time and `$moderatedBy` the signer, everything else as stored, `$updatedAt` and its heights included. That document is judged as a replace judges one: `validate_document_properties` (the schema and `propertyConstraints`, with the `countOf` and `sumOf` totals read as they will be once it is stored, `read_property_constraint_aggregates_for_moderator_change`), `distinctFrom` and the shapes of `encryptedFor` properties, then, when a changed field is in a unique index, `Drive::validate_moderated_document_uniqueness`, the restore's check generalized to a changed document (only the changed fields are checked, and the document's own entries do not clash). Whoever owns the document is no protection: the fields are the moderators'. Nothing the document type prices is charged. +Basic structure refuses one that names no field or a system property (`InvalidContractModerationDocumentFieldsError`, 10905, unpaid). The transform (`transform_document_fields_change_v0`) checks, in order and each refusal paid: the document type exists (10406), every field is one it keeps for its moderators (`DocumentFieldNotChangeableByModeratorsError`, 41123), the signer moderates the contract (41101) and a seated team holds `changeDocumentFields` on the type (41201) and names a listed reason (41203), the document exists (40101) and has not expired (40140). It then builds the changed document: the stored one with each field set or removed, compared as a replace compares (`Value::equal_underlying_data`, so an integer sent at another width than the stored one is no change), `$revision` one higher (`OverflowError`, 10700, at `u64::MAX`), `$moderatedAt` the block's time and `$moderatedBy` the signer, everything else as stored, `$updatedAt` and its heights included. That document is judged as a replace judges one: `validate_document_properties` (the schema and `propertyConstraints`, with the `countOf` and `sumOf` totals read as they will be once it is stored, `read_property_constraint_aggregates_for_moderator_change`), `distinctFrom` and the shapes of `encryptedFor` properties, then, when a changed field is in a unique index, `Drive::validate_moderated_document_uniqueness`, the restore's check generalized to a changed document (only the changed fields are checked, and the document's own entries do not clash). Of the `propertyConstraints` rules, only those reading a field the change moves (directly or through `$old.`, which reads the stored document), `$revision` or a total are judged (`DocumentSystemValues::changed_fields`, `PropertyConstraint::reads_changed_fields`): every other rule reads only what the owner last wrote, and gave its verdict then. A rule reading a referenced document is not judged either: the change checks no reference, and registration keeps such a rule from reading anything the change can break. Whoever owns the document is no protection: the fields are the moderators'. Nothing the document type prices is charged. The action carries the contract and the changed document, and Drive stores it with `DocumentOperationType::UpdateDocument`, the replace's update, every index and aggregate of the type included. The document's storage flags name its owner, as a replace's do: the moderator pays for the bytes the change adds, and what the change frees (a smaller value, an index entry that moved) is refunded to the owner, who paid for it. A seated team's member does not have the change counted toward the team's action share: the changes of one document have no bound, and counting them would let a member farm it. A change that changes nothing is refused (10905) rather than written. `$updatedAt` does not move, so a change never opens a `moderatorAbilities.deleteWithin` window again: a moderator can not keep a post deletable by touching it. diff --git a/book/src/data-model/documents.md b/book/src/data-model/documents.md index 6437b482e42..919de46c883 100644 --- a/book/src/data-model/documents.md +++ b/book/src/data-model/documents.md @@ -658,13 +658,13 @@ A document type either allows replaces (`documentsMutable: true`, the default) o The parser (generation 3, meta-schema v3) reads the list on every parse (`parse_immutable_keyword`, `apply_immutable_fields`): - The shape is checked on both paths: every entry is a string or an object with exactly `property` and `when`, and no property is listed twice. `immutableAllowSetting`, the keyword the `present: "$old.

"` condition replaces, is refused, naming its replacement, so that no contract written with it loads with another meaning. -- A condition is parsed with the `propertyConstraints` grammar (`parse_property_constraint_condition`) and what it reads is checked as a rule's reads are (`validate_property_constraint_reads`), on both paths: a stored condition reading an undeclared or transient property could only read it as absent. A path through `$old.` (`STORED_DOCUMENT_PREFIX`) is judged as the path after it, and only a condition of `immutable` may use one. A condition may not read a `countOf` or `sumOf`, so a replace judges it without reading state. +- A condition is parsed with the `propertyConstraints` grammar (`parse_property_constraint_condition`) and what it reads is checked as a rule's reads are (`validate_property_constraint_reads`), on both paths: a stored condition reading an undeclared or transient property could only read it as absent. A path through `$old.` (`STORED_DOCUMENT_PREFIX`) is judged as the path after it. A condition of `immutable`, a `propertyConstraints` rule and a `retractedWhen` condition may use one; a `deleteConstraints` rule, judged on the stored document itself, may not. A condition may not read a `countOf` or `sumOf`, so a replace judges it without reading state. - Under full validation, when a contract enters the chain: the type is mutable; every listed property is a declared top-level property, neither a system property nor transient (list the containing object to freeze a nested value); a condition stays within a rule's node limit and lists no condition twice. Stored contracts skip these lints, so a later tightening can never make a committed contract unreadable. - A `deletableDocument` reference by id may be listed only without a condition. A replace may clear such a reference once its target is deleted (see [References on the Elements](#references-on-the-elements)), and a replace the condition then left free could set it to another document: the frozen reference would be repointed. The clear stays, because every replace re-validates the reference and without the clear the document could never be replaced again, so the condition is refused at registration instead, and on contract update, which parses the whole new contract the same way. Every other `deletableDocument` form is refused on any immutable property. - A property listed with a condition is not fixed once written (`schema_property_is_fixed_once_written`): a `findBy` key, an `inList` list and the values read beside a `findBy` function may not rely on it. - On contract update the properties listed without a condition may only grow, and a property listed with a condition keeps it as it is or loses it to be listed without one (`validate_immutable_fields_update`, `DocumentTypeUpdateError` otherwise). Whether one condition holds wherever another does cannot be told in general, so a changed condition is refused. The schema compatibility differ strips the key, like `indices` and `required`, so `validate_update` v1 is the single judge. -Enforcement lives in the replace action's state validation (generation 1). The action already records which top-level properties differ from the stored document in `changed_data_fields` (the same set that scopes `refersTo` re-validation). A changed property in the type's `immutable_fields()` fails the replace with `DocumentImmutablePropertyChangedError` (state code 40128) unless it is a `deletableDocument` reference by id that the replace removed after its target was deleted. A changed property in `immutable_field_conditions()` fails it with the same error when its condition holds, or faults, judged by `PropertyConstraint::holds` on the written properties with the stored ones under `$old` and the replace's system values (the stored creation and transfer, this block as the update). The stored properties are rebuilt from the written ones and `stored_changed_values`, the stored value of every changed property; a property the stored document did not hold is left out. Conditions are evaluated only for the properties the replace changes. The replace compares stored and supplied values by underlying data, recursing into objects regardless of member order and into arrays position by position, with integer widths ignored, since storage reorders object members by schema position and narrows integers. "Differ" covers a changed value, a property the stored document lacked, and a property the replace dropped. Transfers, price updates and purchases carry no property data and are unaffected. +Enforcement lives in the replace action's state validation (generation 1). The action already records which top-level properties differ from the stored document in `changed_data_fields` (the same set that scopes `refersTo` re-validation). A changed property in the type's `immutable_fields()` fails the replace with `DocumentImmutablePropertyChangedError` (state code 40128) unless it is a `deletableDocument` reference by id that the replace removed after its target was deleted. A changed property in `immutable_field_conditions()` fails it with the same error when its condition holds, or faults, judged by `PropertyConstraint::holds` on the written properties with the stored ones under `$old` and the replace's system values (the writer as `$ownerId`, the stored creation and transfer, this block as the update, the replace's revision), with the stored version's owner, times, heights and revision for `$old.$ownerId`, `$old.$updatedAt` and the rest: the batch transformer attaches them from the stored document it fetched (`PropertyConstraintReads::stored_system_values`) whenever a rule or condition of the type reads `$old.`. The stored properties are rebuilt from the written ones and `stored_changed_values`, the stored value of every changed property; a property the stored document did not hold is left out. Conditions are evaluated only for the properties the replace changes. The replace compares stored and supplied values by underlying data, recursing into objects regardless of member order and into arrays position by position, with integer widths ignored, since storage reorders object members by schema position and narrows integers. "Differ" covers a changed value, a property the stored document lacked, and a property the replace dropped. Transfers, price updates and purchases carry no property data and are unaffected. In Rust the properties frozen at creation are `DocumentTypeV2Getters::immutable_fields()` and those frozen under a condition `immutable_field_conditions()`, property to `PropertyConstraint`. Earlier document type generations return empty ones. @@ -917,11 +917,11 @@ Conditions are checked in declared order and no further than the outcome needs: The parser (generation 3, meta-schema v3) checks the keyword on every parse, stored contracts included: the shape, that every path an operand reads names an integer or boolean property of the type, every path `length` or `byteLength` measures a string property, every path `count` counts an array or byte array property, every path `byteAt` reads or a `startsWith` or `endsWith` of byte arrays tests a byte array property (within its `maxItems`, when it declares one), every system time or height a rule reads is one the type lists in `required` (and an indexOnly type reads none), every path compared with a string names a string property (and every constant compared with one that declares an `enum` is one of its values) (a nested one by its dotted path) and every path `present`, `absent` or `countPresent` tests names a property of the type, and that neither is `transient` nor inside a transient object (a transient value is never stored, so a stored document could not be held to the rule), that every comparison and `in` reads at least one property (a constant one would make its rule, or an `anyOf` around it, hold for every document or for none), that no `in` lists a value twice and no `countPresent` a path twice, that no `anyOf` or `allOf` holds one of its own kind directly and no `not` a `not`, that no literal divisor is 0 and no literal exponent negative, and that no condition or operand nests deeper than `MAX_PROPERTY_CONSTRAINT_PARSE_DEPTH` (64), a constant that keeps a parse without full validation from recursing without bound and that no registrable rule comes near. Under full validation, when a contract registers or updates, it also holds the limits: at most `SystemLimits::max_property_constraints` rules per type (16) and `max_property_constraint_nodes` nodes per rule (32), counting every comparison and logical operator, every `in` and each value it lists, every `const`, every `present` or `absent`, every arithmetic operator and every operand (a size is one, a `countPresent` one plus one per path), that no `anyOf` or `allOf` lists the same condition twice (conditions that parse alike, so `1` and `1.0` are the same value), and that the rules of one type read at most `max_property_constraint_aggregates` (4) distinct totals. Once every document type of the contract is parsed, a registration also checks every `countOf` and `sumOf`: the type it counts is one of the contract's and not indexOnly, nor the declaring type when it has a contested index (a document a contest awards is stored without the rules judged), a tree of it keeps the total, the filter's keys and values are integers, strings or identifiers of the same kind, and every property a value reads is required. The rules are fixed when the document type is created: adding, removing or changing one is an incompatible schema change (`IncompatibleDocumentTypeSchemaError`, 10246), since stored documents were judged against the rules as they were. -Enforcement lives in `DataContract::validate_document_properties` (generation 0, extended in place: the call is inert before protocol version 14, where `validate_property_constraints` is `None`), after the schema validation. Document create and replace structure validation call it, so consensus applies the rules, and so does every client that validates a document before sending it. The rules are checked in name order against the document's properties, which for a replace is the whole document, and the first one broken fails with `DocumentPropertyConstraintViolatedError` (basic code 10422), naming the document type, the rule and why: the rule does not hold, or evaluating it overflowed, divided by zero, raised to a negative power or read a value that is not an integer. The check changes nothing stored. It reads state only for the `countOf` and `sumOf` totals, which the document batch transformer reads when it builds the action (`Drive::fetch_property_constraint_aggregate`, billed with the write) and hands the check in `DocumentSystemValues::aggregates`; the limits bound its cost. `$ownerId` and the system times and heights read the values of the document version being written (`validate_document_properties` takes them as `DocumentSystemValues`): on a create the writer and the block's time and heights, on a replace the writer, the stored creation and transfer values and the block's as the update. A client passes what it knows: an owner it does not know equals no identifier, and a rule reading a time, a height or a total it is not given is not judged. Consensus reads every total the rules it judges read (`DocumentSystemValues::aggregates` is `Some`), so one missing there is an error in the code building the write, never a skipped rule. The SDK pre-checks use the device clock for the times a write records, and leave a rule reading a block height unjudged, since the height is unknown until the block. Transfers and purchases change no property, only the owner and the transfer's time and heights, so only the rules reading those are judged again, with the new values (`DocumentTypeV0Methods::validate_property_constraints_for_system_change`, next to the `distinctFrom` check). Price updates change only the update's time and heights, and are judged against the rules reading those the same way. +Enforcement lives in `DataContract::validate_document_properties` (generation 0, extended in place: the call is inert before protocol version 14, where `validate_property_constraints` is `None`), after the schema validation. Document create and replace structure validation call it, so consensus applies the rules, and so does every client that validates a document before sending it. The rules are checked in name order against the document's properties, which for a replace is the whole document, and the first one broken fails with `DocumentPropertyConstraintViolatedError` (basic code 10422), naming the document type, the rule and why: the rule does not hold, or evaluating it overflowed, divided by zero, raised to a negative power or read a value that is not an integer. The check changes nothing stored. It reads state only for the `countOf` and `sumOf` totals, which the document batch transformer reads when it builds the action (`Drive::fetch_property_constraint_aggregate`, billed with the write) and hands the check in `DocumentSystemValues::aggregates`; the limits bound its cost. `$ownerId`, the system times and heights and `$revision` read the values of the document version being written (`validate_document_properties` takes them as `DocumentSystemValues`): on a create the writer, the block's time and heights and revision 1, on a replace the writer, the stored creation and transfer values, the block's as the update and the replace's revision. A read through `$old.` reads the stored version `DocumentSystemValues::stored` gives: on a create `StoredVersion::Absent`, where a property reads as left out, `$old.$ownerId` equals no identifier and a stored time, height or revision reads 0, and on any other write the document as stored before it. A client passes what it knows: an owner it does not know equals no identifier, and a rule reading a time, a height, a revision, a total or a stored version it is not given is not judged. Consensus reads every total the rules it judges read (`DocumentSystemValues::aggregates` is `Some`), and gives the stored version to every rule reading it, so one missing there is an error in the code building the write, never a skipped rule. The SDK pre-checks use the device clock for the times a write records, and leave a rule reading a block height the write records unjudged, since the height is unknown until the block; a stored height read through `$old.` is judged, reading 0 on a create. Transfers and purchases change no property, only the owner, the transfer's time and heights and `$revision`, so only the rules reading those, of the document or through `$old.` of the version before the write, or a total depending on the owner, are judged again, with the new values (`DocumentTypeV0Methods::validate_property_constraints_for_system_change`, which asks `PropertyConstraint::reads_change`, next to the `distinctFrom` check). Price updates change only the update's time and heights and `$revision`, and are judged against the rules reading those, of either version, the same way. A moderator's change of fields is judged by `validate_document_properties` with `DocumentSystemValues::changed_fields`, against the rules reading a field it changes (directly or through `$old.`), `$revision`, or a total, which may have moved since the document was last written (`PropertyConstraint::reads_changed_fields`), and a moderator's restore against the rules reading a total (`SystemChange::Restore`), `$old.` reading the restored document itself. A rule reading a referenced document (protocol version 14) is not judged there: its values are read by the reference check, which runs in document create state validation 2 and replace state validation 1, after the structure validation. The parser turns a `referenced` operand into the path `$referenced..` (`REFERENCED_DOCUMENT_PREFIX`), so the evaluation reads it as any path; `DocumentSystemValues::referenced_documents` says whether the data holds those values, and `PropertyConstraint::violation` leaves a rule reading one unjudged without them, which is how the structure validation, transfers, purchases, price updates, moderator restores and changes of fields, and every SDK pre-check pass over it. The reference validation (`validate_document_references`, generation 0, extended in place) checks every reference a rule reads through on every replace (`referenced_fields` lists them), and, once each holds, records the values the rules read of the document it found, or of the removal record a kept `moderatedDocument` reference resolves to (`referenced_document_values`); the state validation then judges those rules alone (`DocumentTypeV0Methods::validate_referencing_property_constraints`) against the document's data with the values under `$referenced` (`data_with_referenced_documents`). No read is added: a create reads each referenced document once, as the existence check always did, and a replace makes the check's read again, billed the same way. Registration checks the declaring side when the type is parsed (`validate_referencing_rules`) and what a rule reads of a referenced type with that type in hand (`referenced_reads_error`): in the contract parse for a type of the same contract (10231), in contract create and update state validation for another contract's (`ReferencedDocumentRuleReadInvalidError`, 40148). -In Rust the rules are `DocumentTypeV2Getters::property_constraints` (a map from name to `PropertyConstraint`: a comparison, an `in`, a string comparison (`TextCompare`, `TextIn`), a `present` or `absent`, or an `anyOf`, `allOf` or `not` of them, empty on types that predate the keyword; `property_reads` lists what a rule reads and how: by value, by presence, by size (`Length`, `Count`) or in a comparison of strings or identifiers, `system_reads` the system times and heights it reads, and `aggregate_reads` the totals, each an `AggregateRead`), each rule's `holds` and `violation` evaluate it against a document's data and `DocumentSystemValues`, and the document check is `DocumentTypeV0Methods::validate_property_constraints`. +In Rust the rules are `DocumentTypeV2Getters::property_constraints` (a map from name to `PropertyConstraint`: a comparison, an `in`, a string comparison (`TextCompare`, `TextIn`), a `present` or `absent`, or an `anyOf`, `allOf` or `not` of them, empty on types that predate the keyword; `property_reads` lists what a rule reads and how: by value, by presence, by size (`Length`, `Count`) or in a comparison of strings or identifiers, `system_reads` the system values it reads, each a `SystemRead`: a time, a height or `$revision` (`SystemValue`), of the version written or, through `$old.`, of the stored one, and `aggregate_reads` the totals, each an `AggregateRead`), each rule's `holds` and `violation` evaluate it against a document's data and `DocumentSystemValues`, and the document check is `DocumentTypeV0Methods::validate_property_constraints`. ### Delete rules (`deleteConstraints`) diff --git a/packages/js-evo-sdk/README.md b/packages/js-evo-sdk/README.md index 736d89b52a2..00703582aeb 100644 --- a/packages/js-evo-sdk/README.md +++ b/packages/js-evo-sdk/README.md @@ -480,15 +480,17 @@ try { } ``` -To find a broken rule before paying for a refused transition, a contract lists a document type's rules and checks a document against them with the code consensus runs. The check covers the rules alone, not the JSON schema. It reads the document's owner for `$ownerId`, and the device clock for the times the write will record (`readsSystem` lists the ones a rule reads); a rule reading a block height is not checked, since the height is unknown until the block, and neither is a rule reading a `countOf` or `sumOf` total, which only the platform reads from state (`readsTotals` lists the ones a rule reads, each with its `kind`, `documentType`, the summed `property` of a `sumOf` and the `filter` keys), nor one reading a value of the document a reference points at, `{ referenced: [reference, field] }`, which the platform reads when it checks the reference (`readsReferenced` lists them, each with its `reference`, `path` and `kind`): +To find a broken rule before paying for a refused transition, a contract lists a document type's rules and checks a document against them with the code consensus runs. The check covers the rules alone, not the JSON schema. It reads the device clock for the times the write will record (`readsSystem` lists the ones a rule reads); a rule reading a block height the write records (every height on a create, the update's on a replace) is not checked, since the height is unknown until the block, and neither is a rule reading a `countOf` or `sumOf` total, which only the platform reads from state (`readsTotals` lists the ones a rule reads, each with its `kind`, `documentType`, the summed `property` of a `sumOf` and the `filter` keys), nor one reading a value of the document a reference points at, `{ referenced: [reference, field] }`, which the platform reads when it checks the reference (`readsReferenced` lists them, each with its `reference`, `path` and `kind`). The second argument says which write is checked. Given the stored document, a replace, `$ownerId`, `$revision` and the creation and transfer are what consensus judges, whatever the document holds: the stored document's owner, creation and transfer times and heights, and the revision after the stored one; a rule reading the stored version through `$old.` (`readsStored`) reads that document, its heights included. Given `null`, a create, `$ownerId` is the document's owner, `$revision` 1 and every time the device clock, and every `$old.` read is absent (a stored time, height or revision reads 0). Given `undefined`, the document's own owner, creation and transfer are read (the device clock for a time it lacks), and neither a rule reading `$old.` nor one reading `$revision`, which depends on the write, is judged: ```ts contract.documentTypePropertyConstraints('offer'); // [{ name: 'discountBelowPrice', rule: { lessThan: ['discount', 'price'] }, // reads: [{ path: 'discount', kind: 'value' }, { path: 'price', kind: 'value' }], -// readsOwner: false, readsSystem: [], readsTotals: [], readsReferenced: [] }, ...] +// readsOwner: false, readsSystem: [], readsStored: false, readsTotals: [], +// readsReferenced: [] }, ...] -const broken = contract.checkDocumentPropertyConstraints(document); +// `null`: a create; pass the stored document to check a replace +const broken = contract.checkDocumentPropertyConstraints(document, null); if (broken) { // { rule: 'discountBelowPrice', violation: 'NotMet', message: 'it does not hold' } } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentTypeDetailsScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentTypeDetailsScreen.kt index b247093fb9c..56e4b3ef4ed 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentTypeDetailsScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentTypeDetailsScreen.kt @@ -404,8 +404,9 @@ private fun PropertyConstraintsFormSection(section: PropertyConstraintsSection) /** * One `propertyConstraints` rule: its name, the rule as declared, what it - * reads, the system times and heights, the totals and the values of referenced documents it - * reads, and whether an owner change is judged against it too + * reads, the system times, heights and revisions, the stored version, the totals and the + * values of referenced documents it reads, and whether an owner change is judged against it + * too * (← `PropertyConstraintRowView` in DocumentTypeDetailsView.swift). */ @Composable @@ -413,6 +414,7 @@ private fun PropertyConstraintRow(rule: DocumentPropertyConstraint) { val prettyRule = remember(rule) { rule.prettyRuleJson } val reads = remember(rule) { propertyConstraintReadsText(rule) } val systemReads = remember(rule) { propertyConstraintSystemReadsText(rule) } + val storedReads = remember(rule) { propertyConstraintStoredReadsText(rule) } val totals = remember(rule) { propertyConstraintTotalsText(rule) } val referenced = remember(rule) { propertyConstraintReferencedReadsText(rule) } Column( @@ -463,6 +465,19 @@ private fun PropertyConstraintRow(rule: DocumentPropertyConstraint) { color = MaterialTheme.colorScheme.tertiary, ) } + if (storedReads != null) { + Text( + storedReads, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.testTag("documentType.propertyConstraint.${rule.name}.readsStored"), + ) + Text( + PROPERTY_CONSTRAINT_STORED_READS_NOTE, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.tertiary, + ) + } if (totals != null) { Text( totals, @@ -491,8 +506,9 @@ private fun PropertyConstraintRow(rule: DocumentPropertyConstraint) { } if (rule.readsOwner) { Text( - "Reads \$ownerId, the document's owner: transfers and purchases are judged " + - "against this rule too.", + "Reads the owner (\$ownerId, \$old.\$ownerId, the owner before the write, " + + "or a total that depends on the owner): transfers and purchases are " + + "judged against this rule too.", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.tertiary, ) diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/PropertyConstraints.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/PropertyConstraints.kt index 504ee8c283e..e25740bf665 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/PropertyConstraints.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/PropertyConstraints.kt @@ -148,7 +148,26 @@ internal fun propertyConstraintSystemReadsText(rule: DocumentPropertyConstraint) */ internal const val PROPERTY_CONSTRAINT_SYSTEM_READS_NOTE = "A price update is judged against the rules reading \$updatedAt or its block heights, " + - "and a transfer or purchase against those reading \$transferredAt or its block heights." + "a transfer or purchase against those reading \$transferredAt or its block heights, " + + "and each of them against those reading \$revision." + +/** + * The line shown under a rule reading the stored version of the document + * through `$old.` ([DocumentPropertyConstraint.readsStored]), `null` for a + * rule reading none of it. The SwiftExampleApp shows the same text. + */ +internal fun propertyConstraintStoredReadsText(rule: DocumentPropertyConstraint): String? = + if (rule.readsStored) "Reads the stored version (\$old.), the one a write replaces" else null + +/** + * The note under a rule reading the stored version + * ([propertyConstraintStoredReadsText] not `null`): a create has none, so + * consensus and the check before sending both read every `$old.` value as + * absent. The same text as the SwiftExampleApp's, for cross-platform UAT. + */ +internal const val PROPERTY_CONSTRAINT_STORED_READS_NOTE = + "A create has no stored version: there, and in the check before sending, every \$old. " + + "read is absent." /** * The line naming the `countOf` and `sumOf` totals [rule] reads, each once: diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/PropertyConstraintsTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/PropertyConstraintsTest.kt index ed023935875..3121bee6a76 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/PropertyConstraintsTest.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/PropertyConstraintsTest.kt @@ -340,15 +340,45 @@ class PropertyConstraintsTest { /** The note under a rule reading a system value; the SwiftExampleApp shows the same text. */ @Test - fun `should say which writes the update and transfer times answer to`() { + fun `should say which writes the update and transfer times and the revision answer to`() { assertEquals( "A price update is judged against the rules reading ${'$'}updatedAt or its block " + - "heights, and a transfer or purchase against those reading ${'$'}transferredAt or " + - "its block heights.", + "heights, a transfer or purchase against those reading ${'$'}transferredAt or " + + "its block heights, and each of them against those reading ${'$'}revision.", PROPERTY_CONSTRAINT_SYSTEM_READS_NOTE, ) } + /** A rule comparing a property with its stored value, as Rust lists it. */ + private val storedRule = DocumentPropertyConstraint( + name = "closedOnlyFromOpen", + ruleJson = """{"equal":["${'$'}old.status",{"const":"open"}]}""", + reads = listOf(PropertyConstraintRead("${'$'}old.status", PropertyConstraintRead.Kind.Text)), + readsOwner = false, + readsStored = true, + ) + + /** The line under a rule reading the stored version; the SwiftExampleApp shows the same text. */ + @Test + fun `should show the stored version line only for a rule reading it`() { + assertEquals( + "Reads the stored version (${'$'}old.), the one a write replaces", + propertyConstraintStoredReadsText(storedRule), + ) + assertNull(propertyConstraintStoredReadsText(rule)) + assertNull(propertyConstraintStoredReadsText(timedRule)) + } + + /** The note under a rule reading the stored version; the SwiftExampleApp shows the same text. */ + @Test + fun `should say a create reads every stored value as absent`() { + assertEquals( + "A create has no stored version: there, and in the check before sending, every " + + "${'$'}old. read is absent.", + PROPERTY_CONSTRAINT_STORED_READS_NOTE, + ) + } + @Test fun `should name the rule the violation and the reason in the alert`() { assertEquals( diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/QueriesNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/QueriesNative.kt index 56f81d1231c..1707de1cb88 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/QueriesNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/QueriesNative.kt @@ -75,10 +75,13 @@ internal object QueriesNative { /** * The `propertyConstraints` rules (protocol version 14) of [documentType] * as a JSON array in name order, each - * `{"name", "rule", "reads": [{"path", "kind"}], "readsOwner", "readsSystem", "readsTotals", "readsReferenced"}`: + * `{"name", "rule", "reads": [{"path", "kind"}], "readsOwner", "readsSystem", "readsStored", "readsTotals", "readsReferenced"}`: * `kind` is `value`, `presence`, `text`, `identifier`, `length`, `count`, - * `elements` or `bytes`, `readsSystem` names the system times and heights - * the rule reads (`$createdAt`, `$updatedAtBlockHeight`, ...), + * `elements` or `bytes`, a property of the stored version listed under + * its `$old.` path, `readsSystem` names the system values the rule reads + * (`$createdAt`, `$updatedAtBlockHeight`, `$revision`, `$old.$updatedAt`, + * ...), `readsStored` says whether it reads the stored version through + * `$old.` (missing from a library built before it), * `readsTotals` lists its `countOf` and `sumOf` totals as * `{"kind", "documentType", "property" (a sumOf only), "filter"}`, and * `readsReferenced` the values it reads of the documents the type's @@ -100,15 +103,18 @@ internal object QueriesNative { * as `{"rule", "violation", "message"}`, or the JSON text `null` when it * meets every rule. [propertiesJson] is what the create would send and * [ownerId] the 32-byte owner `$ownerId` reads; [serializedContract] as - * for [dataContractGetPropertyConstraints]. The device clock stands in for - * the block time the create records (`$createdAt`, `$updatedAt`, - * `$transferredAt`), and a rule reading a block height is not judged, the - * height being unknown until the block, nor is one reading a `countOf` or - * `sumOf` total, which only the platform reads from state, or a value of a - * referenced document, which the platform reads when it checks the - * reference. No network call. Throws on - * error (as above, plus an owner id that is not 32 bytes or properties - * that are not a JSON object). + * for [dataContractGetPropertyConstraints]. A create has no stored + * version, so every `$old.` read is absent (a stored time, height or + * revision reads 0) and `$revision` reads 1, as consensus reads them on a + * create. The device clock stands in for the block time the create + * records (`$createdAt`, `$updatedAt`, `$transferredAt`), and a rule + * reading a block height the create records (without `$old.`) is not + * judged, the height being unknown until the block, nor is one reading a + * `countOf` or `sumOf` total, which only the platform reads from state, or + * a value of a referenced document, which the platform reads when it + * checks the reference. No network call. Throws on error (as above, plus + * an owner id that is not 32 bytes or properties that are not a JSON + * object). */ external fun dataContractCheckPropertyConstraints( sdk: Long, diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/DocumentPropertyConstraints.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/DocumentPropertyConstraints.kt index 885d4e37e03..6ea2d071073 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/DocumentPropertyConstraints.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/DocumentPropertyConstraints.kt @@ -17,7 +17,13 @@ import org.dashfoundation.dashsdk.errors.DashSdkError * one with `DocumentPropertyConstraintViolatedError` (code 10422); a refused * state transition is still paid for. A transfer, a purchase or a price update * is judged against the rules reading what it changes ([readsOwner], - * [readsSystem]). + * [readsSystem]), `$revision` included. + * + * A rule may read the stored version of the document a write replaces + * through the `$old.` prefix ([readsStored]): `$old.status` is the stored + * `status`, `$old.$ownerId` the stored owner, and `$old.$updatedAt` or + * `$old.$revision` a stored system value. A create has no stored version, so + * there every such read is absent. * * Rust parses the rules and reports them * (`dash_sdk_data_contract_get_property_constraints`, through @@ -35,7 +41,8 @@ data class DocumentPropertyConstraint( * sorting changes nothing a reader would notice). Among its operators: * sizes (`{ "length": path }`, `{ "byteLength": path }`, * `{ "count": path }`), `{ "countPresent": [path, path, ...] }`, system - * times and heights as bare operands (`"$createdAt"`), + * times, heights and `$revision` as bare operands (`"$createdAt"`), + * paths of the stored version through `$old.` (`"$old.status"`), * `{ "contains": [arrayPath, value] }`, * `{ "startsWith": [a, b] }`, `{ "endsWith": [a, b] }`, * `{ "notIn": [operand, [values]] }`, `{ "min": [a, b, ...] }`, @@ -46,32 +53,39 @@ data class DocumentPropertyConstraint( /** * Every property the rule reads, in declared order, a property read twice * listed twice, every branch of an `ifThen` or `ifThenElse` included, - * whichever one a document takes. `$ownerId` and the system times and - * heights are no properties and are not listed: see [readsOwner] and - * [readsSystem], which cover every branch too. Nor is a value of a - * document a reference points at: see [readsReferenced]. + * whichever one a document takes. A property of the stored version, read + * through `$old.`, is listed under that path (`$old.status`): see + * [readsStored]. `$ownerId`, `$old.$ownerId` and the system times, + * heights and revisions are no properties and are not listed: see + * [readsOwner] and [readsSystem], which cover every branch too. Nor is a + * value of a document a reference points at: see [readsReferenced]. */ val reads: List, /** - * Whether the rule compares the document's owner, `$ownerId`, or reads a - * total that depends on it ([readsTotals]): then a transfer or a purchase, - * which changes the owner, is judged against it too. + * Whether the rule compares the document's owner, `$ownerId`, or the + * stored version's owner, `$old.$ownerId`, or reads a total that depends + * on it ([readsTotals]): then a transfer or a purchase, which changes the + * owner, is judged against it too. */ val readsOwner: Boolean, /** - * The system times and heights the rule reads, by name, in declared order, - * one read twice listed twice: `$createdAt`, `$updatedAt` and - * `$transferredAt` (a block time in milliseconds), each also with - * `BlockHeight` or `CoreBlockHeight` appended (the Platform or the Core - * block height). The names are wasm-dpp2's - * `PropertyConstraintSystemProperty`. A rule reads only the ones its - * document type records, by listing them in `required`. + * The system values the rule reads, by name, in declared order, one read + * twice listed twice: `$createdAt`, `$updatedAt` and `$transferredAt` (a + * block time in milliseconds), each also with `BlockHeight` or + * `CoreBlockHeight` appended (the Platform or the Core block height), and + * `$revision` (1 for a created document, one more for each later write of + * it). The names are wasm-dpp2's `PropertyConstraintSystemProperty`. A + * name prefixed with `$old.` is the stored version's value + * (`$old.$updatedAt`, `$old.$revision`): see [readsStored]. A rule reads + * only the times and heights its document type records, by listing them + * in `required`, and `$revision` only on a document type that keeps one. * * Consensus judges a price update against the rules reading the update's - * (`$updatedAt...`), and a transfer or a purchase against those reading - * the transfer's (`$transferredAt...`) or the owner ([readsOwner]). This - * list only names what a rule reads; Rust decides which writes a rule - * answers to. + * (`$updatedAt...`), a transfer or a purchase against those reading the + * transfer's (`$transferredAt...`) or the owner ([readsOwner]), and each + * of them against those reading `$revision`, of either version. This list + * only names what a rule reads; Rust decides which writes a rule answers + * to. * * Empty for a rule reading none, and for every rule when the native * library predates the field. @@ -101,6 +115,24 @@ data class DocumentPropertyConstraint( * library predates the field. */ val readsReferenced: List = emptyList(), + /** + * Whether the rule reads the stored version of the document a write + * replaces, through `$old.`: one of its properties (listed in [reads]), + * its owner, `$old.$ownerId` ([readsOwner]), or one of its system values + * (listed in [readsSystem]). + * + * A create has no stored version, so consensus reads every such value as + * absent there: a property as one the document leaves out (0, or its + * `ifAbsent` value; absent to `present`; equal to no string or + * identifier), `$old.$ownerId` as equal to no identifier, and a stored + * time, height or revision as 0. The pre-check + * ([Contracts.checkPropertyConstraints]), which judges a document to + * create, reads them the same way. + * + * `false` for a rule reading none, and for every rule when the native + * library predates the field. + */ + val readsStored: Boolean = false, ) { /** [ruleJson] indented for display, or [ruleJson] itself should it not parse back. */ val prettyRuleJson: String @@ -114,8 +146,8 @@ data class DocumentPropertyConstraint( /** * Decode the JSON array `dash_sdk_data_contract_get_property_constraints` * returns, keeping its order (name order). A rule without - * `readsSystem`, `readsTotals` or `readsReferenced`, from a native - * library built before the key, reads as reading none of those. + * `readsSystem`, `readsStored`, `readsTotals` or `readsReferenced`, from a + * native library built before the key, reads as reading none of those. * * @throws DashSdkError.SerializationError for text that is not such an array. */ @@ -131,10 +163,12 @@ data class DocumentPropertyConstraint( val reads = rule?.get("reads") as? JsonArray val readsOwner = rule?.get("readsOwner")?.jsonBooleanOrNull() val readsSystem = rule?.let(::readsSystemOf) + val readsStored = rule?.let(::readsStoredOf) val readsTotals = rule?.let(::readsTotalsOf) val readsReferenced = rule?.let(::readsReferencedOf) if (name == null || declaration == null || reads == null || readsOwner == null || - readsSystem == null || readsTotals == null || readsReferenced == null + readsSystem == null || readsStored == null || readsTotals == null || + readsReferenced == null ) { throw DashSdkError.SerializationError("Malformed propertyConstraints rule: $entry") } @@ -144,6 +178,7 @@ data class DocumentPropertyConstraint( reads = reads.map(PropertyConstraintRead::fromJson), readsOwner = readsOwner, readsSystem = readsSystem, + readsStored = readsStored, readsTotals = readsTotals, readsReferenced = readsReferenced, ) @@ -157,6 +192,15 @@ data class DocumentPropertyConstraint( private fun readsSystemOf(rule: JsonObject): List? = listOrNull(rule, "readsSystem") { it.jsonStringOrNull() } + /** + * [rule]'s `readsStored`: `false` when the key is missing, `null` when + * it is anything but a JSON boolean. + */ + private fun readsStoredOf(rule: JsonObject): Boolean? { + val value = rule["readsStored"] ?: return false + return value.jsonBooleanOrNull() + } + /** * The totals [rule]'s `readsTotals` lists: empty when the key is * missing, `null` when it or an entry is malformed. @@ -387,9 +431,10 @@ data class PropertyConstraintRead( * * Rust judges the document (`dash_sdk_data_contract_check_property_constraints`, * through [Contracts.checkPropertyConstraints]) with the check consensus runs, - * the device clock standing in for the times the create records, and a rule - * reading a block height, a `countOf` or `sumOf` total or a value of a - * referenced document left unjudged; this type only carries the verdict. + * the device clock standing in for the times the create records, a stored + * time, height or revision read through `$old.` as 0, and a rule reading a + * block height the create records, a `countOf` or `sumOf` total or a value of + * a referenced document left unjudged; this type only carries the verdict. * The fields mirror wasm-dpp2's `DocumentPropertyConstraintViolation` and the * Swift SDK's `PropertyConstraintViolation`. */ diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt index 583fee334bd..d2cc413d94c 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt @@ -669,11 +669,12 @@ class Contracts internal constructor(private val sdk: Sdk) { * * Each rule lists the properties it reads and how * ([DocumentPropertyConstraint.reads]), whether it reads the owner - * ([DocumentPropertyConstraint.readsOwner]), the system times and - * heights it reads ([DocumentPropertyConstraint.readsSystem]), the - * `countOf` and `sumOf` totals it reads ([DocumentPropertyConstraint.readsTotals]) - * and the values it reads of referenced documents - * ([DocumentPropertyConstraint.readsReferenced]). + * ([DocumentPropertyConstraint.readsOwner]), the system times, heights + * and revisions it reads ([DocumentPropertyConstraint.readsSystem]), + * whether it reads the stored version of the document through `$old.` + * ([DocumentPropertyConstraint.readsStored]), the `countOf` and `sumOf` + * totals it reads ([DocumentPropertyConstraint.readsTotals]) and the values + * it reads of referenced documents ([DocumentPropertyConstraint.readsReferenced]). * * [serializedContract] is the contract's platform serialization, the bytes * kept beside a fetched contract ([ContractWithSerialization.binarySerialization], @@ -708,11 +709,18 @@ class Contracts internal constructor(private val sdk: Sdk) { * with (what `DocumentTransactions.create` takes) and [ownerId] the 32-byte * identity that would own it, which `$ownerId` reads. Rust builds the * document the create path builds and judges it with the check consensus - * runs; nothing but the rules is checked. The device clock stands in for - * the block time the create records (`$createdAt`, `$updatedAt`, - * `$transferredAt`), so a rule comparing one is judged as of now; a rule - * reading a block height (`$createdAtBlockHeight`, ...) is not judged, - * since the height is unknown until the block, nor is a rule reading a + * runs; nothing but the rules is checked. A create has no stored version, + * so a rule reading one through `$old.` + * ([DocumentPropertyConstraint.readsStored]) is judged as consensus judges + * it on a create, every such read absent (a stored time, height or + * revision reads 0), and `$revision` reads 1, the revision a created + * document starts at. The device clock stands in for the block time the + * create records (`$createdAt`, `$updatedAt`, `$transferredAt`), so a + * rule comparing one is judged as of now; a rule reading a block height + * the create records (`$createdAtBlockHeight`, ..., without `$old.`) is + * not judged, since the height is unknown until the block (a stored + * height, `$old.$createdAtBlockHeight`, ..., reads 0 and is judged), nor + * is a rule reading a * `countOf` or `sumOf` total ([DocumentPropertyConstraint.readsTotals]), * which the platform reads from state when the document is sent, nor one * reading a value of a referenced document diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/queries/DocumentPropertyConstraintsTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/queries/DocumentPropertyConstraintsTest.kt index 271e4eaf7c8..c151c088ce2 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/queries/DocumentPropertyConstraintsTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/queries/DocumentPropertyConstraintsTest.kt @@ -3,6 +3,8 @@ package org.dashfoundation.dashsdk.queries import kotlinx.serialization.json.Json import org.dashfoundation.dashsdk.errors.DashSdkError import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue @@ -850,4 +852,140 @@ class DocumentPropertyConstraintsTest { } } } + + /** + * Rules reading the stored version of the document through `$old.`, as + * the FFI reports them: a stored property, the stored update time beside + * `$revision`, and the stored owner, in name order beside a rule reading + * none of it. + */ + private val storedRulesJson = """ + [ + { + "name": "closedOnlyFromOpen", + "readsOwner": false, + "reads": [ + { "kind": "text", "path": "status" }, + { "kind": "text", "path": "${'$'}old.status" } + ], + "readsSystem": [], + "readsStored": true, + "readsTotals": [], + "rule": { + "ifThen": [ + { "equal": ["status", { "const": "closed" }] }, + { "equal": ["${'$'}old.status", { "const": "open" }] } + ] + } + }, + { + "name": "priceCap", + "readsOwner": false, + "reads": [{ "kind": "value", "path": "price" }], + "readsSystem": [], + "readsStored": false, + "readsTotals": [], + "rule": { "lessThanOrEqual": ["price", 1000] } + }, + { + "name": "revisedAfterUpdate", + "readsOwner": false, + "reads": [], + "readsSystem": ["${'$'}revision", "${'$'}updatedAt", "${'$'}old.${'$'}updatedAt"], + "readsStored": true, + "readsTotals": [], + "rule": { + "allOf": [ + { "lessThanOrEqual": ["${'$'}revision", 100] }, + { "greaterThanOrEqual": ["${'$'}updatedAt", "${'$'}old.${'$'}updatedAt"] } + ] + } + }, + { + "name": "sellerUnchanged", + "readsOwner": true, + "reads": [{ "kind": "identifier", "path": "sellerId" }], + "readsSystem": [], + "readsStored": true, + "readsTotals": [], + "rule": { "equal": ["sellerId", "${'$'}old.${'$'}ownerId"] } + } + ] + """.trimIndent() + + // Stored version + + /** + * A stored property is listed under its `$old.` path, a stored system + * value under its `$old.` name beside `$revision`, and the stored owner + * only as an owner read, never as a property. + */ + @Test + fun `should decode the rules reading the stored version through old`() { + val rules = DocumentPropertyConstraint.listFromJson(storedRulesJson) + + assertEquals( + listOf("closedOnlyFromOpen", "priceCap", "revisedAfterUpdate", "sellerUnchanged"), + rules.map { it.name }, + ) + assertEquals(listOf(true, false, true, true), rules.map { it.readsStored }) + assertEquals( + listOf( + PropertyConstraintRead("status", PropertyConstraintRead.Kind.Text), + PropertyConstraintRead("${'$'}old.status", PropertyConstraintRead.Kind.Text), + ), + rules[0].reads, + ) + assertEquals( + listOf("${'$'}revision", "${'$'}updatedAt", "${'$'}old.${'$'}updatedAt"), + rules[2].readsSystem, + ) + assertEquals(emptyList(), rules[2].reads) + // `$old.$ownerId` is an owner read, not a property + assertEquals( + listOf(PropertyConstraintRead("sellerId", PropertyConstraintRead.Kind.Identifier)), + rules[3].reads, + ) + assertEquals(listOf(false, false, false, true), rules.map { it.readsOwner }) + assertEquals( + """{"equal":["sellerId","${'$'}old.${'$'}ownerId"]}""", + rules[3].ruleJson, + ) + } + + /** A native library built before `readsStored` leaves the key out. */ + @Test + fun `should read a rule without readsStored as not reading the stored version`() { + val rules = DocumentPropertyConstraint.listFromJson( + """[{"name":"r","readsOwner":false,"reads":[],"readsSystem":[],"readsTotals":[],"rule":{"present":"a"}}]""", + ) + + assertFalse(rules.single().readsStored) + assertEquals( + DocumentPropertyConstraint("r", """{"present":"a"}""", emptyList(), readsOwner = false), + rules.single(), + ) + assertNotEquals( + DocumentPropertyConstraint( + "r", + """{"present":"a"}""", + emptyList(), + readsOwner = false, + readsStored = true, + ), + rules.single(), + ) + } + + /** Present, `readsStored` must be a JSON boolean; only a missing key means false. */ + @Test + fun `should refuse a malformed readsStored`() { + for (readsStored in listOf("1", "0", "\"true\"", "null", "[]", "{}")) { + val json = + """[{"name":"r","readsOwner":false,"reads":[],"readsSystem":[],"readsStored":$readsStored,"rule":{"present":"a"}}]""" + assertThrows(json, DashSdkError.SerializationError::class.java) { + DocumentPropertyConstraint.listFromJson(json) + } + } + } } diff --git a/packages/rs-dpp/schema/meta_schemas/document/v3/document-meta.json b/packages/rs-dpp/schema/meta_schemas/document/v3/document-meta.json index 2358cdf201e..3efc17e99b5 100644 --- a/packages/rs-dpp/schema/meta_schemas/document/v3/document-meta.json +++ b/packages/rs-dpp/schema/meta_schemas/document/v3/document-meta.json @@ -477,11 +477,11 @@ } }, "propertyConstraintPath": { - "description": "The dotted path of a property of the document type, a nested one through the objects around it: an integer or boolean property when an operand reads its value, a string property when length or byteLength measures it, an array or byte array property when count counts its items, a byte array property when byteAt reads one of its bytes or startsWith or endsWith tests it, any property when present, absent or countPresent tests it. Or $ownerId, the document's owner, which only a comparison of identifiers reads, or a system time or height an integer operand reads ($createdAt, $updatedAt, $transferredAt, and each with BlockHeight or CoreBlockHeight appended), one the document type lists in required. Or { \"referenced\": [reference, field] }, a value of the document a reference of the type points at, read as a property of that type is", + "description": "The dotted path of a property of the document type, a nested one through the objects around it: an integer or boolean property when an operand reads its value, a string property when length or byteLength measures it, an array or byte array property when count counts its items, a byte array property when byteAt reads one of its bytes or startsWith or endsWith tests it, any property when present, absent or countPresent tests it. Or $ownerId, the document's owner, which only a comparison of identifiers reads, a system time or height an integer operand reads ($createdAt, $updatedAt, $transferredAt, and each with BlockHeight or CoreBlockHeight appended), one the document type lists in required, or $revision, which an integer operand reads on a document type that keeps a revision. Any of them may follow $old., which reads the stored version of the document a write replaces instead of the version it writes (absent on a create), in a propertyConstraints rule but not a deleteConstraints one, which is judged on the stored document itself. Or { \"referenced\": [reference, field] }, a value of the document a reference of the type points at, read as a property of that type is", "anyOf": [ { "type": "string", - "pattern": "^(\\$ownerId|\\$(created|updated|transferred)At(BlockHeight|CoreBlockHeight)?|[a-zA-Z0-9_]{1,64}(\\.[a-zA-Z0-9_]{1,64})*)$" + "pattern": "^(\\$old\\.)?(\\$ownerId|\\$revision|\\$(created|updated|transferred)At(BlockHeight|CoreBlockHeight)?|[a-zA-Z0-9_]{1,64}(\\.[a-zA-Z0-9_]{1,64})*)$" }, { "type": "object", @@ -2783,7 +2783,7 @@ } ] }, - "description": "The top-level properties of a mutable document type a replace may not change, add or remove. An entry naming a property freezes it at document creation; an entry { \"property\": ..., \"when\": condition } freezes it for any replace the condition holds for, and leaves it free for any other. A condition takes the grammar of a propertyConstraints rule (comparisons, arithmetic, in, present, absent, anyOf, allOf, not, ifThen, ifThenElse, the system times and heights the type requires, $ownerId) and is judged on the document the replace writes: its $updatedAt is the replace's block time, so { \"greaterThan\": [{ \"subtract\": [\"$updatedAt\", \"$createdAt\"] }, 300000] } freezes a property five minutes after the document was created. A path under $old. reads the stored document instead: { \"present\": \"$old.trackingCode\" } lets an absent trackingCode be set once, and { \"equal\": [\"$old.status\", { \"const\": \"published\" }] } freezes a property once the stored document is published. A condition may read no countOf or sumOf total. A replace changing a frozen property is rejected (DocumentImmutablePropertyChangedError, code 40128), except one removing a refersTo deletableDocument reference by id, listed without a condition, whose referenced document has been deleted. Only allowed when documentsMutable is true (the default). Every property must be a declared top-level property that is not transient, listed once: system properties ($-prefixed) are excluded because the platform manages them, and nested paths are not accepted (list the containing object to freeze it whole). A deletableDocument reference by id may be listed only without a condition. On contract update a property may be added, with a condition or without, and one listed with a condition may lose it; one listed without a condition stays, a condition never changes, and no property is dropped. Replaces immutableAllowSetting, which is refused. Available from protocol version 14." + "description": "The top-level properties of a mutable document type a replace may not change, add or remove. An entry naming a property freezes it at document creation; an entry { \"property\": ..., \"when\": condition } freezes it for any replace the condition holds for, and leaves it free for any other. A condition takes the grammar of a propertyConstraints rule (comparisons, arithmetic, in, present, absent, anyOf, allOf, not, ifThen, ifThenElse, the system times and heights the type requires, $revision, $ownerId) and is judged on the document the replace writes: its $updatedAt is the replace's block time, so { \"greaterThan\": [{ \"subtract\": [\"$updatedAt\", \"$createdAt\"] }, 300000] } freezes a property five minutes after the document was created. A path, $ownerId, a time, a height or $revision under $old. reads the stored document instead: { \"present\": \"$old.trackingCode\" } lets an absent trackingCode be set once, and { \"equal\": [\"$old.status\", { \"const\": \"published\" }] } freezes a property once the stored document is published. A condition may read no countOf or sumOf total. A replace changing a frozen property is rejected (DocumentImmutablePropertyChangedError, code 40128), except one removing a refersTo deletableDocument reference by id, listed without a condition, whose referenced document has been deleted. Only allowed when documentsMutable is true (the default). Every property must be a declared top-level property that is not transient, listed once: system properties ($-prefixed) are excluded because the platform manages them, and nested paths are not accepted (list the containing object to freeze it whole). A deletableDocument reference by id may be listed only without a condition. On contract update a property may be added, with a condition or without, and one listed with a condition may lose it; one listed without a condition stays, a condition never changes, and no property is dropped. Replaces immutableAllowSetting, which is refused. Available from protocol version 14." }, "retractedWhen": { "type": "object", @@ -2854,7 +2854,7 @@ } }, "propertyConstraints": { - "description": "Rules every created or replaced document of the type must meet, by name (1 to 64 letters, digits or underscores). A rule is a condition: an object with one key, either a comparison (equal, notEqual, lessThan, lessThanOrEqual, greaterThan or greaterThanOrEqual) listing the two integer expressions it compares, left then right, equal or notEqual of the path of a string property and a const string ({ \"equal\": [\"status\", { \"const\": \"closed\" }] }, either way round) or of the paths of two string properties, which compares their strings, and likewise for identifier properties, whose constants are base58 identifiers, in listing an integer expression and two or more distinct integer values it may take or the path of a string property and two or more distinct strings, startsWith or endsWith listing two strings, a const or a string property each, at least one a property, and holding if the first starts or ends with the second, byte for byte (a constant looked for in a string property that declares enum must start or end one of its values), contains listing the path of a typed array property and the value one of its elements must equal (an integer expression among integers, a const string or string property among strings, a const base58 identifier, identifier property or $ownerId among identifiers; an array left out holds nothing, and a constant must be one of the elements' enum values when they declare one), present or absent naming a property of any type (the document holds it, or leaves it out or sets it to null), or anyOf, allOf, not, ifThen or ifThenElse over conditions: anyOf holds if at least one of its two or more conditions holds, allOf if every one does, not if its one condition does not, ifThen if its second condition holds whenever its first does (the second evaluated only then), ifThenElse if its second holds when its first does and its third when it does not (only that branch evaluated); notIn lists what in lists and holds if the expression takes none of the values. An expression is an integer value, the dotted path of an integer or boolean property of the document type, whose value it takes (a boolean reading as 1 for true and 0 for false), 0 when the document leaves it out, a system time or height the document type records by listing it in required ($createdAt, $updatedAt and $transferredAt, block times in milliseconds, and each with BlockHeight or CoreBlockHeight appended, the Platform and Core block heights: those of the create, of the last create, replace or price update, and of the last create, transfer or purchase), or an object with one key: ifAbsent, a property path and the value it takes when the document leaves it out (an integer, or a string for a string property compared with strings); add, multiply, min or max, two or more operands; subtract, divide, modulo or power, exactly two; abs, one; length or byteLength, the characters or UTF-8 bytes of a string property, or count, the items of an array or byte array property, each 0 when the document leaves the property out ({ \"lessThanOrEqual\": [{ \"count\": \"tags\" }, \"maxTags\"] }); countOf or sumOf, how many documents of a document type of this contract match a filter (keys of that type or $ownerId, each mapped to a value read from the document written, $id its id) or the total of an integer property over them, as that type's count or sum trees keep it once the write is done, which needs documentsCountable or documentsSummable for a whole type and otherwise an index whose properties are exactly the filter's keys ({ \"lessThanOrEqual\": [{ \"countOf\": [\"listing\", { \"$ownerId\": \"$ownerId\" }] }, 10] }). A string property the document leaves out equals no constant and no other string property, not even one also left out, unless an ifAbsent gives it a string default ({ \"ifAbsent\": [\"status\", \"open\"] }), which it then reads as, and a constant compared with a string property that declares enum must be one of its values. The arithmetic is exact over 128-bit signed integers, operands evaluated left to right: divide and modulo are Euclidean (the remainder is never negative), 0 to the power 0 is 1, and a value or intermediate result that does not fit, a zero divisor, a negative exponent or a property value that is not an integer breaks the rule. Conditions are checked in declared order and no further than the outcome needs (anyOf stops at the first that holds, allOf at the first that fails), and a fault met in a condition that is checked breaks the rule whatever the others would say (not does not turn it into a pass), so an earlier condition can guard a later one. Every property an operand reads must be an integer or boolean property, every property length or byteLength measures a string property, every property count counts an array or byte array property, every property compared with a string a string property, present and absent may test a property of any type, and no property a rule reads may be transient or inside a transient object; every comparison and in must read at least one property, an anyOf or allOf may not hold two alike conditions or directly another of its kind, a not may not hold directly another not or a notIn, a literal 0 divisor or negative exponent is refused, and no condition or operand may nest deeper than 64 levels; a type declares at most SystemLimits max_property_constraints rules (16 from protocol version 14) of at most max_property_constraint_nodes nodes each (32), counting every comparison and logical operator, every in and each value it lists, every contains and its array, every const, every present or absent, every arithmetic operator and every operand, a size included; all checked at contract registration. When a document is created or replaced, consensus checks every rule not reading a referenced document, in name order, after the schema validation, then, once the references hold, every rule reading one, in name order, and refuses the first one the document breaks (DocumentPropertyConstraintViolatedError, 10422); a reference that does not hold is refused before any rule reading through it. $ownerId, the document's owner, is an identifier operand (never a property: not in present, absent or an integer operand, and not on an indexOnly type), and a transfer or a purchase, which gives the document a new owner, is refused when it would break a rule reading it. Likewise a transfer or a purchase is judged against the rules reading the transfer's time and heights, and a price update against those reading the update's, since each sets them; an indexOnly type reads no system time or height. The rules change nothing stored, and read state only for countOf and sumOf, each total a billed read of a count or sum tree, at most max_property_constraint_aggregates distinct totals per type (4); a type with a contested index totals no documents of its own type, since a document a contest awards is stored without the rules judged. Fixed when the document type is created: adding, removing or changing a rule is an incompatible schema change on update. Available from protocol version 14.", + "description": "Rules every created or replaced document of the type must meet, by name (1 to 64 letters, digits or underscores). A rule is a condition: an object with one key, either a comparison (equal, notEqual, lessThan, lessThanOrEqual, greaterThan or greaterThanOrEqual) listing the two integer expressions it compares, left then right, equal or notEqual of the path of a string property and a const string ({ \"equal\": [\"status\", { \"const\": \"closed\" }] }, either way round) or of the paths of two string properties, which compares their strings, and likewise for identifier properties, whose constants are base58 identifiers, in listing an integer expression and two or more distinct integer values it may take or the path of a string property and two or more distinct strings, startsWith or endsWith listing two strings, a const or a string property each, at least one a property, and holding if the first starts or ends with the second, byte for byte (a constant looked for in a string property that declares enum must start or end one of its values), contains listing the path of a typed array property and the value one of its elements must equal (an integer expression among integers, a const string or string property among strings, a const base58 identifier, identifier property or $ownerId among identifiers; an array left out holds nothing, and a constant must be one of the elements' enum values when they declare one), present or absent naming a property of any type (the document holds it, or leaves it out or sets it to null), or anyOf, allOf, not, ifThen or ifThenElse over conditions: anyOf holds if at least one of its two or more conditions holds, allOf if every one does, not if its one condition does not, ifThen if its second condition holds whenever its first does (the second evaluated only then), ifThenElse if its second holds when its first does and its third when it does not (only that branch evaluated); notIn lists what in lists and holds if the expression takes none of the values. An expression is an integer value, the dotted path of an integer or boolean property of the document type, whose value it takes (a boolean reading as 1 for true and 0 for false), 0 when the document leaves it out, a system time or height the document type records by listing it in required ($createdAt, $updatedAt and $transferredAt, block times in milliseconds, and each with BlockHeight or CoreBlockHeight appended, the Platform and Core block heights: those of the create, of the last create, replace or price update, and of the last create, transfer or purchase), or an object with one key: ifAbsent, a property path and the value it takes when the document leaves it out (an integer, or a string for a string property compared with strings); add, multiply, min or max, two or more operands; subtract, divide, modulo or power, exactly two; abs, one; length or byteLength, the characters or UTF-8 bytes of a string property, or count, the items of an array or byte array property, each 0 when the document leaves the property out ({ \"lessThanOrEqual\": [{ \"count\": \"tags\" }, \"maxTags\"] }); countOf or sumOf, how many documents of a document type of this contract match a filter (keys of that type or $ownerId, each mapped to a value read from the document written, $id its id) or the total of an integer property over them, as that type's count or sum trees keep it once the write is done, which needs documentsCountable or documentsSummable for a whole type and otherwise an index whose properties are exactly the filter's keys ({ \"lessThanOrEqual\": [{ \"countOf\": [\"listing\", { \"$ownerId\": \"$ownerId\" }] }, 10] }). A string property the document leaves out equals no constant and no other string property, not even one also left out, unless an ifAbsent gives it a string default ({ \"ifAbsent\": [\"status\", \"open\"] }), which it then reads as, and a constant compared with a string property that declares enum must be one of its values. The arithmetic is exact over 128-bit signed integers, operands evaluated left to right: divide and modulo are Euclidean (the remainder is never negative), 0 to the power 0 is 1, and a value or intermediate result that does not fit, a zero divisor, a negative exponent or a property value that is not an integer breaks the rule. Conditions are checked in declared order and no further than the outcome needs (anyOf stops at the first that holds, allOf at the first that fails), and a fault met in a condition that is checked breaks the rule whatever the others would say (not does not turn it into a pass), so an earlier condition can guard a later one. Every property an operand reads must be an integer or boolean property, every property length or byteLength measures a string property, every property count counts an array or byte array property, every property compared with a string a string property, present and absent may test a property of any type, and no property a rule reads may be transient or inside a transient object; every comparison and in must read at least one property, an anyOf or allOf may not hold two alike conditions or directly another of its kind, a not may not hold directly another not or a notIn, a literal 0 divisor or negative exponent is refused, and no condition or operand may nest deeper than 64 levels; a type declares at most SystemLimits max_property_constraints rules (16 from protocol version 14) of at most max_property_constraint_nodes nodes each (32), counting every comparison and logical operator, every in and each value it lists, every contains and its array, every const, every present or absent, every arithmetic operator and every operand, a size included; all checked at contract registration. When a document is created or replaced, consensus checks every rule not reading a referenced document, in name order, after the schema validation, then, once the references hold, every rule reading one, in name order, and refuses the first one the document breaks (DocumentPropertyConstraintViolatedError, 10422); a reference that does not hold is refused before any rule reading through it. $ownerId, the document's owner, is an identifier operand (never a property: not in present, absent or an integer operand, and not on an indexOnly type), and a transfer or a purchase, which gives the document a new owner, is refused when it would break a rule reading it. Likewise a transfer or a purchase is judged against the rules reading the transfer's time and heights, and a price update against those reading the update's, since each sets them; an indexOnly type reads no system time or height. On a type that keeps a revision (documents mutable, transferable, sold at a price their owner sets, or keeping fields for their moderators), $revision is an integer operand: 1 on a create and one more for each later write, so a transfer, a purchase and a price update are judged against the rules reading it too. A path, $ownerId, a time, a height or $revision under $old. reads the stored version of the document a write replaces instead ({ \"greaterThanOrEqual\": [\"counter\", { \"ifAbsent\": [\"$old.counter\", 0] }] }): on a create there is none, so a property under it is absent, $old.$ownerId equals no identifier and a stored time, height or revision reads 0; on a replace it is the document replaced; on a transfer, a purchase or a price update it is the document before it, whose properties are the same, so such a write is judged only against the rules reading what it changes, of either version. Only on a type that keeps a revision, and never in a countOf or sumOf filter. A moderator's change of a document's fields is judged against the rules reading a field it changes, of either version, $revision or a total, and a moderator's restore against the rules reading a total, $old. reading the document as it was. The rules change nothing stored, and read state only for countOf and sumOf, each total a billed read of a count or sum tree, at most max_property_constraint_aggregates distinct totals per type (4); a type with a contested index totals no documents of its own type, since a document a contest awards is stored without the rules judged. Fixed when the document type is created: adding, removing or changing a rule is an incompatible schema change on update. Available from protocol version 14.", "type": "object", "propertyNames": { "pattern": "^[a-zA-Z0-9_]{1,64}$" @@ -2865,7 +2865,7 @@ "minProperties": 1 }, "deleteConstraints": { - "description": "Rules the stored document must meet for its owner to delete it, by name (1 to 64 letters, digits or underscores), in the grammar of a propertyConstraints rule and held to the same limits, counted apart from propertyConstraints (16 rules of 32 nodes each, reading 4 distinct totals). When the owner deletes a document, consensus checks every rule, in name order, against the stored document (its properties, its $ownerId, the system times and heights the type requires, as stored) and refuses the delete at the first rule it breaks (DocumentDeleteConstraintViolatedError, 40147), paid. A countOf or sumOf reads the total as it will be once the document is gone, so a rule over the type's own documents no longer counts it, and a filter may match by the document's own id: { \"noVotes\": { \"equal\": [{ \"countOf\": [\"vote\", { \"pollId\": \"$id\" }] }, 0] } } lets a poll be deleted only while no vote points at it. Only the owner's delete is judged: the contract's moderators and a ttl delete as before. Only on a document type whose owner may delete its documents (canBeDeleted true, not \"onlyWhenConsumed\") and that is not indexOnly, and a refersTo with consume may not target the type, since a consume deletes without the rules. Fixed when the document type is created: adding, removing or changing a rule is an incompatible schema change on update. Available from protocol version 14.", + "description": "Rules the stored document must meet for its owner to delete it, by name (1 to 64 letters, digits or underscores), in the grammar of a propertyConstraints rule and held to the same limits, counted apart from propertyConstraints (16 rules of 32 nodes each, reading 4 distinct totals). When the owner deletes a document, consensus checks every rule, in name order, against the stored document (its properties, its $ownerId, the system times and heights the type requires and its $revision, as stored, which the rule's plain paths read: $old. is refused) and refuses the delete at the first rule it breaks (DocumentDeleteConstraintViolatedError, 40147), paid. A countOf or sumOf reads the total as it will be once the document is gone, so a rule over the type's own documents no longer counts it, and a filter may match by the document's own id: { \"noVotes\": { \"equal\": [{ \"countOf\": [\"vote\", { \"pollId\": \"$id\" }] }, 0] } } lets a poll be deleted only while no vote points at it. Only the owner's delete is judged: the contract's moderators and a ttl delete as before. Only on a document type whose owner may delete its documents (canBeDeleted true, not \"onlyWhenConsumed\") and that is not indexOnly, and a refersTo with consume may not target the type, since a consume deletes without the rules. Fixed when the document type is created: adding, removing or changing a rule is an incompatible schema change on update. Available from protocol version 14.", "type": "object", "propertyNames": { "pattern": "^[a-zA-Z0-9_]{1,64}$" diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/common/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/common/mod.rs index 989256d637e..8e55fbfce5e 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/common/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/common/mod.rs @@ -34,7 +34,7 @@ use crate::data_contract::document_type::property::{ KeyIdReference, KeyReferenceIdentityProperty, PropertyReference, ReferenceHolder, }; use crate::data_contract::document_type::property_constraints::{ - parse_property_constraint_condition, PropertyConstraint, SystemProperty, STORED_DOCUMENT_PREFIX, + parse_property_constraint_condition, PropertyConstraint, SystemProperty, }; use crate::data_contract::document_type::property_names::moderator_abilities::{ delete_settled, CHANGE_FIELDS, DELETE, DELETE_KEEPS_FIELDS, DELETE_KEEPS_RECORD, @@ -3531,10 +3531,10 @@ fn summable_off_count_index_error( /// Parses a condition a replace is judged by, the `when` of an `immutable` /// entry or a type's `retractedWhen`. It takes the grammar of a /// `propertyConstraints` rule, and what it reads is checked as a rule's reads -/// are ([`super::validate_property_constraint_reads`]), on every parse. Beyond -/// a rule, it may read the stored document through `$old.`, as a replace -/// judges it on the document it writes, and may read no `countOf` or `sumOf`: -/// it reads the document alone, so a replace judges it without reading state. +/// are ([`super::validate_property_constraint_reads`]), on every parse: the +/// stored document through `$old.` included, as a replace judges it on the +/// document it writes. Unlike a rule, it may read no `countOf` or `sumOf`: it +/// reads the document alone, so a replace judges it without reading state. /// Under full validation it stays within the node limit of a rule and lists no /// condition twice. Every message reads `document type "{name}" {keyword} /// {subject} ...`. @@ -3559,12 +3559,9 @@ fn parse_replace_condition( "document type \"{name}\" {keyword} {message}" )) }; - let property_kind = |path: &str| { - super::property_equality_kind( - &document_type.flattened_properties, - path.strip_prefix(STORED_DOCUMENT_PREFIX).unwrap_or(path), - ) - }; + // The parse reads a path through `$old.` as the path after it + let property_kind = + |path: &str| super::property_equality_kind(&document_type.flattened_properties, path); let condition = parse_property_constraint_condition(when, name, &property_kind).map_err(|message| { consensus_or_protocol_data_contract_error(condition_error(format!( diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs index 5b5deeb8bff..1c02c54ce13 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs @@ -5,14 +5,16 @@ use crate::data_contract::document_type::accessors::{ use crate::data_contract::document_type::class_methods::apply_required_since::apply_required_since; use crate::data_contract::document_type::class_methods::consensus_or_protocol_data_contract_error; use crate::data_contract::document_type::class_methods::parse_typed_array::parse_typed_array; +use crate::data_contract::document_type::methods::DocumentTypeBasicMethods; use crate::data_contract::document_type::property::reference_where::{ WHERE_CONST, WHERE_IN, WHERE_NOT_EQUAL, }; use crate::data_contract::document_type::property_constraints::{ - parse_delete_constraints, parse_property_constraints, referenced_path, referenced_read, - whole_integer, AffixPosition, AggregateBinding, AggregateKind, AggregateRead, ElementKind, - EqualityKind, PropertyConstraint, PropertyRead, SystemChange, SystemProperty, - REFERENCED_DOCUMENT_PREFIX, STORED_DOCUMENT_PREFIX, + either_version_path, parse_delete_constraints, parse_property_constraints, referenced_path, + referenced_read, stored_version_path, whole_integer, AffixPosition, AggregateBinding, + AggregateKind, AggregateRead, ElementKind, EqualityKind, PropertyConstraint, PropertyRead, + SystemChange, SystemProperty, SystemRead, SystemValue, REFERENCED_DOCUMENT_PREFIX, + STORED_DOCUMENT_PREFIX, STORED_OWNER_ID, }; use crate::data_contract::document_type::reference_lookup::{ clearable_once_its_document_is_deleted, owner_can_change, @@ -3221,7 +3223,7 @@ fn apply_property_constraints_v0( schema_defs, &format!("rule \"{name}\""), constraint, - false, + true, true, &structure_error, )?; @@ -3294,7 +3296,10 @@ fn validate_rule_limits( /// stored document must meet for its owner to delete it /// ([`parse_delete_constraints`]). A rule reads what a `propertyConstraints` /// rule may read, checked the same way ([`validate_property_constraint_reads`]), -/// and under full validation the keyword is held to the same limits, counted +/// except two refused there: `$old.`, since a delete rule is judged on the +/// stored document itself and its plain paths already read it ([`stored_path`]), +/// and a document a reference points at, which a delete does not check; under +/// full validation the keyword is held to the same limits, counted /// apart from `propertyConstraints`. Which type a `countOf` or `sumOf` totals, /// and by which keys, is checked with the contract's other types /// ([`validate_property_constraint_aggregates`]). @@ -3397,28 +3402,94 @@ pub(super) fn property_equality_kind( } } +/// Checks the reads of the type's `propertyConstraints` and `deleteConstraints` +/// rules that depend on which writes the type has, once its moderator abilities +/// are parsed: a rule reading `$revision`, of either version, needs a type that +/// keeps a revision, and a `propertyConstraints` rule reading the stored +/// version through `$old.` needs a write that replaces one (a +/// `deleteConstraints` rule reads none: [`stored_path`] refused it). Both are +/// the types whose documents are mutable, transferable, sold at a price their +/// owner sets, or keep fields for their moderators (`requires_revision`): on +/// any other a create is the only write a rule judges, and it has no stored +/// version and the first revision. On every parse; the keywords arrive with +/// protocol version 14, so no stored contract breaks it. +pub(super) fn validate_stored_version_reads( + document_type: &DocumentTypeV2, + document_type_name: &str, +) -> Result<(), DataContractError> { + if document_type.requires_revision() { + return Ok(()); + } + let has_no_later_write = "its documents are immutable, not transferable, not sold at a \ + price their owner sets, and keep no fields for their moderators"; + for (keyword, rules) in [ + ( + property_names::PROPERTY_CONSTRAINTS, + &document_type.property_constraints, + ), + ( + property_names::DELETE_CONSTRAINTS, + &document_type.delete_constraints, + ), + ] { + for (name, rule) in rules { + if let Some(read) = rule + .system_reads() + .into_iter() + .find(|read| read.value == SystemValue::Revision) + { + return Err(DataContractError::InvalidContractStructure(format!( + "document type \"{document_type_name}\" {keyword} rule \"{name}\" reads {}, \ + but the type keeps no revision: {has_no_later_write}", + read.name() + ))); + } + } + } + if let Some(name) = document_type + .property_constraints + .iter() + .find_map(|(name, rule)| rule.reads_stored().then_some(name)) + { + return Err(DataContractError::InvalidContractStructure(format!( + "document type \"{document_type_name}\" {} rule \"{name}\" reads the stored \ + version through {STORED_DOCUMENT_PREFIX}, but no write of the type replaces one: \ + {has_no_later_write}, so a create, which has none, is the only write a rule judges", + property_names::PROPERTY_CONSTRAINTS + ))); + } + Ok(()) +} + /// A path a condition reads, as the document type names it: `path` itself, -/// or, with `allow_stored_reads`, what follows the `$old.` a condition judging -/// a replace (an `immutable` entry's, or `retractedWhen`) reads the stored -/// document through ([`STORED_DOCUMENT_PREFIX`]). A rule of -/// `propertyConstraints` judges the document written, so there is no stored -/// document for it to read. +/// or, with `allow_stored_reads`, what follows the `$old.` a rule of +/// `propertyConstraints`, an `immutable` entry's condition or `retractedWhen` +/// reads the stored version through ([`STORED_DOCUMENT_PREFIX`]): a property, +/// since `$old.$ownerId` and the stored system values are no property paths. +/// A rule of `deleteConstraints` is judged on the stored document itself, so +/// its plain paths read it and `$old.` is refused there. fn stored_path<'a>( path: &'a str, subject: &str, allow_stored_reads: bool, ) -> Result<&'a str, String> { - match path.strip_prefix(STORED_DOCUMENT_PREFIX) { - Some(stored) if allow_stored_reads => Ok(stored), - Some(_) => Err(format!( - "{subject} reads \"{path}\", but only a condition judging a replace (an \ - `immutable` entry's, or `retractedWhen`) reads the stored document through \ - `{STORED_DOCUMENT_PREFIX}`" - )), + match stored_version_path(path) { + Some(_) if !allow_stored_reads => Err(stored_read_in_delete_rule(subject, path)), + Some(stored) => Ok(stored), None => Ok(path), } } +/// The refusal of a `deleteConstraints` rule, `subject`, reading `path` through +/// `$old.`: such a rule is judged on the stored document itself. +fn stored_read_in_delete_rule(subject: &str, path: &str) -> String { + format!( + "{subject} reads \"{path}\", but a deleteConstraints rule is judged on the stored \ + document itself, so its plain paths read it: name it without \ + `{STORED_DOCUMENT_PREFIX}`" + ) +} + /// Why `document_type` has no property at `lookup` a rule `subject` can read /// as `read`, the message naming it `path`; `None` when it has one: of the kind /// the read needs, neither transient nor inside a transient object. Shared by @@ -3702,8 +3773,13 @@ pub(super) fn property_read_error( /// object, a system time or height the type records, and a constant or a /// default its string property's `enum` admits. `subject` names the condition /// in the errors (`rule "fee"`), and `structure_error` wraps them. With -/// `allow_stored_reads` (the condition of an `immutable` entry) a path may read -/// the stored document through `$old.` and is judged as the path after it. +/// `allow_stored_reads` (a rule of `propertyConstraints`, the condition of an +/// `immutable` entry or `retractedWhen`) a path may read the stored version +/// through `$old.` and is judged as the path after it, and a stored system +/// value as the value after it; without it (a rule of `deleteConstraints`) +/// neither is admitted. Whether the type keeps the revision `$revision` reads, +/// and has a write replacing a stored version at all, is checked once its +/// moderator abilities are parsed ([`validate_stored_version_reads`]). /// With `allow_referenced_reads` (a `propertyConstraints` rule) a /// `referenced` operand may read a document one of the type's references /// points at: what it reads is checked against the referenced type once it is @@ -3737,29 +3813,50 @@ pub(super) fn validate_property_constraint_reads( return Err(structure_error(error)); } } - // An indexOnly type's delete carries its row's values but not its owner, so - // a rule reading the owner could not be judged there + // `$old.$ownerId` is no property path, so its refusal in a delete rule is here + if !allow_stored_reads && constraint.reads_stored() { + let path = constraint + .system_reads() + .into_iter() + .find(|read| read.stored) + .map_or_else(|| STORED_OWNER_ID.to_string(), SystemRead::name); + return Err(structure_error(stored_read_in_delete_rule(subject, &path))); + } + // An indexOnly type keeps no stored version: its documents are never + // replaced. Checked first, so that a rule reading `$old.$ownerId` is told so + if document_type.index_only && constraint.reads_stored() { + return Err(structure_error(format!( + "{subject} reads the stored version through {STORED_DOCUMENT_PREFIX}, which an \ + indexOnly type does not keep: its documents are never replaced" + ))); + } + // Its delete carries its row's values but not its owner, so a rule reading + // the owner could not be judged there if document_type.index_only && constraint.reads_owner() { return Err(structure_error(format!( "{subject} compares $ownerId, which a delete of an indexOnly document \ does not carry" ))); } - for system_property in constraint.system_reads() { - let system_name = system_property.name(); - // Nor its times and heights + for read in constraint.system_reads() { + let system_name = read.name(); + // Nor its times, heights and revision if document_type.index_only { return Err(structure_error(format!( "{subject} reads {system_name}, which a delete of an indexOnly \ document does not carry" ))); } - // A stored document holds only the times and heights its type requires - if !document_type.required_fields.contains(system_name) { - return Err(structure_error(format!( - "{subject} reads {system_name}, which the document type does not \ - record: list it in required" - ))); + // A stored document holds only the times and heights its type requires; + // whether it keeps a revision is known once its moderator abilities are + if let SystemValue::Property(property) = read.value { + if !document_type.required_fields.contains(property.name()) { + let listed = if read.stored { property.name() } else { "it" }; + return Err(structure_error(format!( + "{subject} reads {system_name}, which the document type does not \ + record: list {listed} in required" + ))); + } } } // Which type an aggregate totals, and by which of its keys, is checked once @@ -3837,14 +3934,16 @@ pub(super) fn validate_property_constraint_reads( /// read what a transfer or a purchase changes, nor, on a type whose prices /// can be set, what a price update changes: those writes check no reference, /// so they could not judge it; -/// * it depends on no field the type keeps for its moderators to change, -/// neither reading it nor totalling the type's own documents by it (a key -/// of a `countOf` or `sumOf`), which their change judges without the -/// references either; -/// * on a type whose moderators' deletions keep records, it reads no total -/// over the type's own documents: a moderator's restore brings a document -/// back into those totals and checks no reference, so it could not judge -/// the rule. +/// * on a type keeping fields for its moderators to change, it reads nothing +/// their change can break, which their change is judged against +/// ([`PropertyConstraint::reads_changed_fields`]): such a field, of either +/// version, `$revision`, or any total, which may have moved since the +/// document was last written; their change checks no reference either; +/// * on a type whose moderators' deletions keep records, it reads no total: a +/// moderator's restore is judged against every rule reading one +/// ([`PropertyConstraint::reads_change`]), the totals having perhaps moved +/// while the document was gone, and checks no reference, so it could not +/// judge the rule. /// /// What it reads of the referenced type is checked once that type is in hand /// ([`referenced_reads_error`]). Registration only, like the rest of a rule's @@ -3883,52 +3982,67 @@ pub(super) fn validate_referencing_rules( if can_change_owner && constraint.reads_change(SystemChange::Transfer) { return Err(error( "reads a document a reference points at and what a transfer or a purchase \ - changes ($ownerId, $transferredAt and its heights, or a total depending on the \ - owner): a transfer or a purchase checks no reference, so it could not judge \ - the rule" + changes ($ownerId, $transferredAt and its heights or $revision, of either \ + version, or a total depending on the owner): a transfer or a purchase checks \ + no reference, so it could not judge the rule" .to_string(), )); } if can_change_price && constraint.reads_change(SystemChange::PriceUpdate) { return Err(error( "reads a document a reference points at and what a price update changes \ - ($updatedAt and its heights): a price update checks no reference, so it could \ - not judge the rule" + ($updatedAt and its heights or $revision, of either version): a price update \ + checks no reference, so it could not judge the rule" .to_string(), )); } - // A moderator's change of a key of a total over the type's own - // documents moves the total, the rule reading the key itself or not - let moderated_field = constraint - .own_property_reads() - .into_iter() - .map(|(path, _)| path) - .chain( - constraint - .aggregate_reads() - .into_iter() - .flat_map(AggregateRead::own_type_keys), - ) - .find(|path| is_path_listed(document_type.moderator_changeable_fields(), path)); - if let Some(field) = moderated_field { + // What a moderator's change of the fields the type keeps for them is + // judged against, the reason named as precisely as the rule allows: a + // field it reads, of either version, or keys a total over the type's + // own documents by, `$revision`, or a total + let moderator_fields = document_type.moderator_changeable_fields(); + if !moderator_fields.is_empty() && constraint.reads_changed_fields(moderator_fields) { + let moderated_field = constraint + .own_property_reads() + .into_iter() + .map(|(path, _)| either_version_path(path)) + .chain( + constraint + .aggregate_reads() + .into_iter() + .flat_map(AggregateRead::own_type_keys), + ) + .find(|path| is_path_listed(moderator_fields, path)); + let reads_revision = constraint + .system_reads() + .into_iter() + .any(|read| read.value == SystemValue::Revision); + let reason = match (moderated_field, reads_revision) { + (Some(field), _) => format!( + "depends on \"{field}\" (a property it reads, of either version, or a key \ + of a total over the type's own documents), which the type keeps for its \ + moderators to change" + ), + (None, true) => "$revision, which a moderator's change of the fields the type \ + keeps for them moves" + .to_string(), + (None, false) => "a total, which a moderator's change of the fields the type \ + keeps for them is judged against, since it may have moved \ + since the document was last written" + .to_string(), + }; return Err(error(format!( - "reads a document a reference points at and depends on \"{field}\" (a property \ - it reads, or a key of a total over the type's own documents), which the type \ - keeps for its moderators to change: their change checks no reference, so it \ - could not judge the rule" + "reads a document a reference points at and {reason}: their change checks no \ + reference, so it could not judge the rule" ))); } - if let Some(total) = constraint - .aggregate_reads() - .into_iter() - .find(|read| can_restore && read.of_own_type) - { - return Err(error(format!( - "reads a document a reference points at and a {} of the type's own documents, \ - which a moderator's restore brings a document back into: a restore checks no \ - reference, so it could not judge the rule", - total.wire_name() - ))); + if can_restore && constraint.reads_change(SystemChange::Restore) { + return Err(error( + "reads a document a reference points at and a total, which a moderator's \ + restore is judged against, since it may have moved while the document was \ + gone: a restore checks no reference, so it could not judge the rule" + .to_string(), + )); } } Ok(()) diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/byte_array_reads_tests.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/byte_array_reads_tests.rs index df237a33752..3a1ac481b91 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/byte_array_reads_tests.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/byte_array_reads_tests.rs @@ -209,27 +209,30 @@ fn should_hold_a_byte_read_to_a_stored_byte_array_within_its_max_items() { } } - // Only a condition judging a replace reads the stored document; the - // meta-schema refuses the path when registering, so the parser alone is - // left to refuse it in a stored contract - expect_structure_error( - parse_rule( - json!({ "equal": [{ "byteAt": ["$old.payload", 0] }, 0] }), - false, - ), - "rule \"rule\" reads \"$old.payload\", but only a condition judging a replace", - ); - expect_structure_error( - parse_payment( - json!({ - "deleteConstraints": { - "rule": { "startsWith": ["$old.payload", { "const": "ff" }] } - } - }), - false, - ), - "rule \"rule\" reads \"$old.payload\", but only a condition judging a replace", - ); + // A rule reads the stored version's bytes through `$old.`, but a delete rule, + // judged on the stored document itself, reads them by the plain path + for full_validation in [true, false] { + assert!( + parse_rule( + json!({ "equal": [{ "byteAt": ["$old.payload", 0] }, 0] }), + full_validation, + ) + .is_ok(), + "full_validation: {full_validation}" + ); + expect_structure_error( + parse_payment( + json!({ + "deleteConstraints": { + "rule": { "startsWith": ["$old.payload", { "const": "ff" }] } + } + }), + full_validation, + ), + "rule \"rule\" reads \"$old.payload\", but a deleteConstraints rule is judged on the \ + stored document itself", + ); + } // A transient byte array is never stored, so no rule may read one for rule in [ diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/delete_constraints_tests.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/delete_constraints_tests.rs index efa6fd17dc1..7db2b018092 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/delete_constraints_tests.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/delete_constraints_tests.rs @@ -265,16 +265,30 @@ fn should_refuse_delete_rules_reading_what_no_rule_may() { "document type \"poll\" deleteConstraints rule \"rule\" reads \"question\", which has \ type string, not integer or boolean", ); - // The meta-schema refuses the path first; a stored contract meets the parser - poll_delete_rule(json!({ "present": "$old.status" })) - .expect_err("the meta-schema refuses a path through $old."); - expect_structure_error( - poll_contract( - json!({ "deleteConstraints": { "rule": { "present": "$old.status" } } }), - false, + // A delete rule is judged on the stored document itself, which its plain paths + // read, so none reads through `$old.`: a property, the owner or a system value + for (rule, path) in [ + (json!({ "present": "$old.status" }), "$old.status"), + ( + json!({ "notEqual": ["$old.$ownerId", "$ownerId"] }), + "$old.$ownerId", ), - "only a condition judging a replace", - ); + ( + json!({ "lessThan": ["$old.$createdAt", "endsAt"] }), + "$old.$createdAt", + ), + ] { + for full_validation in [true, false] { + expect_structure_error( + poll_contract(json!({ "deleteConstraints": { "rule": rule } }), full_validation), + &format!( + "document type \"poll\" deleteConstraints rule \"rule\" reads \"{path}\", but \ + a deleteConstraints rule is judged on the stored document itself, so its plain \ + paths read it: name it without `$old.`" + ), + ); + } + } } /// A total a delete rule reads is checked with the contract's other types, as a diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/immutable_tests.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/immutable_tests.rs index ce2be3e9b31..71f47d4a962 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/immutable_tests.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/immutable_tests.rs @@ -534,29 +534,27 @@ fn should_refuse_a_condition_reading_a_total_on_both_modes() { } } -/// `$old.` is the stored document, which only a replace has: a -/// `propertyConstraints` rule judges a create too. +/// A `propertyConstraints` rule reads the stored document through `$old.` as +/// a condition does, on both paths: a create, which has none, reads it absent. #[test] -fn should_refuse_a_stored_read_in_a_property_constraints_rule() { +fn should_read_the_stored_document_in_a_property_constraints_rule() { let schema = post_schema_with( "propertyConstraints", platform_value!({ "keepsMeta": { "present": "$old.meta" } }), ); - // The meta-schema's path pattern refuses it first under full validation; - // the parse refuses it on the stored path as well - assert!(parse_with(schema.clone(), PlatformVersion::latest(), true).is_err()); - expect_structure_error( - parse_with(schema, PlatformVersion::latest(), false), - "rule \"keepsMeta\" reads \"$old.meta\", but only a condition judging a replace (an \ - `immutable` entry's, or `retractedWhen`) reads the stored document", - ); + for full_validation in [false, true] { + let document_type = parse_with(schema.clone(), PlatformVersion::latest(), full_validation) + .unwrap_or_else(|error| { + panic!("the rule should parse (full_validation: {full_validation}): {error}") + }); + assert!(document_type.property_constraints()["keepsMeta"].reads_stored()); + } } /// A `countPresent` in a condition judging a replace counts the stored /// document's properties through `$old.` and the written one's without it: /// `meta` frozen once both hold a `meta.tag` holds only when each does. -/// The same paths in a `propertyConstraints` rule, which judges creates too, -/// are refused. +/// The same paths parse in a `propertyConstraints` rule. #[test] fn should_count_stored_and_written_properties_in_a_condition() { let when = platform_value!({ @@ -607,13 +605,12 @@ fn should_count_stored_and_written_properties_in_a_condition() { "propertyConstraints", platform_value!({ "keepsTag": { "equal": [{ "countPresent": ["$old.meta.tag", "meta.tag"] }, 2] } }), ); - // The meta-schema's path pattern refuses it first under full validation; - // the parse refuses it on the stored path as well - assert!(parse_with(schema.clone(), PlatformVersion::latest(), true).is_err()); - expect_structure_error( - parse_with(schema, PlatformVersion::latest(), false), - "rule \"keepsTag\" reads \"$old.meta.tag\", but only a condition judging a replace", - ); + for full_validation in [false, true] { + assert!( + parse_with(schema.clone(), PlatformVersion::latest(), full_validation).is_ok(), + "full_validation: {full_validation}" + ); + } } /// The lints are validation-only, as for the entries without a condition. diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/mod.rs index 42c46c23e79..5d28526e74d 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/mod.rs @@ -69,7 +69,7 @@ use super::schema_at_path; use super::{ apply_property_constraints, parse_doctype_reference, validate_encrypted_for_declarations, validate_generated_from_declarations, validate_list_element_sources, - validate_reference_lookup_sources, validate_referencing_rules, + validate_reference_lookup_sources, validate_referencing_rules, validate_stored_version_reads, }; mod ranked_prefix_overlap; @@ -645,6 +645,10 @@ fn parse_generation_3( full_validation, platform_version, )?; + // After `apply_property_constraints` and `apply_moderator_abilities`: whether the type + // keeps the revision `$revision` reads, and has a write replacing the stored version a rule + // reads through `$old.`, depends on the fields it keeps for its moderators too. + validate_stored_version_reads(&v2, name).map_err(consensus_or_protocol_data_contract_error)?; // After `apply_index_only`: `ttl` is refused on an indexOnly type. common::apply_documents_ttl( &mut v2, @@ -2022,6 +2026,8 @@ mod retracted_when_tests; #[cfg(all(test, feature = "validation"))] mod shared_stage_error_tests; #[cfg(all(test, feature = "validation"))] +mod stored_version_reads_tests; +#[cfg(all(test, feature = "validation"))] mod string_find_by_key_tests; #[cfg(all(test, feature = "validation"))] mod transient_tests; diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/property_constraint_aggregates_tests.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/property_constraint_aggregates_tests.rs index be2e1df4e9f..fca68587853 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/property_constraint_aggregates_tests.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/property_constraint_aggregates_tests.rs @@ -864,7 +864,9 @@ fn should_refuse_to_skip_a_rule_whose_total_consensus_did_not_read() { ])); let owner = Identifier::from([3; 32]); let read = listing.property_constraints()["atMostTenPerOwner"].aggregate_reads()[0].clone(); - let with = |aggregates| DocumentSystemValues { + // Consensus reads the totals; a client, giving none, judges as a client + let with = |aggregates: Option<_>| DocumentSystemValues { + consensus: aggregates.is_some(), aggregates, ..DocumentSystemValues::owned_by(owner) }; @@ -974,6 +976,7 @@ fn should_refuse_to_skip_a_rule_a_system_change_judges_without_its_total() { let judge = |change: SystemChange, aggregates: Option>| { let system = DocumentSystemValues { updated_at: Some(500), + consensus: aggregates.is_some(), aggregates: aggregates.map(|aggregates| aggregates.into_iter().collect()), ..DocumentSystemValues::owned_by(Identifier::from([3; 32])) }; diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/property_constraints_tests.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/property_constraints_tests.rs index 5e966f0a69c..c26d845b6fb 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/property_constraints_tests.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/property_constraints_tests.rs @@ -16,7 +16,7 @@ use crate::data_contract::accessors::v0::DataContractV0Getters; use crate::data_contract::conversion::value::v0::DataContractValueConversionMethodsV0; use crate::data_contract::document_type::accessors::DocumentTypeV2Getters; use crate::data_contract::document_type::property_constraints::{ - DocumentSystemValues, ElementKind, PropertyConstraint, PropertyRead, SystemProperty, + DocumentSystemValues, ElementKind, PropertyConstraint, PropertyRead, SystemProperty, SystemRead, }; use crate::data_contract::methods::validate_update::DataContractUpdateValidationMethodsV0; use crate::data_contract::DataContract; @@ -871,9 +871,10 @@ fn should_compare_identifier_properties_that_declare_refers_to() { } } -/// `$ownerId` and the system times and heights are no properties of the type: -/// every document has an owner, and a type that records a time holds it on -/// every document. A presence test of one is refused on both paths (the +/// `$ownerId`, the system times and heights and `$revision` are no properties +/// of the type: every document has an owner, a type that records a time holds +/// it on every document, and a type keeping a revision keeps it on every one. +/// A presence test of one, of either version, is refused on both paths (the /// meta-schema admits them as paths, for comparisons and operands), and one of /// any other system property the meta-schema refuses when registering. #[test] @@ -898,7 +899,20 @@ fn should_refuse_a_presence_test_of_a_system_property() { "tests the presence of \"$createdAt\", which is not a property of the document type", ); } - let rules = json!({ "rule": { "present": "$revision" } }); + for path in [ + "$revision", + "$old.$revision", + "$old.$createdAt", + "$old.$ownerId", + ] { + for full_validation in [true, false] { + expect_structure_error( + parse_order(json!({ "rule": { "present": path } }), full_validation), + &format!("tests the presence of \"{path}\", which is not a property"), + ); + } + } + let rules = json!({ "rule": { "present": "$id" } }); let registered = parse_order(rules.clone(), true); assert!( registered.as_ref().is_err_and(is_json_schema_error), @@ -906,7 +920,7 @@ fn should_refuse_a_presence_test_of_a_system_property() { ); expect_structure_error( parse_order(rules, false), - "tests the presence of \"$revision\", which is not a property of the document type", + "tests the presence of \"$id\", which is not a property of the document type", ); } @@ -1080,8 +1094,8 @@ fn should_refuse_a_rule_reading_anything_but_an_integer_property() { "reads $createdAt, which the document type does not record: list it in required", ), ( - "$revision", - "reads \"$revision\", which is not an integer or boolean property", + "$id", + "reads \"$id\", which is not an integer or boolean property", ), ] { for full_validation in [true, false] { @@ -1091,11 +1105,11 @@ fn should_refuse_a_rule_reading_anything_but_an_integer_property() { ); // The meta-schema refuses a `$` in a path when registering, but for // `$ownerId`, which only a comparison of identifiers may read, and the - // system times and heights an operand may read + // system times, heights and revision an operand may read if full_validation && operand.starts_with('$') && operand != "$ownerId" - && SystemProperty::from_name(operand).is_none() + && SystemRead::from_name(operand).is_none() { assert!( result.as_ref().is_err_and(is_json_schema_error), @@ -1804,7 +1818,7 @@ fn should_read_the_system_times_and_heights_the_type_records() { let constraints = document_type.property_constraints(); assert_eq!( constraints["depositAfterCreation"].system_reads(), - [SystemProperty::CreatedAt] + [SystemRead::from(SystemProperty::CreatedAt)] ); assert_eq!( constraints["depositAfterCreation"].property_paths(), @@ -1812,11 +1826,13 @@ fn should_read_the_system_times_and_heights_the_type_records() { ); assert_eq!( constraints["pricedAboveHeight"].system_reads(), - [SystemProperty::UpdatedAtBlockHeight] + [SystemRead::from(SystemProperty::UpdatedAtBlockHeight)] ); assert_eq!( constraints["transferredOnCore"].system_reads(), - [SystemProperty::TransferredAtCoreBlockHeight] + [SystemRead::from( + SystemProperty::TransferredAtCoreBlockHeight + )] ); // Not recording `$updatedAtBlockHeight`, the type may not read it diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/referenced_rule_tests.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/referenced_rule_tests.rs index c572c4538f8..e7b550a3c9c 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/referenced_rule_tests.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/referenced_rule_tests.rs @@ -273,7 +273,7 @@ fn judge( vote.validate_referencing_property_constraints( &data, BTreeMap::from([("pollId".to_string(), poll_values)]), - system, + system.clone(), PlatformVersion::latest(), ) .expect("the rules evaluate") @@ -610,7 +610,7 @@ fn should_compare_two_referenced_fields_by_value() { vote.validate_referencing_property_constraints( &data, BTreeMap::from([("pollId".to_string(), poll), ("postId".to_string(), post)]), - &system, + system.clone(), PlatformVersion::latest(), ) .expect("the rules evaluate") @@ -681,7 +681,7 @@ fn should_read_through_a_reference_inside_an_object() { "meta.pollId".to_string(), platform_value!({ "endsAt": ends_at }), )]), - &system, + system.clone(), PlatformVersion::latest(), ) .expect("the rules evaluate"); @@ -813,9 +813,11 @@ fn parse_entry(rules: Value) -> Result, ProtocolE } /// A moderator's change judges no rule reading a referenced document, so such -/// a rule may not depend on a field moderators change: neither read it nor -/// total the type's own documents by it. Approving an entry moves the count of -/// the poll's approved entries, though the rule does not read `status` itself. +/// a rule may not read what their change is judged against: a field moderators +/// change, read or keying a total of the type's own documents (approving an +/// entry moves the count of the poll's approved entries, though the rule does +/// not read `status` itself), or any total, which may have moved since the +/// document was last written. #[test] fn should_refuse_a_referenced_read_beside_a_total_moderators_move() { let approved_cap = platform_value!({ @@ -838,17 +840,85 @@ fn should_refuse_a_referenced_read_beside_a_total_moderators_move() { expect_structure_error(parse_entry(rules), "depends on \"status\""); } - // A moderator's approval leaves the count of all the poll's entries as it - // was, so a rule reading it stands + // The count of all the poll's entries, which no approval moves, may have + // moved by other writes since the entry was last written, and a moderator's + // change is judged against every rule reading a total + expect_structure_error( + parse_entry(platform_value!({ + "cap": { + "lessThanOrEqual": [ + { "countOf": ["entry", { "pollId": "pollId" }] }, + { "referenced": ["pollId", "endsAt"] } + ] + } + })), + "and a total, which a moderator's change", + ); + + // Reading neither a moderator's field, `$revision` nor a total, a rule stands parse_entry(platform_value!({ + "cap": { "lessThan": ["$createdAt", { "referenced": ["pollId", "endsAt"] }] } + })) + .expect("a moderator's change can break nothing the rule reads"); +} + +/// A moderator's change writes the fields it changes and the revision, so a +/// rule reading a referenced document reads neither the stored version of such +/// a field, through `$old.`, nor `$revision`, of either version. The stored +/// version of what the change leaves alone stands. +#[test] +fn should_refuse_a_referenced_read_beside_a_stored_field_or_revision_moderators_move() { + let stored_status = platform_value!({ "cap": { - "lessThanOrEqual": [ - { "countOf": ["entry", { "pollId": "pollId" }] }, - { "referenced": ["pollId", "endsAt"] } + "anyOf": [ + { "absent": "$old.status" }, + { "lessThan": ["$createdAt", { "referenced": ["pollId", "endsAt"] }] } ] } + }); + expect_structure_error(parse_entry(stored_status), "depends on \"status\""); + for revision in ["$revision", "$old.$revision"] { + let rules = platform_value!({ + "cap": { + "anyOf": [ + { "lessThanOrEqual": [revision, 3] }, + { "lessThan": ["$createdAt", { "referenced": ["pollId", "endsAt"] }] } + ] + } + }); + expect_structure_error( + parse_entry(rules), + "and $revision, which a moderator's change", + ); + } + + parse_entry(platform_value!({ + "cap": { + "lessThan": ["$old.$createdAt", { "referenced": ["pollId", "endsAt"] }] + } })) - .expect("no total the rule reads moves with a moderator's change"); + .expect("a moderator's change leaves the stored creation as it was"); +} + +/// A vote on a poll, the poll's votes counted. +fn counted_vote() -> Value { + platform_value!({ + "type": "object", + "documentsMutable": false, + "canBeDeleted": false, + "properties": { + "pollId": identifier(0, Some(poll_reference())), + }, + "required": ["pollId"], + "indices": [ + { + "name": "byPoll", + "properties": [{ "pollId": "asc" }], + "countable": "countable" + } + ], + "additionalProperties": false, + }) } /// An entry on a poll moderators take down, its removal keeping a record a @@ -876,9 +946,11 @@ fn removable_entry(keeps_record: bool, rules: Value) -> Value { }) } -/// A moderator's restore judges no rule reading a referenced document, yet -/// brings the document back into every total over its type: a rule capping -/// the poll's entries by a value of the poll would let a restore past the cap. +/// A moderator's restore judges no rule reading a referenced document, yet is +/// judged against every rule reading a total, which may have moved while the +/// document was gone: a rule capping the poll's entries by a value of the poll +/// would let a restore past the cap, and so would one capping the votes the +/// entry received meanwhile. #[test] fn should_refuse_a_referenced_read_beside_a_total_a_restore_moves() { let cap = platform_value!({ @@ -897,7 +969,27 @@ fn should_refuse_a_referenced_read_beside_a_total_a_restore_moves() { ], true, ), - "a moderator's restore brings a document back into", + "and a total, which a moderator's restore is judged against", + ); + // A total over another type: the poll's votes, cast while the entry was gone + let votes_cap = platform_value!({ + "cap": { + "lessThanOrEqual": [ + { "countOf": ["vote", { "pollId": "pollId" }] }, + { "referenced": ["pollId", "endsAt"] } + ] + } + }); + expect_structure_error( + parse_types( + vec![ + ("poll", poll()), + ("vote", counted_vote()), + ("entry", removable_entry(true, votes_cap)), + ], + true, + ), + "and a total, which a moderator's restore is judged against", ); // Deletions keeping no record are final, so no restore moves the count diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/stored_version_reads_tests.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/stored_version_reads_tests.rs new file mode 100644 index 00000000000..0ddc377fa0f --- /dev/null +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/stored_version_reads_tests.rs @@ -0,0 +1,374 @@ +//! `propertyConstraints` rules reading the stored version of a document +//! through `$old.`, and `$revision`, under generation 3 (protocol version 14): +//! what registration admits on which document types, and how the parsed type +//! judges a write with the stored version, without it, and for a moderator's +//! change of fields. + +use super::immutable_tests::{expect_structure_error, parse_dispatched}; +use super::*; +use crate::data_contract::document_type::accessors::DocumentTypeV2Getters; +use crate::data_contract::document_type::methods::DocumentTypeV0Methods; +use crate::data_contract::document_type::property_constraints::{ + DocumentSystemValues, StoredDocument, StoredSystemValues, StoredVersion, +}; +use platform_value::platform_value; + +/// A type, parsed as `post`: two integers, a string `status`, an identifier `buyerId`, +/// and what `doctype` adds or replaces at the type's top level (its +/// mutability, `required`, `propertyConstraints` and the rest). +fn listing_schema(doctype: Value) -> Value { + let mut schema = platform_value!({ + "type": "object", + "documentsMutable": true, + "properties": { + "price": { "type": "integer", "minimum": 0, "position": 0 }, + "fee": { "type": "integer", "minimum": 0, "position": 1 }, + "status": { + "type": "string", + "enum": ["open", "closed"], + "maxLength": 10, + "position": 2 + }, + "buyerId": { + "type": "array", + "byteArray": true, + "minItems": 32, + "maxItems": 32, + "contentMediaType": "application/x.dash.dpp.identifier", + "position": 3 + } + }, + "required": ["price", "fee", "$updatedAt"], + "additionalProperties": false + }); + let Value::Map(entries) = doctype else { + panic!("the doctype keys are an object"); + }; + for (key, value) in entries { + schema + .set_value(key.as_text().expect("a text key"), value) + .expect("the doctype key applies"); + } + schema +} + +fn parse_listing(doctype: Value, full_validation: bool) -> Result { + parse_dispatched( + listing_schema(doctype), + PlatformVersion::latest(), + full_validation, + ) +} + +/// A mutable type registers rules reading every kind of stored value and +/// `$revision`, on both paths. +#[test] +fn should_register_stored_reads_and_the_revision_on_a_type_with_a_later_write() { + let rules = platform_value!({ + "priceNeverRises": { + "lessThanOrEqual": ["price", { "ifAbsent": ["$old.price", 1000000] }] + }, + "closedStaysClosed": { + "ifThen": [ + { "equal": ["$old.status", { "const": "closed" }] }, + { "equal": ["status", { "const": "closed" }] } + ] + }, + "buyerKept": { + "anyOf": [{ "absent": "$old.buyerId" }, { "equal": ["buyerId", "$old.buyerId"] }] + }, + "editsAnHourApart": { + "greaterThanOrEqual": [{ "subtract": ["$updatedAt", "$old.$updatedAt"] }, 3600000] + }, + "atMostFiveEdits": { "lessThanOrEqual": ["$revision", 6] }, + "sameOwner": { "equal": ["$ownerId", "$old.$ownerId"] }, + "revisionStepsByOne": { "equal": ["$revision", { "add": ["$old.$revision", 1] }] } + }); + for full_validation in [true, false] { + let document_type = parse_listing( + platform_value!({ "propertyConstraints": rules.clone() }), + full_validation, + ) + .unwrap_or_else(|error| { + panic!("the rules register (full_validation: {full_validation}): {error}") + }); + let parsed = document_type.property_constraints(); + assert_eq!(parsed.len(), 7); + assert!(!parsed["atMostFiveEdits"].reads_stored()); + assert!(parsed + .iter() + .filter(|(name, _)| name.as_str() != "atMostFiveEdits") + .all(|(_, rule)| rule.reads_stored())); + } + + // A transferable type keeps a revision too, however immutable its documents + let transferable = parse_listing( + platform_value!({ + "documentsMutable": false, + "transferable": 1, + "propertyConstraints": { + "resoldAfterADay": { + "ifThen": [ + { "notEqual": ["$ownerId", "$old.$ownerId"] }, + { "greaterThanOrEqual": ["$revision", 2] } + ] + } + } + }), + true, + ); + assert!(transferable.is_ok(), "{transferable:?}"); +} + +/// On a type no write of which replaces a stored version, the stored version +/// is always absent and the revision always the first: a rule reading either +/// is refused, in `deleteConstraints` too for `$revision`. +#[test] +fn should_refuse_stored_reads_and_the_revision_on_a_type_without_a_later_write() { + let no_later_write = "its documents are immutable, not transferable, not sold at a price \ + their owner sets, and keep no fields for their moderators"; + for (doctype, needle) in [ + ( + platform_value!({ + "documentsMutable": false, + "propertyConstraints": { "rule": { "greaterThan": ["price", "$old.price"] } } + }), + format!( + "document type \"post\" propertyConstraints rule \"rule\" reads the stored \ + version through $old., but no write of the type replaces one: {no_later_write}" + ), + ), + ( + platform_value!({ + "documentsMutable": false, + "propertyConstraints": { "rule": { "notEqual": ["$ownerId", "$old.$ownerId"] } } + }), + "propertyConstraints rule \"rule\" reads the stored version through $old., but no \ + write of the type replaces one" + .to_string(), + ), + ( + platform_value!({ + "documentsMutable": false, + "propertyConstraints": { "rule": { "lessThan": ["$revision", 3] } } + }), + format!( + "document type \"post\" propertyConstraints rule \"rule\" reads $revision, but \ + the type keeps no revision: {no_later_write}" + ), + ), + ( + platform_value!({ + "documentsMutable": false, + "canBeDeleted": true, + "deleteConstraints": { "rule": { "lessThan": ["$revision", 3] } } + }), + "document type \"post\" deleteConstraints rule \"rule\" reads $revision, but the \ + type keeps no revision" + .to_string(), + ), + ] { + for full_validation in [true, false] { + expect_structure_error(parse_listing(doctype.clone(), full_validation), &needle); + } + } +} + +/// A stored time or height is one the type records, as a written one is. +#[test] +fn should_refuse_a_stored_time_the_type_does_not_record() { + for full_validation in [true, false] { + expect_structure_error( + parse_listing( + platform_value!({ + "propertyConstraints": { + "rule": { "greaterThan": ["$createdAt", "$old.$transferredAt"] } + } + }), + full_validation, + ), + "rule \"rule\" reads $createdAt, which the document type does not record: list it in \ + required", + ); + expect_structure_error( + parse_listing( + platform_value!({ + "required": ["price", "fee", "$createdAt"], + "propertyConstraints": { + "rule": { "greaterThan": ["$createdAt", "$old.$transferredAt"] } + } + }), + full_validation, + ), + "rule \"rule\" reads $old.$transferredAt, which the document type does not record: \ + list $transferredAt in required", + ); + } +} + +/// An indexOnly type keeps no stored documents to replace. +#[test] +fn should_refuse_a_stored_read_on_an_index_only_type() { + // A stored property, and the stored owner, which is told it is the stored + // version rather than the owner the rule never names + let stored_reads = [ + platform_value!({ "anyOf": [{ "absent": "$old.hashtag" }, { "present": "hashtag" }] }), + platform_value!({ + "anyOf": [ + { "notEqual": ["$old.$ownerId", { "const": "CXH2kZCATjvDTnQAPVg28EgPg9WySUvwvnR5ZkmNqY5i" }] }, + { "present": "hashtag" } + ] + }), + ]; + for rule in stored_reads { + let schema = platform_value!({ + "type": "object", + "indexOnly": true, + "documentsMutable": false, + "properties": { + "hashtag": { "type": "string", "maxLength": 63, "position": 0 } + }, + "required": ["hashtag"], + "indices": [ + { "name": "byHashtag", "properties": [{ "hashtag": "asc" }] } + ], + "additionalProperties": false, + "propertyConstraints": { "rule": rule } + }); + for full_validation in [true, false] { + expect_structure_error( + parse_dispatched(schema.clone(), PlatformVersion::latest(), full_validation), + "rule \"rule\" reads the stored version through $old., which an indexOnly type \ + does not keep: its documents are never replaced", + ); + } + } +} + +fn listing(price: u64, fee: u64) -> Value { + platform_value!({ "price": price, "fee": fee }) +} + +fn stored_listing(price: u64, fee: u64, revision: u64) -> StoredVersion { + StoredVersion::Present(Box::new(StoredDocument { + properties: Some( + [ + ("price".to_string(), Value::U64(price)), + ("fee".to_string(), Value::U64(fee)), + ] + .into(), + ), + system: StoredSystemValues { + revision: Some(revision), + updated_at: Some(0), + ..Default::default() + }, + })) +} + +/// The parsed type judges a rule reading `$old.` with the stored version the +/// write gives, skips it for a client not giving one, and reports consensus +/// not giving one as an error. A moderator's change of fields is judged only +/// against the rules reading what it changes. +#[test] +fn should_judge_stored_reads_through_the_parsed_type() { + let platform_version = PlatformVersion::latest(); + let document_type = parse_listing( + platform_value!({ + "propertyConstraints": { + "priceStrictlyDrops": { "lessThan": ["price", "$old.price"] }, + "feeCapped": { "lessThanOrEqual": ["fee", 100] }, + "atMostFiveEdits": { "lessThanOrEqual": ["$revision", 6] } + } + }), + true, + ) + .expect("the rules register"); + let judged = |data: &Value, system: &DocumentSystemValues| { + document_type + .validate_property_constraints(data, system, platform_version) + .expect("the rules are judged") + }; + let broken_rule = |data: &Value, system: &DocumentSystemValues| { + judged(data, system) + .errors + .first() + .map(|error| error.to_string()) + }; + + // A replace: the price must drop + let replace = |stored: StoredVersion, revision: u64| DocumentSystemValues { + revision: Some(revision), + stored: Some(stored), + ..Default::default() + }; + assert!(judged(&listing(90, 10), &replace(stored_listing(100, 10, 1), 2)).is_valid()); + assert!( + broken_rule(&listing(100, 10), &replace(stored_listing(100, 10, 1), 2)) + .is_some_and(|message| message.contains("priceStrictlyDrops")), + "an unchanged price breaks the rule" + ); + // A create: an absent stored price reads 0, which no price is below + let create = DocumentSystemValues { + revision: Some(1), + stored: Some(StoredVersion::Absent), + ..Default::default() + }; + assert!(broken_rule(&listing(90, 10), &create) + .is_some_and(|message| message.contains("priceStrictlyDrops"))); + + // A client not given the stored version does not judge the rule + let client = DocumentSystemValues { + revision: Some(2), + ..Default::default() + }; + assert!(judged(&listing(100, 10), &client).is_valid()); + + // Consensus not giving it is a fault in the code building the write + let consensus = DocumentSystemValues { + revision: Some(2), + aggregates: Some(Default::default()), + consensus: true, + ..Default::default() + }; + assert!(matches!( + document_type.validate_property_constraints(&listing(100, 10), &consensus, platform_version), + Err(ProtocolError::CorruptedCodeExecution(message)) + if message.contains("rule priceStrictlyDrops of document type post reads the stored version through $old., which consensus did not give") + )); + // Nor is giving the stored version without the properties a rule reads + let without_properties = DocumentSystemValues { + stored: Some(StoredVersion::without_properties(StoredSystemValues { + revision: Some(1), + ..Default::default() + })), + ..consensus.clone() + }; + assert!(matches!( + document_type.validate_property_constraints(&listing(100, 10), &without_properties, platform_version), + Err(ProtocolError::CorruptedCodeExecution(message)) + if message.contains("rule priceStrictlyDrops of document type post reads a property of the stored version through $old., which consensus did not give") + )); + + // A moderator's change of `fee`: the price rule, which reads only what the + // change leaves alone, is not judged, the fee rule and `$revision` are + let moderator_change = |fields: &[&str], revision: u64| DocumentSystemValues { + revision: Some(revision), + stored: Some(stored_listing(100, 10, revision - 1)), + changed_fields: Some(fields.iter().map(|field| field.to_string()).collect()), + ..Default::default() + }; + assert!(judged(&listing(100, 20), &moderator_change(&["fee"], 2)).is_valid()); + assert!( + broken_rule(&listing(100, 200), &moderator_change(&["fee"], 2)) + .is_some_and(|message| message.contains("feeCapped")) + ); + assert!( + broken_rule(&listing(100, 20), &moderator_change(&["fee"], 7)) + .is_some_and(|message| message.contains("atMostFiveEdits")) + ); + assert!( + broken_rule(&listing(100, 20), &moderator_change(&["price"], 2)) + .is_some_and(|message| message.contains("priceStrictlyDrops")) + ); +} diff --git a/packages/rs-dpp/src/data_contract/document_type/methods/mod.rs b/packages/rs-dpp/src/data_contract/document_type/methods/mod.rs index 5213a896147..66f9ea9084b 100644 --- a/packages/rs-dpp/src/data_contract/document_type/methods/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/methods/mod.rs @@ -1129,10 +1129,14 @@ pub trait DocumentTypeV0Methods: DocumentTypeV0Getters + DocumentTypeV0MethodsVe /// `DocumentPropertyConstraintViolatedError` (10422), naming the rule and why (the rule /// does not hold, or evaluating it overflowed, divided by zero, raised to a negative /// power or read a value that is not an integer). A property the document - /// leaves out counts as 0, or as its `ifAbsent` value; `$ownerId` and the system - /// times and heights read `system`, the values of the document version being written - /// (an owner the caller does not know equals no identifier, and a rule reading a time - /// or height it does not know is not judged). Reads the properties and `system` alone: + /// leaves out counts as 0, or as its `ifAbsent` value; `$ownerId`, the system + /// times and heights and `$revision` read `system`, the values of the document version + /// being written (an owner the caller does not know equals no identifier, and a rule + /// reading a time, a height or a revision it does not know is not judged), and a read + /// through `$old.` the stored version `system` gives (a rule reading one it does not give + /// is not judged). A write changing only some fields of a stored document + /// (`system.changed_fields`, a moderator's change) is judged only against the rules + /// reading what it changes. Reads the properties and `system` alone: /// `DataContract::validate_document_properties` runs it after the schema validation, /// so document create and replace, and every client validating a document, apply it. /// @@ -1172,9 +1176,10 @@ pub trait DocumentTypeV0Methods: DocumentTypeV0Getters + DocumentTypeV0MethodsVe /// [`Self::validate_property_constraints`] would. `data` holds the document's /// properties and `referenced`, by reference property, the values those rules read of /// the documents the references point at, which consensus reads with the references it - /// checks; `system` holds the rest, the totals included. Every other rule of the type - /// was judged before the references were checked, and is not judged again. A type with - /// no such rule costs nothing, the data not even copied. + /// checks; `system` holds the rest, the totals and the stored version included, taken + /// by value so that marking the referenced values given copies none of it. Every other + /// rule of the type was judged before the references were checked, and is not judged + /// again. A type with no such rule costs nothing, the data not even copied. /// /// Versioned with [`Self::validate_property_constraints`]: `None` before protocol /// version 14, where no parsed document type carries a rule. @@ -1182,7 +1187,7 @@ pub trait DocumentTypeV0Methods: DocumentTypeV0Getters + DocumentTypeV0MethodsVe &self, data: &BTreeMap, referenced: BTreeMap, - system: &DocumentSystemValues, + system: DocumentSystemValues, platform_version: &PlatformVersion, ) -> Result where @@ -1208,12 +1213,15 @@ pub trait DocumentTypeV0Methods: DocumentTypeV0Getters + DocumentTypeV0MethodsVe /// Judges a stored document's properties, `data`, against the rules of the document /// type's `propertyConstraints` that `change` can break, with `system` the document's /// system values after it, in name order. A transfer or a purchase gives the document a - /// new owner and a new transfer time and heights, and a price update a new update time - /// and heights; neither changes a property, so the rules reading what it changes are - /// the only ones it can break ([`PropertyConstraint::reads_change`]), and the first - /// broken fails with `DocumentPropertyConstraintViolatedError` (10422) as it would on a - /// write. The document type's other rules held when the document was written and still - /// do. A type with no such rule costs nothing, and its data is not copied. + /// new owner, a new transfer time and heights and the next revision, a price update a + /// new update time and heights and the next revision, and a moderator's restore brings + /// it back as it was while the totals around it may have moved; none changes a property, + /// so the rules reading what it changes, of the document or, through `$old.`, of the + /// stored version `system` gives, are the only ones it can break + /// ([`PropertyConstraint::reads_change`]), and the first broken fails with + /// `DocumentPropertyConstraintViolatedError` (10422) as it would on a write. The document + /// type's other rules held when the document was last written and still do. A type with + /// no such rule costs nothing, and its data is not copied. /// /// Versioned with [`Self::validate_property_constraints`]: `None` before protocol /// version 14, where no parsed document type carries a rule. diff --git a/packages/rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs b/packages/rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs index 23a87112987..164b3a874a7 100644 --- a/packages/rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs +++ b/packages/rs-dpp/src/data_contract/document_type/methods/versioned_methods.rs @@ -5,7 +5,8 @@ use crate::data_contract::document_type::accessors::{ }; use crate::data_contract::document_type::methods::DocumentTypeBasicMethods; use crate::data_contract::document_type::property_constraints::{ - data_with_referenced_documents, DocumentSystemValues, PropertyConstraint, SystemChange, + data_with_referenced_documents, data_with_stored_properties, DocumentSystemValues, + PropertyConstraint, SystemChange, }; use crate::data_contract::document_type::v0::DocumentTypeV0; use crate::data_contract::document_type::v1::DocumentTypeV1; @@ -37,6 +38,7 @@ use platform_value::btreemap_extensions::{ }; use platform_value::{Identifier, ReplacementType, Value}; use platform_version::version::PlatformVersion; +use std::borrow::Cow; use std::collections::BTreeMap; pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBasicMethods { @@ -940,8 +942,11 @@ pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBa /// `validate_property_constraints` version 0: every rule of the document type's /// `propertyConstraints` is evaluated against `data` in name order, and the first one - /// broken is reported. A type without rules costs nothing. A rule reading a total - /// consensus did not read ([`PropertyConstraint::unread_aggregate`]) is an error. + /// broken is reported ([`Self::first_broken_property_constraint`]); for a write changing + /// only some fields of a stored document (`system.changed_fields`), only the rules + /// reading what it changes. A rule reading the stored version's properties is judged + /// with them under `$old` ([`DocumentSystemValues::judged_data`]). A type without rules + /// costs nothing. fn validate_property_constraints_v0( &self, data: &Value, @@ -952,37 +957,38 @@ pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBa { // A rule reading a referenced document waits for the values, and no // total of it is read before - for (name, constraint) in self + let rules = self .property_constraints() .iter() - .filter(|(_, constraint)| constraint.is_judged_with(system)) - { - self.expect_every_aggregate_read(name, constraint, system)?; - if let Some(violation) = constraint.violation(data, system) { - return Ok(SimpleConsensusValidationResult::new_with_error( - DocumentPropertyConstraintViolatedError::new( - self.name().clone(), - name.clone(), - violation, - ) - .into(), - )); - } - } - Ok(SimpleConsensusValidationResult::default()) + .filter(|(_, constraint)| { + constraint.is_judged_with(system) + && system + .changed_fields + .as_ref() + .is_none_or(|fields| constraint.reads_changed_fields(fields)) + }); + self.first_broken_property_constraint( + rules, + data, + system + .stored_properties_given() + .then_some(&|| system.judged_data(data)), + system, + ) } /// `validate_referencing_property_constraints` version 0: every rule of the document /// type's `propertyConstraints` reading a document one of its references points at is /// evaluated, in name order, against `data` with `referenced` under `$referenced` - /// ([`data_with_referenced_documents`]), and the first one broken is reported. The data - /// is copied only when such a rule exists. The type's other rules are not judged again. - /// A rule reading a total consensus did not read is an error. + /// ([`data_with_referenced_documents`]), and the stored version's properties under `$old` + /// for a rule reading them ([`DocumentSystemValues::judged_data`]), and the first one + /// broken is reported ([`Self::first_broken_property_constraint`]). The data is copied + /// only when such a rule exists. The type's other rules are not judged again. fn validate_referencing_property_constraints_v0( &self, data: &BTreeMap, referenced: BTreeMap, - system: &DocumentSystemValues, + system: DocumentSystemValues, ) -> Result where Self: DocumentTypeV2Getters, @@ -999,22 +1005,16 @@ pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBa // The values the rules read are now in the data let system = DocumentSystemValues { referenced_documents: true, - ..system.clone() + ..system }; - for (name, constraint) in rules { - self.expect_every_aggregate_read(name, constraint, &system)?; - if let Some(violation) = constraint.violation(&data, &system) { - return Ok(SimpleConsensusValidationResult::new_with_error( - DocumentPropertyConstraintViolatedError::new( - self.name().clone(), - name.clone(), - violation, - ) - .into(), - )); - } - } - Ok(SimpleConsensusValidationResult::default()) + self.first_broken_property_constraint( + rules, + &data, + system + .stored_properties_given() + .then_some(&|| system.judged_data(&data)), + &system, + ) } /// `validate_delete_constraints` version 0: every rule of the document type's @@ -1031,7 +1031,7 @@ pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBa Self: DocumentTypeV2Getters, { for (name, constraint) in self.delete_constraints() { - self.expect_every_aggregate_read(name, constraint, system)?; + self.expect_every_read(name, constraint, system)?; if let Some(violation) = constraint.violation(data, system) { return Ok(SimpleConsensusValidationResult::new_with_error( DocumentDeleteConstraintViolatedError::new( @@ -1047,30 +1047,42 @@ pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBa Ok(SimpleConsensusValidationResult::default()) } - /// An error when `system` holds consensus's totals and lacks one the rule `name` - /// reads, which would otherwise leave the rule unjudged. - fn expect_every_aggregate_read( + /// An error when consensus judges the write and `system` lacks a total the rule `name` + /// reads, or what it reads of the stored version, which would otherwise leave the + /// rule unjudged. + fn expect_every_read( &self, name: &str, constraint: &PropertyConstraint, system: &DocumentSystemValues, ) -> Result<(), ProtocolError> { - match constraint.unread_aggregate(system) { - None => Ok(()), - Some(read) => Err(ProtocolError::CorruptedCodeExecution(format!( + if let Some(read) = constraint.unread_aggregate(system) { + return Err(ProtocolError::CorruptedCodeExecution(format!( "rule {name} of document type {} reads a {} of {} that consensus did not read: \ {read:?}", self.name(), read.wire_name(), read.document_type - ))), + ))); + } + if constraint.unread_stored_version(system) { + return Err(ProtocolError::CorruptedCodeExecution(format!( + "rule {name} of document type {} reads the stored version through $old., which \ + consensus did not give", + self.name() + ))); } + Ok(()) } /// `validate_property_constraints_for_system_change` version 0: every rule of the /// document type's `propertyConstraints` that `change` can break is evaluated against - /// `data` with `system`, in name order, and the first one broken is reported. The data - /// is copied into a map value only when such a rule exists. + /// `data` with `system`, in name order, and the first one broken is reported + /// ([`Self::first_broken_property_constraint`]). The change writes no property, so the + /// stored version's properties, which a rule reads through `$old.`, are `data` itself: + /// those `system.stored` holds are not read. The data is copied into a map value only + /// when such a rule exists, and again under `$old` only when such a rule reads a stored + /// property. fn validate_property_constraints_for_system_change_v0( &self, data: &BTreeMap, @@ -1091,9 +1103,46 @@ pub trait DocumentTypeV0MethodsVersioned: DocumentTypeV0Getters + DocumentTypeBa return Ok(SimpleConsensusValidationResult::default()); } let data = Value::from(data.clone()); - for (name, constraint) in changed_rules { - self.expect_every_aggregate_read(name, constraint, system)?; - if let Some(violation) = constraint.violation(&data, system) { + self.first_broken_property_constraint( + changed_rules, + &data, + Some(&|| Cow::Owned(data_with_stored_properties(data.clone(), data.clone()))), + system, + ) + } + + /// The first of `rules` broken, in the order given, judged against `data` with + /// `system`, and a rule reading a property of the stored version against + /// `with_stored_properties`, the data with them under `$old`, built once, for the + /// first such rule. A rule reading a total or a stored version consensus did not + /// give is an error ([`Self::expect_every_read`]), and so is one reading a stored + /// property without `with_stored_properties`, which a client's check skips. + fn first_broken_property_constraint<'r, 'd>( + &self, + rules: impl IntoIterator, + data: &'d Value, + with_stored_properties: Option<&dyn Fn() -> Cow<'d, Value>>, + system: &DocumentSystemValues, + ) -> Result { + let mut with_stored: Option> = None; + for (name, constraint) in rules { + self.expect_every_read(name, constraint, system)?; + let judged = if constraint.reads_stored_properties() { + let Some(with_stored_properties) = with_stored_properties else { + if system.consensus { + return Err(ProtocolError::CorruptedCodeExecution(format!( + "rule {name} of document type {} reads a property of the stored \ + version through $old., which consensus did not give", + self.name() + ))); + } + continue; + }; + &**with_stored.get_or_insert_with(with_stored_properties) + } else { + data + }; + if let Some(violation) = constraint.violation(judged, system) { return Ok(SimpleConsensusValidationResult::new_with_error( DocumentPropertyConstraintViolatedError::new( self.name().clone(), diff --git a/packages/rs-dpp/src/data_contract/document_type/property_constraints/mod.rs b/packages/rs-dpp/src/data_contract/document_type/property_constraints/mod.rs index d5d65ed8200..636a705ce87 100644 --- a/packages/rs-dpp/src/data_contract/document_type/property_constraints/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/property_constraints/mod.rs @@ -66,7 +66,15 @@ //! transfer are integer operands too (`"$createdAt"`, `"$updatedAtBlockHeight"`, //! [`SystemProperty`]), on a document type that records them, so a price update //! and a transfer or a purchase, which change some of them, are judged against -//! the rules reading those. +//! the rules reading those; and so is `$revision` ([`SystemValue::Revision`]), +//! on a document type that keeps a revision. +//! Under `$old.` ([`STORED_DOCUMENT_PREFIX`]) a path, `$ownerId`, a time, a +//! height or `$revision` reads the stored version of the document a write +//! replaces instead ([`DocumentSystemValues::stored`]), so a rule compares a +//! replace with what it replaces: +//! `{ "greaterThanOrEqual": ["counter", { "ifAbsent": ["$old.counter", 0] }] }` +//! keeps a counter from going down. A create has none, so every such read is +//! absent there ([`StoredVersion::Absent`]). //! `countOf` and `sumOf` are integer operands read from state, [`AggregateRead`]: //! how many documents of a type of the same contract match, or the total of an //! integer property over them, from the count and sum trees their indexes keep @@ -103,12 +111,12 @@ use crate::data_contract::document_type::property_names; use crate::data_contract::errors::DataContractError; use crate::document::property_names::{ CREATED_AT, CREATED_AT_BLOCK_HEIGHT, CREATED_AT_CORE_BLOCK_HEIGHT, CREATOR_ID, - ID as DOCUMENT_ID, OWNER_ID, TRANSFERRED_AT, TRANSFERRED_AT_BLOCK_HEIGHT, + ID as DOCUMENT_ID, OWNER_ID, REVISION, TRANSFERRED_AT, TRANSFERRED_AT_BLOCK_HEIGHT, TRANSFERRED_AT_CORE_BLOCK_HEIGHT, UPDATED_AT, UPDATED_AT_BLOCK_HEIGHT, UPDATED_AT_CORE_BLOCK_HEIGHT, }; -use crate::document::{Document, DocumentV0Getters}; -use crate::prelude::{BlockHeight, CoreBlockHeight, TimestampMillis}; +use crate::document::{Document, DocumentV0Getters, INITIAL_REVISION}; +use crate::prelude::{BlockHeight, CoreBlockHeight, Revision, TimestampMillis}; use bincode::{Decode, DecodeUntrusted, Encode}; use platform_value::btreemap_extensions::BTreeValueMapPathHelper; use platform_value::string_encoding::Encoding; @@ -171,18 +179,43 @@ const OPERAND_KEYS: &str = "add, subtract, multiply, divide, modulo, power, min, /// no change to a limit can make a stored contract unparseable. pub const MAX_PROPERTY_CONSTRAINT_PARSE_DEPTH: usize = 64; -/// The prefix through which the condition of an `immutable` entry reads the -/// stored document instead of the one a replace writes: `$old.status` is the -/// stored `status`. Only such a condition may read it, and only a schema -/// property through it; the condition is judged against the written document's -/// properties with the stored ones under [`STORED_DOCUMENT_KEY`]. +/// The prefix through which a rule, or the condition of an `immutable` entry or +/// of `retractedWhen`, reads the stored version of the document a write +/// replaces instead of the version it writes: `$old.status` is the stored +/// `status`, `$old.$ownerId` ([`STORED_OWNER_ID`]) the stored owner, and +/// `$old.$updatedAt` or `$old.$revision` ([`SystemRead`]) a stored system +/// value. A rule is judged against the written document's properties with the +/// stored ones under [`STORED_DOCUMENT_KEY`] ([`DocumentSystemValues::judged_data`]), +/// and the stored owner, times, heights and revision in +/// [`DocumentSystemValues::stored`]. A create has no stored version, so there +/// every such read is absent ([`StoredVersion::Absent`]). A `deleteConstraints` +/// rule, judged on the stored document itself, reads none. pub const STORED_DOCUMENT_PREFIX: &str = "$old."; -/// The key the stored document's properties sit under in the data the -/// condition of an `immutable` entry is judged against, so that a path through -/// [`STORED_DOCUMENT_PREFIX`] reads them. +/// The key the stored document's properties sit under in the data a rule or a +/// condition is judged against, so that a path through +/// [`STORED_DOCUMENT_PREFIX`] reads them. No property can take the name: a +/// property name is letters, digits and underscores. pub const STORED_DOCUMENT_KEY: &str = "$old"; +/// `$old.$ownerId`: the owner of the stored version of the document, which a +/// comparison of identifiers reads as it reads `$ownerId`. It differs from +/// `$ownerId` only on a transfer or a purchase, where it is the previous owner. +pub const STORED_OWNER_ID: &str = "$old.$ownerId"; + +/// What `path` reads of the stored version, the part after +/// [`STORED_DOCUMENT_PREFIX`], when it reads the stored version: `price` for +/// `$old.price`, `$ownerId` for `$old.$ownerId`. Every reading of a path's +/// version goes through it. +pub fn stored_version_path(path: &str) -> Option<&str> { + path.strip_prefix(STORED_DOCUMENT_PREFIX) +} + +/// `path` as a path of the document, whichever version it reads: what it reads +/// of the stored version ([`stored_version_path`]), or `path` itself. +pub fn either_version_path(path: &str) -> &str { + stored_version_path(path).unwrap_or(path) +} /// The operand key of a value of the document a reference of the type points /// at: `{ "referenced": ["pollId", "endsAt"] }` is the `endsAt` of the /// document the property `pollId` refers to. It stands wherever a property @@ -304,12 +337,41 @@ pub fn data_with_referenced_documents( let at = format!("{reference}{REFERENCED_FIELD_SEPARATOR}"); documents.set_value_at_full_path(at.trim_end_matches('.'), values)?; } - let mut entries: Vec<(Value, Value)> = data - .iter() - .map(|(property, value)| (Value::Text(property.clone()), value.clone())) + Ok(with_reserved_entry( + data.iter() + .map(|(property, value)| (Value::Text(property.clone()), value.clone())), + REFERENCED_DOCUMENT_KEY, + documents, + )) +} + +/// The data a rule reading the stored version's properties is judged against: +/// the document's properties, `data` (a map), with `stored`, the stored +/// version's, under [`STORED_DOCUMENT_KEY`], where a path through +/// [`STORED_DOCUMENT_PREFIX`] reads them. +pub fn data_with_stored_properties(data: Value, stored: Value) -> Value { + let entries = match data { + Value::Map(entries) => entries, + _ => Vec::new(), + }; + with_reserved_entry(entries.into_iter(), STORED_DOCUMENT_KEY, stored) +} + +/// The map of `entries` with `value` under the reserved key `key`, which an +/// entry of `entries` holding the key itself does not keep: no document +/// property takes a name starting with `$`, and the schema validation refuses +/// one a type does not declare, so such an entry is never read as what the key +/// holds. +fn with_reserved_entry( + entries: impl Iterator, + key: &str, + value: Value, +) -> Value { + let mut entries: Vec<(Value, Value)> = entries + .filter(|(entry_key, _)| entry_key.as_text() != Some(key)) .collect(); - entries.push((Value::Text(REFERENCED_DOCUMENT_KEY.to_string()), documents)); - Ok(Value::Map(entries)) + entries.push((Value::Text(key.to_string()), value)); + Value::Map(entries) } /// Whether `text` spells `identifier` in base58, as a constant compared with an @@ -488,6 +550,7 @@ impl SystemProperty { | SystemProperty::UpdatedAtBlockHeight | SystemProperty::UpdatedAtCoreBlockHeight ), + SystemChange::Restore => false, } } } @@ -499,24 +562,120 @@ impl Serialize for SystemProperty { } } -/// A write that changes a stored document's system values and none of its -/// properties, so only the rules reading what it changes can break. +/// A write that changes none of a stored document's properties, so only the +/// rules reading what it does change can break: the others held when the +/// document was last written and still do, since a type's rules never change +/// once it is registered. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SystemChange { - /// A transfer or a purchase: a new owner, and the time and heights of the - /// last transfer. + /// A transfer or a purchase: a new owner, the time and heights of the last + /// transfer, and the next revision. Transfer, - /// A price update: the time and heights of the last update. + /// A price update: the time and heights of the last update, and the next + /// revision. PriceUpdate, + /// A moderator's restore of a document its moderators deleted: the document + /// comes back as it was, owner, times, heights and revision included, but + /// the `countOf` and `sumOf` totals around it may have moved while it was + /// gone. + Restore, +} + +/// A system value of a document a rule may read as an integer operand: one of +/// the times and heights [`SystemProperty`] names, or `$revision`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum SystemValue { + /// A time or a height, on a document type that records it. + Property(SystemProperty), + /// `$revision`: 1 for a created document, and one more for each later write + /// of it (a replace, a transfer, a purchase, a price update, a moderator's + /// change of its fields), on a document type that keeps a revision: one + /// whose documents are mutable, transferable, sold at a price their owner + /// sets, or keep fields for their moderators. + Revision, +} + +impl SystemValue { + /// Its name, as a rule writes it. + pub fn name(self) -> &'static str { + match self { + SystemValue::Property(property) => property.name(), + SystemValue::Revision => REVISION, + } + } + + /// The system value a rule names `name`, if any. + pub fn from_name(name: &str) -> Option { + if name == REVISION { + return Some(SystemValue::Revision); + } + SystemProperty::from_name(name).map(SystemValue::Property) + } + + /// Whether `change` sets it. + pub fn changed_by(self, change: SystemChange) -> bool { + match self { + SystemValue::Property(property) => property.changed_by(change), + SystemValue::Revision => { + matches!(change, SystemChange::Transfer | SystemChange::PriceUpdate) + } + } + } +} + +/// A system value a rule reads: of the document version the write stores +/// (`"$updatedAt"`), or, with `stored`, of the stored version it replaces, +/// through [`STORED_DOCUMENT_PREFIX`] (`"$old.$updatedAt"`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct SystemRead { + pub value: SystemValue, + pub stored: bool, +} + +impl From for SystemRead { + /// `property` of the document version written. + fn from(property: SystemProperty) -> Self { + SystemRead { + value: SystemValue::Property(property), + stored: false, + } + } +} + +impl SystemRead { + /// Its name, as a rule writes it: `$updatedAt`, `$old.$revision`. + pub fn name(self) -> String { + if self.stored { + format!("{STORED_DOCUMENT_PREFIX}{}", self.value.name()) + } else { + self.value.name().to_string() + } + } + + /// The system value a rule names `name`, of either version, if any. + pub fn from_name(name: &str) -> Option { + match stored_version_path(name) { + Some(stored) => SystemValue::from_name(stored).map(|value| SystemRead { + value, + stored: true, + }), + None => SystemValue::from_name(name).map(|value| SystemRead { + value, + stored: false, + }), + } + } } /// The system values of the document version a rule is judged against: its -/// owner, which `$ownerId` reads, and the times and heights [`SystemProperty`] -/// names. Consensus passes every one the document type records; a client -/// passes those it knows. `$ownerId` equals no identifier when the owner is -/// unknown, and [`PropertyConstraint::violation`] does not judge a rule reading -/// a time, a height or an aggregate it is not given. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +/// owner, which `$ownerId` reads, the times and heights [`SystemProperty`] +/// names and its revision, and what a rule reads beyond the document: the +/// totals of other documents and the stored version the write replaces. +/// Consensus passes every one the document type records; a client passes +/// those it knows. `$ownerId` equals no identifier when the owner is unknown, +/// and [`PropertyConstraint::violation`] does not judge a rule reading a time, +/// a height, a revision, an aggregate or a stored version it is not given. +#[derive(Debug, Clone, Default, PartialEq)] pub struct DocumentSystemValues { pub owner_id: Option, pub created_at: Option, @@ -528,24 +687,170 @@ pub struct DocumentSystemValues { pub created_at_core_block_height: Option, pub updated_at_core_block_height: Option, pub transferred_at_core_block_height: Option, + /// `$revision` ([`SystemValue::Revision`]). + pub revision: Option, /// The `countOf` and `sumOf` totals the rules read, each as it will be once /// the write is done ([`AggregateRead`]). `None` for a client, which reads - /// no state: a rule reading a total is then not judged. `Some` for - /// consensus, which reads every total the rules judging the write read, so - /// that one missing there is a fault in the code building the write, which - /// `validate_property_constraints` reports as an error rather than skip the - /// rule ([`PropertyConstraint::unread_aggregate`]). + /// no state: a rule reading a total is then not judged. Consensus reads + /// every total the rules judging the write read ([`Self::consensus`]). pub aggregates: Option>, + /// Whether consensus judges the write, and so gives every total and the + /// stored version the rules judging it read: one missing is then a fault in + /// the code building the write, which the judging reports as an error + /// rather than skip the rule ([`PropertyConstraint::unread_aggregate`], + /// [`PropertyConstraint::unread_stored_version`]). `false` for a client, + /// which skips a rule reading what it does not know. + pub consensus: bool, /// Whether the data the rules are judged against holds, under /// [`REFERENCED_DOCUMENT_KEY`], the values they read of the documents the /// type's references point at. Consensus sets it once the references are /// checked, and judges then the rules reading one; anywhere else a rule /// reading one is not judged ([`PropertyConstraint::violation`]). pub referenced_documents: bool, + /// The version of the document the write replaces, which a rule reads + /// through [`STORED_DOCUMENT_PREFIX`]: [`StoredVersion::Absent`] for a + /// create, the stored version for any other write. `None` for a client not + /// given it: a rule reading it is then not judged. Consensus gives it + /// whenever a rule judging the write reads it ([`Self::consensus`]). + pub stored: Option, + /// `Some` for a write that changes only these top-level properties of a + /// stored document and nothing else a rule reads but `$revision`: a + /// moderator's change of a document's fields. It is judged only against + /// the rules reading one of them, directly or through `$old.`, `$revision` + /// or a total ([`PropertyConstraint::reads_changed_fields`]); every other + /// rule reads what the document held when it was last written, and gave + /// its verdict then. `None` for every other write, judged against every + /// rule. + pub changed_fields: Option>, +} + +/// The stored version of the document a write replaces, as a rule reads it +/// through [`STORED_DOCUMENT_PREFIX`]. +#[derive(Debug, Clone, PartialEq)] +pub enum StoredVersion { + /// There is none: the write is a create. A path through `$old.` reads as a + /// property the document leaves out does (0, or its `ifAbsent` value; + /// absent to `present`; equal to no string or identifier), `$old.$ownerId` + /// equals no identifier, and a stored time, height or revision reads 0. + Absent, + /// The version the write replaces. + Present(Box), +} + +impl StoredVersion { + /// `document`, the version a write replaces. + pub fn of_document(document: &Document) -> Self { + StoredVersion::Present(Box::new(StoredDocument::of_document(document))) + } + + /// The version a write replaces, given by its owner, times, heights and + /// revision, `system`, alone ([`StoredDocument::without_properties`]). + pub fn without_properties(system: StoredSystemValues) -> Self { + StoredVersion::Present(Box::new(StoredDocument::without_properties(system))) + } +} + +/// A stored version of a document, as a rule reads it through `$old.`. +#[derive(Debug, Clone, PartialEq)] +pub struct StoredDocument { + /// Its properties, which `$old.` reads. `None` when not given: no + /// rule judged with it reads one, which the judging checks + /// ([`DocumentSystemValues::stored_properties_given`]), or the write changes + /// no property (a transfer, a purchase, a price update, a restore), so that + /// they are the properties written, which + /// `validate_property_constraints_for_system_change` reads instead. + pub properties: Option>, + /// Its owner, times, heights and revision, which `$old.$ownerId`, + /// `$old.$createdAt` and the rest read. + pub system: StoredSystemValues, +} + +impl StoredDocument { + /// What `document` holds. + pub fn of_document(document: &Document) -> Self { + StoredDocument { + properties: Some(document.properties().clone()), + system: StoredSystemValues::of_document(document), + } + } + + /// What `document` holds, its properties taken rather than copied. + pub fn of_owned_document(document: Document) -> Self { + let system = StoredSystemValues::of_document(&document); + StoredDocument { + properties: Some(document.properties_consumed()), + system, + } + } + + /// Its owner, times, heights and revision, `system`, without its + /// properties ([`Self::properties`]). + pub fn without_properties(system: StoredSystemValues) -> Self { + StoredDocument { + properties: None, + system, + } + } +} + +/// The owner, times, heights and revision of a stored version of a document, +/// as `$old.$ownerId`, `$old.$createdAt` and the rest read them. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct StoredSystemValues { + pub owner_id: Identifier, + pub created_at: Option, + pub updated_at: Option, + pub transferred_at: Option, + pub created_at_block_height: Option, + pub updated_at_block_height: Option, + pub transferred_at_block_height: Option, + pub created_at_core_block_height: Option, + pub updated_at_core_block_height: Option, + pub transferred_at_core_block_height: Option, + pub revision: Option, +} + +impl StoredSystemValues { + /// What `document` holds. + pub fn of_document(document: &Document) -> Self { + StoredSystemValues { + owner_id: document.owner_id(), + created_at: document.created_at(), + updated_at: document.updated_at(), + transferred_at: document.transferred_at(), + created_at_block_height: document.created_at_block_height(), + updated_at_block_height: document.updated_at_block_height(), + transferred_at_block_height: document.transferred_at_block_height(), + created_at_core_block_height: document.created_at_core_block_height(), + updated_at_core_block_height: document.updated_at_core_block_height(), + transferred_at_core_block_height: document.transferred_at_core_block_height(), + revision: document.revision(), + } + } + + /// The system values of a written version holding them: the same owner, + /// times, heights and revision, and nothing a rule reads beyond the + /// document. + pub fn as_written(&self) -> DocumentSystemValues { + DocumentSystemValues { + owner_id: Some(self.owner_id), + created_at: self.created_at, + updated_at: self.updated_at, + transferred_at: self.transferred_at, + created_at_block_height: self.created_at_block_height, + updated_at_block_height: self.updated_at_block_height, + transferred_at_block_height: self.transferred_at_block_height, + created_at_core_block_height: self.created_at_core_block_height, + updated_at_core_block_height: self.updated_at_core_block_height, + transferred_at_core_block_height: self.transferred_at_core_block_height, + revision: self.revision, + ..Default::default() + } + } } impl DocumentSystemValues { - /// The owner alone, no time or height. + /// The owner alone, no time, height or revision. pub fn owned_by(owner_id: Identifier) -> Self { DocumentSystemValues { owner_id: Some(owner_id), @@ -555,7 +860,8 @@ impl DocumentSystemValues { /// A document created by `owner_id` in the block `block_info` describes: /// its creation, last update and last transfer all at that block, as a - /// create records every one its type requires. + /// create records every one its type requires, its first revision, which + /// a rule reads only on a type keeping one, and no stored version. pub fn created_in_block(owner_id: Identifier, block_info: &BlockInfo) -> Self { DocumentSystemValues { owner_id: Some(owner_id), @@ -568,26 +874,97 @@ impl DocumentSystemValues { created_at_core_block_height: Some(block_info.core_height), updated_at_core_block_height: Some(block_info.core_height), transferred_at_core_block_height: Some(block_info.core_height), + revision: Some(INITIAL_REVISION), aggregates: None, + consensus: false, + stored: Some(StoredVersion::Absent), + changed_fields: None, referenced_documents: false, } } - /// The values `document` holds. + /// The values `document` holds; no stored version. pub fn of_document(document: &Document) -> Self { DocumentSystemValues { - owner_id: Some(document.owner_id()), - created_at: document.created_at(), - updated_at: document.updated_at(), - transferred_at: document.transferred_at(), - created_at_block_height: document.created_at_block_height(), - updated_at_block_height: document.updated_at_block_height(), - transferred_at_block_height: document.transferred_at_block_height(), - created_at_core_block_height: document.created_at_core_block_height(), - updated_at_core_block_height: document.updated_at_core_block_height(), - transferred_at_core_block_height: document.transferred_at_core_block_height(), - aggregates: None, - referenced_documents: false, + stored: None, + ..StoredSystemValues::of_document(document).as_written() + } + } + + /// The value `read` reads, `None` when not given: one of the stored + /// version is 0 on a create, and not given when the stored version is not. + pub fn read(&self, read: SystemRead) -> Option { + if read.stored { + return match &self.stored { + Some(StoredVersion::Present(stored)) => { + stored.system.as_written().version_value(read.value) + } + Some(StoredVersion::Absent) => Some(0), + None => None, + }; + } + self.version_value(read.value) + } + + /// The value of `value` of this version, `None` when not given. + fn version_value(&self, value: SystemValue) -> Option { + match value { + SystemValue::Property(property) => self.value(property), + SystemValue::Revision => self.revision.map(i128::from), + } + } + + /// Whether the stored version's properties are given whenever the stored + /// version is: `false` only for a stored version given without them + /// ([`StoredDocument::without_properties`]). + pub fn stored_properties_given(&self) -> bool { + !matches!( + &self.stored, + Some(StoredVersion::Present(stored)) if stored.properties.is_none() + ) + } + + /// The owner of the stored version, which `$old.$ownerId` reads: `None` on + /// a create, and when the stored version is not given. + pub fn stored_owner_id(&self) -> Option { + match &self.stored { + Some(StoredVersion::Present(stored)) => Some(stored.system.owner_id), + Some(StoredVersion::Absent) | None => None, + } + } + + /// The data a rule is judged against for a document whose properties are + /// `data` (a map): `data`, with the stored version's properties under + /// [`STORED_DOCUMENT_KEY`] when they are given + /// ([`data_with_stored_properties`]), so that a path through `$old.` reads + /// them, and with nothing there otherwise. A `$old` key `data` carries + /// itself, which no document holds, is dropped either way, so that it is + /// never read as the stored version. `data` itself when there is nothing to + /// add or drop. + pub fn judged_data<'a>(&self, data: &'a Value) -> Cow<'a, Value> { + if let Some(StoredVersion::Present(stored)) = &self.stored { + if let Some(properties) = &stored.properties { + return Cow::Owned(data_with_stored_properties( + data.clone(), + Value::from(properties.clone()), + )); + } + } + match data { + Value::Map(entries) + if entries + .iter() + .any(|(key, _)| key.as_text() == Some(STORED_DOCUMENT_KEY)) => + { + Cow::Owned(Value::Map( + entries + .iter() + .filter(|(key, _)| key.as_text() != Some(STORED_DOCUMENT_KEY)) + .cloned() + .collect(), + )) + } + _ => Cow::Borrowed(data), } } @@ -760,9 +1137,10 @@ pub enum ConstraintExpression { /// array property at the dotted `path`, `{ "byteAt": ["address", 0] }`, or /// 0 when the array does not hold that byte or the document leaves it out. ByteAt { path: String, index: u16 }, - /// A system property, `"$createdAt"` say: its value in the - /// [`DocumentSystemValues`] the rule is judged with. - System(SystemProperty), + /// A system value, `"$createdAt"` or `"$revision"` say, of the document + /// version written or, through `$old.`, of the stored version it replaces: + /// its value in the [`DocumentSystemValues`] the rule is judged with. + System(SystemRead), /// `add`: the sum of two or more operands. Add(Vec), /// `multiply`: the product of two or more operands. @@ -832,7 +1210,7 @@ impl ConstraintExpression { ) -> Result { match self { ConstraintExpression::Value(value) => Ok(*value), - ConstraintExpression::System(property) => Ok(system.value(*property).unwrap_or(0)), + ConstraintExpression::System(read) => Ok(system.read(*read).unwrap_or(0)), ConstraintExpression::Aggregate(read) => Ok(system .aggregates .as_ref() @@ -1031,11 +1409,14 @@ impl ConstraintExpression { ControlFlow::Continue(()) } - /// Appends the system properties the expression reads to `reads`, in the - /// order it reads them. - fn collect_system_reads(&self, reads: &mut Vec) { + /// Hands `visit` the system values the expression reads, in the order it + /// reads them, stopping at the first `Break`. + fn visit_system_reads( + &self, + visit: &mut dyn FnMut(SystemRead) -> ControlFlow<()>, + ) -> ControlFlow<()> { match self { - ConstraintExpression::System(property) => reads.push(*property), + ConstraintExpression::System(read) => visit(*read)?, ConstraintExpression::Value(_) | ConstraintExpression::Property { .. } | ConstraintExpression::Size { .. } @@ -1047,18 +1428,19 @@ impl ConstraintExpression { | ConstraintExpression::Min(operands) | ConstraintExpression::Max(operands) => { for operand in operands { - operand.collect_system_reads(reads); + operand.visit_system_reads(visit)?; } } - ConstraintExpression::Abs(operand) => operand.collect_system_reads(reads), + ConstraintExpression::Abs(operand) => operand.visit_system_reads(visit)?, ConstraintExpression::Subtract(left, right) | ConstraintExpression::Divide(left, right) | ConstraintExpression::Modulo(left, right) | ConstraintExpression::Power(left, right) => { - left.collect_system_reads(reads); - right.collect_system_reads(reads); + left.visit_system_reads(visit)?; + right.visit_system_reads(visit)?; } } + ControlFlow::Continue(()) } /// Appends the aggregates the expression reads to `reads`, in the order it @@ -1120,12 +1502,6 @@ impl ConstraintExpression { .or_else(|| right.find_aggregate(matches)), } } - - /// Whether an aggregate the expression reads depends on the document's - /// owner ([`AggregateRead::reads_owner`]). - fn reads_owner(&self) -> bool { - self.find_aggregate(&AggregateRead::reads_owner).is_some() - } } /// How a rule reads a property, which decides the properties it may name. @@ -1476,8 +1852,11 @@ pub enum PropertyConstraint { impl PropertyConstraint { /// Whether a document whose properties are `data` and whose system values /// are `system` meets the condition. `$ownerId` reads `system.owner_id`, - /// equalling no identifier when it is `None`, and a system property reads - /// its value there, 0 when not given. + /// equalling no identifier when it is `None`, and a system value reads its + /// value there, 0 when not given. A path through `$old.` reads the stored + /// version's properties `data` holds under [`STORED_DOCUMENT_KEY`] + /// ([`DocumentSystemValues::judged_data`]), and `$old.$ownerId` and a + /// stored system value read [`DocumentSystemValues::stored`]. /// /// Evaluated left to right, and no further than the outcome needs: a /// comparison evaluates its left side, then its right one; `anyOf` checks @@ -1497,7 +1876,6 @@ impl PropertyConstraint { data: &Value, system: &DocumentSystemValues, ) -> Result { - let owner_id = system.owner_id; match self { PropertyConstraint::Compare { comparison, @@ -1545,7 +1923,7 @@ impl PropertyConstraint { path, value, } => { - let equal = identifier_value(data, owner_id, path) == Some(*value); + let equal = identifier_value(data, system, path) == Some(*value); Ok(equal == (*comparison == ConstraintComparison::Equal)) } PropertyConstraint::IdentifierCompareProperties { @@ -1555,15 +1933,15 @@ impl PropertyConstraint { } => { let equal = matches!( ( - identifier_value(data, owner_id, left), - identifier_value(data, owner_id, right) + identifier_value(data, system, left), + identifier_value(data, system, right) ), (Some(left), Some(right)) if left == right ); Ok(equal == (*comparison == ConstraintComparison::Equal)) } PropertyConstraint::IdentifierIn { path, values } => { - Ok(identifier_value(data, owner_id, path) + Ok(identifier_value(data, system, path) .is_some_and(|value| values.contains(&value))) } PropertyConstraint::TextAffix { @@ -1618,7 +1996,7 @@ impl PropertyConstraint { .iter() .any(|element| element.to_identifier().ok() == Some(*value)), ContainsNeedle::IdentifierProperty(path) => { - identifier_value(data, owner_id, path).is_some_and(|value| { + identifier_value(data, system, path).is_some_and(|value| { elements .iter() .any(|element| element.to_identifier().ok() == Some(value)) @@ -1674,24 +2052,26 @@ impl PropertyConstraint { /// Why a document whose properties are `data` and whose system values are /// `system` breaks the rule, `None` when it meets it: the first fault met /// on the way ([`Self::holds`]), or [`PropertyConstraintViolation::NotMet`] - /// when the rule evaluates to false. A rule reading a system property + /// when the rule evaluates to false. A rule reading a system value /// `system` does not give is not judged: consensus gives every one the /// document type records, the only ones a rule may read, so only a client - /// that does not know one skips the rule. So is a rule reading an aggregate + /// that does not know one skips the rule. So is a rule reading the stored + /// version when `system` does not say what it is + /// ([`DocumentSystemValues::stored`]), and a rule reading an aggregate /// `system` does not give: consensus reads every one before judging the /// write, and a client, which cannot read state here, gives none. And so /// is a rule reading a referenced document unless `system` says `data` /// holds the values it reads ([`DocumentSystemValues::referenced_documents`]). + /// `data` holds the stored version's properties under + /// [`STORED_DOCUMENT_KEY`] when there is one ([`DocumentSystemValues::judged_data`]). pub fn violation( &self, data: &Value, system: &DocumentSystemValues, ) -> Option { if !self.is_judged_with(system) - || self - .system_reads() - .into_iter() - .any(|property| system.value(property).is_none()) + || self.reads_system(&|read| system.read(read).is_none()) + || (system.stored.is_none() && self.reads_stored()) || self .find_aggregate(&|read| { !system @@ -1814,44 +2194,55 @@ impl PropertyConstraint { /// references points at (`{ "referenced": [...] }`), the walk stopping at /// the first such read rather than collecting every one. pub fn reads_referenced(&self) -> bool { - self.visit_property_reads(&mut |path, _| { - if path.starts_with(REFERENCED_DOCUMENT_PREFIX) { - ControlFlow::Break(()) - } else { - ControlFlow::Continue(()) - } - }) - .is_break() + self.reads_property(&|path| path.starts_with(REFERENCED_DOCUMENT_PREFIX)) } - /// Whether the rule compares the document's owner, `$ownerId`, or reads an - /// aggregate depending on it ([`AggregateRead::reads_owner`]): then a - /// transfer or a purchase, which changes the owner and nothing else, is - /// judged against it too. + /// Whether the rule compares the document's owner, `$ownerId`, or the + /// stored version's, `$old.$ownerId`, or reads an aggregate depending on it + /// ([`AggregateRead::reads_owner`]): then a transfer or a purchase, which + /// changes the owner and no property, is judged against it too. pub fn reads_owner(&self) -> bool { + self.compares_identifier(&is_owner_path) + || self.find_aggregate(&AggregateRead::reads_owner).is_some() + } + + /// Whether the rule reads the stored version of the document the write + /// replaces, through [`STORED_DOCUMENT_PREFIX`]: one of its properties, its + /// owner or one of its system values, each walk stopping at the first. + pub fn reads_stored(&self) -> bool { + self.reads_stored_properties() + || self.compares_identifier(&|path| path == STORED_OWNER_ID) + || self.reads_system(&|read| read.stored) + } + + /// Whether the rule reads a property of the stored version + /// (`$old.`), which the data it is judged against holds under + /// [`STORED_DOCUMENT_KEY`] ([`DocumentSystemValues::judged_data`]); its + /// owner and system values, which `system` gives, are not properties. + pub fn reads_stored_properties(&self) -> bool { + self.reads_property(&|path| stored_version_path(path).is_some()) + } + + /// Whether the rule compares an identifier, or looks for one among an + /// array's elements, at a path `matches` accepts. + fn compares_identifier(&self, matches: &dyn Fn(&str) -> bool) -> bool { match self { - PropertyConstraint::Compare { left, right, .. } => { - left.reads_owner() || right.reads_owner() - } - PropertyConstraint::In { operand, .. } => operand.reads_owner(), - PropertyConstraint::Contains { - needle: ContainsNeedle::Integer(expression), - .. - } => expression.reads_owner(), - PropertyConstraint::Contains { + PropertyConstraint::IdentifierCompare { path, .. } + | PropertyConstraint::IdentifierIn { path, .. } + | PropertyConstraint::Contains { needle: ContainsNeedle::IdentifierProperty(path), .. - } => path == OWNER_ID, - PropertyConstraint::IdentifierCompare { path, .. } - | PropertyConstraint::IdentifierIn { path, .. } => path == OWNER_ID, + } => matches(path), PropertyConstraint::IdentifierCompareProperties { left, right, .. } => { - left == OWNER_ID || right == OWNER_ID + matches(left) || matches(right) } PropertyConstraint::AnyOf(conditions) | PropertyConstraint::AllOf(conditions) => { - conditions.iter().any(PropertyConstraint::reads_owner) + conditions + .iter() + .any(|condition| condition.compares_identifier(matches)) } PropertyConstraint::Not(condition) | PropertyConstraint::NotIn(condition) => { - condition.reads_owner() + condition.compares_identifier(matches) } PropertyConstraint::IfThen { condition, @@ -1860,8 +2251,10 @@ impl PropertyConstraint { } => [Some(condition), Some(then), otherwise.as_ref()] .into_iter() .flatten() - .any(|part| part.reads_owner()), - PropertyConstraint::TextCompare { .. } + .any(|part| part.compares_identifier(matches)), + PropertyConstraint::Compare { .. } + | PropertyConstraint::In { .. } + | PropertyConstraint::TextCompare { .. } | PropertyConstraint::TextCompareProperties { .. } | PropertyConstraint::TextIn { .. } | PropertyConstraint::TextAffix { .. } @@ -1872,17 +2265,47 @@ impl PropertyConstraint { } } + /// Whether consensus judges the write ([`DocumentSystemValues::consensus`]) + /// but `system` does not say what the stored version is while the rule + /// reads it. Every write consensus judges gives the stored version to the + /// rules reading it, so one missing is a fault in the code building the + /// write, not a rule to skip. + pub fn unread_stored_version(&self, system: &DocumentSystemValues) -> bool { + system.consensus && system.stored.is_none() && self.reads_stored() + } + + /// Whether a write changing the top-level properties `fields` of a stored + /// document, `$revision`, and nothing else a rule reads (a moderator's + /// change of its fields) can break the rule: it reads one of `fields`, + /// directly or through `$old.`, `$revision` of either version, or a total, + /// which may have moved since the document was last written. + pub fn reads_changed_fields(&self, fields: &BTreeSet) -> bool { + self.find_aggregate(&|_| true).is_some() + || self.reads_system(&|read| read.value == SystemValue::Revision) + || self.reads_property(&|path| { + let path = either_version_path(path); + fields.contains(path.split('.').next().unwrap_or(path)) + }) + } + /// A total the rule reads that consensus did not read: `None` unless - /// `system` holds consensus's totals (`Some`) and lacks one the rule reads. - /// Every write consensus judges reads the totals of the rules it judges, so - /// one missing is a fault in the code building the write, not a rule to - /// skip. + /// consensus judges the write ([`DocumentSystemValues::consensus`]) and + /// `system` lacks a total the rule reads. Every write consensus judges reads + /// the totals of the rules it judges, so one missing is a fault in the code + /// building the write, not a rule to skip. pub fn unread_aggregate<'a>( &'a self, system: &DocumentSystemValues, ) -> Option<&'a AggregateRead> { - let aggregates = system.aggregates.as_ref()?; - self.find_aggregate(&|read| !aggregates.contains_key(read)) + if !system.consensus { + return None; + } + self.find_aggregate(&|read| { + !system + .aggregates + .as_ref() + .is_some_and(|aggregates| aggregates.contains_key(read)) + }) } /// The first aggregate the rule reads, in declared order, that `matches`, @@ -1983,46 +2406,60 @@ impl PropertyConstraint { } } - /// The system properties the rule reads (`"$createdAt"`, ...), in - /// declared order, one read twice listed twice. `$ownerId` is - /// [`Self::reads_owner`]'s. - pub fn system_reads(&self) -> Vec { + /// The system values the rule reads (`"$createdAt"`, `"$revision"`, + /// `"$old.$updatedAt"`, ...), in declared order, one read twice listed + /// twice. `$ownerId` and `$old.$ownerId` are [`Self::reads_owner`]'s. + pub fn system_reads(&self) -> Vec { let mut reads = Vec::new(); - self.collect_system_reads(&mut reads); + let _ = self.visit_system_reads(&mut |read| { + reads.push(read); + ControlFlow::Continue(()) + }); reads } - /// Whether `change` can break the rule: it reads the owner, or the time - /// and heights of the last transfer, for a transfer or a purchase; the - /// time and heights of the last update for a price update. Such a write - /// changes those and no property, so a rule reading neither held when the - /// document was written and still does. + /// Whether `change` can break the rule: for a transfer or a purchase, it + /// reads the owner, the time and heights of the last transfer or + /// `$revision`; for a price update, the time and heights of the last update + /// or `$revision`; either of the document written or, through `$old.`, of + /// the stored version, which the change makes the version before it. For a + /// restore, it reads a total. Such a write changes those and no property, + /// so a rule reading none of them held when the document was last written + /// and still does: one comparing properties with their stored values only + /// would compare each with itself. pub fn reads_change(&self, change: SystemChange) -> bool { - (change == SystemChange::Transfer && self.reads_owner()) - || self - .system_reads() - .into_iter() - .any(|property| property.changed_by(change)) + match change { + SystemChange::Restore => self.find_aggregate(&|_| true).is_some(), + SystemChange::Transfer | SystemChange::PriceUpdate => { + (change == SystemChange::Transfer && self.reads_owner()) + || self.reads_system(&|read| read.value.changed_by(change)) + } + } } - fn collect_system_reads(&self, reads: &mut Vec) { + /// Hands `visit` the system values the rule reads, in declared order, + /// stopping at the first `Break`. + fn visit_system_reads( + &self, + visit: &mut dyn FnMut(SystemRead) -> ControlFlow<()>, + ) -> ControlFlow<()> { match self { PropertyConstraint::Compare { left, right, .. } => { - left.collect_system_reads(reads); - right.collect_system_reads(reads); + left.visit_system_reads(visit)?; + right.visit_system_reads(visit)?; } - PropertyConstraint::In { operand, .. } => operand.collect_system_reads(reads), + PropertyConstraint::In { operand, .. } => operand.visit_system_reads(visit)?, PropertyConstraint::Contains { needle: ContainsNeedle::Integer(expression), .. - } => expression.collect_system_reads(reads), + } => expression.visit_system_reads(visit)?, PropertyConstraint::AnyOf(conditions) | PropertyConstraint::AllOf(conditions) => { for condition in conditions { - condition.collect_system_reads(reads); + condition.visit_system_reads(visit)?; } } PropertyConstraint::Not(condition) | PropertyConstraint::NotIn(condition) => { - condition.collect_system_reads(reads) + condition.visit_system_reads(visit)? } PropertyConstraint::IfThen { condition, @@ -2033,7 +2470,7 @@ impl PropertyConstraint { .into_iter() .flatten() { - part.collect_system_reads(reads); + part.visit_system_reads(visit)?; } } PropertyConstraint::TextCompare { .. } @@ -2048,6 +2485,33 @@ impl PropertyConstraint { | PropertyConstraint::Present(_) | PropertyConstraint::Absent(_) => {} } + ControlFlow::Continue(()) + } + + /// Whether the rule reads a system value `matches` accepts, the walk + /// stopping at the first. + fn reads_system(&self, matches: &dyn Fn(SystemRead) -> bool) -> bool { + self.visit_system_reads(&mut |read| { + if matches(read) { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }) + .is_break() + } + + /// Whether the rule reads a property at a path `matches` accepts, the walk + /// stopping at the first. + fn reads_property(&self, matches: &dyn Fn(&str) -> bool) -> bool { + self.visit_property_reads(&mut |path, _| { + if matches(path) { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }) + .is_break() } /// Every string constant the rule compares a property with, as the @@ -2385,16 +2849,16 @@ impl PropertyConstraint { visit(&left.path, PropertyRead::Text)?; visit(&right.path, PropertyRead::Text)?; } - // `$ownerId` is the document's owner, no property of it + // `$ownerId` and `$old.$ownerId` are owners, no properties PropertyConstraint::IdentifierCompare { path, .. } | PropertyConstraint::IdentifierIn { path, .. } => { - if path != OWNER_ID { + if !is_owner_path(path) { visit(path, PropertyRead::Identifier)? } } PropertyConstraint::IdentifierCompareProperties { left, right, .. } => { for path in [left, right] { - if path != OWNER_ID { + if !is_owner_path(path) { visit(path, PropertyRead::Identifier)?; } } @@ -2437,8 +2901,8 @@ impl PropertyConstraint { } ContainsNeedle::IdentifierProperty(path) => { visit(array, PropertyRead::Elements(ElementKind::Identifier))?; - // `$ownerId` is the document's owner, no property of it - if path != OWNER_ID { + // `$ownerId` and `$old.$ownerId` are owners, no properties + if !is_owner_path(path) { visit(path, PropertyRead::Identifier)?; } } @@ -2479,6 +2943,18 @@ struct ParseContext<'a> { property_kind: &'a dyn Fn(&str) -> Option, } +impl ParseContext<'_> { + /// How a bare path compares: `$ownerId` and `$old.$ownerId` as + /// identifiers, and a property, of either version, as `property_kind` + /// says of its path in the type. + fn kind_of(&self, path: &str) -> Option { + if is_owner_path(path) { + return Some(EqualityKind::Identifier); + } + (self.property_kind)(either_version_path(path)) + } +} + /// Reads the `propertyConstraints` keyword of a document type's `schema`: /// every rule by its name, in name order, the order a document is checked /// against them. Empty when the schema declares none. `property_kind` tells @@ -2607,8 +3083,9 @@ fn parse_named_rules( /// Reads one condition, the `when` of an `immutable` entry, with the grammar /// and the shape rules of a `propertyConstraints` rule ([`parse_property_constraints`]). -/// `property_kind` is as there, for paths as the condition names them (through -/// [`STORED_DOCUMENT_PREFIX`] included). The error is the rest of a message +/// `property_kind` is as there: the parse hands it the path a condition names +/// through [`STORED_DOCUMENT_PREFIX`] as the path after it +/// ([`either_version_path`]). The error is the rest of a message /// naming the condition. What the paths name is checked against the parsed /// document type by parser generation 3. pub fn parse_property_constraint_condition( @@ -2690,18 +3167,16 @@ fn referenced_operand(operands: &Value, at: &str) -> Result { Ok(referenced_path(reference, field)) } -/// How a condition compares the value at `path`: `$ownerId` and the -/// identifiers of a referenced document as identifiers, a property of the -/// document type as `property_kind` says, and any other value of a referenced -/// document not at all ([`has_open_kind`]). +/// How a condition compares the value at `path`: `$ownerId`, `$old.$ownerId` +/// and the identifiers of a referenced document as identifiers, a property of +/// the document type, of either version, as `property_kind` says +/// ([`ParseContext::kind_of`]), and any other value of a referenced document +/// not at all ([`has_open_kind`]). fn path_kind(context: &ParseContext, path: &str) -> Option { - if path == OWNER_ID { - return Some(EqualityKind::Identifier); - } if let Some((_, field)) = referenced_read(path) { return is_referenced_system_agreement_property(field).then_some(EqualityKind::Identifier); } - (context.property_kind)(path) + context.kind_of(path) } /// Whether the value at `path` is a schema property of a referenced document, @@ -2812,8 +3287,8 @@ fn parse_condition( )); }; let parent = enter(at, key); - // `$ownerId`, the document's owner, compares as an identifier property, and - // so do the identifiers of a referenced document + // `$ownerId` and `$old.$ownerId` compare as identifier properties, and so do + // the identifiers of a referenced document let kind_of = |path: &str| path_kind(context, path); let condition = match key { ANY_OF => PropertyConstraint::AnyOf(condition_list(body, key, at, depth + 1, context)?), @@ -3009,11 +3484,13 @@ fn parse_condition( its elements" )); }; - // `$ownerId` and the system times are values, never arrays + // `$ownerId` and the system values are values, never arrays; an + // array of the stored version is named through `$old.` let array = match named_path(array, &format!("{at}[0]")) { Some(Err(error)) => return Err(error), Some(Ok(path)) - if !path.starts_with('$') || path.starts_with(REFERENCED_DOCUMENT_PREFIX) => + if !either_version_path(&path).starts_with('$') + || path.starts_with(REFERENCED_DOCUMENT_PREFIX) => { path } @@ -3025,7 +3502,7 @@ fn parse_condition( // what is checked against the parsed document type. An array of a // referenced document is of the kind of what is looked for in it: a // string for a const or a string default, the kind of a path - let array_kind = (context.property_kind)(&array).or_else(|| { + let array_kind = context.kind_of(&array).or_else(|| { if !has_open_kind(&array) { return None; } @@ -3521,8 +3998,8 @@ fn parse_expression( } if let Some(path) = value.as_text() { let path = bare_path(path, at)?; - if let Some(property) = SystemProperty::from_name(&path) { - return Ok(ConstraintExpression::System(property)); + if let Some(read) = SystemRead::from_name(&path) { + return Ok(ConstraintExpression::System(read)); } return Ok(ConstraintExpression::Property { path, if_absent: 0 }); } @@ -3550,11 +4027,21 @@ fn parse_expression( Some(path) => path?, None => return Err(format!("at {at} must name a property path first")), }; - if SystemProperty::from_name(&path).is_some() { - return Err(format!( - "at {at} gives {path} a default, but a system property a rule reads is \ - always set: name it on its own" - )); + match SystemRead::from_name(&path) { + Some(SystemRead { stored: false, .. }) => { + return Err(format!( + "at {at} gives {path} a default, but a system property a rule reads is \ + always set: name it on its own" + )); + } + Some(SystemRead { stored: true, .. }) => { + return Err(format!( + "at {at} gives {path} a default, but a system value of the stored \ + version is always set, and reads 0 on a create, which has none: name \ + it on its own" + )); + } + None => {} } if if_absent.as_text().is_some() { return Err(format!( @@ -3643,7 +4130,7 @@ fn parse_expression( Some(path) => path?, None => return Err(format!("at {at} must name a property path first")), }; - if path == OWNER_ID || SystemProperty::from_name(&path).is_some() { + if is_owner_path(&path) || SystemRead::from_name(&path).is_some() { return Err(format!( "at {at} names {path}, but byteAt reads a byte array property" )); @@ -3801,6 +4288,12 @@ fn parse_aggregate( let binding = match binding { Value::Text(path) if path == OWNER_ID => AggregateBinding::Owner, Value::Text(path) if path == DOCUMENT_ID => AggregateBinding::Id, + Value::Text(path) if stored_version_path(path).is_some() => { + return Err(format!( + "at {at}.{key} takes {path}, but a total matches its documents by the \ + document being written, never the stored version it replaces" + )) + } Value::Text(path) if path.starts_with('$') => { return Err(format!( "at {at}.{key} takes {path}, but the system values a key takes are \ @@ -3918,14 +4411,23 @@ fn integer_value(value: &Value, at: &str) -> Result { }) } +/// Whether `path` names an owner rather than a property: `$ownerId`, or the +/// stored version's, `$old.$ownerId`. +fn is_owner_path(path: &str) -> bool { + either_version_path(path) == OWNER_ID +} + /// The identifier `data` holds at `path`, in any of the forms a document's -/// identifier takes, or `owner_id` for `$ownerId`; `None` when the document -/// leaves the property out or holds something that is no identifier there, -/// which the schema validation running first refuses for an identifier -/// property. -fn identifier_value(data: &Value, owner_id: Option, path: &str) -> Option { +/// identifier takes, or the owner `system` gives for `$ownerId`, and the +/// stored version's for `$old.$ownerId`; `None` when the document leaves the +/// property out or holds something that is no identifier there, which the +/// schema validation running first refuses for an identifier property. +fn identifier_value(data: &Value, system: &DocumentSystemValues, path: &str) -> Option { if path == OWNER_ID { - return owner_id; + return system.owner_id; + } + if path == STORED_OWNER_ID { + return system.stored_owner_id(); } match data.get_optional_value_at_path(path) { Ok(Some(value)) => value.to_identifier().ok(), diff --git a/packages/rs-dpp/src/data_contract/document_type/property_constraints/tests.rs b/packages/rs-dpp/src/data_contract/document_type/property_constraints/tests.rs index 6e8d2420760..1a4ddcfb8c9 100644 --- a/packages/rs-dpp/src/data_contract/document_type/property_constraints/tests.rs +++ b/packages/rs-dpp/src/data_contract/document_type/property_constraints/tests.rs @@ -2531,7 +2531,7 @@ fn should_parse_the_system_times_and_heights_as_operands() { rule, PropertyConstraint::Compare { comparison: ConstraintComparison::LessThan, - left: ConstraintExpression::System(system), + left: ConstraintExpression::System(system.into()), right: property("deadline"), }, "{}", @@ -2539,7 +2539,7 @@ fn should_parse_the_system_times_and_heights_as_operands() { ); assert_eq!(rule.node_count(), 3); assert_eq!(rule.property_reads(), [("deadline", PropertyRead::Value)]); - assert_eq!(rule.system_reads(), [system]); + assert_eq!(rule.system_reads(), [SystemRead::from(system)]); assert!(!rule.reads_owner()); } for name in ["$ownerId", "$id", "$revision", "$createdat", "createdAt"] { @@ -2551,7 +2551,10 @@ fn should_parse_the_system_times_and_heights_as_operands() { let rule = parse_rule_value(platform_value!({ "greaterThan": ["$createdAtBlockHeight", 1000] })); - assert_eq!(rule.system_reads(), [SystemProperty::CreatedAtBlockHeight]); + assert_eq!( + rule.system_reads(), + [SystemRead::from(SystemProperty::CreatedAtBlockHeight)] + ); } #[test] @@ -2599,7 +2602,11 @@ fn should_read_the_system_values_the_rule_is_judged_with() { created_at_core_block_height: Some(7), updated_at_core_block_height: Some(8), transferred_at_core_block_height: Some(9), + revision: None, aggregates: None, + consensus: false, + stored: None, + changed_fields: None, referenced_documents: false, }; for (index, property) in SystemProperty::ALL.into_iter().enumerate() { @@ -2904,7 +2911,10 @@ fn should_parse_contains_by_the_kind_of_the_array() { assert_eq!(defaulted.text_defaults(), [("status", "sale")]); // A system value looked for among integers is read like any operand let created = parse_rule_value(platform_value!({ "contains": ["scores", "$createdAt"] })); - assert_eq!(created.system_reads(), [SystemProperty::CreatedAt]); + assert_eq!( + created.system_reads(), + [SystemRead::from(SystemProperty::CreatedAt)] + ); } #[test] @@ -4294,6 +4304,7 @@ fn should_read_an_aggregate_from_the_system_values_and_skip_a_rule_not_given_one // missing total is reported, which `validate_property_constraints` turns // into an error; a client's, which reads none, only skips the rule let other = DocumentSystemValues { + consensus: true, aggregates: Some(BTreeMap::from([( AggregateRead { document_type: "listing".to_string(), @@ -4310,4 +4321,483 @@ fn should_read_an_aggregate_from_the_system_values_and_skip_a_rule_not_given_one rule.unread_aggregate(&DocumentSystemValues::default()), None ); + // Consensus giving no totals at all lacks this one too + let none_read = DocumentSystemValues { + consensus: true, + ..DocumentSystemValues::default() + }; + assert_eq!(rule.unread_aggregate(&none_read), Some(&read)); +} + +// ── the stored version ($old.) and $revision ──────────────────────────── + +/// The system values of a stored version holding `properties`, owned by +/// `owner`, last updated at `updated_at` and at revision `revision`. +fn stored_version( + properties: &[(&str, Value)], + owner: Identifier, + updated_at: u64, + revision: u64, +) -> StoredVersion { + StoredVersion::Present(Box::new(StoredDocument { + properties: Some( + properties + .iter() + .map(|(key, value)| (key.to_string(), value.clone())) + .collect(), + ), + system: StoredSystemValues { + owner_id: owner, + updated_at: Some(updated_at), + revision: Some(revision), + ..Default::default() + }, + })) +} + +/// Why `rule` breaks for a document whose properties are `data` and whose +/// system values are `system`, judged as the document type judges it: with +/// the stored version's properties under `$old`. +fn judge( + rule: &PropertyConstraint, + data: &Value, + system: &DocumentSystemValues, +) -> Option { + rule.violation(&system.judged_data(data), system) +} + +/// A path, `$ownerId`, a time, a height or `$revision` under `$old.` names the +/// stored version's; every such read marks the rule as reading it. +#[test] +fn should_parse_reads_of_the_stored_version() { + let rule = parse_rule_value(platform_value!({ + "greaterThanOrEqual": ["price", { "ifAbsent": ["$old.price", 0] }] + })); + assert_eq!( + rule.property_reads(), + [ + ("price", PropertyRead::Value), + ("$old.price", PropertyRead::Value) + ] + ); + assert!(rule.reads_stored()); + assert!(!parse_rule_value(platform_value!({ "greaterThan": ["price", 0] })).reads_stored()); + + let updated = parse_rule_value(platform_value!({ + "greaterThanOrEqual": [{ "subtract": ["$updatedAt", "$old.$updatedAt"] }, 3600000] + })); + let stored_update = SystemRead { + value: SystemValue::Property(SystemProperty::UpdatedAt), + stored: true, + }; + assert_eq!( + updated.system_reads(), + [SystemRead::from(SystemProperty::UpdatedAt), stored_update] + ); + assert_eq!(stored_update.name(), "$old.$updatedAt"); + assert_eq!( + SystemRead::from_name("$old.$updatedAt"), + Some(stored_update) + ); + assert!(updated.reads_stored()); + + let revisions = parse_rule_value(platform_value!({ + "equal": ["$revision", { "add": ["$old.$revision", 1] }] + })); + assert_eq!( + revisions + .system_reads() + .into_iter() + .map(SystemRead::name) + .collect::>(), + ["$revision", "$old.$revision"] + ); + assert!(revisions.reads_stored()); + + // `$old.$ownerId` compares as an identifier, reads the owner, and is no property + let resold = parse_rule_value(platform_value!({ "notEqual": ["$ownerId", "$old.$ownerId"] })); + assert_eq!( + resold, + PropertyConstraint::IdentifierCompareProperties { + comparison: ConstraintComparison::NotEqual, + left: OWNER_ID.to_string(), + right: STORED_OWNER_ID.to_string(), + } + ); + assert!(resold.property_reads().is_empty()); + assert!(resold.reads_owner()); + assert!(resold.reads_stored()); + + // A string, an identifier or an array of the stored version compares as the + // property after `$old.` does + let reopened = parse_rule_value(platform_value!({ + "ifThen": [ + { "equal": ["$old.status", { "const": "closed" }] }, + { "equal": ["status", { "const": "closed" }] } + ] + })); + assert_eq!( + reopened.property_reads(), + [ + ("$old.status", PropertyRead::Text), + ("status", PropertyRead::Text) + ] + ); + let kept_label = parse_rule_value(platform_value!({ + "ifThen": [ + { "contains": ["$old.labels", { "const": "verified" }] }, + { "contains": ["labels", { "const": "verified" }] } + ] + })); + assert_eq!( + kept_label.property_reads(), + [ + ("$old.labels", PropertyRead::Elements(ElementKind::Text)), + ("labels", PropertyRead::Elements(ElementKind::Text)) + ] + ); + let same_buyer = parse_rule_value(platform_value!({ "equal": ["buyerId", "$old.buyerId"] })); + assert!(matches!( + same_buyer, + PropertyConstraint::IdentifierCompareProperties { .. } + )); +} + +#[test] +fn should_refuse_what_the_stored_version_cannot_take() { + expect_refusal( + platform_value!({ + "rule": { "lessThan": [{ "ifAbsent": ["$old.$updatedAt", 0] }, "deadline"] } + }), + "at lessThan[0].ifAbsent gives $old.$updatedAt a default, but a system value of the \ + stored version is always set, and reads 0 on a create, which has none: name it on its \ + own", + ); + expect_refusal( + platform_value!({ "rule": { "equal": [{ "byteAt": ["$old.$ownerId", 0] }, 1] } }), + "names $old.$ownerId, but byteAt reads a byte array property", + ); + expect_refusal( + platform_value!({ + "rule": { "lessThan": [{ "countOf": ["listing", { "status": "$old.status" }] }, 10] } + }), + "takes $old.status, but a total matches its documents by the document being written, \ + never the stored version it replaces", + ); +} + +/// On a create there is no stored version: a property under `$old.` is absent +/// and a stored system value reads 0. On a later write it is the version +/// replaced. A rule reading it is not judged when the stored version is not +/// given, as a client not handed one judges. +#[test] +fn should_judge_a_stored_read_on_a_create_on_a_replace_and_not_without_it() { + let rule = parse_rule_value(platform_value!({ + "greaterThanOrEqual": ["price", { "ifAbsent": ["$old.price", 0] }] + })); + let price = |value: i64| data(&[("price", Value::I64(value))]); + let owner = Identifier::new([1; 32]); + let create = DocumentSystemValues { + stored: Some(StoredVersion::Absent), + ..Default::default() + }; + let replacing = |stored_price: i64| DocumentSystemValues { + stored: Some(stored_version( + &[("price", Value::I64(stored_price))], + owner, + 0, + 1, + )), + ..Default::default() + }; + + assert_eq!(judge(&rule, &price(5), &create), None); + assert_eq!( + judge(&rule, &price(-1), &create), + Some(PropertyConstraintViolation::NotMet) + ); + assert_eq!(judge(&rule, &price(3), &replacing(3)), None); + assert_eq!( + judge(&rule, &price(2), &replacing(3)), + Some(PropertyConstraintViolation::NotMet) + ); + // Not given: not judged, whatever it would say + assert_eq!( + judge(&rule, &price(-1), &DocumentSystemValues::default()), + None + ); + + // A `$old` the written data carries itself is never read as the stored version + let forged = data(&[ + ("price", Value::I64(-1)), + ("$old", data(&[("price", Value::I64(-5))])), + ]); + assert_eq!( + judge(&rule, &forged, &create), + Some(PropertyConstraintViolation::NotMet) + ); + // Stored at 0, the price may not fall to -1, though the forged -5 would allow it + assert_eq!( + judge(&rule, &forged, &replacing(0)), + Some(PropertyConstraintViolation::NotMet), + "the stored version replaces it" + ); +} + +#[test] +fn should_read_the_stored_owner_times_and_revision() { + let seller = Identifier::new([1; 32]); + let buyer = Identifier::new([2; 32]); + let empty = data(&[]); + + // A transfer: the owner differs from the stored one + let changed_hands = + parse_rule_value(platform_value!({ "notEqual": ["$ownerId", "$old.$ownerId"] })); + let owned_by = |owner: Identifier, stored: StoredVersion| DocumentSystemValues { + owner_id: Some(owner), + stored: Some(stored), + ..Default::default() + }; + assert_eq!( + judge( + &changed_hands, + &empty, + &owned_by(buyer, stored_version(&[], seller, 0, 1)) + ), + None + ); + assert_eq!( + judge( + &changed_hands, + &empty, + &owned_by(seller, stored_version(&[], seller, 0, 1)) + ), + Some(PropertyConstraintViolation::NotMet) + ); + // A create has no stored owner, which equals no identifier + assert_eq!( + judge( + &changed_hands, + &empty, + &owned_by(buyer, StoredVersion::Absent) + ), + None + ); + + // Edits an hour apart: the stored update time reads 0 on a create + let hour_apart = parse_rule_value(platform_value!({ + "greaterThanOrEqual": [{ "subtract": ["$updatedAt", "$old.$updatedAt"] }, 3600000] + })); + let updated = |at: u64, stored: StoredVersion| DocumentSystemValues { + updated_at: Some(at), + stored: Some(stored), + ..Default::default() + }; + let day = 86_400_000; + assert_eq!( + judge( + &hour_apart, + &empty, + &updated(day + 3_600_000, stored_version(&[], seller, day, 1)) + ), + None + ); + assert_eq!( + judge( + &hour_apart, + &empty, + &updated(day + 3_599_999, stored_version(&[], seller, day, 1)) + ), + Some(PropertyConstraintViolation::NotMet) + ); + assert_eq!( + judge(&hour_apart, &empty, &updated(day, StoredVersion::Absent)), + None + ); + + // At most five writes after the create, and the revision moves by one + let five_edits = parse_rule_value(platform_value!({ "lessThanOrEqual": ["$revision", 6] })); + let at_revision = |revision: Option| DocumentSystemValues { + revision, + ..Default::default() + }; + assert_eq!(judge(&five_edits, &empty, &at_revision(Some(6))), None); + assert_eq!( + judge(&five_edits, &empty, &at_revision(Some(7))), + Some(PropertyConstraintViolation::NotMet) + ); + // Not given: not judged + assert_eq!(judge(&five_edits, &empty, &at_revision(None)), None); + let next_revision = parse_rule_value(platform_value!({ + "equal": ["$revision", { "add": ["$old.$revision", 1] }] + })); + let written_at = |revision: u64, stored: StoredVersion| DocumentSystemValues { + revision: Some(revision), + stored: Some(stored), + ..Default::default() + }; + assert_eq!( + judge( + &next_revision, + &empty, + &written_at(3, stored_version(&[], seller, 0, 2)) + ), + None + ); + assert_eq!( + judge( + &next_revision, + &empty, + &written_at(1, StoredVersion::Absent) + ), + None, + "a create's first revision follows the 0 an absent stored version reads" + ); +} + +/// A transfer, a purchase or a price update changes no property, so it is +/// judged only against the rules reading what it changes, of either version; +/// a restore only against the rules reading a total, and a moderator's change +/// of fields against those reading one of them, `$revision` or a total. +#[test] +fn should_tell_which_writes_a_stored_read_answers_to() { + let rule = |value: Value| parse_rule_value(value); + let stricter = rule(platform_value!({ "greaterThan": ["price", "$old.price"] })); + let resold = rule(platform_value!({ "notEqual": ["$ownerId", "$old.$ownerId"] })); + let held_a_day = rule(platform_value!({ + "greaterThanOrEqual": [{ "subtract": ["$transferredAt", "$old.$transferredAt"] }, 86400000] + })); + let priced_apart = rule(platform_value!({ + "greaterThan": ["$old.$updatedAtBlockHeight", 10] + })); + let revised = rule(platform_value!({ "lessThanOrEqual": ["$revision", 6] })); + let capped = rule(platform_value!({ + "ifThen": [ + { "notEqual": ["status", "$old.status"] }, + { "lessThan": [{ "countOf": ["dispute", { "orderId": "$id" }] }, 3] } + ] + })); + + for (name, parsed, transfer, price_update, restore) in [ + ("stricter", &stricter, false, false, false), + ("resold", &resold, true, false, false), + ("held_a_day", &held_a_day, true, false, false), + ("priced_apart", &priced_apart, false, true, false), + ("revised", &revised, true, true, false), + ("capped", &capped, false, false, true), + ] { + assert_eq!( + parsed.reads_change(SystemChange::Transfer), + transfer, + "{name}: transfer" + ); + assert_eq!( + parsed.reads_change(SystemChange::PriceUpdate), + price_update, + "{name}: price update" + ); + assert_eq!( + parsed.reads_change(SystemChange::Restore), + restore, + "{name}: restore" + ); + } + + let fields = |names: &[&str]| -> BTreeSet { + names.iter().map(|name| name.to_string()).collect() + }; + assert!(stricter.reads_changed_fields(&fields(&["price"]))); + assert!(!stricter.reads_changed_fields(&fields(&["note"]))); + assert!(!resold.reads_changed_fields(&fields(&["price"]))); + assert!(revised.reads_changed_fields(&fields(&["note"]))); + assert!(capped.reads_changed_fields(&fields(&["note"]))); + let nested = rule(platform_value!({ "equal": ["$old.meta.state", "meta.state"] })); + assert!(nested.reads_changed_fields(&fields(&["meta"]))); +} + +/// Consensus gives the stored version to every rule reading it: one missing +/// while consensus's totals are there is a fault in the code building the +/// write, not a rule to skip. +#[test] +fn should_report_a_stored_version_consensus_did_not_give() { + let rule = parse_rule_value(platform_value!({ "greaterThan": ["price", "$old.price"] })); + let consensus = |stored: Option| DocumentSystemValues { + consensus: true, + stored, + ..Default::default() + }; + assert!(rule.unread_stored_version(&consensus(None))); + assert!(!rule.unread_stored_version(&consensus(Some(StoredVersion::Absent)))); + assert!(!rule.unread_stored_version(&DocumentSystemValues::default())); + let unread = parse_rule_value(platform_value!({ "greaterThan": ["price", 0] })); + assert!(!unread.unread_stored_version(&consensus(None))); + + // Given without its properties, the stored version is given: whether a + // rule reading one of them may be judged is the judging's to tell + let without_properties = consensus(Some(StoredVersion::without_properties( + StoredSystemValues::default(), + ))); + assert!(!rule.unread_stored_version(&without_properties)); + assert!(!without_properties.stored_properties_given()); + assert!(consensus(None).stored_properties_given()); + let revised = + parse_rule_value(platform_value!({ "greaterThan": ["$revision", "$old.$revision"] })); + assert!(revised.unread_stored_version(&consensus(None))); +} + +/// A create records the first revision and no stored version; a document's +/// values carry its revision and no stored version either, and as the version +/// a write replaces, its properties, owner and revision are what `$old.` reads. +#[test] +fn should_take_the_revision_and_stored_version_of_a_create_and_of_a_document() { + let owner = Identifier::new([3; 32]); + let created = DocumentSystemValues::created_in_block(owner, &BlockInfo::default()); + assert_eq!(created.revision, Some(INITIAL_REVISION)); + assert_eq!(created.stored, Some(StoredVersion::Absent)); + assert_eq!(created.stored_owner_id(), None); + assert_eq!( + created.read(SystemRead { + value: SystemValue::Revision, + stored: true + }), + Some(0) + ); + + let document: Document = crate::document::DocumentV0 { + owner_id: owner, + properties: BTreeMap::from([("price".to_string(), Value::U64(7))]), + revision: Some(3), + updated_at: Some(20), + ..Default::default() + } + .into(); + let values = DocumentSystemValues::of_document(&document); + assert_eq!(values.revision, Some(3)); + assert_eq!(values.stored, None); + + let replacing = DocumentSystemValues { + stored: Some(StoredVersion::of_document(&document)), + ..DocumentSystemValues::default() + }; + assert_eq!(replacing.stored_owner_id(), Some(owner)); + for (value, expected) in [ + (SystemValue::Revision, 3), + (SystemValue::Property(SystemProperty::UpdatedAt), 20), + ] { + assert_eq!( + replacing.read(SystemRead { + value, + stored: true + }), + Some(expected) + ); + } + assert_eq!( + replacing + .judged_data(&data(&[])) + .get_optional_value_at_path("$old.price") + .ok() + .flatten(), + Some(&Value::U64(7)) + ); } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs index f9aca64fc88..e60341912b8 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/advanced_structure_v1/mod.rs @@ -150,6 +150,7 @@ impl DocumentCreateTransitionActionStructureValidationV1 for DocumentCreateTrans self.data().into(), &DocumentSystemValues { aggregates: Some(self.property_constraint_aggregates().clone()), + consensus: true, ..DocumentSystemValues::created_in_block(owner_id, &self.block_info()) }, platform_version, @@ -313,7 +314,7 @@ mod tests { prefunded_voting_balance, current_store_contest_info: None, should_store_contest_info: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), moderated: false, consumed_documents: Vec::new(), derived_index_values: None, @@ -593,7 +594,7 @@ mod tests { prefunded_voting_balance, current_store_contest_info: None, should_store_contest_info: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), moderated: false, consumed_documents: Vec::new(), derived_index_values: None, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/state_v2/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/state_v2/mod.rs index 9e4b650a687..e783d9dc53c 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/state_v2/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_create_transition_action/state_v2/mod.rs @@ -170,8 +170,9 @@ impl DocumentCreateTransitionActionStateValidationV2 for DocumentCreateTransitio .validate_referencing_property_constraints( self.data(), referenced_documents, - &DocumentSystemValues { + DocumentSystemValues { aggregates: Some(self.property_constraint_aggregates().clone()), + consensus: true, ..system }, platform_version, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_delete_transition_action/state_v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_delete_transition_action/state_v1/mod.rs index aa66e970f8c..bc5cee0bc42 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_delete_transition_action/state_v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_delete_transition_action/state_v1/mod.rs @@ -96,6 +96,7 @@ impl DocumentDeleteTransitionActionStateValidationV1 for DocumentDeleteTransitio &data, &DocumentSystemValues { aggregates: Some(aggregates), + consensus: true, ..DocumentSystemValues::of_document(&document) }, platform_version, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_purchase_transition_action/advanced_structure_v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_purchase_transition_action/advanced_structure_v0/mod.rs index 0278c88752d..e7699dbdb1a 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_purchase_transition_action/advanced_structure_v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_purchase_transition_action/advanced_structure_v0/mod.rs @@ -1,4 +1,4 @@ -use dpp::data_contract::document_type::property_constraints::{DocumentSystemValues, SystemChange}; +use dpp::data_contract::document_type::property_constraints::{DocumentSystemValues, StoredVersion, SystemChange}; use dpp::consensus::basic::document::{InvalidDocumentTransitionActionError, InvalidDocumentTypeError}; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; @@ -84,12 +84,21 @@ impl DocumentPurchaseTransitionActionStructureValidationV0 for DocumentPurchaseT // `propertyConstraints` that read them: the stored properties met every rule when // they were written, and these are all this action changes that a rule reads. A // `countOf` or `sumOf` that depends on the owner reads the total the action read - // from state, as it will be once the document changes hands. + // from state, as it will be once the document changes hands. A path through `$old.` + // reads the document before the purchase: the same properties, its seller, previous + // transfer and revision, which the transformer attached when a rule the change can + // break reads them. The properties are the written ones, which the judging reads + // there, so none is copied document_type .validate_property_constraints_for_system_change( self.document().properties(), &DocumentSystemValues { aggregates: Some(self.property_constraint_aggregates().clone()), + consensus: true, + stored: self + .stored_system_values() + .cloned() + .map(StoredVersion::without_properties), ..DocumentSystemValues::of_document(self.document()) }, SystemChange::Transfer, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_replace_transition_action/advanced_structure_v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_replace_transition_action/advanced_structure_v0/mod.rs index 42b304be333..753e863c8c0 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_replace_transition_action/advanced_structure_v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_replace_transition_action/advanced_structure_v0/mod.rs @@ -1,7 +1,7 @@ use dpp::data_contract::document_type::property_constraints::DocumentSystemValues; use dpp::consensus::basic::document::{InvalidDocumentTransitionActionError, InvalidDocumentTypeError}; use dpp::data_contract::accessors::v0::DataContractV0Getters; -use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters}; use dpp::data_contract::document_type::methods::{DocumentTypeBasicMethods, DocumentTypeV0Methods}; use dpp::identifier::Identifier; use dpp::data_contract::validate_document::DataContractDocumentValidationMethodsV0; @@ -10,6 +10,7 @@ use drive::state_transition_action::batch::batched_transition::document_transiti use drive::state_transition_action::batch::batched_transition::document_transition::document_replace_transition_action::{DocumentReplaceTransitionAction, DocumentReplaceTransitionActionAccessorsV0}; use dpp::version::PlatformVersion; use crate::error::Error; +use crate::execution::validation::state_transition::batch::action_validation::document::document_replace_transition_action::state_v1::ReplaceConditionInputs; pub(in crate::execution::validation::state_transition::state_transitions::batch::action_validation) trait DocumentReplaceTransitionActionStructureValidationV0 { fn validate_structure_v0( @@ -49,26 +50,28 @@ impl DocumentReplaceTransitionActionStructureValidationV0 for DocumentReplaceTra // Validate user defined properties. The rules read the writer, the times and // heights the replace keeps (creation, last transfer) and the ones it sets (the - // update), as the stored document will hold them, and the `countOf` and `sumOf` - // totals the action read from state as they will be once it is stored. + // update), as the stored document will hold them, its revision, the `countOf` and + // `sumOf` totals the action read from state as they will be once it is stored, and, + // through `$old.`, the document it replaces: its properties, rebuilt from the + // written ones and the stored value of each changed one, and its owner, times, + // heights and revision, which the transformer attached when a rule reads them. + // The stored version is built as much as the rules judged here read it: the + // rules reading a referenced document wait for replace state validation 1, once + // the references hold, and an `immutable` condition reading it is judged there too. + // The revision, the stored version and the referenced documents were added in + // place at protocol version 14, inert for every earlier version this generation + // serves: no rule parses before 14 (`parse_property_constraints` is `None`), so + // none reads them and `validate_property_constraints` is `None` there. + let stored = self.stored_version_read_by( + document_type + .property_constraints() + .values() + .filter(|rule| !rule.reads_referenced()), + ); let system = DocumentSystemValues { - owner_id: Some(owner_id), - created_at: self.created_at(), - updated_at: self.updated_at(), - transferred_at: self.transferred_at(), - created_at_block_height: self.created_at_block_height(), - updated_at_block_height: self.updated_at_block_height(), - transferred_at_block_height: self.transferred_at_block_height(), - created_at_core_block_height: self.created_at_core_block_height(), - updated_at_core_block_height: self.updated_at_core_block_height(), - transferred_at_core_block_height: self.transferred_at_core_block_height(), aggregates: Some(self.property_constraint_aggregates().clone()), - // The rules reading a referenced document wait for replace state - // validation 1, once the references hold. Added in place at protocol - // version 14, inert for every earlier version this generation serves: - // no rule parses before 14 (`parse_property_constraints` is `None`), - // so no rule reads a referenced document there - referenced_documents: false, + consensus: true, + ..self.condition_system_values(owner_id, stored) }; let result = data_contract .validate_document_properties( diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_replace_transition_action/state_v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_replace_transition_action/state_v1/mod.rs index 82005f1eb1c..d6e26787291 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_replace_transition_action/state_v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_replace_transition_action/state_v1/mod.rs @@ -4,7 +4,8 @@ use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV2Getters; use dpp::data_contract::document_type::methods::DocumentTypeV0Methods; use dpp::data_contract::document_type::property_constraints::{ - DocumentSystemValues, STORED_DOCUMENT_KEY, + data_with_stored_properties, DocumentSystemValues, PropertyConstraint, StoredDocument, + StoredSystemValues, StoredVersion, }; use std::collections::BTreeMap; use dpp::identifier::Identifier; @@ -68,7 +69,8 @@ impl DocumentReplaceTransitionActionStateValidationV1 for DocumentReplaceTransit // replace writes (its `$updatedAt` this block's time), with the stored // properties under `$old`, rebuilt from the written ones and the stored // value of each changed one: an added property the stored document did - // not hold, a removed one it did. A condition that cannot be evaluated + // not hold, a removed one it did; and the stored owner, times, heights + // and revision the transformer attached. A condition that cannot be evaluated // (an overflow, a division by zero) counts as holding: the property // stays frozen rather than freed by a fault. Conditions are evaluated // only for the properties the replace changes. @@ -102,10 +104,7 @@ impl DocumentReplaceTransitionActionStateValidationV1 for DocumentReplaceTransit for property in self.changed_data_fields() { if let Some(condition) = conditions.get(property) { let (data, system) = judged.get_or_insert_with(|| { - ( - self.condition_data(), - self.condition_system_values(owner_id), - ) + self.condition_inputs(owner_id, self.stored_system_values()) }); if !condition.holds(data, system).unwrap_or(true) { continue; @@ -143,10 +142,10 @@ impl DocumentReplaceTransitionActionStateValidationV1 for DocumentReplaceTransit } // The document the replace writes keeps its creation and last transfer and is - // updated in this block, for every time and height a `where` entry reads; the values - // the type's rules read of the documents its references point at are collected from - // those documents, every such reference being checked on every replace - let system = self.condition_system_values(owner_id); + // updated in this block, for every time and height a `where` entry reads; and the + // values the type's rules read of the documents its references point at are + // collected from those documents, every such reference being checked on every replace + let system = self.condition_system_values(owner_id, None); let mut referenced_documents = BTreeMap::new(); let reference_result = self.base().validate_document_references( self.data(), @@ -171,13 +170,22 @@ impl DocumentReplaceTransitionActionStateValidationV1 for DocumentReplaceTransit // The rules reading a document a reference points at (protocol version 14), judged // once the references hold, with the values their checks read, as on a create: every - // replace judges every rule, and the structure validation judged the others + // replace judges every rule, and the structure validation judged the others. The + // document it replaces, as much of it as they read through `$old.` + let stored = self.stored_version_read_by( + document_type + .property_constraints() + .values() + .filter(|rule| rule.reads_referenced()), + ); let result = document_type .validate_referencing_property_constraints( self.data(), referenced_documents, - &DocumentSystemValues { + DocumentSystemValues { aggregates: Some(self.property_constraint_aggregates().clone()), + consensus: true, + stored, ..system }, platform_version, @@ -193,26 +201,52 @@ impl DocumentReplaceTransitionActionStateValidationV1 for DocumentReplaceTransit /// What a condition judging a replace is judged against: the `when` of an /// `immutable` entry, here, and a type's `retractedWhen`, which the batch -/// transformer judges a barred owner's replace on. +/// transformer judges a barred owner's replace on; and the stored version a +/// `propertyConstraints` rule reads through `$old.`. pub(in crate::execution::validation::state_transition::state_transitions::batch) trait ReplaceConditionInputs { - /// The properties the replace writes, with the stored document's under - /// `$old` for a condition reading them through `$old.`: the written ones, - /// each changed one set back to its stored value, and an added one, which - /// the stored document did not hold, left out. - fn condition_data(&self) -> Value; + /// The properties of the stored document the replace replaces, rebuilt from + /// those it writes: each changed one set back to its stored value, and an + /// added one, which the stored document did not hold, left out. + fn stored_properties(&self) -> BTreeMap; + + /// The stored version the replace replaces as much as `rules` read of it + /// through `$old.`: `None` when none reads it; its owner, times, heights and + /// revision, which the transformer attached when something the document + /// type declares reads them, alone when none reads one of its properties; + /// and with its properties ([`Self::stored_properties`]) otherwise. + fn stored_version_read_by<'r>( + &self, + rules: impl Iterator, + ) -> Option; /// The system values of the document the replace writes, as a /// `propertyConstraints` rule judges a replace: the stored creation and - /// transfer, this block as the update, and `owner_id`, the writer. - fn condition_system_values(&self, owner_id: Identifier) -> DocumentSystemValues; + /// transfer, this block as the update, its revision, `owner_id`, the writer, + /// and `stored`, the version it replaces as the rules judged read it. + fn condition_system_values( + &self, + owner_id: Identifier, + stored: Option, + ) -> DocumentSystemValues; + + /// The properties the replace writes, with, given `stored_system`, the + /// stored document's under `$old`, and [`Self::condition_system_values`] + /// with the stored owner, times, heights and revision, what a condition + /// judging the replace is judged against. Without `stored_system`, which + /// the transformer attaches whenever a condition reads the stored version, + /// there is no stored version to read. + fn condition_inputs( + &self, + owner_id: Identifier, + stored_system: Option<&StoredSystemValues>, + ) -> (Value, DocumentSystemValues); } impl ReplaceConditionInputs for DocumentReplaceTransitionAction { - fn condition_data(&self) -> Value { - let written = self.data(); + fn stored_properties(&self) -> BTreeMap { let stored_changed = self.stored_changed_values(); - let mut stored = written.clone(); + let mut stored = self.data().clone(); for property in self.changed_data_fields() { match stored_changed.get(property) { Some(value) => { @@ -223,23 +257,57 @@ impl ReplaceConditionInputs for DocumentReplaceTransitionAction { } } } - let mut data: Vec<(Value, Value)> = written - .iter() - .map(|(property, value)| (Value::Text(property.clone()), value.clone())) - .collect(); - data.push(( - Value::Text(STORED_DOCUMENT_KEY.to_string()), - Value::Map( - stored - .into_iter() - .map(|(property, value)| (Value::Text(property), value)) - .collect(), + stored + } + + fn stored_version_read_by<'r>( + &self, + rules: impl Iterator, + ) -> Option { + let (mut reads_stored, mut reads_properties) = (false, false); + for rule in rules { + reads_stored |= rule.reads_stored(); + reads_properties |= rule.reads_stored_properties(); + } + let system = self + .stored_system_values() + .filter(|_| reads_stored)? + .clone(); + Some(if reads_properties { + StoredVersion::Present(Box::new(StoredDocument { + properties: Some(self.stored_properties()), + system, + })) + } else { + StoredVersion::without_properties(system) + }) + } + + fn condition_inputs( + &self, + owner_id: Identifier, + stored_system: Option<&StoredSystemValues>, + ) -> (Value, DocumentSystemValues) { + let data = Value::from(self.data().clone()); + let Some(stored_system) = stored_system else { + return (data, self.condition_system_values(owner_id, None)); + }; + // The stored properties go into the data, so the system values carry + // the rest alone + ( + data_with_stored_properties(data, Value::from(self.stored_properties())), + self.condition_system_values( + owner_id, + Some(StoredVersion::without_properties(stored_system.clone())), ), - )); - Value::Map(data) + ) } - fn condition_system_values(&self, owner_id: Identifier) -> DocumentSystemValues { + fn condition_system_values( + &self, + owner_id: Identifier, + stored: Option, + ) -> DocumentSystemValues { DocumentSystemValues { owner_id: Some(owner_id), created_at: self.created_at(), @@ -251,7 +319,11 @@ impl ReplaceConditionInputs for DocumentReplaceTransitionAction { created_at_core_block_height: self.created_at_core_block_height(), updated_at_core_block_height: self.updated_at_core_block_height(), transferred_at_core_block_height: self.transferred_at_core_block_height(), + revision: Some(self.revision()), aggregates: None, + consensus: false, + stored, + changed_fields: None, referenced_documents: false, } } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_transfer_transition_action/advanced_structure_v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_transfer_transition_action/advanced_structure_v0/mod.rs index de758205c71..d46e750634a 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_transfer_transition_action/advanced_structure_v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_transfer_transition_action/advanced_structure_v0/mod.rs @@ -1,4 +1,4 @@ -use dpp::data_contract::document_type::property_constraints::{DocumentSystemValues, SystemChange}; +use dpp::data_contract::document_type::property_constraints::{DocumentSystemValues, StoredVersion, SystemChange}; use dpp::consensus::basic::document::{InvalidDocumentTransitionActionError, InvalidDocumentTypeError}; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; @@ -70,12 +70,21 @@ impl DocumentTransferTransitionActionStructureValidationV0 for DocumentTransferT // `propertyConstraints` that read them: the stored properties met every rule when // they were written, and these are all this action changes that a rule reads. A // `countOf` or `sumOf` that depends on the owner reads the total the action read - // from state, as it will be once the document changes hands. + // from state, as it will be once the document changes hands. A path through `$old.` + // reads the document before the transfer: the same properties, its previous owner, + // transfer and revision, which the transformer attached when a rule the change can + // break reads them. The properties are the written ones, which the judging reads + // there, so none is copied document_type .validate_property_constraints_for_system_change( self.document().properties(), &DocumentSystemValues { aggregates: Some(self.property_constraint_aggregates().clone()), + consensus: true, + stored: self + .stored_system_values() + .cloned() + .map(StoredVersion::without_properties), ..DocumentSystemValues::of_document(self.document()) }, SystemChange::Transfer, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_update_price_transition_action/advanced_structure_v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_update_price_transition_action/advanced_structure_v0/mod.rs index c86518e1e70..6c954d86399 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_update_price_transition_action/advanced_structure_v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_update_price_transition_action/advanced_structure_v0/mod.rs @@ -2,7 +2,7 @@ use dpp::consensus::basic::document::{InvalidDocumentTransitionActionError, Inva use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dpp::data_contract::document_type::methods::DocumentTypeV0Methods; -use dpp::data_contract::document_type::property_constraints::{DocumentSystemValues, SystemChange}; +use dpp::data_contract::document_type::property_constraints::{DocumentSystemValues, StoredVersion, SystemChange}; use dpp::document::DocumentV0Getters; use dpp::validation::SimpleConsensusValidationResult; use drive::state_transition_action::batch::batched_transition::document_transition::document_base_transition_action::DocumentBaseTransitionActionAccessorsV0; @@ -53,12 +53,21 @@ impl DocumentUpdatePriceTransitionActionStructureValidationV0 // reading them: the stored properties met every rule when they were written, // and those times and heights are all this action changes that a rule reads. // Such a rule reading a `countOf` or `sumOf` too reads the total the action - // read from state. + // read from state. A path through `$old.` reads the document before the price + // update: the same properties, its previous update and revision, which the + // transformer attached when a rule the change can break reads them. The + // properties are the written ones, which the judging reads there, so none is + // copied document_type .validate_property_constraints_for_system_change( self.document().properties(), &DocumentSystemValues { aggregates: Some(self.property_constraint_aggregates().clone()), + consensus: true, + stored: self + .stored_system_values() + .cloned() + .map(StoredVersion::without_properties), ..DocumentSystemValues::of_document(self.document()) }, SystemChange::PriceUpdate, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/distinct_from.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/distinct_from.rs index 2bd19897209..cc779e6b939 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/distinct_from.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/distinct_from.rs @@ -532,7 +532,7 @@ mod distinct_from_tests { creator_id: None, moderated_at: None, moderated_by: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }); let before = action @@ -613,14 +613,14 @@ mod distinct_from_tests { let transfer = DocumentTransferTransitionAction::V0(DocumentTransferTransitionActionV0 { base: base(), document: transferred.clone(), - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }); let purchase = DocumentPurchaseTransitionAction::V0(DocumentPurchaseTransitionActionV0 { base: base(), document: transferred.clone(), original_owner_id: fixture.identity.id(), price: 1, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }); for (name, before, at) in [ diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/encrypted_for.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/encrypted_for.rs index 1d61e3a6d57..95bb3fd2f9b 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/encrypted_for.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/encrypted_for.rs @@ -461,7 +461,7 @@ mod encrypted_for_tests { creator_id: None, moderated_at: None, moderated_by: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }); let before = action diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/generated_from.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/generated_from.rs index 01afc3c178d..57c77833125 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/generated_from.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/generated_from.rs @@ -901,7 +901,7 @@ mod generated_from_tests { creator_id: None, moderated_at: None, moderated_by: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }) }; diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/max_bytes.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/max_bytes.rs index 46a8978d2d3..cd1cafb0132 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/max_bytes.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/max_bytes.rs @@ -397,7 +397,7 @@ mod max_bytes_tests { creator_id: None, moderated_at: None, moderated_by: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }) }; let platform_version_13 = diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/property_constraints.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/property_constraints.rs index 0655af2c117..3bafcc32cca 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/property_constraints.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/property_constraints.rs @@ -14,6 +14,7 @@ use super::*; mod property_constraints_tests { use super::*; use crate::execution::validation::state_transition::batch::action_validation::document::document_replace_transition_action::DocumentReplaceTransitionActionValidation; + use crate::execution::validation::state_transition::batch::action_validation::document::document_update_price_transition_action::DocumentUpdatePriceTransitionActionValidation; use crate::execution::validation::state_transition::tests::setup_identity_without_adding_it; use crate::rpc::core::MockCoreRPCLike; use crate::test::helpers::setup::TempPlatform; @@ -33,6 +34,7 @@ mod property_constraints_tests { use dpp::tokens::gas_fees_paid_by::GasFeesPaidBy; use drive::state_transition_action::batch::batched_transition::document_transition::document_base_transition_action::{DocumentBaseTransitionAction, DocumentBaseTransitionActionV0}; use drive::state_transition_action::batch::batched_transition::document_transition::document_replace_transition_action::{DocumentReplaceTransitionAction, DocumentReplaceTransitionActionV0}; + use drive::state_transition_action::batch::batched_transition::document_transition::document_update_price_transition_action::{DocumentUpdatePriceTransitionAction, DocumentUpdatePriceTransitionActionV0}; use drive::util::storage_flags::StorageFlags; use simple_signer::signer::SimpleSigner; use std::collections::{BTreeMap, BTreeSet}; @@ -369,20 +371,27 @@ mod property_constraints_tests { } } - /// The fixture over [`timed_offer_schema`] with an offer created at [`NOW`], - /// block 20, ending a day later. - async fn timed_offer() -> OfferFixture { - let mut fixture = OfferFixture::with_schema(timed_offer_schema()); + /// The fixture over `schema` with an offer created at [`NOW`], block 20, + /// `fill` setting what the type adds to [`set_valid_offer`]'s integers. + async fn created_offer(schema: Value, fill: impl FnOnce(&mut Document)) -> OfferFixture { + let mut fixture = OfferFixture::with_schema(schema); fixture.block_info = at_block(NOW, 20); assert_matches!( - fixture - .create(|document| document.set("endsAt", Value::U64(NOW + DAY_MS))) - .await, + fixture.create(fill).await, StateTransitionExecutionResult::SuccessfulExecution { .. } ); fixture } + /// The fixture over [`timed_offer_schema`] with an offer created at [`NOW`], + /// block 20, ending a day later. + async fn timed_offer() -> OfferFixture { + created_offer(timed_offer_schema(), |document| { + document.set("endsAt", Value::U64(NOW + DAY_MS)) + }) + .await + } + /// A mutable, transferable `offer` type with the integers /// [`set_valid_offer`] fills and three typed arrays, of `labels`, of /// `members` and of `tiers`, with three rules looking among them: @@ -1806,7 +1815,7 @@ mod property_constraints_tests { creator_id: None, moderated_at: None, moderated_by: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }); let before = action @@ -1832,6 +1841,82 @@ mod property_constraints_tests { ); } + /// The price update structure dispatcher on both sides of the gate: + /// generation 0 gained the `propertyConstraints` judgement of a price update + /// in place, so at protocol version 13 it must still accept the action (the + /// dpp gate is `None` there), and at 14 refuse one breaking a rule reading + /// `$revision`, which a price update moves. Built by hand the way the + /// transformer builds it. + #[test] + fn should_not_judge_property_constraints_on_a_price_update_before_protocol_version_14() { + let platform_version = PlatformVersion::latest(); + let fixture = OfferFixture::with_schema(stored_offer_schema(platform_value!({ + "propertyConstraints": { + "neverRepriced": { "lessThanOrEqual": ["$revision", 1] } + } + }))); + + let (_, contract_fetch_info) = fixture + .platform + .drive + .get_contract_with_fetch_info_and_fee( + fixture.contract.id().to_buffer(), + None, + false, + None, + platform_version, + ) + .expect("expected to fetch the contract"); + let contract_fetch_info = contract_fetch_info.expect("the contract is in state"); + let mut document: Document = dpp::document::DocumentV0 { + id: Identifier::from([0xAB; 32]), + owner_id: fixture.identity.id(), + revision: Some(2), + created_at: Some(NOW), + updated_at: Some(NOW + DAY_MS), + transferred_at: Some(NOW), + ..Default::default() + } + .into(); + set_valid_offer(&mut document); + + let action = + DocumentUpdatePriceTransitionAction::V0(DocumentUpdatePriceTransitionActionV0 { + base: DocumentBaseTransitionAction::V0(DocumentBaseTransitionActionV0 { + id: document.id(), + identity_contract_nonce: 2, + document_type_name: "offer".to_string(), + data_contract: contract_fetch_info, + token_cost: None, + shielded_token_payment: None, + gas_fees_paid_by: GasFeesPaidBy::default(), + contract_gas_fees_paid_by: GasFeesPaidBy::default(), + declared_action_fee: None, + }), + document, + property_constraint_reads: Default::default(), + }); + + let before = action + .validate_structure(PlatformVersion::get(13).expect("platform version 13 should exist")) + .expect("structure validation should run"); + assert!( + before.is_valid(), + "structure generation 0 must not judge propertyConstraints: {:?}", + before.errors + ); + + let at = action + .validate_structure(platform_version) + .expect("structure validation should run"); + assert_matches!( + at.errors.as_slice(), + [ConsensusError::BasicError(BasicError::DocumentPropertyConstraintViolatedError(e))] + if e.constraint() == "neverRepriced" + && e.violation() == PropertyConstraintViolation::NotMet + ); + } + /// Sizes read by real creates: a title too long in characters, one short /// enough in characters but too long in bytes, more tags than the quantity /// and a signature of the wrong length are each refused with the rule they @@ -2825,6 +2910,227 @@ mod property_constraints_tests { assert_eq!(fixture.stored_offers().len(), 1); } + const HOUR_MS: u64 = 3_600_000; + + /// A mutable, transferable and purchasable `offer` type recording its + /// creation, update and transfer times, with the integers + /// [`set_valid_offer`] fills and `doctype` added at its top level: its + /// `propertyConstraints`, which read the stored version through `$old.`, + /// or its `immutable` entries. + fn stored_offer_schema(doctype: Value) -> Value { + let schema = platform_value!({ + "type": "object", + "documentsMutable": true, + "transferable": 1, + "tradeMode": 1, + "properties": { + "price": { "type": "integer", "minimum": 0, "position": 0 }, + "fee": { "type": "integer", "minimum": 0, "position": 1 }, + "quantity": { "type": "integer", "minimum": 0, "position": 2 }, + "deposit": { "type": "integer", "minimum": 0, "position": 3 } + }, + "required": [ + "price", + "fee", + "quantity", + "deposit", + "$createdAt", + "$updatedAt", + "$transferredAt" + ], + "additionalProperties": false + }); + let Value::Map(entries) = doctype else { + panic!("the doctype keys are an object"); + }; + entries.into_iter().fold(schema, |schema, (key, value)| { + with_keys(schema, [(key.as_text().expect("a text key"), value)]) + }) + } + + /// The fixture over [`stored_offer_schema`] with an offer created at + /// [`NOW`], block 20. + async fn stored_offer(doctype: Value) -> OfferFixture { + created_offer(stored_offer_schema(doctype), |_| {}).await + } + + /// A replace is judged with the document it replaces under `$old.`: its + /// properties, and the update time the replace overwrites, which the + /// transformer keeps beside the action. + #[tokio::test] + async fn should_judge_a_replace_against_the_document_it_replaces() { + let mut fixture = stored_offer(platform_value!({ + "propertyConstraints": { + "depositNeverDrops": { + "greaterThanOrEqual": ["deposit", { "ifAbsent": ["$old.deposit", 0] }] + }, + "editsAnHourApart": { + "greaterThanOrEqual": [ + { "subtract": ["$updatedAt", "$old.$updatedAt"] }, + HOUR_MS + ] + } + } + })) + .await; + + fixture.block_info = at_block(NOW + 2 * HOUR_MS, 21); + assert_matches!( + fixture + .replace(|document| document.set("deposit", Value::U64(300))) + .await, + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + + // Ten minutes after the last update + fixture.block_info = at_block(NOW + 2 * HOUR_MS + 600_000, 22); + let result = fixture + .replace(|document| document.set("deposit", Value::U64(400))) + .await; + expect_violated( + result, + "editsAnHourApart", + PropertyConstraintViolation::NotMet, + ); + + fixture.block_info = at_block(NOW + 4 * HOUR_MS, 23); + let result = fixture + .replace(|document| document.set("deposit", Value::U64(250))) + .await; + expect_violated( + result, + "depositNeverDrops", + PropertyConstraintViolation::NotMet, + ); + assert_matches!( + fixture + .replace(|document| document.set("deposit", Value::U64(500))) + .await, + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + assert_eq!(integer(&fixture.stored_offers()[0], "deposit"), Some(500)); + } + + /// A transfer and a purchase are judged with the document before them under + /// `$old.`: its owner and its transfer time, which the write overwrites. A + /// rule comparing properties alone is not judged by them, nor by a price + /// update: none changes a property, so it would compare each with itself. + #[tokio::test] + async fn should_judge_a_transfer_and_a_purchase_against_the_document_before_them() { + let rules = platform_value!({ + "propertyConstraints": { + "heldADay": { + "ifThen": [ + { "notEqual": ["$ownerId", "$old.$ownerId"] }, + { + "greaterThanOrEqual": [ + { "subtract": ["$transferredAt", "$old.$transferredAt"] }, + DAY_MS + ] + } + ] + }, + "quantityRisesOnEveryEdit": { "greaterThan": ["quantity", "$old.quantity"] } + } + }); + + let mut fixture = stored_offer(rules.clone()).await; + let recipient = Identifier::new([9; 32]); + fixture.block_info = at_block(NOW + HOUR_MS, 21); + expect_violated( + fixture.transfer(recipient).await, + "heldADay", + PropertyConstraintViolation::NotMet, + ); + fixture.block_info = at_block(NOW + 2 * DAY_MS, 22); + assert_matches!( + fixture.transfer(recipient).await, + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + assert_eq!(fixture.stored_offers()[0].owner_id(), recipient); + + let mut fixture = stored_offer(rules).await; + fixture.block_info = at_block(NOW + 60_000, 21); + fixture.set_price(500).await; + let early_buyer = fixture.other_identity(960); + fixture.block_info = at_block(NOW + HOUR_MS, 22); + expect_violated( + fixture.purchase_by(&early_buyer, 500).await, + "heldADay", + PropertyConstraintViolation::NotMet, + ); + let buyer = fixture.other_identity(961); + fixture.block_info = at_block(NOW + 2 * DAY_MS, 23); + assert_matches!( + fixture.purchase_by(&buyer, 500).await, + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + assert_eq!(fixture.stored_offers()[0].owner_id(), buyer.0.id()); + } + + /// `$revision` counts every write: a replace, a price update and a + /// transfer each move it, and each is judged against a rule reading it. + #[tokio::test] + async fn should_judge_every_write_moving_the_revision() { + let rules = platform_value!({ + "propertyConstraints": { "atMostThreeWrites": { "lessThanOrEqual": ["$revision", 3] } } + }); + let mut fixture = stored_offer(rules.clone()).await; + assert_matches!( + fixture + .replace(|document| document.set("deposit", Value::U64(300))) + .await, + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + fixture.set_price(500).await; + expect_violated( + fixture.transfer(Identifier::new([9; 32])).await, + "atMostThreeWrites", + PropertyConstraintViolation::NotMet, + ); + + let mut fixture = stored_offer(rules).await; + fixture.set_price(500).await; + fixture.set_price(400).await; + expect_violated( + fixture.try_set_price(300).await, + "atMostThreeWrites", + PropertyConstraintViolation::NotMet, + ); + } + + /// An `immutable` condition reads the stored update time too: `fee` is + /// frozen for an hour after each update. + #[tokio::test] + async fn should_freeze_a_property_by_the_stored_update_time() { + let mut fixture = stored_offer(platform_value!({ + "immutable": [{ + "property": "fee", + "when": { + "lessThan": [{ "subtract": ["$updatedAt", "$old.$updatedAt"] }, HOUR_MS] + } + }] + })) + .await; + + fixture.block_info = at_block(NOW + 2 * HOUR_MS, 21); + assert_matches!( + fixture + .replace(|document| document.set("fee", Value::U64(20))) + .await, + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + fixture.block_info = at_block(NOW + 2 * HOUR_MS + 600_000, 22); + let result = fixture + .replace(|document| document.set("fee", Value::U64(30))) + .await; + let StateTransitionExecutionResult::PaidConsensusError { error, .. } = result else { + panic!("expected a paid consensus error, got {result:?}"); + }; + assert_eq!(error.code(), 40128, "{error:?}"); + assert_eq!(integer(&fixture.stored_offers()[0], "fee"), Some(20)); + } + /// The totals a rule reads leave out the other writes of its batch, which is /// sound only while a document batch carries one transition: raising the /// limit needs the batch's own writes added to them. diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/referenced_rules.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/referenced_rules.rs index 848a7fd9bb5..8c17af1901a 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/referenced_rules.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/referenced_rules.rs @@ -197,6 +197,67 @@ mod referenced_rules_tests { assert_where_refused(&result, "{ \"in\": [\"open\", \"extended\"] }"); } + /// A rule reading both the referenced document and, through `$old.`, the + /// document a replace replaces: each raise must top the stored amount by + /// the auction's reserve, a create topping nothing, as its stored amount + /// is absent. A replace is refused or accepted by both values together, + /// the auction read as it is at each replace. + #[tokio::test] + async fn should_judge_a_rule_reading_the_referenced_and_the_stored_document() { + let mut setup = ReferenceTestSetup::new(CONTRACT_PATH, 6110); + let (mut auction, result) = setup + .create( + "auction", + &[ + ("reservePrice", Value::U32(100)), + ("status", Value::Text("open".to_string())), + ], + ) + .await; + assert_successful(&result, "the auction must be created"); + + // A create has no stored amount: the reserve alone + let (_, result) = setup + .create( + "raise", + &[ + ("auctionId", id_value(&auction)), + ("amount", Value::U32(50)), + ], + ) + .await; + assert_rule_broken(&result, "raisesByTheReserve"); + let (mut raise, result) = setup + .create( + "raise", + &[ + ("auctionId", id_value(&auction)), + ("amount", Value::U32(120)), + ], + ) + .await; + assert_successful(&result, "a first raise over the reserve holds"); + + // Over the reserve, yet not 100 over the stored 120 + raise.set("amount", Value::U32(200)); + let result = setup.replace("raise", &mut raise).await; + assert_rule_broken(&result, "raisesByTheReserve"); + raise.set("amount", Value::U32(220)); + let result = setup.replace("raise", &mut raise).await; + assert_successful(&result, "a raise 100 over the stored 120 holds"); + + // The reserve as it is now, over the stored 220 + auction.set("reservePrice", Value::U32(10)); + let result = setup.replace("auction", &mut auction).await; + assert_successful(&result, "the auction's owner lowers the reserve"); + raise.set("amount", Value::U32(229)); + let result = setup.replace("raise", &mut raise).await; + assert_rule_broken(&result, "raisesByTheReserve"); + raise.set("amount", Value::U32(230)); + let result = setup.replace("raise", &mut raise).await; + assert_successful(&result, "a raise 10 over the stored 220 holds"); + } + /// The `where` entries that are not an equality: a literal the referenced /// side must equal, a value it must differ from, and an ordering bounded by /// the time of the write, which holds only when both sides have a value. diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/mod.rs index 68687ef3f0f..2e21c2fa3eb 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/mod.rs @@ -29,7 +29,7 @@ mod retraction; use contract_moderation_gate::{BatchTransitionContractModerationGate, ContractModerationRefusal}; use moderator_fields::judge_moderator_field_write; -use property_constraint_aggregates::attach_property_constraint_aggregates; +use property_constraint_aggregates::attach_property_constraint_reads; use retraction::judge_barred_replace; use std::borrow::Cow; use std::collections::btree_map::Entry; @@ -967,8 +967,9 @@ impl BatchTransitionInternalTransformerV0 for BatchTransition { ); } - // The `countOf` and `sumOf` totals the rules judging the write read - attach_property_constraint_aggregates( + // The `countOf` and `sumOf` totals the rules judging the write read, and the + // stored version they read through `$old.` + attach_property_constraint_reads( drive, &data_contract_fetch_info.contract, &mut document_create_action, @@ -1058,6 +1059,7 @@ impl BatchTransitionInternalTransformerV0 for BatchTransition { if let Some(error) = judge_barred_replace( &data_contract_fetch_info.contract, &document_replace_action, + original_document, owner_id, bar, ) { @@ -1090,8 +1092,9 @@ impl BatchTransitionInternalTransformerV0 for BatchTransition { ); } - // The `countOf` and `sumOf` totals the rules judging the write read - attach_property_constraint_aggregates( + // The `countOf` and `sumOf` totals the rules judging the write read, and the + // stored version they read through `$old.` + attach_property_constraint_reads( drive, &data_contract_fetch_info.contract, &mut document_replace_action, @@ -1207,8 +1210,9 @@ impl BatchTransitionInternalTransformerV0 for BatchTransition { execution_context .add_operation(ValidationOperation::PrecalculatedOperation(fee_result)); - // The `countOf` and `sumOf` totals the rules judging the write read - attach_property_constraint_aggregates( + // The `countOf` and `sumOf` totals the rules judging the write read, and the + // stored version they read through `$old.` + attach_property_constraint_reads( drive, &data_contract_fetch_info.contract, &mut document_transfer_action, @@ -1285,8 +1289,9 @@ impl BatchTransitionInternalTransformerV0 for BatchTransition { execution_context .add_operation(ValidationOperation::PrecalculatedOperation(fee_result)); - // The `countOf` and `sumOf` totals the rules judging the write read - attach_property_constraint_aggregates( + // The `countOf` and `sumOf` totals the rules judging the write read, and the + // stored version they read through `$old.` + attach_property_constraint_reads( drive, &data_contract_fetch_info.contract, &mut document_update_price_action, @@ -1401,8 +1406,9 @@ impl BatchTransitionInternalTransformerV0 for BatchTransition { execution_context .add_operation(ValidationOperation::PrecalculatedOperation(fee_result)); - // The `countOf` and `sumOf` totals the rules judging the write read - attach_property_constraint_aggregates( + // The `countOf` and `sumOf` totals the rules judging the write read, and the + // stored version they read through `$old.` + attach_property_constraint_reads( drive, &data_contract_fetch_info.contract, &mut document_purchase_action, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/property_constraint_aggregates.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/property_constraint_aggregates.rs index 42d8b048322..ebd637fb3ea 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/property_constraint_aggregates.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/property_constraint_aggregates.rs @@ -7,7 +7,10 @@ use crate::execution::types::state_transition_execution_context::{ use dpp::block::block_info::BlockInfo; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV2Getters; -use dpp::data_contract::document_type::property_constraints::{AggregateRead, SystemChange}; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, SystemChange, +}; +use dpp::data_contract::document_type::DocumentTypeRef; use dpp::data_contract::DataContract; use dpp::document::{Document, DocumentV0Getters}; use dpp::platform_value::{Identifier, Value}; @@ -59,9 +62,18 @@ struct VersionData<'a> { /// create or a replace of a document of `writer`'s, stored as `stored` before /// (`None` for a create), or a transfer, a purchase or a price update of `stored`, /// judged by the rules the change can break. Any other action, a refused write -/// included, reads nothing. +/// included, reads nothing. To the action of a write replacing `stored` it also +/// hands the owner, times, heights and revision `stored` holds, when what judges +/// the write reads the stored version through `$old.` ([`reads_stored_version`]): +/// the action keeps only some of them (a replace overwrites the update's, a +/// transfer the owner and the transfer's). Taken from +/// the document already fetched, so nothing more is read or billed. Added in place +/// to the shipped transformer at protocol version 14 and inert before it: no rule or +/// condition exists there (`parse_property_constraints` is `None`, and meta-schemas +/// before v3 refuse a condition), so nothing reads the stored version and none is +/// attached. #[allow(clippy::too_many_arguments)] -pub(super) fn attach_property_constraint_aggregates( +pub(super) fn attach_property_constraint_reads( drive: &Drive, contract: &DataContract, result: &mut ConsensusValidationResult, @@ -75,6 +87,16 @@ pub(super) fn attach_property_constraint_aggregates( let Some(BatchedTransitionAction::DocumentAction(action)) = result.data.as_mut() else { return Ok(()); }; + let stored_document = stored; + let stored_system_values = |document_type_name: &str, change: Option| { + stored_document + .filter(|_| { + contract + .document_type_for_name(document_type_name) + .is_ok_and(|document_type| reads_stored_version(document_type, change)) + }) + .map(StoredSystemValues::of_document) + }; let stored = stored.map(DocumentVersion::of); // A create or a replace judges the rules reading a referenced document, // once its references hold; a transfer, a purchase or a price update does @@ -112,6 +134,9 @@ pub(super) fn attach_property_constraint_aggregates( }; let aggregates = read(action.base().document_type_name(), written, None)?; action.set_property_constraint_aggregates(aggregates); + if let Some(values) = stored_system_values(action.base().document_type_name(), None) { + action.set_stored_system_values(values); + } } // The action's document carries its new owner DocumentTransitionAction::TransferAction(action) => { @@ -121,6 +146,12 @@ pub(super) fn attach_property_constraint_aggregates( Some(SystemChange::Transfer), )?; action.set_property_constraint_aggregates(aggregates); + if let Some(values) = stored_system_values( + action.base().document_type_name(), + Some(SystemChange::Transfer), + ) { + action.set_stored_system_values(values); + } } DocumentTransitionAction::PurchaseAction(action) => { let aggregates = read( @@ -129,6 +160,12 @@ pub(super) fn attach_property_constraint_aggregates( Some(SystemChange::Transfer), )?; action.set_property_constraint_aggregates(aggregates); + if let Some(values) = stored_system_values( + action.base().document_type_name(), + Some(SystemChange::Transfer), + ) { + action.set_stored_system_values(values); + } } DocumentTransitionAction::UpdatePriceAction(action) => { let aggregates = read( @@ -137,6 +174,12 @@ pub(super) fn attach_property_constraint_aggregates( Some(SystemChange::PriceUpdate), )?; action.set_property_constraint_aggregates(aggregates); + if let Some(values) = stored_system_values( + action.base().document_type_name(), + Some(SystemChange::PriceUpdate), + ) { + action.set_stored_system_values(values); + } } DocumentTransitionAction::DeleteAction(_) | DocumentTransitionAction::IndexOnlyDeleteAction(_) => {} @@ -144,9 +187,33 @@ pub(super) fn attach_property_constraint_aggregates( Ok(()) } +/// Whether what judges a write of a document of `document_type` reads the stored version through +/// `$old.`, so that the write needs its owner, times, heights and revision: for a replace +/// (`change` `None`), a `propertyConstraints` rule or an `immutable` entry's condition; for a +/// transfer, a purchase or a price update, a rule `change` can break, the only ones it is +/// judged against. A `retractedWhen` condition is judged on the stored document itself, before +/// they are attached. +pub(crate) fn reads_stored_version( + document_type: DocumentTypeRef, + change: Option, +) -> bool { + match change { + None => document_type + .property_constraints() + .values() + .chain(document_type.immutable_field_conditions().values()) + .any(|rule| rule.reads_stored()), + Some(change) => document_type + .property_constraints() + .values() + .any(|rule| rule.reads_change(change) && rule.reads_stored()), + } +} + /// Reads the `countOf` and `sumOf` totals the `propertyConstraints` rules of the document type /// `document_type_name` read for a moderator's field change, which stores `written` in place of -/// `stored`, the same document under the same owner: judged as a replace is, by every rule. +/// `stored`, the same document under the same owner: judged by every rule reading a total, as a +/// replace is. #[allow(clippy::too_many_arguments)] pub(crate) fn read_property_constraint_aggregates_for_moderator_change( drive: &Drive, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/retraction.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/retraction.rs index c02795887a5..3c72e130fe5 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/retraction.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/transformer/v0/retraction.rs @@ -2,7 +2,9 @@ use crate::execution::validation::state_transition::batch::action_validation::do use dpp::consensus::ConsensusError; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV2Getters; +use dpp::data_contract::document_type::property_constraints::StoredSystemValues; use dpp::data_contract::DataContract; +use dpp::document::Document; use dpp::platform_value::Identifier; use dpp::prelude::ConsensusValidationResult; use drive::state_transition_action::batch::batched_transition::document_transition::document_base_transition_action::DocumentBaseTransitionActionAccessorsV0; @@ -18,7 +20,9 @@ use drive::state_transition_action::batch::batched_transition::BatchedTransition /// already refused, whose own refusal stands. /// /// The condition is judged as an `immutable` entry's is, on the document the replace writes (its -/// `$updatedAt` this block's time), with the stored one under `$old`. Every other rule of the +/// `$updatedAt` this block's time), with `stored`, the stored document, read through `$old.`: its +/// properties as the action rebuilds them, its owner, times, heights and revision as stored, since +/// the transformer attaches those to the action only afterwards. Every other rule of the /// type still judges the replace afterwards. Judged in the transformer, after the stored /// document is fetched, so the mempool refuses a barred owner's replace as a block does. Added in /// place to the shipped transformer at protocol version 14 and inert before it: the gate, and so @@ -26,6 +30,7 @@ use drive::state_transition_action::batch::batched_transition::BatchedTransition pub(super) fn judge_barred_replace( contract: &DataContract, result: &ConsensusValidationResult, + stored: &Document, owner_id: Identifier, bar: &ConsensusError, ) -> Option { @@ -42,12 +47,9 @@ pub(super) fn judge_barred_replace( .document_type_optional_for_name(action.base().document_type_name()) .and_then(|document_type| { document_type.retracted_when().map(|condition| { - condition - .holds( - &action.condition_data(), - &action.condition_system_values(owner_id), - ) - .unwrap_or(false) + let (data, system) = action + .condition_inputs(owner_id, Some(&StoredSystemValues::of_document(stored))); + condition.holds(&data, &system).unwrap_or(false) }) }) .unwrap_or(false); diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/state/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/state/v0/mod.rs index 1736a2b27dc..0b96711388d 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/state/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/state/v0/mod.rs @@ -53,7 +53,9 @@ use dpp::data_contract::config::moderation::{ use dpp::data_contract::config::v2::DataContractConfigGettersV2; use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters}; use dpp::data_contract::document_type::methods::{DocumentTypeBasicMethods, DocumentTypeV0Methods}; -use dpp::data_contract::document_type::property_constraints::DocumentSystemValues; +use dpp::data_contract::document_type::property_constraints::{ + DocumentSystemValues, StoredDocument, StoredSystemValues, StoredVersion, SystemChange, +}; use dpp::data_contract::document_type::DocumentTypeRef; use dpp::data_contract::errors::DataContractError; use dpp::data_contract::validate_document::DataContractDocumentValidationMethodsV0; @@ -1363,9 +1365,10 @@ fn document_deletion_context( /// the contract (see [`Moderators`]: a seated team must also hold `changeDocumentFields` on the /// type) for a reason a seated team's proposal lists, the document exists and has not expired, /// and the document as changed is still one of its type: its schema, the shapes of its -/// `encryptedFor` properties, its `distinctFrom` properties, its `propertyConstraints` with the -/// totals they read, and its unique indexes. Every refusal is paid for by bumping the signer's -/// contract nonce. +/// `encryptedFor` properties, its `distinctFrom` properties, the rules of its +/// `propertyConstraints` the change can break (those reading a field it changes, of either +/// version, `$revision` or a total, the totals read as they will be), and its unique indexes. +/// Every refusal is paid for by bumping the signer's contract nonce. /// /// The fields are the moderators', not the document's owner's, so whoever owns the document, /// the contract owner and the moderators included, is no protection. Nothing the document type @@ -1573,8 +1576,11 @@ fn transform_document_fields_change_v0( changed.set_moderated_by(Some(moderator_id)); // The changed document is judged as a replace judges one: the owner is the document's, the - // times and heights are the ones it keeps, and the `countOf` and `sumOf` totals are read as - // they will be once it is stored in place of the one read. + // times and heights are the ones it keeps, its revision the next, the `countOf` and `sumOf` + // totals are read as they will be once it is stored in place of the one read, and a path + // through `$old.` reads the one read. Only the rules reading a field the change writes, + // `$revision` or a total are judged: every other rule reads what the document held when its + // owner last wrote it, and gave its verdict then, as rules never change once registered. let aggregates = read_property_constraint_aggregates_for_moderator_change( platform.drive, contract, @@ -1586,19 +1592,15 @@ fn transform_document_fields_change_v0( tx, platform_version, )?; + // The document read is not needed again, so its properties move into the stored version let system = DocumentSystemValues { - owner_id: Some(changed.owner_id()), - created_at: changed.created_at(), - updated_at: changed.updated_at(), - transferred_at: changed.transferred_at(), - created_at_block_height: changed.created_at_block_height(), - updated_at_block_height: changed.updated_at_block_height(), - transferred_at_block_height: changed.transferred_at_block_height(), - created_at_core_block_height: changed.created_at_core_block_height(), - updated_at_core_block_height: changed.updated_at_core_block_height(), - transferred_at_core_block_height: changed.transferred_at_core_block_height(), aggregates: Some(aggregates), - referenced_documents: false, + consensus: true, + stored: Some(StoredVersion::Present(Box::new( + StoredDocument::of_owned_document(stored), + ))), + changed_fields: Some(changed_fields.clone()), + ..DocumentSystemValues::of_document(&changed) }; // Each check runs only on a document the previous ones passed, as a replace's do: the later // two read values the schema check makes well formed. @@ -1668,8 +1670,9 @@ fn transform_document_fields_change_v0( /// restored, block time is within the restore window after the removal, the bytes hash to what /// the record holds, the removal is no deletion the seated team approved together (those /// stand), no other document holds a value of one of the type's unique indexes, and the -/// restored document meets its type's `propertyConstraints` with the totals after its -/// insertion. Every refusal in a block is paid for by bumping the signer's contract nonce. +/// restored document meets the rules of its type's `propertyConstraints` reading a total, +/// with the totals after its insertion: the others read only what it held when last written. +/// Every refusal in a block is paid for by bumping the signer's contract nonce. /// /// The action carries the contract, the decoded document and the record marked restored, so /// Drive puts the document back and marks the record without reading again. Nothing the @@ -1926,7 +1929,10 @@ fn transform_document_restore_v0( // Contract moderation is inactive before protocol version 14, so this check cannot // alter earlier blocks. The hash pins the document's retained values, but other writes - // may have changed the totals its rules read while it was absent from the live trees. + // may have changed the totals its rules read while it was absent from the live trees: the + // rules reading one are judged again, a path through `$old.` reading the document as it + // comes back. Every other rule reads only what the document held when it was last written, + // and gave its verdict then, as rules never change once registered. if !document_type.property_constraints().is_empty() { let aggregates = read_property_constraint_aggregates_for_restore( platform.drive, @@ -1938,13 +1944,20 @@ fn transform_document_restore_v0( tx, platform_version, )?; + // A restore writes no property: `$old.` reads the document itself, the judging + // reading its properties from those written, so none is copied let system = DocumentSystemValues { aggregates: Some(aggregates), + consensus: true, + stored: Some(StoredVersion::without_properties( + StoredSystemValues::of_document(&document), + )), ..DocumentSystemValues::of_document(&document) }; - let result = document_type.validate_property_constraints( - &Value::from(document.properties()), + let result = document_type.validate_property_constraints_for_system_change( + document.properties(), &system, + SystemChange::Restore, platform_version, )?; if !result.is_valid() { diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/moderator_fields.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/moderator_fields.rs index 6dd1d14f565..272bb36670e 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/moderator_fields.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/moderator_fields.rs @@ -18,6 +18,7 @@ const JSON_SCHEMA: u32 = 10101; const DOCUMENT_PROPERTY_CONSTRAINT_VIOLATED: u32 = 10422; const NOTICE: &str = "notice"; const CARD: &str = "card"; +const BADGE: &str = "badge"; /// A report of a post, which its author can not replace, which moderators may delete, and /// whose `status` and `resolution` only they write, queried by who handled it last and when. @@ -107,6 +108,31 @@ fn card_schema() -> Value { }) } +/// A badge its owner retitles on every replace, whose `level` only moderators write and never +/// lower, written at most four times +fn badge_schema() -> Value { + platform_value!({ + "type": "object", + "moderatorAbilities": { "changeFields": ["level"] }, + "properties": { + "title": { "type": "string", "minLength": 1, "maxLength": 50, "position": 0 }, + "level": { "type": "integer", "minimum": 0, "maximum": 10, "position": 1 }, + }, + "required": ["title"], + "propertyConstraints": { + "atMostFourWrites": { "lessThanOrEqual": ["$revision", 4] }, + "levelNeverDrops": { + "greaterThanOrEqual": [ + { "ifAbsent": ["level", 0] }, + { "ifAbsent": ["$old.level", 0] } + ] + }, + "titleChangesOnEveryEdit": { "notEqual": ["title", "$old.title"] }, + }, + "additionalProperties": false, + }) +} + /// A contract whose owner and named moderator moderate posts, reports, tickets, notices and /// cards async fn setup() -> Setup { @@ -207,14 +233,19 @@ async fn create_ticket( .await } -/// A replacement of `document`, a ticket, by `actor`, its owner -async fn replace_ticket(setup: &Setup, actor: &Actor, document: Document) -> StateTransition { +/// A replacement of `document`, of the type `document_type_name`, by `actor`, its owner +async fn replacement_of( + setup: &Setup, + actor: &Actor, + document_type_name: &str, + document: Document, +) -> StateTransition { BatchTransition::new_document_replacement_transition_from_document( document, setup .contract - .document_type_for_name(TICKET) - .expect("expected the ticket type"), + .document_type_for_name(document_type_name) + .expect("expected the document type"), &actor.key, actor.contract_nonce(), 0, @@ -550,7 +581,7 @@ async fn should_let_only_moderators_write_those_fields_in_their_own_documents() assert_success(&setup.process(&create_ticket, &transaction)); ticket.set("slot", Value::U64(4)); ticket.increment_revision().expect("expected a revision"); - let sets_the_slot = replace_ticket(&setup, &setup.user, ticket.clone()).await; + let sets_the_slot = replacement_of(&setup, &setup.user, TICKET, ticket.clone()).await; assert_paid_with_code( &setup.process(&sets_the_slot, &transaction), DOCUMENT_MODERATOR_FIELD_NOT_WRITABLE, @@ -573,7 +604,7 @@ async fn should_let_only_moderators_write_those_fields_in_their_own_documents() let mut stale = ticket.clone(); stale.set("title", Value::Text("scanner".to_string())); stale.properties_mut().remove("slot"); - let stale_replace = replace_ticket(&setup, &setup.user, stale).await; + let stale_replace = replacement_of(&setup, &setup.user, TICKET, stale).await; assert_paid_with_code( &setup.process(&stale_replace, &transaction), INVALID_DOCUMENT_REVISION, @@ -586,7 +617,7 @@ async fn should_let_only_moderators_write_those_fields_in_their_own_documents() changes_the_slot .increment_revision() .expect("expected a revision"); - let replace = replace_ticket(&setup, &setup.user, changes_the_slot).await; + let replace = replacement_of(&setup, &setup.user, TICKET, changes_the_slot).await; assert_paid_with_code( &setup.process(&replace, &transaction), DOCUMENT_MODERATOR_FIELD_NOT_WRITABLE, @@ -596,7 +627,7 @@ async fn should_let_only_moderators_write_those_fields_in_their_own_documents() drops_the_slot .increment_revision() .expect("expected a revision"); - let replace = replace_ticket(&setup, &setup.user, drops_the_slot).await; + let replace = replacement_of(&setup, &setup.user, TICKET, drops_the_slot).await; assert_paid_with_code( &setup.process(&replace, &transaction), DOCUMENT_MODERATOR_FIELD_NOT_WRITABLE, @@ -606,7 +637,7 @@ async fn should_let_only_moderators_write_those_fields_in_their_own_documents() keeps_the_slot .increment_revision() .expect("expected a revision"); - let replace = replace_ticket(&setup, &setup.user, keeps_the_slot).await; + let replace = replacement_of(&setup, &setup.user, TICKET, keeps_the_slot).await; assert_success(&setup.process(&replace, &transaction)); let replaced = setup .stored_document(TICKET, ticket.id(), Some(&transaction)) @@ -1005,7 +1036,7 @@ async fn should_stamp_a_moderator_who_writes_the_fields_in_their_own_documents() .expect("expected the ticket"); renamed.set("title", Value::Text("scanner".to_string())); renamed.increment_revision().expect("expected a revision"); - let replace = replace_ticket(&setup, &setup.user, renamed).await; + let replace = replacement_of(&setup, &setup.user, TICKET, renamed).await; assert_success(&setup.process_at(&replace, BLOCK_TIME_MS + 3_000, &transaction)); let replaced = setup .stored_document(TICKET, ticket.id(), Some(&transaction)) @@ -1027,7 +1058,7 @@ async fn should_stamp_a_moderator_who_writes_the_fields_in_their_own_documents() .expect("expected the ticket"); reslotted.set("slot", Value::U64(7)); reslotted.increment_revision().expect("expected a revision"); - let replace = replace_ticket(&setup, &setup.moderator, reslotted).await; + let replace = replacement_of(&setup, &setup.moderator, TICKET, reslotted).await; assert_success(&setup.process_at(&replace, BLOCK_TIME_MS + 4_000, &transaction)); let mut retitled = setup .stored_document(TICKET, own.id(), Some(&transaction)) @@ -1036,7 +1067,7 @@ async fn should_stamp_a_moderator_who_writes_the_fields_in_their_own_documents() assert_eq!(retitled.moderated_by(), Some(setup.moderator.id())); retitled.set("title", Value::Text("chair".to_string())); retitled.increment_revision().expect("expected a revision"); - let replace = replace_ticket(&setup, &setup.moderator, retitled).await; + let replace = replacement_of(&setup, &setup.moderator, TICKET, retitled).await; assert_success(&setup.process_at(&replace, BLOCK_TIME_MS + 6_000, &transaction)); let kept = setup .stored_document(TICKET, own.id(), Some(&transaction)) @@ -1153,3 +1184,73 @@ async fn should_prove_a_whole_number_set_on_a_number_field() { let proved = setup.assert_change_proved(&weigh); assert_eq!(proved.get("weight"), Some(&Value::Float(2.0))); } + +/// A moderator's change of fields is judged only against the rules reading a field it changes, +/// of the document or of the stored version under `$old.`, `$revision`, which it moves, or a +/// total. `titleChangesOnEveryEdit` judges the owner's replaces and leaves the moderator's +/// changes alone, though they keep the title. +#[tokio::test] +async fn should_judge_a_field_change_by_the_rules_reading_what_it_changes() { + let setup = Setup::new_at_with( + Some(moderators_without_lists()), + PlatformVersion::latest(), + |contract| { + add_document_type(contract, POST, post_schema(true)); + add_document_type(contract, BADGE, badge_schema()); + }, + ) + .await; + let transaction = setup.platform.drive.grove.start_transaction(); + let (badge, create) = setup + .create_document_of_type_with(&setup.user, BADGE, |document| { + let properties = document.properties_mut(); + properties.clear(); + properties.insert("title".to_string(), Value::Text("first".to_string())); + }) + .await; + assert_success(&setup.process(&create, &transaction)); + let change_level = + |level: u64| change_action(BADGE, badge.id(), platform_value!({ "level": level })); + + let raise = setup.moderate(&setup.moderator, change_level(2)).await; + assert_success(&setup.process(&raise, &transaction)); + let lower = setup.moderate(&setup.moderator, change_level(1)).await; + assert_paid_with_code( + &setup.process(&lower, &transaction), + DOCUMENT_PROPERTY_CONSTRAINT_VIOLATED, + ); + let raise_again = setup.moderate(&setup.moderator, change_level(5)).await; + assert_success(&setup.process(&raise_again, &transaction)); + + // The owner's replace is judged against every rule: one keeping the title is refused + let stored = setup + .stored_document(BADGE, badge.id(), Some(&transaction)) + .expect("expected the badge"); + assert_eq!(stored.revision(), Some(3)); + let mut kept = stored.clone(); + kept.increment_revision().unwrap(); + let keeps_title = replacement_of(&setup, &setup.user, BADGE, kept).await; + assert_paid_with_code( + &setup.process(&keeps_title, &transaction), + DOCUMENT_PROPERTY_CONSTRAINT_VIOLATED, + ); + let mut retitled = stored; + retitled.set("title", Value::Text("second".to_string())); + retitled.increment_revision().unwrap(); + let retitle = replacement_of(&setup, &setup.user, BADGE, retitled).await; + assert_success(&setup.process(&retitle, &transaction)); + + // A fifth write is refused by the rule reading `$revision`, which the change moves + let fifth = setup.moderate(&setup.moderator, change_level(6)).await; + assert_paid_with_code( + &setup.process(&fifth, &transaction), + DOCUMENT_PROPERTY_CONSTRAINT_VIOLATED, + ); + let stored = setup + .stored_document(BADGE, badge.id(), Some(&transaction)) + .expect("expected the badge"); + assert_eq!(stored.revision(), Some(4)); + assert!(stored + .get("level") + .is_some_and(|level| level.equal_underlying_data(&Value::U64(5)))); +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/referenced_rules.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/referenced_rules.rs index fd64a68adf6..be8bcac7e0a 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/referenced_rules.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/referenced_rules.rs @@ -203,8 +203,10 @@ fn comment_schema() -> Value { }) } -/// A stall on a topic, kept to a hundred and one posts on it while it is -/// open, with a note only moderators write +/// A stall on a topic, written only while the topic is open, with a note +/// only moderators write. Its rule reads no total: registration refuses a rule +/// reading a referenced document beside one on a type keeping fields for its +/// moderators, whose change is judged against every rule reading a total fn stall_schema() -> Value { platform_value!({ "type": "object", @@ -220,12 +222,7 @@ fn stall_schema() -> Value { }, "required": ["topicId"], "propertyConstraints": { - "fewPosts": { - "lessThanOrEqual": [ - { "countOf": [THREAD_POST, { "topicId": "topicId" }] }, - { "add": [{ "referenced": ["topicId", "open"] }, 100] } - ] - } + "topicOpen": { "equal": [{ "referenced": ["topicId", "open"] }, 1] } }, "additionalProperties": false, }) @@ -585,13 +582,14 @@ async fn should_check_every_where_entry_of_a_removed_document_a_rule_reads() { } /// A moderator's change of a field judges no rule reading a referenced -/// document, and reads none of its totals: the stall's rule, reading the posts -/// on its topic and the topic itself, is left for the owner's writes. +/// document: the stall's rule, reading whether its topic is open, is left for +/// the owner's writes, so a moderator changes the note of a stall whose topic +/// has closed. #[tokio::test] -async fn should_change_a_field_without_reading_a_total_of_a_rule_it_does_not_judge() { +async fn should_change_a_field_without_judging_a_rule_reading_a_reference() { let setup = setup().await; let transaction = setup.platform.drive.grove.start_transaction(); - let (topic, create_topic) = create_with( + let (mut topic, create_topic) = create_with( &setup, &setup.user, TOPIC, @@ -608,6 +606,10 @@ async fn should_change_a_field_without_reading_a_total_of_a_rule_it_does_not_jud .await; assert_success(&setup.process(&create_stall, &transaction)); + topic.set("open", Value::Bool(false)); + let close = replacement(&setup.user, &setup.contract, TOPIC, &mut topic).await; + assert_success(&setup.process(&close, &transaction)); + let change = setup .moderate( &setup.moderator, diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/restore_constraints.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/restore_constraints.rs index dfc9407deaf..1b065890344 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/restore_constraints.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/restore_constraints.rs @@ -422,3 +422,43 @@ async fn should_preserve_the_rule_free_restore_fee_and_document() { Some(removed) ); } + +/// A restore is judged only against the rules reading a total, with `$old.` reading the restored +/// document itself. `textChangesOnEveryEdit`, which the restored document could never meet +/// against itself, is not judged; `onePerOwnerUnlessRetitled` is, and finds the text unchanged, +/// so its cap applies. +#[tokio::test] +async fn should_judge_a_restore_by_the_rules_reading_a_total_with_the_restored_document_stored() { + let setup = setup_with_schema(post_schema_with(platform_value!({ + "indices": [{"name": "byOwner", "properties": [{"$ownerId": "asc"}], + "countable": "countable"}], + "propertyConstraints": { + "onePerOwnerUnlessRetitled": {"anyOf": [ + {"notEqual": ["text", "$old.text"]}, + {"lessThanOrEqual": [{"countOf": ["post", {"$ownerId": "$ownerId"}]}, 1]} + ]}, + "textChangesOnEveryEdit": {"notEqual": ["text", "$old.text"]} + } + }))) + .await; + let tx = setup.platform.drive.grove.start_transaction(); + let first = create_post(&setup, &setup.user, "first", None, &tx).await; + let bytes = remove_post(&setup, &first, &tx).await; + let restore = setup + .moderate(&setup.moderator, restore_action(POST, bytes)) + .await; + assert_success(&setup.process(&restore, &tx)); + assert!(setup.stored_document(POST, first.id(), Some(&tx)).is_some()); + + // A create has no stored text, so its cap does not apply; a restore's does + let second = create_post(&setup, &setup.user, "second", None, &tx).await; + let bytes = remove_post(&setup, &second, &tx).await; + let restore = setup + .moderate(&setup.moderator, restore_action(POST, bytes)) + .await; + let result = setup.process(&restore, &tx); + constraint_refusal(&result, "onePerOwnerUnlessRetitled"); + assert!(setup + .stored_document(POST, second.id(), Some(&tx)) + .is_none()); +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_create/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_create/mod.rs index 1c3100022f1..0c15483ea79 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_create/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_create/mod.rs @@ -7020,10 +7020,11 @@ mod tests { #[tokio::test] async fn should_reject_a_rule_reading_a_referenced_document_beside_a_total_a_restore_moves() { - // A moderator's restore brings an entry back into the count of its - // room's entries the rule bounds by the room's capacity, and judges - // no rule reading a referenced document, so the contract is refused - // before any restore could pass the capacity + // A moderator's restore is judged against every rule reading a total, + // which may have moved while the entry was gone (here the count of its + // room's entries, bounded by the room's capacity), and judges no rule + // reading a referenced document, so the contract is refused before any + // restore could pass the capacity let config = DataContractConfig::default_for_version(PlatformVersion::latest()) .unwrap() .with_moderation(Some(ContractModerationConfig { @@ -7047,7 +7048,7 @@ mod tests { )), .. } if message.contains("rule \"cap\"") - && message.contains("a moderator's restore brings a document back into") + && message.contains("and a total, which a moderator's restore is judged against") ); } diff --git a/packages/rs-drive-abci/tests/supporting_files/contract/reference-validation/reference-validation-contract-referenced-rules.json b/packages/rs-drive-abci/tests/supporting_files/contract/reference-validation/reference-validation-contract-referenced-rules.json index 4ecbe61c00b..e3175a38512 100644 --- a/packages/rs-drive-abci/tests/supporting_files/contract/reference-validation/reference-validation-contract-referenced-rules.json +++ b/packages/rs-drive-abci/tests/supporting_files/contract/reference-validation/reference-validation-contract-referenced-rules.json @@ -125,6 +125,38 @@ }, "additionalProperties": false }, + "raise": { + "type": "object", + "documentsMutable": true, + "canBeDeleted": true, + "properties": { + "auctionId": { + "type": "array", + "byteArray": true, + "minItems": 32, + "maxItems": 32, + "contentMediaType": "application/x.dash.dpp.identifier", + "refersTo": { "type": "permanentDocument", "documentType": "auction" }, + "position": 0 + }, + "amount": { "type": "integer", "minimum": 0, "maximum": 1000000000, "position": 1 } + }, + "required": ["auctionId", "amount"], + "propertyConstraints": { + "raisesByTheReserve": { + "greaterThanOrEqual": [ + "amount", + { + "add": [ + { "ifAbsent": ["$old.amount", 0] }, + { "referenced": ["auctionId", "reservePrice"] } + ] + } + ] + } + }, + "additionalProperties": false + }, "order": { "type": "object", "documentsMutable": true, diff --git a/packages/rs-drive/src/drive/document/index_uniqueness/mod.rs b/packages/rs-drive/src/drive/document/index_uniqueness/mod.rs index 72252948d33..c8bb79eb43a 100644 --- a/packages/rs-drive/src/drive/document/index_uniqueness/mod.rs +++ b/packages/rs-drive/src/drive/document/index_uniqueness/mod.rs @@ -145,7 +145,7 @@ mod tests { prefunded_voting_balance: None, current_store_contest_info: None, should_store_contest_info: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), moderated: false, consumed_documents: Vec::new(), derived_index_values: None, diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/mod.rs index a208d5995a2..c55f74eeb69 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/mod.rs @@ -5,6 +5,7 @@ mod v1; use derive_more::From; use dpp::data_contract::document_type::property_constraints::AggregateRead; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::block::block_info::BlockInfo; use dpp::platform_value::{Identifier, Value}; @@ -29,9 +30,6 @@ pub enum DocumentCreateTransitionAction { V0(DocumentCreateTransitionActionV0), } -/// What `property_constraint_aggregates` returns for an action holding none. -static NO_PROPERTY_CONSTRAINT_AGGREGATES: BTreeMap = BTreeMap::new(); - impl DocumentCreateTransitionActionAccessorsV0 for DocumentCreateTransitionAction { fn base(&self) -> &DocumentBaseTransitionAction { match self { @@ -149,19 +147,18 @@ impl DocumentCreateTransitionActionAccessorsV0 for DocumentCreateTransitionActio fn property_constraint_aggregates(&self) -> &BTreeMap { match self { - DocumentCreateTransitionAction::V0(v0) => v0 - .property_constraint_aggregates - .as_deref() - .unwrap_or(&NO_PROPERTY_CONSTRAINT_AGGREGATES), + DocumentCreateTransitionAction::V0(v0) => { + PropertyConstraintReads::aggregates_of(&v0.property_constraint_reads) + } } } fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap) { match self { - DocumentCreateTransitionAction::V0(v0) => { - v0.property_constraint_aggregates = - (!aggregates.is_empty()).then(|| Box::new(aggregates)) - } + DocumentCreateTransitionAction::V0(v0) => PropertyConstraintReads::set_aggregates( + &mut v0.property_constraint_reads, + aggregates, + ), } } diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/mod.rs index 81b0ce2809b..386b854b802 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/mod.rs @@ -2,6 +2,7 @@ pub mod transformer; use dpp::block::block_info::BlockInfo; use dpp::data_contract::document_type::property_constraints::AggregateRead; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::document::{Document, DocumentV0}; use dpp::platform_value::{Identifier, Value}; use std::collections::BTreeMap; @@ -45,11 +46,10 @@ pub struct DocumentCreateTransitionActionV0 { /// contest. Boxed, since only such a create holds one and the action is the largest variant /// of a large enum. pub should_store_contest_info: Option>, - /// The `countOf` and `sumOf` totals the document type's `propertyConstraints` rules - /// read, each as it will be once this write is done, read from state when the action is - /// built; `None` when the rules judging the write read none, and boxed, since only - /// such a write holds any and the action is one variant of a large enum. - pub property_constraint_aggregates: Option>>, + /// What the document type's `propertyConstraints` rules read beyond the document, + /// attached once the action is built ([`PropertyConstraintReads`]): the `countOf` and + /// `sumOf` totals, each as it will be once this write is done. + pub property_constraint_reads: Option>, /// Whether the batch transformer judged the create a moderator's write of fields the /// document type keeps for its moderators: its owner moderates the contract and sets one. /// The document is then stamped `$moderatedAt` the block's time and `$moderatedBy` the diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/transformer.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/transformer.rs index c0223f3607d..882d706dede 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_create_transition_action/v0/transformer.rs @@ -164,7 +164,7 @@ impl DocumentCreateTransitionActionV0 { prefunded_voting_balance: prefunded_voting_balances_by_vote_poll, current_store_contest_info, should_store_contest_info: should_store_contest_info.map(Box::new), - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), moderated: false, consumed_documents: Vec::new(), derived_index_values: None, diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/mod.rs index 54c683dccd3..c69a41012fc 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/mod.rs @@ -1,7 +1,10 @@ mod v0; use derive_more::From; -use dpp::data_contract::document_type::property_constraints::AggregateRead; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, +}; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::document::Document; use dpp::fee::Credits; use std::collections::BTreeMap; @@ -23,9 +26,6 @@ pub enum DocumentPurchaseTransitionAction { V0(DocumentPurchaseTransitionActionV0), } -/// What `property_constraint_aggregates` returns for an action holding none. -static NO_PROPERTY_CONSTRAINT_AGGREGATES: BTreeMap = BTreeMap::new(); - impl DocumentPurchaseTransitionActionAccessorsV0 for DocumentPurchaseTransitionAction { fn base(&self) -> &DocumentBaseTransitionAction { match self { @@ -65,18 +65,36 @@ impl DocumentPurchaseTransitionActionAccessorsV0 for DocumentPurchaseTransitionA fn property_constraint_aggregates(&self) -> &BTreeMap { match self { - DocumentPurchaseTransitionAction::V0(v0) => v0 - .property_constraint_aggregates - .as_deref() - .unwrap_or(&NO_PROPERTY_CONSTRAINT_AGGREGATES), + DocumentPurchaseTransitionAction::V0(v0) => { + PropertyConstraintReads::aggregates_of(&v0.property_constraint_reads) + } } } fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap) { + match self { + DocumentPurchaseTransitionAction::V0(v0) => PropertyConstraintReads::set_aggregates( + &mut v0.property_constraint_reads, + aggregates, + ), + } + } + + fn stored_system_values(&self) -> Option<&StoredSystemValues> { + match self { + DocumentPurchaseTransitionAction::V0(v0) => { + PropertyConstraintReads::stored_system_values_of(&v0.property_constraint_reads) + } + } + } + + fn set_stored_system_values(&mut self, values: StoredSystemValues) { match self { DocumentPurchaseTransitionAction::V0(v0) => { - v0.property_constraint_aggregates = - (!aggregates.is_empty()).then(|| Box::new(aggregates)) + PropertyConstraintReads::set_stored_system_values( + &mut v0.property_constraint_reads, + values, + ) } } } diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/v0/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/v0/mod.rs index a96d5a9fc33..601cea83bd7 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/v0/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/v0/mod.rs @@ -1,6 +1,9 @@ pub mod transformer; -use dpp::data_contract::document_type::property_constraints::AggregateRead; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, +}; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::document::Document; use dpp::fee::Credits; use dpp::identifier::Identifier; @@ -19,11 +22,11 @@ pub struct DocumentPurchaseTransitionActionV0 { pub original_owner_id: Identifier, /// Price pub price: Credits, - /// The `countOf` and `sumOf` totals the document type's `propertyConstraints` rules - /// read, each as it will be once this write is done, read from state when the action is - /// built; `None` when the rules judging the write read none, and boxed, since only - /// such a write holds any and the action is one variant of a large enum. - pub property_constraint_aggregates: Option>>, + /// What the document type's `propertyConstraints` rules read beyond the document, + /// attached once the action is built ([`PropertyConstraintReads`]): the `countOf` and + /// `sumOf` totals, each as it will be once this write is done, and the system values of + /// the stored version it replaces, which a rule reads through `$old.`. + pub property_constraint_reads: Option>, } /// document purchase transition action accessors v0 @@ -48,4 +51,11 @@ pub trait DocumentPurchaseTransitionActionAccessorsV0 { /// Sets the totals the rules judging this write read, once they are read from state fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap); + + /// The owner, times, heights and revision of the stored version this write replaces, + /// which a rule reads through `$old.`, when anything the document type declares reads them + fn stored_system_values(&self) -> Option<&StoredSystemValues>; + + /// Sets the system values of the stored version this write replaces, once it is read + fn set_stored_system_values(&mut self, values: StoredSystemValues); } diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/v0/transformer.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/v0/transformer.rs index ebd01a37791..2a27cf65f34 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/v0/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_purchase_transition_action/v0/transformer.rs @@ -94,7 +94,7 @@ impl DocumentPurchaseTransitionActionV0 { document: modified_document, original_owner_id, price: *price, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), } .into(), )) diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/mod.rs index be39f165f2a..91b7f505c4d 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/mod.rs @@ -1,7 +1,10 @@ mod v0; mod v1; -use dpp::data_contract::document_type::property_constraints::AggregateRead; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, +}; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use std::collections::{BTreeMap, BTreeSet}; use derive_more::From; @@ -27,9 +30,6 @@ pub enum DocumentReplaceTransitionAction { V0(DocumentReplaceTransitionActionV0), } -/// What `property_constraint_aggregates` returns for an action holding none. -static NO_PROPERTY_CONSTRAINT_AGGREGATES: BTreeMap = BTreeMap::new(); - impl DocumentReplaceTransitionActionAccessorsV0 for DocumentReplaceTransitionAction { fn base(&self) -> &DocumentBaseTransitionAction { match self { @@ -166,18 +166,36 @@ impl DocumentReplaceTransitionActionAccessorsV0 for DocumentReplaceTransitionAct fn property_constraint_aggregates(&self) -> &BTreeMap { match self { - DocumentReplaceTransitionAction::V0(v0) => v0 - .property_constraint_aggregates - .as_deref() - .unwrap_or(&NO_PROPERTY_CONSTRAINT_AGGREGATES), + DocumentReplaceTransitionAction::V0(v0) => { + PropertyConstraintReads::aggregates_of(&v0.property_constraint_reads) + } } } fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap) { + match self { + DocumentReplaceTransitionAction::V0(v0) => PropertyConstraintReads::set_aggregates( + &mut v0.property_constraint_reads, + aggregates, + ), + } + } + + fn stored_system_values(&self) -> Option<&StoredSystemValues> { + match self { + DocumentReplaceTransitionAction::V0(v0) => { + PropertyConstraintReads::stored_system_values_of(&v0.property_constraint_reads) + } + } + } + + fn set_stored_system_values(&mut self, values: StoredSystemValues) { match self { DocumentReplaceTransitionAction::V0(v0) => { - v0.property_constraint_aggregates = - (!aggregates.is_empty()).then(|| Box::new(aggregates)) + PropertyConstraintReads::set_stored_system_values( + &mut v0.property_constraint_reads, + values, + ) } } } diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/v0/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/v0/mod.rs index fde218d1006..37f5ea22dbe 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/v0/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/v0/mod.rs @@ -1,6 +1,9 @@ pub mod transformer; -use dpp::data_contract::document_type::property_constraints::AggregateRead; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, +}; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::document::{Document, DocumentV0}; use dpp::identity::TimestampMillis; use dpp::platform_value::{Identifier, Value}; @@ -66,11 +69,11 @@ pub struct DocumentReplaceTransitionActionV0 { /// The moderator who last wrote those fields: the stored document's, or the owner's, as /// `moderated_at` pub moderated_by: Option, - /// The `countOf` and `sumOf` totals the document type's `propertyConstraints` rules - /// read, each as it will be once this write is done, read from state when the action is - /// built; `None` when the rules judging the write read none, and boxed, since only - /// such a write holds any and the action is one variant of a large enum. - pub property_constraint_aggregates: Option>>, + /// What the document type's `propertyConstraints` rules read beyond the document, + /// attached once the action is built ([`PropertyConstraintReads`]): the `countOf` and + /// `sumOf` totals, each as it will be once this write is done, and the system values of + /// the stored version it replaces, which a rule reads through `$old.`. + pub property_constraint_reads: Option>, } /// document replace transition action accessors v0 @@ -137,6 +140,13 @@ pub trait DocumentReplaceTransitionActionAccessorsV0 { /// Sets the totals the rules judging this write read, once they are read from state fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap); + + /// The owner, times, heights and revision of the stored version this write replaces, + /// which a rule reads through `$old.`, when anything the document type declares reads them + fn stored_system_values(&self) -> Option<&StoredSystemValues>; + + /// Sets the system values of the stored version this write replaces, once it is read + fn set_stored_system_values(&mut self, values: StoredSystemValues); } /// document from replace transition v0 diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/v0/transformer.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/v0/transformer.rs index 38e1cebd066..9431db2257e 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/v0/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_replace_transition_action/v0/transformer.rs @@ -207,7 +207,7 @@ impl DocumentReplaceTransitionActionV0 { creator_id: original_creator_id, moderated_at: original_moderated_at, moderated_by: original_moderated_by, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), } .into(), )) diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/mod.rs index 004408e1d72..ccdf267ccbe 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/mod.rs @@ -1,7 +1,10 @@ mod v0; use derive_more::From; -use dpp::data_contract::document_type::property_constraints::AggregateRead; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, +}; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::document::Document; use std::collections::BTreeMap; @@ -22,9 +25,6 @@ pub enum DocumentTransferTransitionAction { V0(DocumentTransferTransitionActionV0), } -/// What `property_constraint_aggregates` returns for an action holding none. -static NO_PROPERTY_CONSTRAINT_AGGREGATES: BTreeMap = BTreeMap::new(); - impl DocumentTransferTransitionActionAccessorsV0 for DocumentTransferTransitionAction { fn base(&self) -> &DocumentBaseTransitionAction { match self { @@ -52,18 +52,36 @@ impl DocumentTransferTransitionActionAccessorsV0 for DocumentTransferTransitionA fn property_constraint_aggregates(&self) -> &BTreeMap { match self { - DocumentTransferTransitionAction::V0(v0) => v0 - .property_constraint_aggregates - .as_deref() - .unwrap_or(&NO_PROPERTY_CONSTRAINT_AGGREGATES), + DocumentTransferTransitionAction::V0(v0) => { + PropertyConstraintReads::aggregates_of(&v0.property_constraint_reads) + } } } fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap) { + match self { + DocumentTransferTransitionAction::V0(v0) => PropertyConstraintReads::set_aggregates( + &mut v0.property_constraint_reads, + aggregates, + ), + } + } + + fn stored_system_values(&self) -> Option<&StoredSystemValues> { + match self { + DocumentTransferTransitionAction::V0(v0) => { + PropertyConstraintReads::stored_system_values_of(&v0.property_constraint_reads) + } + } + } + + fn set_stored_system_values(&mut self, values: StoredSystemValues) { match self { DocumentTransferTransitionAction::V0(v0) => { - v0.property_constraint_aggregates = - (!aggregates.is_empty()).then(|| Box::new(aggregates)) + PropertyConstraintReads::set_stored_system_values( + &mut v0.property_constraint_reads, + values, + ) } } } diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/v0/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/v0/mod.rs index e3492172fb3..28d0077ed3a 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/v0/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/v0/mod.rs @@ -1,6 +1,9 @@ pub mod transformer; -use dpp::data_contract::document_type::property_constraints::AggregateRead; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, +}; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::document::Document; use std::collections::BTreeMap; @@ -13,11 +16,11 @@ pub struct DocumentTransferTransitionActionV0 { pub base: DocumentBaseTransitionAction, /// The new document to be inserted pub document: Document, - /// The `countOf` and `sumOf` totals the document type's `propertyConstraints` rules - /// read, each as it will be once this write is done, read from state when the action is - /// built; `None` when the rules judging the write read none, and boxed, since only - /// such a write holds any and the action is one variant of a large enum. - pub property_constraint_aggregates: Option>>, + /// What the document type's `propertyConstraints` rules read beyond the document, + /// attached once the action is built ([`PropertyConstraintReads`]): the `countOf` and + /// `sumOf` totals, each as it will be once this write is done, and the system values of + /// the stored version it replaces, which a rule reads through `$old.`. + pub property_constraint_reads: Option>, } /// document transfer transition action accessors v0 @@ -37,4 +40,11 @@ pub trait DocumentTransferTransitionActionAccessorsV0 { /// Sets the totals the rules judging this write read, once they are read from state fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap); + + /// The owner, times, heights and revision of the stored version this write replaces, + /// which a rule reads through `$old.`, when anything the document type declares reads them + fn stored_system_values(&self) -> Option<&StoredSystemValues>; + + /// Sets the system values of the stored version this write replaces, once it is read + fn set_stored_system_values(&mut self, values: StoredSystemValues); } diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/v0/transformer.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/v0/transformer.rs index 5529ee0eba6..affe8843f11 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/v0/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_transfer_transition_action/v0/transformer.rs @@ -94,7 +94,7 @@ impl DocumentTransferTransitionActionV0 { DocumentTransferTransitionActionV0 { base, document: modified_document, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), } .into(), )) diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/mod.rs index 9da45febf5c..dcac84191bf 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/mod.rs @@ -1,7 +1,10 @@ mod v0; use derive_more::From; -use dpp::data_contract::document_type::property_constraints::AggregateRead; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, +}; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::document::Document; use std::collections::BTreeMap; @@ -22,9 +25,6 @@ pub enum DocumentUpdatePriceTransitionAction { V0(DocumentUpdatePriceTransitionActionV0), } -/// What `property_constraint_aggregates` returns for an action holding none. -static NO_PROPERTY_CONSTRAINT_AGGREGATES: BTreeMap = BTreeMap::new(); - impl DocumentUpdatePriceTransitionActionAccessorsV0 for DocumentUpdatePriceTransitionAction { fn base(&self) -> &DocumentBaseTransitionAction { match self { @@ -52,18 +52,36 @@ impl DocumentUpdatePriceTransitionActionAccessorsV0 for DocumentUpdatePriceTrans fn property_constraint_aggregates(&self) -> &BTreeMap { match self { - DocumentUpdatePriceTransitionAction::V0(v0) => v0 - .property_constraint_aggregates - .as_deref() - .unwrap_or(&NO_PROPERTY_CONSTRAINT_AGGREGATES), + DocumentUpdatePriceTransitionAction::V0(v0) => { + PropertyConstraintReads::aggregates_of(&v0.property_constraint_reads) + } } } fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap) { + match self { + DocumentUpdatePriceTransitionAction::V0(v0) => PropertyConstraintReads::set_aggregates( + &mut v0.property_constraint_reads, + aggregates, + ), + } + } + + fn stored_system_values(&self) -> Option<&StoredSystemValues> { + match self { + DocumentUpdatePriceTransitionAction::V0(v0) => { + PropertyConstraintReads::stored_system_values_of(&v0.property_constraint_reads) + } + } + } + + fn set_stored_system_values(&mut self, values: StoredSystemValues) { match self { DocumentUpdatePriceTransitionAction::V0(v0) => { - v0.property_constraint_aggregates = - (!aggregates.is_empty()).then(|| Box::new(aggregates)) + PropertyConstraintReads::set_stored_system_values( + &mut v0.property_constraint_reads, + values, + ) } } } diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/v0/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/v0/mod.rs index d35d2c14a14..8319b589dc4 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/v0/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/v0/mod.rs @@ -1,6 +1,9 @@ pub mod transformer; -use dpp::data_contract::document_type::property_constraints::AggregateRead; +use dpp::data_contract::document_type::property_constraints::{ + AggregateRead, StoredSystemValues, +}; +use crate::state_transition_action::batch::batched_transition::document_transition::property_constraint_reads::PropertyConstraintReads; use dpp::document::Document; use std::collections::BTreeMap; @@ -13,11 +16,11 @@ pub struct DocumentUpdatePriceTransitionActionV0 { pub base: DocumentBaseTransitionAction, /// The new document to be updated pub document: Document, - /// The `countOf` and `sumOf` totals the document type's `propertyConstraints` rules - /// read, each as it will be once this write is done, read from state when the action is - /// built; `None` when the rules judging the write read none, and boxed, since only - /// such a write holds any and the action is one variant of a large enum. - pub property_constraint_aggregates: Option>>, + /// What the document type's `propertyConstraints` rules read beyond the document, + /// attached once the action is built ([`PropertyConstraintReads`]): the `countOf` and + /// `sumOf` totals, each as it will be once this write is done, and the system values of + /// the stored version it replaces, which a rule reads through `$old.`. + pub property_constraint_reads: Option>, } /// document transfer transition action accessors v0 @@ -37,4 +40,11 @@ pub trait DocumentUpdatePriceTransitionActionAccessorsV0 { /// Sets the totals the rules judging this write read, once they are read from state fn set_property_constraint_aggregates(&mut self, aggregates: BTreeMap); + + /// The owner, times, heights and revision of the stored version this write replaces, + /// which a rule reads through `$old.`, when anything the document type declares reads them + fn stored_system_values(&self) -> Option<&StoredSystemValues>; + + /// Sets the system values of the stored version this write replaces, once it is read + fn set_stored_system_values(&mut self, values: StoredSystemValues); } diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/v0/transformer.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/v0/transformer.rs index 311918c38af..da39f1476dc 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/v0/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/document_update_price_transition_action/v0/transformer.rs @@ -87,7 +87,7 @@ impl DocumentUpdatePriceTransitionActionV0 { DocumentUpdatePriceTransitionActionV0 { base, document: modified_document, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), } .into(), )) diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/mod.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/mod.rs index cd98d558509..f601d5fcf72 100644 --- a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/mod.rs +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/mod.rs @@ -15,6 +15,8 @@ pub mod document_transfer_transition_action; mod document_transition_action_type; /// document_update_price_transition_action pub mod document_update_price_transition_action; +/// property_constraint_reads +pub mod property_constraint_reads; pub use dpp::state_transition::batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType; diff --git a/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/property_constraint_reads.rs b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/property_constraint_reads.rs new file mode 100644 index 00000000000..373d9072ea6 --- /dev/null +++ b/packages/rs-drive/src/state_transition_action/batch/batched_transition/document_transition/property_constraint_reads.rs @@ -0,0 +1,61 @@ +use dpp::data_contract::document_type::property_constraints::{AggregateRead, StoredSystemValues}; +use std::collections::BTreeMap; + +/// What the `propertyConstraints` rules judging a document write read beyond the document it +/// writes, read once its action is built: the `countOf` and `sumOf` totals, and the system +/// values of the stored version the write replaces. An action holds it boxed, and only while it +/// holds something, since few writes do and the action is one variant of a large enum. +#[derive(Debug, Clone, Default)] +pub struct PropertyConstraintReads { + /// The totals the rules judging the write read, each as it will be once the write is done. + pub aggregates: BTreeMap, + /// The owner, times, heights and revision of the stored version the write replaces, which + /// a rule or a condition reads through `$old.`: `None` for a create, and when nothing the + /// document type declares reads them. + pub stored_system_values: Option, +} + +/// What [`PropertyConstraintReads::aggregates_of`] gives for an action holding none. +static NO_AGGREGATES: BTreeMap = BTreeMap::new(); + +impl PropertyConstraintReads { + /// The totals an action holding `reads` holds, none when it holds nothing. + pub fn aggregates_of(reads: &Option>) -> &BTreeMap { + reads + .as_deref() + .map_or(&NO_AGGREGATES, |reads| &reads.aggregates) + } + + /// The stored system values an action holding `reads` holds. + pub fn stored_system_values_of(reads: &Option>) -> Option<&StoredSystemValues> { + reads + .as_deref() + .and_then(|reads| reads.stored_system_values.as_ref()) + } + + /// Sets the totals an action holding `reads` holds. An action holding + /// nothing, given no totals, is left without a box. + pub fn set_aggregates( + reads: &mut Option>, + aggregates: BTreeMap, + ) { + if reads.is_none() && aggregates.is_empty() { + return; + } + Self::update(reads, |held| held.aggregates = aggregates); + } + + /// Sets the stored system values an action holding `reads` holds. + pub fn set_stored_system_values(reads: &mut Option>, values: StoredSystemValues) { + Self::update(reads, |held| held.stored_system_values = Some(values)); + } + + /// Applies `change` to what `reads` holds, leaving no box once it holds nothing. + fn update(reads: &mut Option>, change: impl FnOnce(&mut Self)) { + let held = reads.get_or_insert_with(Box::default); + change(held); + if held.aggregates.is_empty() && held.stored_system_values.is_none() { + *reads = None; + } + } +} diff --git a/packages/rs-drive/src/state_transition_action/batch/tests.rs b/packages/rs-drive/src/state_transition_action/batch/tests.rs index 5b048df97c4..144bbad17a8 100644 --- a/packages/rs-drive/src/state_transition_action/batch/tests.rs +++ b/packages/rs-drive/src/state_transition_action/batch/tests.rs @@ -255,7 +255,7 @@ fn make_create_v0() -> DocumentCreateTransitionActionV0 { prefunded_voting_balance: None, current_store_contest_info: None, should_store_contest_info: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), moderated: false, consumed_documents: Vec::new(), derived_index_values: None, @@ -410,7 +410,7 @@ fn make_replace_v0() -> DocumentReplaceTransitionActionV0 { creator_id: Some(Identifier::from([0xCC; 32])), moderated_at: None, moderated_by: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), } } @@ -524,7 +524,7 @@ fn make_transfer_v0() -> DocumentTransferTransitionActionV0 { DocumentTransferTransitionActionV0 { base: test_document_base(), document: test_document(), - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), } } @@ -567,7 +567,7 @@ fn make_purchase_v0() -> DocumentPurchaseTransitionActionV0 { document: test_document(), original_owner_id: Identifier::from([0xDD; 32]), price: 5000, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), } } @@ -620,7 +620,7 @@ fn make_update_price_v0() -> DocumentUpdatePriceTransitionActionV0 { DocumentUpdatePriceTransitionActionV0 { base: test_document_base(), document: test_document(), - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), } } @@ -2659,7 +2659,7 @@ fn test_all_purchases_amount_multiple_document_purchases() { document: test_document(), original_owner_id: Identifier::from([0xDD; 32]), price: 3000, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }) .into(); batch.set_transitions(vec![ @@ -2960,7 +2960,7 @@ fn stamp_test_create_action(protocol_version: u32) -> DocumentCreateTransitionAc prefunded_voting_balance: None, current_store_contest_info: None, should_store_contest_info: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), moderated: false, consumed_documents: Vec::new(), derived_index_values: None, @@ -2998,7 +2998,7 @@ fn stamp_test_replace_action(protocol_version: u32) -> DocumentReplaceTransition creator_id: Some(Identifier::from([0xCC; 32])), moderated_at: None, moderated_by: None, - property_constraint_aggregates: Default::default(), + property_constraint_reads: Default::default(), }) } diff --git a/packages/rs-platform-version/src/version/v14.rs b/packages/rs-platform-version/src/version/v14.rs index ad5345af822..5e8d9495d19 100644 --- a/packages/rs-platform-version/src/version/v14.rs +++ b/packages/rs-platform-version/src/version/v14.rs @@ -1164,6 +1164,38 @@ pub const PROTOCOL_VERSION_14: ProtocolVersion = 14; /// `submittedCharter`'s `rewardSplit` members add up to 100, replacing the /// charter-specific check, whose error 11001 keeps its place in /// `BasicError` but is never produced. +/// A rule reads `$revision`, an integer operand (`SystemValue::Revision`), +/// 1 on a create and one more for each later write, on a type keeping a +/// revision (`requires_revision`); a transfer, a purchase and a price +/// update, which move it, are judged against the rules reading it. A rule +/// reads the stored version of the document a write replaces through +/// `$old.` (`STORED_DOCUMENT_PREFIX`), as the condition of item 66 does: a +/// property (`$old.status`, in any read a bare path takes, checked as the +/// path after it), `$old.$ownerId`, and a time, a height or `$revision` +/// (`SystemRead::stored`); only on a type keeping a revision and not +/// indexOnly, never in a `countOf` or `sumOf` filter, and never in a rule +/// of `deleteConstraints`, which reads the stored document by its plain +/// paths (parser generation 3; `validate_stored_version_reads` once the +/// moderator abilities are parsed). `DocumentSystemValues::stored` gives +/// it: `StoredVersion::Absent` on a create, where a property under it is +/// absent, `$old.$ownerId` equals no identifier and a stored time, height +/// or revision reads 0; on a replace the document replaced, its properties +/// rebuilt from the written ones and `stored_changed_values`, its owner, +/// times, heights and revision taken from the fetched document by the batch +/// transformer and kept on the action beside the totals +/// (`PropertyConstraintReads`, which replaces the boxed totals) when a +/// rule or a condition reads them; on a transfer, a purchase or a price +/// update the document before it, the write judged only against the rules +/// reading what it changes, of either version. A moderator's change of a +/// document's fields (`DocumentSystemValues::changed_fields`) is judged +/// against the rules reading a field it writes, of either version, +/// `$revision` or a total, and a moderator's restore (`SystemChange::Restore`, +/// through `validate_property_constraints_for_system_change`) against the +/// rules reading a total, with `$old.` reading the restored document: rules +/// never change once registered, so no other rule could give another +/// verdict than at the document's last write. A rule reading a stored +/// version a client does not give is not judged, and one consensus does +/// not give is an error, as for a total. /// A rule may also read a value of the document a reference of the type /// points at, `{ "referenced": [reference, field] }`, wherever a path /// stands: `field` is a property path of the referenced type, its `$id`, @@ -1180,9 +1212,11 @@ pub const PROTOCOL_VERSION_14: ProtocolVersion = 14; /// through anything but a stored property holding one reference /// to one document by id or by a `findBy` without a function, beside what /// a transfer, a purchase or a price update of a type that has them -/// changes, beside a field moderators change, read or deciding a total -/// over the type's own documents, and beside any total over the type's -/// own documents where a moderator's restore can bring one back (10231); +/// changes (`$revision` and `$old.` reads included), beside what a +/// moderator's change of the fields a type keeps for them is judged +/// against (such a field, of either version, `$revision`, or any total), +/// and beside any total where a moderator's restore, judged against every +/// rule reading one, can bring a document back (10231); /// and /// `create_document_types_from_document_schemas` 1, in place, checks what /// it reads of a type of the same contract (10231: the field exists, is @@ -1429,7 +1463,11 @@ pub const PROTOCOL_VERSION_14: ProtocolVersion = 14; /// given as a `$ref` to the contract's `$defs` from the definition, as the /// core parse does, when it checks a rule's string constants and defaults /// against the property's `enum` and an `encryptedFor` key id's bounds; it -/// refused every such contract with a decoding error before. +/// refused every such contract with a decoding error before. The stored +/// version a rule reads through `$old.` (item 39) is judged as stored too, +/// and a `$old` key the written data carries itself, which no property can +/// name, is dropped before a rule reads it +/// (`DocumentSystemValues::judged_data`). /// /// 53. **Properties the platform generates (`generatedFrom`)**: the property /// keyword (meta-schema v3, `apply_generated_from` 0, `GeneratedFrom` on @@ -1550,7 +1588,8 @@ pub const PROTOCOL_VERSION_14: ProtocolVersion = 14; /// ability, appended to `ModerationAbility`, on the type, and citing a /// listed reason) sets or removes those fields on any document of the type, /// whoever owns it. The changed document is judged as a replace judges one -/// (schema, `propertyConstraints` with their totals, `distinctFrom`, +/// (schema, the `propertyConstraints` reading a field it changes, `$revision` +/// or a total, with the stored document under `$old.` (item 39), `distinctFrom`, /// `encryptedFor` shapes, unique indexes through /// `validate_moderated_document_uniqueness`, the restore's check /// generalized and renamed), its references are not checked again, and it @@ -1906,8 +1945,10 @@ pub const PROTOCOL_VERSION_14: ProtocolVersion = 14; /// `sumOf`, and is judged on the document the replace writes (its /// `$updatedAt` the replace's block time, so `$updatedAt - $createdAt` /// is the document's age), with the stored document's properties read -/// through `$old.` (`STORED_DOCUMENT_PREFIX`), which only such a -/// condition may read. Document replace state validation 1, extended in +/// through `$old.` (`STORED_DOCUMENT_PREFIX`), and its owner, times, +/// heights and revision through `$old.$ownerId`, `$old.$updatedAt` and the +/// rest, which a `propertyConstraints` rule reads too (item 39), as it +/// reads `$revision`. Document replace state validation 1, extended in /// place, refuses a replace changing, adding or removing a property whose /// condition holds, or faults, with `DocumentImmutablePropertyChangedError` /// (40128); the stored properties are rebuilt from the written ones and @@ -2361,9 +2402,12 @@ pub const PROTOCOL_VERSION_14: ProtocolVersion = 14; /// through generation 0. /// /// 87. **Moderator document restores obey `propertyConstraints`**: moderation state -/// validation 0, in place, judges every rule of the restored type after uniqueness -/// and before constructing restoration operations. The retained document supplies -/// its original id, owner, properties, times and heights. The shared aggregate reader +/// validation 0, in place, judges the rules of the restored type that read a +/// `countOf` or `sumOf` total (`SystemChange::Restore`, item 39), the only values +/// that can have moved while the document was gone, after uniqueness and before +/// constructing restoration operations. The retained document supplies its original +/// id, owner, properties, times, heights and revision, and is the stored version a +/// rule reads through `$old.`. The shared aggregate reader /// adds it to the live totals as an insertion, with no contribution from its removal /// record. A failing rule returns paid `DocumentPropertyConstraintViolatedError` /// (10422) in a block, charging the moderator and consuming its nonce while leaving @@ -2476,23 +2520,23 @@ pub const PROTOCOL_VERSION_14: ProtocolVersion = 14; /// parser generations 0 to 2 refuse them as unsupported property types. /// /// 93. **Fee estimates size sum and count trees, and sum items, as they are -/// stored**: grovedb's `GROVE_V4` (`average_case_propagated_aggregate_kind` -/// 1) estimates a sum, big sum, count or count-sum tree that a batch -/// creates together with its contents as that tree rather than as a plain -/// tree. The `apply: false` estimate of a document insert under a -/// countable or summable index (which creates the value tree and its `0` -/// bucket with the document's reference) no longer comes in below the -/// applied storage fee: by 9 bytes per aggregate of each tree created, 18 -/// bytes for a summable index. A replaced root key of such a tree is sized -/// the same way in the estimate's replaced bytes, so an estimate that -/// rewrites a sum tree's root (an identity or token balance change among -/// them) charges 9 more replaced bytes per tree. `GROVE_V4` also sizes an -/// inserted `SumItem` or `ItemWithSumItem`, and a replaced +/// stored**: grovedb's `GROVE_V4` +/// (`average_case_propagated_aggregate_kind` 1) estimates a sum, big sum, +/// count or count-sum tree that a batch creates together with its contents +/// as that tree rather than as a plain tree. The `apply: false` estimate of +/// a document insert under a countable or summable index (which creates the +/// value tree and its `0` bucket with the document's reference) no longer +/// comes in below the applied storage fee: by 9 bytes per aggregate of each +/// tree created, 18 bytes for a summable index. A replaced root key of such +/// a tree is sized the same way in the estimate's replaced bytes, so an +/// estimate that rewrites a sum tree's root (an identity or token balance +/// change among them) charges 9 more replaced bytes per tree. `GROVE_V4` +/// also sizes an inserted `SumItem` or `ItemWithSumItem`, and a replaced /// `ItemWithSumItem`, with its sum at the fixed 9-byte width the apply /// charges, up to 8 bytes more per item, in both estimators -/// (`average_case_sum_item_cost_size` 1, `worst_case_sum_item_cost_size` -/// 1). Applied fees are unchanged. Inert before this version: `GROVE_V1` -/// to `GROVE_V3` keep the old sizing. +/// (`average_case_sum_item_cost_size` 1 and +/// `worst_case_sum_item_cost_size` 1). Applied fees are unchanged. Inert +/// before this version: `GROVE_V1` to `GROVE_V3` keep the old sizing. /// /// The app-connect system contract (`SystemDataContract::AppConnect`, schema v1) /// carries only the wallet's `loginKeyResponse`: a flat indexOnly entry keyed by diff --git a/packages/rs-sdk-ffi/src/data_contract/property_constraints.rs b/packages/rs-sdk-ffi/src/data_contract/property_constraints.rs index e6cb9a81bfd..ea2b90a988e 100644 --- a/packages/rs-sdk-ffi/src/data_contract/property_constraints.rs +++ b/packages/rs-sdk-ffi/src/data_contract/property_constraints.rs @@ -41,7 +41,7 @@ use dash_sdk::dpp::data_contract::document_type::methods::{ DocumentTypeBasicMethods, DocumentTypeV0Methods, }; use dash_sdk::dpp::data_contract::document_type::property_constraints::{ - AggregateKind, AggregateRead, DocumentSystemValues, PropertyRead, + AggregateKind, AggregateRead, DocumentSystemValues, PropertyRead, StoredVersion, }; use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; use dash_sdk::dpp::document::{Document, DocumentV0Getters}; @@ -63,7 +63,7 @@ const PROPERTY_CONSTRAINTS_KEYWORD: &str = "propertyConstraints"; /// Get the `propertyConstraints` rules of a document type as a JSON array /// /// Each element is -/// `{ "name": string, "rule": object, "reads": [{ "path": string, "kind": string }], "readsOwner": bool, "readsSystem": [string], "readsTotals": [{ "kind": string, "documentType": string, "property"?: string, "filter": [string] }], "readsReferenced": [{ "reference": string, "path": string, "kind": string }] }`: +/// `{ "name": string, "rule": object, "reads": [{ "path": string, "kind": string }], "readsOwner": bool, "readsSystem": [string], "readsStored": bool, "readsTotals": [{ "kind": string, "documentType": string, "property"?: string, "filter": [string] }], "readsReferenced": [{ "reference": string, "path": string, "kind": string }] }`: /// the rule's name (its key in `propertyConstraints`), the rule exactly as the /// document type's schema declares it, every property it reads in declared /// order (`kind` is `"value"` for an integer operand, `"presence"` for @@ -71,12 +71,15 @@ const PROPERTY_CONSTRAINTS_KEYWORD: &str = "propertyConstraints"; /// an identifier comparison, `"length"` for a `length` or `byteLength` operand, /// `"count"` for a `count` operand, `"elements"` for the array a `contains` /// looks in and `"bytes"` for a byte array a `byteAt` operand reads a byte of, -/// or a `startsWith` or `endsWith` tests; `$ownerId` is no property and is not -/// listed), whether it reads `$ownerId` (or a +/// or a `startsWith` or `endsWith` tests; a property of the stored version is listed +/// under its `$old.` path; `$ownerId` and `$old.$ownerId` are no properties and are not +/// listed), whether it reads `$ownerId` or `$old.$ownerId` (or a /// total that depends on the owner), which makes a transfer or a purchase answer to it too, -/// the system times and heights it reads (`"$createdAt"`, ...), which make a price update -/// answer to a rule reading the update's and a transfer or purchase one reading the -/// transfer's, and the `countOf` and `sumOf` totals it reads in declared order (`kind` +/// the system values it reads (`"$createdAt"`, `"$revision"`, `"$old.$updatedAt"`, ...), +/// which make a price update answer to a rule reading the update's, a transfer or purchase +/// one reading the transfer's and each one reading `$revision`, whether it reads the stored +/// version of the document through `$old.` (`readsStored`: absent on a create, which the +/// pre-check judges), and the `countOf` and `sumOf` totals it reads in declared order (`kind` /// `"countOf"` or `"sumOf"`, the type of the contract it totals, the summed `property` of /// a `sumOf` only, and the keys its `filter` matches documents by; a total the platform /// reads from state when the document is sent, which the pre-check does not), and the @@ -147,9 +150,13 @@ pub unsafe extern "C" fn dash_sdk_data_contract_get_property_constraints( /// value is typed as it would be sent; the document is then judged by DPP's /// `validate_property_constraints`, the check consensus runs on a create: /// every rule, in name order, evaluated by `PropertyConstraint::violation`. +/// A create has no stored version, so a path through `$old.` reads absent, as +/// consensus reads it (a stored time, height or revision reads 0), and +/// `$revision` is the document's first. /// The device clock stands in for the block time the create records /// (`$createdAt`, `$updatedAt`, `$transferredAt`), and a rule reading a block -/// height is not judged, since the height is unknown until the block, and +/// height the create records (`$createdAtBlockHeight` and the rest, without +/// `$old.`) is not judged, since the height is unknown until the block, and /// neither is a rule reading a `countOf` or `sumOf` total (`"readsTotals"`), /// which the platform reads from state when the document is sent, nor one /// reading a value of a document a reference points at (`"readsReferenced"`), @@ -345,8 +352,9 @@ fn property_constraints_json( "readsSystem": constraint .system_reads() .into_iter() - .map(|property| property.name()) + .map(|read| read.name()) .collect::>(), + "readsStored": constraint.reads_stored(), "readsTotals": constraint .aggregate_reads() .into_iter() @@ -373,12 +381,14 @@ fn total_read_json(read: &AggregateRead) -> serde_json::Value { entry } -/// The system values a create of a document owned by `owner_id` will have, as -/// far as a client can tell before its block: the device clock stands in for -/// the block time it records as its creation, update and transfer, and the -/// block heights are unknown until the block, so a rule reading one is not -/// judged. -fn system_values_for_create(owner_id: Identifier) -> DocumentSystemValues { +/// The system values the create of `document` will have, as far as a client +/// can tell before its block: its owner and its revision, the device clock in +/// place of the block time it records as its creation, update and transfer, +/// and no stored version, so a path through `$old.` reads absent, as consensus +/// reads it on a create, and a stored time, height or revision 0. The block +/// heights the create records are unknown until the block, so a rule reading +/// one is not judged; a stored height through `$old.` is. +fn system_values_for_create(document: &Document) -> DocumentSystemValues { // A clock before the epoch reads as the epoch; milliseconds fit a `u64` let now = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -388,7 +398,9 @@ fn system_values_for_create(owner_id: Identifier) -> DocumentSystemValues { created_at: Some(now), updated_at: Some(now), transferred_at: Some(now), - ..DocumentSystemValues::owned_by(owner_id) + revision: document.revision(), + stored: Some(StoredVersion::Absent), + ..DocumentSystemValues::owned_by(document.owner_id()) } } @@ -414,7 +426,7 @@ fn property_constraint_violation_json( ) })?; let data = Value::from(properties); - let system = system_values_for_create(document.owner_id()); + let system = system_values_for_create(document); let result = document_type .validate_property_constraints(&data, &system, platform_version) .map_err(|e| { @@ -674,6 +686,7 @@ mod tests { ], "readsOwner": false, "readsSystem": [], + "readsStored": false, "readsTotals": [], "readsReferenced": [] }, @@ -686,6 +699,7 @@ mod tests { ], "readsOwner": false, "readsSystem": [], + "readsStored": false, "readsTotals": [], "readsReferenced": [] }, @@ -698,6 +712,7 @@ mod tests { ], "readsOwner": false, "readsSystem": [], + "readsStored": false, "readsTotals": [], "readsReferenced": [] }, @@ -710,6 +725,7 @@ mod tests { ], "readsOwner": true, "readsSystem": [], + "readsStored": false, "readsTotals": [], "readsReferenced": [] }, @@ -719,6 +735,7 @@ mod tests { "reads": [{ "path": "fee", "kind": "value" }], "readsOwner": false, "readsSystem": [], + "readsStored": false, "readsTotals": [], "readsReferenced": [] } @@ -1027,6 +1044,79 @@ mod tests { assert_eq!(open.expect("checked"), serde_json::Value::Null); } + /// A mutable `listing` type whose rules read its revision and its stored + /// version: `createdUnrevised` (`$old.$revision` is 0, as on a create, and + /// `$revision` at most 1) and `priceNeverRises` (the price is at most the + /// stored one). + fn stored_contract_bytes() -> Vec { + let platform_version = PlatformVersion::latest(); + let documents = platform_value!({ + "listing": { + "type": "object", + "documentsMutable": true, + "properties": { + "price": { "type": "integer", "minimum": 0, "position": 0 } + }, + "required": ["price"], + "additionalProperties": false, + "propertyConstraints": { + "createdUnrevised": { + "allOf": [ + { "equal": ["$old.$revision", 0] }, + { "lessThanOrEqual": ["$revision", 1] } + ] + }, + "priceNeverRises": { "lessThanOrEqual": ["price", "$old.price"] } + } + } + }); + DataContractFactory::new(platform_version.protocol_version) + .expect("factory for the protocol version") + .create_with_value_config(Identifier::new(OWNER), 1, documents, None, None) + .expect("listing contract") + .data_contract() + .serialize_to_bytes_with_platform_version(platform_version) + .expect("serialized contract") + } + + /// The listing reports the rules reading the stored version, and the + /// pre-check, which checks a create, judges them as consensus judges a + /// create: with nothing under `$old.`, and the first revision. + #[test] + fn should_judge_stored_reads_as_a_create_has_none() { + let sdk = sdk_handle(PlatformVersion::latest()); + let contract = stored_contract_bytes(); + + let rules = rules_of(sdk, &contract, "listing"); + // A create's stored price reads 0, which a price above it breaks + let priced = check(sdk, &contract, "listing", json!({ "price": 5 }), OWNER); + let free = check(sdk, &contract, "listing", json!({ "price": 0 }), OWNER); + destroy_mock_sdk_handle(sdk); + + let rules = rules.expect("rules of listing"); + assert_eq!(rules[0]["name"], "createdUnrevised"); + assert_eq!( + rules[0]["readsSystem"], + json!(["$old.$revision", "$revision"]) + ); + assert_eq!(rules[0]["readsStored"], json!(true)); + assert_eq!(rules[1]["name"], "priceNeverRises"); + assert_eq!( + rules[1]["reads"], + json!([ + { "path": "price", "kind": "value" }, + { "path": "$old.price", "kind": "value" } + ]) + ); + assert_eq!(rules[1]["readsSystem"], json!([])); + assert_eq!(rules[1]["readsStored"], json!(true)); + + let priced = priced.expect("checked"); + assert_eq!(priced["rule"], "priceNeverRises"); + assert_eq!(priced["violation"], "NotMet"); + assert_eq!(free.expect("checked"), serde_json::Value::Null); + } + /// A `deal` type with two `ifThenElse` rules: `feePerPrice` (with a fee, the /// price is at least ten times it; without one, at most 100) and /// `openEndedSoldByOwner` (a deal without an end is sold by its owner, one @@ -1130,6 +1220,7 @@ mod tests { ], "readsOwner": false, "readsSystem": [], + "readsStored": false, "readsTotals": [], "readsReferenced": [] }, @@ -1149,6 +1240,7 @@ mod tests { ], "readsOwner": true, "readsSystem": ["$createdAt"], + "readsStored": false, "readsTotals": [], "readsReferenced": [] } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DocumentPropertyConstraints.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DocumentPropertyConstraints.swift index 73fb69883b7..5371810e50c 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DocumentPropertyConstraints.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DocumentPropertyConstraints.swift @@ -6,9 +6,16 @@ import Foundation /// properties must meet. Consensus checks every rule, in name order, and /// refuses a document breaking one with `DocumentPropertyConstraintViolatedError` /// (code 10422); a refused state transition is still paid for. A transfer or a -/// purchase is judged against the rules reading `$ownerId` or the transfer's -/// time or heights too, and a price update against the rules reading the -/// update's (see `readsOwner` and `readsSystem`). +/// purchase is judged against the rules reading the owner or the transfer's +/// time or heights too, a price update against the rules reading the +/// update's, and each of them against the rules reading `$revision` (see +/// `readsOwner` and `readsSystem`). +/// +/// A rule may read the stored version of the document a write replaces +/// through the `$old.` prefix (see `readsStored`): `$old.status` is the stored +/// `status`, `$old.$ownerId` the stored owner, and `$old.$updatedAt` or +/// `$old.$revision` a stored system value. A create has no stored version, so +/// there every such read is absent. /// /// Rust parses the rules and reports them /// (`dash_sdk_data_contract_get_property_constraints`); this type only carries @@ -23,7 +30,8 @@ public struct DocumentPropertyConstraint: Equatable, Sendable { /// sorting changes nothing a reader would notice). Among its operators: /// sizes (`{ "length": path }`, `{ "byteLength": path }`, /// `{ "count": path }`), `{ "countPresent": [path, path, ...] }`, system - /// times and heights as bare operands (`"$createdAt"`), + /// times, heights and `$revision` as bare operands (`"$createdAt"`), + /// paths of the stored version through `$old.` (`"$old.status"`), /// `{ "contains": [arrayPath, value] }`, /// `{ "startsWith": [a, b] }`, `{ "endsWith": [a, b] }`, /// `{ "notIn": [operand, [values]] }`, `{ "min": [a, b, ...] }`, @@ -38,34 +46,58 @@ public struct DocumentPropertyConstraint: Equatable, Sendable { /// Every property the rule reads, in declared order, a property read twice /// listed twice. The list describes the rule, not one document: it covers /// every branch of an `ifThen` or `ifThenElse`, whichever one a document - /// takes. `$ownerId` is no property and is not listed: see `readsOwner`; - /// nor are the system times and heights: see `readsSystem`. A property a - /// total's filter takes a value from is listed (`category` in + /// takes. A property of the stored version, read through `$old.`, is + /// listed under that path (`$old.status`): see `readsStored`. `$ownerId` + /// and `$old.$ownerId` are no properties and are not listed: see + /// `readsOwner`; nor are the system times, heights and revisions: see + /// `readsSystem`. A property a total's filter takes a value from is listed + /// (`category` in /// `{ "sumOf": ["listing", "price", { "category": "category" }] }`), the /// total itself is not: see `readsTotals`. Nor is a value of a document a /// reference points at: see `readsReferenced`. public let reads: [PropertyConstraintRead] - /// Whether the rule reads the document's owner, `$ownerId`, in any branch, - /// as in `reads`: by comparing it, or through a total that depends on it - /// (a `countOf` or `sumOf` filtered by `$ownerId`, see `readsTotals`). - /// Then a transfer or a purchase, which changes the owner, is judged - /// against it too. + /// Whether the rule reads the document's owner in any branch, as in + /// `reads`: by comparing `$ownerId`, or the stored version's owner + /// `$old.$ownerId`, or through a total that depends on it (a `countOf` or + /// `sumOf` filtered by `$ownerId`, see `readsTotals`). Then a transfer or + /// a purchase, which changes the owner, is judged against it too. public let readsOwner: Bool - /// The system times and heights the rule reads, by name, in declared - /// order, one read twice listed twice, every branch included as in - /// `reads`: `$createdAt`, `$updatedAt` and `$transferredAt` (block times, - /// in milliseconds), each also with `BlockHeight` or `CoreBlockHeight` - /// appended (the Platform and Core block heights), the names of wasm-dpp2's - /// `PropertyConstraintSystemProperty`. Consensus judges a price update - /// against the rules reading `$updatedAt…`, and a transfer or a purchase - /// against the rules reading `$transferredAt…` (or `$ownerId`). + /// The system values the rule reads, by name, in declared order, one read + /// twice listed twice, every branch included as in `reads`: `$createdAt`, + /// `$updatedAt` and `$transferredAt` (block times, in milliseconds), each + /// also with `BlockHeight` or `CoreBlockHeight` appended (the Platform and + /// Core block heights), and `$revision` (1 for a created document, one + /// more for each later write of it), the names of wasm-dpp2's + /// `PropertyConstraintSystemProperty`. A name prefixed with `$old.` is the + /// stored version's value (`$old.$updatedAt`, `$old.$revision`): see + /// `readsStored`. Consensus judges a price update against the rules + /// reading `$updatedAt…`, a transfer or a purchase against the rules + /// reading `$transferredAt…` (or the owner, see `readsOwner`), and each of + /// them against the rules reading `$revision`, of either version. /// /// Empty for a rule reading none, and for every rule reported by a library /// built before the field existed. public let readsSystem: [String] + /// Whether the rule reads the stored version of the document a write + /// replaces, through `$old.`: one of its properties (listed in `reads`), + /// its owner, `$old.$ownerId` (see `readsOwner`), or one of its system + /// values (listed in `readsSystem`). + /// + /// A create has no stored version, so consensus reads every such value as + /// absent there: a property as one the document leaves out (0, or its + /// `ifAbsent` value; absent to `present`; equal to no string or + /// identifier), `$old.$ownerId` as equal to no identifier, and a stored + /// time, height or revision as 0. The pre-check + /// (`SDK.checkDocumentPropertyConstraints`), which judges a document to + /// create, reads them the same way. + /// + /// `false` for a rule reading none, and for every rule reported by a + /// library built before the field existed. + public let readsStored: Bool + /// The `countOf` and `sumOf` totals the rule reads, in declared order, one /// read twice listed twice, every branch included as in `reads`: how many /// documents of a type of the same contract match a filter, or the total @@ -102,13 +134,15 @@ public struct DocumentPropertyConstraint: Equatable, Sendable { readsOwner: Bool, readsSystem: [String] = [], readsTotals: [PropertyConstraintTotalRead] = [], - readsReferenced: [PropertyConstraintReferencedRead] = [] + readsReferenced: [PropertyConstraintReferencedRead] = [], + readsStored: Bool = false ) { self.name = name self.ruleJSON = ruleJSON self.reads = reads self.readsOwner = readsOwner self.readsSystem = readsSystem + self.readsStored = readsStored self.readsTotals = readsTotals self.readsReferenced = readsReferenced } @@ -129,7 +163,9 @@ public struct DocumentPropertyConstraint: Equatable, Sendable { } /// Decode the JSON array `dash_sdk_data_contract_get_property_constraints` - /// returns, keeping its order (name order). + /// returns, keeping its order (name order). A rule without `readsSystem`, + /// `readsStored` or `readsTotals`, from a library built before the key, + /// reads as reading none. public static func list(fromJSON json: String) throws -> [DocumentPropertyConstraint] { guard let entries = try PropertyConstraintJSON.object(from: json) as? [Any] else { throw SDKError.serializationError("propertyConstraints rules are not a JSON array") @@ -142,7 +178,8 @@ public struct DocumentPropertyConstraint: Equatable, Sendable { let readsOwner = DocumentTypedArray.jsonBool(rule["readsOwner"]), let readsSystem = systemReads(rule["readsSystem"]), let readsTotals = totalReads(rule["readsTotals"]), - let readsReferenced = referencedReads(rule["readsReferenced"]) + let readsReferenced = referencedReads(rule["readsReferenced"]), + let readsStored = storedRead(rule["readsStored"]) else { throw SDKError.serializationError("Malformed propertyConstraints rule: \(entry)") } @@ -153,11 +190,21 @@ public struct DocumentPropertyConstraint: Equatable, Sendable { readsOwner: readsOwner, readsSystem: readsSystem, readsTotals: readsTotals, - readsReferenced: readsReferenced + readsReferenced: readsReferenced, + readsStored: readsStored ) } } + /// A rule's `readsStored`, `false` when the key is missing (a library + /// built before it), or `nil` for anything but a JSON boolean. + private static func storedRead(_ value: Any?) -> Bool? { + guard let value else { + return false + } + return DocumentTypedArray.jsonBool(value) + } + /// A rule's `readsSystem` names, `[]` when the key is missing (a library /// built before it), or `nil` for anything but an array of strings. private static func systemReads(_ value: Any?) -> [String]? { @@ -526,19 +573,27 @@ extension SDK { /// `serializedContract` is as for `documentPropertyConstraints`. Bridges /// `dash_sdk_data_contract_check_property_constraints`. /// + /// A create has no stored version, so a rule reading one through `$old.` + /// (`DocumentPropertyConstraint.readsStored`) is judged as consensus + /// judges it on a create, every such read absent (a stored time, height + /// or revision reads 0), and `$revision` reads 1, the revision a created + /// document starts at. + /// /// The block the create lands in is not known yet, so Rust estimates its /// system values: the device clock stands in for the block time the create /// records as `$createdAt`, `$updatedAt` and `$transferredAt`, and a rule - /// reading a block height (a `readsSystem` name ending in `BlockHeight` - /// or `CoreBlockHeight`) is not judged at all. Nor is a rule reading a - /// `countOf` or `sumOf` total (its `readsTotals` not empty), or a value of - /// a document a reference points at (its `readsReferenced` not empty): the - /// platform reads the total from state when the document is sent, and the + /// reading a block height the create records (a `readsSystem` name ending + /// in `BlockHeight` or `CoreBlockHeight` without `$old.`) is not judged + /// at all; a stored height (`$old.$createdAtBlockHeight`, ...) reads 0, + /// as above, and is judged. Nor is a rule reading a `countOf` or `sumOf` + /// total (its `readsTotals` not empty), or a value of a document a + /// reference points at (its `readsReferenced` not empty): the platform + /// reads the total from state when the document is sent, and the /// referenced document when it checks the reference, and this check reads /// no state. So `nil` does not promise consensus accepts the document: a - /// rule reading a block height, a total or a referenced document, or a - /// time rule the device clock judges differently from the block time, can - /// still refuse it. + /// rule reading a block height the create records, a total or a + /// referenced document, or a time rule the device clock judges differently + /// from the block time, can still refuse it. /// /// - Throws: `SDKError.invalidParameter` for an owner id that is not 32 /// bytes or properties that are not a JSON object, `SDKError.notFound` for diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDocumentType.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDocumentType.swift index 570e44d1b73..a1efe9242db 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDocumentType.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDocumentType.swift @@ -190,9 +190,10 @@ extension PersistentDocumentType { /// when it meets every rule judged: what /// `SDK.checkDocumentPropertyConstraints(serializedContract:documentType:propertiesJSON:ownerId:)` /// reports for the parent contract's stored platform serialization. As - /// there, the device clock stands in for the create's block time, and a - /// rule reading a block height, a `countOf` or `sumOf` total or a value of - /// a referenced document is not judged. + /// there, the device clock stands in for the create's block time, a + /// stored time, height or revision read through `$old.` reads 0, and a + /// rule reading a block height the create records, a `countOf` or `sumOf` + /// total or a value of a referenced document is not judged. /// /// - Throws: `SDKError.invalidState` when the parent contract has no /// stored serialization, or what the SDK call throws. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentTypeDetailsView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentTypeDetailsView.swift index 2beb74f810a..276ffaac5bf 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentTypeDetailsView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentTypeDetailsView.swift @@ -477,9 +477,9 @@ struct ExpandableIndexRowView: View { } /// One `propertyConstraints` rule: its name, the rule as declared, what it -/// reads (properties, `$ownerId`, system times and heights, `countOf` and -/// `sumOf` totals, values of referenced documents), and whether an owner -/// change is judged against it too. +/// reads (properties, `$ownerId`, system times, heights and revisions, the +/// stored version through `$old.`, `countOf` and `sumOf` totals, values of +/// referenced documents), and whether an owner change is judged against it too. struct PropertyConstraintRowView: View { let rule: DocumentPropertyConstraint @@ -515,7 +515,7 @@ struct PropertyConstraintRowView: View { if rule.readsOwner { Label( - "Reads $ownerId, the document's owner: transfers and purchases are judged against this rule too.", + "Reads the owner ($ownerId, $old.$ownerId, the owner before the write, or a total that depends on the owner): transfers and purchases are judged against this rule too.", systemImage: "person.crop.circle.badge.checkmark" ) .font(.caption2) @@ -527,7 +527,17 @@ struct PropertyConstraintRowView: View { .font(.caption2) .foregroundColor(.teal) .accessibilityIdentifier("documentType.propertyConstraint.\(rule.name).readsSystem") - Text("A price update is judged against the rules reading $updatedAt or its block heights, and a transfer or purchase against those reading $transferredAt or its block heights.") + Text("A price update is judged against the rules reading $updatedAt or its block heights, a transfer or purchase against those reading $transferredAt or its block heights, and each of them against those reading $revision.") + .font(.caption2) + .foregroundColor(.secondary) + } + + if rule.readsStored { + Label("Reads the stored version ($old.), the one a write replaces", systemImage: "clock.arrow.circlepath") + .font(.caption2) + .foregroundColor(.orange) + .accessibilityIdentifier("documentType.propertyConstraint.\(rule.name).readsStored") + Text("A create has no stored version: there, and in the check before sending, every $old. read is absent.") .font(.caption2) .foregroundColor(.secondary) } @@ -554,8 +564,8 @@ struct PropertyConstraintRowView: View { } .padding(.vertical, 4) // Keeps the row's identifier on the row and the readsSystem, - // readsTotals and readsReferenced lines' on those lines, rather than - // the row's on every child + // readsStored, readsTotals and readsReferenced lines' on those lines, + // rather than the row's on every child .accessibilityElement(children: .contain) .accessibilityIdentifier("documentType.propertyConstraint.\(rule.name)") } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift index 33c1a672e9c..8b0a1f695df 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift @@ -1835,8 +1835,9 @@ struct CreateDocumentView: View { /// The first propertyConstraints rule the document would break, or `nil` /// when it meets every rule judged or has none (the device clock stands in - /// for the block time, and a rule reading a block height, a `countOf` or - /// `sumOf` total or a value of a referenced document is not judged). + /// for the block time, a stored value read through `$old.` reads 0, and a + /// rule reading a block height the create records, a `countOf` or `sumOf` + /// total or a value of a referenced document is not judged). /// A check that cannot run (no SDK, no stored contract serialization) /// blocks nothing: consensus judges the document either way. private func propertyConstraintViolation( diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentPropertyConstraintsTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentPropertyConstraintsTests.swift index 925fe3f7cbf..282fe7fc621 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentPropertyConstraintsTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentPropertyConstraintsTests.swift @@ -1138,4 +1138,150 @@ final class DocumentPropertyConstraintsTests: XCTestCase { XCTAssertTrue(matches(error), "unexpected error: \(error)", file: file, line: line) } } + + /// Rules reading the stored version of the document through `$old.`, as + /// the FFI reports them: a stored property, the stored update time beside + /// `$revision`, and the stored owner, in name order beside a rule reading + /// none of it. + private let storedRulesJSON = """ + [ + { + "name": "closedOnlyFromOpen", + "readsOwner": false, + "readsSystem": [], + "readsStored": true, + "readsTotals": [], + "reads": [ + { "kind": "text", "path": "status" }, + { "kind": "text", "path": "$old.status" } + ], + "rule": { + "ifThen": [ + { "equal": ["status", { "const": "closed" }] }, + { "equal": ["$old.status", { "const": "open" }] } + ] + } + }, + { + "name": "priceCap", + "readsOwner": false, + "readsSystem": [], + "readsStored": false, + "readsTotals": [], + "reads": [{ "kind": "value", "path": "price" }], + "rule": { "lessThanOrEqual": ["price", 1000] } + }, + { + "name": "revisedAfterUpdate", + "readsOwner": false, + "readsSystem": ["$revision", "$updatedAt", "$old.$updatedAt"], + "readsStored": true, + "readsTotals": [], + "reads": [], + "rule": { + "allOf": [ + { "lessThanOrEqual": ["$revision", 100] }, + { "greaterThanOrEqual": ["$updatedAt", "$old.$updatedAt"] } + ] + } + }, + { + "name": "sellerUnchanged", + "readsOwner": true, + "readsSystem": [], + "readsStored": true, + "readsTotals": [], + "reads": [{ "kind": "identifier", "path": "sellerId" }], + "rule": { "equal": ["sellerId", "$old.$ownerId"] } + } + ] + """ + + // MARK: - Stored version reads + + /// A stored property is listed under its `$old.` path, a stored system + /// value under its `$old.` name beside `$revision`, and the stored owner + /// only as an owner read, never as a property. + func testStoredVersionReadsDecode() throws { + let rules = try DocumentPropertyConstraint.list(fromJSON: storedRulesJSON) + + XCTAssertEqual( + rules.map(\.name), + ["closedOnlyFromOpen", "priceCap", "revisedAfterUpdate", "sellerUnchanged"] + ) + XCTAssertEqual(rules.map(\.readsStored), [true, false, true, true]) + XCTAssertEqual( + rules[0].reads, + [ + PropertyConstraintRead(path: "status", kind: .text), + PropertyConstraintRead(path: "$old.status", kind: .text) + ] + ) + XCTAssertEqual(rules[2].readsSystem, ["$revision", "$updatedAt", "$old.$updatedAt"]) + XCTAssertEqual(rules[2].reads, []) + // `$old.$ownerId` is an owner read, not a property + XCTAssertEqual(rules[3].reads, [PropertyConstraintRead(path: "sellerId", kind: .identifier)]) + XCTAssertEqual(rules.map(\.readsOwner), [false, false, false, true]) + XCTAssertEqual(rules[3].ruleJSON, #"{"equal":["sellerId","$old.$ownerId"]}"#) + } + + /// A library built before `readsStored` leaves the key out. + func testMissingStoredReadDecodesAsFalse() throws { + let rules = try DocumentPropertyConstraint.list(fromJSON: """ + [{ "name": "r", "rule": { "present": "a" }, "readsOwner": false, + "readsSystem": [], "readsTotals": [], + "reads": [{ "path": "a", "kind": "presence" }] }] + """) + + XCTAssertEqual(rules.first?.readsStored, false) + } + + func testMalformedStoredReadsAreRefused() { + let rule = #""name": "r", "rule": {"present": "a"}, "reads": [], "readsOwner": false"# + let malformed = [ + // A number is not a boolean, although NSNumber would cast it + #"[{\#(rule), "readsStored": 1}]"#, + #"[{\#(rule), "readsStored": 0}]"#, + // Nor is a string + #"[{\#(rule), "readsStored": "true"}]"#, + // A null is no missing key + #"[{\#(rule), "readsStored": null}]"#, + #"[{\#(rule), "readsStored": []}]"#, + #"[{\#(rule), "readsStored": {}}]"# + ] + // The same rule with a boolean decodes + XCTAssertNoThrow(try DocumentPropertyConstraint.list(fromJSON: #"[{\#(rule), "readsStored": true}]"#)) + for json in malformed { + XCTAssertThrowsError(try DocumentPropertyConstraint.list(fromJSON: json), json) { error in + guard case SDKError.serializationError = error else { + return XCTFail("\(json): expected a serialization error, got \(error)") + } + } + } + } + + /// The initializer still builds a rule without naming `readsStored`, as it + /// did before the field existed. + func testInitializerDefaultsToNotReadingTheStoredVersion() { + let rule = DocumentPropertyConstraint( + name: "r", + ruleJSON: #"{"present":"a"}"#, + reads: [PropertyConstraintRead(path: "a", kind: .presence)], + readsOwner: false, + readsSystem: [] + ) + + XCTAssertFalse(rule.readsStored) + XCTAssertNotEqual( + rule, + DocumentPropertyConstraint( + name: "r", + ruleJSON: #"{"present":"a"}"#, + reads: [PropertyConstraintRead(path: "a", kind: .presence)], + readsOwner: false, + readsSystem: [], + readsStored: true + ) + ) + } } diff --git a/packages/wasm-dpp2/src/data_contract/document_type_property_constraints.rs b/packages/wasm-dpp2/src/data_contract/document_type_property_constraints.rs index a44e918240e..32ade856d87 100644 --- a/packages/wasm-dpp2/src/data_contract/document_type_property_constraints.rs +++ b/packages/wasm-dpp2/src/data_contract/document_type_property_constraints.rs @@ -8,23 +8,29 @@ //! (or `$ownerId`, the document's owner) with constants or with another //! property of its kind, a test of whether a string or a byte array starts or ends //! with another (`startsWith`, `endsWith`), a presence test (`present`, -//! `absent`), or `anyOf`, `allOf` or `not` over conditions. Consensus evaluates every rule on each create and -//! replace, and the rules reading `$ownerId` on each transfer and purchase, -//! refusing a broken one with `DocumentPropertyConstraintViolatedError` -//! (basic code 10422). What this module adds is *discovery* ("which rules does +//! `absent`), or `anyOf`, `allOf` or `not` over conditions. Through `$old.` a +//! rule reads the stored version of the document a write replaces. Consensus +//! evaluates every rule on each create and replace; on a transfer or a +//! purchase, the rules reading the owner, the transfer's time and heights or +//! `$revision`, of either version; on a price update, those reading the +//! update's or `$revision`; and on a moderator's change or restore, the rules +//! it can break, refusing a broken one with +//! `DocumentPropertyConstraintViolatedError` (basic code 10422). What this module adds is *discovery* ("which rules does //! this document type declare, and what do they read?") and a *pre-check* //! that evaluates a document against them with the very code consensus runs, //! so an app can find a broken rule before paying for a refused transition. use crate::error::{WasmDppError, WasmDppResult}; +use dpp::consensus::ConsensusError; +use dpp::consensus::basic::BasicError; use dpp::consensus::basic::document::PropertyConstraintViolation; use dpp::data_contract::document_type::DocumentTypeRef; use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters}; -use dpp::data_contract::document_type::methods::DocumentTypeBasicMethods; +use dpp::data_contract::document_type::methods::{DocumentTypeBasicMethods, DocumentTypeV0Methods}; use dpp::data_contract::document_type::property_constraints::{ - AggregateKind, DocumentSystemValues, PropertyRead, + AggregateKind, DocumentSystemValues, PropertyRead, StoredVersion, }; -use dpp::document::{Document, DocumentV0Getters}; +use dpp::document::{Document, DocumentV0Getters, INITIAL_REVISION}; use dpp::platform_value::Value; use dpp::version::PlatformVersion; use js_sys::{Array, BigInt, Object, Reflect}; @@ -49,7 +55,8 @@ export type PropertyConstraintReferenced = { /** * Where a rule reads a value: the dotted path of a property of the document - * type, or a value of a referenced document. + * type, that path under `$old.` for the stored version the write replaces + * (`$old.price`; absent on a create), or a value of a referenced document. */ export type PropertyConstraintPath = string | PropertyConstraintReferenced; @@ -60,9 +67,10 @@ export type PropertyConstraintPath = string | PropertyConstraintReferenced; * (rules report such a literal as a `bigint`, exactly); * - a string: the dotted path of an integer or boolean property, whose value * it takes (a boolean reads as 1 for true and 0 for false), 0 when the - * document leaves the property out; or a system time or height the - * document type records by listing it in `required` - * (`PropertyConstraintSystemProperty`); + * document leaves the property out, under `$old.` the stored version's; or + * a system value (`PropertyConstraintSystemProperty`): a time or height the + * document type records by listing it in `required`, or `$revision` on a + * type keeping one, either under `$old.` for the stored version's; * - `ifAbsent`: a property path and the integer it takes when left out; * - `add`, `multiply`, `min` and `max` over two or more operands, * `subtract`, `divide`, `modulo` and `power` over exactly two, `abs` over @@ -130,7 +138,9 @@ export type PropertyConstraintAggregateFilter = Record< * `endsWith` of strings or byte arrays. * * - a string: the dotted path of a string, an identifier or a byte array - * property, or `"$ownerId"`, the document's owner, an identifier; + * property, under `$old.` the stored version's, or `"$ownerId"`, the + * document's owner, or `"$old.$ownerId"`, the stored version's (the owner + * before a transfer or a purchase), each an identifier; * - `const`: a string constant, a base58 identifier beside an identifier * property or `$ownerId`, or hex digits, two a byte, beside a byte array * property in a `startsWith` or `endsWith`; @@ -156,7 +166,7 @@ export type PropertyConstraintEqualityOperand = * - a comparison of two integer expressions; `equal` and `notEqual` also * compare strings or identifiers, which are never ordered; * - `in`: an integer expression and two or more distinct integers, or a - * string or identifier property (or `$ownerId`) and two or more distinct + * string or identifier property (or `$ownerId` or `$old.$ownerId`) and two or more distinct * strings or base58 identifiers; * - `startsWith` / `endsWith`: two strings, a `const` or a string property * each, the first starting or ending with the second, byte for byte; or @@ -211,13 +221,20 @@ export type PropertyConstraintReadKind = | 'bytes'; /** - * A system time or height a rule reads: the block time in milliseconds - * (`At`), the Platform block height (`AtBlockHeight`) or the Core block height + * A system value a rule reads: the block time in milliseconds (`At`), the + * Platform block height (`AtBlockHeight`) or the Core block height * (`AtCoreBlockHeight`) of the document's creation, its last update (a create, * a replace or a price update) and its last transfer (a create, a transfer or - * a purchase). + * a purchase); or `$revision`, 1 on a create and one more for each later + * write. Under `$old.` it is the stored version's, the document a write + * replaces (0 on a create, which has none). */ export type PropertyConstraintSystemProperty = + | PropertyConstraintSystemValue + | `$old.${PropertyConstraintSystemValue}`; + +/** A system value of one version of the document. */ +export type PropertyConstraintSystemValue = | '$createdAt' | '$updatedAt' | '$transferredAt' @@ -226,7 +243,8 @@ export type PropertyConstraintSystemProperty = | '$transferredAtBlockHeight' | '$createdAtCoreBlockHeight' | '$updatedAtCoreBlockHeight' - | '$transferredAtCoreBlockHeight'; + | '$transferredAtCoreBlockHeight' + | '$revision'; /** * A `countOf` or `sumOf` total a rule reads: how many documents of @@ -269,22 +287,31 @@ export type DocumentPropertyConstraint = { /** The rule as the schema declares it. */ rule: PropertyConstraintCondition; /** - * Every property of the document type the rule reads, in declared order; - * `$ownerId` is no property and is not listed, and neither is a value of a - * referenced document (`readsReferenced`). + * Every property of the document type the rule reads, in declared order, + * one of the stored version under its `$old.` path; `$ownerId` and + * `$old.$ownerId` are no properties and are not listed, and neither is a + * value of a referenced document (`readsReferenced`). */ reads: Array<{ path: string; kind: PropertyConstraintReadKind }>; /** - * Whether the rule reads `$ownerId`, or a total that depends on the owner: - * then a transfer or a purchase is judged against it too. + * Whether the rule reads `$ownerId` or `$old.$ownerId`, or a total that + * depends on the owner: then a transfer or a purchase is judged against it + * too. */ readsOwner: boolean; /** - * The system times and heights the rule reads, in declared order. A price - * update is judged against a rule reading the update's, and a transfer or a - * purchase against one reading the transfer's. + * The system values the rule reads, in declared order, of either version. A + * price update is judged against a rule reading the update's, a transfer or + * a purchase against one reading the transfer's, and each against one + * reading `$revision`. */ readsSystem: PropertyConstraintSystemProperty[]; + /** + * Whether the rule reads the stored version of the document through + * `$old.`. `checkDocumentPropertyConstraints` judges it only when told what + * the stored version is: none for a create, or the stored document. + */ + readsStored: boolean; /** * The `countOf` and `sumOf` totals the rule reads, in declared order, one * read twice listed twice. The pre-check does not judge a rule reading one. @@ -484,10 +511,16 @@ pub(crate) fn property_constraints_for_document_type( name, )?; let reads_system = Array::new(); - for property in constraint.system_reads() { - reads_system.push(&JsValue::from_str(property.name())); + for read in constraint.system_reads() { + reads_system.push(&JsValue::from_str(&read.name())); } set_field(&object, "readsSystem", &reads_system, name)?; + set_field( + &object, + "readsStored", + &JsValue::from_bool(constraint.reads_stored()), + name, + )?; let reads_totals = Array::new(); for read in constraint.aggregate_reads() { let entry = Object::new(); @@ -530,36 +563,69 @@ pub(crate) fn property_constraints_for_document_type( } /// The system values a create or a replace of `document` will have, as far as -/// a client can tell before its block: the owner, and the stored times and -/// heights the write keeps, with the device clock standing in for the block -/// time it records (its update, and its creation and transfer when the -/// document has none yet). The block heights it records are unknown until the -/// block, so a rule reading one is not judged, and so is a rule reading a -/// `countOf` or `sumOf` total, or a value of a referenced document, which no -/// client reads from state here. -fn system_values_for_write(document: &Document) -> DocumentSystemValues { +/// a client can tell before its block: the owner, the revision, and the stored +/// times and heights the write keeps, with the device clock standing in for +/// the block time it records (its update, and its creation and transfer when +/// the document has none yet), and `stored`, the version it replaces. Told +/// which write it is, they are what consensus judges whatever `document` +/// holds: on a replace, the stored owner, creation and transfer, which a +/// replace keeps, and the revision after the stored one, the only one a +/// replace may write; on a create, the first revision and this block for +/// every time. Not told, it does not know the revision the write records +/// either, the first or the one after the stored. The block heights it records +/// are unknown until the block, so a rule reading one is not judged, and so is +/// a rule reading a `countOf` or `sumOf` total, or a value of a referenced +/// document, which no client reads from state here, or a stored version or +/// revision it is not given. +fn system_values_for_write( + document: &Document, + stored: Option, +) -> DocumentSystemValues { // Milliseconds since the epoch, a whole number well inside a `u64` let now = js_sys::Date::now() as u64; - let stored = DocumentSystemValues::of_document(document); + let values = match &stored { + Some(StoredVersion::Present(stored)) => DocumentSystemValues { + revision: stored + .system + .revision + .and_then(|revision| revision.checked_add(1)), + ..stored.system.as_written() + }, + Some(StoredVersion::Absent) => DocumentSystemValues { + owner_id: Some(document.owner_id()), + created_at: Some(now), + transferred_at: Some(now), + revision: Some(INITIAL_REVISION), + ..Default::default() + }, + None => DocumentSystemValues { + revision: None, + ..DocumentSystemValues::of_document(document) + }, + }; DocumentSystemValues { - created_at: stored.created_at.or(Some(now)), + created_at: values.created_at.or(Some(now)), updated_at: Some(now), - transferred_at: stored.transferred_at.or(Some(now)), + transferred_at: values.transferred_at.or(Some(now)), updated_at_block_height: None, updated_at_core_block_height: None, - ..stored + stored, + ..values } } /// The first rule of `document_type`'s `propertyConstraints` that `document` /// breaks, in name order, as consensus judges a create or replace: its /// properties with every `generatedFrom` property generated from its params, -/// as the transition builders send them, its owner for `$ownerId`, and its -/// system times and heights as [`system_values_for_write`] estimates them. +/// as the transition builders send them, its owner for `$ownerId`, its system +/// times and heights as [`system_values_for_write`] estimates them, and +/// `stored`, the version it replaces, for the paths through `$old.`, judged by +/// the code consensus judges with (`validate_property_constraints`). /// `undefined` when it meets them all. pub(crate) fn check_property_constraints( document_type: DocumentTypeRef<'_>, document: &Document, + stored: Option, ) -> WasmDppResult { let constraints = document_type.property_constraints(); if constraints.is_empty() { @@ -567,26 +633,32 @@ pub(crate) fn check_property_constraints( } let mut properties = document.properties().clone(); document_type.regenerate_generated_properties(&mut properties, PlatformVersion::desired())?; - let data = Value::from(properties); - let system = system_values_for_write(document); - for (name, constraint) in constraints { - if let Some(violation) = constraint.violation(&data, &system) { - let object = Object::new(); - set_field(&object, "rule", &JsValue::from_str(name), name)?; - set_field( - &object, - "violation", - &JsValue::from_str(violation_name(violation)), - name, - )?; - set_field( - &object, - "message", - &JsValue::from_str(&violation.to_string()), - name, - )?; - return Ok(object.into()); - } - } - Ok(JsValue::UNDEFINED) + let result = document_type.validate_property_constraints( + &Value::from(properties), + &system_values_for_write(document, stored), + PlatformVersion::desired(), + )?; + let Some(ConsensusError::BasicError(BasicError::DocumentPropertyConstraintViolatedError( + broken, + ))) = result.errors.first() + else { + return Ok(JsValue::UNDEFINED); + }; + let name = broken.constraint(); + let violation = broken.violation(); + let object = Object::new(); + set_field(&object, "rule", &JsValue::from_str(name), name)?; + set_field( + &object, + "violation", + &JsValue::from_str(violation_name(violation)), + name, + )?; + set_field( + &object, + "message", + &JsValue::from_str(&violation.to_string()), + name, + )?; + Ok(object.into()) } diff --git a/packages/wasm-dpp2/src/data_contract/model.rs b/packages/wasm-dpp2/src/data_contract/model.rs index 025602b6805..ea810b49a63 100644 --- a/packages/wasm-dpp2/src/data_contract/model.rs +++ b/packages/wasm-dpp2/src/data_contract/model.rs @@ -49,6 +49,7 @@ use dpp::data_contract::conversion::json::DataContractJsonConversionMethodsV0; use dpp::data_contract::conversion::value::v0::DataContractValueConversionMethodsV0; use dpp::data_contract::document_type::DocumentTypeRef; use dpp::data_contract::document_type::accessors::DocumentTypeV2Getters; +use dpp::data_contract::document_type::property_constraints::StoredVersion; use dpp::data_contract::errors::DataContractError; use dpp::data_contract::group::Group; use dpp::data_contract::schema::DataContractSchemaMethodsV0; @@ -58,6 +59,7 @@ use dpp::data_contract::validate_update::DataContractUpdateValidationMethodsV0; use dpp::data_contract::{ DataContract, GroupContractPosition, TokenConfiguration, TokenContractPosition, }; +use dpp::document::DocumentV0Getters; use dpp::platform_value::string_encoding::Encoding; use dpp::platform_value::string_encoding::Encoding::{Base64, Hex}; use dpp::platform_value::string_encoding::{decode, encode}; @@ -891,26 +893,45 @@ impl DataContractWasm { /// The first `propertyConstraints` rule `document` breaks, in name order, /// evaluated with the same code consensus runs on a create or replace: its - /// properties, its owner for `$ownerId`, and for the system times the - /// device clock in place of the block time the write will record (the - /// document's stored creation and transfer times when it has them). A - /// rule reading a block height the write records is not judged, since the - /// height is unknown until the block, a rule reading a `countOf` or - /// `sumOf` total, which only the platform reads from state (a rule's - /// `readsTotals` lists them), or a rule reading a value of the document a - /// reference points at, which the platform reads with the reference (a - /// rule's `readsReferenced` lists them). + /// properties, its owner for `$ownerId`, the revision the write records for + /// `$revision` (below), and for the system times the device clock in place + /// of the block time the + /// write will record (the document's stored creation and transfer times + /// when it has them). A rule reading a block height the write records is + /// not judged, since the height is unknown until the block, a rule reading + /// a `countOf` or `sumOf` total, which only the platform reads from state + /// (a rule's `readsTotals` lists them), or a rule reading a value of the + /// document a reference points at, which the platform reads with the + /// reference (a rule's `readsReferenced` lists them). /// `undefined` when it meets every rule of its document type. /// + /// `storedDocument` is the stored version the write replaces, which a rule + /// reads through `$old.` (a rule's `readsStored` says it does): the stored + /// document for a replace, `null` for a create, which has none, so that + /// every `$old.` read is absent. Left `undefined`, a rule reading it is not + /// judged, and neither is one reading `$revision`, which depends on the + /// write: 1 on a create, one more than the stored on a replace. Given + /// either, `$revision`, `$ownerId` and the creation and + /// transfer times are what consensus judges, whatever `document` holds: on + /// a replace the stored document's owner, creation and transfer and the + /// revision after its own, the only one consensus accepts on a replace; + /// on a create revision 1 and the device clock. + /// /// A pre-check, so an app can refuse a document before paying for a /// transition consensus would refuse with /// `DocumentPropertyConstraintViolatedError` (code 10422). It judges the /// rules alone, not the document's JSON schema. Throws when the document - /// belongs to another contract or names a document type this one lacks. + /// belongs to another contract or names a document type this one lacks, + /// and when the stored document is not the same document. #[wasm_bindgen(js_name = "checkDocumentPropertyConstraints")] pub fn check_document_property_constraints( &self, document: &DocumentWasm, + #[wasm_bindgen( + js_name = "storedDocument", + unchecked_param_type = "Document | null | undefined" + )] + stored_document: JsValue, ) -> WasmDppResult { let document_contract_id: Identifier = document.data_contract_id.into(); if document_contract_id != self.0.id() { @@ -929,7 +950,25 @@ impl DataContractWasm { )) })?; - Ok(check_property_constraints(document_type, &document.document)?.into()) + let stored = if stored_document.is_undefined() { + None + } else if stored_document.is_null() { + Some(StoredVersion::Absent) + } else { + let stored = stored_document.to_wasm::("Document")?; + let stored_contract_id: Identifier = stored.data_contract_id.into(); + let same_document = stored_contract_id == document_contract_id + && stored.document_type_name == document.document_type_name + && stored.document.id() == document.document.id(); + if !same_document { + return Err(WasmDppError::invalid_argument( + "the stored document is another document than the one checked".to_string(), + )); + } + Some(StoredVersion::of_document(&stored.document)) + }; + + Ok(check_property_constraints(document_type, &document.document, stored)?.into()) } /// Whether `newContract` is an update of this contract the platform diff --git a/packages/wasm-dpp2/tests/unit/DocumentPropertyConstraints.spec.ts b/packages/wasm-dpp2/tests/unit/DocumentPropertyConstraints.spec.ts index cc653c96df0..0bf6c4f4cce 100644 --- a/packages/wasm-dpp2/tests/unit/DocumentPropertyConstraints.spec.ts +++ b/packages/wasm-dpp2/tests/unit/DocumentPropertyConstraints.spec.ts @@ -156,6 +156,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [], readsOwner: false, readsSystem: ['$createdAt'], + readsStored: false, readsTotals: [], readsReferenced: [{ reference: 'pollId', path: 'endsAt', kind: 'value' }], }, @@ -165,6 +166,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [{ reference: 'pollId', path: 'status', kind: 'text' }], }, @@ -181,7 +183,7 @@ describe('DataContract: propertyConstraints (v14)', () => { revision: BigInt(1), }); - expect(contract.checkDocumentPropertyConstraints(vote)).to.equal(undefined); + expect(contract.checkDocumentPropertyConstraints(vote, null)).to.equal(undefined); }); }); @@ -199,6 +201,7 @@ describe('DataContract: propertyConstraints (v14)', () => { ], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -211,6 +214,7 @@ describe('DataContract: propertyConstraints (v14)', () => { ], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -223,6 +227,7 @@ describe('DataContract: propertyConstraints (v14)', () => { ], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -235,6 +240,7 @@ describe('DataContract: propertyConstraints (v14)', () => { ], readsOwner: true, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -244,6 +250,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [{ path: 'fee', kind: 'value' }], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -300,6 +307,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [{ path: 'tags', kind: 'count' }, { path: 'maxTags', kind: 'value' }], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -309,6 +317,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [{ path: 'title', kind: 'length' }], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -323,13 +332,16 @@ describe('DataContract: propertyConstraints (v14)', () => { }); expect(contract.checkDocumentPropertyConstraints( listing({ title: 'Café', tags: ['a', 'b'], maxTags: 2 }), + null, )).to.equal(undefined); expect(contract.checkDocumentPropertyConstraints( listing({ title: 'Café', tags: ['a', 'b', 'c'], maxTags: 2 }), + null, )).to.deep.include({ rule: 'tagsWithinLimit', violation: 'NotMet' }); // 8 characters, 16 bytes expect(contract.checkDocumentPropertyConstraints( listing({ title: 'éééééééé' }), + null, )).to.deep.include({ rule: 'titleBytes', violation: 'NotMet' }); }); @@ -357,6 +369,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [{ path: 'endsAt', kind: 'value' }], readsOwner: false, readsSystem: ['$createdAt'], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -366,6 +379,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [], readsOwner: false, readsSystem: ['$createdAtBlockHeight'], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -379,11 +393,11 @@ describe('DataContract: propertyConstraints (v14)', () => { revision: BigInt(1), }); // Ended in 1970: before a create today, by the device clock - expect(contract.checkDocumentPropertyConstraints(listing(1))) + expect(contract.checkDocumentPropertyConstraints(listing(1), null)) .to.deep.include({ rule: 'endsAfterCreation', violation: 'NotMet' }); // Ends in 2100; the block height a create records is unknown before its // block, so the height rule is not judged - expect(contract.checkDocumentPropertyConstraints(listing(4102444800000))) + expect(contract.checkDocumentPropertyConstraints(listing(4102444800000), null)) .to.equal(undefined); }); @@ -414,6 +428,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [{ path: 'labels', kind: 'elements' }], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -426,8 +441,8 @@ describe('DataContract: propertyConstraints (v14)', () => { ownerId, revision: BigInt(1), }); - expect(contract.checkDocumentPropertyConstraints(listing(['new']))).to.equal(undefined); - expect(contract.checkDocumentPropertyConstraints(listing(['new', 'used']))) + expect(contract.checkDocumentPropertyConstraints(listing(['new']), null)).to.equal(undefined); + expect(contract.checkDocumentPropertyConstraints(listing(['new', 'used']), null)) .to.deep.include({ rule: 'notUsed', violation: 'NotMet' }); }); @@ -458,11 +473,11 @@ describe('DataContract: propertyConstraints (v14)', () => { ownerId, revision: BigInt(1), }); - expect(contract.checkDocumentPropertyConstraints(link('https://pay.dash'))).to.equal(undefined); - expect(contract.checkDocumentPropertyConstraints(link('https://pay.com'))) + expect(contract.checkDocumentPropertyConstraints(link('https://pay.dash'), null)).to.equal(undefined); + expect(contract.checkDocumentPropertyConstraints(link('https://pay.com'), null)) .to.deep.include({ rule: 'dashDomain', violation: 'NotMet' }); // No case folding - expect(contract.checkDocumentPropertyConstraints(link('HTTPS://pay.dash'))) + expect(contract.checkDocumentPropertyConstraints(link('HTTPS://pay.dash'), null)) .to.deep.include({ rule: 'secureUrl', violation: 'NotMet' }); }); @@ -505,7 +520,7 @@ describe('DataContract: propertyConstraints (v14)', () => { revision: BigInt(1), }); const violationOf = (properties: Record) => ( - contract.checkDocumentPropertyConstraints(profile(properties)) + contract.checkDocumentPropertyConstraints(profile(properties), null) ); expect(violationOf({ corePaymentAddress: address(1) })).to.equal(undefined); @@ -555,7 +570,7 @@ describe('DataContract: propertyConstraints (v14)', () => { revision: BigInt(1), }); const violationOf = (properties: Record) => ( - contract.checkDocumentPropertyConstraints(order(properties)) + contract.checkDocumentPropertyConstraints(order(properties), null) ); expect(violationOf({ price: 100, fee: 10 })).to.equal(undefined); @@ -618,6 +633,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [{ kind: 'countOf', documentType: 'listing', filter: [] }], readsReferenced: [], }, @@ -627,6 +643,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [], readsOwner: true, readsSystem: [], + readsStored: false, readsTotals: [{ kind: 'countOf', documentType: 'listing', filter: ['$ownerId'] }], readsReferenced: [], }, @@ -636,6 +653,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [{ path: 'category', kind: 'value' }], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [{ kind: 'sumOf', documentType: 'listing', property: 'price', filter: ['category'], }], @@ -652,7 +670,7 @@ describe('DataContract: propertyConstraints (v14)', () => { ownerId, revision: BigInt(1), }); - expect(contract.checkDocumentPropertyConstraints(listing)).to.equal(undefined); + expect(contract.checkDocumentPropertyConstraints(listing, null)).to.equal(undefined); }); it('should report integer literals past Number.MAX_SAFE_INTEGER exactly, as bigint', () => { @@ -679,6 +697,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [{ path: 'balance', kind: 'value' }], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -688,6 +707,7 @@ describe('DataContract: propertyConstraints (v14)', () => { reads: [{ path: 'tier', kind: 'value' }], readsOwner: false, readsSystem: [], + readsStored: false, readsTotals: [], readsReferenced: [], }, @@ -711,25 +731,194 @@ describe('DataContract: propertyConstraints (v14)', () => { const contract = buildContract(schemas, 13, false); expect(contract.documentTypePropertyConstraints('offer')).to.deep.equal([]); - expect(contract.checkDocumentPropertyConstraints(offer(contract, { discount: 200 }))) + expect(contract.checkDocumentPropertyConstraints(offer(contract, { discount: 200 }), null)) .to.equal(undefined); }); }); + describe('rules reading the stored version ($old.)', () => { + const rules = { + atMostThreeWrites: { lessThanOrEqual: ['$revision', 3] }, + priceNeverRises: { lessThanOrEqual: ['price', { ifAbsent: ['$old.price', 1000000] }] }, + }; + const listingSchemas = { + listing: { + type: 'object', + documentsMutable: true, + properties: { + price: { type: 'integer', minimum: 0, position: 0 }, + }, + required: ['price'], + additionalProperties: false, + propertyConstraints: rules, + }, + }; + // A fixed id, so that a stored and a written version are the same document + const listingId = otherId; + + function listing( + contract: InstanceType, + price: number, + revision: number, + ) { + return new wasm.Document({ + id: listingId, + properties: { price }, + documentTypeName: 'listing', + dataContractId: contract.id, + ownerId, + revision: BigInt(revision), + }); + } + + it('should report the stored reads and $revision a rule reads', () => { + const contract = buildContract(listingSchemas); + + expect(contract.documentTypePropertyConstraints('listing')).to.deep.equal([ + { + name: 'atMostThreeWrites', + rule: rules.atMostThreeWrites, + reads: [], + readsOwner: false, + readsSystem: ['$revision'], + readsStored: false, + readsTotals: [], + readsReferenced: [], + }, + { + name: 'priceNeverRises', + rule: rules.priceNeverRises, + reads: [ + { path: 'price', kind: 'value' }, + { path: '$old.price', kind: 'value' }, + ], + readsOwner: false, + readsSystem: [], + readsStored: true, + readsTotals: [], + readsReferenced: [], + }, + ]); + }); + + it('should judge them against the stored document, a create, or not at all', () => { + const contract = buildContract(listingSchemas); + const stored = listing(contract, 100, 1); + + // A replace: the price may only drop + expect(contract.checkDocumentPropertyConstraints(listing(contract, 90, 2), stored)) + .to.equal(undefined); + expect(contract.checkDocumentPropertyConstraints(listing(contract, 120, 2), stored)) + .to.deep.include({ rule: 'priceNeverRises', violation: 'NotMet' }); + // A create has no stored version: the default stands in for the stored price + expect(contract.checkDocumentPropertyConstraints(listing(contract, 120, 1), null)) + .to.equal(undefined); + // Not told which write it is, neither the rule reading the stored version nor + // the one reading the revision the write records is judged + expect(contract.checkDocumentPropertyConstraints(listing(contract, 120, 2), undefined)) + .to.equal(undefined); + expect(contract.checkDocumentPropertyConstraints(listing(contract, 120, 4), undefined)) + .to.equal(undefined); + }); + + it('should judge the revision a replace writes, as the replacement built from the edit sends it', () => { + const contract = buildContract(listingSchemas); + // Fetched at revision 3 and edited in place, as an app replaces a document + const stored = listing(contract, 100, 3); + const edited = listing(contract, 90, 3); + const replacement = new wasm.DocumentReplaceTransition({ + document: edited, identityContractNonce: BigInt(1), + }); + + // The replacement writes revision 4, the only one consensus accepts + expect(replacement.revision).to.equal(BigInt(4)); + expect(contract.checkDocumentPropertyConstraints(edited, stored)) + .to.deep.include({ rule: 'atMostThreeWrites', violation: 'NotMet' }); + // Whatever revision the document checked holds + expect(contract.checkDocumentPropertyConstraints(listing(contract, 90, 4), stored)) + .to.deep.include({ rule: 'atMostThreeWrites', violation: 'NotMet' }); + // A replace of revision 2 writes revision 3, within the rule + expect(contract.checkDocumentPropertyConstraints(edited, listing(contract, 100, 2))) + .to.equal(undefined); + // A create writes revision 1 + expect(contract.checkDocumentPropertyConstraints(listing(contract, 90, 7), null)) + .to.equal(undefined); + }); + + it('should judge the creation a replace keeps, not the device clock', () => { + const dayMs = 86400000; + const contract = buildContract({ + note: { + type: 'object', + documentsMutable: true, + properties: { + text: { type: 'string', maxLength: 63, position: 0 }, + }, + required: ['text', '$createdAt', '$updatedAt'], + additionalProperties: false, + propertyConstraints: { + editableForADay: { lessThanOrEqual: [{ subtract: ['$updatedAt', '$createdAt'] }, dayMs] }, + }, + }, + }); + const note = (text: string, revision: number, createdAt?: number) => { + const document = new wasm.Document({ + id: listingId, + properties: { text }, + documentTypeName: 'note', + dataContractId: contract.id, + ownerId, + revision: BigInt(revision), + }); + if (createdAt !== undefined) { + document.createdAt = BigInt(createdAt); + } + return document; + }; + + // The edit carries no creation time; the stored document's stands + expect(contract.checkDocumentPropertyConstraints( + note('edited', 2), + note('first', 1, Date.now() - 3 * dayMs), + )).to.deep.include({ rule: 'editableForADay', violation: 'NotMet' }); + expect(contract.checkDocumentPropertyConstraints( + note('edited', 2), + note('first', 1, Date.now() - dayMs / 24), + )).to.equal(undefined); + // A create is created now, whatever the document holds + expect(contract.checkDocumentPropertyConstraints(note('first', 1, 1), null)) + .to.equal(undefined); + }); + + it('should throw for a stored document that is another document', () => { + const contract = buildContract(listingSchemas); + const other = new wasm.Document({ + properties: { price: 100 }, + documentTypeName: 'listing', + dataContractId: contract.id, + ownerId, + revision: BigInt(1), + }); + + expect(() => contract.checkDocumentPropertyConstraints(listing(contract, 90, 2), other)) + .to.throw(/another document/); + }); + }); + describe('checkDocumentPropertyConstraints()', () => { it('should report nothing for a document meeting every rule', () => { const contract = buildContract(schemas); - expect(contract.checkDocumentPropertyConstraints(offer(contract, {}))).to.equal(undefined); + expect(contract.checkDocumentPropertyConstraints(offer(contract, {}), null)).to.equal(undefined); expect(contract.checkDocumentPropertyConstraints(offer(contract, { status: 'closed', closedAt: 1000, sellerId: ownerId, discount: 5, - }))).to.equal(undefined); + }), null)).to.equal(undefined); }); it('should report the first rule broken, in name order, as consensus would', () => { const contract = buildContract(schemas); const violationOf = (properties: Record, owner = ownerId) => ( - contract.checkDocumentPropertyConstraints(offer(contract, properties, owner)) + contract.checkDocumentPropertyConstraints(offer(contract, properties, owner), null) ); expect(violationOf({ status: 'closed' })).to.deep.include({ @@ -751,10 +940,11 @@ describe('DataContract: propertyConstraints (v14)', () => { it('should read the document owner for $ownerId', () => { const contract = buildContract(schemas); - expect(contract.checkDocumentPropertyConstraints(offer(contract, { sellerId: otherId }))) + expect(contract.checkDocumentPropertyConstraints(offer(contract, { sellerId: otherId }), null)) .to.deep.include({ rule: 'sellerIsOwner', violation: 'NotMet' }); expect(contract.checkDocumentPropertyConstraints( offer(contract, { sellerId: otherId }, otherId), + null, )).to.equal(undefined); }); @@ -768,7 +958,7 @@ describe('DataContract: propertyConstraints (v14)', () => { revision: BigInt(1), }); - expect(contract.checkDocumentPropertyConstraints(document)).to.equal(undefined); + expect(contract.checkDocumentPropertyConstraints(document, null)).to.equal(undefined); }); it('should throw for a document of another contract or an unknown type', () => { @@ -788,8 +978,8 @@ describe('DataContract: propertyConstraints (v14)', () => { revision: BigInt(1), }); - expect(() => contract.checkDocumentPropertyConstraints(foreign)).to.throw(/another contract|not this one/); - expect(() => contract.checkDocumentPropertyConstraints(unknownType)).to.throw(/not found/); + expect(() => contract.checkDocumentPropertyConstraints(foreign, null)).to.throw(/another contract|not this one/); + expect(() => contract.checkDocumentPropertyConstraints(unknownType, null)).to.throw(/not found/); }); });