github.com/MetalBlockchain/metalgo@v1.11.9/vms/platformvm/txs/mempool/mempool.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package mempool
     5  
     6  import (
     7  	"errors"
     8  
     9  	"github.com/prometheus/client_golang/prometheus"
    10  
    11  	"github.com/MetalBlockchain/metalgo/snow/engine/common"
    12  	"github.com/MetalBlockchain/metalgo/vms/platformvm/txs"
    13  
    14  	txmempool "github.com/MetalBlockchain/metalgo/vms/txs/mempool"
    15  )
    16  
    17  var (
    18  	_ Mempool = (*mempool)(nil)
    19  
    20  	ErrCantIssueAdvanceTimeTx     = errors.New("can not issue an advance time tx")
    21  	ErrCantIssueRewardValidatorTx = errors.New("can not issue a reward validator tx")
    22  )
    23  
    24  type Mempool interface {
    25  	txmempool.Mempool[*txs.Tx]
    26  
    27  	// RequestBuildBlock notifies the consensus engine that a block should be
    28  	// built. If [emptyBlockPermitted] is true, the notification will be sent
    29  	// regardless of whether there are no transactions in the mempool. If not,
    30  	// a notification will only be sent if there is at least one transaction in
    31  	// the mempool.
    32  	RequestBuildBlock(emptyBlockPermitted bool)
    33  }
    34  
    35  type mempool struct {
    36  	txmempool.Mempool[*txs.Tx]
    37  
    38  	toEngine chan<- common.Message
    39  }
    40  
    41  func New(
    42  	namespace string,
    43  	registerer prometheus.Registerer,
    44  	toEngine chan<- common.Message,
    45  ) (Mempool, error) {
    46  	metrics, err := txmempool.NewMetrics(namespace, registerer)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	pool := txmempool.New[*txs.Tx](
    51  		metrics,
    52  	)
    53  	return &mempool{
    54  		Mempool:  pool,
    55  		toEngine: toEngine,
    56  	}, nil
    57  }
    58  
    59  func (m *mempool) Add(tx *txs.Tx) error {
    60  	switch tx.Unsigned.(type) {
    61  	case *txs.AdvanceTimeTx:
    62  		return ErrCantIssueAdvanceTimeTx
    63  	case *txs.RewardValidatorTx:
    64  		return ErrCantIssueRewardValidatorTx
    65  	default:
    66  	}
    67  
    68  	return m.Mempool.Add(tx)
    69  }
    70  
    71  func (m *mempool) RequestBuildBlock(emptyBlockPermitted bool) {
    72  	if !emptyBlockPermitted && m.Len() == 0 {
    73  		return
    74  	}
    75  
    76  	select {
    77  	case m.toEngine <- common.PendingTxs:
    78  	default:
    79  	}
    80  }