Skip to content

build: fix test.yml, bump go version, install BLS, fix job names - #18

Merged
shumkov merged 3 commits into
dashpay:v0.34-dashfrom
xdustinface:pr-github-fix-tests
Dec 1, 2020
Merged

shumkov merged 3 commits into
dashpay:v0.34-dashfrom
xdustinface:pr-github-fix-tests

Conversation

@xdustinface

Copy link
Copy Markdown
Contributor

tests.yml should now pass with this. However, please take a look into the logs.. last time i checked them there were some errors in there... might be expected errors or so, didn't investigate a lot yet just overflew it. Will link it here as soon as it run through.

@shumkov shumkov changed the title github: Fix test.yml, bump go version, install BLS, fix job names github: fix test.yml, bump go version, install BLS, fix job names Dec 1, 2020
@shumkov shumkov changed the title github: fix test.yml, bump go version, install BLS, fix job names ci: fix test.yml, bump go version, install BLS, fix job names Dec 1, 2020

@shumkov shumkov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@shumkov shumkov changed the title ci: fix test.yml, bump go version, install BLS, fix job names build: fix test.yml, bump go version, install BLS, fix job names Dec 1, 2020
@shumkov
shumkov merged commit 79991a7 into dashpay:v0.34-dash Dec 1, 2020
shumkov added a commit that referenced this pull request Aug 17, 2026
* fix(consensus): prevent remote crash/brick via unknown vote-extension type

An unprivileged peer could send a Commit (or precommit) carrying a
vote-extension whose proto enum Type is undefined. proto3 enums are open, so
gogoproto accepts any varint; VoteExtensionFromProto's default arm then
panicked, terminating the consensus goroutine (which is designed to re-panic).
Because the message is written to the WAL before it is processed, the node
re-read it on restart and crash-looped — a one-packet, network-wide kill of
every validator and full node, not recoverable by restart.

Fix (defense-in-depth):
- VoteExtensionFromProto no longer panics on an unknown type; it returns a
  non-threshold-recoverable extension so construction cannot crash on any path.
- MakeQuorumSigns — the shared chokepoint of VerifyCommit (commits) and
  VerifyExtensionSign (precommit votes) — rejects unknown extension types, so a
  message carrying one fails closed instead of being silently excluded from the
  sign items (which on the precommit path would otherwise still reach the ABCI
  VerifyVoteExtension call).

The rejection is deliberately NOT placed in Commit.ValidateBasic: that runs on
the WAL decode path, where a rejection becomes a DataCorruptionError that aborts
replay and would re-brick already-attacked nodes. On the verification path the
error is swallowed by loggingMiddleware on both live and replay, so poisoned
nodes restart cleanly.

Tests (red→green verified for each):
- types/commit_extension_regression_test.go — construction does not panic;
  VerifyCommit, MakeQuorumSigns and the precommit VerifyExtensionSign reject
  the unknown type. The vote-path test fails if the MakeQuorumSigns check is
  removed, pinning the silent-ignore regression.
- internal/consensus/commit_extension_unbrick_test.go — writes a poison commit
  to a real WAL, confirms it still DECODES (a ValidateBasic rejection would
  abort replay), and that verifying the replayed commit returns an error
  without panicking. This is the restart-recovery (un-brick) property.

Green across types, privval, light, and internal/consensus vote/commit/WAL/
replay tests. Independently validated: crash removed, un-brick preserved, no
false-accept, no legitimate traffic rejected.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(types): return an error for unknown vote-extension types

VoteExtensionFromProto returned a fabricated GenericVoteExtension for a type
outside the defined enum values. proto3 enums are open, so a peer can put any
varint on the wire, and vote extensions feed the sign-hash through
MakeQuorumSigns: substituting a default silently changes the digest, so at best
verification fails with a misleading error and at worst two nodes derive
different canonical votes for the same commit. Nothing on a path feeding a
signature may be fabricated.

The conversion now returns an error, propagated through VoteExtensions.Add,
VoteExtensionsFromProto, NewVoteExtensionsFromABCIExtended and
Commit.GetCanonicalVote, and out through the callers that already return an
error. A poisoned message is rejected by the existing caller instead of
terminating the consensus goroutine.

A poison commit still decodes from the WAL — CommitFromProto keeps extensions in
wire form and Commit.ValidateBasic is unchanged — and is rejected later at
VerifyCommit, so an already-attacked node still restarts. A poison precommit now
dies at MsgFromProto -> VoteFromProto in the reactor; it could never reach the
WAL, because on every prior version that same conversion panicked there.

NewVoteExtensionsFromABCIExtended propagates the error and ExtendVote panics on
it: that input is our own application, not a peer, so an undefined type is a
local bug and must fail loudly, consistent with the panics ExtendVote already
raises on ABCI misbehaviour.

Drops the defensive loop MakeQuorumSigns used to carry: both paths it guarded
funnel through the same VoteExtensionsFromProto call, which now rejects the type
before Filter can silently exclude it.

Out of scope by instruction: peer punishment, Commit.ValidateBasic validation,
WAL write ordering, and recover()/panic-handling middleware.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): bound inbound peer-supplied values

Seven ingress-only bounds on data a remote peer controls. Each rejects with an
error at the point the value enters; none punish, score or evict the peer.

- types: ValidatorSetFromProto rejects a QuorumType outside uint8. It arrives on
  the statesync LightBlock path, is not covered by ValidatorSet.Hash() (which
  hashes only ThresholdPublicKey and QuorumHash), and reaches
  tmmath.MustConvertUint8 in both sign-hash construction and the SignItem zerolog
  marshaller, so merely logging a tampered set kills the node. Mirrors the
  SafeConvertInt32 guard ToProto already applies to the outbound value.
- statesync: validate peer-supplied ConsensusParams before Bootstrap persists
  them. ConsensusParamsFromProto validates nothing and the existing hash check
  covers only Block.MaxBytes, Block.MaxGas and Version.ConsensusVersion.
- p2p/conn: cap the two SecretConnection handshake reads at 128 and 1024 bytes,
  down from 1 MiB each. Both are read before any authentication exists and
  protoio allocates the declared length eagerly.
- consensus: reject a negative Round in VoteSetBitsMessage.ValidateBasic, the
  only message type missing the check. A negative round matches PeerState's
  freshly-initialised sentinel rounds.
- p2p: cap Envelope.Attributes at 8; honest senders set at most two and the map
  is retained for the envelope's whole queue lifetime.
- p2p: cap stored addresses per peer at 32. PEX lets a peer choose how many
  addresses it advertises for its own NodeID, prunePeers bounds only the peer
  count, and every insert rewrites the whole peerInfo to the database. Capped on
  insert only, so stores already holding more still load.
- types: NodeInfo.Validate no longer resolves ListenAddr. It runs on an
  unauthenticated peer's value after conn.Handshake returns, so HandshakeTimeout
  does not cover the lookup. ParseAddressString keeps resolving for the startup
  path; the shared parsing and NodeID validation move to splitAddressString.
  Also fixes ParseAddressString returning (nil, nil) for an empty host, which
  made NewEndpoint nil-deref at boot on listen-address "tcp://:26656", and
  guards an unchecked ips[0].

The QuorumType bound also runs on the state-store read path
(dbStore.Load and LoadValidators), which returns errors rather than panicking.
That trade is deliberate: a node holding an out-of-range value already dies in
MustConvertUint8, so this replaces a later panic with a clean startup error.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): evict least valuable address instead of refusing new ones

The per-peer address bound had no eviction, so once a NodeID reached it every
later address for that peer was silently refused forever — ordinary peer churn
alone was enough to freeze a peer's address set with stale entries.

Reaching the bound now drops the least valuable stored address (oldest successful
dial, then most dial failures, address string breaking ties so eviction does not
depend on map iteration order) and stores the new one, mirroring how prunePeers
handles the peer-count analogue. The address in use is never the candidate, since
Dialed stamps it with the newest LastDialSuccess. The eviction is logged at Debug.

The bound moves from an exported const to PeerManagerOptions.MaxAddressesPerPeer,
matching every other bound on the struct. Unlike its siblings, 0 selects the
default rather than disabling the bound: every constructor outside node setup
leaves it unset, and a security bound must not have a zero-value silent disable.

routerDashDialer.ConnectAsync no longer discards Add's bool: it reported success
for an address that was never stored. Eviction removes the at-capacity case, but
an inactive peer still refuses the insert, so that case is logged at Debug.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): bound envelope attribute bytes and stop shouting about rejections

The attribute cap bounded the entry count but not the retained bytes, so a peer
could still attach eight entries whose keys and values are arbitrarily long. The
summed key+value length is now bounded too, with the cheaper count check first.

Both rejections get a sentinel error wrapped with the offending counts, so callers
and tests can classify them with errors.Is instead of substring matching.

The rejection also logged at Error under a message shared with a genuine decode
failure, letting any peer produce an ERROR line on demand. It now has its own
greppable message at Debug. The proto.Unmarshal branch keeps Error: bytes that do
not parse as protobuf at all can mean a real bug, version skew or corruption.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(privval,protoio): bound privval handshake reads, add a size sentinel

privval/secret_connection.go is a byte-fork of internal/p2p/conn that still read
both unauthenticated handshake messages with a 1 MiB cap, so the bound applied to
the p2p copy never protected the privval listener. It now uses the same caps.

The two files are not de-duplicated here: they diverge in wire type
(privval.AuthSigMessage vs p2p.AuthSigMessage), in signing call (Sign vs
SignDigest) and in failure policy (errors vs panics), so sharing an implementation
is a protocol change rather than a refactor. Tracked in lklimek/tenderdash#26.

protoio exports ErrMsgExceedsMaxSize and wraps it with the offending lengths, so
the handshake test asserts with errors.Is instead of pinning a message string
owned by another package.

The cap comments now state measured body sizes (34 for the ephemeral key, 102 for
an ed25519 AuthSigMessage, 150 for BLS12-381) and say that maxSize bounds the body,
not the framed length.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): validate QuorumType against the supported LLMQ types

The peer-supplied QuorumType was only checked for uint8 representability, which
accepts any of 0-255, while the rest of the codebase validates the same value
against btcjson.LLMQType.Validate() at six call sites. It also ran after the
per-validator loop and threw the converted value away.

The check now uses the allowlist, runs immediately after the nil guard so a
tampered set is rejected before the expensive loop, and keeps the converted value.

ValidateBasic gets the same check next to ThresholdPublicKeyValid and
QuorumHashValid: the light client's HTTP provider builds its set with
NewValidatorSet and never goes through the proto path, so the guard placed only in
ValidatorSetFromProto never fired there.

Two test fixtures built ValidatorSet literals with an unset quorum type and relied
on it passing validation; they now name a real one. Genesis already rejects a zero
quorum type, so no production path supplies it.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): apply the same host rules on both address parsing paths

ParseAddressString and validateAddressString split the same address format but
applied different rules: only validateAddressString checked the host with
ValidateHostname, so a host the peer handshake rejects was still accepted at
startup. ParseAddressString now runs the same check.

splitAddressString's doc claimed it validates each part; it validates the node ID
and port and only rejects an empty host. Its results are named in the signature.

The standalone listen-address rejection and malformed-NodeID tests fold into the
existing TestNodeInfoValidate table, which already carries ListenAddr rows. The
hostname-is-not-resolved test stays standalone: it asserts timing, not rejection.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): drop the unused Timeout.Commit and Timeout.BypassCommitTimeout

ValidateConsensusParams wrote two deprecation warnings straight to stderr, both
guarded by fields outside HashedParams, so a remote statesync witness controlled
whether an unstructured stderr write fired.

Both fields were marked "Unused, TODO: Remove in 0.15" and the proto already
reserves commit and bypass_commit_timeout, so nothing reads or writes them: ToProto
never sets them, ConsensusParamsFromProto never reads them, and the two warnings
were their only consumers. Removed along with the warnings, at v1.6.

Genesis files still carrying the keys keep parsing: consensus params are decoded
with encoding/json, which ignores unknown fields.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs: record the deferred and accepted statesync and node-info risks

Two statesync gaps are deferred rather than fixed here: extending HashedParams to
cover the remaining consensus params is consensus-breaking (lklimek/tenderdash#24),
and mirroring the P2P provider's validation into the RPC provider is tracked
separately (lklimek/tenderdash#25).

Two accepted risks are recorded where they apply: the stricter ListenAddr hostname
check and the removal of DNS resolution from our own startup config validation both
carry no regression risk in deployments that only ever use IP literals.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): return an error for unknown vote-extension types (#18)

* fix(types): return an error for unknown vote-extension types

VoteExtensionFromProto returned a fabricated GenericVoteExtension for a type
outside the defined enum values. proto3 enums are open, so a peer can put any
varint on the wire, and vote extensions feed the sign-hash through
MakeQuorumSigns: substituting a default silently changes the digest, so at best
verification fails with a misleading error and at worst two nodes derive
different canonical votes for the same commit. Nothing on a path feeding a
signature may be fabricated.

The conversion now returns an error, propagated through VoteExtensions.Add,
VoteExtensionsFromProto, NewVoteExtensionsFromABCIExtended and
Commit.GetCanonicalVote, and out through the callers that already return an
error. A poisoned message is rejected by the existing caller instead of
terminating the consensus goroutine.

A poison commit still decodes from the WAL — CommitFromProto keeps extensions in
wire form and Commit.ValidateBasic is unchanged — and is rejected later at
VerifyCommit, so an already-attacked node still restarts. A poison precommit now
dies at MsgFromProto -> VoteFromProto in the reactor; it could never reach the
WAL, because on every prior version that same conversion panicked there.

NewVoteExtensionsFromABCIExtended propagates the error and ExtendVote panics on
it: that input is our own application, not a peer, so an undefined type is a
local bug and must fail loudly, consistent with the panics ExtendVote already
raises on ABCI misbehaviour.

Drops the defensive loop MakeQuorumSigns used to carry: both paths it guarded
funnel through the same VoteExtensionsFromProto call, which now rejects the type
before Filter can silently exclude it.

Out of scope by instruction: peer punishment, Commit.ValidateBasic validation,
WAL write ordering, and recover()/panic-handling middleware.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs: remove commit-extension-panic exploit spec

The spec documented an unpatched vulnerability (exact packet size,
ungated reactor branch, exploit cost) under docs/, a VuePress-built
site with no exclude rule for this path — publishable before the fix
ships, contradicting the doc's own §8 guidance not to push it early.

Flagged HIGH by security review; removing rather than gating, since
no exclude mechanism exists in the current VuePress config.

* fix(types): add a sentinel error and reject nil vote extensions

VoteExtensionsFromProto dereferenced every slice element without a nil check,
contradicting the fail-closed contract VoteExtensionFromProto documents: the
conversion is reachable from untrusted network input and must neither panic nor
fabricate a value. A nil element now yields an error naming its index.

The unknown-type rejection gains an exported sentinel, ErrUnknownVoteExtensionType,
so callers can match it with errors.Is. A future peer-punishment change needs to
distinguish "this peer sent an undefined enum value" from any other conversion
failure, which a bare fmt.Errorf cannot express. The message text is unchanged.

Add, VoteExtensionsFromProto and NewVoteExtensionsFromABCIExtended became fallible
without their godoc saying so; each now documents its error contract. Callers of
VoteExtensions.Add are the one signature change the compiler cannot enforce - a
stale .Add(ve) call still compiles and silently swallows the rejection - so the
error is now part of the documented API surface.

Tests assert the specific sentinel via errors.Is rather than "some error".
VerifyCommit's case previously passed even with the rejection fully removed,
because its fake zero signature failed verification first; it now builds a commit
that genuinely verifies, asserts that positive control, and only then flips one
extension type to an undefined value. Restores direct coverage of
Vote.VerifyExtensionSign, which the peer-path test does not exercise: its vote is
built as a struct literal, reaching a path no converter can guard.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test: share one vote-extension helper and drop review IDs from comments

Making VoteExtensionsFromProto fallible spread the same three-line convert-and-
require dance across two packages and a dozen call sites, as two near-identical
private helpers whose signatures had already diverged (testing.TB vs *testing.T).
Export MustVoteExtensionsFromProto from types/test_util.go instead, following the
existing convention of a non-test file importing testing (internal/state/test/
factory), and use it everywhere a *testing.T is in scope.

The two production helpers that convert extensions, types.makeCommit and the
state test factory, keep returning an error: they have no t to fail.

Also drops ephemeral review-finding IDs from test comments in the two files this
change touches. Those IDs are reassigned on every review run and go dead after
merge, so each is replaced by the invariant it stood for.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(kvstore): return errors from the sign-item helpers

makeVoteExtensionSignItems panicked on the newly fail-closed conversion of
peer-forwarded wire data, and makeBlockSignItem panicked on its own marshalling
failures. STYLE_GUIDE.md reserves panic for a broken internal invariant; neither
qualifies, since both derive from a FinalizeBlock request. Both now return an
error, propagated by FinalizeBlock the same way as its other failure paths.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test: cover the light-client and ExtendVote extension-type paths

The unknown-type rejection has four propagation destinations; the light client
and the ABCI-facing ExtendVote had no test. verifyBlockSignatureWithDashCore
builds a canonical vote from a provider-supplied commit, so a malicious provider
could otherwise panic the light client; its Dash Core client is left nil in the
test because the rejection must happen before any RPC round-trip.

ExtendVote's panic is asserted rather than removed. That response comes from our
own application, so a type outside the enum is a local app/tenderdash mismatch,
not a network fault, and failing loudly is the intended behaviour there. The test
pins that contract so it cannot be softened by accident.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs: correct two comments on the vote-extension paths

MakeQuorumSigns claimed a causal dependency that does not hold for the traced
input; the real reason to convert first is that MakeBlockSignItem panics rather
than returning an error, so fallible work belongs ahead of it.

Marks the ExtendVote panic as a reviewed, deliberate choice: ABCI hardening is
out of scope here, and panicking on an ABCI-supplied undefined type is the
intended strongest signal, not an oversight to be fixed later.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>

* fix(p2p): only evict peer addresses that failed their last dial

A PEX-advertised URL carries a sender-chosen NodeID, so a peer can insert
addresses under another node's identity. For an address learned but not yet
dialed, LastDialSuccess and DialFailures tie with freshly injected junk, and
eviction fell through to the lowest address string, which the sender controls:
it could make its entries sort above a chosen victim and remove that victim
deterministically. Against a bootstrapping node that is a partial eclipse
primitive, not a memory bound.

leastValuableAddress becomes evictableAddresses, which returns only addresses
that failed their last dial, least valuable first. An unproven newcomer can no
longer displace an unproven incumbent: with none evictable the new address is
refused, and refusing is not a permanent freeze, since unreachable addresses
accumulate dial failures and become replaceable. DialFailures resets on a
successful dial, so one failure already means the address did not work on the
most recent attempt; a higher threshold would buy nothing here and would freeze
the set outright when MinRetryTime is 0, where retryDelay returns retryNever and
the count can never grow.

The eviction decision is now made before any address is dropped, so a refusal
leaves the peer's address map untouched.

The cap test asserted that an over-cap address is always stored, which is the
behaviour this commit removes; it now asserts a refusal while every stored
address is still viable. The oldest-dial-success test needs its unproven
incumbents to have failed a dial before eviction can consider them at all.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): prune the address index when an address is evicted

peerStore.index only ever grew: Set added every address in peer.AddressInfo and
removed none, and Delete could not help either, since by the time it runs the
evicted addresses are already gone from AddressInfo. A peer picks the NodeID it
advertises over PEX, so each eviction leaked an unreachable index entry at the
sender's request, per process and never reclaimed. The per-peer address cap was
therefore not the memory bound it claimed to be.

Set now drops from the index every address the stored entry carried and the
incoming one does not, guarded on the index still pointing at this peer so an
address re-pointed to another peer survives. Doing it in Set rather than at the
eviction call site keeps the invariant inside peerStore and covers any later
removal path.

peerInfo.Copy is a prerequisite, not a cleanup: it copied the struct and then
rewrote the values of the same map, so a "copy" shared its address map with the
store. Set would have diffed that map against itself and found nothing, and Add's
delete reached into the store before Set ran. It now allocates its own map, as
its name and doc always claimed. Every structural mutation of a fetched map is in
Add, and every field mutation is in Dialed, DialFailed and UpdatePeerInfo, all of
which persist through Set.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(types): name every path the hostname check gates

The accepted-risk note reasoned only about NodeInfo.Validate's ListenAddr, but
the same change added ValidateHostname to the exported ParseAddressString, which
also gates NewEndpoint (node/setup.go, the operator's listen address) and
ValidatorAddress.NetAddress. The note now states the accepted risk for each.

NetAddress gains no strictness: it has no production caller, and its input has
already passed ValidateHostname in ValidatorAddress.Validate. That is checkable
here, unlike the shape of the app-supplied masternode list, which this repo
cannot confirm, so the note no longer rests on it.

ParseAddressString's doc says the host must pass ValidateHostname before it is
resolved, which its tests already assert.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): validate the genesis quorum type against the LLMQ allowlist

Genesis is the third entry point for a quorum type, and it only checked for zero
while ValidatorSet.ValidateBasic and ValidatorSetFromProto check the allowlist.
A genesis naming validator_quorum_type 200 passed ValidateAndComplete and failed
later in the block replayer, reporting a validator set rather than the field the
operator mistyped.

Both zero-checks are replaced by one btcjson.LLMQType.Validate() call, which
subsumes them; the second was unreachable with a different message anyway, as
nothing between the two touches the field. This is what the TODO sitting on the
first check asked for.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): harden per-peer address eviction against sender steering

Three related weaknesses in the MaxAddressesPerPeer eviction path:

Eviction eligibility now derives from the dial timestamps
(peerAddressInfo.failedLastDial) instead of DialFailures. Accepted zeroes
DialFailures on every inbound connection for scoring and retry backoff, so a
peer that reconnects periodically - the normal case in a validator mesh - kept
re-marking its junk addresses as viable and permanently disabled eviction of
them. An inbound connection proves the peer is up, not that any stored address
is dialable, so it no longer touches eviction eligibility.

Ties between eviction candidates are broken pseudo-randomly (shuffle before a
stable sort) instead of by the address string. The address string is chosen by
the advertising peer, so a deterministic order over it handed the sender its
choice of victim whenever candidates tied on dial history.

New AddTrusted stores an operator- or executor-supplied address (bootstrap and
persistent-peer config, the Dash quorum-connection dialer) even when every
stored address is viable, evicting the least valuable one; failed addresses go
first. Add keeps refusing a peer-learned newcomer in that state. Previously
both paths shared Add, so unproven PEX-learned incumbents could block a
validator's real address from ever being stored. Node setup now also reports
when a configured peer address was not re-added instead of discarding the
result.

The most-dial-failures eviction test now has two evictable candidates with
different failure counts; with a single candidate it never exercised the
comparison it claims to test (verified by mutating the comparator).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(privval): validate the quorum type on both remote-signer transports

SignVote and SignProposal on the gRPC signer server and in the socket
transport's DefaultValidationRequestHandler converted the request's bare int32
quorum type to btcjson.LLMQType unchecked. Sign-hash construction narrows the
type to uint8 with a panicking conversion, so a request carrying an
out-of-range type crashed the signer; an in-range but unknown type produced a
sign hash for a quorum type that does not exist. Both transports now check the
type against the LLMQ allowlist before the privVal is touched, matching the
guards on the proto-decode, validator-set, and genesis entry points.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(config): drop the unsafe commit-timeout override knobs

The Timeout.Commit and Timeout.BypassCommitTimeout consensus parameters are
gone, but the config surface still offered unsafe-commit-timeout-override and
unsafe-bypass-commit-timeout-override: struct fields, validation, TOML
template lines, and documentation for values nothing reads. All removed. The
config template test now guards against offering overrides for parameters
that no longer exist. Existing config files carrying the keys keep loading,
since unknown TOML keys are ignored during unmarshalling.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(types): count every hostname-check call site accurately

The listen-address strictness note claimed ValidateHostname gates three
paths; it has four non-test call sites. The note now scopes its claim to the
three paths whose strictness the shared check changed and names the fourth,
NodeAddress.Validate, which runs the same check on its own and gains nothing
from the sharing.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Revert "fix(config): drop the unsafe commit-timeout override knobs"

This reverts commit 9b3da4faa87c6e9b8b9f4d608e6c2dc84869e6e2.

* Revert "fix(types): drop the unused Timeout.Commit and Timeout.BypassCommitTimeout"

This reverts commit 5c07b3440a1be7686c4bc31529117c4cf3577978.

* Revert "fix(p2p): harden per-peer address eviction against sender steering"

This reverts commit d935795ef250eaf408b3da082e534f187cdc6ed8.

* Revert "fix(p2p): prune the address index when an address is evicted"

This reverts commit ffb6c6680d5f4587910252ed5cc8b7296792dc70.

* Revert "fix(p2p): only evict peer addresses that failed their last dial"

This reverts commit 8caadb105f2b2a1c61a8da68a272d8e9ef2db95f.

* Revert "fix(p2p): evict least valuable address instead of refusing new ones"

This reverts commit 91f2dc6af0807552c68ddd053d758181529bef2d.

* fix(types): let ValidateBasic be the only quorum-type gate on the proto path

An empty validator set serializes to an empty proto message whose QuorumType is
0, so the early allowlist check in ValidatorSetFromProto rejected a zero-validator
genesis before the empty-set determination could report
ErrValidatorSetNilOrEmpty, and the node refused to reload its own state. The
terminal ValidateBasic already validates the quorum type, and short-circuits on
empty sets first, so the early check only cost a second error string.

State.FromProto now compares that sentinel with errors.Is so the initial-height
tolerance survives future wrapping.

* fix(privval): validate a whole signing request before it reaches the signer

Both remote-signer transports checked the quorum type and nothing else, so a
request without a vote or proposal was dereferenced and a quorum hash of the
wrong size panicked SignItem.UpdateSignHash — either one stops the validator
from signing at all. ValidateQuorumParams now carries the quorum checks and
their rationale once for all four handlers, replacing the inverted error
branches on the socket transport with guard clauses.

* refactor(statesync): give the consensus-params checks a name and a test

verifyConsensusParams holds the validation and the hash comparison of the P2P
path in the order they must run, so both are covered by a unit test instead of
requiring a full light-client fixture. Its comment states what the params hash
does not cover and what the bound does not reject, and the RPC provider says
plainly that it verifies nothing.

* docs(p2p,types): state the hostname and address-cap decisions once, in place

NodeInfo.Validate carries the whole hostname-strictness rationale, covering the
node and seed constructors that reach it, so node/setup.go no longer explains
code that is gone. PeerManager.Add says what its cap does not do, the two
secret-connection read-cap comments read identically again, and the divergence
note names the sibling file instead of a fork issue.

NewEndpoint failures now name the config key that produced them, and the
envelope attribute counter no longer shadows the bytes package.

* fix(p2p): drop the per-peer address cap, correct the statesync note

The cap bounded peerInfo.AddressInfo at 32 entries per NodeID and refused
anything further, with no eviction. PEX takes the NodeID from the sender's
URL without relating it to the sender's identity, and stored addresses are
only syntax-validated, so one PEX response could fill all 32 slots of a
chosen victim NodeID with junk hostnames. Nothing evicts an individual
address, the map is persisted so the state survives restart, and Advertise
re-gossips it, so the victim's real address was refused indefinitely. The
Dash quorum dialer compounds it by discarding the Add result and then
pinning the entry with PeerScorePersistent. The same lockout occurs with no
attacker at all, from ordinary address churn, because stored addresses
never expire.

Removing the cap restores unbounded address growth, which is the existing
behaviour on v1.6-dev and a resource concern rather than a targeted one:
the victim's real address stays dialable. Bounding the store is still
worth doing, but it has to bound per sending peer rather than per
advertised NodeID, which is a design change rather than a hotfix.

Also corrects the note at the RPC state provider. It claimed that path
performs no validation and no ConsensusHash comparison, and that the
provider is unused in production. Both are wrong: the equivalent checks
run one layer down in lightrpc.Client.ConsensusParams, and use-p2p
defaults to false, so this is the provider in use unless it is set.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Ivan Shumkov <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
shumkov added a commit that referenced this pull request Aug 17, 2026
…ic (#32)

* fix(types): reject unknown vote-extension types in Commit.ValidateBasic

Every other field of a Commit is either checked by ValidateBasic or covered by the
threshold signature. The vote-extension type is neither, and proto3 enums are open,
so an undefined varint decodes into the generated enum field unchallenged and rides
through every boundary a Commit crosses.

Add the type check. Type only: an extension's contents are threshold-signed, so
they are not ValidateBasic's to police, and the content rules in
VoteExtensions.Validate() were written for a vote, where they are not signed.

ValidVoteExtensionType is placed next to VoteExtensionFromProto so the set of
dispatchable types has one home. A type accepted by one and missing from the other
would be admitted into a struct nothing can convert.

This inverts a property PR #18 deliberately pinned -- that a poison commit must
still decode from the WAL, because a rejection during WAL decode raises
DataCorruptionError and aborts catchupReplay. The inversion is safe because the
rejection moved upstream rather than merely being added: MsgFromProto calls
ValidateBasic at the p2p boundary, so a poison commit is now rejected as it arrives
and walMiddleware never has anything to write. A WAL from an older build could
still hold one, and that case is recoverable via repairWalFile. The block store,
which panics through mustDecodeCommit and has no repair path, is made safe by
verifying the commit at statesync backfill ingress -- this change's predicate, not
an assumption.

commit_extension_unbrick_test.go is rewritten rather than deleted, and states which
property it now pins and why. Two tests in commit_extension_regression_test.go
built their poison through CommitFromProto, which now rejects it; they build the
struct directly instead, because their subject is defence in depth -- what
GetCanonicalVote and VerifyCommit do on the consensus goroutine if a poison commit
arrives by a route that skips ValidateBasic.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(types): one authority for vote-extension type membership

The enum-membership question was answered in two hand-written switches that had to
be kept in step by hand, and Commit.ValidateBasic's rejections were anonymous
strings that three tests pinned by substring.

Membership now has one derivation per layer. tmproto.VoteExtensionType.IsValid
reads the generated name table, so it answers for whatever the .proto defines with
no hand-maintained case list, and (*VoteExtension).Validate uses it - the obvious
place to look for vote-extension validation now checks the type it validates.
VoteExtensionFromProto's dispatch switch is the only remaining case list, and
Commit.ValidateBasic calls it instead of mirroring it, which removes
ValidVoteExtensionType entirely. A table-driven test walks
VoteExtensionType_name and fails if a defined type has no dispatch arm.

Both rejections wrap sentinels: ErrUnknownVoteExtensionType, now owned by the proto
package and aliased in types so a rejection from either side matches one errors.Is
check, and ErrNilVoteExtension, shared with VoteExtensionsFromProto. The tests
assert with ErrorIs and EqualError rather than substrings.

The comment above the check claimed every other Commit field is checked or covered
by the threshold signature. Commit.Hash is a checksum of ThresholdBlockSignature
alone, so nothing binds the extension list's order, count or duplication; the
comment now says only what is true, and a TODO points at the tracking issue.
An INTENTIONAL note records the accepted rollback hazard of an ungated rejection.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(types): record the accepted risks around commit extension validation

Two hazards the type check does not close, both accepted rather than fixed:
a block store poisoned before the statesync backfill gate shipped still panics
on load with no repair path, and scripts/scmigrate gates on the returned commit
instead of the error, so it can re-persist such a commit.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(types): make the conversion dispatch the sole vote-extension type gate

Drop the redundant IsValid guard from tmproto.VoteExtension.Validate: every
wire-input path reaches extensions through types.VoteExtensionFromProto's
dispatch switch before Validate can run, so the switch is the one enforcement
gate. IsValid stays as a query helper that reads the generated name table; the
cross-check test pins that the dispatch covers every .proto-defined type. The
ErrUnknownVoteExtensionType sentinel moves back to types/ as the sole
definition now that the proto package no longer returns it.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs: align security markers, godocs, and operator docs with shipped behavior

- scmigrate INTENTIONAL marker: the accepted-risk rationale claimed the path
  is not part of the running node's write path; it is wired to the shipped
  'tenderdash key-migrate' subcommand. State the true rationale: the store
  already holds the record, so re-persisting adds no new exposure.
- pre-upgrade-poisoned-store marker: name all three panic surfaces
  (mustDecodeCommit, LoadSeenCommit, LoadBlock), not just mustDecodeCommit.
- mustDecodeCommit panic message: the failure is a proto->commit decode, not
  'converting commit to proto'.
- CommitFromProto godoc: a validation error does not imply a nil result;
  callers must branch on the error, never the value.
- Commit.ValidateBasic godoc: document the ErrNilVoteExtension and
  ErrUnknownVoteExtensionType sentinels callers already depend on.
- Drop private-fork issue references from comments; state the constraints
  self-containedly instead.
- UPGRADING.md: document the three operator-visible consequences of rejecting
  undefined vote-extension types (p2p rejection, startup panic on an already
  poisoned store with no repair path, rollback hazard once a future release
  adds a new extension type).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(consensus): recover in gossip handlers, return the canonicalization error

Tightening Commit.ValidateBasic makes an already-stored commit with an
unknown extension type unreadable. The accepted risk was recorded as a
startup panic, but startup reads only the last-height seen commit and the
replay range. A commit written by statesync backfill sits below those, so
the node starts normally and the record is reached later, by a gossip
handler loading the height a peer advertised. That handler ran in a bare
goroutine while every other peer-facing path in the node recovers, so one
unreadable historical record let any peer terminate the process by naming
its height, repeatedly. Gossip handlers now recover and log, matching the
consensus reactor, the statesync reactor and the p2p client.

GenericVoteExtension.SignItem returned an error for its first fallible
call and panicked for the other two, one of which is
CanonicalizeVoteExtension. That function keeps its own list of the types
it can canonicalize, separate from the conversion dispatch this PR makes
authoritative, so a type added to the .proto with a dispatch arm but no
canonical form would pass the new gate and then panic on the consensus
goroutine. It now returns the error, which its only caller already
handles.

Drops VoteExtensionType.IsValid: it had no production caller, and both
tests using it asserted a tautology, since IsValid is the same map lookup
they iterated. The dispatch coverage test keeps its value without it.

Corrects UPGRADING.md, which promised a startup panic for the exact
population that does not get one, and adds the WAL case, where repair
rewrites only the most recent segment.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Lukasz Klimek <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: Ivan Shumkov <[email protected]>
shumkov added a commit that referenced this pull request Aug 17, 2026
* fix(consensus): prevent remote crash/brick via unknown vote-extension type

An unprivileged peer could send a Commit (or precommit) carrying a
vote-extension whose proto enum Type is undefined. proto3 enums are open, so
gogoproto accepts any varint; VoteExtensionFromProto's default arm then
panicked, terminating the consensus goroutine (which is designed to re-panic).
Because the message is written to the WAL before it is processed, the node
re-read it on restart and crash-looped — a one-packet, network-wide kill of
every validator and full node, not recoverable by restart.

Fix (defense-in-depth):
- VoteExtensionFromProto no longer panics on an unknown type; it returns a
  non-threshold-recoverable extension so construction cannot crash on any path.
- MakeQuorumSigns — the shared chokepoint of VerifyCommit (commits) and
  VerifyExtensionSign (precommit votes) — rejects unknown extension types, so a
  message carrying one fails closed instead of being silently excluded from the
  sign items (which on the precommit path would otherwise still reach the ABCI
  VerifyVoteExtension call).

The rejection is deliberately NOT placed in Commit.ValidateBasic: that runs on
the WAL decode path, where a rejection becomes a DataCorruptionError that aborts
replay and would re-brick already-attacked nodes. On the verification path the
error is swallowed by loggingMiddleware on both live and replay, so poisoned
nodes restart cleanly.

Tests (red→green verified for each):
- types/commit_extension_regression_test.go — construction does not panic;
  VerifyCommit, MakeQuorumSigns and the precommit VerifyExtensionSign reject
  the unknown type. The vote-path test fails if the MakeQuorumSigns check is
  removed, pinning the silent-ignore regression.
- internal/consensus/commit_extension_unbrick_test.go — writes a poison commit
  to a real WAL, confirms it still DECODES (a ValidateBasic rejection would
  abort replay), and that verifying the replayed commit returns an error
  without panicking. This is the restart-recovery (un-brick) property.

Green across types, privval, light, and internal/consensus vote/commit/WAL/
replay tests. Independently validated: crash removed, un-brick preserved, no
false-accept, no legitimate traffic rejected.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(types): return an error for unknown vote-extension types

VoteExtensionFromProto returned a fabricated GenericVoteExtension for a type
outside the defined enum values. proto3 enums are open, so a peer can put any
varint on the wire, and vote extensions feed the sign-hash through
MakeQuorumSigns: substituting a default silently changes the digest, so at best
verification fails with a misleading error and at worst two nodes derive
different canonical votes for the same commit. Nothing on a path feeding a
signature may be fabricated.

The conversion now returns an error, propagated through VoteExtensions.Add,
VoteExtensionsFromProto, NewVoteExtensionsFromABCIExtended and
Commit.GetCanonicalVote, and out through the callers that already return an
error. A poisoned message is rejected by the existing caller instead of
terminating the consensus goroutine.

A poison commit still decodes from the WAL — CommitFromProto keeps extensions in
wire form and Commit.ValidateBasic is unchanged — and is rejected later at
VerifyCommit, so an already-attacked node still restarts. A poison precommit now
dies at MsgFromProto -> VoteFromProto in the reactor; it could never reach the
WAL, because on every prior version that same conversion panicked there.

NewVoteExtensionsFromABCIExtended propagates the error and ExtendVote panics on
it: that input is our own application, not a peer, so an undefined type is a
local bug and must fail loudly, consistent with the panics ExtendVote already
raises on ABCI misbehaviour.

Drops the defensive loop MakeQuorumSigns used to carry: both paths it guarded
funnel through the same VoteExtensionsFromProto call, which now rejects the type
before Filter can silently exclude it.

Out of scope by instruction: peer punishment, Commit.ValidateBasic validation,
WAL write ordering, and recover()/panic-handling middleware.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): bound inbound peer-supplied values

Seven ingress-only bounds on data a remote peer controls. Each rejects with an
error at the point the value enters; none punish, score or evict the peer.

- types: ValidatorSetFromProto rejects a QuorumType outside uint8. It arrives on
  the statesync LightBlock path, is not covered by ValidatorSet.Hash() (which
  hashes only ThresholdPublicKey and QuorumHash), and reaches
  tmmath.MustConvertUint8 in both sign-hash construction and the SignItem zerolog
  marshaller, so merely logging a tampered set kills the node. Mirrors the
  SafeConvertInt32 guard ToProto already applies to the outbound value.
- statesync: validate peer-supplied ConsensusParams before Bootstrap persists
  them. ConsensusParamsFromProto validates nothing and the existing hash check
  covers only Block.MaxBytes, Block.MaxGas and Version.ConsensusVersion.
- p2p/conn: cap the two SecretConnection handshake reads at 128 and 1024 bytes,
  down from 1 MiB each. Both are read before any authentication exists and
  protoio allocates the declared length eagerly.
- consensus: reject a negative Round in VoteSetBitsMessage.ValidateBasic, the
  only message type missing the check. A negative round matches PeerState's
  freshly-initialised sentinel rounds.
- p2p: cap Envelope.Attributes at 8; honest senders set at most two and the map
  is retained for the envelope's whole queue lifetime.
- p2p: cap stored addresses per peer at 32. PEX lets a peer choose how many
  addresses it advertises for its own NodeID, prunePeers bounds only the peer
  count, and every insert rewrites the whole peerInfo to the database. Capped on
  insert only, so stores already holding more still load.
- types: NodeInfo.Validate no longer resolves ListenAddr. It runs on an
  unauthenticated peer's value after conn.Handshake returns, so HandshakeTimeout
  does not cover the lookup. ParseAddressString keeps resolving for the startup
  path; the shared parsing and NodeID validation move to splitAddressString.
  Also fixes ParseAddressString returning (nil, nil) for an empty host, which
  made NewEndpoint nil-deref at boot on listen-address "tcp://:26656", and
  guards an unchecked ips[0].

The QuorumType bound also runs on the state-store read path
(dbStore.Load and LoadValidators), which returns errors rather than panicking.
That trade is deliberate: a node holding an out-of-range value already dies in
MustConvertUint8, so this replaces a later panic with a clean startup error.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): evict least valuable address instead of refusing new ones

The per-peer address bound had no eviction, so once a NodeID reached it every
later address for that peer was silently refused forever — ordinary peer churn
alone was enough to freeze a peer's address set with stale entries.

Reaching the bound now drops the least valuable stored address (oldest successful
dial, then most dial failures, address string breaking ties so eviction does not
depend on map iteration order) and stores the new one, mirroring how prunePeers
handles the peer-count analogue. The address in use is never the candidate, since
Dialed stamps it with the newest LastDialSuccess. The eviction is logged at Debug.

The bound moves from an exported const to PeerManagerOptions.MaxAddressesPerPeer,
matching every other bound on the struct. Unlike its siblings, 0 selects the
default rather than disabling the bound: every constructor outside node setup
leaves it unset, and a security bound must not have a zero-value silent disable.

routerDashDialer.ConnectAsync no longer discards Add's bool: it reported success
for an address that was never stored. Eviction removes the at-capacity case, but
an inactive peer still refuses the insert, so that case is logged at Debug.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): bound envelope attribute bytes and stop shouting about rejections

The attribute cap bounded the entry count but not the retained bytes, so a peer
could still attach eight entries whose keys and values are arbitrarily long. The
summed key+value length is now bounded too, with the cheaper count check first.

Both rejections get a sentinel error wrapped with the offending counts, so callers
and tests can classify them with errors.Is instead of substring matching.

The rejection also logged at Error under a message shared with a genuine decode
failure, letting any peer produce an ERROR line on demand. It now has its own
greppable message at Debug. The proto.Unmarshal branch keeps Error: bytes that do
not parse as protobuf at all can mean a real bug, version skew or corruption.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(privval,protoio): bound privval handshake reads, add a size sentinel

privval/secret_connection.go is a byte-fork of internal/p2p/conn that still read
both unauthenticated handshake messages with a 1 MiB cap, so the bound applied to
the p2p copy never protected the privval listener. It now uses the same caps.

The two files are not de-duplicated here: they diverge in wire type
(privval.AuthSigMessage vs p2p.AuthSigMessage), in signing call (Sign vs
SignDigest) and in failure policy (errors vs panics), so sharing an implementation
is a protocol change rather than a refactor. Tracked in lklimek/tenderdash#26.

protoio exports ErrMsgExceedsMaxSize and wraps it with the offending lengths, so
the handshake test asserts with errors.Is instead of pinning a message string
owned by another package.

The cap comments now state measured body sizes (34 for the ephemeral key, 102 for
an ed25519 AuthSigMessage, 150 for BLS12-381) and say that maxSize bounds the body,
not the framed length.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): validate QuorumType against the supported LLMQ types

The peer-supplied QuorumType was only checked for uint8 representability, which
accepts any of 0-255, while the rest of the codebase validates the same value
against btcjson.LLMQType.Validate() at six call sites. It also ran after the
per-validator loop and threw the converted value away.

The check now uses the allowlist, runs immediately after the nil guard so a
tampered set is rejected before the expensive loop, and keeps the converted value.

ValidateBasic gets the same check next to ThresholdPublicKeyValid and
QuorumHashValid: the light client's HTTP provider builds its set with
NewValidatorSet and never goes through the proto path, so the guard placed only in
ValidatorSetFromProto never fired there.

Two test fixtures built ValidatorSet literals with an unset quorum type and relied
on it passing validation; they now name a real one. Genesis already rejects a zero
quorum type, so no production path supplies it.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): apply the same host rules on both address parsing paths

ParseAddressString and validateAddressString split the same address format but
applied different rules: only validateAddressString checked the host with
ValidateHostname, so a host the peer handshake rejects was still accepted at
startup. ParseAddressString now runs the same check.

splitAddressString's doc claimed it validates each part; it validates the node ID
and port and only rejects an empty host. Its results are named in the signature.

The standalone listen-address rejection and malformed-NodeID tests fold into the
existing TestNodeInfoValidate table, which already carries ListenAddr rows. The
hostname-is-not-resolved test stays standalone: it asserts timing, not rejection.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): drop the unused Timeout.Commit and Timeout.BypassCommitTimeout

ValidateConsensusParams wrote two deprecation warnings straight to stderr, both
guarded by fields outside HashedParams, so a remote statesync witness controlled
whether an unstructured stderr write fired.

Both fields were marked "Unused, TODO: Remove in 0.15" and the proto already
reserves commit and bypass_commit_timeout, so nothing reads or writes them: ToProto
never sets them, ConsensusParamsFromProto never reads them, and the two warnings
were their only consumers. Removed along with the warnings, at v1.6.

Genesis files still carrying the keys keep parsing: consensus params are decoded
with encoding/json, which ignores unknown fields.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs: record the deferred and accepted statesync and node-info risks

Two statesync gaps are deferred rather than fixed here: extending HashedParams to
cover the remaining consensus params is consensus-breaking (lklimek/tenderdash#24),
and mirroring the P2P provider's validation into the RPC provider is tracked
separately (lklimek/tenderdash#25).

Two accepted risks are recorded where they apply: the stricter ListenAddr hostname
check and the removal of DNS resolution from our own startup config validation both
carry no regression risk in deployments that only ever use IP literals.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): return an error for unknown vote-extension types (#18)

* fix(types): return an error for unknown vote-extension types

VoteExtensionFromProto returned a fabricated GenericVoteExtension for a type
outside the defined enum values. proto3 enums are open, so a peer can put any
varint on the wire, and vote extensions feed the sign-hash through
MakeQuorumSigns: substituting a default silently changes the digest, so at best
verification fails with a misleading error and at worst two nodes derive
different canonical votes for the same commit. Nothing on a path feeding a
signature may be fabricated.

The conversion now returns an error, propagated through VoteExtensions.Add,
VoteExtensionsFromProto, NewVoteExtensionsFromABCIExtended and
Commit.GetCanonicalVote, and out through the callers that already return an
error. A poisoned message is rejected by the existing caller instead of
terminating the consensus goroutine.

A poison commit still decodes from the WAL — CommitFromProto keeps extensions in
wire form and Commit.ValidateBasic is unchanged — and is rejected later at
VerifyCommit, so an already-attacked node still restarts. A poison precommit now
dies at MsgFromProto -> VoteFromProto in the reactor; it could never reach the
WAL, because on every prior version that same conversion panicked there.

NewVoteExtensionsFromABCIExtended propagates the error and ExtendVote panics on
it: that input is our own application, not a peer, so an undefined type is a
local bug and must fail loudly, consistent with the panics ExtendVote already
raises on ABCI misbehaviour.

Drops the defensive loop MakeQuorumSigns used to carry: both paths it guarded
funnel through the same VoteExtensionsFromProto call, which now rejects the type
before Filter can silently exclude it.

Out of scope by instruction: peer punishment, Commit.ValidateBasic validation,
WAL write ordering, and recover()/panic-handling middleware.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs: remove commit-extension-panic exploit spec

The spec documented an unpatched vulnerability (exact packet size,
ungated reactor branch, exploit cost) under docs/, a VuePress-built
site with no exclude rule for this path — publishable before the fix
ships, contradicting the doc's own §8 guidance not to push it early.

Flagged HIGH by security review; removing rather than gating, since
no exclude mechanism exists in the current VuePress config.

* fix(types): add a sentinel error and reject nil vote extensions

VoteExtensionsFromProto dereferenced every slice element without a nil check,
contradicting the fail-closed contract VoteExtensionFromProto documents: the
conversion is reachable from untrusted network input and must neither panic nor
fabricate a value. A nil element now yields an error naming its index.

The unknown-type rejection gains an exported sentinel, ErrUnknownVoteExtensionType,
so callers can match it with errors.Is. A future peer-punishment change needs to
distinguish "this peer sent an undefined enum value" from any other conversion
failure, which a bare fmt.Errorf cannot express. The message text is unchanged.

Add, VoteExtensionsFromProto and NewVoteExtensionsFromABCIExtended became fallible
without their godoc saying so; each now documents its error contract. Callers of
VoteExtensions.Add are the one signature change the compiler cannot enforce - a
stale .Add(ve) call still compiles and silently swallows the rejection - so the
error is now part of the documented API surface.

Tests assert the specific sentinel via errors.Is rather than "some error".
VerifyCommit's case previously passed even with the rejection fully removed,
because its fake zero signature failed verification first; it now builds a commit
that genuinely verifies, asserts that positive control, and only then flips one
extension type to an undefined value. Restores direct coverage of
Vote.VerifyExtensionSign, which the peer-path test does not exercise: its vote is
built as a struct literal, reaching a path no converter can guard.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test: share one vote-extension helper and drop review IDs from comments

Making VoteExtensionsFromProto fallible spread the same three-line convert-and-
require dance across two packages and a dozen call sites, as two near-identical
private helpers whose signatures had already diverged (testing.TB vs *testing.T).
Export MustVoteExtensionsFromProto from types/test_util.go instead, following the
existing convention of a non-test file importing testing (internal/state/test/
factory), and use it everywhere a *testing.T is in scope.

The two production helpers that convert extensions, types.makeCommit and the
state test factory, keep returning an error: they have no t to fail.

Also drops ephemeral review-finding IDs from test comments in the two files this
change touches. Those IDs are reassigned on every review run and go dead after
merge, so each is replaced by the invariant it stood for.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(kvstore): return errors from the sign-item helpers

makeVoteExtensionSignItems panicked on the newly fail-closed conversion of
peer-forwarded wire data, and makeBlockSignItem panicked on its own marshalling
failures. STYLE_GUIDE.md reserves panic for a broken internal invariant; neither
qualifies, since both derive from a FinalizeBlock request. Both now return an
error, propagated by FinalizeBlock the same way as its other failure paths.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test: cover the light-client and ExtendVote extension-type paths

The unknown-type rejection has four propagation destinations; the light client
and the ABCI-facing ExtendVote had no test. verifyBlockSignatureWithDashCore
builds a canonical vote from a provider-supplied commit, so a malicious provider
could otherwise panic the light client; its Dash Core client is left nil in the
test because the rejection must happen before any RPC round-trip.

ExtendVote's panic is asserted rather than removed. That response comes from our
own application, so a type outside the enum is a local app/tenderdash mismatch,
not a network fault, and failing loudly is the intended behaviour there. The test
pins that contract so it cannot be softened by accident.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs: correct two comments on the vote-extension paths

MakeQuorumSigns claimed a causal dependency that does not hold for the traced
input; the real reason to convert first is that MakeBlockSignItem panics rather
than returning an error, so fallible work belongs ahead of it.

Marks the ExtendVote panic as a reviewed, deliberate choice: ABCI hardening is
out of scope here, and panicking on an ABCI-supplied undefined type is the
intended strongest signal, not an oversight to be fixed later.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>

* fix(p2p): only evict peer addresses that failed their last dial

A PEX-advertised URL carries a sender-chosen NodeID, so a peer can insert
addresses under another node's identity. For an address learned but not yet
dialed, LastDialSuccess and DialFailures tie with freshly injected junk, and
eviction fell through to the lowest address string, which the sender controls:
it could make its entries sort above a chosen victim and remove that victim
deterministically. Against a bootstrapping node that is a partial eclipse
primitive, not a memory bound.

leastValuableAddress becomes evictableAddresses, which returns only addresses
that failed their last dial, least valuable first. An unproven newcomer can no
longer displace an unproven incumbent: with none evictable the new address is
refused, and refusing is not a permanent freeze, since unreachable addresses
accumulate dial failures and become replaceable. DialFailures resets on a
successful dial, so one failure already means the address did not work on the
most recent attempt; a higher threshold would buy nothing here and would freeze
the set outright when MinRetryTime is 0, where retryDelay returns retryNever and
the count can never grow.

The eviction decision is now made before any address is dropped, so a refusal
leaves the peer's address map untouched.

The cap test asserted that an over-cap address is always stored, which is the
behaviour this commit removes; it now asserts a refusal while every stored
address is still viable. The oldest-dial-success test needs its unproven
incumbents to have failed a dial before eviction can consider them at all.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): prune the address index when an address is evicted

peerStore.index only ever grew: Set added every address in peer.AddressInfo and
removed none, and Delete could not help either, since by the time it runs the
evicted addresses are already gone from AddressInfo. A peer picks the NodeID it
advertises over PEX, so each eviction leaked an unreachable index entry at the
sender's request, per process and never reclaimed. The per-peer address cap was
therefore not the memory bound it claimed to be.

Set now drops from the index every address the stored entry carried and the
incoming one does not, guarded on the index still pointing at this peer so an
address re-pointed to another peer survives. Doing it in Set rather than at the
eviction call site keeps the invariant inside peerStore and covers any later
removal path.

peerInfo.Copy is a prerequisite, not a cleanup: it copied the struct and then
rewrote the values of the same map, so a "copy" shared its address map with the
store. Set would have diffed that map against itself and found nothing, and Add's
delete reached into the store before Set ran. It now allocates its own map, as
its name and doc always claimed. Every structural mutation of a fetched map is in
Add, and every field mutation is in Dialed, DialFailed and UpdatePeerInfo, all of
which persist through Set.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(types): name every path the hostname check gates

The accepted-risk note reasoned only about NodeInfo.Validate's ListenAddr, but
the same change added ValidateHostname to the exported ParseAddressString, which
also gates NewEndpoint (node/setup.go, the operator's listen address) and
ValidatorAddress.NetAddress. The note now states the accepted risk for each.

NetAddress gains no strictness: it has no production caller, and its input has
already passed ValidateHostname in ValidatorAddress.Validate. That is checkable
here, unlike the shape of the app-supplied masternode list, which this repo
cannot confirm, so the note no longer rests on it.

ParseAddressString's doc says the host must pass ValidateHostname before it is
resolved, which its tests already assert.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(types): validate the genesis quorum type against the LLMQ allowlist

Genesis is the third entry point for a quorum type, and it only checked for zero
while ValidatorSet.ValidateBasic and ValidatorSetFromProto check the allowlist.
A genesis naming validator_quorum_type 200 passed ValidateAndComplete and failed
later in the block replayer, reporting a validator set rather than the field the
operator mistyped.

Both zero-checks are replaced by one btcjson.LLMQType.Validate() call, which
subsumes them; the second was unreachable with a different message anyway, as
nothing between the two touches the field. This is what the TODO sitting on the
first check asked for.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(p2p): harden per-peer address eviction against sender steering

Three related weaknesses in the MaxAddressesPerPeer eviction path:

Eviction eligibility now derives from the dial timestamps
(peerAddressInfo.failedLastDial) instead of DialFailures. Accepted zeroes
DialFailures on every inbound connection for scoring and retry backoff, so a
peer that reconnects periodically - the normal case in a validator mesh - kept
re-marking its junk addresses as viable and permanently disabled eviction of
them. An inbound connection proves the peer is up, not that any stored address
is dialable, so it no longer touches eviction eligibility.

Ties between eviction candidates are broken pseudo-randomly (shuffle before a
stable sort) instead of by the address string. The address string is chosen by
the advertising peer, so a deterministic order over it handed the sender its
choice of victim whenever candidates tied on dial history.

New AddTrusted stores an operator- or executor-supplied address (bootstrap and
persistent-peer config, the Dash quorum-connection dialer) even when every
stored address is viable, evicting the least valuable one; failed addresses go
first. Add keeps refusing a peer-learned newcomer in that state. Previously
both paths shared Add, so unproven PEX-learned incumbents could block a
validator's real address from ever being stored. Node setup now also reports
when a configured peer address was not re-added instead of discarding the
result.

The most-dial-failures eviction test now has two evictable candidates with
different failure counts; with a single candidate it never exercised the
comparison it claims to test (verified by mutating the comparator).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(privval): validate the quorum type on both remote-signer transports

SignVote and SignProposal on the gRPC signer server and in the socket
transport's DefaultValidationRequestHandler converted the request's bare int32
quorum type to btcjson.LLMQType unchecked. Sign-hash construction narrows the
type to uint8 with a panicking conversion, so a request carrying an
out-of-range type crashed the signer; an in-range but unknown type produced a
sign hash for a quorum type that does not exist. Both transports now check the
type against the LLMQ allowlist before the privVal is touched, matching the
guards on the proto-decode, validator-set, and genesis entry points.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(config): drop the unsafe commit-timeout override knobs

The Timeout.Commit and Timeout.BypassCommitTimeout consensus parameters are
gone, but the config surface still offered unsafe-commit-timeout-override and
unsafe-bypass-commit-timeout-override: struct fields, validation, TOML
template lines, and documentation for values nothing reads. All removed. The
config template test now guards against offering overrides for parameters
that no longer exist. Existing config files carrying the keys keep loading,
since unknown TOML keys are ignored during unmarshalling.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(types): count every hostname-check call site accurately

The listen-address strictness note claimed ValidateHostname gates three
paths; it has four non-test call sites. The note now scopes its claim to the
three paths whose strictness the shared check changed and names the fourth,
NodeAddress.Validate, which runs the same check on its own and gains nothing
from the sharing.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Revert "fix(config): drop the unsafe commit-timeout override knobs"

This reverts commit 9b3da4faa87c6e9b8b9f4d608e6c2dc84869e6e2.

* Revert "fix(types): drop the unused Timeout.Commit and Timeout.BypassCommitTimeout"

This reverts commit 5c07b3440a1be7686c4bc31529117c4cf3577978.

* Revert "fix(p2p): harden per-peer address eviction against sender steering"

This reverts commit d935795ef250eaf408b3da082e534f187cdc6ed8.

* Revert "fix(p2p): prune the address index when an address is evicted"

This reverts commit ffb6c6680d5f4587910252ed5cc8b7296792dc70.

* Revert "fix(p2p): only evict peer addresses that failed their last dial"

This reverts commit 8caadb105f2b2a1c61a8da68a272d8e9ef2db95f.

* Revert "fix(p2p): evict least valuable address instead of refusing new ones"

This reverts commit 91f2dc6af0807552c68ddd053d758181529bef2d.

* fix(types): let ValidateBasic be the only quorum-type gate on the proto path

An empty validator set serializes to an empty proto message whose QuorumType is
0, so the early allowlist check in ValidatorSetFromProto rejected a zero-validator
genesis before the empty-set determination could report
ErrValidatorSetNilOrEmpty, and the node refused to reload its own state. The
terminal ValidateBasic already validates the quorum type, and short-circuits on
empty sets first, so the early check only cost a second error string.

State.FromProto now compares that sentinel with errors.Is so the initial-height
tolerance survives future wrapping.

* fix(privval): validate a whole signing request before it reaches the signer

Both remote-signer transports checked the quorum type and nothing else, so a
request without a vote or proposal was dereferenced and a quorum hash of the
wrong size panicked SignItem.UpdateSignHash — either one stops the validator
from signing at all. ValidateQuorumParams now carries the quorum checks and
their rationale once for all four handlers, replacing the inverted error
branches on the socket transport with guard clauses.

* refactor(statesync): give the consensus-params checks a name and a test

verifyConsensusParams holds the validation and the hash comparison of the P2P
path in the order they must run, so both are covered by a unit test instead of
requiring a full light-client fixture. Its comment states what the params hash
does not cover and what the bound does not reject, and the RPC provider says
plainly that it verifies nothing.

* docs(p2p,types): state the hostname and address-cap decisions once, in place

NodeInfo.Validate carries the whole hostname-strictness rationale, covering the
node and seed constructors that reach it, so node/setup.go no longer explains
code that is gone. PeerManager.Add says what its cap does not do, the two
secret-connection read-cap comments read identically again, and the divergence
note names the sibling file instead of a fork issue.

NewEndpoint failures now name the config key that produced them, and the
envelope attribute counter no longer shadows the bytes package.

* fix(p2p): drop the per-peer address cap, correct the statesync note

The cap bounded peerInfo.AddressInfo at 32 entries per NodeID and refused
anything further, with no eviction. PEX takes the NodeID from the sender's
URL without relating it to the sender's identity, and stored addresses are
only syntax-validated, so one PEX response could fill all 32 slots of a
chosen victim NodeID with junk hostnames. Nothing evicts an individual
address, the map is persisted so the state survives restart, and Advertise
re-gossips it, so the victim's real address was refused indefinitely. The
Dash quorum dialer compounds it by discarding the Add result and then
pinning the entry with PeerScorePersistent. The same lockout occurs with no
attacker at all, from ordinary address churn, because stored addresses
never expire.

Removing the cap restores unbounded address growth, which is the existing
behaviour on v1.6-dev and a resource concern rather than a targeted one:
the victim's real address stays dialable. Bounding the store is still
worth doing, but it has to bound per sending peer rather than per
advertised NodeID, which is a design change rather than a hotfix.

Also corrects the note at the RPC state provider. It claimed that path
performs no validation and no ConsensusHash comparison, and that the
provider is unused in production. Both are wrong: the equivalent checks
run one layer down in lightrpc.Client.ConsensusParams, and use-p2p
defaults to false, so this is the provider in use unless it is set.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Ivan Shumkov <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
shumkov added a commit that referenced this pull request Aug 17, 2026
…ic (#32)

* fix(types): reject unknown vote-extension types in Commit.ValidateBasic

Every other field of a Commit is either checked by ValidateBasic or covered by the
threshold signature. The vote-extension type is neither, and proto3 enums are open,
so an undefined varint decodes into the generated enum field unchallenged and rides
through every boundary a Commit crosses.

Add the type check. Type only: an extension's contents are threshold-signed, so
they are not ValidateBasic's to police, and the content rules in
VoteExtensions.Validate() were written for a vote, where they are not signed.

ValidVoteExtensionType is placed next to VoteExtensionFromProto so the set of
dispatchable types has one home. A type accepted by one and missing from the other
would be admitted into a struct nothing can convert.

This inverts a property PR #18 deliberately pinned -- that a poison commit must
still decode from the WAL, because a rejection during WAL decode raises
DataCorruptionError and aborts catchupReplay. The inversion is safe because the
rejection moved upstream rather than merely being added: MsgFromProto calls
ValidateBasic at the p2p boundary, so a poison commit is now rejected as it arrives
and walMiddleware never has anything to write. A WAL from an older build could
still hold one, and that case is recoverable via repairWalFile. The block store,
which panics through mustDecodeCommit and has no repair path, is made safe by
verifying the commit at statesync backfill ingress -- this change's predicate, not
an assumption.

commit_extension_unbrick_test.go is rewritten rather than deleted, and states which
property it now pins and why. Two tests in commit_extension_regression_test.go
built their poison through CommitFromProto, which now rejects it; they build the
struct directly instead, because their subject is defence in depth -- what
GetCanonicalVote and VerifyCommit do on the consensus goroutine if a poison commit
arrives by a route that skips ValidateBasic.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(types): one authority for vote-extension type membership

The enum-membership question was answered in two hand-written switches that had to
be kept in step by hand, and Commit.ValidateBasic's rejections were anonymous
strings that three tests pinned by substring.

Membership now has one derivation per layer. tmproto.VoteExtensionType.IsValid
reads the generated name table, so it answers for whatever the .proto defines with
no hand-maintained case list, and (*VoteExtension).Validate uses it - the obvious
place to look for vote-extension validation now checks the type it validates.
VoteExtensionFromProto's dispatch switch is the only remaining case list, and
Commit.ValidateBasic calls it instead of mirroring it, which removes
ValidVoteExtensionType entirely. A table-driven test walks
VoteExtensionType_name and fails if a defined type has no dispatch arm.

Both rejections wrap sentinels: ErrUnknownVoteExtensionType, now owned by the proto
package and aliased in types so a rejection from either side matches one errors.Is
check, and ErrNilVoteExtension, shared with VoteExtensionsFromProto. The tests
assert with ErrorIs and EqualError rather than substrings.

The comment above the check claimed every other Commit field is checked or covered
by the threshold signature. Commit.Hash is a checksum of ThresholdBlockSignature
alone, so nothing binds the extension list's order, count or duplication; the
comment now says only what is true, and a TODO points at the tracking issue.
An INTENTIONAL note records the accepted rollback hazard of an ungated rejection.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(types): record the accepted risks around commit extension validation

Two hazards the type check does not close, both accepted rather than fixed:
a block store poisoned before the statesync backfill gate shipped still panics
on load with no repair path, and scripts/scmigrate gates on the returned commit
instead of the error, so it can re-persist such a commit.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(types): make the conversion dispatch the sole vote-extension type gate

Drop the redundant IsValid guard from tmproto.VoteExtension.Validate: every
wire-input path reaches extensions through types.VoteExtensionFromProto's
dispatch switch before Validate can run, so the switch is the one enforcement
gate. IsValid stays as a query helper that reads the generated name table; the
cross-check test pins that the dispatch covers every .proto-defined type. The
ErrUnknownVoteExtensionType sentinel moves back to types/ as the sole
definition now that the proto package no longer returns it.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs: align security markers, godocs, and operator docs with shipped behavior

- scmigrate INTENTIONAL marker: the accepted-risk rationale claimed the path
  is not part of the running node's write path; it is wired to the shipped
  'tenderdash key-migrate' subcommand. State the true rationale: the store
  already holds the record, so re-persisting adds no new exposure.
- pre-upgrade-poisoned-store marker: name all three panic surfaces
  (mustDecodeCommit, LoadSeenCommit, LoadBlock), not just mustDecodeCommit.
- mustDecodeCommit panic message: the failure is a proto->commit decode, not
  'converting commit to proto'.
- CommitFromProto godoc: a validation error does not imply a nil result;
  callers must branch on the error, never the value.
- Commit.ValidateBasic godoc: document the ErrNilVoteExtension and
  ErrUnknownVoteExtensionType sentinels callers already depend on.
- Drop private-fork issue references from comments; state the constraints
  self-containedly instead.
- UPGRADING.md: document the three operator-visible consequences of rejecting
  undefined vote-extension types (p2p rejection, startup panic on an already
  poisoned store with no repair path, rollback hazard once a future release
  adds a new extension type).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(consensus): recover in gossip handlers, return the canonicalization error

Tightening Commit.ValidateBasic makes an already-stored commit with an
unknown extension type unreadable. The accepted risk was recorded as a
startup panic, but startup reads only the last-height seen commit and the
replay range. A commit written by statesync backfill sits below those, so
the node starts normally and the record is reached later, by a gossip
handler loading the height a peer advertised. That handler ran in a bare
goroutine while every other peer-facing path in the node recovers, so one
unreadable historical record let any peer terminate the process by naming
its height, repeatedly. Gossip handlers now recover and log, matching the
consensus reactor, the statesync reactor and the p2p client.

GenericVoteExtension.SignItem returned an error for its first fallible
call and panicked for the other two, one of which is
CanonicalizeVoteExtension. That function keeps its own list of the types
it can canonicalize, separate from the conversion dispatch this PR makes
authoritative, so a type added to the .proto with a dispatch arm but no
canonical form would pass the new gate and then panic on the consensus
goroutine. It now returns the error, which its only caller already
handles.

Drops VoteExtensionType.IsValid: it had no production caller, and both
tests using it asserted a tautology, since IsValid is the same map lookup
they iterated. The dispatch coverage test keeps its value without it.

Corrects UPGRADING.md, which promised a startup panic for the exact
population that does not get one, and adds the WAL case, where repair
rewrites only the most recent segment.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Lukasz Klimek <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: Ivan Shumkov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants