Skip to content

About

Reference library for the DRep Groups CIP draft (metadata label 8416)

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

drep-groups

Reference implementation of DRep Groups, a draft Cardano standard for recording which DReps belong to which group, party or council, directly on chain.

A group publishes its rules in transaction metadata under label 8416. DReps join and leave with their own signatures. Any indexer that follows the standard computes the same membership list from the chain alone, without trusting a website or a database.

This package holds the rules in code: it decodes the metadata, checks every signature against the group's policies and replays the chain into groups and memberships. Pure TypeScript, no network access, no platform dependency.

Status: draft. The CIP is open as cardano-foundation/CIPs pull request 1318, metadata label 8416 will be registered in CIP-10 together with it, and the API can still change.

What a group can do

  • Open groups: any registered DRep can join, anyone can leave at any time.
  • Permissioned groups: joining needs approval by the group's admission policy, leaving is always possible without anyone's consent.
  • Multisig from day one: a group is controlled by a native script (for example 3 of 5 admins). A separate admission policy can approve and remove members with its own threshold.
  • Consent of listed admins: every key a group names in a policy must sign explicitly, as a required_signers entry, when it is added to a role, so nobody can be shown as an admin without agreeing. A key can resign from its roles at any time.
  • Profile: name, description, website, logo, a link to the charter and optional payment addresses, stored as a CIP-100 document and referenced by hash.
  • Website verification: a group can prove a domain through a well-known file.

The protocol records affiliation only: a group holds no voting power, casts no votes on chain and never changes a delegation. Members may agree to vote together, as a party or council would, and each of them still casts its own vote with its own DRep.

How it works

Every action is an ordinary transaction with a small metadata payload. There is no smart contract, no token and no deposit.

Event Signed by Effect
create every key of the new policies, in required_signers new open or permissioned group
update control policy, plus every key new to its role, in required_signers new policies or profile
dissolve control policy group closed for good, all memberships end
resign the resigning key, in required_signers the key leaves every role whose policy lists it
join the DRep member (open group) or pending request (permissioned)
approve admission policy pending request becomes a membership
leave the DRep membership or request ends, always allowed
remove admission policy membership or request ends (permissioned groups only)

The rules this library enforces, in short:

  • Signatures come from the transaction, the union of required_signers and the vkey witnesses, and satisfy the policies. Consent is stricter: a key that consents (listed in a new policy, resigning, or a key-based DRep joining) must appear in required_signers, so its wallet signed knowingly. A vkey witness alone never counts as consent.
  • Policies need a signature: a control or admission policy that can be satisfied without any signature, for example with only a time lock, is rejected when it is set.
  • Group ids are shown as bech32 drep_group over 33 bytes, the transaction hash and a one byte event index.
  • Scripts must be on chain at or before the event that uses them, published in the payload or, for script DReps, in their registration transaction. A cache can never change a verdict.
  • Chain order decides: block height, position in the block, certificates before metadata events. DRep registrations and retirements are part of the replay, a retirement ends every membership of that DRep.
  • Control actions carry a sequence number, so a stale multisig transaction cannot apply on top of a newer change.
  • Malformed data never stops an indexer: invalid events are ignored one by one, decoding works without recursion, and deeply nested values cannot crash it.

Install

npm install drep-groups

ESM only.

Quick start

import { decodeTransaction, replay, type ChainInput } from 'drep-groups';

// 1. Every transaction with metadata label 8416, as full CBOR plus its position in the chain
const tx = decodeTransaction(cborBytes, { txHash, blockHeight, txIndex });

// 2. DRep registrations and retirements of every credential that appears in a join
const registration: ChainInput = {
  kind: 'ledger',
  input: { kind: 'reg', credential: { kind: 'key', hash: drepKeyHash }, txHash, blockHeight, txIndex, certIndex: 0 },
};

// 3. Replay in any order, the library sorts by chain order and drops duplicates
const state = replay([{ kind: 'tx', tx }, registration]);

state.groups;    // groups with mode, policies, profile anchor, seq and status
state.instances; // memberships and requests: pending, active or closed with a reason
state.verdicts;  // valid or invalid for every event, with a reason text
state.ignored;   // transactions whose payload did not count, and why

replay is pure. After a rollback, replay again without the rolled back inputs.

Feeding it from Koios

Any chain source works. With the public Koios API the inputs come from three calls:

  • GET /tx_by_metalabel?_label=8416&_after_block_height=<cursor> lists new transactions with the label.
  • POST /tx_cbor with {"_tx_hashes": [...]} returns their full CBOR.
  • POST /tx_info with the same hashes returns tx_block_index, the position inside the block.

DRep registrations and retirements come from GET /drep_updates, the position of each certificate again from tx_info.

Incremental indexing

replay recomputes everything from all inputs. An indexer with a database can instead call runEngine after every sync: it applies only the new label transactions and credential inputs to your Store, in steps bounded by a budget, and recovers after rollbacks. MemoryStore is a complete in-memory implementation. A store of your own can run the contract checks of drep-groups/conformance (runSchedule with seeded chains), which compare the engine against replay. Ingest and opening a recovery never run while a runEngine call is in flight, so serialize them with your runs, for example under the same lease holder.

import { MemoryStore, runEngine } from 'drep-groups';

const store = new MemoryStore();
store.ingestLabelTx(tx);                // label transactions
store.ingestLedgerRow(row);             // DRep registrations and retirements
store.setFrontiers({ L: labelHeight, R: ledgerHeight }); // heights read completely so far
const lease = store.acquireLease('indexer');
const budget = { controlTxs: 50, controlBytes: 200_000, credentialUnits: 50, credentialInputs: 500, truncateRows: 1000, resetRows: 1000 };

let report;
do report = await runEngine(store, budget, lease);
while (report.more);

Building transactions

The library also writes. encodePayload turns events into the exact bytes of the label 8416 value, so a tool never hand-writes CBOR. Every function here is pure and works offline.

import { encodePayload, majorityScript } from 'drep-groups';

const control = majorityScript([keyHashA, keyHashB, keyHashC], 2); // 2 of 3
const payload = encodePayload({
  events: [
    { tag: 'create', mode: 'open', control: control.hash, admission: null, profile: { url, dataHash } },
    { tag: 'join', group: { local: 0 }, member: { kind: 'key', hash: founderKeyHash } },
  ],
  scripts: [control.script],
});
// payload goes into the transaction's metadata under label 8416
  • Events and limits: encodePayload takes { events, scripts? } and throws EncodeError for anything the decoder would ignore: no events or more than 64, more than 8 scripts, a script beyond the node or depth limit, malformed hashes, a mode that does not match the admission policy, an empty anchor URL. Long anchor URLs and scripts are split into 64 byte chunks for you (chunkText, chunkBytes). encodeNativeScript(script) gives the bytes to hash with nativeScriptHash, encodeCbor is the small definite length writer underneath.

  • Local references: a group does not exist before its create is on chain, so the founding transaction refers to it as { local: 0 }, the index of the earlier event in the same payload. The same works for founder join events in the create transaction. A local reference must point to an earlier event. Everything after that transaction uses the full reference { txHash, index }.

  • Publish every new policy: put the script of every policy a create or update introduces into scripts (key 2). The indexer can only judge a policy it has seen on chain, and a policy that appears in no payload and no registration makes the event invalid ("control policy unresolved" or "new control policy unresolved").

  • Consent: a create needs every key listed in its control and admission policies in required_signers. An update that sets a new policy needs every key new to that role in required_signers, on top of the current control policy. A key that stays in its role does not sign again, a key that moves from admission into control does, and a key that resigned from a role counts as new when a policy lists it again. A vkey witness does not replace the required_signers entry. Add every consenting key as required_signers before submitting.

  • Resign: a resign event names a key and needs only that key in required_signers, no control policy and no seq. The key leaves every role whose current policy lists it. Its sig counts as false in that role from then on, and GroupState lists it in resignedControl or resignedAdmission. A new policy for a role clears that role's resignations. A resign bumps seq, so control actions prepared before it become stale. It is rejected for a key that is listed in no role, or already resigned from every role it is in.

  • Policies that need no signature: satisfiableWithoutSignature(script) tells whether a script can be satisfied by a time lock alone. A create or update that sets such a policy is invalid.

  • Script DReps and reference scripts: the member script of a script DRep comes from the witness scripts of its registration transaction or from a native script in a reference script of an output that transaction spends or uses as a reference input. Set LedgerInput.referenceScripts to those script_ref values. decodeTxRefs(cbor) reads the script references of a transaction's outputs, a collateral return sits at index outputs.length. Plutus reference scripts resolve nothing.

  • Majority scripts: majorityScript(keys, n) returns an n of k script over key leaves as { script, bytes, hash, keys }. Keys are lowercased, deduplicated and sorted ascending, so one key set and one threshold always give one script hash, whichever order the signers were collected in. It throws EncodeError for an invalid key or a threshold outside 1 to k.

  • Approvals together with an update: one transaction can carry approve events and a control update. Order the events with the approvals first, then the update, because events are judged in order and an approval after a policy change is checked against the new admission policy. The transaction must satisfy both policies, so collect the signatures of both.

  • One control action at a time: control actions carry seq. Read the group's current seq from the index, build the action with it and wait for it to be included before building the next one. A second action prepared in parallel becomes stale as soon as the first one is included, and a stale event is ignored. An update with an empty change set only increments seq, which cancels pending control actions on purpose.

  • Bind the content before signing: a signer should not trust a transaction because it came from the right tool. inspectTransaction(cbor) returns TxFacts: whether the auxiliary data hash in the body matches the metadata that is actually attached (auxHashMatches), how many label 8416 payloads it carries (groupPayloads) and whether it also holds certificates, withdrawals, votes or proposals. It throws a plain Error on malformed CBOR. Compare the decoded events with what the signer was told and refuse anything unexpected, for example a vote hidden next to a join.

  • Preview before submit: previewTransaction(deps, tx) judges every event of an unsubmitted transaction with the engine's own rules and writes nothing. It returns { ignored } when the payload would not count at all, otherwise one PreviewEvent per event with valid and a reason. The preview is exact once runEngine reports more: false with the ledger frontier at or above the label frontier. While the ledger frontier lags, membership events between the two are still pending and the verdicts are inconclusive. tx is a ChainTx from decodeTransaction: set its position after everything you have ingested and fill requiredSigners and the vkey witnesses the final transaction will carry. deps reads your committed state:

    const preview = await previewTransaction({
      load: (keys) => store.load(keys, []),        // a bounded view of the committed state
      queuedJoins: (refs) => store.queuedJoins(refs, []),
    }, tx);
  • Profile context: the profile document is CIP-100 JSON-LD. Embed the context object inline in the profile document, copied from context/drep-groups-v1.jsonld in the package. The GitHub URL https://github.com/katomm/cardano-drep-groups/blob/main/context/drep-groups-v1.jsonld serves only as the term namespace. It defines name, description, website, image, charter and paymentAddresses with address, purpose and paymentScript. The anchor hash is blake2b-256 over the raw document bytes.

API

Function Purpose
decodeTransaction(cbor, position) full Conway transaction to a ChainTx (signers, validity interval, raw label 8416 payload, witness scripts)
replay(inputs) chain inputs to a RegistryState
decodePayload(bytes) one payload to its events and published scripts, null when the payload is ignored
parseNativeScript(bytes), evaluateNativeScript(script, ctx), collectKeyHashes(script) native scripts with exact CBOR types and ledger semantics
checkPaymentAddress(entry, network, scripts) checks a profile payment address: invalid, declared or script-controlled
groupIdToBech32(ref), groupIdFromBech32(s) display form of a group id, bech32 with prefix drep_group over 33 bytes (tx_hash and a one byte event index, so an index above 255 throws)
nativeScriptHash(bytes), keyHashOfVkey(vkey) Cardano hashes
refKey(ref), credKey(credential), orderInputs(inputs) helpers for keys and ordering
encodePayload({ events, scripts? }) events and scripts to the label 8416 payload bytes, throws EncodeError on anything the decoder would ignore
encodeNativeScript(script), encodeCbor(value), chunkText(s), chunkBytes(b) native script bytes, the definite length CBOR writer and the 64 byte chunking
majorityScript(keys, n) n of k script over sorted, deduplicated key hashes with its bytes and hash
inspectTransaction(cbor) TxFacts of a transaction: auxiliary data hash binding, label 8416 payload count, certificates, withdrawals, votes and proposals
previewTransaction(deps, tx) every event of an unsubmitted transaction judged with the engine's rules over committed state, nothing written
runEngine(store, budget, lease, opts?) one bounded incremental run over a Store: an open recovery, or new label transactions and credential inputs
MemoryStore complete in-memory Store, with ingest hooks, frontiers, a lease and snapshot()
effectiveClose(instance, dissolveAt, firstUnregAfterJoin, q?) when and why a membership ends: explicit close, dissolve or retirement, whichever comes first
comparePos(a, b), endOf(height), posOfCert(input), posOfScripts(tx), posOfEvent(tx, index) total order of certificates, payload scripts and events
scriptComplexity(script) node count and nesting depth of a native script, counted the way the payload limits count them
memberScriptWitness(credential, witnessScripts, referenceScripts?) the member script a script DRep's registration proves through a witness or a native reference script, null when none matches
decodeTxRefs(cbor) inputs, reference inputs and the script_ref of every output of a transaction, for filling LedgerInput.referenceScripts
nativeScriptFromScriptRef(bytes) the native script inside a script_ref value, null for Plutus or malformed data
satisfiableWithoutSignature(script) whether a native script can be satisfied with no signature
drep-groups/conformance generateChain, generateSchedule and runSchedule: contract checks of a Store against replay

All types are exported, among them ChainTx, LedgerInput, ChainInput, GroupState, Instance, EventVerdict and RegistryState.

Hex strings: every hash passed in and returned is lowercase hex without a prefix. Hashes are compared as strings, so lowercase hex from other sources before passing it in.

Ledger inputs must come from transactions with is_valid = true. The caller guarantees this.

Payment addresses

checkPaymentAddress({ address, paymentScript }, network, state.scripts) returns a status:

  • invalid: not a bech32 address, wrong network, a pointer address or not a payment address. Do not show it.
  • declared: a valid base or enterprise address without a proven controller. reason says why a payment script claim did not hold.
  • script-controlled: the payment credential is a script, it equals paymentScript and the script is published on chain. script holds it for display, for example "3 of 5: Alice, Bob, ...".

hasStake is false for enterprise addresses, which cannot delegate their votes.

Test vectors

vectors/vectors.json (also importable as drep-groups/vectors/vectors.json) holds 50 scenarios with inputs and expected results: open and permissioned lifecycles, the consent rule, signature-free policies, resign, policy rotation, retirement and re-registration, certificate ordering, script DReps including reference scripts, time locks, malformed payloads, duplicate keys and deeply nested data.

Payloads are CBOR hex, so the file works for any language. An implementation passes when it produces the same groups and instances and the same valid flag for every verdict. Reason texts are informative. Compared groups include resignedControl and resignedAdmission. A ledger input can carry referenceScriptsHex: the raw script_ref values of the outputs that the registration transaction spends or uses as reference inputs, in any order, absent when empty. Only native scripts resolve a member script.

Development

npm install
npm test           # unit tests, differential tests and test vectors
npm run typecheck
npm run build      # emits dist/
npm run vectors    # regenerates vectors/vectors.json from vectors/definitions.ts

Expected results in vectors/definitions.ts are written by hand from the specification. When a vector fails, check the case against the rules before changing either side.

License

Apache-2.0

Releasing

Releases are tag driven and staged:

  1. Bump the version in a pull request with npm version <patch|minor> --no-git-tag-version and add a changelog entry.
  2. After the squash merge, tag the merge commit v<version> and push the tag.
  3. The release workflow checks the tag against package.json and main, runs the tests and stages the package on npm with provenance.
  4. A maintainer approves the staged version on npmjs.com with 2FA. The workflow also creates the GitHub release.

About

Reference library for the DRep Groups CIP draft (metadata label 8416)

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages