> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ana.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# Verification

> What the chain publishes about the Anafi engine, and how a third party reads and checks it.

After you read this page, you can read the engine identity, its attestation evidence, its heartbeat and the live adapter list from the chain, and watch every change to them. You need only a chain node. These reads do not go through the Anafi API.

The engine runs in an Intel TDX enclave. Its signer key and its encryption key are published on chain in [`AnafiRegistry`](https://docs.ana.fi/contracts/registry), with the attestation evidence. The engine signs a heartbeat on chain. Each adapter and the DSL registry accept a signature only from the published signer key.

## What the registry publishes

| Value | Getter | Changes with |
| - | - | - |
| Engine signer address | `engineSigKey() returns (address)` | `setEngineIdentity` |
| Engine encryption key, X25519, 32 bytes | `engineEncKey() returns (bytes32)` | `setEngineIdentity` |
| Measurement of the engine application | `composeHash() returns (bytes32)` | `setEngineIdentity` |
| Commitment to the attestation evidence | `engineEvidenceHash() returns (bytes32)` | `setEngineIdentity` |
| Number of identity changes | `version() returns (uint64)` | `setEngineIdentity` |
| Last heartbeat block | `lastHeartbeatBlock() returns (uint64)` | `attestHeartbeat` |
| Last heartbeat time | `lastHeartbeatTick() returns (uint64)` | `attestHeartbeat` |
| Live adapters | `delegationAdapters() returns (address[])`, `isDelegationAdapter(address) returns (bool)` | `addDelegationAdapter`, `removeDelegationAdapter` |
| Admin | `owner() returns (address)`, `pendingOwner() returns (address)` | `transferOwnership`, `acceptOwnership` |

Both keys, the compose hash and the evidence change together in one call, `setEngineIdentity`. Each call replaces all of them and adds 1 to `version()`.

## The attestation evidence

The evidence is not in storage. It is in the data of the event that each identity change emits:

```solidity theme={null}
event EngineIdentitySet(
    address indexed newSigKey,
    bytes32 newEncKey,
    bytes32 newCompose,
    uint64 indexed newVersion,
    bytes tlsCertDer,   // the TLS certificate of the engine, DER form
    bytes quote,        // the Intel TDX quote that binds tlsCertDer, newSigKey and newEncKey
    bytes eventLog      // the event log that goes with the quote
);
```

Storage holds one commitment to the three blobs:

```solidity theme={null}
engineEvidenceHash = keccak256(abi.encode(tlsCertDer, quote, eventLog));
// bytes32(0) when all three blobs are empty
```

A zero `engineEvidenceHash` means that the registry owner posted no evidence with the current identity. Treat such an identity as unattested. The registry does not check the quote on chain. A verifier checks it off chain.

### Check the evidence

**1. Read the current identity**

Read `version()`, `engineSigKey()`, `engineEncKey()`, `composeHash()` and `engineEvidenceHash()` from the registry.

**2. Fetch the event of that version**

Get the `EngineIdentitySet` log with the indexed topic `newVersion` equal to `version()`. The first identity has version 0 and comes from `initialize`, which emits no `EngineIdentitySet`.

**3. Compare the event with storage**

`newSigKey`, `newEncKey` and `newCompose` must equal the storage values. `keccak256(abi.encode(tlsCertDer, quote, eventLog))` must equal `engineEvidenceHash()`.

**4. Check the quote**

Verify the Intel TDX quote with the quote verification tool of your choice. Check that the quote binds `tlsCertDer`, `newSigKey` and `newEncKey`.

```ts theme={null}
import { createPublicClient, encodeAbiParameters, http, keccak256, parseAbi } from "viem";
import { polygonAmoy } from "viem/chains";

const publicClient = createPublicClient({ chain: polygonAmoy, transport: http() });
const registry = "0x100B1e2d05dac3DdF6774b6668BCE07c9BEc8018"; // polygon-amoy

const REGISTRY_ABI = parseAbi([
  "function engineSigKey() view returns (address)",
  "function engineEncKey() view returns (bytes32)",
  "function composeHash() view returns (bytes32)",
  "function engineEvidenceHash() view returns (bytes32)",
  "function version() view returns (uint64)",
  "event EngineIdentitySet(address indexed newSigKey, bytes32 newEncKey, bytes32 newCompose, uint64 indexed newVersion, bytes tlsCertDer, bytes quote, bytes eventLog)",
]);

const read = (functionName: "engineSigKey" | "engineEncKey" | "composeHash" | "engineEvidenceHash" | "version") =>
  publicClient.readContract({ address: registry, abi: REGISTRY_ABI, functionName });

const [sigKey, encKey, compose, evidenceHash, version] = await Promise.all([
  read("engineSigKey"), read("engineEncKey"), read("composeHash"), read("engineEvidenceHash"), read("version"),
]);

const [log] = await publicClient.getContractEvents({
  address: registry,
  abi: REGISTRY_ABI,
  eventName: "EngineIdentitySet",
  args: { newVersion: version as bigint },
  fromBlock: deployedAtBlock, // from the Deployments page
});

const { newSigKey, newEncKey, newCompose, tlsCertDer, quote, eventLog } = log.args;
const recomputed = keccak256(
  encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }, { type: "bytes" }], [tlsCertDer!, quote!, eventLog!]),
);
const evidenceMatches = recomputed === evidenceHash;
const keysMatch = newSigKey === sigKey && newEncKey === encKey && newCompose === compose;
```

Your node can limit the block range of `getContractEvents`. Split a long range into parts.

## The heartbeat

The engine signs a heartbeat, and any address submits it with `attestHeartbeat(attestedBlock, attestedTick, engineSignature)`. The registry accepts it only when:

* `attestedBlock` is more than `lastHeartbeatBlock()` and not more than `block.number`,
* the signature recovers to `engineSigKey()` over this digest:

```solidity theme={null}
keccak256(abi.encode(keccak256("ANAFI_HEARTBEAT_V1"), block.chainid, address(registry), attestedBlock, attestedTick))
```

Each accepted heartbeat emits `HeartbeatAttested(uint64 indexed attestedBlock, uint64 attestedTick)`.

Use the heartbeat as a liveness signal:

* Compare `lastHeartbeatTick()` with the current time. A large gap means that no new heartbeat landed.
* Compare `lastHeartbeatBlock()` with the chain head. This tells a stopped engine from a stopped chain.

The contract sets no heartbeat interval. Choose your own alarm threshold.

To check a heartbeat yourself, take the `attestHeartbeat` transaction of a `HeartbeatAttested` log, decode its input, compute the digest, and recover the signer:

```ts theme={null}
import { decodeFunctionData, encodeAbiParameters, keccak256, parseAbi, recoverAddress, toHex } from "viem";

const HEARTBEAT_ABI = parseAbi([
  "function attestHeartbeat(uint64 attestedBlock, uint64 attestedTick, bytes engineSignature)",
  "event HeartbeatAttested(uint64 indexed attestedBlock, uint64 attestedTick)",
]);

const [heartbeatLog] = await publicClient.getContractEvents({
  address: registry,
  abi: HEARTBEAT_ABI,
  eventName: "HeartbeatAttested",
  args: { attestedBlock: lastHeartbeatBlock },
  fromBlock: lastHeartbeatBlock,
});
const tx = await publicClient.getTransaction({ hash: heartbeatLog.transactionHash });
const { args } = decodeFunctionData({ abi: HEARTBEAT_ABI, data: tx.input });
const [attestedBlock, attestedTick, engineSignature] = args;

const digest = keccak256(
  encodeAbiParameters(
    [{ type: "bytes32" }, { type: "uint256" }, { type: "address" }, { type: "uint64" }, { type: "uint64" }],
    [keccak256(toHex("ANAFI_HEARTBEAT_V1")), BigInt(polygonAmoy.id), registry, attestedBlock, attestedTick],
  ),
);
const signer = await recoverAddress({ hash: digest, signature: engineSignature });
// signer must equal engineSigKey() at the block of the heartbeat
```

This decode works when the heartbeat transaction calls the registry directly.

## The live adapter list

`delegationAdapters()` returns the adapters that the registry lists, in list order. Each Anafi adapter calls `isDelegationAdapter(address(this))` first on each redeem. An adapter that the list does not hold refuses every redeem with `AdapterNotAllowed()`.

Check an adapter before you grant it a permission:

1. The registry lists it: `isDelegationAdapter(adapter)` is `true`.
2. It reads this registry: `adapter.anafiRegistry()` equals the registry address. The registry checked this when it listed the adapter.
3. It has the expected tag: `ROUTE_TAG()` returns `0x31747694805ea00e26185495e79555aa0fd8bc5ed92dee2440234ea76be46373`.

The SDK reads `delegationAdapters()` and serves an account kind only while the list holds the configured adapter of that kind. See [Client](https://docs.ana.fi/sdk/client.md).

Watch the list with `DelegationAdapterAdded(address indexed adapter)` and `DelegationAdapterRemoved(address indexed adapter)`.

## Admin and code changes

The registry owner can change the engine identity, the adapter list and the code of each proxy. See [Contracts overview](https://docs.ana.fi/contracts/overview.md#admin-powers-and-upgrades). Each change is visible on chain:

| Change | Event | Contract |
| - | - | - |
| New engine identity | `EngineIdentitySet` | `AnafiRegistry` |
| Adapter listed or delisted | `DelegationAdapterAdded`, `DelegationAdapterRemoved` | `AnafiRegistry` |
| Admin handover started or done | `OwnershipTransferStarted`, `OwnershipTransferred` | `AnafiRegistry` |
| New code of a proxy | `Upgraded(address indexed implementation)` | `AnafiRegistry`, `AnafiDslRegistry`, both adapters |
| Safe admission changed | `SafeProxyCodehashAdmittedSet`, `SafeSingletonAdmittedSet` | Safe adapter |
| Gas token admitted or stopped | `GasOverheadSet` | both adapters |
| Swap pair added or removed | `SwapRouterAllowedSet` | ERC20Allow adapter |

To read the current implementation of a proxy, read the ERC-1967 implementation slot `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`:

```ts theme={null}
const word = await publicClient.getStorageAt({
  address: proxy,
  slot: "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
});
const implementation = `0x${word!.slice(26)}`;
```

`AnafiSwapExecutor` and `AnafiOffRampFallbackHandler` have no proxy, so their code never changes.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.