mempool

package
v0.0.0-...-7ece11e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 29, 2023 License: MIT Imports: 26 Imported by: 2

README

Memory pool for transactions

This package will process txs which are received from other peers in a broadcast tx message. We need to make some policy and validation to check tx before add it into mempool.

Which valid txs in mempool, mining processing will get them and make consensus to create a new block

@Note: this is only one type of tx resource for mining

Documentation

Index

Constants

View Source
const (
	RejectDuplicateTx = iota
	RejectInvalidTx
	RejectSanityTx
	RejectSanityTxLocktime
	RejectSalaryTx
	RejectDuplicateStakePubkey
	RejectDuplicateRequestStopAutoStaking
	RejectVersion
	RejectInvalidTxType
	RejectDoubleSpendWithMempoolTx
	RejectDoubleSpendWithBlockchainTx
	RejectMetadataWithBlockchainTx
	RejectInvalidFee
	RejectInvalidSize
	CanNotCheckDoubleSpend
	DatabaseError
	MarshalError
	UnmarshalShardCommitteeError
	DuplicateBlockError
	OldBlockError
	MaxPoolSizeError
	UnexpectedTransactionError
	TransactionNotFoundError
	RejectTestTransactionError
	WrongShardIDError
	HashError
	RejectReplacementTxError
	GetStakingMetadataError
	WalletKeySerializedError
	GetBeaconBlockHashFromDatabaseError
	FetchBeaconBlockFromDatabaseError
	UnmarshalBeaconBlockError
	FindBeaconHeightForCrossShardBlockError
	ValidateAggSignatureForCrossShardBlockError
	DuplicateSerialNumbersHashError
	CouldNotGetExchangeRateError
)
View Source
const (

	// DefaultEstimateFeeMaxRollback is the default number of rollbacks
	// allowed by the fee estimator for orphaned blocks.
	DefaultEstimateFeeMaxRollback = 2

	// DefaultEstimateFeeMinRegisteredBlocks is the default minimum
	// number of blocks which must be observed by the fee estimator before
	// it will provide fee estimations.
	DefaultEstimateFeeMinRegisteredBlocks = 3
)

Variables

View Source
var ErrCodeMessage = map[int]struct {
	Code    int
	Message string
}{
	RejectDuplicateTx:                           {-1000, "Reject duplicate tx in mempool"},
	RejectInvalidTx:                             {-1001, "Reject invalid tx"},
	RejectSanityTx:                              {-1002, "Reject not sansity tx"},
	RejectSalaryTx:                              {-1003, "Reject salary tx"},
	RejectInvalidFee:                            {-1004, "Reject invalid fee"},
	RejectVersion:                               {-1005, "Reject invalid version"},
	CanNotCheckDoubleSpend:                      {-1006, "Can not check double spend"},
	DatabaseError:                               {-1007, "Database Error"},
	RejectDuplicateStakePubkey:                  {-1008, "Reject Duplicate Stake Error"},
	DuplicateBlockError:                         {-1009, "Duplicate Block Error"},
	OldBlockError:                               {-1010, "Old Block Error"},
	MaxPoolSizeError:                            {-1011, "Max Pool Size Error"},
	UnexpectedTransactionError:                  {-1012, "Unexpected Transaction Error"},
	TransactionNotFoundError:                    {-1013, "Transaction Not Found Error"},
	RejectTestTransactionError:                  {-1014, "Reject Test Transaction Error"},
	RejectInvalidTxType:                         {-1015, "Reject Invalid Tx Type"},
	RejectDoubleSpendWithMempoolTx:              {-1016, "Reject Double Spend With Other Tx in mempool"},
	RejectDoubleSpendWithBlockchainTx:           {-1017, "Reject Double Spend With Current Blockchain"},
	WrongShardIDError:                           {-1018, "Reject Cross Shard Block With Same ShardID in Pool"},
	MarshalError:                                {-1019, "Marshal Error"},
	UnmarshalShardCommitteeError:                {-1020, "Unmarshal Shard Committee Error"},
	HashError:                                   {-1021, "Hash Error"},
	RejectReplacementTxError:                    {-1022, "Replacement or Cancel Tx Error"},
	GetStakingMetadataError:                     {-1023, "Get Staking Metadata Error"},
	WalletKeySerializedError:                    {-1024, "Wallet Key Serialized Error"},
	GetBeaconBlockHashFromDatabaseError:         {-1025, "Get Beacon Block Hash From Database Error"},
	FetchBeaconBlockFromDatabaseError:           {-1026, "Fetch Beacon Block From Database Error"},
	UnmarshalBeaconBlockError:                   {-1027, "Unmarshal Beacon Block Error"},
	FindBeaconHeightForCrossShardBlockError:     {-1028, "Find Beacon Height For Cross Shard Block Error"},
	ValidateAggSignatureForCrossShardBlockError: {-1029, "Validate Agg Signature For Cross Shard Block Error"},
	RejectDuplicateRequestStopAutoStaking:       {-1030, "Reject Duplicate Request Stop Auto Staking"},
	DuplicateSerialNumbersHashError:             {-1031, "Duplicate Serial Numbers Hash Error"},
	CouldNotGetExchangeRateError:                {-1032, "Could not get the exchange rate error"},
	RejectSanityTxLocktime:                      {-1033, "Wrong tx locktime"},
	RejectMetadataWithBlockchainTx:              {-1034, "Reject invalid metadata with blockchain"},
}
View Source
var (
	// EstimateFeeDatabaseKey is the key that we use to
	// store the fee estimator in the database.
	EstimateFeeDatabaseKey = []byte("estimatefee")
)
View Source
var Logger = MempoolLogger{}

Global instant to use

Functions

func NewCoinPerKilobyte

func NewCoinPerKilobyte(fee uint64, size uint64) uint64

NewCoinPerKilobyte creates a CoinPerByte from an Amount and a size in bytes.

Types

type BlockPoolError

type BlockPoolError struct {
	Code    int
	Message string
	Err     error
}

func (*BlockPoolError) Error

func (e *BlockPoolError) Error() string

func (*BlockPoolError) Init

func (e *BlockPoolError) Init(key int, err error)

type Config

type Config struct {
	ConsensusEngine interface {
		IsCommitteeInShard(shardID byte) bool
	}
	BlockChain        *blockchain.BlockChain       // Block chain of node
	DataBase          map[int]incdb.Database       // main database of blockchain
	DataBaseMempool   databasemp.DatabaseInterface // database is used for storage data in mempool into lvdb
	FeeEstimator      map[byte]*FeeEstimator       // FeeEstimatator provides a feeEstimator. If it is not nil, the mempool records all new transactions it observes into the feeEstimator.
	TxLifeTime        uint                         // Transaction life time in pool
	MaxTx             uint64                       //Max transaction pool may have
	IsLoadFromMempool bool                         //Reset mempool database when run node
	PersistMempool    bool
	RelayShards       []byte
	// UserKeyset            *incognitokey.KeySet
	PubSubManager interface {
		PublishMessage(message *pubsub.Message)
	}
}

config is a descriptor containing the memory pool configuration.

type FeeEstimator

type FeeEstimator struct {
	// contains filtered or unexported fields
}

feeEstimator manages the data necessary to create fee estimations. It is safe for concurrent access.

func NewFeeEstimator

func NewFeeEstimator(maxRollback, minRegisteredBlocks uint32, limitFee, minFeePerTx, specifiedFeeTx, specifiedFeePerKBType2, specifiedFeePerTxType2 uint64) *FeeEstimator

NewFeeEstimator creates a feeEstimator for which at most maxRollback blocks can be unregistered and which returns an error unless minRegisteredBlocks have been registered with it.

func RestoreFeeEstimator

func RestoreFeeEstimator(data FeeEstimatorState) (*FeeEstimator, error)

RestoreFeeEstimator takes a FeeEstimatorState that was previously returned by Save and restores it to a feeEstimator

func (*FeeEstimator) EstimateFee

func (ef *FeeEstimator) EstimateFee(numBlocks uint64, tokenId *common.Hash) (uint64, error)

EstimateFee estimates the fee per byte to have a tx confirmed a given number of blocks from now.

func (FeeEstimator) GetLimitFeeForNativeToken

func (ef FeeEstimator) GetLimitFeeForNativeToken() uint64

returns the limit fee (min fee per kb)

func (FeeEstimator) GetMinFeePerTx

func (ef FeeEstimator) GetMinFeePerTx() uint64

returns the min fee per tx

func (FeeEstimator) GetSpecifiedFeePerKBType2

func (ef FeeEstimator) GetSpecifiedFeePerKBType2() uint64

returns the specified fee per KB type 2

func (FeeEstimator) GetSpecifiedFeePerTxType2

func (ef FeeEstimator) GetSpecifiedFeePerTxType2() uint64

returns the specified fee per Tx type 2

func (FeeEstimator) GetSpecifiedFeeTx

func (ef FeeEstimator) GetSpecifiedFeeTx() uint64

returns the specified fee tx

func (*FeeEstimator) LastKnownHeight

func (ef *FeeEstimator) LastKnownHeight() uint64

LastKnownHeight returns the height of the last block which was registered.

func (*FeeEstimator) ObserveTransaction

func (ef *FeeEstimator) ObserveTransaction(t *TxDesc)

ObserveTransaction is called when a new transaction is observed in the mempool.

func (*FeeEstimator) RegisterBlock

func (ef *FeeEstimator) RegisterBlock(block *types.ShardBlock) error

RegisterBlock informs the fee estimator of a new block to take into account.

func (*FeeEstimator) Rollback

func (ef *FeeEstimator) Rollback(hash *common.Hash) error

Rollback unregisters a recently registered block from the feeEstimator. This can be used to reverse the effect of an orphaned block on the fee estimator. The maximum number of rollbacks allowed is given by maxRollbacks.

Note: not everything can be rolled back because some transactions are deleted if they have been observed too long ago. That means the result of Rollback won't always be exactly the same as if the last block had not happened, but it should be close enough.

func (*FeeEstimator) Save

func (ef *FeeEstimator) Save() FeeEstimatorState

Save records the current state of the feeEstimator to a []byte that can be restored later.

type FeeEstimatorState

type FeeEstimatorState []byte

FeeEstimatorState represents a saved feeEstimator that can be restored with data from an earlier session of the program.

type MempoolLogger

type MempoolLogger struct {
	// contains filtered or unexported fields
}

func (*MempoolLogger) Init

func (mempoolLogger *MempoolLogger) Init(inst common.Logger)

type MempoolTxError

type MempoolTxError struct {
	Code    int    // The code to send with reject messages
	Message string // Human readable message of the issue
	Err     error
}

func NewMempoolTxError

func NewMempoolTxError(key int, err error) *MempoolTxError

func (MempoolTxError) Error

func (e MempoolTxError) Error() string

Error satisfies the error interface and prints human-readable errors.

type TempDesc

type TempDesc struct {
	StartTime     time.Time
	IsPushMessage bool
	Height        uint64
	Fee           uint64
	FeePerKB      int32
}

type TxDesc

type TxDesc struct {
	Desc            metadata.TxDesc // transaction details
	StartTime       time.Time       //Unix Time that transaction enter mempool
	IsFowardMessage bool
}

TxDesc is transaction message in mempool

type TxPool

type TxPool struct {
	CPendingTxs chan<- metadata.Transaction // channel to deliver txs to block gen
	CRemoveTxs  chan<- metadata.Transaction // channel to deliver txs to block gen

	ScanTime          time.Duration
	IsBlockGenStarted bool
	IsUnlockMempool   bool
	ReplaceFeeRatio   float64

	//for testing
	IsTest bool
	// contains filtered or unexported fields
}

func (*TxPool) AnnouncePersisDatabaseMempool

func (tp *TxPool) AnnouncePersisDatabaseMempool()

func (*TxPool) Count

func (tp *TxPool) Count() int

Count return len of transaction pool

func (*TxPool) EmptyPool

func (tp *TxPool) EmptyPool() bool

func (TxPool) GetClonedPoolCandidate

func (tp TxPool) GetClonedPoolCandidate() map[common.Hash]string

func (TxPool) GetOTAHashH

func (tp TxPool) GetOTAHashH() map[common.Hash][]common.Hash

func (TxPool) GetPool

func (tp TxPool) GetPool() map[common.Hash]*TxDesc

func (TxPool) GetSerialNumbersHashH

func (tp TxPool) GetSerialNumbersHashH() map[common.Hash][]common.Hash

----------- transaction.MempoolRetriever's implementation -----------------

func (*TxPool) GetTx

func (tp *TxPool) GetTx(txHash *common.Hash) (metadata.Transaction, error)

GetTx get transaction info by hash

func (TxPool) GetTxsInMem

func (tp TxPool) GetTxsInMem() map[common.Hash]metadata.TxDesc

func (*TxPool) HaveTransaction

func (tp *TxPool) HaveTransaction(hash *common.Hash) bool

// HaveTransaction returns whether or not the passed transaction hash

// exists in the source pool.

func (*TxPool) Init

func (tp *TxPool) Init(cfg *Config)

Init Txpool from config

func (*TxPool) InitChannelMempool

func (tp *TxPool) InitChannelMempool(cPendingTxs chan metadata.Transaction, cRemoveTxs chan metadata.Transaction)

InitChannelMempool - init channel

func (*TxPool) LastUpdated

func (tp *TxPool) LastUpdated() time.Time

// LastUpdated returns the last time a transaction was added to or

// removed from the source pool.

func (*TxPool) ListTxs

func (tp *TxPool) ListTxs() []string

List all tx ids in mempool

func (*TxPool) ListTxsDetail

func (tp *TxPool) ListTxsDetail() ([]common.Hash, []metadata.Transaction)

List all tx ids in mempool

func (*TxPool) LoadOrResetDatabaseMempool

func (tp *TxPool) LoadOrResetDatabaseMempool() error

LoadOrResetDatabaseMempool - Load and reset database of mempool when start node

func (*TxPool) MarkForwardedTransaction

func (tp *TxPool) MarkForwardedTransaction(txHash common.Hash)

MarkForwardedTransaction - mart a transaction is forward message

func (*TxPool) MaxFee

func (tp *TxPool) MaxFee() uint64

Get Max fee

func (*TxPool) MaybeAcceptBatchTransactionForBlockProducing

func (tp *TxPool) MaybeAcceptBatchTransactionForBlockProducing(shardID byte, txs []metadata.Transaction, beaconHeight int64, shardView *blockchain.ShardBestState) ([]*metadata.TxDesc, error)

func (*TxPool) MaybeAcceptSalaryTransactionForBlockProducing

func (tp *TxPool) MaybeAcceptSalaryTransactionForBlockProducing(shardID byte, tx metadata.Transaction, beaconHeight int64, shardView *blockchain.ShardBestState) (*metadata.TxDesc, error)

MaybeAcceptSalaryTransactionForBlockProducing performs the following validations on minteable transactions

  • Validate transaction sanity
  • Validate transaction with current mempool
  • Validate transaction by itself
  • Validate transaction with blockchain

func (*TxPool) MaybeAcceptTransaction

func (tp *TxPool) MaybeAcceptTransaction(tx metadata.Transaction, beaconHeight int64) (*common.Hash, *TxDesc, error)

MaybeAcceptTransaction is the main workhorse for handling insertion of new free-standing transactions into a memory pool. It includes functionality such as rejecting duplicate transactions, ensuring transactions follow all rules, detecting orphan transactions, and insertion into the memory pool.

If the transaction is an orphan (missing parent transactions), the transaction is NOT added to the orphan pool, but each unknown referenced parent is returned. Use ProcessTransaction instead if new orphans should be added to the orphan pool.

This function is safe for concurrent access. #1: tx #2: default nil, contain input coins hash, which are used for creating this tx

func (*TxPool) MaybeAcceptTransactionForBlockProducing

func (tp *TxPool) MaybeAcceptTransactionForBlockProducing(tx metadata.Transaction, beaconHeight int64, shardView *blockchain.ShardBestState) (*metadata.TxDesc, error)

This function is safe for concurrent access.

func (*TxPool) MiningDescs

func (tp *TxPool) MiningDescs() []*metadata.TxDesc

// MiningDescs returns a slice of mining descriptors for all the transactions // in the pool.

func (*TxPool) MonitorPool

func (tp *TxPool) MonitorPool()

func (*TxPool) RemoveCandidateList

func (tp *TxPool) RemoveCandidateList(candidate []string)

func (*TxPool) RemoveRequestStopStakingList

func (tp *TxPool) RemoveRequestStopStakingList(requestStopStakings []string)

func (*TxPool) RemoveStuckTx

func (tp *TxPool) RemoveStuckTx(txHash common.Hash, tx metadata.Transaction)

RemoveStuckTx is to remove a stuck tx from mempool by passing tx hash (not by a hash built from tx object)

func (*TxPool) RemoveTx

func (tp *TxPool) RemoveTx(txs []metadata.Transaction, isInBlock bool)

RemoveTx safe remove transaction for pool

func (*TxPool) SendTransactionToBlockGen

func (tp *TxPool) SendTransactionToBlockGen()

=======================Service for other package SendTransactionToBlockGen - push tx into channel and send to Block generate of consensus

func (*TxPool) Size

func (tp *TxPool) Size() uint64

Sum of all transactions sizes

func (*TxPool) Start

func (tp *TxPool) Start(cQuit chan struct{})

loop forever in mempool receive data from other package

func (*TxPool) TriggerCRemoveTxs

func (tp *TxPool) TriggerCRemoveTxs(tx metadata.Transaction)

TriggerCRemoveTxs - send a tx channel into CRemoveTxs of tx mempool

func (*TxPool) ValidateSerialNumberHashH

func (tp *TxPool) ValidateSerialNumberHashH(serialNumber []byte) error

ValidateSerialNumberHashH - check serialNumberHashH which is used by a tx in mempool

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL