# Header work

> Decide if a block header's hash meets its target, so any node can check the proof of work from the header alone.

Inspired by afflom/prism-btc (https://github.com/afflom/prism-btc). Bitcoin proof of work as a UOR-ADDR realization. Pattern: Decision table, OMG DMN 1.5, hit policy FIRST. To write one of your own, follow How to build a decision table app (../../guides/decision-table/index.md). The prompt below is data, quoted from the example.

**Figure: What the Header work app does.** A request goes in, the rules decide, and the Lean kernel has already proved what the rules promise.

| Step | What happens |
| --- | --- |
| 1. Request | zeros, target, rest |
| 2. 3 rules | the first that matches wins |
| 3. Answer | accepted, rejected |
| 4. Proved | 3 theorems, 34 tests |

Verified by prismpm verify in the pinned SDK. Fingerprint: 3333795535adf906ae4643be5bdf17b1b46c9d27719308ecfa908f39874616d7. Acceptance vectors: 34. Claims: 6.

## The prompt

```json
{
  "schema": "prism/prompt/1",
  "goal": "Decide if a block header's hash meets its target, so any node can check the proof of work from the header alone.",
  "pattern": "decisionTable",
  "repository": "afflom/prism-btc",
  "license": "Apache-2.0",
  "app": {
    "name": "header-work",
    "limits": [
      "The hash and target are compared by their leading zero bits, then by the rest of the hash; decoding the compact bits to a target is the caller's.",
      "It does not search nonces; prism-btc-node does."
    ],
    "title": "Header work",
    "purpose": "Decide whether a block header is accepted, from the leading zero bits of its double SHA-256 hash, the leading zero bits of its target, and how the rest of the hash compares with the target when those are equal.",
    "fields": [
      {
        "name": "zeros",
        "kind": "number",
        "min": 0,
        "means": "leading zero bits of the header's sha256d hash",
        "max": 256
      },
      {
        "name": "target",
        "kind": "number",
        "min": 0,
        "means": "leading zero bits of the target the compact bits decode to",
        "max": 256
      },
      {
        "name": "rest",
        "kind": "choice",
        "values": [
          "lower",
          "tied",
          "higher"
        ],
        "means": "with equal leading zeros, the rest of the hash against the rest of the target"
      }
    ],
    "outcomes": [
      "accepted",
      "rejected"
    ],
    "meanings": {
      "accepted": "block_hash <= target: the header carries the work",
      "rejected": "block_hash > target: the candidate does not admit"
    },
    "rules": [
      {
        "when": [
          {
            "field": "zeros",
            "op": ">",
            "value": {
              "field": "target"
            }
          }
        ],
        "then": "accepted",
        "why": "ARCHITECTURE.md: admission is block_hash <= target compared as bytes (LexicographicLessEqThreshold); more leading zeros is smaller"
      },
      {
        "when": [
          {
            "field": "zeros",
            "op": "<",
            "value": {
              "field": "target"
            }
          }
        ],
        "then": "rejected",
        "why": "crates/prism-btc-node/src/lib.rs scan_template_nonces: fewer leading zeros is above the target, so the nonce is not taken"
      },
      {
        "when": [
          {
            "field": "rest",
            "op": "is",
            "value": "higher"
          }
        ],
        "then": "rejected",
        "why": "ARCHITECTURE.md: with an equal zero prefix the remaining bytes decide, and above the target does not admit"
      }
    ],
    "otherwise": "accepted",
    "otherwiseWhy": "the rest is lower than or tied with the target: block_hash <= target admits",
    "properties": [
      {
        "kind": "never",
        "when": [
          {
            "field": "zeros",
            "op": "<",
            "value": {
              "field": "target"
            }
          }
        ],
        "then": "accepted",
        "why": "a header without the work is never accepted"
      },
      {
        "kind": "always",
        "when": [
          {
            "field": "zeros",
            "op": ">",
            "value": {
              "field": "target"
            }
          }
        ],
        "then": "accepted",
        "why": "more leading zeros than the target always admits"
      },
      {
        "kind": "never",
        "when": [
          {
            "field": "zeros",
            "op": "=",
            "value": {
              "field": "target"
            }
          },
          {
            "field": "rest",
            "op": "is",
            "value": "higher"
          }
        ],
        "then": "accepted",
        "why": "a hash above the target never admits"
      }
    ],
    "examples": [
      {
        "request": "77 76 higher",
        "response": "accepted"
      },
      {
        "request": "75 76 lower",
        "response": "rejected"
      },
      {
        "request": "76 76 lower",
        "response": "accepted"
      },
      {
        "request": "76 76 tied",
        "response": "accepted"
      },
      {
        "request": "76 76 higher",
        "response": "rejected"
      }
    ]
  },
  "stakeholders": [
    {
      "name": "Node operator",
      "text": "Runs a node and needs every accepted header to carry the work its target requires.",
      "concerns": [
        "Correct answers",
        "Proved guarantees"
      ]
    },
    {
      "name": "Miner",
      "text": "Runs prism-btc-node's nonce scan and needs a header it submits to be one Bitcoin Core accepts.",
      "concerns": [
        "Agreement with Bitcoin Core"
      ]
    }
  ],
  "concerns": [
    {
      "name": "Agreement with Bitcoin Core",
      "text": "The admission is Bitcoin's own block_hash <= target, so a header the app accepts is one submitblock accepts.",
      "model": "component"
    }
  ],
  "components": [
    {
      "name": "Bitcoin Core",
      "text": "The Bitcoin Core node prism-btc-node talks to over RPC: getblocktemplate for templates, submitblock for admitted headers.",
      "kind": "externalSystem"
    },
    {
      "name": "prism-btc-wasm",
      "text": "The WebAssembly binding of the prism-btc kernel, crates/prism-btc-wasm.",
      "kind": "service"
    }
  ],
  "threats": [
    {
      "name": "Header accepted without work",
      "text": "A header whose hash is above its target is accepted and relayed.",
      "stride": "tampering",
      "asset": "answer",
      "likelihood": "low",
      "impact": "critical",
      "control": {
        "name": "Work proved",
        "text": "The app never accepts fewer leading zeros than the target, and the node takes a nonce only when target.is_satisfied_by_bytes(digest).",
        "evidence": [
          {
            "kind": "proof",
            "reference": "HeaderWorkProofs::inv001Holds"
          },
          {
            "kind": "review",
            "reference": "crates/prism-btc-node/src/lib.rs scan_template_nonces"
          }
        ]
      }
    },
    {
      "name": "Target misdecoded",
      "text": "The compact bits are decoded to an easier target, so a header passes with less work.",
      "stride": "tampering",
      "asset": "request",
      "likelihood": "low",
      "impact": "major",
      "accepted": "The app compares the zero counts it is given; decoding Bits to Target belongs to the caller, and Bitcoin Core re-checks every submitted block."
    },
    {
      "name": "Nonce space exhausted",
      "text": "No nonce of a template admits, so mining stalls.",
      "stride": "denialOfService",
      "asset": "request",
      "likelihood": "medium",
      "impact": "minor",
      "accepted": "prism-btc-node rolls the extranonce when the 32-bit nonce space is exhausted; the app answers each candidate on its own."
    }
  ],
  "quality": [
    {
      "characteristic": "Compatibility",
      "subcharacteristic": "Interoperability",
      "requirement": "Agrees with Bitcoin Core",
      "text": "Every header the app accepts is one Bitcoin Core accepts by work, and every one it rejects is one Core rejects.",
      "measure": "Disagreements with Core",
      "measureText": "Examples whose answer differs from block_hash <= target.",
      "threshold": 0
    }
  ],
  "journeys": [
    {
      "stakeholder": "Node operator",
      "steps": [
        "REQ-001",
        "REQ-002",
        "REQ-003",
        "otherwise",
        "INV-001"
      ]
    },
    {
      "stakeholder": "Miner",
      "steps": [
        "REQ-001",
        "otherwise",
        "INV-002",
        "INV-003"
      ]
    }
  ],
  "axioms": {}
}
```

## Claims

- HW-01: The app never answers accepted when zeros is below target
- HW-02: The app always answers accepted when zeros is above target
- HW-03: The app never answers accepted when zeros equals target and rest is higher
- HW-04: The architecture description declares every stakeholder, concern, component, edge, viewpoint and view it references
- HW-05: The ISO/IEC 25010 quality model numbers every characteristic, subcharacteristic, requirement and measure, and every parent it names is declared
- HW-06: Every compliance obligation is numbered in order and names its evidence

## Pattern

Decision table: OMG DMN 1.5, hit policy FIRST. The rules are tried in order, and the first one that matches gives the answer. If none matches, the default answer applies. This is a DMN decision table with the FIRST hit policy.

| Pattern | Standard | Answers |
| --- | --- | --- |
| Decision table | OMG DMN 1.5, hit policy FIRST | accepted, rejected |

**Figure: Rules for each answer.** Each bar counts the rules that give one answer. When no rule matches, the answer is accepted.

|  | rules |
| --- | --- |
| accepted | 1 |
| rejected | 2 |

## Behavior

A request is zeros, target, rest, separated by spaces. The first rule that matches decides. If none matches, the answer is accepted. A request over 88 bytes, or in any other form, is answered invalid.

| Rule | When | Answer | Why |
| --- | --- | --- | --- |
| REQ-001 | zeros is above target | accepted | ARCHITECTURE.md: admission is block\_hash \<= target compared as bytes (LexicographicLessEqThreshold); more leading zeros is smaller |
| REQ-002 | zeros is below target | rejected | crates/prism-btc-node/src/lib.rs scan\_template\_nonces: fewer leading zeros is above the target, so the nonce is not taken |
| REQ-003 | rest is higher | rejected | ARCHITECTURE.md: with an equal zero prefix the remaining bytes decide, and above the target does not admit |
| otherwise | no rule matches | accepted | the rest is lower than or tied with the target: block\_hash \<= target admits |

## Properties Lean proves

Each property is a theorem about the same definitions the app is built from. It is proved for every request, not only the tested ones.

| Property | Statement | Theorem | Why |
| --- | --- | --- | --- |
| INV-001 | It never answers accepted when zeros is below target. | HeaderWorkProofs::inv001Holds | a header without the work is never accepted |
| INV-002 | It always answers accepted when zeros is above target. | HeaderWorkProofs::inv002Holds | more leading zeros than the target always admits |
| INV-003 | It never answers accepted when zeros equals target and rest is higher. | HeaderWorkProofs::inv003Holds | a hash above the target never admits |

## Architecture

Stakeholders and the concerns each one views the app through (ISO/IEC/IEEE 42010).

| Stakeholder | Who they are | Concerns |
| --- | --- | --- |
| Miner | Runs prism-btc-node's nonce scan and needs a header it submits to be one Bitcoin Core accepts. | Agreement with Bitcoin Core |
| Node operator | Runs a node and needs every accepted header to carry the work its target requires. | Correct answers, Proved guarantees |
| Verifier | Anyone who loads the holo, checks its fingerprint and replays its acceptance vectors before trusting an answer. | Integrity of the published app, Refused malformed requests, Proved guarantees |

## Concerns

What the stakeholders care about, and the model each is viewed in.

| Concern | What it means | Model |
| --- | --- | --- |
| Agreement with Bitcoin Core | The admission is Bitcoin's own block\_hash \<= target, so a header the app accepts is one submitblock accepts. | component |
| Correct answers | Every well-formed request is answered by the first rule that matches it, or accepted when none does, as the spec states. | quality |
| Integrity of the published app | What a visitor runs is the holo the build verified, with its fingerprint and signed provenance beside it. | security |
| Proved guarantees | Each of the 3 properties of the spec holds for every request, proved by the Lean kernel. | quality |
| Refused malformed requests | A request that is not the 3 fields in order, or is longer than 88 bytes, is answered invalid and never guessed. | security |

## Components

8 components and 11 edges between them.

| Component | Kind | What it is |
| --- | --- | --- |
| Bitcoin Core | externalSystem | The Bitcoin Core node prism-btc-node talks to over RPC: getblocktemplate for templates, submitblock for admitted headers. |
| Browser | externalSystem | The visitor's web browser, which loads the page and runs the Header work guest. |
| GitHub Pages | externalSystem | Serves the page and the holo from the repository Pages workflow. |
| Header work guest | service | The Core-Wasm guest built from the model: it answers one request of at most 88 bytes with one answer of at most 64. |
| Header work page | staticSite | The page the template publishes: the holo, its fingerprint, its provenance and its acceptance vectors. |
| prism-btc-wasm | service | The WebAssembly binding of the prism-btc kernel, crates/prism-btc-wasm. |
| Prism build | cliAdapter | prismpm verify in the SDK image prismpm.lock pins: it checks every theorem, builds the guest and replays every vector. |
| Source repository | externalSystem | The repository that holds the prompt, the model and its gate. |

## Design views

The SDK checks each view against the system model and draws it as OPL and PlantUML.

| View | Diagram | Viewpoint |
| --- | --- | --- |
| Deciding a Header work request | opmObjectProcess | Node operator: Correct answers |
| Components of Header work | umlComponent | Verifier: Integrity of the published app |
| Answering a Header work request | umlSequence | Node operator: Correct answers |
| States of the Header work guest | umlStateMachine | Verifier: Refused malformed requests |

## Features and journeys

8 features. Each names the definitions that do the work and the tests that accept it. Each stakeholder has one journey.

| Feature | Calls | Accepted by |
| --- | --- | --- |
| When zeros is above target, the answer is accepted. | HeaderWork::rule1, HeaderWork::judge | HeaderWork::application |
| When zeros is below target, the answer is rejected. | HeaderWork::rule2, HeaderWork::judge | HeaderWork::application |
| When rest is higher, the answer is rejected. | HeaderWork::rule3, HeaderWork::judge | HeaderWork::application |
| When no rule matches, the answer is accepted. | HeaderWork::judge | HeaderWork::application |
| A request that is not zeros, target, rest in order, separated by single spaces, or is over 88 bytes, is answered invalid. | HeaderWork::dispatch, HeaderWork::decodeField1 | HeaderWork::application |
| It never answers accepted when zeros is below target. | HeaderWork::judge | HeaderWorkProofs::inv001Holds |
| It always answers accepted when zeros is above target. | HeaderWork::judge | HeaderWorkProofs::inv002Holds |
| It never answers accepted when zeros equals target and rest is higher. | HeaderWork::judge | HeaderWorkProofs::inv003Holds |

## Journeys

The ordered features each stakeholder takes.

| Stakeholder | Steps |
| --- | --- |
| Miner | REQ-001 → otherwise → INV-002 → INV-003 |
| Node operator | REQ-001 → REQ-002 → REQ-003 → otherwise → INV-001 |
| Verifier | refuse → INV-001 → INV-002 → INV-003 |

## Security and threat model

12 threats against 4 assets. Each has a STRIDE category, and either a control with evidence or a risk that is accepted on purpose.

| Threat | STRIDE | Asset | Risk | Answered by |
| --- | --- | --- | --- | --- |
| Answer that breaks INV-001 | repudiation | Answer | medium likelihood, critical impact | Proof of INV-001: proof HeaderWorkProofs::inv001Holds |
| Answer that breaks INV-002 | repudiation | Answer | medium likelihood, critical impact | Proof of INV-002: proof HeaderWorkProofs::inv002Holds |
| Answer that breaks INV-003 | repudiation | Answer | medium likelihood, critical impact | Proof of INV-003: proof HeaderWorkProofs::inv003Holds |
| Granted capability | informationDisclosure | Answer | low likelihood, major impact | No capability granted: gate prism-code check refuses an ungranted guest import |
| Header accepted without work | tampering | Answer | low likelihood, critical impact | Work proved: proof HeaderWorkProofs::inv001Holds; review crates/prism-btc-node/src/lib.rs scan\_template\_nonces |
| Malformed request | tampering | Request bytes | high likelihood, major impact | Strict decoder: gate malformed-request acceptance vectors, replayed in the compiled guest by prismpm verify |
| Nonce space exhausted | denialOfService | Request bytes | medium likelihood, minor impact | accepted: prism-btc-node rolls the extranonce when the 32-bit nonce space is exhausted; the app answers each candidate on its own. |
| Oversized request | denialOfService | Request bytes | medium likelihood, minor impact | Bounded request: gate acceptance vectors at the request bound, one byte over it, and at the guest allocation bound, replayed by prismpm verify |
| Substituted holo | spoofing | Published holo | low likelihood, critical impact | Fingerprint and provenance: gate actions/attest-build-provenance in the pages workflow; gate prism-code check of the holo identities in the page |
| Substituted host | spoofing | Published holo | low likelihood, critical impact | accepted: A page cannot defend against its own host. The holo carries signed build provenance a visitor can check, and the app can be rebuilt from its prompt. |
| Tampered model | tampering | Model source | low likelihood, major impact | Regenerated from the prompt: gate prismpm verify in the SDK image prismpm.lock pins; review app/prompt.json |
| Target misdecoded | tampering | Request bytes | low likelihood, major impact | accepted: The app compares the zero counts it is given; decoding Bits to Target belongs to the caller, and Bitcoin Core re-checks every submitted block. |

## Quality

ISO/IEC 25010:2023 requirements. Each has a measure and a threshold that a theorem pins.

| Requirement | Characteristic | Measure | Threshold |
| --- | --- | --- | --- |
| Agrees with Bitcoin Core: Every header the app accepts is one Bitcoin Core accepts by work, and every one it rejects is one Core rejects. | Compatibility: Interoperability | Disagreements with Core | 0 |
| Bounded allocation: The guest allocates at most 176 bytes for one request. | Performance efficiency: Resource utilization | Guest allocation bytes | 176 |
| Bounded request: A request over 88 bytes is refused before any field is read. | Performance efficiency: Time behaviour | Request bytes read | 88 |
| Every property proved: All 3 properties are theorems the Lean kernel checks. | Security: Integrity | Unproved properties | 0 |
| Every request answered: Every request gets an answer: a rule, accepted otherwise, or invalid. | Functional suitability: Functional completeness | Unanswered requests | 0 |
| Every vector replays: All 34 acceptance vectors replay in the compiled guest, the shortest 0 bytes long. | Reliability: Faultlessness | Failed vectors | 0 |
| Examples answered as stated: Every one of the 5 examples of the spec is answered as it states. | Functional suitability: Functional correctness | Example mismatches | 0 |

## Compliance

One obligation per standard, each naming its evidence.

| Standard | Subject | Evidence |
| --- | --- | --- |
| ISO/IEC/IEEE 42010:2022 | Architecture description | Architecture::architectureDescriptionHolds |
| ISO/PAS 19450:2015 and OMG UML 2.5.1 | Design views | Design::viewOpmDecide, Design::viewUmlComponents, Design::viewUmlRequest, Design::viewUmlStates |
| ISO/IEC 25010:2023 | Product quality | Quality::qualityModelHolds |
| ISO/IEC 27034-1:2011 and ISO/IEC 27005:2022 | Application security and risk | Security::controlSet |
| OMG DMN 1.5, hit policy FIRST | Decision table | HeaderWork::judge |
| OpenSpec | Requirements | HeaderWork::application |
| SPDX Apache-2.0 | Licensing | HeaderWork::application |

## Rendered design views

Written by the SDK from the design records when it verified the app.

### design/Design.viewOpmDecide.opl

```
View: Design::viewOpmDecide
Title: Deciding a Header work request
Viewpoint: Architecture::viewpointNodeOperatorCorrectAnswers
Notation: ISO/PAS 19450:2015 OPM, Prism OPL profile

componentBrowser is an object.
componentHeaderWorkGuest is an object.
componentHeaderWorkGuest can be stateDeciding or stateIdle.
processDecide is a process.
processEncodeAnswer is a process.
processJudge is a process.
processParseRequest is a process.
componentHeaderWorkGuest handles processDecide.
processParseRequest requires componentBrowser.
processEncodeAnswer affects componentBrowser.
processJudge invokes processEncodeAnswer.
processParseRequest invokes processJudge.
processDecide zooms into processParseRequest, processJudge, and processEncodeAnswer, in that sequence.

```

### design/Design.viewUmlComponents.puml

```
@startuml
' UML 2.5.1 component diagram
' view: Design::viewUmlComponents
' viewpoint: Architecture::viewpointVerifierIntegrityOfThePublishedApp
title Components of Header work
component "componentBitcoinCore" as c0
component "componentBrowser" as c1
component "componentGitHubPages" as c2
component "componentHeaderWorkGuest" as c3
component "componentHeaderWorkPage" as c4
component "componentPrismBtcWasm" as c5
component "componentPrismBuild" as c6
component "componentSourceRepository" as c7
c0 --> c3 : edgeBitcoinCoreToHeaderWorkGuest
c1 --> c3 : edgeBrowserToHeaderWorkGuest
c2 --> c1 : edgeGitHubPagesToBrowser
c3 --> c0 : edgeHeaderWorkGuestToBitcoinCore
c3 --> c1 : edgeHeaderWorkGuestToBrowser
c3 --> c5 : edgeHeaderWorkGuestToPrismBtcWasm
c4 --> c2 : edgeHeaderWorkPageToGitHubPages
c5 --> c3 : edgePrismBtcWasmToHeaderWorkGuest
c6 --> c3 : edgePrismBuildToHeaderWorkGuest
c6 --> c4 : edgePrismBuildToHeaderWorkPage
c7 --> c6 : edgeSourceRepositoryToPrismBuild
@enduml

```

### design/Design.viewUmlRequest.puml

```
@startuml
' UML 2.5.1 sequence diagram
' view: Design::viewUmlRequest
' viewpoint: Architecture::viewpointNodeOperatorCorrectAnswers
title Answering a Header work request
participant "componentBrowser" as p0
participant "componentHeaderWorkGuest" as p1
p0 -> p1 : processDecide
p1 --> p0 : processDecide
@enduml

```

### design/Design.viewUmlStates.puml

```
@startuml
' UML 2.5.1 state machine diagram
' view: Design::viewUmlStates
' viewpoint: Architecture::viewpointVerifierRefusedMalformedRequests
title States of the Header work guest
state "stateAnsweredAccepted" as s0
state "stateAnsweredRejected" as s1
state "stateDeciding" as s2
state "stateIdle" as s3
state "stateRefused" as s4
[*] --> s3
s3 --> s2 : processParseRequest
s3 --> s4 : processParseRequest
s2 --> s0 : processRule1
s2 --> s1 : processRule2
s2 --> s1 : processRule3
s2 --> s0 : processOtherwise
s0 --> s3 : processEncodeAnswer
s1 --> s3 : processEncodeAnswer
s4 --> s3 : processEncodeAnswer
@enduml

```

## Prism source

Every file the builder wrote, laid out as a repository created from UOR-Foundation/template; the download prism-header-work.zip has them all.

- app/src/Architecture.lex.tex (399 lines)
- app/src/Compliance.lex.tex (56 lines)
- app/src/Design.lex.tex (514 lines)
- app/src/Features.lex.tex (109 lines)
- app/src/Quality.lex.tex (361 lines)
- app/src/Security.lex.tex (537 lines)
- app/src/HeaderWork.lex.tex (199 lines)
- app/src/HeaderWorkProofs.lex.tex (93 lines)
- app/lexlean.toml (43 lines)
- app/prompt.json (274 lines)
- model/ids.toml (59 lines)
- features/suites/header\_work.feature (38 lines)
- crates/conformance/tests/header\_work.rs (122 lines)
- site/app.json (101 lines)
- openspec/specs/header-work/spec.md (150 lines)
