Repository navigation
feat(platform)!: add contract groups - #4791
Conversation
A contract group is an identity-owned set of contracts, contract document
types and contract tokens. A group is registered by a data contract create
transition; later contracts created by an owner can add themselves, one of
their document types, or one of their tokens to it in their own create
transition.
Wire: DataContractCreateTransition version 1 adds `contractGroup`, an
optional registration carrying the owner (single or multi owner), a name and
a description, and `contractGroupMemberships`. The group id is derived, not
sent: hash_double("contract_group" || owner id || identity nonce), which can
never collide with the contract id the same transition derives. Version 0
stays valid and carries neither; the version bounds gate version 1 to
protocol version 14.
Storage: a new `ContractGroups` root tree (key 68) holds every group under
`Groups` and a backwards index from each member contract under `Members`.
The backwards entries are plain one-hop GroveDB references; memberships are
append-only and contracts are never deleted, so a reference cannot dangle.
Fresh chains build the tree in `create_initial_state_structure` v4, upgrading
chains in `transition_to_version_14`.
Validation: structure checks (owner rules, name and description lengths,
member existence in the created contract, duplicates, redundancy, membership
cap) are unpaid, codes 10360 to 10367. State checks (the registered group
must be new, every group joined must exist and count the signer among its
owners) are paid with a nonce bump, codes 40218 to 40220. Each group lookup
is billed.
`SystemLimits::max_contract_group_size` becomes `max_group_member_count`: it
bounds the members of a change-control `Group` inside a contract, which is a
different thing from a contract group. Protocol version 14 is unreleased, so
the rename is in place across every table.
Co-Authored-By: Claude Opus 5 <[email protected]>
|
Important Review skippedToo many files! This PR contains 130 files, which is 30 over the limit of 100. To get a review, reduce the PR to 100 files or fewer by splitting it into smaller PRs or changing its base branch. Upgrade to a paid plan to raise the limit. This review couldn't start because sufficient usage credits or metered capacity aren't available. Add credits or update usage-based reviews in the billing tab, then retry. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (130)
You can disable this status message by setting the Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
🕓 Queued for automated review — 5th in line, estimated start in ~2.7 h (commit 5e0f738)
|
… version The factory test asserted the transition it builds is version 0. PV14 raised the default contract create transition version to 1, so the assertion now compares against the versioned default instead of a literal. Co-Authored-By: Claude Fable 5.1 <[email protected]>
A Data Model chapter covering what a contract group is, the id derivation, the wire and stored types, version 1 of the create transition and its bounds, the unpaid structure and paid state checks with their codes, the action and operation ordering, the ContractGroups root tree layout and why it uses plain references, cost estimation, tree creation on fresh and upgrading chains, fetch, prove and verify, the version tables and limits touched, fees, what is deliberately not there yet, the tests, and the rules to follow. The error codes chapter gains the two new ranges. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
📖 Book Preview built successfully. Download the preview from the workflow artifacts. Updated at 2026-09-17T01:53:10.594Z |
The three contract group state errors were numbered 40218 to 40220, inside the identity block, while every other family has its own hundred. They move to 41000 to 41002 (40900 is shielded). Protocol version 14 is unreleased, so nothing shipped with the old numbers. The book's error codes chapter gains the shielded row it was missing along with the new contract group row. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Contact requests and profiles are document types of the one dashpay contract, not separate contracts. The opening now motivates contract groups from what actually pushes a project onto several contracts: frozen indexes, tokens kept apart, and versioned contracts. The JSON example no longer borrows the dashpay name. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The new root tree at key 68 lands under the SpentAssetLockTransactions (72) node of the root Merk. Two drive initialization tests now count 18 root elements and expect the larger proof for that node, plus a proof for the new tree. Four drive-abci fee tests that write an asset lock outpoint moved by 1480 credits; each becomes a helper run at the latest version with the new fee and at protocol version 13 with the old one, so a leak into the released version would fail the twin. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ractGroups root tree The nightly chain-simulation suite runs run_chain_one_identity_in_solitude at the latest version; its identity creation writes a spent asset lock outpoint, so the balance moves by the same 1480 credits as the unit fee tests. The protocol version 13 twin keeps the old balance and its comment now explains the difference instead of claiming parity. Co-Authored-By: Claude Fable 5.1 <[email protected]>
MultiOwner, a set of co-owners any of whom could register or add
members, becomes OwnerAndAdmins { owner, admins }: one owner, who must
be the identity registering the group in both forms, plus one to
sixteen admins who may add members alongside it. Being named as an
admin is not enough to register. InvalidContractGroupOwnersError
becomes InvalidContractGroupAdminsError (10364) and
IdentityNotContractGroupOwnerError becomes
IdentityNotContractGroupOwnerOrAdminError (41002); the limit is
max_contract_group_admins. Docs, book chapter and tests follow.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## v4.2-dev #4791 +/- ##
============================================
+ Coverage 78.51% 78.53% +0.02%
============================================
Files 2868 2905 +37
Lines 411869 416700 +4831
============================================
+ Hits 323396 327275 +3879
- Misses 88473 89425 +952
🚀 New features to boost your workflow:
|
The whole-group query enumerated every member with no limit. The 16 membership cap is per creating transition, so a group can grow without bound across contracts, and fetching or proving a large group was unbounded work and proof size. The group's information now has its own single-item proof, and members are read one kind at a time (contracts, document types, tokens) in pages: a start-after cursor, key order, and a limit that must lie between 1 and the node's max_query_limit on both the fetch and the proof side. For the two-level kinds the cursor's contract gets a conditional subquery starting after the cursor's entry, so a page can end mid-contract and the next resumes there. The per-contract memberships query keeps no limit: memberships are creation-only and capped at 16 per contract. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Consensus and wire format: - gate DataContractCreateTransition V1 to protocol version 14 and later in active_version_range, independently of the embedded contract format - drop the redundant owner from ContractGroupRegistration; the registrant is the owner, a registration only names admins, and 10365 is unassigned - validate that every admin identity exists and is not a masternode identity (new state error 41003 ContractGroupAdminNotFoundError) - read the registered group id from the action instead of re-deriving it, and bill the double SHA-256 the derivation costs - check new memberships against the contract's existing memberships, not only against the transition, and create per-contract trees only if they do not exist yet - move the ContractGroups root tree from key 68 to key 124 so it hangs under the Versions node and leaves asset lock fees unchanged - default the V1 contract group fields when decoding JSON Storage: - store document type and token members of a group under a flat composite key (contract id followed by name or position) instead of a subtree per contract, so a continuation page is a plain range after the cursor key and GroveDB never charges an empty descent against the page limit - share insert_contract_groups_structure between genesis and the protocol version 14 upgrade Bindings and cleanup: - share the signing tail between the V0 and V1 create transition methods - expose the V1 fields in wasm-dpp2 and pick the transition version from the platform version Tests: frozen discriminant test pins 41003; protocol version 13 twins for the root structure and heights; transition_to_version_14 tree creation; V0 create at the latest version; V1 JSON round trip and default; unknown admin and already-held membership paid failures; limit-one paging past a contract with no entries left. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Issue being fixed or feature implemented
Contract groups: an identity-owned set of contracts, contract document types and contract tokens. A group is registered when creating a data contract, and later contracts created by an owner can add themselves, one of their document types, or one of their tokens to it. This gives a project a provable, on-chain statement that a set of contracts, types and tokens belong together, for anything that later wants to act on the set as a whole (a contract-group key bound, aggregate queries, tooling).
This is the first of several PRs. It lands the consensus core: wire format, storage, validation, proofs. DAPI queries and the SDK surfaces follow separately.
What was done?
Wire (
rs-dpp)DataContractCreateTransitionV1= V0 pluscontract_group: Option<ContractGroupRegistration>andcontract_group_memberships: Vec<ContractGroupMembership>, both defaulting to empty when decoded from JSON. V0 stays valid and carries neither;active_version_rangeand the serialization bounds gate V1 to protocol version 14 (max 1, default 1), so a v13 node rejects it whichever contract format it embeds.dpp::contract_group:ContractGroupOwner(SingleOwner(id)/OwnerAndAdmins { owner, admins }),ContractGroupMember(Contract/DocumentType(name)/Token(position)),ContractGroupMembership,ContractGroupRegistration(admins, name, description; the owner is the transition signer and is never on the wire), versionedContractGroupInfoandgenerate_contract_group_id.hash_double("contract_group" || owner_id || identity_nonce). The contract created by the same transition ishash_double(owner_id || identity_nonce), so a client knows both ids up front and they cannot collide.Storage (
rs-drive)New root tree
ContractGroups(key 124, under theVersionsnode so no existing root node gains a child and asset lock fees do not move):The backwards side holds plain one-hop
UpstreamRootHeightReferences rather than GroveDB bidirectional references: memberships are append-only and contracts are never deleted, so nothing can dangle, and a bidirectional reference would add a backref slot per forward leaf for cleanup that never happens.Membersis keyed by contract first so "is document type D of contract C in group G" is one point lookup, which is what a futureContractBounds::ContractGroupcheck would need per batch member. Document type and token members of a group sit on one level under a composite key (contract id followed by the name or position) rather than under a subtree per contract, so a page of members is a plain range after the cursor key with no descent that could be empty.Fresh chains build the three trees in
create_initial_state_structurev4; upgrading chains build them intransition_to_version_14. Both call the sameinsert_contract_groups_structure, which inserts each tree only if it does not exist. Insert, fetch, prove, verify and estimation all sit underdrive.methods.contract_group/drive.methods.verify.contract_group.Validation (
rs-drive-abci)RegisterContractGroupbeforeAddContractGroupMemberships, both after the contract itself, so a contract can join the group its own transition registers.Limits rename
SystemLimits::max_contract_group_sizebecomesmax_group_member_count. It bounds the members of a change-controlGroupdeclared inside a contract, which is a different concept from a contract group, and keeping both names as "contract group" would be a trap. Protocol version 14 is unreleased, so the rename is in place across every table. New limits:max_contract_group_memberships_per_contract(16),max_contract_group_admins(16),max_contract_group_name_length(64),max_contract_group_description_length(256).Docs
docs/protocol/contract-groups.md: the protocol note.book/src/data-model/contract-groups.md(Data Model section): the model and id derivation, the types, create transition V1 and its bounds, the unpaid structure and paid state checks with codes, action and operation ordering, the root tree layout and why it uses plain references, cost estimation, tree creation on fresh and upgrading chains, fetch/prove/verify, the version tables and limits touched, fees, what is deliberately not there yet, tests, and rules. The error codes chapter lists the two new ranges.mdbook buildis clean.Tests
rs-dpp(3): id derivation is distinct from the contract id and stable; owner resolution for both kinds; stored info round-trips through bincode.rs-drive(6): the root tree exists at genesis on v14 and is absent on v13; registration with present and absent proofs; memberships recorded on both sides for two contracts and three member kinds, each proved and verified; estimation builds the same operations as apply and its fee is never below actual; a second registration of the same id is refused.rs-drive-abci(9): register and join in one transition; an owner adding later contracts by document type and by token, with the proof verified against the committed root; joining a group you do not own is a paid failure with the nonce bumped and nothing written; joining an unknown group; a group with admins accepts the owner and each admin and refuses an outsider; naming an unknown admin, and re-adding a membership the contract already holds, are paid failures; a version 0 create still processes at the latest version; malformed registrations and memberships each produce their own structure error.Workspace
cargo check --testsis clean andclippy -D warningspasses ondpp,drive,drive-abciandplatform-version.CI on the first push failed
data_contract::factory::v0::tests::should_create_data_contract_create_transition_from_data_contract, which asserted the factory builds a version 0 transition; the targeted runs above had filtered it out. It now compares against the versioneddefault_current_version(3d0bec9), and the wholedpppackage (4263 tests,--all-features) passes locally.The state codes were moved from 40218-40220, which sat inside the identity block, to their own range 41000-41002 (40900 belongs to shielded errors). PV14 is unreleased, so nothing shipped with the old numbers.
A local no-fail-fast run of the whole
driveanddrive-abcipackages found what CI's fail-fast would have shown one at a time (cada386): the drive initialization tests count 18 root trees and prove the new tree, and four drive-abci fee tests that write an asset lock outpoint (identity create validation, asset lock reuse after issue, asset lock replay attack, identity top-up validation) each became arun_*_at_protocol_versionhelper with a_protocol_version_13twin. The root key was first 68, which sat underSpentAssetLockTransactionsand raised every asset lock fee by 1480 credits; it is now 124, under theVersionsnode, so those fees are unchanged and the twins pin the latest-version fee equal to the version 13 fee. The chain-simulation baselinerun_chain_one_identity_in_solitude_latest_protocol_versionis likewise back at its version 13 balance.Review fix: the whole-group query enumerated every member with no limit, and a group can grow without bound across contracts (the 16 cap is per creating transition), so fetching or proving a large group was unbounded work. It is replaced by a separate info proof (
fetch_/prove_/verify_contract_group_info) and paged member enumeration (fetch_/prove_/verify_contract_group_members) driven by aContractGroupMembersQuerythat names one kind (Contracts,DocumentTypes,Tokens) and astart_aftercursor, with alimitthat must lie between 1 and the node'smax_query_limiton both the fetch and the proof side. Document type and token members are stored under a flat composite key (contract id followed by the name or position), so every kind pages with a plain range after the cursor key; a subtree per contract would have made a continuation page descend into the cursor's contract, and GroveDB charges an empty descent against the limit, which shortened every continuation page and ended a limit-one walk early. The per-contract memberships query keeps no limit because a contract's memberships are creation-only and capped at 16. A drive test walks every kind with the cursor, proves each page and checks that zero and over-limit page sizes are refused.Review round 2 (5e0f738) addressed the 15 findings from the high-effort code review: the protocol version gate on V1 in
active_version_range, the flat member keys above, the root key move to 124, admin existence checks, per-contract invariants checked against state with idempotent tree creation, the frozen discriminant test extended, an upgrade test fortransition_to_version_14, protocol version 13 twins for the root structure tests, a V0 create at the latest version, the V1 fields in wasm-dpp2,serde(default)on the V1 fields with a JSON round trip, the group id hash billed and read from the action, one shared signing tail for V0 and V1, one shared tree creation helper for genesis and upgrade, and the owner dropped from the wire.Breaking changes
Consensus. A new state transition version, a new root tree and new consensus error codes, all gated to protocol version 14, which is unreleased.
Notes for reviewers
Decisions taken that are worth a second opinion:
Groupvariant pointing at a contract's change-control group, so a token group's roster owns the contract group, was specified and deliberately left out of this PR.DataContractUpdateTransitionV1.Ownersindex (identity to the groups it owns) was considered and left out, since owners can derive their own group ids from their nonces.Follow-ups, not in this PR:
getContractGroupInfo, a pagedgetContractGroupMembersandgetContractGroupsForContractthrough DAPI and the SDKs; the legacy wasm-dpp JSON surface for the two new fields (wasm-dpp2 has them);ContractBounds::ContractGroupfor identity keys.🤖 Generated with Claude Code