Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
fee-on-transfer and rebasing assets, multiple rewards, emergency exits,
recovery, and vesting boundaries. See
[the staking accounting guide](docs/staking-accounting.md).
- Production governance/timelock safety analysis (`packages/core/src/governance/`) with a
normalized proposal lifecycle and ordered state-transition model, explicit adapters for
OpenZeppelin Governor/TimelockController, Compound Governor Bravo, Safe-style multisigs, and
cross-chain receivers, plus 16 evidence-backed rules (`CP-GOV-001`–`CP-GOV-016`) covering
checkpointing, same-block voting power, quorum/window math, timelock readiness, replay,
proposal/operation identity, arbitrary calldata/value flow, guardian bypasses, delay updates,
predecessor/salt handling, role separation, upgrades, cross-chain domains, and threshold
signatures. Includes bounded deterministic APIs, versioned JSON/Markdown output, config v0→v1
migration, cancellation, `chainproof governance`, scanner integration, secure/vulnerable
fixtures, and regression tests. See [docs/governance-safety.md](docs/governance-safety.md).
- Token callback/hook/reentrancy analysis (`@chainproof/core`
`packages/core/src/rules/callback-analysis/`): models the implicit
control-flow edges ERC-721/1155 receiver hooks, ERC-777 sender/receiver
Expand Down
82 changes: 82 additions & 0 deletions PR_DESCRIPTION_TASK2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
## Summary

Closes #84.

Implements Task 2: a production-grade, deterministic governance, timelock, multisig, and proposal
execution safety analyzer for ChainProof.

## What changed

- Added a normalized governance state-transition/data-flow model and framework adapters for
OpenZeppelin Governor/TimelockController, Compound Governor Bravo, Safe-style multisigs, and
cross-chain governance receivers.
- Added 16 evidence-backed rules (`CP-GOV-001`–`CP-GOV-016`) covering live/same-block voting power,
snapshots, quorum/window math, timelock readiness, replay, complete proposal/operation identity,
arbitrary target/value/calldata flow, guardian bypasses, delay updates, predecessors, salts, role
separation, upgrades, cross-chain domains, and threshold signatures.
- Added bounded/cancellable public APIs, schema-versioned deterministic JSON/Markdown reports,
sanitized diagnostics, configuration validation, and v0→v1 migration.
- Added `chainproof governance` with rule selection, resource limits, model output, report artifacts,
and configurable CI severity exit thresholds.
- Integrated governance findings into the normal scanner exactly once per physical file.
- Added paired secure/vulnerable fixtures and comprehensive core/scanner/CLI tests.
- Added user/developer documentation and fixed clean-checkout lint/build ordering.

## Scope

The analyzer reports structural implementation safety. It does not score political legitimacy,
voter preferences, or proposal outcomes.

## Architecture and security boundaries

`model.ts` performs a bounded, cycle-safe AST walk and emits semantic state/transition/operation
records. `adapters.ts` recognizes framework structure without treating a name as proof of safety.
`analyzer.ts` runs pure rules over that model; `api.ts` owns budgets, cancellation, deterministic
ordering, and sanitized filesystem diagnostics; `serialize.ts` and the CLI are transport/presentation
only. The feature performs no RPC, network, package download, compiler subprocess, symbolic
execution, or provider call. Deployment role membership, bridge finality/authenticity, economic
adequacy, and political outcomes remain outside the static source boundary.

## Precision / recall considerations

- A cheap, comment/string-stripped governance prefilter protects ordinary scan performance; the
dedicated API skips it and can model generic implementations directly.
- Findings require semantic function/state roles plus ordered guards, writes, calls, or parameter
taint. Framework adapters suppress only mitigations visible in source.
- Secure checkpointed Governor, predecessor-aware/salted TimelockController, Safe-style multisig,
and domain-separated cross-chain fixtures are zero-finding false-positive controls.
- Unresolved inherited modifiers, assembly/computed selectors, proxy storage aliases, deployment
configuration, and external bridge/token behavior may require manual review and are documented.

## Performance

Local Node.js benchmark on the final implementation (100 copies of `VulnerableGovernor.sol`, 1,024
finding cap): **599.2 ms**, **17.4 MiB heap delta**. Preflight source/contract/function checks and
per-function operation, per-finding evidence, project file, and total finding limits provide
deterministic adversarial bounds. Regression tests enforce early contract limiting, an eight-operation
cap on a 200-statement function, cancellation, and a 5-second guardrail for the bounded fixture.

## Validation

- `npm run build`
- `npm test`
- `npm run lint`
- `npm run test:ci --workspace=packages/core`
- affected workspace builds/tests and TypeDoc generation

Latest local evidence after updating from target `master`: **41 core suites / 332 tests** and
**6 CLI suites / 24 tests** pass. Core coverage is 83.9% statements overall and 91.78% statements
for `src/governance`.

## Follow-up work

- Add cross-file modifier/body expansion to the governance model using the shared import graph.
- Add optional deployment-manifest checks for concrete role membership and open-executor policy.
- Add assembly-aware selector/value-flow summaries while retaining the current bounded guarantees.

## Review guide

1. Start with `packages/core/src/governance/model.ts` and `analyzer.ts`.
2. Review deterministic bounds/config/reporting in `api.ts`, `config.ts`, and `serialize.ts`.
3. Exercise `chainproof governance examples/contracts/governance --format json --fail-on none`.
4. Compare the vulnerable and secure fixtures under `examples/contracts/governance/`.
51 changes: 51 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- [Repository Layout](#repository-layout)
- [Installation](#installation)
- [CLI Reference](#cli-reference)
- [Governance Safety Analysis](#governance-safety-analysis)
- [Invariant DSL](#invariant-dsl)
- [Staking Accounting](#staking-accounting)
- [VS Code Extension](#vs-code-extension)
Expand Down Expand Up @@ -304,6 +305,56 @@ chainproof invariants migrate legacy-spec.json --output vault.cpinv.json

`check` exits `1` if any invariant `fail`s or `error`s, `0` otherwise (`timeout`/`skipped` do not fail the build by themselves — inspect `bounded.timeExceeded`/`stepsExceededIds` in `--format json` output).

### `chainproof governance`

Run the bounded governance, timelock, multisig, and cross-chain proposal safety analyzer:

```bash
chainproof governance contracts/ --format markdown --output governance-report.md
chainproof governance contracts/Governor.sol --format json --fail-on high
chainproof governance contracts/ --include-rule CP-GOV-001 --include-rule CP-GOV-002
chainproof governance contracts/ --config governance.config.json --include-models
```

The command emits deterministic, schema-versioned JSON or Markdown. `--fail-on` accepts
`none|info|low|medium|high|critical`; the default is `high`. Rule include/exclude flags are
repeatable, and bounded-analysis flags limit sources, files, contracts, functions, operations,
evidence, and findings. See [Governance Safety Analysis](#governance-safety-analysis).

---

## Governance Safety Analysis

The specialized engine in `packages/core/src/governance/` builds a normalized state-transition
model for proposal creation, checkpointed voting, quorum math, queue/schedule, timelock delay,
cancel, execute, multisig signature validation, emergency authority, upgrades, and cross-chain
message delivery. It traces proposal-controlled target/value/calldata into privileged calls and
checks guards and state writes in source order.

It recognizes OpenZeppelin Governor and TimelockController shapes, Compound Governor Bravo,
Safe-style threshold multisigs, cross-chain governors, and generic checkpoint/timelock patterns.
The ordinary `chainproof scan` pipeline also runs these rules once per physical Solidity file.

```typescript
import {
analyzeGovernanceFiles,
serializeGovernanceReport,
} from '@chainproof/core';

const report = analyzeGovernanceFiles(['contracts/'], {
includeModels: true,
limits: { maxFindings: 200 },
excludeRules: ['CP-GOV-009'],
});
process.stdout.write(serializeGovernanceReport(report));
```

Reports describe structural implementation safety only. They do not judge voter preferences,
political legitimacy, or whether a proposal's outcome is desirable. Full rule semantics,
configuration schema, threat model, limitations, and troubleshooting are documented in
**[docs/governance-safety.md](docs/governance-safety.md)**. Secure/vulnerable fixtures live under
[`examples/contracts/governance/`](examples/contracts/governance/SecureGovernor.sol).

---

## Staking Accounting
Expand Down
Loading
Loading