From 6e600d5884991515257beb0c4f1afe9642287aaf Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Wed, 18 Nov 2026 13:57:56 +0100 Subject: [PATCH 01/11] fix(syncing): authenticate DA blobs before acting on them The DA retriever marked every decoded blob as DA included and let the first header or data blob for a height take that height's slot, before checking who signed it. Blobs from any key could stall DA sync or mark a height as DA included. Decoded blobs are now candidates only. For heights the node already holds, only blobs matching the stored block are marked. For future heights, a header is emitted once it is signed by the expected proposer and has the data it commits to, and DA inclusion is marked at that point. --- block/internal/syncing/da_retriever.go | 437 ++++++++++++------ .../syncing/da_retriever_strict_test.go | 14 +- block/internal/syncing/da_retriever_test.go | 240 +++++++++- block/internal/syncing/syncer.go | 23 +- block/internal/syncing/syncer_test.go | 10 +- 5 files changed, 557 insertions(+), 167 deletions(-) diff --git a/block/internal/syncing/da_retriever.go b/block/internal/syncing/da_retriever.go index 7d2dceeede..4a8496d676 100644 --- a/block/internal/syncing/da_retriever.go +++ b/block/internal/syncing/da_retriever.go @@ -34,6 +34,25 @@ type pendingDataCleaner interface { type expectedProposerProvider func(height uint64) ([]byte, bool) +// syncedHeaderProvider returns the stored header for a height the node has +// already synced. synced is false for heights above the node's height. The +// header is nil when the height is synced but no longer stored. +type syncedHeaderProvider func(height uint64) (header *types.SignedHeader, synced bool, err error) + +type pendingHeader struct { + header *types.SignedHeader + daHeight uint64 + // envelope is set when the DA envelope signature verified against the header's signer key. + envelope bool +} + +type pendingData struct { + data *types.Data + hash types.Hash + signer []byte + daHeight uint64 +} + // daRetriever handles DA retrieval operations for syncing type daRetriever struct { client da.Client @@ -41,15 +60,21 @@ type daRetriever struct { genesis genesis.Genesis logger zerolog.Logger - expectedProposer expectedProposerProvider + expectedProposer expectedProposerProvider + syncedHeader syncedHeaderProvider + signatureProvider types.SyncNodeSignatureBytesProvider mu sync.Mutex - // transient cache, only full event need to be passed to the syncer - // on restart, will be refetch as da height is updated by syncer - pendingHeaders map[uint64]*types.SignedHeader - pendingData map[uint64]*types.Data - - // strictMode indicates if the node has seen a valid DAHeaderEnvelope + // Anyone can post to the DA namespaces, so every decoded blob is only a + // candidate: it is not marked DA included and does not displace another + // blob until it is authenticated. Candidates for future heights are kept + // without a cap; growing them costs one paid blob per entry, and a cap + // would let an outsider crowd out the header of a newly rotated proposer. + // Transient: rebuilt from DA on restart. + pendingHeaders map[uint64][]pendingHeader + pendingData map[uint64][]pendingData + + // strictMode indicates if the node has seen an authenticated DAHeaderEnvelope // and should now reject all legacy/unsigned headers. strictMode bool } @@ -66,8 +91,8 @@ func NewDARetriever( cache: cache, genesis: genesis, logger: logger.With().Str("component", "da_retriever").Logger(), - pendingHeaders: make(map[uint64]*types.SignedHeader), - pendingData: make(map[uint64]*types.Data), + pendingHeaders: make(map[uint64][]pendingHeader), + pendingData: make(map[uint64][]pendingData), strictMode: false, } } @@ -76,6 +101,14 @@ func (r *daRetriever) setExpectedProposerProvider(provider expectedProposerProvi r.expectedProposer = provider } +func (r *daRetriever) setSyncedHeaderProvider(provider syncedHeaderProvider) { + r.syncedHeader = provider +} + +func (r *daRetriever) setSignatureProvider(provider types.SyncNodeSignatureBytesProvider) { + r.signatureProvider = provider +} + // RetrieveFromDA retrieves blocks from the specified DA height and returns height events func (r *daRetriever) RetrieveFromDA(ctx context.Context, daHeight uint64) ([]common.DAHeightEvent, error) { r.logger.Debug().Uint64("da_height", daHeight).Msg("retrieving from DA") @@ -177,101 +210,276 @@ func (r *daRetriever) processBlobs(ctx context.Context, blobs [][]byte, daHeight r.mu.Lock() defer r.mu.Unlock() - // Decode all blobs for _, bz := range blobs { if len(bz) == 0 { continue } - if header := r.tryDecodeHeader(bz, daHeight); header != nil { - if existing, ok := r.pendingHeaders[header.Height()]; ok { - if r.shouldReplacePendingHeader(existing, header) { - r.cache.RemoveHeaderDAIncluded(existing.Hash().String()) - r.pendingHeaders[header.Height()] = header - r.logger.Debug().Uint64("height", header.Height()).Uint64("da_height", daHeight).Msg("replaced pending header with expected proposer header") - continue - } + if header, envelope := r.tryDecodeHeader(bz); header != nil { + r.addPendingHeader(pendingHeader{header: header, daHeight: daHeight, envelope: envelope}) + continue + } - r.cache.RemoveHeaderDAIncluded(header.Hash().String()) - r.logger.Debug().Uint64("height", header.Height()).Uint64("da_height", daHeight).Msg("header blob already exists for height, discarding") - continue + if data, signer := r.tryDecodeData(bz); data != nil { + r.addPendingData(pendingData{data: data, hash: data.Hash(), signer: signer, daHeight: daHeight}) + } + } + + events := r.settleSyncedHeights(ctx, daHeight) + events = append(events, r.matchPending(ctx, daHeight)...) + + if len(events) > 0 { + startHeight := events[0].Header.Height() + endHeight := events[0].Header.Height() + for _, event := range events { + h := event.Header.Height() + if h < startHeight { + startHeight = h } + if h > endHeight { + endHeight = h + } + } + r.logger.Info().Uint64("da_height", daHeight).Uint64("start_height", startHeight).Uint64("end_height", endHeight).Msg("processed blocks from DA") + } - r.pendingHeaders[header.Height()] = header - continue + return events +} + +func (r *daRetriever) addPendingHeader(candidate pendingHeader) { + height := candidate.header.Height() + for _, existing := range r.pendingHeaders[height] { + if existing.envelope == candidate.envelope && sameSignedHeader(existing.header, candidate.header) { + return } + } + r.pendingHeaders[height] = append(r.pendingHeaders[height], candidate) +} - if data := r.tryDecodeData(bz, daHeight); data != nil { - if _, ok := r.pendingData[data.Height()]; ok { - // a (malicious) node may have re-published valid data to another da height (should never happen) - // we can already discard it, only the first one is valid - r.logger.Debug().Uint64("height", data.Height()).Uint64("da_height", daHeight).Msg("data blob already exists for height, discarding") - continue - } +func (r *daRetriever) addPendingData(candidate pendingData) { + height := candidate.data.Height() + for _, existing := range r.pendingData[height] { + if bytes.Equal(existing.hash, candidate.hash) && bytes.Equal(existing.signer, candidate.signer) { + return + } + } + r.pendingData[height] = append(r.pendingData[height], candidate) +} + +// settleSyncedHeights resolves candidates for heights the node already holds. +// The stored block is the reference: only the blobs that carry it are marked +// DA included, everything else at that height is dropped. A complete block is +// still returned as an event, which the syncer skips as already processed. +func (r *daRetriever) settleSyncedHeights(ctx context.Context, daHeight uint64) []common.DAHeightEvent { + if r.syncedHeader == nil { + return nil + } - r.pendingData[data.Height()] = data + var events []common.DAHeightEvent + settle := func(height uint64) { + stored, synced, err := r.syncedHeader(height) + if err != nil { + // keep the candidates and retry on the next pass + r.logger.Warn().Err(err).Uint64("height", height).Msg("failed to load synced header") + return + } + if !synced { + return + } + if stored != nil { + for _, candidate := range r.pendingData[height] { + if types.Validate(stored, candidate.data) == nil { + r.markDataDAIncluded(candidate) + } + } + for _, candidate := range r.pendingHeaders[height] { + if !sameSignedHeader(candidate.header, stored) { + continue + } + r.markHeaderDAIncluded(candidate) + if data, ok := r.dataFor(ctx, candidate.header); ok { + events = append(events, common.DAHeightEvent{ + Header: candidate.header, + Data: data.data, + DaHeight: daHeight, + Source: common.SourceDA, + }) + } + break + } } + delete(r.pendingHeaders, height) + delete(r.pendingData, height) + } + + for height := range r.pendingHeaders { + settle(height) } + for height := range r.pendingData { + settle(height) + } + return events +} +// matchPending emits an event for every future height that has a header from +// the expected proposer together with the data that header commits to. +func (r *daRetriever) matchPending(ctx context.Context, daHeight uint64) []common.DAHeightEvent { events := make([]common.DAHeightEvent, 0, len(r.pendingHeaders)) - // Match headers with data and create events - for height, header := range r.pendingHeaders { - data := r.pendingData[height] + for height, candidates := range r.pendingHeaders { + // Left over from a failed load or synced since settleSyncedHeights ran: + // it is settled against the stored block on the next pass. + if r.isSynced(height) { + continue + } + expected := r.expectedProposerFor(height) + + for i, candidate := range candidates { + header := candidate.header + if !isFromProposer(header, expected) { + continue + } - // Handle empty data case - if data == nil { - if isEmptyDataExpected(header) { - data = createEmptyDataForHeader(ctx, header) - delete(r.pendingHeaders, height) - } else { + data, ok := r.dataFor(ctx, header) + if !ok { // keep header in pending headers until data lands r.logger.Debug().Uint64("height", height).Msg("header found but no matching data") continue } - } else { - delete(r.pendingHeaders, height) - } - - // Create height event - event := common.DAHeightEvent{ - Header: header, - Data: data, - DaHeight: daHeight, - Source: common.SourceDA, - } - events = append(events, event) - } + // The envelope signature already proves the proposer signed this header. + if !candidate.envelope && !r.hasValidSignature(header, data.data) { + r.logger.Debug().Uint64("height", height).Msg("invalid header signature") + continue + } - if len(events) > 0 { - startHeight := events[0].Header.Height() - endHeight := events[0].Header.Height() - for _, event := range events { - h := event.Header.Height() - if h < startHeight { - startHeight = h + r.markHeaderDAIncluded(candidate) + if !isEmptyDataExpected(header) { + r.markDataDAIncluded(data) } - if h > endHeight { - endHeight = h + + events = append(events, common.DAHeightEvent{ + Header: header, + Data: data.data, + DaHeight: daHeight, + Source: common.SourceDA, + }) + + if len(candidates) == 1 { + delete(r.pendingHeaders, height) + } else { + r.pendingHeaders[height] = append(candidates[:i:i], candidates[i+1:]...) } + break } - r.logger.Info().Uint64("da_height", daHeight).Uint64("start_height", startHeight).Uint64("end_height", endHeight).Msg("processed blocks from DA") } return events } -func (r *daRetriever) shouldReplacePendingHeader(existing, candidate *types.SignedHeader) bool { - if r.expectedProposer == nil { +// dataFor returns the pending data the header commits to. The commitment +// does not cover all metadata, so a copy signed by the header's proposer wins +// over one signed by anyone else. +func (r *daRetriever) dataFor(ctx context.Context, header *types.SignedHeader) (pendingData, bool) { + var match *pendingData + for i, candidate := range r.pendingData[header.Height()] { + if types.Validate(header, candidate.data) != nil { + continue + } + if bytes.Equal(candidate.signer, header.ProposerAddress) { + return candidate, true + } + if match == nil { + match = &r.pendingData[header.Height()][i] + } + } + if match != nil { + return *match, true + } + if isEmptyDataExpected(header) { + return pendingData{data: createEmptyDataForHeader(ctx, header)}, true + } + return pendingData{}, false +} + +func (r *daRetriever) isSynced(height uint64) bool { + if r.syncedHeader == nil { return false } + _, synced, err := r.syncedHeader(height) + return synced || err != nil +} + +// expectedProposerFor returns the proposer expected at a future height, or nil when unknown. +func (r *daRetriever) expectedProposerFor(height uint64) []byte { + if r.expectedProposer != nil { + if expected, ok := r.expectedProposer(height); ok && len(expected) > 0 { + return expected + } + } + return r.genesis.ProposerAddress +} + +// sameSignedHeader compares the signature and signer as well as the hash: +// the hash covers neither, so anyone can repost a real header under their own key. +func sameSignedHeader(a, b *types.SignedHeader) bool { + return bytes.Equal(a.Hash(), b.Hash()) && + bytes.Equal(a.Signature, b.Signature) && + bytes.Equal(signerAddress(a), signerAddress(b)) +} + +func signerAddress(header *types.SignedHeader) []byte { + if header.Signer.PubKey == nil { + return nil + } + return types.KeyAddress(header.Signer.PubKey) +} - expected, ok := r.expectedProposer(candidate.Height()) - if !ok || len(expected) == 0 { +// isFromProposer checks the key the header is signed with, not only the +// ProposerAddress field, which anyone can fill in. +func isFromProposer(header *types.SignedHeader, expected []byte) bool { + if len(expected) == 0 { + return true + } + if header.Signer.PubKey == nil { return false } - return !bytes.Equal(existing.ProposerAddress, expected) && bytes.Equal(candidate.ProposerAddress, expected) + return bytes.Equal(header.ProposerAddress, expected) && bytes.Equal(signerAddress(header), expected) +} + +func (r *daRetriever) hasValidSignature(header *types.SignedHeader, data *types.Data) bool { + if r.signatureProvider != nil { + header.SetCustomVerifierForSyncNode(r.signatureProvider) + } + return header.ValidateBasicWithData(data) == nil +} + +func (r *daRetriever) markHeaderDAIncluded(candidate pendingHeader) { + header := candidate.header + headerHash := header.MemoizeHash().String() + r.cache.SetHeaderDAIncluded(headerHash, candidate.daHeight, header.Height()) + + r.logger.Debug(). + Str("header_hash", headerHash). + Uint64("da_height", candidate.daHeight). + Uint64("height", header.Height()). + Msg("header marked as DA included") + + if candidate.envelope && !r.strictMode { + r.logger.Info().Uint64("height", header.Height()).Msg("valid DA envelope detected, switching to STRICT MODE") + r.strictMode = true + } +} + +func (r *daRetriever) markDataDAIncluded(candidate pendingData) { + dataHash := candidate.data.DACommitment().String() + r.cache.SetDataDAIncluded(dataHash, candidate.daHeight, candidate.data.Height()) + + r.logger.Debug(). + Str("data_hash", dataHash). + Uint64("da_height", candidate.daHeight). + Uint64("height", candidate.data.Height()). + Msg("data marked as DA included") } func (r *daRetriever) removePendingData(height uint64) { @@ -281,8 +489,9 @@ func (r *daRetriever) removePendingData(height uint64) { delete(r.pendingData, height) } -// tryDecodeHeader attempts to decode a blob as a header -func (r *daRetriever) tryDecodeHeader(bz []byte, daHeight uint64) *types.SignedHeader { +// tryDecodeHeader attempts to decode a blob as a header. The second result +// reports whether a DA envelope signature verified against the header's signer key. +func (r *daRetriever) tryDecodeHeader(bz []byte) (*types.SignedHeader, bool) { header := new(types.SignedHeader) isValidEnvelope := false @@ -292,33 +501,33 @@ func (r *daRetriever) tryDecodeHeader(bz []byte, daHeight uint64) *types.SignedH // If in strict mode, we REQUIRE an envelope. if r.strictMode { r.logger.Warn().Err(err).Msg("strict mode is enabled, rejecting non-envelope blob") - return nil + return nil, false } // Fallback for backward compatibility (only if NOT in strict mode) r.logger.Debug().Msg("trying legacy decoding") var headerPb pb.SignedHeader if errLegacy := proto.Unmarshal(bz, &headerPb); errLegacy != nil { - return nil + return nil, false } if errLegacy := header.FromProto(&headerPb); errLegacy != nil { - return nil + return nil, false } } else { // We have a structurally valid envelope (or at least it parsed) if len(envelopeSignature) > 0 { if header.Signer.PubKey == nil { r.logger.Debug().Msg("header signer has no pubkey, cannot verify envelope") - return nil + return nil, false } payload, err := header.MarshalBinary() if err != nil { r.logger.Debug().Err(err).Msg("failed to marshal header for verification") - return nil + return nil, false } if valid, err := header.Signer.PubKey.Verify(payload, envelopeSignature); err != nil || !valid { r.logger.Info().Err(err).Msg("DA envelope signature verification failed") - return nil + return nil, false } r.logger.Debug().Uint64("height", header.Height()).Msg("DA envelope signature verified") isValidEnvelope = true @@ -327,95 +536,43 @@ func (r *daRetriever) tryDecodeHeader(bz []byte, daHeight uint64) *types.SignedH if r.strictMode && !isValidEnvelope { // no need to print warnings, as tryDecodeHeader could try to decode data first, which will show this warning. r.logger.Debug().Msg("strict mode: rejecting block that is not a fully valid envelope") - return nil + return nil, false } if err := header.Header.ValidateBasic(); err != nil { r.logger.Debug().Err(err).Msg("invalid header structure") - return nil - } - - if err := r.assertExpectedProposer(header); err != nil { - r.logger.Debug().Err(err).Msg("unexpected proposer") - return nil - } - - if isValidEnvelope && !r.strictMode { - r.logger.Info().Uint64("height", header.Height()).Msg("valid DA envelope detected, switching to STRICT MODE") - r.strictMode = true - } - - // Optimistically mark as DA included - // This has to be done for all fetched DA headers prior to validation because P2P does not confirm - // da inclusion. This is not an issue, as an invalid header will be rejected. There cannot be hash collisions. - headerHash := header.MemoizeHash().String() - r.cache.SetHeaderDAIncluded(headerHash, daHeight, header.Height()) - - r.logger.Debug(). - Str("header_hash", headerHash). - Uint64("da_height", daHeight). - Uint64("height", header.Height()). - Msg("optimistically marked header as DA included") - - return header -} - -func (r *daRetriever) assertExpectedProposer(header *types.SignedHeader) error { - if r.expectedProposer == nil { - return nil + return nil, false } - expected, ok := r.expectedProposer(header.Height()) - if !ok || len(expected) == 0 { - return nil - } - if !bytes.Equal(header.ProposerAddress, expected) { - return fmt.Errorf("%w - got: %x, want: %x", types.ErrUnexpectedProposer, header.ProposerAddress, expected) - } - return nil + return header, isValidEnvelope } -// tryDecodeData attempts to decode a blob as signed data -func (r *daRetriever) tryDecodeData(bz []byte, daHeight uint64) *types.Data { +// tryDecodeData attempts to decode a blob as signed data. The second result is +// the address of the key that signed it. +func (r *daRetriever) tryDecodeData(bz []byte) (*types.Data, []byte) { var signedData types.SignedData if err := signedData.UnmarshalBinary(bz); err != nil { - return nil + return nil, nil } // Skip completely empty data if len(signedData.Txs) == 0 && len(signedData.Signature) == 0 { - return nil + return nil, nil } - // Validate signature using the configured provider - if err := r.assertValidSignedData(&signedData); err != nil { + if err := assertValidSignedData(&signedData, r.genesis); err != nil { r.logger.Debug().Err(err).Msg("invalid signed data") - return nil + return nil, nil } // Reject data without metadata before using accessors (DACommitment, // Height) that assume it is present. if signedData.Metadata == nil { r.logger.Debug().Msg("invalid signed data: missing metadata") - return nil + return nil, nil } - // Mark as DA included - dataHash := signedData.Data.DACommitment().String() - r.cache.SetDataDAIncluded(dataHash, daHeight, signedData.Height()) - - r.logger.Debug(). - Str("data_hash", dataHash). - Uint64("da_height", daHeight). - Uint64("height", signedData.Height()). - Msg("data marked as DA included") - - return &signedData.Data -} - -// assertValidSignedData validates signed data using the configured signature provider -func (r *daRetriever) assertValidSignedData(signedData *types.SignedData) error { - return assertValidSignedData(signedData, r.genesis) + return &signedData.Data, types.KeyAddress(signedData.Signer.PubKey) } // isEmptyDataExpected checks if empty data is expected for a header diff --git a/block/internal/syncing/da_retriever_strict_test.go b/block/internal/syncing/da_retriever_strict_test.go index 449a7aa4d2..0452bd6e1c 100644 --- a/block/internal/syncing/da_retriever_strict_test.go +++ b/block/internal/syncing/da_retriever_strict_test.go @@ -72,26 +72,26 @@ func TestDARetriever_StrictEnvelopeMode_Switch(t *testing.T) { // A. Initial State: StrictMode is false. Legacy blob should be accepted. assert.False(t, r.strictMode) - decodedLegacy := r.tryDecodeHeader(legacyBlob, 100) + decodedLegacy, _ := r.tryDecodeHeader(legacyBlob) require.NotNil(t, decodedLegacy) assert.Equal(t, uint64(1), decodedLegacy.Height()) // StrictMode should still be false because it was a legacy blob assert.False(t, r.strictMode) - // B. Receiving Envelope: Should be accepted and Switch StrictMode to true. - decodedEnvelope := r.tryDecodeHeader(envelopeBlob, 101) - require.NotNil(t, decodedEnvelope) - assert.Equal(t, uint64(2), decodedEnvelope.Height()) + // B. Receiving Envelope: once authenticated it switches StrictMode to true. + events := r.processBlobs(t.Context(), [][]byte{envelopeBlob}, 101) + require.Len(t, events, 1) + assert.Equal(t, uint64(2), events[0].Header.Height()) assert.True(t, r.strictMode, "retriever should have switched to strict mode") // C. Receiving Legacy again: Should be REJECTED now. // We reuse the same legacyBlob (or a new one, doesn't matter, structure is legacy). - decodedLegacyAgain := r.tryDecodeHeader(legacyBlob, 102) + decodedLegacyAgain, _ := r.tryDecodeHeader(legacyBlob) assert.Nil(t, decodedLegacyAgain, "legacy blob should be rejected in strict mode") // D. Receiving Envelope again: Should still be accepted. - decodedEnvelopeAgain := r.tryDecodeHeader(envelopeBlob, 103) + decodedEnvelopeAgain, _ := r.tryDecodeHeader(envelopeBlob) require.NotNil(t, decodedEnvelopeAgain) } diff --git a/block/internal/syncing/da_retriever_test.go b/block/internal/syncing/da_retriever_test.go index 87fa77d112..d336ff8304 100644 --- a/block/internal/syncing/da_retriever_test.go +++ b/block/internal/syncing/da_retriever_test.go @@ -201,18 +201,20 @@ func TestDARetriever_TryDecodeHeaderAndData_Basic(t *testing.T) { r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) hb, sh := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, nil, nil) - gotH := r.tryDecodeHeader(hb, 123) + gotH, _ := r.tryDecodeHeader(hb) require.NotNil(t, gotH) assert.Equal(t, sh.Hash().String(), gotH.Hash().String()) db, sd := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 1) - gotD := r.tryDecodeData(db, 123) + gotD, _ := r.tryDecodeData(db) require.NotNil(t, gotD) assert.Equal(t, sd.Height(), gotD.Height()) // invalid data fails - assert.Nil(t, r.tryDecodeHeader([]byte("junk"), 1)) - assert.Nil(t, r.tryDecodeData([]byte("junk"), 1)) + junkH, _ := r.tryDecodeHeader([]byte("junk")) + assert.Nil(t, junkH) + junkD, _ := r.tryDecodeData([]byte("junk")) + assert.Nil(t, junkD) } func TestDARetriever_tryDecodeData_InvalidSignature(t *testing.T) { @@ -227,7 +229,8 @@ func TestDARetriever_tryDecodeData_InvalidSignature(t *testing.T) { db, err := signedData.MarshalBinary() require.NoError(t, err) - assert.Nil(t, r.tryDecodeData(db, 55)) + got, _ := r.tryDecodeData(db) + assert.Nil(t, got) } func TestDARetriever_tryDecodeData_NilMetadata(t *testing.T) { @@ -247,7 +250,8 @@ func TestDARetriever_tryDecodeData_NilMetadata(t *testing.T) { db, err := sd.MarshalBinary() require.NoError(t, err) - assert.Nil(t, r.tryDecodeData(db, 99)) + got, _ := r.tryDecodeData(db) + assert.Nil(t, got) } func TestDARetriever_validateBlobResponse(t *testing.T) { @@ -300,6 +304,211 @@ func TestDARetriever_RetrieveFromDA_TwoNamespaces_Success(t *testing.T) { assert.Equal(t, uint64(9), events[0].Data.Height()) } +func TestDARetriever_ProcessBlobs_OutsiderDataDoesNotClaimHeight(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + outsiderBin, _ := makeSignedDataBytes(t, gen.ChainID, 5, nil, outsiderPub, outsiderSigner, 3) + require.Empty(t, r.processBlobs(context.Background(), [][]byte{outsiderBin}, 10)) + + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + events := r.processBlobs(context.Background(), [][]byte{hdrBin, dataBin}, 11) + + require.Len(t, events, 1) + require.Equal(t, data.DACommitment(), events[0].Data.DACommitment()) + require.NoError(t, types.Validate(hdr, events[0].Data)) +} + +func TestDARetriever_ProcessBlobs_OutsiderDataDoesNotReplaceEmptyData(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + outsiderBin, _ := makeSignedDataBytes(t, gen.ChainID, 5, nil, outsiderPub, outsiderSigner, 3) + hdrBin, _ := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, nil, nil) + events := r.processBlobs(context.Background(), [][]byte{outsiderBin, hdrBin}, 10) + + require.Len(t, events, 1) + require.Empty(t, events[0].Data.Txs) +} + +func TestDARetriever_ProcessBlobs_OutsiderHeaderDoesNotClaimHeight(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + outsiderAddr, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + // Signed by the outsider, and a second one that only copies the proposer address. + outsiderBin, outsiderHdr := makeSignedHeaderBytes(t, gen.ChainID, 5, outsiderAddr, outsiderPub, outsiderSigner, nil, &data.Data, nil) + spoofedBin, spoofedHdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, outsiderPub, outsiderSigner, nil, &data.Data, nil) + + require.Empty(t, r.processBlobs(context.Background(), [][]byte{outsiderBin, spoofedBin, dataBin}, 10)) + for _, h := range []*types.SignedHeader{outsiderHdr, spoofedHdr} { + _, included := r.cache.GetHeaderDAIncludedByHash(h.Hash().String()) + require.False(t, included) + } + + events := r.processBlobs(context.Background(), [][]byte{hdrBin}, 11) + require.Len(t, events, 1) + require.Equal(t, hdr.Hash().String(), events[0].Header.Hash().String()) +} + +func TestDARetriever_ProcessBlobs_SyncedHeightMarksOnlyStoredBlock(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + outsiderAddr, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + fakeDataBin, fakeData := makeSignedDataBytes(t, gen.ChainID, 5, outsiderAddr, outsiderPub, outsiderSigner, 3) + fakeHdrBin, _ := makeSignedHeaderBytes(t, gen.ChainID, 5, outsiderAddr, outsiderPub, outsiderSigner, nil, &fakeData.Data, nil) + + r.setSyncedHeaderProvider(func(height uint64) (*types.SignedHeader, bool, error) { + return hdr, height <= 5, nil + }) + + // A self-consistent block from an outsider for a height the node holds. + require.Empty(t, r.processBlobs(context.Background(), [][]byte{fakeHdrBin, fakeDataBin}, 10)) + _, headerIncluded := r.cache.GetHeaderDAIncludedByHeight(5) + _, dataIncluded := r.cache.GetDataDAIncludedByHeight(5) + require.False(t, headerIncluded) + require.False(t, dataIncluded) + require.Empty(t, r.pendingHeaders) + require.Empty(t, r.pendingData) + + // The stored block is still reported; the syncer skips it as already processed. + events := r.processBlobs(context.Background(), [][]byte{hdrBin, dataBin}, 11) + require.Len(t, events, 1) + require.Equal(t, hdr.Hash().String(), events[0].Header.Hash().String()) + daHeight, headerIncluded := r.cache.GetHeaderDAIncludedByHash(hdr.Hash().String()) + require.True(t, headerIncluded) + require.Equal(t, uint64(11), daHeight) + _, dataIncluded = r.cache.GetDataDAIncludedByHash(data.Data.DACommitment().String()) + require.True(t, dataIncluded) +} + +// resignHeader reposts a real header under another key: same header hash and +// header signature, different signer. It returns the copy as a legacy blob and +// wrapped in an envelope that key signed. +func resignHeader(t *testing.T, real *types.SignedHeader, pub crypto.PubKey, signer signerpkg.Signer) [][]byte { + t.Helper() + addr, err := signer.GetAddress() + require.NoError(t, err) + copied := &types.SignedHeader{Header: real.Header, Signature: real.Signature, Signer: types.Signer{PubKey: pub, Address: addr}} + payload, err := copied.MarshalBinary() + require.NoError(t, err) + envelopeSig, err := signer.Sign(t.Context(), payload) + require.NoError(t, err) + envelope, err := copied.MarshalDAEnvelope(envelopeSig) + require.NoError(t, err) + return [][]byte{payload, envelope} +} + +func TestDARetriever_ProcessBlobs_ResignedHeaderCopyDoesNotReplaceRealHeader(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + copies := resignHeader(t, hdr, outsiderPub, outsiderSigner) + + require.Empty(t, r.processBlobs(context.Background(), append(copies, dataBin), 10)) + require.False(t, r.strictMode) + + events := r.processBlobs(context.Background(), [][]byte{hdrBin}, 11) + require.Len(t, events, 1) + require.Equal(t, addr, types.KeyAddress(events[0].Header.Signer.PubKey)) +} + +func TestDARetriever_ProcessBlobs_SyncedHeightIgnoresResignedHeaderCopy(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + _, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, nil, nil) + r.setSyncedHeaderProvider(func(height uint64) (*types.SignedHeader, bool, error) { + return hdr, height <= 5, nil + }) + + require.Empty(t, r.processBlobs(context.Background(), resignHeader(t, hdr, outsiderPub, outsiderSigner), 10)) + _, included := r.cache.GetHeaderDAIncludedByHeight(5) + require.False(t, included) + require.False(t, r.strictMode) +} + +func TestDARetriever_ProcessBlobs_SyncedHeightRejectsDataWithWrongMetadata(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + _, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + _, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + r.setSyncedHeaderProvider(func(height uint64) (*types.SignedHeader, bool, error) { + return hdr, height <= 5, nil + }) + + // Same transactions as the stored block, different timestamp. + wrongTimeBin, _ := makeSignedDataBytesWithTime(t, gen.ChainID, 5, nil, outsiderPub, outsiderSigner, 2, uint64(data.Time().UnixNano())+1) + require.Empty(t, r.processBlobs(context.Background(), [][]byte{wrongTimeBin}, 10)) + _, included := r.cache.GetDataDAIncludedByHeight(5) + require.False(t, included) +} + +func TestDARetriever_ProcessBlobs_PrefersDataSignedByProposer(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + hdrBin, _ := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + + // The real transactions and metadata the header checks, with a forged LastDataHash. + forged := types.Data{Metadata: &types.Metadata{ChainID: gen.ChainID, Height: 5, Time: uint64(data.Time().UnixNano()), LastDataHash: types.Hash("forged")}, Txs: data.Txs} + payload, err := forged.MarshalBinary() + require.NoError(t, err) + sig, err := outsiderSigner.Sign(t.Context(), payload) + require.NoError(t, err) + forgedBin, err := (&types.SignedData{Data: forged, Signature: sig, Signer: types.Signer{PubKey: outsiderPub}}).MarshalBinary() + require.NoError(t, err) + + events := r.processBlobs(context.Background(), [][]byte{forgedBin, dataBin, hdrBin}, 10) + require.Len(t, events, 1) + require.Equal(t, data.Data.Hash(), events[0].Data.Hash()) +} + +func TestDARetriever_ProcessBlobs_KeepsCandidatesWhenSyncedHeaderLoadFails(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, nil, nil) + loadErr := errors.New("store unavailable") + r.setSyncedHeaderProvider(func(uint64) (*types.SignedHeader, bool, error) { + return hdr, true, loadErr + }) + + require.Empty(t, r.processBlobs(context.Background(), [][]byte{hdrBin}, 10)) + _, included := r.cache.GetHeaderDAIncludedByHeight(5) + require.False(t, included) + + loadErr = nil + require.Len(t, r.processBlobs(context.Background(), nil, 11), 1) + _, included = r.cache.GetHeaderDAIncludedByHeight(5) + require.True(t, included) +} + func TestDARetriever_ProcessBlobs_CrossDAHeightMatching(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) @@ -348,9 +557,10 @@ func TestDARetriever_ProcessBlobs_KeepsDataForLaterHeaderAfterCandidateEvent(t * correctHeaderBin, correctHeader := makeSignedHeaderBytes(t, gen.ChainID, 5, expectedAddr, expectedPub, expectedSigner, nil, &data.Data, nil) events := r.processBlobs(context.Background(), [][]byte{wrongHeaderBin, dataBin}, 100) - require.Len(t, events, 1) - require.Equal(t, wrongHeader.Hash().String(), events[0].Header.Hash().String()) - require.Contains(t, r.pendingData, uint64(5), "data should stay available until the candidate block is accepted") + require.Empty(t, events, "a header from an unexpected proposer must not be emitted") + _, wrongIncluded := r.cache.GetHeaderDAIncludedByHash(wrongHeader.Hash().String()) + require.False(t, wrongIncluded, "a header from an unexpected proposer must not be marked DA included") + require.Contains(t, r.pendingData, uint64(5), "data should stay available for the expected proposer's header") events = r.processBlobs(context.Background(), [][]byte{correctHeaderBin}, 101) require.Len(t, events, 1) @@ -371,18 +581,16 @@ func TestDARetriever_ProcessBlobs_RejectsUnexpectedProposerBeforePendingHeader(t return expectedAddr, true }) - _, data := makeSignedDataBytes(t, gen.ChainID, 5, expectedAddr, expectedPub, expectedSigner, 1) + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, expectedAddr, expectedPub, expectedSigner, 1) wrongHeaderBin, _ := makeSignedHeaderBytes(t, gen.ChainID, 5, wrongAddr, wrongPub, wrongSigner, nil, &data.Data, nil) correctHeaderBin, correctHeader := makeSignedHeaderBytes(t, gen.ChainID, 5, expectedAddr, expectedPub, expectedSigner, nil, &data.Data, nil) events := r.processBlobs(context.Background(), [][]byte{wrongHeaderBin}, 100) require.Empty(t, events) - require.NotContains(t, r.pendingHeaders, uint64(5), "unexpected proposer must not occupy the pending header slot") - events = r.processBlobs(context.Background(), [][]byte{correctHeaderBin}, 101) - require.Empty(t, events) - require.Contains(t, r.pendingHeaders, uint64(5), "expected proposer should be accepted as pending while data is missing") - require.Equal(t, correctHeader.Hash().String(), r.pendingHeaders[5].Hash().String()) + events = r.processBlobs(context.Background(), [][]byte{correctHeaderBin, dataBin}, 101) + require.Len(t, events, 1, "an unexpected proposer's header must not block the expected one") + require.Equal(t, correctHeader.Hash().String(), events[0].Header.Hash().String()) } func TestDARetriever_ProcessBlobs_ReplacesFutureHeaderOnceExpectedProposerIsKnown(t *testing.T) { @@ -405,7 +613,7 @@ func TestDARetriever_ProcessBlobs_ReplacesFutureHeaderOnceExpectedProposerIsKnow events := r.processBlobs(context.Background(), [][]byte{wrongHeaderBin}, 100) require.Empty(t, events) - require.Equal(t, wrongHeader.Hash().String(), r.pendingHeaders[5].Hash().String()) + require.Equal(t, wrongHeader.Hash().String(), r.pendingHeaders[5][0].header.Hash().String()) expectedKnown = true events = r.processBlobs(context.Background(), [][]byte{correctHeaderBin, dataBin}, 101) diff --git a/block/internal/syncing/syncer.go b/block/internal/syncing/syncer.go index aba3d8e44a..70371d7565 100644 --- a/block/internal/syncing/syncer.go +++ b/block/internal/syncing/syncer.go @@ -14,6 +14,7 @@ import ( "time" "github.com/celestiaorg/go-header" + ds "github.com/ipfs/go-datastore" "github.com/rs/zerolog" "github.com/evstack/ev-node/block/internal/cache" @@ -185,6 +186,8 @@ func (s *Syncer) Start(ctx context.Context) (err error) { // Initialize DA-specific handlers only when DA is configured. daRetriever := NewDARetriever(s.daClient, s.cache, s.genesis, s.logger) daRetriever.setExpectedProposerProvider(s.expectedProposerForHeight) + daRetriever.setSyncedHeaderProvider(s.syncedHeader) + daRetriever.setSignatureProvider(s.options.SyncNodeSignatureBytesProvider) s.daRetriever = daRetriever if s.config.Instrumentation.IsTracingEnabled() { s.daRetriever = WithTracingDARetriever(s.daRetriever) @@ -309,14 +312,32 @@ func (s *Syncer) SetLastState(state types.State) { s.lastState.Store(&state) } +// expectedProposerForHeight predicts the proposer of a height that is not +// synced yet. The prediction is wrong for heights past a proposer rotation +// that has not been applied; it corrects itself once the rotation block is. func (s *Syncer) expectedProposerForHeight(height uint64) ([]byte, bool) { state := s.getLastState() - if height != state.LastBlockHeight+1 || len(state.NextProposerAddress) == 0 { + if height <= state.LastBlockHeight || len(state.NextProposerAddress) == 0 { return nil, false } return state.NextProposerAddress, true } +func (s *Syncer) syncedHeader(height uint64) (*types.SignedHeader, bool, error) { + if height > s.getLastState().LastBlockHeight { + return nil, false, nil + } + header, err := s.store.GetHeader(s.ctx, height) + if errors.Is(err, ds.ErrNotFound) { + // pruned, which only happens once the height is DA included + return nil, true, nil + } + if err != nil { + return nil, true, err + } + return header, true, nil +} + // initializeState loads the current sync state func (s *Syncer) initializeState() error { // Load state from store diff --git a/block/internal/syncing/syncer_test.go b/block/internal/syncing/syncer_test.go index e78a8771c6..5c928f0f59 100644 --- a/block/internal/syncing/syncer_test.go +++ b/block/internal/syncing/syncer_test.go @@ -215,7 +215,7 @@ func TestSyncer_ValidateBlock_UsesStateNextProposer(t *testing.T) { require.Contains(t, err.Error(), "unexpected proposer") } -func TestSyncer_ExpectedProposerForHeight_OnlyNextHeight(t *testing.T) { +func TestSyncer_ExpectedProposerForHeight_OnlyFutureHeights(t *testing.T) { addr, _, _ := buildSyncTestSigner(t) s := &Syncer{lastState: &atomic.Pointer[types.State]{}} s.SetLastState(types.State{ @@ -227,7 +227,11 @@ func TestSyncer_ExpectedProposerForHeight_OnlyNextHeight(t *testing.T) { require.True(t, ok) require.Equal(t, addr, got) - _, ok = s.expectedProposerForHeight(6) + got, ok = s.expectedProposerForHeight(6) + require.True(t, ok) + require.Equal(t, addr, got) + + _, ok = s.expectedProposerForHeight(4) require.False(t, ok) } @@ -602,7 +606,7 @@ func TestProcessHeightEvent_SyncsAndUpdatesState(t *testing.T) { lastState := s.getLastState() data := makeData(gen.ChainID, 1, 0) _, hdr := makeSignedHeaderBytes(t, gen.ChainID, 1, addr, pub, signer, lastState.AppHash, data, nil) - daRetriever := &daRetriever{pendingData: map[uint64]*types.Data{1: data}} + daRetriever := &daRetriever{pendingData: map[uint64][]pendingData{1: {{data: data}}}} s.daRetriever = daRetriever // Expect ExecuteTxs call for height 1 From 999b56c524cf74b756377343c4309d14b417ade4 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Wed, 18 Nov 2026 13:57:57 +0100 Subject: [PATCH 02/11] test(e2e): cover DA blobs posted by a non-sequencer key --- test/e2e/da_outsider_blobs_e2e_test.go | 323 +++++++++++++++++++++++++ 1 file changed, 323 insertions(+) create mode 100644 test/e2e/da_outsider_blobs_e2e_test.go diff --git a/test/e2e/da_outsider_blobs_e2e_test.go b/test/e2e/da_outsider_blobs_e2e_test.go new file mode 100644 index 0000000000..b589fe2669 --- /dev/null +++ b/test/e2e/da_outsider_blobs_e2e_test.go @@ -0,0 +1,323 @@ +//go:build e2e && evm + +package e2e + +import ( + "context" + "crypto/rand" + "encoding/binary" + "flag" + "fmt" + "net" + "os" + "path/filepath" + "testing" + "time" + + "github.com/celestiaorg/go-square/v3/share" + "github.com/libp2p/go-libp2p/core/crypto" + "github.com/stretchr/testify/require" + + blobrpc "github.com/evstack/ev-node/pkg/da/jsonrpc" + datypes "github.com/evstack/ev-node/pkg/da/types" + nodeclient "github.com/evstack/ev-node/pkg/rpc/client" + "github.com/evstack/ev-node/pkg/signer" + "github.com/evstack/ev-node/pkg/signer/noop" + "github.com/evstack/ev-node/pkg/store" + "github.com/evstack/ev-node/types" +) + +// These tests post blobs signed by a key that is not the sequencer's into the +// chain's DA namespaces, and check that full nodes are not affected by them. + +const ( + outsiderChainID = "testing" + outsiderHeaderNS = "outsider-hdr-ns" + outsiderDataNS = "outsider-data-ns" +) + +// A full node syncing only from DA must not stall when an outsider pre-posts +// signed data for a future height. +func TestDAOutsiderDataDoesNotStallDASync(t *testing.T) { + nw := startOutsiderNet(t) + target := nw.seqHeight(t) + 50 + + nw.outsider.postData(t, nw.daAddr, target) + + p2pNode := nw.startFullNode(t, nw.daAddr, true) + daNode := nw.startFullNode(t, nw.daAddr, false) + + nw.awaitHeight(t, nw.seqRPC, target+20, 60*time.Second) + nw.awaitHeight(t, p2pNode, target+5, 30*time.Second) + nw.awaitHeight(t, daNode, target+5, 30*time.Second) +} + +// A full node syncing only from DA must not stall when an outsider pre-posts +// headers for future heights. +func TestDAOutsiderHeaderDoesNotStallDASync(t *testing.T) { + nw := startOutsiderNet(t) + from := nw.seqHeight(t) + 50 + const squatted = 10 + + for h := from; h < from+squatted; h++ { + nw.outsider.postPhantomHeader(t, nw.daAddr, h) + } + + daNode := nw.startFullNode(t, nw.daAddr, false) + + nw.awaitHeight(t, nw.seqRPC, from+squatted+20, 60*time.Second) + nw.awaitHeight(t, daNode, from+squatted+5, 30*time.Second) +} + +// A full node must not report blocks as DA-included when the sequencer never +// posted them to the DA layer the node follows. The sequencer submits to its +// own DA; the full node syncs blocks over P2P and follows a second DA that +// only the outsider posts to. +func TestDAOutsiderBlobsDoNotForgeDAInclusion(t *testing.T) { + nw := startOutsiderNet(t) + followedDA := nw.startLocalDA(t) + + node := nw.startFullNode(t, followedDA, true) + nw.awaitHeight(t, node, 20, 30*time.Second) + synced := nw.height(t, node) + + // Every height is at or below the node's height, so none is its "next" + // height: the retriever skips the proposer check, and the syncer drops the + // pair as already processed without validating it. + for h := uint64(1); h <= synced; h++ { + nw.outsider.postBlock(t, followedDA, h) + } + + time.Sleep(10 * time.Second) + if got := nw.daIncludedHeight(t, node); got > 0 { + t.Fatalf("full node reported DA-included height %d (outsider covered 1..%d) although the sequencer posted nothing to its DA", got, synced) + } +} + +type outsiderNet struct { + sut *SystemUnderTest + workDir string + daAddr string + seqHome string + seqRPC string + seqP2P string + + outsider *outsider +} + +func startOutsiderNet(t *testing.T) *outsiderNet { + t.Helper() + flag.Parse() + n := &outsiderNet{sut: NewSystemUnderTest(t), workDir: t.TempDir(), outsider: newOutsider(t)} + n.daAddr = n.startLocalDA(t) + + n.seqHome = filepath.Join(n.workDir, "sequencer") + passphrase := filepath.Join(n.workDir, "passphrase.txt") + require.NoError(t, os.WriteFile(passphrase, []byte("12345678"), 0o600)) + + out, err := n.sut.RunCmd(binaryPath, "init", + "--home="+n.seqHome, + "--chain_id="+outsiderChainID, + "--evnode.node.aggregator", + "--evnode.signer.passphrase_file="+passphrase, + ) + require.NoError(t, err, out) + + rpcPort, p2pPort := mustGetAvailablePort(t), mustGetAvailablePort(t) + n.seqRPC = fmt.Sprintf("http://127.0.0.1:%d", rpcPort) + n.seqP2P = fmt.Sprintf("/ip4/127.0.0.1/tcp/%d/p2p/%s", p2pPort, NodeID(t, n.seqHome)) + n.sut.ExecCmdWithLogPrefix("sequencer", binaryPath, "start", + "--home="+n.seqHome, + "--evnode.node.aggregator", + "--evnode.signer.passphrase_file="+passphrase, + "--evnode.node.block_time=100ms", + "--evnode.da.block_time=500ms", + "--evnode.da.address="+n.daAddr, + "--evnode.da.namespace="+outsiderHeaderNS, + "--evnode.da.data_namespace="+outsiderDataNS, + fmt.Sprintf("--evnode.rpc.address=127.0.0.1:%d", rpcPort), + fmt.Sprintf("--evnode.p2p.listen_address=/ip4/127.0.0.1/tcp/%d", p2pPort), + fmt.Sprintf("--kv-endpoint=127.0.0.1:%d", mustGetAvailablePort(t)), + ) + n.sut.AwaitNodeUp(t, n.seqRPC, 10*time.Second) + n.awaitHeight(t, n.seqRPC, 3, 10*time.Second) + return n +} + +func (n *outsiderNet) startLocalDA(t *testing.T) string { + t.Helper() + port := mustGetAvailablePort(t) + n.sut.ExecCmdWithLogPrefix(fmt.Sprintf("local-da-%d", port), filepath.Join(filepath.Dir(binaryPath), "local-da"), "-port", fmt.Sprint(port)) + require.Eventually(t, func() bool { + conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + if err != nil { + return false + } + conn.Close() + return true + }, 5*time.Second, 100*time.Millisecond) + return fmt.Sprintf("http://127.0.0.1:%d", port) +} + +// startFullNode starts a full node following daAddr, peered with the sequencer +// over P2P only when withP2P is set. It returns the node's RPC URL. +func (n *outsiderNet) startFullNode(t *testing.T, daAddr string, withP2P bool) string { + t.Helper() + rpcPort, p2pPort := mustGetAvailablePort(t), mustGetAvailablePort(t) + home := filepath.Join(n.workDir, fmt.Sprintf("fullnode-%d", rpcPort)) + out, err := n.sut.RunCmd(binaryPath, "init", "--home="+home, "--chain_id="+outsiderChainID) + require.NoError(t, err, out) + MustCopyFile(t, filepath.Join(n.seqHome, "config", "genesis.json"), filepath.Join(home, "config", "genesis.json")) + + args := []string{"start", + "--home=" + home, + "--evnode.da.address=" + daAddr, + "--evnode.da.namespace=" + outsiderHeaderNS, + "--evnode.da.data_namespace=" + outsiderDataNS, + "--evnode.da.block_time=500ms", + "--evnode.log.level=debug", + fmt.Sprintf("--evnode.rpc.address=127.0.0.1:%d", rpcPort), + fmt.Sprintf("--evnode.p2p.listen_address=/ip4/127.0.0.1/tcp/%d", p2pPort), + fmt.Sprintf("--kv-endpoint=127.0.0.1:%d", mustGetAvailablePort(t)), + } + if withP2P { + args = append(args, "--evnode.p2p.peers="+n.seqP2P) + } + rpc := fmt.Sprintf("http://127.0.0.1:%d", rpcPort) + n.sut.ExecCmdWithLogPrefix(fmt.Sprintf("fullnode-%d", rpcPort), binaryPath, args...) + n.sut.AwaitNodeLive(t, rpc, 10*time.Second) + return rpc +} + +func (n *outsiderNet) height(t *testing.T, rpc string) uint64 { + t.Helper() + state, err := nodeclient.NewClient(rpc).GetState(t.Context()) + if err != nil { + return 0 + } + return state.LastBlockHeight +} + +func (n *outsiderNet) seqHeight(t *testing.T) uint64 { return n.height(t, n.seqRPC) } + +func (n *outsiderNet) awaitHeight(t *testing.T, rpc string, want uint64, timeout time.Duration) { + t.Helper() + for deadline := time.Now().Add(timeout); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) { + if n.height(t, rpc) >= want { + return + } + } + t.Fatalf("%s stuck at height %d, want >= %d (sequencer at %d)", rpc, n.height(t, rpc), want, n.seqHeight(t)) +} + +func (n *outsiderNet) daIncludedHeight(t *testing.T, rpc string) uint64 { + t.Helper() + bz, err := nodeclient.NewClient(rpc).GetMetadata(t.Context(), store.DAIncludedHeightKey) + if err != nil || len(bz) != 8 { + return 0 + } + return binary.LittleEndian.Uint64(bz) +} + +type outsider struct { + signer signer.Signer + pub crypto.PubKey + addr []byte +} + +func newOutsider(t *testing.T) *outsider { + t.Helper() + priv, pub, err := crypto.GenerateEd25519Key(rand.Reader) + require.NoError(t, err) + s, err := noop.NewNoopSigner(priv) + require.NoError(t, err) + addr, err := s.GetAddress() + require.NoError(t, err) + return &outsider{signer: s, pub: pub, addr: addr} +} + +// postData posts outsider-signed data with valid metadata for height. +func (o *outsider) postData(t *testing.T, daAddr string, height uint64) { + t.Helper() + submitBlobs(t, daAddr, o.dataBlob(t, o.data(height))) +} + +// postBlock posts an outsider header and the data its DataHash commits to. +func (o *outsider) postBlock(t *testing.T, daAddr string, height uint64) { + t.Helper() + d := o.data(height) + submitBlobs(t, daAddr, o.headerBlob(t, height, d.Time(), d.DACommitment()), o.dataBlob(t, d)) +} + +// postPhantomHeader posts an outsider header for height whose DataHash points +// at data that never lands. +func (o *outsider) postPhantomHeader(t *testing.T, daAddr string, height uint64) { + t.Helper() + phantom := types.Data{Txs: types.Txs{types.Tx(fmt.Sprintf("phantom-%d", height))}} + submitBlobs(t, daAddr, o.headerBlob(t, height, time.Now(), phantom.DACommitment())) +} + +func (o *outsider) data(height uint64) types.Data { + return types.Data{ + Metadata: &types.Metadata{ChainID: outsiderChainID, Height: height, Time: uint64(time.Now().UnixNano())}, + Txs: types.Txs{types.Tx(fmt.Sprintf("outsider-%d", height))}, + } +} + +func (o *outsider) dataBlob(t *testing.T, d types.Data) *blobrpc.Blob { + t.Helper() + payload, err := d.MarshalBinary() + require.NoError(t, err) + sig, err := o.signer.Sign(t.Context(), payload) + require.NoError(t, err) + sd := types.SignedData{Data: d, Signature: sig, Signer: types.Signer{PubKey: o.pub, Address: o.addr}} + bz, err := sd.MarshalBinary() + require.NoError(t, err) + return newBlob(t, outsiderDataNS, bz) +} + +// headerBlob builds an outsider header wrapped in a DA envelope signed by the outsider. +func (o *outsider) headerBlob(t *testing.T, height uint64, ts time.Time, dataHash types.Hash) *blobrpc.Blob { + t.Helper() + h := types.SignedHeader{ + Header: types.Header{ + BaseHeader: types.BaseHeader{ChainID: outsiderChainID, Height: height, Time: uint64(ts.UnixNano())}, + DataHash: dataHash, + ProposerAddress: o.addr, + }, + Signer: types.Signer{PubKey: o.pub, Address: o.addr}, + } + sigBytes, err := types.DefaultAggregatorNodeSignatureBytesProvider(&h.Header) + require.NoError(t, err) + h.Signature, err = o.signer.Sign(t.Context(), sigBytes) + require.NoError(t, err) + + payload, err := h.MarshalBinary() + require.NoError(t, err) + envelopeSig, err := o.signer.Sign(t.Context(), payload) + require.NoError(t, err) + bz, err := h.MarshalDAEnvelope(envelopeSig) + require.NoError(t, err) + return newBlob(t, outsiderHeaderNS, bz) +} + +func newBlob(t *testing.T, namespace string, bz []byte) *blobrpc.Blob { + t.Helper() + ns, err := share.NewNamespaceFromBytes(datypes.NamespaceFromString(namespace).Bytes()) + require.NoError(t, err) + blob, err := blobrpc.NewBlobV0(ns, bz) + require.NoError(t, err) + return blob +} + +// submitBlobs posts blobs in a single DA submission, so they land at one DA height. +func submitBlobs(t *testing.T, daAddr string, blobs ...*blobrpc.Blob) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + c, err := blobrpc.NewClient(ctx, daAddr, "", "") + require.NoError(t, err) + defer c.Close() + _, err = c.Blob.Submit(ctx, blobs, nil) + require.NoError(t, err) +} From 929b6d14cb8bf2ec93846b42e96100013c3ffc05 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 13:12:36 +0100 Subject: [PATCH 03/11] test: rename DA outsider tests to unexpected-signer naming Renames the e2e file to da_blob_sync_e2e_test.go and the tests and helpers covering DA blobs signed by a key other than the expected proposer. No behaviour change. --- block/internal/syncing/da_retriever.go | 2 +- block/internal/syncing/da_retriever_test.go | 56 +++++----- ...s_e2e_test.go => da_blob_sync_e2e_test.go} | 100 +++++++++--------- 3 files changed, 79 insertions(+), 79 deletions(-) rename test/e2e/{da_outsider_blobs_e2e_test.go => da_blob_sync_e2e_test.go} (72%) diff --git a/block/internal/syncing/da_retriever.go b/block/internal/syncing/da_retriever.go index 4a8496d676..dc92f3de6d 100644 --- a/block/internal/syncing/da_retriever.go +++ b/block/internal/syncing/da_retriever.go @@ -69,7 +69,7 @@ type daRetriever struct { // candidate: it is not marked DA included and does not displace another // blob until it is authenticated. Candidates for future heights are kept // without a cap; growing them costs one paid blob per entry, and a cap - // would let an outsider crowd out the header of a newly rotated proposer. + // would let another key crowd out the header of a newly rotated proposer. // Transient: rebuilt from DA on restart. pendingHeaders map[uint64][]pendingHeader pendingData map[uint64][]pendingData diff --git a/block/internal/syncing/da_retriever_test.go b/block/internal/syncing/da_retriever_test.go index d336ff8304..0b0c250aab 100644 --- a/block/internal/syncing/da_retriever_test.go +++ b/block/internal/syncing/da_retriever_test.go @@ -304,14 +304,14 @@ func TestDARetriever_RetrieveFromDA_TwoNamespaces_Success(t *testing.T) { assert.Equal(t, uint64(9), events[0].Data.Height()) } -func TestDARetriever_ProcessBlobs_OutsiderDataDoesNotClaimHeight(t *testing.T) { +func TestDARetriever_ProcessBlobs_UnexpectedSignerDataDoesNotClaimHeight(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) - _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + _, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) - outsiderBin, _ := makeSignedDataBytes(t, gen.ChainID, 5, nil, outsiderPub, outsiderSigner, 3) - require.Empty(t, r.processBlobs(context.Background(), [][]byte{outsiderBin}, 10)) + otherBin, _ := makeSignedDataBytes(t, gen.ChainID, 5, nil, otherPub, otherSigner, 3) + require.Empty(t, r.processBlobs(context.Background(), [][]byte{otherBin}, 10)) dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) @@ -322,34 +322,34 @@ func TestDARetriever_ProcessBlobs_OutsiderDataDoesNotClaimHeight(t *testing.T) { require.NoError(t, types.Validate(hdr, events[0].Data)) } -func TestDARetriever_ProcessBlobs_OutsiderDataDoesNotReplaceEmptyData(t *testing.T) { +func TestDARetriever_ProcessBlobs_UnexpectedSignerDataDoesNotReplaceEmptyData(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) - _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + _, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) - outsiderBin, _ := makeSignedDataBytes(t, gen.ChainID, 5, nil, outsiderPub, outsiderSigner, 3) + otherBin, _ := makeSignedDataBytes(t, gen.ChainID, 5, nil, otherPub, otherSigner, 3) hdrBin, _ := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, nil, nil) - events := r.processBlobs(context.Background(), [][]byte{outsiderBin, hdrBin}, 10) + events := r.processBlobs(context.Background(), [][]byte{otherBin, hdrBin}, 10) require.Len(t, events, 1) require.Empty(t, events[0].Data.Txs) } -func TestDARetriever_ProcessBlobs_OutsiderHeaderDoesNotClaimHeight(t *testing.T) { +func TestDARetriever_ProcessBlobs_UnexpectedSignerHeaderDoesNotClaimHeight(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) - outsiderAddr, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + otherAddr, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) - // Signed by the outsider, and a second one that only copies the proposer address. - outsiderBin, outsiderHdr := makeSignedHeaderBytes(t, gen.ChainID, 5, outsiderAddr, outsiderPub, outsiderSigner, nil, &data.Data, nil) - spoofedBin, spoofedHdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, outsiderPub, outsiderSigner, nil, &data.Data, nil) + // Signed by another key, and a second one that only copies the proposer address. + otherBin, otherHdr := makeSignedHeaderBytes(t, gen.ChainID, 5, otherAddr, otherPub, otherSigner, nil, &data.Data, nil) + spoofedBin, spoofedHdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, otherPub, otherSigner, nil, &data.Data, nil) - require.Empty(t, r.processBlobs(context.Background(), [][]byte{outsiderBin, spoofedBin, dataBin}, 10)) - for _, h := range []*types.SignedHeader{outsiderHdr, spoofedHdr} { + require.Empty(t, r.processBlobs(context.Background(), [][]byte{otherBin, spoofedBin, dataBin}, 10)) + for _, h := range []*types.SignedHeader{otherHdr, spoofedHdr} { _, included := r.cache.GetHeaderDAIncludedByHash(h.Hash().String()) require.False(t, included) } @@ -361,20 +361,20 @@ func TestDARetriever_ProcessBlobs_OutsiderHeaderDoesNotClaimHeight(t *testing.T) func TestDARetriever_ProcessBlobs_SyncedHeightMarksOnlyStoredBlock(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) - outsiderAddr, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + otherAddr, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) - fakeDataBin, fakeData := makeSignedDataBytes(t, gen.ChainID, 5, outsiderAddr, outsiderPub, outsiderSigner, 3) - fakeHdrBin, _ := makeSignedHeaderBytes(t, gen.ChainID, 5, outsiderAddr, outsiderPub, outsiderSigner, nil, &fakeData.Data, nil) + fakeDataBin, fakeData := makeSignedDataBytes(t, gen.ChainID, 5, otherAddr, otherPub, otherSigner, 3) + fakeHdrBin, _ := makeSignedHeaderBytes(t, gen.ChainID, 5, otherAddr, otherPub, otherSigner, nil, &fakeData.Data, nil) r.setSyncedHeaderProvider(func(height uint64) (*types.SignedHeader, bool, error) { return hdr, height <= 5, nil }) - // A self-consistent block from an outsider for a height the node holds. + // A self-consistent block signed by another key for a height the node holds. require.Empty(t, r.processBlobs(context.Background(), [][]byte{fakeHdrBin, fakeDataBin}, 10)) _, headerIncluded := r.cache.GetHeaderDAIncludedByHeight(5) _, dataIncluded := r.cache.GetDataDAIncludedByHeight(5) @@ -413,13 +413,13 @@ func resignHeader(t *testing.T, real *types.SignedHeader, pub crypto.PubKey, sig func TestDARetriever_ProcessBlobs_ResignedHeaderCopyDoesNotReplaceRealHeader(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) - _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + _, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) - copies := resignHeader(t, hdr, outsiderPub, outsiderSigner) + copies := resignHeader(t, hdr, otherPub, otherSigner) require.Empty(t, r.processBlobs(context.Background(), append(copies, dataBin), 10)) require.False(t, r.strictMode) @@ -431,7 +431,7 @@ func TestDARetriever_ProcessBlobs_ResignedHeaderCopyDoesNotReplaceRealHeader(t * func TestDARetriever_ProcessBlobs_SyncedHeightIgnoresResignedHeaderCopy(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) - _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + _, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) @@ -440,7 +440,7 @@ func TestDARetriever_ProcessBlobs_SyncedHeightIgnoresResignedHeaderCopy(t *testi return hdr, height <= 5, nil }) - require.Empty(t, r.processBlobs(context.Background(), resignHeader(t, hdr, outsiderPub, outsiderSigner), 10)) + require.Empty(t, r.processBlobs(context.Background(), resignHeader(t, hdr, otherPub, otherSigner), 10)) _, included := r.cache.GetHeaderDAIncludedByHeight(5) require.False(t, included) require.False(t, r.strictMode) @@ -448,7 +448,7 @@ func TestDARetriever_ProcessBlobs_SyncedHeightIgnoresResignedHeaderCopy(t *testi func TestDARetriever_ProcessBlobs_SyncedHeightRejectsDataWithWrongMetadata(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) - _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + _, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) @@ -459,7 +459,7 @@ func TestDARetriever_ProcessBlobs_SyncedHeightRejectsDataWithWrongMetadata(t *te }) // Same transactions as the stored block, different timestamp. - wrongTimeBin, _ := makeSignedDataBytesWithTime(t, gen.ChainID, 5, nil, outsiderPub, outsiderSigner, 2, uint64(data.Time().UnixNano())+1) + wrongTimeBin, _ := makeSignedDataBytesWithTime(t, gen.ChainID, 5, nil, otherPub, otherSigner, 2, uint64(data.Time().UnixNano())+1) require.Empty(t, r.processBlobs(context.Background(), [][]byte{wrongTimeBin}, 10)) _, included := r.cache.GetDataDAIncludedByHeight(5) require.False(t, included) @@ -467,7 +467,7 @@ func TestDARetriever_ProcessBlobs_SyncedHeightRejectsDataWithWrongMetadata(t *te func TestDARetriever_ProcessBlobs_PrefersDataSignedByProposer(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) - _, outsiderPub, outsiderSigner := buildSyncTestSigner(t) + _, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) @@ -478,9 +478,9 @@ func TestDARetriever_ProcessBlobs_PrefersDataSignedByProposer(t *testing.T) { forged := types.Data{Metadata: &types.Metadata{ChainID: gen.ChainID, Height: 5, Time: uint64(data.Time().UnixNano()), LastDataHash: types.Hash("forged")}, Txs: data.Txs} payload, err := forged.MarshalBinary() require.NoError(t, err) - sig, err := outsiderSigner.Sign(t.Context(), payload) + sig, err := otherSigner.Sign(t.Context(), payload) require.NoError(t, err) - forgedBin, err := (&types.SignedData{Data: forged, Signature: sig, Signer: types.Signer{PubKey: outsiderPub}}).MarshalBinary() + forgedBin, err := (&types.SignedData{Data: forged, Signature: sig, Signer: types.Signer{PubKey: otherPub}}).MarshalBinary() require.NoError(t, err) events := r.processBlobs(context.Background(), [][]byte{forgedBin, dataBin, hdrBin}, 10) diff --git a/test/e2e/da_outsider_blobs_e2e_test.go b/test/e2e/da_blob_sync_e2e_test.go similarity index 72% rename from test/e2e/da_outsider_blobs_e2e_test.go rename to test/e2e/da_blob_sync_e2e_test.go index b589fe2669..9dc1307e73 100644 --- a/test/e2e/da_outsider_blobs_e2e_test.go +++ b/test/e2e/da_blob_sync_e2e_test.go @@ -31,18 +31,18 @@ import ( // chain's DA namespaces, and check that full nodes are not affected by them. const ( - outsiderChainID = "testing" - outsiderHeaderNS = "outsider-hdr-ns" - outsiderDataNS = "outsider-data-ns" + daSyncChainID = "testing" + daSyncHeaderNS = "da-sync-hdr-ns" + daSyncDataNS = "da-sync-data-ns" ) -// A full node syncing only from DA must not stall when an outsider pre-posts +// A full node syncing only from DA must not stall when another key pre-posts // signed data for a future height. -func TestDAOutsiderDataDoesNotStallDASync(t *testing.T) { - nw := startOutsiderNet(t) +func TestDASyncWithUnexpectedSignerData(t *testing.T) { + nw := startDASyncNet(t) target := nw.seqHeight(t) + 50 - nw.outsider.postData(t, nw.daAddr, target) + nw.other.postData(t, nw.daAddr, target) p2pNode := nw.startFullNode(t, nw.daAddr, true) daNode := nw.startFullNode(t, nw.daAddr, false) @@ -52,15 +52,15 @@ func TestDAOutsiderDataDoesNotStallDASync(t *testing.T) { nw.awaitHeight(t, daNode, target+5, 30*time.Second) } -// A full node syncing only from DA must not stall when an outsider pre-posts +// A full node syncing only from DA must not stall when another key pre-posts // headers for future heights. -func TestDAOutsiderHeaderDoesNotStallDASync(t *testing.T) { - nw := startOutsiderNet(t) +func TestDASyncWithUnexpectedSignerHeaders(t *testing.T) { + nw := startDASyncNet(t) from := nw.seqHeight(t) + 50 const squatted = 10 for h := from; h < from+squatted; h++ { - nw.outsider.postPhantomHeader(t, nw.daAddr, h) + nw.other.postPhantomHeader(t, nw.daAddr, h) } daNode := nw.startFullNode(t, nw.daAddr, false) @@ -72,9 +72,9 @@ func TestDAOutsiderHeaderDoesNotStallDASync(t *testing.T) { // A full node must not report blocks as DA-included when the sequencer never // posted them to the DA layer the node follows. The sequencer submits to its // own DA; the full node syncs blocks over P2P and follows a second DA that -// only the outsider posts to. -func TestDAOutsiderBlobsDoNotForgeDAInclusion(t *testing.T) { - nw := startOutsiderNet(t) +// only another key posts to. +func TestDAInclusionWithUnexpectedSignerBlobs(t *testing.T) { + nw := startDASyncNet(t) followedDA := nw.startLocalDA(t) node := nw.startFullNode(t, followedDA, true) @@ -85,16 +85,16 @@ func TestDAOutsiderBlobsDoNotForgeDAInclusion(t *testing.T) { // height: the retriever skips the proposer check, and the syncer drops the // pair as already processed without validating it. for h := uint64(1); h <= synced; h++ { - nw.outsider.postBlock(t, followedDA, h) + nw.other.postBlock(t, followedDA, h) } time.Sleep(10 * time.Second) if got := nw.daIncludedHeight(t, node); got > 0 { - t.Fatalf("full node reported DA-included height %d (outsider covered 1..%d) although the sequencer posted nothing to its DA", got, synced) + t.Fatalf("full node reported DA-included height %d (other signer covered 1..%d) although the sequencer posted nothing to its DA", got, synced) } } -type outsiderNet struct { +type daSyncNet struct { sut *SystemUnderTest workDir string daAddr string @@ -102,13 +102,13 @@ type outsiderNet struct { seqRPC string seqP2P string - outsider *outsider + other *otherSigner } -func startOutsiderNet(t *testing.T) *outsiderNet { +func startDASyncNet(t *testing.T) *daSyncNet { t.Helper() flag.Parse() - n := &outsiderNet{sut: NewSystemUnderTest(t), workDir: t.TempDir(), outsider: newOutsider(t)} + n := &daSyncNet{sut: NewSystemUnderTest(t), workDir: t.TempDir(), other: newOtherSigner(t)} n.daAddr = n.startLocalDA(t) n.seqHome = filepath.Join(n.workDir, "sequencer") @@ -117,7 +117,7 @@ func startOutsiderNet(t *testing.T) *outsiderNet { out, err := n.sut.RunCmd(binaryPath, "init", "--home="+n.seqHome, - "--chain_id="+outsiderChainID, + "--chain_id="+daSyncChainID, "--evnode.node.aggregator", "--evnode.signer.passphrase_file="+passphrase, ) @@ -133,8 +133,8 @@ func startOutsiderNet(t *testing.T) *outsiderNet { "--evnode.node.block_time=100ms", "--evnode.da.block_time=500ms", "--evnode.da.address="+n.daAddr, - "--evnode.da.namespace="+outsiderHeaderNS, - "--evnode.da.data_namespace="+outsiderDataNS, + "--evnode.da.namespace="+daSyncHeaderNS, + "--evnode.da.data_namespace="+daSyncDataNS, fmt.Sprintf("--evnode.rpc.address=127.0.0.1:%d", rpcPort), fmt.Sprintf("--evnode.p2p.listen_address=/ip4/127.0.0.1/tcp/%d", p2pPort), fmt.Sprintf("--kv-endpoint=127.0.0.1:%d", mustGetAvailablePort(t)), @@ -144,7 +144,7 @@ func startOutsiderNet(t *testing.T) *outsiderNet { return n } -func (n *outsiderNet) startLocalDA(t *testing.T) string { +func (n *daSyncNet) startLocalDA(t *testing.T) string { t.Helper() port := mustGetAvailablePort(t) n.sut.ExecCmdWithLogPrefix(fmt.Sprintf("local-da-%d", port), filepath.Join(filepath.Dir(binaryPath), "local-da"), "-port", fmt.Sprint(port)) @@ -161,19 +161,19 @@ func (n *outsiderNet) startLocalDA(t *testing.T) string { // startFullNode starts a full node following daAddr, peered with the sequencer // over P2P only when withP2P is set. It returns the node's RPC URL. -func (n *outsiderNet) startFullNode(t *testing.T, daAddr string, withP2P bool) string { +func (n *daSyncNet) startFullNode(t *testing.T, daAddr string, withP2P bool) string { t.Helper() rpcPort, p2pPort := mustGetAvailablePort(t), mustGetAvailablePort(t) home := filepath.Join(n.workDir, fmt.Sprintf("fullnode-%d", rpcPort)) - out, err := n.sut.RunCmd(binaryPath, "init", "--home="+home, "--chain_id="+outsiderChainID) + out, err := n.sut.RunCmd(binaryPath, "init", "--home="+home, "--chain_id="+daSyncChainID) require.NoError(t, err, out) MustCopyFile(t, filepath.Join(n.seqHome, "config", "genesis.json"), filepath.Join(home, "config", "genesis.json")) args := []string{"start", "--home=" + home, "--evnode.da.address=" + daAddr, - "--evnode.da.namespace=" + outsiderHeaderNS, - "--evnode.da.data_namespace=" + outsiderDataNS, + "--evnode.da.namespace=" + daSyncHeaderNS, + "--evnode.da.data_namespace=" + daSyncDataNS, "--evnode.da.block_time=500ms", "--evnode.log.level=debug", fmt.Sprintf("--evnode.rpc.address=127.0.0.1:%d", rpcPort), @@ -189,7 +189,7 @@ func (n *outsiderNet) startFullNode(t *testing.T, daAddr string, withP2P bool) s return rpc } -func (n *outsiderNet) height(t *testing.T, rpc string) uint64 { +func (n *daSyncNet) height(t *testing.T, rpc string) uint64 { t.Helper() state, err := nodeclient.NewClient(rpc).GetState(t.Context()) if err != nil { @@ -198,9 +198,9 @@ func (n *outsiderNet) height(t *testing.T, rpc string) uint64 { return state.LastBlockHeight } -func (n *outsiderNet) seqHeight(t *testing.T) uint64 { return n.height(t, n.seqRPC) } +func (n *daSyncNet) seqHeight(t *testing.T) uint64 { return n.height(t, n.seqRPC) } -func (n *outsiderNet) awaitHeight(t *testing.T, rpc string, want uint64, timeout time.Duration) { +func (n *daSyncNet) awaitHeight(t *testing.T, rpc string, want uint64, timeout time.Duration) { t.Helper() for deadline := time.Now().Add(timeout); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) { if n.height(t, rpc) >= want { @@ -210,7 +210,7 @@ func (n *outsiderNet) awaitHeight(t *testing.T, rpc string, want uint64, timeout t.Fatalf("%s stuck at height %d, want >= %d (sequencer at %d)", rpc, n.height(t, rpc), want, n.seqHeight(t)) } -func (n *outsiderNet) daIncludedHeight(t *testing.T, rpc string) uint64 { +func (n *daSyncNet) daIncludedHeight(t *testing.T, rpc string) uint64 { t.Helper() bz, err := nodeclient.NewClient(rpc).GetMetadata(t.Context(), store.DAIncludedHeightKey) if err != nil || len(bz) != 8 { @@ -219,13 +219,13 @@ func (n *outsiderNet) daIncludedHeight(t *testing.T, rpc string) uint64 { return binary.LittleEndian.Uint64(bz) } -type outsider struct { +type otherSigner struct { signer signer.Signer pub crypto.PubKey addr []byte } -func newOutsider(t *testing.T) *outsider { +func newOtherSigner(t *testing.T) *otherSigner { t.Helper() priv, pub, err := crypto.GenerateEd25519Key(rand.Reader) require.NoError(t, err) @@ -233,38 +233,38 @@ func newOutsider(t *testing.T) *outsider { require.NoError(t, err) addr, err := s.GetAddress() require.NoError(t, err) - return &outsider{signer: s, pub: pub, addr: addr} + return &otherSigner{signer: s, pub: pub, addr: addr} } -// postData posts outsider-signed data with valid metadata for height. -func (o *outsider) postData(t *testing.T, daAddr string, height uint64) { +// postData posts data signed by another key with valid metadata for height. +func (o *otherSigner) postData(t *testing.T, daAddr string, height uint64) { t.Helper() submitBlobs(t, daAddr, o.dataBlob(t, o.data(height))) } -// postBlock posts an outsider header and the data its DataHash commits to. -func (o *outsider) postBlock(t *testing.T, daAddr string, height uint64) { +// postBlock posts a header signed by another key and the data its DataHash commits to. +func (o *otherSigner) postBlock(t *testing.T, daAddr string, height uint64) { t.Helper() d := o.data(height) submitBlobs(t, daAddr, o.headerBlob(t, height, d.Time(), d.DACommitment()), o.dataBlob(t, d)) } -// postPhantomHeader posts an outsider header for height whose DataHash points +// postPhantomHeader posts a header signed by another key for height whose DataHash points // at data that never lands. -func (o *outsider) postPhantomHeader(t *testing.T, daAddr string, height uint64) { +func (o *otherSigner) postPhantomHeader(t *testing.T, daAddr string, height uint64) { t.Helper() phantom := types.Data{Txs: types.Txs{types.Tx(fmt.Sprintf("phantom-%d", height))}} submitBlobs(t, daAddr, o.headerBlob(t, height, time.Now(), phantom.DACommitment())) } -func (o *outsider) data(height uint64) types.Data { +func (o *otherSigner) data(height uint64) types.Data { return types.Data{ - Metadata: &types.Metadata{ChainID: outsiderChainID, Height: height, Time: uint64(time.Now().UnixNano())}, - Txs: types.Txs{types.Tx(fmt.Sprintf("outsider-%d", height))}, + Metadata: &types.Metadata{ChainID: daSyncChainID, Height: height, Time: uint64(time.Now().UnixNano())}, + Txs: types.Txs{types.Tx(fmt.Sprintf("other-%d", height))}, } } -func (o *outsider) dataBlob(t *testing.T, d types.Data) *blobrpc.Blob { +func (o *otherSigner) dataBlob(t *testing.T, d types.Data) *blobrpc.Blob { t.Helper() payload, err := d.MarshalBinary() require.NoError(t, err) @@ -273,15 +273,15 @@ func (o *outsider) dataBlob(t *testing.T, d types.Data) *blobrpc.Blob { sd := types.SignedData{Data: d, Signature: sig, Signer: types.Signer{PubKey: o.pub, Address: o.addr}} bz, err := sd.MarshalBinary() require.NoError(t, err) - return newBlob(t, outsiderDataNS, bz) + return newBlob(t, daSyncDataNS, bz) } -// headerBlob builds an outsider header wrapped in a DA envelope signed by the outsider. -func (o *outsider) headerBlob(t *testing.T, height uint64, ts time.Time, dataHash types.Hash) *blobrpc.Blob { +// headerBlob builds a header signed by another key, wrapped in a DA envelope signed by that key. +func (o *otherSigner) headerBlob(t *testing.T, height uint64, ts time.Time, dataHash types.Hash) *blobrpc.Blob { t.Helper() h := types.SignedHeader{ Header: types.Header{ - BaseHeader: types.BaseHeader{ChainID: outsiderChainID, Height: height, Time: uint64(ts.UnixNano())}, + BaseHeader: types.BaseHeader{ChainID: daSyncChainID, Height: height, Time: uint64(ts.UnixNano())}, DataHash: dataHash, ProposerAddress: o.addr, }, @@ -298,7 +298,7 @@ func (o *outsider) headerBlob(t *testing.T, height uint64, ts time.Time, dataHas require.NoError(t, err) bz, err := h.MarshalDAEnvelope(envelopeSig) require.NoError(t, err) - return newBlob(t, outsiderHeaderNS, bz) + return newBlob(t, daSyncHeaderNS, bz) } func newBlob(t *testing.T, namespace string, bz []byte) *blobrpc.Blob { From 97b9d0892737dfd9d1dce1d92ccd26ece90840c3 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 13:12:48 +0100 Subject: [PATCH 04/11] fix(syncing): require DA data to be signed by the header's proposer dataFor fell back to data signed by any key when the proposer's copy had not arrived. types.Validate and the DA commitment do not cover LastDataHash, so a copy of a block's transactions re-signed with a forged LastDataHash could be stored by a DA-only node. Its stored data hash then diverges from the canonical one, breaking P2P data sync at the next height. Only accept data signed by the header's proposer. Headers already have to come from that key, so this adds no new constraint on honest submitters. --- block/internal/syncing/da_retriever.go | 20 +++++--------------- block/internal/syncing/da_retriever_test.go | 6 ++++-- 2 files changed, 9 insertions(+), 17 deletions(-) diff --git a/block/internal/syncing/da_retriever.go b/block/internal/syncing/da_retriever.go index dc92f3de6d..8c3ddc5345 100644 --- a/block/internal/syncing/da_retriever.go +++ b/block/internal/syncing/da_retriever.go @@ -377,24 +377,14 @@ func (r *daRetriever) matchPending(ctx context.Context, daHeight uint64) []commo return events } -// dataFor returns the pending data the header commits to. The commitment -// does not cover all metadata, so a copy signed by the header's proposer wins -// over one signed by anyone else. +// dataFor returns the pending data the header commits to, signed by the +// header's proposer. Neither the commitment nor types.Validate covers +// LastDataHash, so a copy signed by anyone else could carry a forged one. func (r *daRetriever) dataFor(ctx context.Context, header *types.SignedHeader) (pendingData, bool) { - var match *pendingData - for i, candidate := range r.pendingData[header.Height()] { - if types.Validate(header, candidate.data) != nil { - continue - } - if bytes.Equal(candidate.signer, header.ProposerAddress) { + for _, candidate := range r.pendingData[header.Height()] { + if bytes.Equal(candidate.signer, header.ProposerAddress) && types.Validate(header, candidate.data) == nil { return candidate, true } - if match == nil { - match = &r.pendingData[header.Height()][i] - } - } - if match != nil { - return *match, true } if isEmptyDataExpected(header) { return pendingData{data: createEmptyDataForHeader(ctx, header)}, true diff --git a/block/internal/syncing/da_retriever_test.go b/block/internal/syncing/da_retriever_test.go index 0b0c250aab..c25e2b0816 100644 --- a/block/internal/syncing/da_retriever_test.go +++ b/block/internal/syncing/da_retriever_test.go @@ -465,7 +465,7 @@ func TestDARetriever_ProcessBlobs_SyncedHeightRejectsDataWithWrongMetadata(t *te require.False(t, included) } -func TestDARetriever_ProcessBlobs_PrefersDataSignedByProposer(t *testing.T) { +func TestDARetriever_ProcessBlobs_RequiresDataSignedByProposer(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) _, otherPub, otherSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} @@ -483,7 +483,9 @@ func TestDARetriever_ProcessBlobs_PrefersDataSignedByProposer(t *testing.T) { forgedBin, err := (&types.SignedData{Data: forged, Signature: sig, Signer: types.Signer{PubKey: otherPub}}).MarshalBinary() require.NoError(t, err) - events := r.processBlobs(context.Background(), [][]byte{forgedBin, dataBin, hdrBin}, 10) + require.Empty(t, r.processBlobs(context.Background(), [][]byte{forgedBin, hdrBin}, 10)) + + events := r.processBlobs(context.Background(), [][]byte{dataBin}, 11) require.Len(t, events, 1) require.Equal(t, data.Data.Hash(), events[0].Data.Hash()) } From 2aff5a50ad7eb06395f06f151440cebd0ac1ed60 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 13:36:32 +0100 Subject: [PATCH 05/11] refactor(syncing): drop unused genesis parameter from assertValidSignedData The proposer is checked against the signer key when data is matched to a header, not here, so the parameter only suggested a check that is not made. --- block/internal/syncing/assert.go | 3 +-- block/internal/syncing/da_retriever.go | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/block/internal/syncing/assert.go b/block/internal/syncing/assert.go index 3a23a06876..9325520be6 100644 --- a/block/internal/syncing/assert.go +++ b/block/internal/syncing/assert.go @@ -4,11 +4,10 @@ import ( "errors" "fmt" - "github.com/evstack/ev-node/pkg/genesis" "github.com/evstack/ev-node/types" ) -func assertValidSignedData(signedData *types.SignedData, genesis genesis.Genesis) error { +func assertValidSignedData(signedData *types.SignedData) error { if signedData == nil || signedData.Txs == nil { return errors.New("empty signed data") } diff --git a/block/internal/syncing/da_retriever.go b/block/internal/syncing/da_retriever.go index 8c3ddc5345..c62a269db3 100644 --- a/block/internal/syncing/da_retriever.go +++ b/block/internal/syncing/da_retriever.go @@ -550,7 +550,7 @@ func (r *daRetriever) tryDecodeData(bz []byte) (*types.Data, []byte) { return nil, nil } - if err := assertValidSignedData(&signedData, r.genesis); err != nil { + if err := assertValidSignedData(&signedData); err != nil { r.logger.Debug().Err(err).Msg("invalid signed data") return nil, nil } From dceb75fc2dae906f0e0e9e8c33a9b00cbf7b90ec Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 13:36:33 +0100 Subject: [PATCH 06/11] test(syncing): cover a rotated proposer's header arriving before the rotation A DA-only node catching up can see the new proposer's header while it still predicts the old one. The header must be held as a candidate and emitted once the rotation is applied, not dropped. --- block/internal/syncing/da_retriever_test.go | 28 +++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/block/internal/syncing/da_retriever_test.go b/block/internal/syncing/da_retriever_test.go index c25e2b0816..ce3d08d87f 100644 --- a/block/internal/syncing/da_retriever_test.go +++ b/block/internal/syncing/da_retriever_test.go @@ -595,6 +595,34 @@ func TestDARetriever_ProcessBlobs_RejectsUnexpectedProposerBeforePendingHeader(t require.Equal(t, correctHeader.Hash().String(), events[0].Header.Hash().String()) } +func TestDARetriever_ProcessBlobs_HoldsRotatedProposerHeaderUntilRotationIsApplied(t *testing.T) { + oldAddr, _, _ := buildSyncTestSigner(t) + newAddr, newPub, newSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: oldAddr} + + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + rotated := false + r.setExpectedProposerProvider(func(uint64) ([]byte, bool) { + if rotated { + return newAddr, true + } + return oldAddr, true + }) + + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, newAddr, newPub, newSigner, 1) + hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, newAddr, newPub, newSigner, nil, &data.Data, nil) + + require.Empty(t, r.processBlobs(context.Background(), [][]byte{hdrBin, dataBin}, 100)) + _, included := r.cache.GetHeaderDAIncludedByHash(hdr.Hash().String()) + require.False(t, included) + + rotated = true + events := r.processBlobs(context.Background(), nil, 101) + require.Len(t, events, 1) + require.Equal(t, hdr.Hash().String(), events[0].Header.Hash().String()) + require.Equal(t, data.Data.DACommitment().String(), events[0].Data.DACommitment().String()) +} + func TestDARetriever_ProcessBlobs_ReplacesFutureHeaderOnceExpectedProposerIsKnown(t *testing.T) { expectedAddr, expectedPub, expectedSigner := buildSyncTestSigner(t) wrongAddr, wrongPub, wrongSigner := buildSyncTestSigner(t) From 6ff82c334ad88a12fd3a5d30c3752af3096c9568 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 14:39:43 +0100 Subject: [PATCH 07/11] fix(syncing): address review findings on held DA candidates - Events carry the DA height the block was posted at, not the height it was released at. A block held for a rotation was otherwise checked for forced inclusion against the wrong DA height. - Held candidates are re-matched at DA heights with no blobs, so a rotated proposer's block is released on an idle chain. - Heights the node already holds only mark data DA included when it is signed by the stored block's proposer. - Headers whose Signer.Address does not match their key are dropped on decode, so they cannot be deduplicated against the real header. - Fix lint findings in the retriever and its tests. --- block/internal/syncing/da_retriever.go | 30 +++++++--- block/internal/syncing/da_retriever_test.go | 65 ++++++++++++++++++--- 2 files changed, 80 insertions(+), 15 deletions(-) diff --git a/block/internal/syncing/da_retriever.go b/block/internal/syncing/da_retriever.go index c62a269db3..11836496d9 100644 --- a/block/internal/syncing/da_retriever.go +++ b/block/internal/syncing/da_retriever.go @@ -113,6 +113,13 @@ func (r *daRetriever) setSignatureProvider(provider types.SyncNodeSignatureBytes func (r *daRetriever) RetrieveFromDA(ctx context.Context, daHeight uint64) ([]common.DAHeightEvent, error) { r.logger.Debug().Uint64("da_height", daHeight).Msg("retrieving from DA") blobsResp, err := r.fetchBlobs(ctx, daHeight) + if errors.Is(err, datypes.ErrBlobNotFound) { + // Held candidates may have become valid since the last blob arrived, + // e.g. after a proposer rotation was applied. + if events := r.processBlobs(ctx, nil, daHeight); len(events) > 0 { + return events, nil + } + } if err != nil { return nil, err } @@ -225,8 +232,8 @@ func (r *daRetriever) processBlobs(ctx context.Context, blobs [][]byte, daHeight } } - events := r.settleSyncedHeights(ctx, daHeight) - events = append(events, r.matchPending(ctx, daHeight)...) + events := r.settleSyncedHeights(ctx) + events = append(events, r.matchPending(ctx)...) if len(events) > 0 { startHeight := events[0].Header.Height() @@ -270,7 +277,7 @@ func (r *daRetriever) addPendingData(candidate pendingData) { // The stored block is the reference: only the blobs that carry it are marked // DA included, everything else at that height is dropped. A complete block is // still returned as an event, which the syncer skips as already processed. -func (r *daRetriever) settleSyncedHeights(ctx context.Context, daHeight uint64) []common.DAHeightEvent { +func (r *daRetriever) settleSyncedHeights(ctx context.Context) []common.DAHeightEvent { if r.syncedHeader == nil { return nil } @@ -288,7 +295,7 @@ func (r *daRetriever) settleSyncedHeights(ctx context.Context, daHeight uint64) } if stored != nil { for _, candidate := range r.pendingData[height] { - if types.Validate(stored, candidate.data) == nil { + if bytes.Equal(candidate.signer, stored.ProposerAddress) && types.Validate(stored, candidate.data) == nil { r.markDataDAIncluded(candidate) } } @@ -301,7 +308,7 @@ func (r *daRetriever) settleSyncedHeights(ctx context.Context, daHeight uint64) events = append(events, common.DAHeightEvent{ Header: candidate.header, Data: data.data, - DaHeight: daHeight, + DaHeight: max(candidate.daHeight, data.daHeight), Source: common.SourceDA, }) } @@ -323,7 +330,7 @@ func (r *daRetriever) settleSyncedHeights(ctx context.Context, daHeight uint64) // matchPending emits an event for every future height that has a header from // the expected proposer together with the data that header commits to. -func (r *daRetriever) matchPending(ctx context.Context, daHeight uint64) []common.DAHeightEvent { +func (r *daRetriever) matchPending(ctx context.Context) []common.DAHeightEvent { events := make([]common.DAHeightEvent, 0, len(r.pendingHeaders)) for height, candidates := range r.pendingHeaders { @@ -348,7 +355,7 @@ func (r *daRetriever) matchPending(ctx context.Context, daHeight uint64) []commo } // The envelope signature already proves the proposer signed this header. - if !candidate.envelope && !r.hasValidSignature(header, data.data) { + if !candidate.envelope && !r.hasValidSignature(header, data.data) { //nolint:contextcheck // validation API does not accept context r.logger.Debug().Uint64("height", height).Msg("invalid header signature") continue } @@ -361,7 +368,7 @@ func (r *daRetriever) matchPending(ctx context.Context, daHeight uint64) []commo events = append(events, common.DAHeightEvent{ Header: header, Data: data.data, - DaHeight: daHeight, + DaHeight: max(candidate.daHeight, data.daHeight), Source: common.SourceDA, }) @@ -534,6 +541,13 @@ func (r *daRetriever) tryDecodeHeader(bz []byte) (*types.SignedHeader, bool) { return nil, false } + // Otherwise a copy differing only in Signer.Address is deduplicated + // against the real header and then fails validation. + if header.Signer.PubKey != nil && !bytes.Equal(types.KeyAddress(header.Signer.PubKey), header.Signer.Address) { + r.logger.Debug().Msg("header signer address does not match its key") + return nil, false + } + return header, isValidEnvelope } diff --git a/block/internal/syncing/da_retriever_test.go b/block/internal/syncing/da_retriever_test.go index ce3d08d87f..6dc0d7f8a4 100644 --- a/block/internal/syncing/da_retriever_test.go +++ b/block/internal/syncing/da_retriever_test.go @@ -397,11 +397,11 @@ func TestDARetriever_ProcessBlobs_SyncedHeightMarksOnlyStoredBlock(t *testing.T) // resignHeader reposts a real header under another key: same header hash and // header signature, different signer. It returns the copy as a legacy blob and // wrapped in an envelope that key signed. -func resignHeader(t *testing.T, real *types.SignedHeader, pub crypto.PubKey, signer signerpkg.Signer) [][]byte { +func resignHeader(t *testing.T, orig *types.SignedHeader, pub crypto.PubKey, signer signerpkg.Signer) [][]byte { t.Helper() addr, err := signer.GetAddress() require.NoError(t, err) - copied := &types.SignedHeader{Header: real.Header, Signature: real.Signature, Signer: types.Signer{PubKey: pub, Address: addr}} + copied := &types.SignedHeader{Header: orig.Header, Signature: orig.Signature, Signer: types.Signer{PubKey: pub, Address: addr}} payload, err := copied.MarshalBinary() require.NoError(t, err) envelopeSig, err := signer.Sign(t.Context(), payload) @@ -487,7 +487,7 @@ func TestDARetriever_ProcessBlobs_RequiresDataSignedByProposer(t *testing.T) { events := r.processBlobs(context.Background(), [][]byte{dataBin}, 11) require.Len(t, events, 1) - require.Equal(t, data.Data.Hash(), events[0].Data.Hash()) + require.Equal(t, data.Hash(), events[0].Data.Hash()) } func TestDARetriever_ProcessBlobs_KeepsCandidatesWhenSyncedHeaderLoadFails(t *testing.T) { @@ -595,12 +595,13 @@ func TestDARetriever_ProcessBlobs_RejectsUnexpectedProposerBeforePendingHeader(t require.Equal(t, correctHeader.Hash().String(), events[0].Header.Hash().String()) } -func TestDARetriever_ProcessBlobs_HoldsRotatedProposerHeaderUntilRotationIsApplied(t *testing.T) { +func TestDARetriever_RetrieveFromDA_ReleasesRotatedProposerBlockAtEmptyHeight(t *testing.T) { oldAddr, _, _ := buildSyncTestSigner(t) newAddr, newPub, newSigner := buildSyncTestSigner(t) gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: oldAddr} - r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + client := mocks.NewMockClient(t) + r := newTestDARetriever(t, client, config.DefaultConfig(), gen) rotated := false r.setExpectedProposerProvider(func(uint64) ([]byte, bool) { if rotated { @@ -612,15 +613,65 @@ func TestDARetriever_ProcessBlobs_HoldsRotatedProposerHeaderUntilRotationIsAppli dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, newAddr, newPub, newSigner, 1) hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, newAddr, newPub, newSigner, nil, &data.Data, nil) - require.Empty(t, r.processBlobs(context.Background(), [][]byte{hdrBin, dataBin}, 100)) + require.Empty(t, r.processBlobs(context.Background(), [][]byte{hdrBin}, 100)) + require.Empty(t, r.processBlobs(context.Background(), [][]byte{dataBin}, 102)) _, included := r.cache.GetHeaderDAIncludedByHash(hdr.Hash().String()) require.False(t, included) rotated = true - events := r.processBlobs(context.Background(), nil, 101) + notFound := datypes.ResultRetrieve{BaseResult: datypes.BaseResult{Code: datypes.StatusNotFound}} + client.On("RetrieveBlobs", mock.Anything, uint64(125), mock.Anything).Return(notFound).Twice() + + events, err := r.RetrieveFromDA(context.Background(), 125) + require.NoError(t, err) require.Len(t, events, 1) require.Equal(t, hdr.Hash().String(), events[0].Header.Hash().String()) require.Equal(t, data.Data.DACommitment().String(), events[0].Data.DACommitment().String()) + require.Equal(t, uint64(102), events[0].DaHeight, "the block is complete at the DA height its data was posted, not where it was released") +} + +func TestDARetriever_ProcessBlobs_DropsHeaderWithMismatchedSignerAddress(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + otherAddr, _, _ := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + altered := *hdr + altered.Signer = types.Signer{PubKey: pub, Address: otherAddr} + alteredBin, err := altered.MarshalBinary() + require.NoError(t, err) + + require.Empty(t, r.processBlobs(context.Background(), [][]byte{alteredBin, dataBin}, 10)) + events := r.processBlobs(context.Background(), [][]byte{hdrBin}, 11) + require.Len(t, events, 1) + require.Equal(t, hdr.Hash().String(), events[0].Header.Hash().String()) +} + +func TestDARetriever_ProcessBlobs_SyncedHeightRejectsDataFromOtherSigner(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + _, otherPub, otherSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + _, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + _, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + r.setSyncedHeaderProvider(func(height uint64) (*types.SignedHeader, bool, error) { return hdr, height <= 5, nil }) + + // Same txs, so it matches the stored header's DA commitment, but signed by + // another key with a forged LastDataHash. + forged := types.Data{Metadata: &types.Metadata{ChainID: gen.ChainID, Height: 5, Time: data.Metadata.Time, LastDataHash: types.Hash("forged")}, Txs: data.Txs} + payload, err := forged.MarshalBinary() + require.NoError(t, err) + sig, err := otherSigner.Sign(t.Context(), payload) + require.NoError(t, err) + forgedBin, err := (&types.SignedData{Data: forged, Signature: sig, Signer: types.Signer{PubKey: otherPub}}).MarshalBinary() + require.NoError(t, err) + + r.processBlobs(context.Background(), [][]byte{forgedBin}, 10) + _, included := r.cache.GetDataDAIncludedByHeight(5) + require.False(t, included) } func TestDARetriever_ProcessBlobs_ReplacesFutureHeaderOnceExpectedProposerIsKnown(t *testing.T) { From 267bca2119cbf682754cdc0230d95507b17ad5a4 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 14:54:15 +0100 Subject: [PATCH 08/11] fix(syncing): address CodeRabbit review on DA candidate handling - An inline subscription event counts as done only if a block completed at that DA height. Blocks released from earlier heights are still delivered, but no longer let the subscriber skip the other namespace of a split height. - Read the expected proposer before checking whether a height is synced, so a block committed between the two reads cannot fall back to the genesis proposer. - The DA inclusion e2e test fails on metadata read errors instead of treating them as "not included", and its comment describes the settlement path it covers. --- block/internal/syncing/da_follower.go | 12 ++++++++---- block/internal/syncing/da_follower_test.go | 13 ++++++++++--- block/internal/syncing/da_retriever.go | 4 +++- test/e2e/da_blob_sync_e2e_test.go | 10 ++++++---- test/e2e/go.mod | 2 +- 5 files changed, 28 insertions(+), 13 deletions(-) diff --git a/block/internal/syncing/da_follower.go b/block/internal/syncing/da_follower.go index 443fb876ae..30ddc47606 100644 --- a/block/internal/syncing/da_follower.go +++ b/block/internal/syncing/da_follower.go @@ -104,16 +104,20 @@ func (f *daFollower) HandleEvent(ctx context.Context, ev datypes.SubscriptionEve } events := f.retriever.ProcessBlobs(ctx, ev.Blobs, ev.Height) - if len(events) == 0 { - return errors.New("skip inline: no complete events") // Split namespace, subscriber rolls back - } - + completed := false for _, event := range events { if err := f.eventSink.PipeEvent(ctx, event); err != nil { f.logger.Warn().Err(err).Uint64("da_height", ev.Height). Msg("failed to pipe inline event, catchup will retry") return err // Actual pipe failure, subscriber rolls back } + completed = completed || event.DaHeight == ev.Height + } + // Events from earlier DA heights, e.g. held for a proposer rotation, say + // nothing about this height: with split namespaces its other half may still + // be on its way. + if !completed { + return errors.New("skip inline: no complete events at this height") // subscriber rolls back } f.logger.Debug().Uint64("da_height", ev.Height).Int("events", len(events)). diff --git a/block/internal/syncing/da_follower_test.go b/block/internal/syncing/da_follower_test.go index 710d2d81d0..015571fa0f 100644 --- a/block/internal/syncing/da_follower_test.go +++ b/block/internal/syncing/da_follower_test.go @@ -40,6 +40,13 @@ func TestDAFollower_HandleEvent(t *testing.T) { mockEvents: []common.DAHeightEvent{}, expectedError: "skip inline: no complete events", }, + { + name: "error_only_events_from_earlier_heights", + isInline: true, + blobs: [][]byte{[]byte("blob")}, + mockEvents: []common.DAHeightEvent{{DaHeight: 99}}, + expectedError: "skip inline: no complete events", + }, { name: "error_pipe_fails", isInline: true, @@ -87,9 +94,9 @@ func TestDAFollower_HandleEvent(t *testing.T) { assert.Contains(t, err.Error(), tt.expectedError) } else { require.NoError(t, err) - if tt.isInline && len(tt.blobs) > 0 { - assert.Len(t, pipedEvents, len(tt.mockEvents)) - } + } + if tt.isInline && len(tt.blobs) > 0 { + assert.Len(t, pipedEvents, len(tt.mockEvents)) } }) } diff --git a/block/internal/syncing/da_retriever.go b/block/internal/syncing/da_retriever.go index 11836496d9..537b9f22fb 100644 --- a/block/internal/syncing/da_retriever.go +++ b/block/internal/syncing/da_retriever.go @@ -334,12 +334,14 @@ func (r *daRetriever) matchPending(ctx context.Context) []common.DAHeightEvent { events := make([]common.DAHeightEvent, 0, len(r.pendingHeaders)) for height, candidates := range r.pendingHeaders { + // Read before isSynced: once the height is synced the prediction falls + // back to the genesis proposer. + expected := r.expectedProposerFor(height) // Left over from a failed load or synced since settleSyncedHeights ran: // it is settled against the stored block on the next pass. if r.isSynced(height) { continue } - expected := r.expectedProposerFor(height) for i, candidate := range candidates { header := candidate.header diff --git a/test/e2e/da_blob_sync_e2e_test.go b/test/e2e/da_blob_sync_e2e_test.go index 9dc1307e73..cec700f5a7 100644 --- a/test/e2e/da_blob_sync_e2e_test.go +++ b/test/e2e/da_blob_sync_e2e_test.go @@ -14,6 +14,7 @@ import ( "testing" "time" + "connectrpc.com/connect" "github.com/celestiaorg/go-square/v3/share" "github.com/libp2p/go-libp2p/core/crypto" "github.com/stretchr/testify/require" @@ -81,9 +82,8 @@ func TestDAInclusionWithUnexpectedSignerBlobs(t *testing.T) { nw.awaitHeight(t, node, 20, 30*time.Second) synced := nw.height(t, node) - // Every height is at or below the node's height, so none is its "next" - // height: the retriever skips the proposer check, and the syncer drops the - // pair as already processed without validating it. + // Every height is at or below the node's height, so the blobs are settled + // against the stored blocks, which another key's blobs never match. for h := uint64(1); h <= synced; h++ { nw.other.postBlock(t, followedDA, h) } @@ -213,9 +213,11 @@ func (n *daSyncNet) awaitHeight(t *testing.T, rpc string, want uint64, timeout t func (n *daSyncNet) daIncludedHeight(t *testing.T, rpc string) uint64 { t.Helper() bz, err := nodeclient.NewClient(rpc).GetMetadata(t.Context(), store.DAIncludedHeightKey) - if err != nil || len(bz) != 8 { + if connect.CodeOf(err) == connect.CodeNotFound { return 0 } + require.NoError(t, err) + require.Len(t, bz, 8) return binary.LittleEndian.Uint64(bz) } diff --git a/test/e2e/go.mod b/test/e2e/go.mod index b6da896199..c191470754 100644 --- a/test/e2e/go.mod +++ b/test/e2e/go.mod @@ -3,6 +3,7 @@ module github.com/evstack/ev-node/test/e2e go 1.26.0 require ( + connectrpc.com/connect v1.21.0 cosmossdk.io/math v1.5.3 github.com/celestiaorg/go-square/v3 v3.0.2 github.com/celestiaorg/tastora v0.20.0 @@ -36,7 +37,6 @@ require ( cloud.google.com/go/iam v1.12.0 // indirect cloud.google.com/go/kms v1.35.0 // indirect cloud.google.com/go/longrunning v1.2.0 // indirect - connectrpc.com/connect v1.21.0 // indirect connectrpc.com/grpcreflect v1.3.1 // indirect cosmossdk.io/api v0.9.2 // indirect cosmossdk.io/collections v1.3.1 // indirect From f7f27be8fa7f2d8c5153c3866f098f0049d94a02 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 15:41:07 +0100 Subject: [PATCH 09/11] fix(syncing): release held DA blocks when a proposer rotation is applied Blocks from a rotated proposer that land on DA before the rotation is applied are held by the retriever. They were only rechecked when the retriever processed another DA height. In subscription mode the follower only sees heights with blobs in the chain's namespaces, so after catch-up a held block waited for the next blob, indefinitely on an idle chain. When applying a block changes the next proposer, the syncer now asks the retriever for held blocks that have become valid and pipes them in. --- block/internal/syncing/da_retriever.go | 13 +++++ .../internal/syncing/da_retriever_tracing.go | 7 +++ block/internal/syncing/syncer.go | 19 +++++++ block/internal/syncing/syncer_test.go | 51 +++++++++++++++++++ 4 files changed, 90 insertions(+) diff --git a/block/internal/syncing/da_retriever.go b/block/internal/syncing/da_retriever.go index 537b9f22fb..6ca412ce70 100644 --- a/block/internal/syncing/da_retriever.go +++ b/block/internal/syncing/da_retriever.go @@ -32,6 +32,10 @@ type pendingDataCleaner interface { removePendingData(height uint64) } +type heldEventReleaser interface { + releaseHeld(ctx context.Context) []common.DAHeightEvent +} + type expectedProposerProvider func(height uint64) ([]byte, bool) // syncedHeaderProvider returns the stored header for a height the node has @@ -481,6 +485,15 @@ func (r *daRetriever) markDataDAIncluded(candidate pendingData) { Msg("data marked as DA included") } +// releaseHeld returns held candidates that have become valid, e.g. once a +// proposer rotation is applied. +func (r *daRetriever) releaseHeld(ctx context.Context) []common.DAHeightEvent { + r.mu.Lock() + defer r.mu.Unlock() + + return r.matchPending(ctx) +} + func (r *daRetriever) removePendingData(height uint64) { r.mu.Lock() defer r.mu.Unlock() diff --git a/block/internal/syncing/da_retriever_tracing.go b/block/internal/syncing/da_retriever_tracing.go index a3f538fa73..f904d899da 100644 --- a/block/internal/syncing/da_retriever_tracing.go +++ b/block/internal/syncing/da_retriever_tracing.go @@ -60,6 +60,13 @@ func (t *tracedDARetriever) ProcessBlobs(ctx context.Context, blobs [][]byte, da return t.inner.ProcessBlobs(ctx, blobs, daHeight) } +func (t *tracedDARetriever) releaseHeld(ctx context.Context) []common.DAHeightEvent { + if releaser, ok := t.inner.(heldEventReleaser); ok { + return releaser.releaseHeld(ctx) + } + return nil +} + func (t *tracedDARetriever) removePendingData(height uint64) { if cleaner, ok := t.inner.(pendingDataCleaner); ok { cleaner.removePendingData(height) diff --git a/block/internal/syncing/syncer.go b/block/internal/syncing/syncer.go index 70371d7565..a3f5959518 100644 --- a/block/internal/syncing/syncer.go +++ b/block/internal/syncing/syncer.go @@ -868,9 +868,28 @@ func (s *Syncer) trySyncNextBlockWithState(ctx context.Context, event *common.DA s.removePendingDAData(event) + if !bytes.Equal(currentState.NextProposerAddress, newState.NextProposerAddress) { + s.releaseHeldDAEvents(ctx) + } + return nil } +// releaseHeldDAEvents hands over DA blocks held back until the rotation that +// was just applied. In subscription mode nothing else rechecks them until +// another blob lands in the chain's namespaces. +func (s *Syncer) releaseHeldDAEvents(ctx context.Context) { + releaser, ok := s.daRetriever.(heldEventReleaser) + if !ok { + return + } + for _, event := range releaser.releaseHeld(ctx) { + if err := s.PipeEvent(ctx, event); err != nil { + return + } + } +} + func (s *Syncer) removePendingDAData(event *common.DAHeightEvent) { if event.Source != common.SourceDA { return diff --git a/block/internal/syncing/syncer_test.go b/block/internal/syncing/syncer_test.go index 5c928f0f59..d2b695f682 100644 --- a/block/internal/syncing/syncer_test.go +++ b/block/internal/syncing/syncer_test.go @@ -626,6 +626,57 @@ func TestProcessHeightEvent_SyncsAndUpdatesState(t *testing.T) { assert.Equal(t, uint64(1), st1.LastBlockHeight) } +func TestProcessHeightEvent_ReleasesHeldDABlockWhenRotationIsApplied(t *testing.T) { + st := store.New(dssync.MutexWrap(datastore.NewMapDatastore())) + cm, err := cache.NewManager(config.DefaultConfig(), st, zerolog.Nop()) + require.NoError(t, err) + + oldAddr, oldPub, oldSigner := buildSyncTestSigner(t) + newAddr, newPub, newSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: oldAddr} + + mockExec := testmocks.NewMockExecutor(t) + mockExec.EXPECT().InitChain(mock.Anything, mock.Anything, uint64(1), "tchain").Return([]byte("app0"), nil).Once() + mockHeaderStore := extmocks.NewMockStore[*types.P2PSignedHeader](t) + mockHeaderStore.EXPECT().Height().Return(uint64(0)).Maybe() + mockDataStore := extmocks.NewMockStore[*types.P2PData](t) + mockDataStore.EXPECT().Height().Return(uint64(0)).Maybe() + + errChan := make(chan error, 1) + s := NewSyncer(st, mockExec, nil, cm, common.NopMetrics(), config.DefaultConfig(), gen, + mockHeaderStore, mockDataStore, zerolog.Nop(), common.DefaultBlockOptions(), errChan, nil) + require.NoError(t, s.initializeState()) + s.ctx = t.Context() + + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + r.setExpectedProposerProvider(s.expectedProposerForHeight) + r.setSyncedHeaderProvider(s.syncedHeader) + s.daRetriever = r + + // The new proposer's block lands on DA before the rotation block is applied. + nextDataBin, nextData := makeSignedDataBytes(t, gen.ChainID, 2, newAddr, newPub, newSigner, 1) + nextHeaderBin, nextHeader := makeSignedHeaderBytes(t, gen.ChainID, 2, newAddr, newPub, newSigner, nil, &nextData.Data, nil) + require.Empty(t, r.processBlobs(t.Context(), [][]byte{nextHeaderBin, nextDataBin}, 7)) + + lastState := s.getLastState() + data := makeData(gen.ChainID, 1, 0) + _, hdr := makeSignedHeaderBytes(t, gen.ChainID, 1, oldAddr, oldPub, oldSigner, lastState.AppHash, data, nil) + mockExec.EXPECT().ExecuteTxs(mock.Anything, mock.Anything, uint64(1), mock.Anything, lastState.AppHash). + Return(execution.ExecuteResult{UpdatedStateRoot: []byte("app1"), NextProposerAddress: newAddr}, nil).Once() + + s.processHeightEvent(t.Context(), &common.DAHeightEvent{Header: hdr, Data: data, Source: common.SourceDA, DaHeight: 6}) + requireEmptyChan(t, errChan) + require.Equal(t, newAddr, s.getLastState().NextProposerAddress) + + select { + case event := <-s.heightInCh: + require.Equal(t, nextHeader.Hash().String(), event.Header.Hash().String()) + require.Equal(t, uint64(7), event.DaHeight) + default: + t.Fatal("held block was not released after the rotation was applied") + } +} + func TestProcessHeightEvent_AlreadyProcessedDADataDoesNotAccumulate(t *testing.T) { const alreadyProcessedBlocks = 8 From 5e1d73ad3f6c9598ebd14851bc236a32b97888e4 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 16:16:05 +0100 Subject: [PATCH 10/11] fix(submitting): count DA inclusion only for the stored block's markers The retriever marks a future height DA included when its header and data come from the proposer the node expects. Before a rotation is applied that is still the old proposer, so a block it signs for a later height leaves markers behind. The DA inclusion loop looked markers up by height only, so it could count a height as DA included from those markers when the accepted proposer's header or data was not on DA. IsHeightDAIncluded and setNodeHeightToDAHeight now take the stored header and accept a height only when its markers are for that block's header hash and data commitment. Placeholders restored from the store after a restart still count, since their hash is not known. Also keep handing off released held blocks when PipeEvent fails on shutdown; it keeps each one as pending. --- block/internal/cache/generic_cache.go | 14 +++++ block/internal/cache/generic_cache_test.go | 23 ++++++++ block/internal/cache/manager.go | 10 ++++ block/internal/submitting/submitter.go | 23 ++++---- block/internal/submitting/submitter_test.go | 63 ++++++++++++++++----- block/internal/syncing/syncer.go | 5 +- node/single_sequencer_integration_test.go | 4 +- 7 files changed, 113 insertions(+), 29 deletions(-) diff --git a/block/internal/cache/generic_cache.go b/block/internal/cache/generic_cache.go index 543dfa4c48..3566ab9147 100644 --- a/block/internal/cache/generic_cache.go +++ b/block/internal/cache/generic_cache.go @@ -87,6 +87,20 @@ func (c *Cache) getDAIncludedByHeight(blockHeight uint64) (uint64, bool) { return v, exists } +// getDAIncludedByHeightAndHash is getDAIncludedByHeight for the block whose +// hash is known. A placeholder restored from the store is accepted, since its +// hash is unknown until the entry is set again. +func (c *Cache) getDAIncludedByHeightAndHash(blockHeight uint64, hash string) (uint64, bool) { + c.mu.RLock() + defer c.mu.RUnlock() + stored, ok := c.hashByHeight[blockHeight] + if !ok || (stored != hash && stored != HeightPlaceholderKey(c.storeKeyPrefix, blockHeight)) { + return 0, false + } + v, exists := c.daIncluded[stored] + return v, exists +} + // setDAIncluded records DA inclusion in memory. // If a previous entry already exists at blockHeight (e.g. a placeholder from // RestoreFromStore), it is evicted from daIncluded to avoid orphan leaks. diff --git a/block/internal/cache/generic_cache_test.go b/block/internal/cache/generic_cache_test.go index da7048c0ff..4040ddfd25 100644 --- a/block/internal/cache/generic_cache_test.go +++ b/block/internal/cache/generic_cache_test.go @@ -162,6 +162,29 @@ func TestCache_RestoreFromStore_PlaceholderOverwrittenByRealHash(t *testing.T) { assert.Equal(t, uint64(99), daH2) } +func TestCache_getDAIncludedByHeightAndHash(t *testing.T) { + st := testMemStore(t) + writeSnapshot(t, st, "hdr/", []snapshotEntry{{blockHeight: 3, daHeight: 99}}) + c := NewCache(st, "hdr/") + require.NoError(t, c.RestoreFromStore(context.Background(), 0)) + + daH, ok := c.getDAIncludedByHeightAndHash(3, "anyHash") + require.True(t, ok, "a restored placeholder stands in for any hash") + assert.Equal(t, uint64(99), daH) + + c.setDAIncluded("hashA", 100, 4) + daH, ok = c.getDAIncludedByHeightAndHash(4, "hashA") + require.True(t, ok) + assert.Equal(t, uint64(100), daH) + + _, ok = c.getDAIncludedByHeightAndHash(4, "hashB") + assert.False(t, ok, "a marker for another block at the same height") + + c.removeDAIncluded("hashA") + _, ok = c.getDAIncludedByHeightAndHash(4, "hashA") + assert.False(t, ok) +} + // TestCache_RestoreFromStore_RoundTrip verifies that SaveToStore persists a // snapshot that a freshly-constructed cache can fully recover. func TestCache_RestoreFromStore_RoundTrip(t *testing.T) { diff --git a/block/internal/cache/manager.go b/block/internal/cache/manager.go index c2e2521baf..0c79ad2810 100644 --- a/block/internal/cache/manager.go +++ b/block/internal/cache/manager.go @@ -35,6 +35,7 @@ type CacheManager interface { SetHeaderSeen(hash string, blockHeight uint64) GetHeaderDAIncludedByHash(hash string) (uint64, bool) GetHeaderDAIncludedByHeight(blockHeight uint64) (uint64, bool) + GetHeaderDAIncludedByHeightAndHash(blockHeight uint64, hash string) (uint64, bool) SetHeaderDAIncluded(hash string, daHeight uint64, blockHeight uint64) RemoveHeaderDAIncluded(hash string) @@ -43,6 +44,7 @@ type CacheManager interface { SetDataSeen(hash string, blockHeight uint64) GetDataDAIncludedByHash(daCommitmentHash string) (uint64, bool) GetDataDAIncludedByHeight(blockHeight uint64) (uint64, bool) + GetDataDAIncludedByHeightAndHash(blockHeight uint64, daCommitmentHash string) (uint64, bool) SetDataDAIncluded(daCommitmentHash string, daHeight uint64, blockHeight uint64) RemoveDataDAIncluded(hash string) @@ -157,6 +159,10 @@ func (m *implementation) GetHeaderDAIncludedByHeight(blockHeight uint64) (uint64 return m.headerCache.getDAIncludedByHeight(blockHeight) } +func (m *implementation) GetHeaderDAIncludedByHeightAndHash(blockHeight uint64, hash string) (uint64, bool) { + return m.headerCache.getDAIncludedByHeightAndHash(blockHeight, hash) +} + func (m *implementation) SetHeaderDAIncluded(hash string, daHeight uint64, blockHeight uint64) { m.headerCache.setDAIncluded(hash, daHeight, blockHeight) } @@ -186,6 +192,10 @@ func (m *implementation) GetDataDAIncludedByHeight(blockHeight uint64) (uint64, return m.dataCache.getDAIncludedByHeight(blockHeight) } +func (m *implementation) GetDataDAIncludedByHeightAndHash(blockHeight uint64, daCommitmentHash string) (uint64, bool) { + return m.dataCache.getDAIncludedByHeightAndHash(blockHeight, daCommitmentHash) +} + func (m *implementation) SetDataDAIncluded(daCommitmentHash string, daHeight uint64, blockHeight uint64) { m.dataCache.setDAIncluded(daCommitmentHash, daHeight, blockHeight) } diff --git a/block/internal/submitting/submitter.go b/block/internal/submitting/submitter.go index 6841fc425a..de1a30cbbe 100644 --- a/block/internal/submitting/submitter.go +++ b/block/internal/submitting/submitter.go @@ -335,20 +335,20 @@ func (s *Submitter) processDAInclusionLoop() { nextHeight := currentDAIncluded + 1 // Get block data first - _, data, err := s.store.GetBlockData(s.ctx, nextHeight) + header, data, err := s.store.GetBlockData(s.ctx, nextHeight) if err != nil { break } // Check if this height is DA included - if included, err := s.IsHeightDAIncluded(nextHeight, data); err != nil || !included { + if included, err := s.IsHeightDAIncluded(nextHeight, header, data); err != nil || !included { break } s.logger.Debug().Uint64("height", nextHeight).Msg("advancing DA included height") // Set node height to DA height mapping using already retrieved data - if err := s.setNodeHeightToDAHeight(s.ctx, nextHeight, data, currentDAIncluded == 0); err != nil { + if err := s.setNodeHeightToDAHeight(s.ctx, nextHeight, header, data, currentDAIncluded == 0); err != nil { s.logger.Error().Err(err).Uint64("height", nextHeight).Msg("failed to set node height to DA height mapping") break } @@ -446,10 +446,10 @@ func (s *Submitter) sendCriticalError(err error) { // setNodeHeightToDAHeight persists the DA heights for a block's header and data. // For empty-tx blocks, both use the header DA height since no data blob is posted. -func (s *Submitter) setNodeHeightToDAHeight(ctx context.Context, height uint64, data *types.Data, genesisInclusion bool) error { +func (s *Submitter) setNodeHeightToDAHeight(ctx context.Context, height uint64, header *types.SignedHeader, data *types.Data, genesisInclusion bool) error { dataHash := data.DACommitment() - daHeightForHeader, ok := s.cache.GetHeaderDAIncludedByHeight(height) + daHeightForHeader, ok := s.cache.GetHeaderDAIncludedByHeightAndHash(height, header.Hash().String()) if !ok { return fmt.Errorf("header for height %d not found in cache", height) } @@ -462,7 +462,7 @@ func (s *Submitter) setNodeHeightToDAHeight(ctx context.Context, height uint64, // For empty transactions, use the same DA height as the header. dataDAHeight := daHeightForHeader if !bytes.Equal(dataHash, common.DataHashForEmptyTxs) { - daHeightForData, ok := s.cache.GetDataDAIncludedByHeight(height) + daHeightForData, ok := s.cache.GetDataDAIncludedByHeightAndHash(height, dataHash.String()) if !ok { return fmt.Errorf("data for height %d not found in cache", height) } @@ -488,8 +488,11 @@ func (s *Submitter) setNodeHeightToDAHeight(ctx context.Context, height uint64, return nil } -// IsHeightDAIncluded reports whether the block at height has been DA-included. -func (s *Submitter) IsHeightDAIncluded(height uint64, data *types.Data) (bool, error) { +// IsHeightDAIncluded reports whether the stored block at height has been +// DA-included. The markers must be for this block: a header or data at the +// same height from another proposer, e.g. one rotated out before it was +// applied, does not count. +func (s *Submitter) IsHeightDAIncluded(height uint64, header *types.SignedHeader, data *types.Data) (bool, error) { // Already finalized — cache entries were cleared, but we know it's included. if height <= s.GetDAIncludedHeight() { return true, nil @@ -506,8 +509,8 @@ func (s *Submitter) IsHeightDAIncluded(height uint64, data *types.Data) (bool, e dataCommitment := data.DACommitment() - _, headerIncluded := s.cache.GetHeaderDAIncludedByHeight(height) - _, dataIncluded := s.cache.GetDataDAIncludedByHeight(height) + _, headerIncluded := s.cache.GetHeaderDAIncludedByHeightAndHash(height, header.Hash().String()) + _, dataIncluded := s.cache.GetDataDAIncludedByHeightAndHash(height, dataCommitment.String()) dataIncluded = bytes.Equal(dataCommitment, common.DataHashForEmptyTxs) || dataIncluded diff --git a/block/internal/submitting/submitter_test.go b/block/internal/submitting/submitter_test.go index 67e1773a14..8f1e78df29 100644 --- a/block/internal/submitting/submitter_test.go +++ b/block/internal/submitting/submitter_test.go @@ -124,7 +124,7 @@ func TestSubmitter_IsHeightDAIncluded(t *testing.T) { h1, d1 := newHeaderAndData("chain", 3, true) h2, d2 := newHeaderAndData("chain", 4, true) - _, d3 := newHeaderAndData("chain", 2, true) // already DA included, cache was cleared + h3, d3 := newHeaderAndData("chain", 2, true) // already DA included, cache was cleared cm.SetHeaderDAIncluded(h1.Hash().String(), 100, 3) cm.SetDataDAIncluded(d1.DACommitment().String(), 100, 3) @@ -134,20 +134,21 @@ func TestSubmitter_IsHeightDAIncluded(t *testing.T) { specs := map[string]struct { height uint64 + header *types.SignedHeader data *types.Data exp bool expErr bool }{ - "below store height and cached": {height: 3, data: d1, exp: true}, - "above store height": {height: 6, data: d2, exp: false}, - "data missing": {height: 4, data: d2, exp: false}, - "at daIncludedHeight - cache cleared": {height: 2, data: d3, exp: true}, - "below daIncludedHeight - cache cleared": {height: 1, data: d3, exp: true}, + "below store height and cached": {height: 3, header: h1, data: d1, exp: true}, + "above store height": {height: 6, header: h2, data: d2, exp: false}, + "data missing": {height: 4, header: h2, data: d2, exp: false}, + "at daIncludedHeight - cache cleared": {height: 2, header: h3, data: d3, exp: true}, + "below daIncludedHeight - cache cleared": {height: 1, header: h3, data: d3, exp: true}, } for name, spec := range specs { t.Run(name, func(t *testing.T) { - included, err := s.IsHeightDAIncluded(spec.height, spec.data) + included, err := s.IsHeightDAIncluded(spec.height, spec.header, spec.data) if spec.expErr { require.Error(t, err) return @@ -158,6 +159,40 @@ func TestSubmitter_IsHeightDAIncluded(t *testing.T) { } } +func TestSubmitter_IsHeightDAIncluded_IgnoresMarkersForAnotherBlock(t *testing.T) { + ctx := t.Context() + cm, st := newTestCacheAndStore(t) + batch, err := st.NewBatch(ctx) + require.NoError(t, err) + require.NoError(t, batch.SetHeight(5)) + require.NoError(t, batch.Commit()) + + s := &Submitter{store: st, cache: cm, logger: zerolog.Nop(), daIncludedHeight: &atomic.Uint64{}} + s.ctx = ctx + + // Markers left by another proposer's block at height 5, e.g. one rotated + // out before its block was applied. + otherHeader, otherData := newHeaderAndData("chain", 5, true) + cm.SetHeaderDAIncluded(otherHeader.Hash().String(), 100, 5) + cm.SetDataDAIncluded(otherData.DACommitment().String(), 100, 5) + + header, data := newHeaderAndData("chain", 5, true) + included, err := s.IsHeightDAIncluded(5, header, data) + require.NoError(t, err) + assert.False(t, included) + + cm.SetHeaderDAIncluded(header.Hash().String(), 101, 5) + included, err = s.IsHeightDAIncluded(5, header, data) + require.NoError(t, err) + assert.False(t, included, "the data marker is still the other block's") + assert.Error(t, s.setNodeHeightToDAHeight(ctx, 5, header, data, false)) + + cm.SetDataDAIncluded(data.DACommitment().String(), 101, 5) + included, err = s.IsHeightDAIncluded(5, header, data) + require.NoError(t, err) + assert.True(t, included) +} + func TestSubmitter_setSequencerHeightToDAHeight(t *testing.T) { ctx := t.Context() cm, _ := newTestCacheAndStore(t) @@ -199,7 +234,7 @@ func TestSubmitter_setSequencerHeightToDAHeight(t *testing.T) { mockStore.On("SetMetadata", mock.Anything, dataKey, dBz).Return(nil).Once() mockStore.On("SetMetadata", mock.Anything, store.GenesisDAHeightKey, gBz).Return(nil).Once() - require.NoError(t, s.setNodeHeightToDAHeight(ctx, 1, d, true)) + require.NoError(t, s.setNodeHeightToDAHeight(ctx, 1, h, d, true)) } func TestSubmitter_setNodeHeightToDAHeight_Errors(t *testing.T) { @@ -213,11 +248,11 @@ func TestSubmitter_setNodeHeightToDAHeight_Errors(t *testing.T) { // No cache entries -> expect error on missing header _, ok := cm.GetHeaderDAIncludedByHash(h.Hash().String()) assert.False(t, ok) - assert.Error(t, s.setNodeHeightToDAHeight(ctx, 1, d, false)) + assert.Error(t, s.setNodeHeightToDAHeight(ctx, 1, h, d, false)) // Add header, missing data cm.SetHeaderDAIncluded(h.Hash().String(), 10, 1) - assert.Error(t, s.setNodeHeightToDAHeight(ctx, 1, d, false)) + assert.Error(t, s.setNodeHeightToDAHeight(ctx, 1, h, d, false)) } func TestSubmitter_initializeDAIncludedHeight(t *testing.T) { @@ -708,7 +743,7 @@ func TestSubmitter_IsHeightDAIncluded_AfterRestart(t *testing.T) { _, realHeaderFound := cm2.GetHeaderDAIncludedByHash(h3.Hash().String()) assert.False(t, realHeaderFound, "real hash must not be present before DA retriever re-fires") - included, err := s.IsHeightDAIncluded(3, d3) + included, err := s.IsHeightDAIncluded(3, h3, d3) require.NoError(t, err) assert.True(t, included, "IsHeightDAIncluded must return true for in-flight height using snapshot placeholder, "+ @@ -721,7 +756,7 @@ func TestSubmitter_IsHeightDAIncluded_AfterRestart(t *testing.T) { _, realHeaderFound = cm2.GetHeaderDAIncludedByHash(h3.Hash().String()) assert.True(t, realHeaderFound, "real hash must be present after DA retriever re-fires") - included, err = s.IsHeightDAIncluded(3, d3) + included, err = s.IsHeightDAIncluded(3, h3, d3) require.NoError(t, err) assert.True(t, included, "IsHeightDAIncluded must still return true after real hash is written") } @@ -794,7 +829,7 @@ func TestSubmitter_setNodeHeightToDAHeight_AfterRestart(t *testing.T) { // ── Step 3: call setNodeHeightToDAHeight — must succeed via fallback ────── // Before this fix, GetHeaderDAIncludedByHash(realHash) would miss and the function // would return an error, stalling processDAInclusionLoop. - err = s.setNodeHeightToDAHeight(ctx, 3, d3, false) + err = s.setNodeHeightToDAHeight(ctx, 3, h3, d3, false) require.NoError(t, err, "setNodeHeightToDAHeight must succeed via height-based lookup before DA retriever re-fires") @@ -815,6 +850,6 @@ func TestSubmitter_setNodeHeightToDAHeight_AfterRestart(t *testing.T) { cm2.SetHeaderDAIncluded(h3.Hash().String(), 12, 3) cm2.SetDataDAIncluded(d3.DACommitment().String(), 12, 3) - err = s.setNodeHeightToDAHeight(ctx, 3, d3, false) + err = s.setNodeHeightToDAHeight(ctx, 3, h3, d3, false) require.NoError(t, err, "setNodeHeightToDAHeight must still work once real hashes are populated") } diff --git a/block/internal/syncing/syncer.go b/block/internal/syncing/syncer.go index a3f5959518..0f88157981 100644 --- a/block/internal/syncing/syncer.go +++ b/block/internal/syncing/syncer.go @@ -884,9 +884,8 @@ func (s *Syncer) releaseHeldDAEvents(ctx context.Context) { return } for _, event := range releaser.releaseHeld(ctx) { - if err := s.PipeEvent(ctx, event); err != nil { - return - } + // On cancellation PipeEvent keeps the event as pending, so carry on. + _ = s.PipeEvent(ctx, event) } } diff --git a/node/single_sequencer_integration_test.go b/node/single_sequencer_integration_test.go index 63792aea69..130b62e235 100644 --- a/node/single_sequencer_integration_test.go +++ b/node/single_sequencer_integration_test.go @@ -206,10 +206,10 @@ func (s *FullNodeTestSuite) TestSubmitBlocksToDA() { err = waitForAtLeastNDAIncludedHeight(s.node, n) s.NoError(err, "Failed to get DA inclusion") for height := uint64(1); height <= n; height++ { - _, data, err := s.node.Store.GetBlockData(s.ctx, height) + header, data, err := s.node.Store.GetBlockData(s.ctx, height) require.NoError(s.T(), err) - ok, err := castState(s.T(), s.node).bc.Submitter.IsHeightDAIncluded(height, data) + ok, err := castState(s.T(), s.node).bc.Submitter.IsHeightDAIncluded(height, header, data) require.NoError(s.T(), err) require.True(s.T(), ok, "Block at height %d is not DA included", height) } From 189634f7cc862de0daa66a373266269578454d72 Mon Sep 17 00:00:00 2001 From: Damian Nolan Date: Thu, 3 Dec 2026 16:59:15 +0100 Subject: [PATCH 11/11] fix(syncing): dedup DA candidates in constant time and pair split synced blocks - Held header and data candidates were deduplicated by comparing each new blob with every one held at its height, hashing both headers each time, under the retriever lock. Anyone can post many distinct blobs for one height, so this was quadratic: 8,000 junk headers took about 14s. Each candidate's key is now computed once and kept in a per-height set, dropped once nothing is held for the height. - For a height the node already holds, the stored block's header or data is now kept until the other half lands, so the block completes inline at the DA height of its second half. Settling deleted the first half, so neither DA height produced an event and the subscriber re-fetched both through catch-up. --- block/internal/syncing/da_retriever.go | 132 ++++++++++++++------ block/internal/syncing/da_retriever_test.go | 51 ++++++++ 2 files changed, 143 insertions(+), 40 deletions(-) diff --git a/block/internal/syncing/da_retriever.go b/block/internal/syncing/da_retriever.go index 6ca412ce70..a93ff67c5c 100644 --- a/block/internal/syncing/da_retriever.go +++ b/block/internal/syncing/da_retriever.go @@ -57,6 +57,15 @@ type pendingData struct { daHeight uint64 } +// candidateKey identifies a held blob, so each copy is held once. +type candidateKey struct { + data bool + envelope bool + hash string + signature string + signer string +} + // daRetriever handles DA retrieval operations for syncing type daRetriever struct { client da.Client @@ -77,6 +86,9 @@ type daRetriever struct { // Transient: rebuilt from DA on restart. pendingHeaders map[uint64][]pendingHeader pendingData map[uint64][]pendingData + // heldKeys deduplicates candidates per height in constant time: anyone can + // post many distinct blobs for one height. + heldKeys map[uint64]map[candidateKey]struct{} // strictMode indicates if the node has seen an authenticated DAHeaderEnvelope // and should now reject all legacy/unsigned headers. @@ -97,6 +109,7 @@ func NewDARetriever( logger: logger.With().Str("component", "da_retriever").Logger(), pendingHeaders: make(map[uint64][]pendingHeader), pendingData: make(map[uint64][]pendingData), + heldKeys: make(map[uint64]map[candidateKey]struct{}), strictMode: false, } } @@ -258,29 +271,62 @@ func (r *daRetriever) processBlobs(ctx context.Context, blobs [][]byte, daHeight } func (r *daRetriever) addPendingHeader(candidate pendingHeader) { - height := candidate.header.Height() - for _, existing := range r.pendingHeaders[height] { - if existing.envelope == candidate.envelope && sameSignedHeader(existing.header, candidate.header) { - return - } + header := candidate.header + key := candidateKey{ + envelope: candidate.envelope, + hash: string(header.Hash()), + signature: string(header.Signature), + signer: string(signerAddress(header)), + } + if r.hold(header.Height(), key) { + r.pendingHeaders[header.Height()] = append(r.pendingHeaders[header.Height()], candidate) } - r.pendingHeaders[height] = append(r.pendingHeaders[height], candidate) } func (r *daRetriever) addPendingData(candidate pendingData) { - height := candidate.data.Height() - for _, existing := range r.pendingData[height] { - if bytes.Equal(existing.hash, candidate.hash) && bytes.Equal(existing.signer, candidate.signer) { - return - } + key := candidateKey{data: true, hash: string(candidate.hash), signer: string(candidate.signer)} + if r.hold(candidate.data.Height(), key) { + r.pendingData[candidate.data.Height()] = append(r.pendingData[candidate.data.Height()], candidate) + } +} + +// hold records key for height and reports whether it was new. +func (r *daRetriever) hold(height uint64, key candidateKey) bool { + if r.heldKeys == nil { + r.heldKeys = make(map[uint64]map[candidateKey]struct{}) + } + keys := r.heldKeys[height] + if keys == nil { + keys = make(map[candidateKey]struct{}) + r.heldKeys[height] = keys + } + if _, ok := keys[key]; ok { + return false + } + keys[key] = struct{}{} + return true +} + +// prune drops empty candidate lists for height, and its dedup keys once +// nothing is held for it. +func (r *daRetriever) prune(height uint64) { + if len(r.pendingHeaders[height]) == 0 { + delete(r.pendingHeaders, height) + } + if len(r.pendingData[height]) == 0 { + delete(r.pendingData, height) + } + if len(r.pendingHeaders[height]) == 0 && len(r.pendingData[height]) == 0 { + delete(r.heldKeys, height) } - r.pendingData[height] = append(r.pendingData[height], candidate) } // settleSyncedHeights resolves candidates for heights the node already holds. // The stored block is the reference: only the blobs that carry it are marked -// DA included, everything else at that height is dropped. A complete block is -// still returned as an event, which the syncer skips as already processed. +// DA included, everything else at that height is dropped. Its header or data +// is kept until the other half lands, so the block completes as an event, +// which the syncer skips as already processed, at the DA height of its second +// half. func (r *daRetriever) settleSyncedHeights(ctx context.Context) []common.DAHeightEvent { if r.syncedHeader == nil { return nil @@ -297,30 +343,38 @@ func (r *daRetriever) settleSyncedHeights(ctx context.Context) []common.DAHeight if !synced { return } - if stored != nil { - for _, candidate := range r.pendingData[height] { - if bytes.Equal(candidate.signer, stored.ProposerAddress) && types.Validate(stored, candidate.data) == nil { - r.markDataDAIncluded(candidate) - } - } - for _, candidate := range r.pendingHeaders[height] { - if !sameSignedHeader(candidate.header, stored) { - continue - } - r.markHeaderDAIncluded(candidate) - if data, ok := r.dataFor(ctx, candidate.header); ok { - events = append(events, common.DAHeightEvent{ - Header: candidate.header, - Data: data.data, - DaHeight: max(candidate.daHeight, data.daHeight), - Source: common.SourceDA, - }) - } + defer r.prune(height) + + var data, headers = r.pendingData[height], r.pendingHeaders[height] + r.pendingData[height], r.pendingHeaders[height] = nil, nil + if stored == nil { + return + } + for _, candidate := range data { + if bytes.Equal(candidate.signer, stored.ProposerAddress) && types.Validate(stored, candidate.data) == nil { + r.markDataDAIncluded(candidate) + r.pendingData[height] = []pendingData{candidate} break } } - delete(r.pendingHeaders, height) - delete(r.pendingData, height) + for _, candidate := range headers { + if !sameSignedHeader(candidate.header, stored) { + continue + } + r.markHeaderDAIncluded(candidate) + if data, ok := r.dataFor(ctx, candidate.header); ok { + events = append(events, common.DAHeightEvent{ + Header: candidate.header, + Data: data.data, + DaHeight: max(candidate.daHeight, data.daHeight), + Source: common.SourceDA, + }) + r.pendingData[height] = nil + } else { + r.pendingHeaders[height] = []pendingHeader{candidate} + } + break + } } for height := range r.pendingHeaders { @@ -378,11 +432,8 @@ func (r *daRetriever) matchPending(ctx context.Context) []common.DAHeightEvent { Source: common.SourceDA, }) - if len(candidates) == 1 { - delete(r.pendingHeaders, height) - } else { - r.pendingHeaders[height] = append(candidates[:i:i], candidates[i+1:]...) - } + r.pendingHeaders[height] = append(candidates[:i:i], candidates[i+1:]...) + r.prune(height) break } } @@ -499,6 +550,7 @@ func (r *daRetriever) removePendingData(height uint64) { defer r.mu.Unlock() delete(r.pendingData, height) + r.prune(height) } // tryDecodeHeader attempts to decode a blob as a header. The second result diff --git a/block/internal/syncing/da_retriever_test.go b/block/internal/syncing/da_retriever_test.go index 6dc0d7f8a4..10f212ee3e 100644 --- a/block/internal/syncing/da_retriever_test.go +++ b/block/internal/syncing/da_retriever_test.go @@ -630,6 +630,57 @@ func TestDARetriever_RetrieveFromDA_ReleasesRotatedProposerBlockAtEmptyHeight(t require.Equal(t, uint64(102), events[0].DaHeight, "the block is complete at the DA height its data was posted, not where it was released") } +func TestDARetriever_ProcessBlobs_SyncedBlockCompletesAtSecondHalf(t *testing.T) { + addr, pub, signer := buildSyncTestSigner(t) + otherAddr, otherPub, otherSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 5, addr, pub, signer, 2) + hdrBin, hdr := makeSignedHeaderBytes(t, gen.ChainID, 5, addr, pub, signer, nil, &data.Data, nil) + otherDataBin, _ := makeSignedDataBytes(t, gen.ChainID, 5, otherAddr, otherPub, otherSigner, 3) + r.setSyncedHeaderProvider(func(height uint64) (*types.SignedHeader, bool, error) { return hdr, height <= 5, nil }) + + require.Empty(t, r.processBlobs(context.Background(), [][]byte{hdrBin, otherDataBin}, 10)) + _, included := r.cache.GetHeaderDAIncludedByHash(hdr.Hash().String()) + require.True(t, included) + require.Len(t, r.pendingHeaders[5], 1, "the stored header waits for its data") + require.Empty(t, r.pendingData[5], "data that is not the stored block's is dropped") + + events := r.processBlobs(context.Background(), [][]byte{dataBin}, 12) + require.Len(t, events, 1) + require.Equal(t, uint64(12), events[0].DaHeight) + _, included = r.cache.GetDataDAIncludedByHeight(5) + require.True(t, included) + require.NotContains(t, r.pendingHeaders, uint64(5)) + require.NotContains(t, r.pendingData, uint64(5)) + require.NotContains(t, r.heldKeys, uint64(5)) +} + +func TestDARetriever_ProcessBlobs_HoldsEachCopyOnce(t *testing.T) { + addr, _, _ := buildSyncTestSigner(t) + otherAddr, otherPub, otherSigner := buildSyncTestSigner(t) + gen := genesis.Genesis{ChainID: "tchain", InitialHeight: 1, StartTime: time.Now().Add(-time.Second), ProposerAddress: addr} + r := newTestDARetriever(t, nil, config.DefaultConfig(), gen) + + var blobs [][]byte + for i := range 3 { + dataBin, data := makeSignedDataBytes(t, gen.ChainID, 100, otherAddr, otherPub, otherSigner, i+1) + hdrBin, _ := makeSignedHeaderBytes(t, gen.ChainID, 100, otherAddr, otherPub, otherSigner, nil, &data.Data, nil) + blobs = append(blobs, hdrBin, dataBin) + } + require.Empty(t, r.processBlobs(context.Background(), blobs, 10)) + require.Empty(t, r.processBlobs(context.Background(), blobs, 11)) + require.Len(t, r.pendingHeaders[100], 3) + require.Len(t, r.pendingData[100], 3) + require.Len(t, r.heldKeys[100], 6) + + r.removePendingData(100) + r.pendingHeaders[100] = nil + r.prune(100) + require.NotContains(t, r.heldKeys, uint64(100)) +} + func TestDARetriever_ProcessBlobs_DropsHeaderWithMismatchedSignerAddress(t *testing.T) { addr, pub, signer := buildSyncTestSigner(t) otherAddr, _, _ := buildSyncTestSigner(t)