Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions block/components.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,10 @@ func (bc *Components) Stop() error {
}

// NewSyncComponents creates components for a non-aggregator full node that can only sync blocks.
// Non-aggregator full nodes can sync from P2P and DA but cannot produce blocks or submit to DA.
// They have more sync capabilities than light nodes but no block production. No signer required.
// Non-aggregator full nodes can sync from P2P and DA but cannot produce blocks.
// They have more sync capabilities than light nodes but no block production.
// signer is optional: a proposer demoted by a rotation passes its own so it
// keeps posting the blocks it produced but did not get onto DA.
func NewSyncComponents(
config config.Config,
genesis genesis.Genesis,
Expand All @@ -149,6 +151,7 @@ func NewSyncComponents(
metrics *Metrics,
blockOpts BlockOptions,
raftNode common.RaftNode,
signer signer.Signer,
) (*Components, error) {
newCacheManager := cache.NewManager
if daClient == nil {
Expand Down Expand Up @@ -190,7 +193,7 @@ func NewSyncComponents(

var submitter *submitting.Submitter
if daClient != nil {
// Create submitter for DA-enabled sync nodes (no signer, only DA inclusion processing).
// DA inclusion processing, and submission of this node's own blocks if it has a signer.
var daSubmitter submitting.DASubmitterAPI = submitting.NewDASubmitter(daClient, config, genesis, blockOpts, metrics, logger, headerDAHintAppender, dataDAHintAppender)
if config.Instrumentation.IsTracingEnabled() {
daSubmitter = submitting.WithTracingDASubmitter(daSubmitter)
Expand All @@ -204,7 +207,7 @@ func NewSyncComponents(
genesis,
daSubmitter,
nil, // No sequencer for sync nodes
nil, // No signer for sync nodes
signer,
logger,
errorCh,
)
Expand Down
71 changes: 71 additions & 0 deletions block/components_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ func TestNewSyncComponents_Creation(t *testing.T) {
NopMetrics(),
DefaultBlockOptions(),
nil,
nil,
)

require.NoError(t, err)
Expand All @@ -133,6 +134,74 @@ func TestNewSyncComponents_Creation(t *testing.T) {
assert.Nil(t, components.Executor) // Sync nodes don't have executors
}

// A proposer demoted by a rotation runs as a sync node. Given its signer, it
// keeps posting the blocks it produced that are not yet on DA.
func TestNewSyncComponents_WithSignerPostsOwnBlocks(t *testing.T) {
ctx := t.Context()
memStore := store.New(sync.MutexWrap(datastore.NewMapDatastore()))

priv, _, err := crypto.GenerateEd25519Key(crand.Reader)
require.NoError(t, err)
signer, err := noop.NewNoopSigner(priv)
require.NoError(t, err)
addr, err := signer.GetAddress()
require.NoError(t, err)
pub, err := signer.GetPublic()
require.NoError(t, err)

gen := genesis.Genesis{ChainID: "test-chain", InitialHeight: 1, StartTime: time.Now(), ProposerAddress: addr}
header := &types.SignedHeader{
Header: types.Header{BaseHeader: types.BaseHeader{ChainID: gen.ChainID, Height: 1, Time: uint64(time.Now().UnixNano())}, ProposerAddress: addr},
Signer: types.Signer{PubKey: pub, Address: addr},
}
data := &types.Data{Metadata: &types.Metadata{ChainID: gen.ChainID, Height: 1}, Txs: types.Txs{types.Tx("tx")}}
batch, err := memStore.NewBatch(ctx)
require.NoError(t, err)
require.NoError(t, batch.SaveBlockData(header, data, &types.Signature{}))
require.NoError(t, batch.SetHeight(1))
require.NoError(t, batch.Commit())

cfg := config.DefaultConfig()
cfg.DA.BlockTime.Duration = 100 * time.Millisecond
daClient := testmocks.NewMockClient(t)
daClient.On("GetHeaderNamespace").Return(datypes.NamespaceFromString("ns").Bytes()).Maybe()
daClient.On("GetDataNamespace").Return(datypes.NamespaceFromString("data-ns").Bytes()).Maybe()
daClient.On("GetForcedInclusionNamespace").Return([]byte(nil)).Maybe()
daClient.On("HasForcedInclusionNamespace").Return(false).Maybe()
submitted := make(chan struct{}, 2)
daClient.On("Submit", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Run(func(mock.Arguments) { submitted <- struct{}{} }).
Return(datypes.ResultSubmit{BaseResult: datypes.BaseResult{Code: datypes.StatusSuccess, SubmittedCount: 1, Height: 1}})

components, err := NewSyncComponents(
cfg,
gen,
memStore,
testmocks.NewMockExecutor(t),
daClient,
extmocks.NewMockStore[*types.P2PSignedHeader](t),
extmocks.NewMockStore[*types.P2PData](t),
noopDAHintAppender{},
noopDAHintAppender{},
zerolog.Nop(),
NopMetrics(),
DefaultBlockOptions(),
nil,
signer,
)
require.NoError(t, err)
require.NoError(t, components.Submitter.Start(ctx))
t.Cleanup(func() { _ = components.Submitter.Stop() })

for range 2 { // header and data
select {
case <-submitted:
case <-time.After(5 * time.Second):
t.Fatal("sync node with a signer did not post its own block")
}
}
}

func TestNewSyncComponents_WithoutDA(t *testing.T) {
ds := sync.MutexWrap(datastore.NewMapDatastore())
memStore := store.New(ds)
Expand All @@ -159,6 +228,7 @@ func TestNewSyncComponents_WithoutDA(t *testing.T) {
NopMetrics(),
DefaultBlockOptions(),
nil,
nil,
)

require.NoError(t, err)
Expand Down Expand Up @@ -212,6 +282,7 @@ func TestNewSyncComponents_WithoutDADoesNotRestoreDAInclusionCache(t *testing.T)
NopMetrics(),
DefaultBlockOptions(),
nil,
nil,
)
require.NoError(t, err)
require.Nil(t, components.Submitter)
Expand Down
10 changes: 8 additions & 2 deletions block/internal/cache/pending_base.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ type pendingBase[T any] struct {
pendingCache *lru.Cache[uint64, T]

mu sync.Mutex // Protects getPending logic

// setMu orders cursor updates with their writes to the store, so a
// delayed caller cannot persist a lower height over a higher one.
setMu sync.Mutex
}

// newPendingBase constructs a new pendingBase for a given type.
Expand Down Expand Up @@ -125,8 +129,10 @@ func (pb *pendingBase[T]) getLastSubmittedHeight() uint64 {
}

func (pb *pendingBase[T]) setLastSubmittedHeight(ctx context.Context, newLastSubmittedHeight uint64) {
lsh := pb.lastHeight.Load()
if newLastSubmittedHeight > lsh && pb.lastHeight.CompareAndSwap(lsh, newLastSubmittedHeight) {
pb.setMu.Lock()
defer pb.setMu.Unlock()
if newLastSubmittedHeight > pb.lastHeight.Load() {
pb.lastHeight.Store(newLastSubmittedHeight)
bz := make([]byte, 8)
binary.LittleEndian.PutUint64(bz, newLastSubmittedHeight)
err := pb.store.SetMetadata(ctx, pb.metaKey, bz)
Expand Down
157 changes: 157 additions & 0 deletions block/internal/submitting/submitter.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,83 @@ func (s *Submitter) Stop() error {
case <-time.After(5 * time.Second):
s.logger.Warn().Msg("submitter shutdown timed out waiting for goroutines, proceeding anyway")
}
s.flushOwnPending()
Comment thread
damiannolan marked this conversation as resolved.
Resolved
s.logger.Info().Msg("submitter stopped")
return nil
}

// flushTimeout bounds the final submission on stop, so an unavailable DA
// layer cannot hold up shutdown or a hand-over to a new proposer.
const flushTimeout = 10 * time.Second

// flushOwnPending submits what this node produced but has not yet posted.
// Only a block's producer can sign it for DA, so a proposer demoted by a
// rotation that stops without posting leaves a gap no other node can fill.
// The executor is stopped before the submitter, so no new blocks arrive.
// Raft is skipped: its nodes share one key and the new leader resumes from
// the replicated last submitted height, so a flush would only duplicate blobs.
// A sync-mode submitter is skipped too: the next role's submission loop posts
// the same blocks, and a flush would hold up promotion while DA is slow.
func (s *Submitter) flushOwnPending() {
if s.signer == nil || s.daSubmitter == nil || s.config.Raft.Enable || !s.config.Node.Aggregator {
return
}
ctx, cancel := context.WithTimeout(context.Background(), flushTimeout)
defer cancel()

if s.headerSubmissionMtx.TryLock() {
err := drainOwnPending(func() (bool, error) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
headers, marshalled, err := s.cache.GetPendingHeaders(ctx)
if err != nil {
return false, err
}
if headers, marshalled = s.ownPendingHeaders(ctx, headers, marshalled); len(headers) == 0 {
return false, nil
}
before := s.cache.GetLastSubmittedHeaderHeight()
err = s.daSubmitter.SubmitHeaders(ctx, headers, marshalled, s.cache, s.signer)
return s.cache.GetLastSubmittedHeaderHeight() > before, err
})
s.headerSubmissionMtx.Unlock()
if err != nil {
s.logger.Warn().Err(err).Msg("failed to flush pending headers on stop")
}
} else {
s.logger.Warn().Msg("skipping header flush on stop: a submission is still in progress")
}

if s.dataSubmissionMtx.TryLock() {
err := drainOwnPending(func() (bool, error) {
data, marshalled, err := s.cache.GetPendingData(ctx)
if err != nil {
return false, err
}
if data, marshalled = s.ownPendingData(ctx, data, marshalled); len(data) == 0 {
return false, nil
}
before := s.cache.GetLastSubmittedDataHeight()
err = s.daSubmitter.SubmitData(ctx, data, marshalled, s.cache, s.signer)
return s.cache.GetLastSubmittedDataHeight() > before, err
})
s.dataSubmissionMtx.Unlock()
if err != nil {
s.logger.Warn().Err(err).Msg("failed to flush pending data on stop")
}
} else {
s.logger.Warn().Msg("skipping data flush on stop: a submission is still in progress")
}
}

// drainOwnPending repeats submitNext while it makes progress, since each DA
// submission posts at most one size-limited batch.
func drainOwnPending(submitNext func() (progressed bool, err error)) error {
for {
if progressed, err := submitNext(); err != nil || !progressed {
return err
}
}
}

// daSubmissionLoop handles submission of headers and data to DA layer (aggregator nodes only)
func (s *Submitter) daSubmissionLoop() {
s.logger.Info().Msg("starting DA submission loop")
Expand Down Expand Up @@ -210,6 +283,10 @@ func (s *Submitter) daSubmissionLoop() {
s.logger.Error().Err(err).Msg("failed to get pending headers for batching decision")
return
}
headers, marshalledHeaders = s.ownPendingHeaders(s.ctx, headers, marshalledHeaders)
if len(headers) == 0 {
return
}

// Calculate total size (excluding signature)
totalSize := uint64(0)
Expand Down Expand Up @@ -270,6 +347,10 @@ func (s *Submitter) daSubmissionLoop() {
s.logger.Error().Err(err).Msg("failed to get pending data for batching decision")
return
}
signedDataList, marshalledData = s.ownPendingData(s.ctx, signedDataList, marshalledData)
if len(signedDataList) == 0 {
return
}

// Calculate total size (excluding signature)
totalSize := uint64(0)
Expand Down Expand Up @@ -375,10 +456,85 @@ func (s *Submitter) processDAInclusionLoop() {
// This can only be performed after the height has been persisted to store
s.cache.DeleteHeight(nextHeight)
}
s.skipDAIncludedSubmissions(s.ctx)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
}

// ownPendingHeaders returns the first run of pending headers produced by the
// local signer, moving the cursor past any produced by another proposer before it.
func (s *Submitter) ownPendingHeaders(ctx context.Context, headers []*types.SignedHeader, marshalled [][]byte) ([]*types.SignedHeader, [][]byte) {
addr, err := s.signer.GetAddress()
if err != nil {
s.logger.Error().Err(err).Msg("failed to get signer address")
return nil, nil
}
start, end := ownRun(len(headers), func(i int) (bool, error) {
return signedBy(headers[i], addr), nil
})
if start > 0 {
s.cache.SetLastSubmittedHeaderHeight(ctx, headers[start-1].Height())
}
return headers[start:end], marshalled[start:end]
}

// ownPendingData is ownPendingHeaders for data, which takes its producer from
// the header stored at the same height.
func (s *Submitter) ownPendingData(ctx context.Context, data []*types.SignedData, marshalled [][]byte) ([]*types.SignedData, [][]byte) {
addr, err := s.signer.GetAddress()
if err != nil {
s.logger.Error().Err(err).Msg("failed to get signer address")
return nil, nil
}
start, end := ownRun(len(data), func(i int) (bool, error) {
header, err := s.store.GetHeader(ctx, data[i].Height())
if err != nil {
return false, err
}
return signedBy(header, addr), nil
})
if start > 0 {
s.cache.SetLastSubmittedDataHeight(ctx, data[start-1].Height())
}
return data[start:end], marshalled[start:end]
}

// ownRun returns the bounds of the first run of items the local signer
// produced. Only a block's producer can sign its DA envelope and data, so
// another proposer's blocks are left to it: leading ones are skipped, and the
// run stops before the next one so the submission cursor stays contiguous.
// An item whose producer cannot be determined ends the run without skipping it.
func ownRun(n int, isOwn func(i int) (bool, error)) (start, end int) {
for ; start < n; start++ {
own, err := isOwn(start)
if err != nil {
return start, start
}
if own {
break
}
}
for end = start; end < n; end++ {
if own, err := isOwn(end); err != nil || !own {
break
}
}
return start, end
}

func signedBy(header *types.SignedHeader, addr []byte) bool {
return len(header.Signer.Address) == 0 || bytes.Equal(header.Signer.Address, addr)
}

// skipDAIncludedSubmissions moves the pending submission cursors past the DA
// included height, so a node promoted after syncing does not walk every block
// it synced before reaching its own.
func (s *Submitter) skipDAIncludedSubmissions(ctx context.Context) {
h := s.GetDAIncludedHeight()
s.cache.SetLastSubmittedHeaderHeight(ctx, h)
s.cache.SetLastSubmittedDataHeight(ctx, h)
}

// setFinalWithRetry sets the final height in executor with retry logic.
// NOTE: the function retries the execution client call regardless of the error. Callers decide how to handle exhaustion.
func (s *Submitter) setFinalWithRetry(nextHeight uint64) error {
Expand Down Expand Up @@ -422,6 +578,7 @@ func (s *Submitter) SetDAIncludedHeight(height uint64) {
func (s *Submitter) initializeDAIncludedHeight(ctx context.Context) error {
if height, err := s.store.GetMetadata(ctx, store.DAIncludedHeightKey); err == nil && len(height) == 8 {
s.SetDAIncludedHeight(binary.LittleEndian.Uint64(height))
s.skipDAIncludedSubmissions(ctx)
}
return nil
}
Expand Down
Loading
Loading