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

# xdrlint rules

> Every xdrlint rule on one page: what it reports, why it matters, examples, limits and how to suppress it; how to run the linter, its output formats and configuration.

For authors of Go indexers and pipelines built on the go-stellar-sdk ingest stack (the `xdr`, `ingest`,
`processors/token_transfer` and `strkey` packages): what each `xdrlint` rule reports, how to run the linter, and how
to configure it or accept a report.

| Family | Mistake |
| - | - |
| XDR1xx | trusting fields stellar-core never validated |
| XDR2xx | walking self-referential structures with no depth or size bound |
| XDR3xx | deriving participants from the envelope instead of the meta |
| XDR4xx | assumptions about the ledger's form, ranges and outcomes |
| XDR000 | suppression hygiene: a suppression with no reason, an unknown rule, or one that suppresses nothing |

Each rule has a page with what it reports, why, a reported and a compliant example taken from the linter's own
fixtures, and its limits. The guide sections are in [guide/indexer-hardening.mdx](https://docs.xdrcheck.dev/hardening/overview.md).

| Rule | What it reports | Default severity | Default set | Guide section | Checklist |
| - | - | - | - | - | - |
| [XDR000](#xdr000) | suppression without a reason, naming an unknown rule, or suppressing nothing | error | yes | this page | — |
| [XDR101](#xdr101) | address built from a memo | error | yes | [The event routing ID](https://docs.xdrcheck.dev/hardening/overview.md) | HC-101 |
| [XDR102](#xdr102) | unnormalised address used as an identity key | error | yes | [Muxed and signed-payload handling](https://docs.xdrcheck.dev/hardening/overview.md) | HC-102 |
| [XDR103](#xdr103) | unvalidated bytes or string into text storage | error | yes | [Validated versus unvalidated fields](https://docs.xdrcheck.dev/hardening/overview.md) | HC-103 |
| [XDR105](#xdr105) | Must\<Arm>() on a multi-arm union without a dominating discriminant check | warning | opt-in | [Validated versus unvalidated fields](https://docs.xdrcheck.dev/hardening/overview.md) | HC-107 |
| [XDR201](#xdr201) | recursion over a self-referential xdr type with no depth bound | warning | yes | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) | HC-201 |
| [XDR202](#xdr202) | iterative walker with an unbounded worklist | warning | yes | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) | HC-202 |
| [XDR203](#xdr203) | decoded integer used as an allocation size or loop bound | warning | yes | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) | HC-203 |
| [XDR204](#xdr204) | persisted serialisation of a recursive value with no length check | info | opt-in | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) | HC-209 |
| [XDR205](#xdr205) | decoder with limits disabled | error | yes | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) | HC-204 |
| [XDR206](#xdr206) | behaviour at a bound differs from the declared overflow policy | warning | yes | [What to do at a bound: a trade-off](https://docs.xdrcheck.dev/hardening/overview.md) | HC-205 |
| [XDR207](#xdr207) | bound below what stellar-core admits, on a path fed from ledger meta | warning | yes | [What stellar-core admits](https://docs.xdrcheck.dev/hardening/overview.md) | HC-206 |
| [XDR301](#xdr301) | participants harvested from the authorization tree or invocation arguments | error | yes | [Participants from meta](https://docs.xdrcheck.dev/hardening/overview.md) | HC-301 |
| [XDR302](#xdr302) | envelope operation fields used as participants without a success gate | error | yes | [Participants from meta](https://docs.xdrcheck.dev/hardening/overview.md) | HC-302 |
| [XDR303](#xdr303) | participant builder that never reads meta | warning | yes | [Participants from meta](https://docs.xdrcheck.dev/hardening/overview.md) | HC-303 |
| [XDR304](#xdr304) | token-shaped contract event trusted without checking the emitting contract | error | yes | [Deriving participants](https://docs.xdrcheck.dev/hardening/overview.md) | HC-305 |
| [XDR401](#xdr401) | one meta version assumed: an arm read without a version check, or a version check that halts on the others | error | yes | [Fail closed at protocol boundaries](https://docs.xdrcheck.dev/hardening/overview.md) | HC-506 |
| [XDR402](#xdr402) | wide integer narrowed without a range check and stored | error | yes | [64-bit IDs](https://docs.xdrcheck.dev/hardening/overview.md) | HC-404 |
| [XDR403](#xdr403) | error or ok result discarded on a value that is then stored | warning | yes | [Validated versus unvalidated fields](https://docs.xdrcheck.dev/hardening/overview.md) | HC-108 |
| [XDR404](#xdr404) | contract event topics or data trusted by position or kind without a shape or emitter check | error | yes | [Contract events](https://docs.xdrcheck.dev/hardening/overview.md) | HC-306 |
| [XDR405](#xdr405) | rows from diagnostic events without a success gate, or from transaction-level changes in operation scope | error | yes | [Failed transactions: what still lands in the ledger](https://docs.xdrcheck.dev/hardening/overview.md) | HC-307 |
| [XDR406](#xdr406) | closed switch over an xdr enum that writes rows, with no default or a panicking default | warning | opt-in | [Fail closed at protocol boundaries](https://docs.xdrcheck.dev/hardening/overview.md) | HC-507 |

## Running it

| Mode | How |
| - | - |
| Standalone | `go install github.com/OWNER/REPO/lint/cmd/xdrlint@<version>`, then `xdrlint ./...` in your module |
| `go vet` tool | `go vet -vettool=$(which xdrlint) ./...`; configuration from `.xdrlint.yml` or `XDRLINT_PROFILE`, `XDRLINT_CONFIG` |
| golangci-lint module plugin | a `.custom-gcl.yml` naming `github.com/OWNER/REPO/lint/plugin`, built with `golangci-lint custom` at the golangci-lint version that uses the same `golang.org/x/tools` (v2.15.0 for this release); settings under `linters.settings.custom.xdrlint.settings`: `profile`, `config`, or any configuration key inline. See the package documentation of `lint/plugin` |

Building `xdrlint` needs Go 1.26 or later; the code it checks may declare an older Go version.

A five-minute walk-through (install, run, read a diagnostic, suppress with a reason, run in CI) is in
[lint/README.md](https://docs.xdrcheck.dev/guides/lint-go.md).

Output:

| Flag | Output |
| - | - |
| (none) | text: `file:line:col: XDR201 (warning): message`, then a `fix:` line with the usual fix and a `docs:` line with the rule's page; on stderr a closing summary of what was found, whether the run fails and how to accept a report. Page links start at `-docs-base` (or `XDRLINT_DOCS_BASE`; default `lint/docs`; a base containing `{rule}` is a template) |
| `-json` | the `go/analysis` diagnostic tree with each report's rule, severity, function, guide anchor, corpus entry, fix and page link |
| `-sarif FILE` | SARIF 2.1.0, every rule linked to its page, suppressed reports marked as such |
| `-report FILE` | every report, suppressed ones included, as `xcc.report/v1` rows |
| `-expect FILE` | a comparison with a frozen expected list that fails on any difference in either direction. The list is compared by count: each entry (rule, file, function, suppressed) stands for `count` reports (default 1), so one report more than it counts is a difference |

| Exit | When |
| - | - |
| 0 | no unsuppressed report at or above `-fail-on`, and no `-expect` difference |
| 1 | an unsuppressed report that no `-pending` list names is at or above `-fail-on` (default `error`), or, with `-expect`, any difference |
| 2 | a usage, configuration or loading error; or no recognised source package is loaded (none of the packages, nor anything they import, is go-stellar-sdk's `xdr` package or an alias of it), since the rules then analyse nothing |

## Configuration

`.xdrlint.yml` in the module (or a file named with `-config`), over a shipped profile named with `-profile`
(`default`, `wallet-backend`, or a path). Keys are flat and lower-case so that golangci-lint can pass them through:

| Key | Meaning |
| - | - |
| `rules` | enabled rule IDs (default: every rule not marked opt-in) |
| `severity` | map of rule ID to `error`, `warning` or `info` |
| `xdrpackagealiases` | extra import paths treated as the SDK's `xdr` package |
| `participantnameregex` | names of participant sets (default `(?i)participant`) |
| `sinksparticipant`, `sinksaccountkey`, `sinkstext`, `sinksmovement` | extra sinks, as `pkg.Func`, `pkg.Type.Method` or `pkg.Type.Field` |
| `sanitizersaddress`, `sanitizerstext`, `sanitizersevent` | functions accepted as normalisers or verifiers |
| `budgetmethods` | methods accepted as a depth budget check (XDR201) |
| `overflowpolicy`, `overflowflags`, `haltingfuncs`, `ingestentrypoints` | what the project does at a bound (XDR206) |
| `floors` | map of structure to the minimum bound (XDR207) |
| `suppressions` | an external suppression file |

A configured name that does not exist in a loaded package stops the run, so a misspelt sink cannot silently check
nothing.

## Configuring and suppressing

Every report can be accepted with a reason:

* **Inline**, on the reported line or on the enclosing function's doc comment:
  `//xdrlint:ignore XDR201 linear walk over a tree the decoder bounded`. Under golangci-lint,
  `//nolint:xdrlint // <reason>` works too (enable `nolintlint` with `require-explanation` and
  `require-specific`).
* **An external suppression file**, for code you cannot edit: a YAML list of entries with `rule`, `file`
  (module-relative), one or more of `function` (`F` or `Type.Method`), `anchor` (a substring of the reported line),
  `line` (the reported line) and `message` (the report's message), and `reason`; optionally `finding`, `issue`,
  `commit`, `reviewer` and `date`. Every key given must match. An entry with a function only survives line drift
  but also accepts any new report of its rule in that function; an anchor or a line narrows it to one site, which
  is what a list frozen against one commit should use. `function` with `message` is the baseline key that
  survives code moving within the file: the message is compared without the line numbers it names
  (`line 28`, `events.go:12`), so it names one report without naming a line.

A suppression without a reason, one naming an unknown rule, and one that suppresses nothing are reported as
XDR000, which cannot itself be suppressed.

Every diagnostic names, in `assumption` (JSON, SARIF result properties and `-report` rows), the assumption about
the ledger the reported code makes, as a stable key such as `meta-version:v4-only` or `narrowing:u64->int64`.
`lint/docs/assumptions.md` lists every key with the input that violates it. Suppressed reports are not printed, but `-report`, `-json` and `-sarif`
keep them, marked as suppressed.

## Suppression hygiene

### XDR000

**Suppression without a reason, naming an unknown rule, or suppressing nothing.**

| | |
| - | - |
| Family | XDR0xx: suppression hygiene |
| How to fix | give the directive or entry a reason after the rule ID, name a rule that exists, or delete the suppression that matches nothing |
| Default severity | error (`severity: {XDR000: …}` changes it) |
| Default rule set | yes |
| Documentation | [Configuring and suppressing](#configuring-and-suppressing) |
| Fixtures | `lint/testdata/xdr0xx/xdr000` |

**What it reports**

A suppression that cannot be trusted:

* an inline directive (`//xdrlint:ignore`) with no reason, naming an unknown rule, malformed, or naming XDR000;
* an entry of an external suppression file with no reason, an unknown rule, none of a function, an anchor and a
  line, or an unknown key;
* any suppression, inline or external, that suppresses nothing.

**Why it matters**

A suppression is a reviewed statement that a report is understood. One without a reason cannot be reviewed, and
one that suppresses nothing has outlived the code it was written for. Reporting stale suppressions is what makes a
frozen suppression list able to fail: when the site changes or the rule stops firing, the run turns red.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr0xx/xdr000/bad.go
func describe(tx xdr.TransactionEnvelope) []string {
	var names []string

	//xdrlint:ignore XDR201
	names = append(names, tx.SourceAccount().ToAccountId().Address())

	//xdrlint:ignore XDR999 not a rule of this linter
	names = append(names, tx.Memo().Type.String())

	// xdrlint:ignore XDR102 a space after the slashes would hide the directive

	//xdrlint:allow XDR102 wrong verb

	//xdrlint:ignore XDR000 hygiene is not optional

	//xdrlint:ignore XDR10 a typo

	return names
}
```

Not reported: a well-formed directive that marks a sink.

```go theme={null}
// lint/testdata/xdr0xx/xdr000/good.go
// storeKey is an account-key sink; the directive is well formed and the key
// is reduced to the base account first.
//
//xdrlint:sink accountkey
func storeKey(keys map[string]bool, a xdr.MuxedAccount) {
	acc := a.ToAccountId()
	keys[acc.Address()] = true
}
```

**Limits**

XDR000 cannot itself be suppressed.

**Configure and suppress**

Turn the rule off by leaving XDR000 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR000 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

## Mistake 1: trusting fields stellar-core does not validate

### XDR101

**Address built from a memo.**

| | |
| - | - |
| Family | XDR1xx: trusting unvalidated fields |
| How to fix | route only a u64 to\_muxed\_id (or a MEMO\_ID) into a muxed address; keep memo text and hash as data, never as an ID |
| Default severity | error (`severity: {XDR101: …}` changes it) |
| Default rule set | yes |
| Guide | [The event routing ID](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-101 |
| Demonstrating corpus entry | `cap-0067/to-muxed-id-text-from-memo` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr1xx/xdr101` |

**What it reports**

A value derived from a transaction memo reaches the construction of a muxed address: an
`xdr.MuxedAccountMed25519`, `xdr.MuxedEd25519Account` or `xdr.MuxedContract` literal, `strkey.MuxedAccount.SetID`,
`strkey.MuxedContract.SetID`, `strkey.Encode` with a muxed version byte, `xdr.NewMuxedAccount` or
`xdr.MuxedAccountFromAccountId`.

Sources are the memo accessors (`xdr.Memo.Id`, `Text`, `Hash`, `RetHash` and their `Get…`/`Must…` forms,
`TransactionEnvelope.Memo()`, `ingest.LedgerTransaction.Memo()`), the token transfer processor's `MuxedInfo`
getters, and any value assigned on a path where a type switch chose the text or hash arm of a `MuxedInfo`.

**Why it matters**

stellar-core never checks what a memo contains, and since CAP-67 it copies the memo of a classic payment into
the event's `to_muxed_id`, which can therefore be a 64-bit ID, a text string or 32 bytes. A text or hash memo is
not a routing ID, and an address built from one names an account that nobody controls. Store a memo-derived ID
as an ID, next to the base account, and never turn it into an `M…` address.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr1xx/xdr101/bad.go
// (b) A type switch whose text and hash arm sets id = 0 and falls through
// to SetID.
func destinationFromSwitch(to string, info *token_transfer.MuxedInfo) (string, error) {
	var id uint64
	switch c := info.Content.(type) {
	case *token_transfer.MuxedInfo_Id:
		id = c.Id
	case *token_transfer.MuxedInfo_Text, *token_transfer.MuxedInfo_Hash:
		id = 0
	default:
		return "", nil
	}
	var m strkey.MuxedContract
	if err := m.SetContractID(to); err != nil {
		return "", err
	}
	m.SetID(id)
	return m.Address()
}
```

Not reported: the ID is stored as an ID.

```go theme={null}
// lint/testdata/xdr1xx/xdr101/good.go
// (a) The memo-derived routing ID stored only as an ID, never as an address.
func setToMuxedID(t *transfer, info *token_transfer.MuxedInfo) {
	if info == nil {
		return
	}
	switch c := info.Content.(type) {
	case *token_transfer.MuxedInfo_Id:
		id := c.Id
		t.ToMuxedID = &id
	case *token_transfer.MuxedInfo_Text, *token_transfer.MuxedInfo_Hash:
		// A memo, not a routing ID: not stored as one.
	}
}
```

**Limits**

A memo copied into a struct field and encoded into an address in another package is not followed. An indexer
that deliberately renders memo-routed addresses for display should suppress the report with that reason.

**Configure and suppress**

Turn the rule off by leaving XDR101 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR101 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR102

**Unnormalised address used as an identity key.**

| | |
| - | - |
| Family | XDR1xx: trusting unvalidated fields |
| How to fix | key on the base account: MuxedAccount.ToAccountId(), or a switch on ScAddress.Type that handles the muxed, claimable-balance and pool kinds |
| Default severity | error (`severity: {XDR102: …}` changes it) |
| Default rule set | yes |
| Guide | [Muxed and signed-payload handling](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-102 |
| Demonstrating corpus entry | `cap-0027/muxed-source-and-destination-max-ids` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr1xx/xdr102` |

**What it reports**

An address string taken from a value that can be muxed, a signed payload, or a non-account kind is used as a
participant or account key without being reduced to its base account or having its kind checked.

Sources are `(*xdr.MuxedAccount).Address()` and `GetAddress()` (also through `TransactionEnvelope.SourceAccount()`,
`FeeBumpAccount()`, `Operation.SourceAccount` and operation destinations), `ingest.LedgerTransaction.AccountMuxed()`
and `FeeAccountAddress()`, `xdr.ScAddress.String()`, `(*xdr.SignerKey).Address()` and the keys of
`AccountEntry.SignerSummary()`. Sinks are participant sets and configured account-key types and functions
(`sinksparticipant`, `sinksaccountkey`).

An address can be wrong in two ways, and each is checked on its own: it can be in muxed form (`M…`, `W…`), or it
can be of a kind that is not an account (`B…` claimable balance, `L…` liquidity pool, `P…`, `T…`, `X…` signers).

The report is silent when the value went through `MuxedAccount.ToAccountId()`, when a dominating switch or `if` on
`ScAddress.Type` handles the muxed kinds and excludes or routes the claimable-balance and liquidity-pool kinds,
when a configured normaliser (`sanitizersaddress`) produced it, or when the address is the contract of a contract
data entry the host wrote into meta (never a muxed kind). Besides:

* **A sink that normalises.** An account-key type whose own `Value()` decodes the strkey, reduces the muxed
  account kind and refuses any payload that is not a 32-byte key (as `AddressBytea.Value()` does) stores a muxed
  address as its base key; so does a function whose string parameter only becomes such a type (a builder's
  `WithAccount`). Only the non-account kinds are reported there, because that type refuses them with a write
  error. The property is read from the `Value()` body, in whichever package declares it.
* **A re-parse of the same entry.** A sink on the passing branch of `sac.ContractBalanceFromContractData(entry, …)`
  (ok only when the balance key's holder is a contract) is kind-checked, when the address was read from the same
  ledger entry.
* **Contract storage.** The host refuses to store a claimable-balance, liquidity-pool or muxed address, so an
  address read from the key or value of a contract-data entry is a `G…` or `C…` address. This is decided per call
  of a shared helper: `addrString(entry.Key)` is exempt, `addrString(topics[1])` is not.
* **Where `B…` and `L…` come from.** A contract can never store, return or emit a claimable-balance or pool
  address: the host refuses to convert one to a contract value. Such an address reaches a reader only in events the
  host emits for the Stellar Asset Contract, or in the envelope (invocation arguments, the authorization tree), which
  is submitter bytes. The non-account kind is reported only for an address that may have been read from a contract
  event's topics or data or from those envelope fields, and not for one decoded on the branch where the event's name
  is one the Stellar Asset Contract never emits (`case "supply": decode(topics)`).

**Why it matters**

stellar-core uses only the ed25519 key of a muxed account; the 64-bit ID is never validated. Storing the `M…`
form as identity splits one account into as many accounts as there are IDs, and fixed-width columns truncate
`M…`, `P…` and `B…` strkeys. `ScAddress.String()` renders every kind SEP-23 defines, including claimable
balances (`B…`) and liquidity pools (`L…`), which are not accounts at all.

**Example**

Reported: the operation source is used as identity in its muxed form.

```go theme={null}
// lint/testdata/xdr1xx/xdr102/bad.go
// (a) The operation source rendered with Address(): M… when muxed.
func operationParticipants(op xdr.Operation, participants set) {
	participants.Add(op.SourceAccount.Address())
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr1xx/xdr102/good.go
// (a) Reduced to the base account first.
func operationParticipantsBase(op xdr.Operation, tx *ingest.LedgerTransaction, participants set) {
	if op.SourceAccount != nil {
		participants.Add(op.SourceAccount.ToAccountId().Address())
	}
	participants.Add(tx.Envelope.SourceAccount().ToAccountId().Address())
	if acc, err := tx.Account(); err == nil {
		participants.Add(acc)
	}
}
```

**Limits**

Flows through `map[string]interface{}` are not followed. Sinks in another module are seen only when configured.
Values decoded from bytes (an RPC response, base64 topics) are not recognised as events or envelope fields, so an
address read from them loses the non-account-kind aspect (a false negative). The event-name exemption trusts that a contract's event called
`supply` is not a Stellar Asset Contract event, which holds for every event name the SAC does not use.

**Configure and suppress**

Turn the rule off by leaving XDR102 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR102 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR103

**Unvalidated bytes or string into text storage.**

| | |
| - | - |
| Family | XDR1xx: trusting unvalidated fields |
| How to fix | check utf8.ValidString and reject or strip NUL before storing as text, or store the bytes as bytea, hex or base64 |
| Default severity | error (`severity: {XDR103: …}` changes it) |
| Default rule set | yes |
| Guide | [Validated versus unvalidated fields](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-103 |
| Demonstrating corpus entry | `cap-0067/to-muxed-id-text-non-utf8-memo` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr1xx/xdr103` |

**What it reports**

Bytes or a string that a submitter or a contract controls reach text storage without UTF-8 and NUL handling.

Sources are `xdr.Memo.Text` and its accessors, `ingest.LedgerTransaction.Memo()`, `xdr.ScVal.Str`,
`ScVal.ExecutableTag`, `ContractExecutableExternalRef.Tag`, `ScBytes`, `ManageDataOp.DataValue`,
`DataEntry.DataValue` and the text arm of a token transfer `MuxedInfo`. Text sinks are the arguments of
`database/sql` and `pgx` `Exec`, `Query` and `CopyFrom`, `string` struct fields tagged `db:"…"`, proto3 string
fields of the reader's own message types, and any field named in `sinkstext` (all errors), and `string` fields
tagged `json:"…"` (a warning: `encoding/json` writes invalid UTF-8 as U+FFFD and NUL as `\u0000`, so the
stored text silently differs from the bytes on chain, and a PostgreSQL `jsonb` column rejects the NUL).

Not sources: `SetOptionsOp.HomeDomain` and `ManageDataOp.DataName`, which stellar-core validates as printable
ASCII. `ScSymbol` is restricted by the host.

The report is silent after a dominating `utf8.ValidString` check together with a NUL check, after
`strings.ToValidUTF8` with NUL stripping, after base64 or hex encoding, after conversion to `[]byte` for a bytes
column, or after a configured sanitiser (`sanitizerstext`). A value that parsed as an integer
(`strconv.ParseUint`, `ParseInt`, `Atoi` with a nil error) or that a dominating comparison or `switch` fixed to
one of a few clean string literals carries no text either.

**Why it matters**

A text memo has only an XDR length bound: stellar-core accepts a memo that is not valid UTF-8 and copies it
verbatim into the transaction's events. An `ScString` is arbitrary bytes. PostgreSQL rejects invalid UTF-8 and
NUL in text columns, so one such value fails the whole persist transaction; for a reader that commits a ledger
at a time, that stops ingestion.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr1xx/xdr103/bad.go
// (a) Memo text into a database/sql parameter.
func storeMemo(db *sql.DB, memo xdr.Memo) error {
	text, ok := memo.GetText()
	if !ok {
		return nil
	}
	_, err := db.Exec(`INSERT INTO memos (text) VALUES ($1)`, text)
	return err
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr1xx/xdr103/good.go
// (b) Invalid UTF-8 replaced and NUL bytes stripped.
func storeMemoSanitised(db *sql.DB, memo xdr.Memo) error {
	text := strings.ReplaceAll(strings.ToValidUTF8(memo.MustText(), "�"), "\x00", "")
	_, err := db.Exec(`INSERT INTO memos (text) VALUES ($1)`, text)
	return err
}
```

**Limits**

The analyzer cannot see SQL column types: a column that is really `bytea` is reported until it is configured or
the value is converted to `[]byte`. SQL built by string concatenation is not followed. Fields are followed one by
one through struct values and through struct pointers passed to or returned from functions of the same package (a
builder's methods); what a pointer field points to, and a callee's writes through a pointer, are not. A helper of the
same package called at several sites returns at each site only what that site passed in.

**Configure and suppress**

Turn the rule off by leaving XDR103 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR103 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR105

**Must\<Arm>() on a multi-arm union without a dominating discriminant check.**

| | |
| - | - |
| Family | XDR1xx: trusting unvalidated fields |
| How to fix | switch on the union's type, or use the ok result of Get\<Arm>(), before calling Must\<Arm>() |
| Default severity | warning (`severity: {XDR105: …}` changes it) |
| Default rule set | no: opt-in, add XDR105 to `rules` |
| Guide | [Validated versus unvalidated fields](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-107 |
| Demonstrating corpus entry | `cap-0067/token-events-bytes-and-bad-type-muxed-id` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr1xx/xdr105` |

**What it reports**

`Must<Arm>()` on a union with more than one arm, at a point not dominated by a check of the same value's
discriminant (a `switch` on its type, a comparison, or the `ok` result of the matching `Get<Arm>()`).

**Why it matters**

The `Must…` accessors panic when the value holds another arm. Which arm a field of a ledger holds is chosen by the
submitter or a contract wherever the protocol allows several, so an unchecked `Must…` lets a ledger crash the
reader.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr1xx/xdr105/bad.go
func memoText(m xdr.Memo) string {
	return m.MustText()
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr1xx/xdr105/good.go
func memoTextChecked(m xdr.Memo) string {
	if m.Type != xdr.MemoTypeMemoText {
		return ""
	}
	return m.MustText()
}
```

**Limits**

Opt-in, because the rule cannot know protocol facts that fix the arm (for example that a successful operation of
one type always has a result of the matching arm) and reports such calls too.

**Configure and suppress**

Turn the rule off by leaving XDR105 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR105 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

## Mistake 2: no depth or size cap on recursive structures

### XDR201

**Recursion over a self-referential xdr type with no depth bound.**

| | |
| - | - |
| Family | XDR2xx: missing depth and size caps |
| How to fix | pass a depth counter down the recursion and stop at a limit at or above what stellar-core admits |
| Default severity | warning (`severity: {XDR201: …}` changes it) |
| Default rule set | yes |
| Guide | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-201 |
| Fixtures | `lint/testdata/xdr2xx/xdr201` |

**What it reports**

A function or closure that recurses, directly or through other functions of the same package, passing a value of a
self-referential xdr type (after dereference, slice element or range element), with no depth bound. The
self-referential types are computed from the loaded `xdr` package: `SorobanAuthorizedInvocation`,
`SorobanDelegateSignature`, the `ScVal` group, `ClaimPredicate` and the `ScSpecTypeDef` group at go-stellar-sdk
v0.9.0. The report is an error when a level merges its children's results (`Union`, `append(x, ys...)`), and a
warning otherwise.

A bound is an integer parameter, receiver field or captured variable that every recursive call changes by a
constant and that is compared with a limit before recursing, leading to a return or break; or a configured budget
method (`budgetmethods`) called and error-checked first.

**Why it matters**

The host checks only the authorization entries that a `require_auth` call matched. Unmatched entries, nested trees included, are never examined, and a transaction carrying them succeeds, so the shape of the tree is the submitter's choice.

A bound silences this rule only. A constant bound on a path fed from ledger meta is then examined by XDR207, which
reports it when it is below what stellar-core admits, and the behaviour past the bound by XDR206. A low fixed cap
is never the quiet option.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr201/bad.go
// (a) A named function over SubInvocations.
func countContracts(inv xdr.SorobanAuthorizedInvocation) int {
	n := 0
	if inv.Function.Type == xdr.SorobanAuthorizedFunctionTypeSorobanAuthorizedFunctionTypeContractFn {
		n++
	}
	for _, sub := range inv.SubInvocations {
		n += countContracts(sub)
	}
	return n
}
```

Not reported: the depth limit comes from configuration.

```go theme={null}
// lint/testdata/xdr2xx/xdr201/good.go
// (a) A depth parameter compared with a bound from configuration.
func walkBounded(cfg config, inv xdr.SorobanAuthorizedInvocation, depth int) error {
	if depth > cfg.MaxAuthDepth {
		return errTooDeep
	}
	for _, sub := range inv.SubInvocations {
		if err := walkBounded(cfg, sub, depth+1); err != nil {
			return err
		}
	}
	return nil
}
```

**Limits**

"The walk only runs for successful transactions" is deliberately not a bound. Recursion through interface
dispatch, through `fmt` and `Stringer` (`ScVal.String`), or across packages is not seen. Walkers over structures
that stellar-core bounds itself (`ClaimPredicate`, at most 4 levels) are reported and can be suppressed with that
reason.

**Configure and suppress**

Turn the rule off by leaving XDR201 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR201 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR202

**Iterative walker with an unbounded worklist.**

| | |
| - | - |
| Family | XDR2xx: missing depth and size caps |
| How to fix | count nodes (or the worklist length) inside the loop and stop at a limit at or above what stellar-core admits |
| Default severity | warning (`severity: {XDR202: …}` changes it) |
| Default rule set | yes |
| Guide | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-202 |
| Fixtures | `lint/testdata/xdr2xx/xdr202` |

**What it reports**

A loop that pops values of a self-referential xdr type from a slice and appends their children, with no comparison
of the worklist length or of a counter incremented in the loop against a bound.

**Why it matters**

Rewriting a recursive walk as a loop with an explicit stack removes the recursion but not the problem: the work
still grows with a tree the submitter shaped (see XDR201). The bound has to be there in either form.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr202/bad.go
// The natural rewrite that silences XDR201 and moves the problem.
func contractsIterative(root xdr.SorobanAuthorizedInvocation) []string {
	var out []string
	stack := []xdr.SorobanAuthorizedInvocation{root}
	for len(stack) > 0 {
		inv := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		if fn, ok := inv.Function.GetContractFn(); ok {
			s, _ := fn.ContractAddress.String()
			out = append(out, s)
		}
		stack = append(stack, inv.SubInvocations...)
	}
	return out
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr202/good.go
// An explicit stack with a node counter and a length check.
func contractsBounded(root xdr.SorobanAuthorizedInvocation, maxNodes int) ([]string, error) {
	var out []string
	stack := []xdr.SorobanAuthorizedInvocation{root}
	visited := 0
	for len(stack) > 0 {
		visited++
		if visited > maxNodes || len(stack) > maxNodes {
			return nil, errTooMany
		}
		inv := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		if fn, ok := inv.Function.GetContractFn(); ok {
			s, _ := fn.ContractAddress.String()
			out = append(out, s)
		}
		stack = append(stack, inv.SubInvocations...)
	}
	return out, nil
}
```

**Configure and suppress**

Turn the rule off by leaving XDR202 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR202 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR203

**Decoded integer used as an allocation size or loop bound.**

| | |
| - | - |
| Family | XDR2xx: missing depth and size caps |
| How to fix | compare the decoded integer with an upper bound before allocating or looping on it |
| Default severity | warning (`severity: {XDR203: …}` changes it) |
| Default rule set | yes |
| Guide | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-203 |
| Demonstrating corpus entry | `xdr-strict/length-prefix-exceeds-input` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr2xx/xdr203` |

**What it reports**

An integer read from a decoded xdr value used as an allocation size (`make`, `strings.Repeat`, `bytes.Repeat`) or a
loop bound with no dominating upper-bound comparison. `len` of a decoded slice is not reported: the decoder
already materialised it, and go-xdr caps its own pre-allocation and checks lengths against the remaining input.

**Why it matters**

A `u32` in a contract value or an operation is any number the submitter chose. Using it as a size lets one
transaction make the reader allocate gigabytes or spin for billions of iterations.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr203/bad.go
func bytesFor(v xdr.ScVal) []byte {
	if v.U32 == nil {
		return nil
	}
	return make([]byte, *v.U32)
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr203/good.go
func bytesBounded(v xdr.ScVal) []byte {
	if v.U32 == nil {
		return nil
	}
	n := *v.U32
	if n > maxAlloc {
		return nil
	}
	return make([]byte, n)
}
```

**Limits**

The value is followed through assignments, conversions and arithmetic, not through other calls.

**Configure and suppress**

Turn the rule off by leaving XDR203 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR203 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR204

**Persisted serialisation of a recursive value with no length check.**

| | |
| - | - |
| Family | XDR2xx: missing depth and size caps |
| How to fix | check the serialised length before writing it to the database |
| Default severity | info (`severity: {XDR204: …}` changes it) |
| Default rule set | no: opt-in, add XDR204 to `rules` |
| Guide | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-209 |
| Demonstrating corpus entry | `cap-0046/overly-large-values-golden` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr2xx/xdr204` |

**What it reports**

A serialisation of a value of a self-referential xdr type (`MarshalBinary`, `MarshalBase64`, `xdr.MarshalBase64`,
`xdr.MarshalHex`, `fmt.Sprint…`) passed to the database with no check of its length.

**Why it matters**

Contract values in events and contract data can be large and deeply nested within the network's limits. Persisting
their serialised form without a size check moves an unbounded value into a column, an index or a message that may
have a limit of its own.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr204/xdr204.go
func storeValue(db *sql.DB, v xdr.ScVal) error {
	s, err := xdr.MarshalBase64(v)
	if err != nil {
		return err
	}
	_, err = db.Exec("INSERT INTO vals (v) VALUES ($1)", s)
	return err
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr204/xdr204.go
func storeChecked(db *sql.DB, v xdr.ScVal) error {
	s, err := xdr.MarshalBase64(v)
	if err != nil {
		return err
	}
	if len(s) > maxStored {
		return nil
	}
	_, err = db.Exec("INSERT INTO vals (v) VALUES ($1)", s)
	return err
}
```

**Limits**

Opt-in and informational: storing the raw value is often exactly what a reader should do (the guide recommends
keeping the raw XDR beside derived values); the rule only asks that the size be considered.

**Configure and suppress**

Turn the rule off by leaving XDR204 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR204 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR205

**Decoder with limits disabled.**

| | |
| - | - |
| Family | XDR2xx: missing depth and size caps |
| How to fix | decode with limits: keep the default MaxDepth and set MaxInputLen, or use xdr.SafeUnmarshal |
| Default severity | error (`severity: {XDR205: …}` changes it) |
| Default rule set | yes |
| Guide | [Recommendations for meta readers](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-204 |
| Demonstrating corpus entry | a `limits/` entry at the Soroban host's value depth limit |
| Fixtures | `lint/testdata/xdr2xx/xdr205` |

**What it reports**

* An error for any use of go-xdr's `DecodeUnlimitedDepth`, or a `DecodeOptions` literal whose `MaxDepth` is an
  unlimited sentinel.
* A warning for `xdr.Unmarshal` or `xdr.UnmarshalWithOptions` on a reader without a `Len() int` method (a network
  body, a decompression stream) when `MaxInputLen` is not set.

**Why it matters**

The decoder's limits are what bound everything a reader does afterwards. With the depth limit disabled, one deeply nested value exhausts the stack; with no input length, a length prefix can claim more data than the stream holds.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr205/bad.go
// Depth unlimited, from a network body.
func decodeUnlimited(body io.Reader) (xdr.ScVal, error) {
	var v xdr.ScVal
	_, err := xdr.UnmarshalWithOptions(body, &v, xdr.DecodeOptions{MaxDepth: xdr3.DecodeUnlimitedDepth})
	return v, err
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr2xx/xdr205/good.go
// A stream with MaxInputLen set.
func decodeLimited(r io.Reader, n int) (xdr.ScVal, error) {
	var v xdr.ScVal
	_, err := xdr.UnmarshalWithOptions(r, &v, xdr.DecodeOptions{MaxInputLen: n})
	return v, err
}
```

**Limits**

Options held in a variable instead of a literal are not examined.

**Configure and suppress**

Turn the rule off by leaving XDR205 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR205 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR206

**Behaviour at a bound differs from the declared overflow policy.**

| | |
| - | - |
| Family | XDR2xx: missing depth and size caps |
| How to fix | make the branch past the bound do what overflowpolicy declares (fail the ledger, or skip and set the flag); never exit the process |
| Default severity | warning (`severity: {XDR206: …}` changes it) |
| Default rule set | yes |
| Guide | [What to do at a bound: a trade-off](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-205 |
| Fixtures | `lint/testdata/xdr2xx/xdr206` |

**What it reports**

For a walk that has a bound (XDR201 or XDR202 accepted it), the branch taken past the bound does something other
than what the project declared in `overflowpolicy`:

* under any policy, it ends the process: `panic`, `log.Fatal…`, `os.Exit` or a configured `haltingfuncs` entry;
* under `halt-ledger`, it returns without an error (`return nil`, `continue`, `break`), silently truncating;
* under `skip-and-flag`, it returns or continues without setting one of the configured `overflowflags`.

With no policy declared only the first case is reported, and the message asks for a declaration.

**Why it matters**

Past a bound a reader of ledger meta has two defensible choices, and both cost something. Stopping the ledger
with a typed, alertable error stores nothing wrong but leaves ingestion stopped on a ledger stellar-core accepted
until the bound is raised. Skipping the field, flagging the record as incomplete and keeping the raw XDR keeps
ingestion up but leaves the record incomplete until it is re-derived. A crash is neither, and a silent truncation
is the partial drop no reader wants. The linter checks that the code does what was declared; it does not choose.

**Example**

Reported under any policy:

```go theme={null}
// lint/testdata/xdr2xx/xdr206/xdr206.go
func walkPanics(l limits, inv xdr.SorobanAuthorizedInvocation, depth int) {
	if depth > l.MaxAuthDepth {
		panic("auth tree too deep")
	}
	for _, sub := range inv.SubInvocations {
		walkPanics(l, sub, depth+1)
	}
}
```

Compliant under `halt-ledger`:

```go theme={null}
// lint/testdata/xdr2xx/xdr206/xdr206.go
// Without a declared policy, stopping with an error and skipping are both
// left alone.
func walkError(l limits, inv xdr.SorobanAuthorizedInvocation, depth int) error {
	if depth > l.MaxAuthDepth {
		return errTooDeep
	}
	for _, sub := range inv.SubInvocations {
		if err := walkError(l, sub, depth+1); err != nil {
			return err
		}
	}
	return nil
}
```

**Limits**

Whether an error returned under `halt-ledger` really stops the ledger, or a caller swallows it, is not decided
locally.

**Configure and suppress**

Turn the rule off by leaving XDR206 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR206 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR207

**Bound below what stellar-core admits, on a path fed from ledger meta.**

| | |
| - | - |
| Family | XDR2xx: missing depth and size caps |
| How to fix | raise the constant to at least what stellar-core admits for that structure, or read the bound from configuration |
| Default severity | warning (`severity: {XDR207: …}` changes it) |
| Default rule set | yes |
| Guide | [What stellar-core admits](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-206 |
| Demonstrating corpus entry | a contract event whose data is nested as deep as the Soroban host converts |
| Fixtures | `lint/testdata/xdr2xx/xdr207` |

**What it reports**

A depth bound that is a compile-time constant, in a walk fed from ledger meta, below what stellar-core admits
for that structure; or, for a structure with no established limit, any such constant (as info). A bound read from
configuration is not examined: the project owns that number.

Floors shipped with the linter (`floors` in the configuration overrides or extends them):

| Structure | Floor | Source |
| - | - | - |
| `ClaimPredicate` | 4 levels | stellar-core v30.0.0, `src/transactions/CreateClaimableBalanceOpFrame.cpp` |
| `SorobanAuthorizedInvocation`, `SorobanDelegateSignature`, `ScSpecTypeDef` | not established | |

**Why it matters**

"Add a cap" is the first fix a team reaches for, and a cap below what stellar-core admits makes a reader of
consensus meta reject or mangle a valid ledger. A low fixed cap trades an XDR201 report for this one; it is never
the quiet option. Readers of untrusted input before submission (for example `net/http` handlers) are not
reported: a tighter cap there is legitimate.

**Example**

```go theme={null}
// lint/testdata/xdr2xx/xdr207/bad.go
func walkEventValue(v xdr.ScVal, depth int) error {
	if depth > maxScValDepth {
		return errTooDeep
	}
	if vec, ok := v.GetVec(); ok && vec != nil {
		for _, x := range *vec {
			if err := walkEventValue(x, depth+1); err != nil {
				return err
			}
		}
	}
	return nil
}
```

```go theme={null}
// lint/testdata/xdr2xx/xdr207/good.go
func walkAtFloor(v xdr.ScVal, depth int) error {
	if depth > maxValueDepth {
		return errTooDeep
	}
	if vec, ok := v.GetVec(); ok && vec != nil {
		for _, x := range *vec {
			if err := walkAtFloor(x, depth+1); err != nil {
				return err
			}
		}
	}
	return nil
}
```

**Limits**

Bounds computed at run time are not examined. A function that serves both meta and pre-submission input is
treated as a meta reader.

**Configure and suppress**

Turn the rule off by leaving XDR207 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR207 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

## Mistake 3: participants from the envelope instead of the meta

### XDR301

**Participants harvested from the authorization tree or invocation arguments.**

| | |
| - | - |
| Family | XDR3xx: participants from the envelope instead of the meta |
| How to fix | take participants from meta (entry changes, nonce entries, events of a verified contract), not from the authorization tree or call arguments |
| Default severity | error (`severity: {XDR301: …}` changes it) |
| Default rule set | yes |
| Guide | [Participants from meta](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-301 |
| Demonstrating corpus entry | `cap-0046/auth-unmatched-entries-succeed` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr3xx/xdr301` |

**What it reports**

A value read from an authorization entry or from invocation arguments reaches a participant sink (or a configured
state-change sink) without corroboration from meta. Sources are the credential addresses of
`SorobanAuthorizationEntry`, delegate addresses, `RootInvocation` and `SubInvocations`, the contract address and
create-contract preimages of a `SorobanAuthorizedFunction`, `InvokeContractArgs.ContractAddress` and `Args`, and
create-contract preimages.

The report is silent when the value is used only as a key into, or compared with, a set built from meta, and the
sink depends on that membership test.

**Why it matters**

The host authenticates only the authorization entries a `require_auth` call matched; a successful transaction can
carry any number of others, naming any address. The proof that an address authorised an operation is the nonce
entry the host wrote for it in the meta. A reader that adds every address in the tree lets a submitter write into
anyone's history.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr3xx/xdr301/bad.go
// (a) A credential address goes straight into the participant set.
func credentialParticipants(tx ingest.LedgerTransaction, entries []xdr.SorobanAuthorizationEntry) addrSet {
	participants := addrSet{}
	_ = tx.GetFeeChanges()
	for _, e := range entries {
		if e.Credentials.Type != xdr.SorobanCredentialsTypeSorobanCredentialsAddress {
			continue
		}
		addr, err := e.Credentials.MustAddress().Address.String()
		if err != nil {
			continue
		}
		participants.Add(addr)
	}
	return participants
}
```

Not reported: authorizers come from the nonce entries in meta.

```go theme={null}
// lint/testdata/xdr3xx/xdr301/good.go
// (a) Authorizers are the owners of the nonce entries the host created.
func authorizers(tx ingest.LedgerTransaction, opIndex uint32) (addrSet, error) {
	participants := addrSet{}
	changes, err := tx.GetOperationChanges(opIndex)
	if err != nil {
		return nil, err
	}
	for _, c := range changes {
		if c.Type != xdr.LedgerEntryTypeContractData || c.Post == nil {
			continue
		}
		cd := c.Post.Data.MustContractData()
		if cd.Key.Type != xdr.ScValTypeScvLedgerKeyNonce {
			continue
		}
		a, err := cd.Contract.String()
		if err != nil {
			return nil, err
		}
		participants.Add(a)
	}
	return participants, nil
}
```

**Limits**

An indexer that deliberately keeps "declared, unverified" relations apart from participants should suppress the
report with that reason. The host also requires authorization for some top-level host functions (a deploy from an
address). When the operation's own host function and the authorization tree reach the same sink through a function
value (a callback both paths call), the rule's source is type-based and cannot tell them apart: that report is a
known false positive of the rule, and it is suppressed with a reason that says the path is the operation's own host
function of a successful transaction.

**Configure and suppress**

Turn the rule off by leaving XDR301 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR301 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR302

**Envelope operation fields used as participants without a success gate.**

| | |
| - | - |
| Family | XDR3xx: participants from the envelope instead of the meta |
| How to fix | add operation accounts only after a success check (LedgerTransaction.Successful()), or take them from meta |
| Default severity | error (`severity: {XDR302: …}` changes it) |
| Default rule set | yes |
| Guide | [Participants from meta](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-302 |
| Demonstrating corpus entry | `cap-0015/fee-bump-inner-failed` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr3xx/xdr302` |

**What it reports**

An operation source or an account named in an operation body (payment and path-payment destinations,
`CreateAccountOp.Destination`, claimants, trustors, the clawback source, the sponsored account, revoked
sponsorship owners) reaches a participant sink at a point not dominated by a success check
(`LedgerTransaction.Successful()`, `TransactionResult(Pair).Successful()`, or a variable holding one). A helper
that returns such accounts without checking success is silent; its unguarded call sites are reported.

**Why it matters**

A failed transaction still lands in the ledger and its fee is charged, so the transaction source and the fee
source are always participants. Operation accounts are participants only when the operation was applied: a
failed payment never touched its destination. Adding them anyway lets anyone place entries in another account's
history for the price of a fee.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr3xx/xdr302/bad.go
// (c) The success check exists but comes after the envelope accounts were
// taken (the shape fixed upstream by moving the check up).
func opParticipants(tx ingest.LedgerTransaction, op xdr.Operation) []string {
	_ = tx.FeeChanges
	participants := []string{}
	for _, a := range destinations(op) {
		participants = append(participants, a.Address())
	}
	if !tx.Successful() {
		return participants
	}
	return participants
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr3xx/xdr302/good.go
// (a) The same as bad (c) with the check first: a failed transaction is
// attributed to its source and fee-bump source only.
func opParticipantsGated(tx ingest.LedgerTransaction, op xdr.Operation) []string {
	_ = tx.FeeChanges
	if !tx.Successful() {
		sourceOnly := []string{tx.Envelope.SourceAccount().ToAccountId().Address()}
		if tx.Envelope.IsFeeBump() {
			sourceOnly = append(sourceOnly, tx.Envelope.FeeBumpAccount().ToAccountId().Address())
		}
		return sourceOnly
	}
	participants := []string{}
	for _, a := range destinations(op) {
		participants = append(participants, a.Address())
	}
	return participants
}
```

**Limits**

A success check in a caller in another package is not seen.

**Configure and suppress**

Turn the rule off by leaving XDR302 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR302 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR303

**Participant builder that never reads meta.**

| | |
| - | - |
| Family | XDR3xx: participants from the envelope instead of the meta |
| How to fix | derive participants from the transaction meta (changes and events), not from the envelope alone |
| Default severity | warning (`severity: {XDR303: …}` changes it) |
| Default rule set | yes |
| Guide | [Participants from meta](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-303 |
| Demonstrating corpus entry | `cap-0073/sac-trust-creates-trustline` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr3xx/xdr303` |

**What it reports**

A function that writes a participant sink where neither it, its same-package callees, nor a same-package caller
reads any meta: fee changes, operation changes, `UnsafeMeta`, `GetChanges` and its variants, contract events,
`xdr.TransactionMeta…`, `xdr.LedgerEntryChange…` or `ingest.Change`.

**Why it matters**

Some participants exist only in the meta: the holder of a trustline the Stellar Asset Contract created, an
account a contract paid, an authorizer recorded by its nonce entry. A participant builder that reads only the
envelope misses all of them. It is a coarse backstop with little noise, since a real indexer reads at least the
fee changes.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr3xx/xdr303/bad.go
// (a) A builder that reads only the envelope's operations.
func EnvelopeParticipants(tx ingest.LedgerTransaction) []string {
	var participants []string
	participants = append(participants, tx.Envelope.SourceAccount().ToAccountId().Address())
	for _, op := range tx.Envelope.Operations() {
		if op.SourceAccount != nil {
			participants = append(participants, op.SourceAccount.ToAccountId().Address())
		}
	}
	return participants
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr3xx/xdr303/good.go
// (a) A builder that also reads fee changes.
func FeeAwareParticipants(tx ingest.LedgerTransaction) []string {
	var participants []string
	participants = append(participants, tx.Envelope.SourceAccount().ToAccountId().Address())
	for _, c := range tx.FeeChanges {
		if c.Type == xdr.LedgerEntryChangeTypeLedgerEntryUpdated && c.Updated.Data.Type == xdr.LedgerEntryTypeAccount {
			participants = append(participants, c.Updated.Data.Account.AccountId.Address())
		}
	}
	return participants
}
```

**Configure and suppress**

Turn the rule off by leaving XDR303 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR303 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR304

**Token-shaped contract event trusted without checking the emitting contract.**

| | |
| - | - |
| Family | XDR3xx: participants from the envelope instead of the meta |
| How to fix | compare the event's ContractId with asset.ContractID(passphrase) before trusting its asset or accounts |
| Default severity | error (`severity: {XDR304: …}` changes it) |
| Default rule set | yes |
| Guide | [Deriving participants](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-305 |
| Demonstrating corpus entry | `cap-0067/forged-token-event-from-unrelated-contract` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr3xx/xdr304` |

**What it reports**

A value read from the topics or data of a contract event reaches a participant sink, or is parsed into an asset
(an `xdr.Asset`, a catalogued asset constructor, a split on `":"`, a configured `sinksmovement` call), at a point
not dominated by a comparison of the event's `ContractId` with an expected contract ID.

The report is silent after `ev.ContractId` is compared with a contract ID derived from the asset and the network
passphrase (`asset.ContractID(passphrase)`, the shape go-stellar-sdk's token transfer processor uses), after a
configured verifier (`sanitizersevent`), and for a sink keyed by the event's contract ID: a configured movement
sink that takes it as an argument, or a configured sink (`sinksparticipant`, `sinksmovement`) called on a builder
that was given it earlier in the chain, such as `b.WithToken(contractID).WithAccount(to)`, directly or through a
variable or a helper that renders the ID. A record kept explicitly "for contract C" is not a claim
about another contract's asset.

**Why it matters**

The host fills an event's contract ID from the executing contract; the topics and data are whatever that contract
passes (soroban-env-host v30.0.0, `src/host.rs` and `src/events/mod.rs`). Anyone can deploy a contract that emits
a four-topic `transfer` naming a victim account and a real classic asset. A reader that credits the asset or adds
the named account as a participant lets a stranger write into another user's history.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr3xx/xdr304/bad.go
// (a) The recipient topic of a transfer-shaped event becomes a participant.
func transferParticipants(tx ingest.LedgerTransaction, participants map[string]bool) error {
	events, err := tx.GetContractEvents()
	if err != nil {
		return err
	}
	for _, ev := range events {
		topics := ev.Body.V0.Topics
		if len(topics) < 3 {
			continue
		}
		to, ok := topics[2].GetAddress()
		if !ok {
			continue
		}
		s, _ := to.String()
		participants[s] = true
	}
	return nil
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr3xx/xdr304/good.go
// (a) The recipient is taken only from the asset's own contract, the shape
// of the SDK's token transfer processor.
func sacTransferParticipants(tx ingest.LedgerTransaction, asset xdr.Asset, passphrase string, participants map[string]bool) error {
	expected, err := asset.ContractID(passphrase)
	if err != nil {
		return err
	}
	events, err := tx.GetContractEvents()
	if err != nil {
		return err
	}
	for _, ev := range events {
		if ev.ContractId == nil || *ev.ContractId != xdr.ContractId(expected) {
			continue
		}
		topics := ev.Body.V0.Topics
		if len(topics) < 3 {
			continue
		}
		to, ok := topics[2].GetAddress()
		if !ok {
			continue
		}
		s, _ := to.String()
		participants[s] = true
	}
	return nil
}
```

**Limits**

Any argument earlier in the builder chain that carries the emitting contract's ID keys the builder; the rule does
not check which setter took it. Writing the account into a plain participant set beside a keyed builder is still
reported. Verification done in another package is not seen.

**Configure and suppress**

Turn the rule off by leaving XDR304 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR304 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

## Beyond the three: assumptions about the ledger's form, ranges and outcomes

### XDR401

**One meta version assumed: an arm read without a version check, or a version check that halts on the others.**

| | |
| - | - |
| Family | XDR4xx: assumptions about the ledger's form, ranges and outcomes |
| How to fix | switch on the meta's V and handle every version the SDK declares (or skip the transaction with a typed, logged reason); never Must\<Vn>() or .Vn without that switch |
| Default severity | error (`severity: {XDR401: …}` changes it) |
| Default rule set | yes |
| Guide | [Fail closed at protocol boundaries](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-506 |
| Demonstrating corpus entry | `ledger/meta-profile-default-flags-txmeta-v3` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr4xx/xdr401` |

**What it reports**

Code that assumes one version of a versioned meta union, `xdr.TransactionMeta` or `xdr.LedgerCloseMeta`:

* an arm read with no version check of the same value: `meta.MustV3()`, `tx.UnsafeMeta.V4.SorobanMeta`, `lcm.V1`,
  where no enclosing or earlier `if` or `switch` tests `meta.V`, `meta.GetV3()` or a variable bound to them;
* a version check that halts the job on the versions it does not accept: `if meta.V != 4 { return err }`,
  `if lcm.V != 1 { panic(…) }`, or a `switch meta.V` whose default returns an error or panics, when the accepted
  versions leave out a version the rule takes as emitted by a current stellar-core (TransactionMeta v2–v4,
  LedgerCloseMeta v0–v2; see Limits).

The message names the versions that halt the job. A `switch` that handles every version the SDK declares and
stops above them with a typed error is the reviewed-version policy and is not reported. Writes to an arm (a test
helper building meta) are not reads.

**Why it matters**

Which meta version a reader receives depends on where its ledgers come from, not only on the protocol. The public
data lake serves TransactionMeta v4 for all of history; captive core and older datastores emit v2 for ledgers
before protocol 20 and v3 for protocols 20 to 22, and LedgerCloseMeta v0 before protocol 20. A reader tested on
one source stops on the first ledger from another: `export_token_transfer` failing with "expected version 4 got
3" is this mistake. A later protocol can add a version too.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr401/bad.go
// (c) A version check that halts on every other version (the export dies on
// older meta).
func unifiedEvents(tx ingest.LedgerTransaction) ([]xdr.TransactionEvent, error) {
	version := tx.UnsafeMeta.V
	if version != 4 {
		return nil, fmt.Errorf("expected meta version 4, got %d", version)
	}
	return tx.UnsafeMeta.MustV4().Events, nil
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr401/good.go
// Every version the SDK declares handled; the default is the reviewed-version
// policy (stop with a typed error above what was reviewed).
func txChangesAfterAll(meta xdr.TransactionMeta) (xdr.LedgerEntryChanges, error) {
	switch meta.V {
	case 0:
		return nil, nil
	case 1:
		return nil, nil
	case 2:
		return meta.MustV2().TxChangesAfter, nil
	case 3:
		return meta.MustV3().TxChangesAfter, nil
	case 4:
		return meta.MustV4().TxChangesAfter, nil
	default:
		return nil, fmt.Errorf("meta version %d is above the reviewed versions", meta.V)
	}
}
```

**Limits**

The check is matched by how the value is written (`tx.UnsafeMeta`), within one function: a check made by the
caller before it passes the meta on is not seen. An else-if chain (`GetV1`, then `GetV2`, then `V == 0`, else
an error) is not judged. The rule assumes that a current stellar-core emits TransactionMeta v2 to v4 and
LedgerCloseMeta v0 to v2, and treats TransactionMeta v0 and v1 as historical forms: a check that rejects only
them is not reported. That table is an assumption of the rule, not a statement checked against stellar-core. Files of test support code (names
containing `test` or `mock`, integration-test and load-test directories) are skipped.

**Configure and suppress**

Turn the rule off by leaving XDR401 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR401 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR402

**Wide integer narrowed without a range check and stored.**

| | |
| - | - |
| Family | XDR4xx: assumptions about the ledger's form, ranges and outcomes |
| How to fix | keep the full width (uint64, a decimal string or NUMERIC column, big.Int), or compare with the target type's bounds and reject the value before converting |
| Default severity | error (`severity: {XDR402: …}` changes it) |
| Default rule set | yes |
| Guide | [64-bit IDs](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-404 |
| Demonstrating corpus entry | `cap-0027/muxed-source-id-above-2-pow-63` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr4xx/xdr402` |

**What it reports**

A conversion that cannot hold every value of a ledger integer, whose result is stored:

* `uint64` (muxed IDs, offer IDs, time bounds, sequence ages: `xdr.Uint64`, `xdr.TimePoint`, `xdr.Duration`)
  to `int64`, `int`, a 32-bit or smaller type, or `float64`;
* `int64` to `int32` or smaller; `uint32` or `int32` to `int16` or smaller;
* `(*big.Int).Int64()` or `Uint64()` without a dominating `IsInt64()`, `IsUint64()`, `BitLen()` or `Cmp()` on the
  same value (an i128 amount narrowed to 64 bits);
* `strconv.ParseFloat` of a token amount read from an SDK field or method (an i128 rounded to `float64`, a
  warning).

The value must be computed from the ledger: on the way back through arithmetic, conversions, loads and field
reads, a named integer type of the SDK's `xdr` package, an integer field of an SDK struct, or the result of an
SDK function. Stored means written to a struct field, a map, a slice element or an escaping variable, appended,
or passed to a database call or a builder (`With…`, `Set…`, `Add…`), possibly after more arithmetic or a
conversion to text or a nullable wrapper (`null.IntFrom`). A relational comparison (`<`, `<=`, `>`, `>=`) of the
value, or of a value it was computed from, with a constant that dominates the conversion counts as a range check;
a nil or equality check does not. Ledger close times stellar-core writes (`SeqTime`, `CloseTime`) are not
reported, nor is a minimum sequence age (`PreconditionsV2.MinSeqAge`, `TransactionEnvelope.MinSeqAge()`) stored in
a 64-bit type: stellar-core admits a transaction only while that age is at most the ledger's close time
(`txBAD_MIN_SEQ_AGE_OR_GAP`), so no value in a ledger reaches 2^63. `uint32` to `int32` is not reported: ledger sequences and
indexes stay far below 2^31.

**Why it matters**

The ledger's integers are wider than many readers' columns. Muxed IDs reach 2^64−1 on mainnet, SAC balances above
2^63 exist, and a `uint64` written to a signed 64-bit warehouse column made a load reject tens of thousands of rows.
A narrowing conversion does not fail: it stores a negative or rounded number that looks real.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr402/bad.go
// (a) A muxed ID into a signed 64-bit column: an ID ≥ 2^63 is stored
// negative.
func sellerMuxedID(m xdr.MuxedAccountMed25519, row *txRow) {
	row.SellerMuxedID = int64(m.Id)
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr402/good.go
// A range check before the conversion.
func muxedIDChecked(m xdr.MuxedAccountMed25519, row *txRow) bool {
	if uint64(m.Id) > math.MaxInt64 {
		return false
	}
	row.SellerMuxedID = int64(m.Id)
	return true
}
```

**Limits**

A value taken out of an `interface{}` (a details map) is not followed. A result returned to the caller and stored
there is not followed. A range check is any dominating comparison with a constant, not one that proves the bound.
Splitting a big integer into 64-bit halves after `Rsh` or `And` is not reported.

**Configure and suppress**

Turn the rule off by leaving XDR402 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR402 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR403

**Error or ok result discarded on a value that is then stored.**

| | |
| - | - |
| Family | XDR4xx: assumptions about the ledger's form, ranges and outcomes |
| How to fix | check the error (or ok) and fail or skip the row with a logged reason; a zero value stored in its place is indistinguishable from a real one |
| Default severity | warning (`severity: {XDR403: …}` changes it) |
| Default rule set | yes |
| Guide | [Validated versus unvalidated fields](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-108 |
| Demonstrating corpus entry | `cap-0067/address-types-in-sac-events-golden` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr4xx/xdr403` |

**What it reports**

`v, _ := f(…)`, where `f` returns an error as its last result and is a function of the SDK module (`xdr`,
`strkey`, `amount`, `ingest`, `processors`, …), `strconv`, `encoding/hex`, `encoding/base64`, `encoding/json`,
`math/big` or `time` (or is `big.Int.SetString`, with its ok result), and `v` is later stored in the same
function: part of a composite literal, assigned to a field, map entry or slice element, appended, or passed to a
database call or a builder. A variable tested in a condition first (`if v == "" { … }`) counts as checked.

Not reported: `strkey.Encode` of a 32-byte array (an ID; it cannot fail), and a parse of a string field of an SDK
struct (the SDK formatted it).

**Why it matters**

A discarded error leaves the zero value in its place: an empty address, amount 0, a zero ID. Stored, it cannot be
told apart from a real value, and nothing records that the row is wrong.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr403/bad.go
// (b) An amount that did not parse is stored as 0.
func amount(s string, row *transferRow) {
	f, _ := strconv.ParseFloat(s, 64)
	row.Amount = f
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr403/good.go
func destinationChecked(id xdr.Hash) (transferRow, error) {
	to, err := strkey.Encode(strkey.VersionByteContract, id[:])
	if err != nil {
		return transferRow{}, err
	}
	return transferRow{To: to}, nil
}
```

**Limits**

A discarded `ok` of an xdr `Get<Arm>()` accessor is not reported: one wide row per union, with the other arms left
at zero, is a common and deliberate layout (XDR105 covers arm reads that panic). Uses in another function are not
followed.

**Configure and suppress**

Turn the rule off by leaving XDR403 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR403 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR404

**Contract event topics or data trusted by position or kind without a shape or emitter check.**

| | |
| - | - |
| Family | XDR4xx: assumptions about the ledger's form, ranges and outcomes |
| How to fix | check len(topics) and each value's Type (or use Get\<Arm>() and its ok) before reading it, or first compare the event's ContractId with the contract whose event shape you rely on |
| Default severity | error (`severity: {XDR404: …}` changes it) |
| Default rule set | yes |
| Guide | [Contract events](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-306 |
| Demonstrating corpus entry | `cap-0046/event-topic-count-extremes` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr4xx/xdr404` |

**What it reports**

A contract event's topics or data read by position or kind with no shape check and no check of the emitting
contract:

* `topics[k]` with a constant `k`, with no enclosing or earlier check that mentions `len(topics)` (directly, or
  through a variable set under such a check);
* `v.Must<Arm>()` on a topic, the data or a value read from them, with no check of `v.Type` or `v.Get<Arm>()`.

Event values are the `Topics` and `Data` fields of `xdr.ContractEventV0` and what is read from them, and
parameters named `topics` or `data` of type `xdr.ScVal`, `[]xdr.ScVal` or `xdr.ScVec`. A dominating comparison of
the event's `ContractId` with something other than `nil` fixes the shape to that contract's and silences the
report.

**Why it matters**

Any contract can emit any number of topics of any type. A reader that indexes `topics[2]` or calls `MustSym()`
panics on the first event that does not have the shape it expected; a reader that stops on a panic halts the
whole pipeline on an event anyone can emit.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr404/bad.go
// (a) A fixed position read with no length check: a contract that emits one
// topic panics the reader.
func eventName(ev xdr.ContractEvent) string {
	topics := ev.Body.V0.Topics
	sym, ok := topics[1].GetSym()
	if !ok {
		return ""
	}
	return string(sym)
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr404/good.go
// Length and type checked.
func eventNameChecked(ev xdr.ContractEvent) string {
	topics := ev.Body.V0.Topics
	if len(topics) < 2 {
		return ""
	}
	sym, ok := topics[1].GetSym()
	if !ok {
		return ""
	}
	return string(sym)
}
```

**Limits**

The length check is matched by how the slice is written; a check made by the caller is not seen. Transaction-level
events (which only the host emits) are treated like contract events.

**Configure and suppress**

Turn the rule off by leaving XDR404 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR404 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR405

**Rows from diagnostic events without a success gate, or from transaction-level changes in operation scope.**

| | |
| - | - |
| Family | XDR4xx: assumptions about the ledger's form, ranges and outcomes |
| How to fix | build rows from diagnostic events only after LedgerTransaction.Successful(); attribute to an operation only its own changes (GetOperationChanges), never the fee or transaction-level changes |
| Default severity | error (`severity: {XDR405: …}` changes it) |
| Default rule set | yes |
| Guide | [Failed transactions: what still lands in the ledger](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-307 |
| Demonstrating corpus entry | `cap-0046/failed-soroban-tx-with-sac-transfers-in-diagnostics` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr4xx/xdr405` |

**What it reports**

Rows built from meta that does not mean what the row says:

* `LedgerTransaction.GetDiagnosticEvents()`, or a `DiagnosticEvents` field of the SDK's meta and event types,
  feeding rows with no success check (`Successful()`, `TransactionResultCodeTxSuccess`, a variable holding one) in
  the function or in every same-package caller (an error);
* `LedgerTransaction.GetChanges()` or the `TxChangesBefore`/`TxChangesAfter` fields read in a function that works
  on one operation (an integer parameter named like an operation index, or an operation wrapper type) and feeding
  rows (a warning).

Feeding rows means the value, or a value ranged or derived from it, is used in a composite literal, appended,
assigned to a field or map entry, or passed to a same-package function in such a position. Not reported: a
function whose rows record the transaction's success (it, or a same-package function it calls, reads
`Successful()`), and an accessor that copies the events into a `DiagnosticEvents` field.

**Why it matters**

A failed Soroban transaction still carries the diagnostic events of the calls that ran before it failed, some with
`InSuccessfulContractCall` set, but the transaction rolled them back. Rows built from them describe transfers that
never happened. `GetChanges()` holds the fee, sequence-number and transaction-level changes as well as every
operation's, so reading it for one operation attributes changes the operation did not make.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr405/bad.go
// (a) Rows from diagnostic events with no success gate here or in the
// caller: a failed transaction's rolled-back calls become balance changes.
func balanceChanges(tx ingest.LedgerTransaction) ([]balanceChange, error) {
	events, err := tx.GetDiagnosticEvents()
	if err != nil {
		return nil, err
	}
	var out []balanceChange
	for _, ev := range events {
		if !ev.InSuccessfulContractCall {
			continue
		}
		out = append(out, balanceChange{Event: ev.Event})
	}
	return out, nil
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr405/good.go
// The caller gates on success.
func balanceChangesGated(tx ingest.LedgerTransaction) ([]balanceChange, error) {
	events, err := tx.GetDiagnosticEvents()
	if err != nil {
		return nil, err
	}
	var out []balanceChange
	for _, ev := range events {
		out = append(out, balanceChange{Event: ev.Event})
	}
	return out, nil
}
```

**Limits**

Callers are followed within the package, up to four levels. Operation scope is read from parameter names and
types.

**Configure and suppress**

Turn the rule off by leaving XDR405 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR405 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).

### XDR406

**Closed switch over an xdr enum that writes rows, with no default or a panicking default.**

| | |
| - | - |
| Family | XDR4xx: assumptions about the ledger's form, ranges and outcomes |
| How to fix | add a default that records the unknown value (a counter, a typed skip, an error the operator sees) without halting, and handle every value the SDK declares |
| Default severity | warning (`severity: {XDR406: …}` changes it) |
| Default rule set | no: opt-in, add XDR406 to `rules` |
| Guide | [Fail closed at protocol boundaries](https://docs.xdrcheck.dev/hardening/overview.md) |
| Self-audit checklist item | HC-507 |
| Demonstrating corpus entry | `cap-0088/first-ledger-with-signed-ms` (registered in `corpus/plan.json`) |
| Fixtures | `lint/testdata/xdr4xx/xdr406` |

**What it reports**

A `switch` over an enum of the SDK's `xdr` package (`OperationType`, `LedgerEntryType`, `ScValType`, …) whose
cases write rows (append, assign to a field or map entry, build a composite literal, call a builder or database
method) and that has no default, or a default that panics or exits. The message lists the values the SDK declares
that the switch does not handle; when it handles all of them, a value a later protocol adds still falls through.

This rule is opt-in.

**Why it matters**

Protocol upgrades add enum values: operations, entry types, value types, address kinds. A closed switch drops the
new value without a trace, or halts the job on it, on upgrade day. A default that records the unknown value (an
error the operator sees, a counter, a typed skip) turns a silent loss into a decision.

**Example**

Reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr406/bad.go
// (b) A panicking default: a new value stops the job.
func memoRow(m xdr.Memo) row {
	switch m.Type {
	case xdr.MemoTypeMemoNone, xdr.MemoTypeMemoText, xdr.MemoTypeMemoId, xdr.MemoTypeMemoHash, xdr.MemoTypeMemoReturn:
		return row{Kind: m.Type.String()}
	default:
		panic("unknown memo type")
	}
}
```

Not reported:

```go theme={null}
// lint/testdata/xdr4xx/xdr406/good.go
// A default that reports the unknown value without halting.
func memoRowChecked(m xdr.Memo) (row, error) {
	switch m.Type {
	case xdr.MemoTypeMemoNone, xdr.MemoTypeMemoText, xdr.MemoTypeMemoId, xdr.MemoTypeMemoHash, xdr.MemoTypeMemoReturn:
		return row{Kind: m.Type.String()}, nil
	default:
		return row{}, fmt.Errorf("unknown memo type %d", m.Type)
	}
}
```

**Limits**

Many switches handle a subset on purpose (only the entry types a table holds). The rule cannot tell that from an
omission, which is why it is opt-in.

**Configure and suppress**

Turn the rule off by leaving XDR406 out of `rules` in `.xdrlint.yml` or a profile. To accept one report, put `//xdrlint:ignore XDR406 <reason>` on the reported line or on the enclosing function's doc comment (under golangci-lint, `//nolint:xdrlint // <reason>`), or add an entry to an external suppression file for code you cannot edit. A suppression needs a reason, and one that suppresses nothing is itself reported (XDR000). See [Configuring and suppressing](#configuring-and-suppressing).


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