code.vegaprotocol.io/vega@v0.79.0/core/processor/processor.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package processor
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  	"time"
    22  
    23  	"code.vegaprotocol.io/vega/core/assets"
    24  	"code.vegaprotocol.io/vega/core/broker"
    25  	dscommon "code.vegaprotocol.io/vega/core/datasource/common"
    26  	"code.vegaprotocol.io/vega/core/datasource/external/ethcall"
    27  	"code.vegaprotocol.io/vega/core/events"
    28  	"code.vegaprotocol.io/vega/core/execution/common"
    29  	"code.vegaprotocol.io/vega/core/governance"
    30  	"code.vegaprotocol.io/vega/core/netparams"
    31  	"code.vegaprotocol.io/vega/core/types"
    32  	"code.vegaprotocol.io/vega/libs/crypto"
    33  	"code.vegaprotocol.io/vega/libs/num"
    34  	commandspb "code.vegaprotocol.io/vega/protos/vega/commands/v1"
    35  
    36  	abcitypes "github.com/cometbft/cometbft/abci/types"
    37  	"github.com/pkg/errors"
    38  )
    39  
    40  //go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/processor TimeService,EpochService,DelegationEngine,ExecutionEngine,GovernanceEngine,Stats,Assets,ValidatorTopology,Notary,EvtForwarder,EvtForwarderHeartbeat,Witness,Banking,NetworkParameters,OraclesEngine,OracleAdaptors,Limits,StakeVerifier,StakingAccounts,ERC20MultiSigTopology,Checkpoint,Broker,SpamEngine,PoWEngine,SnapshotEngine,StateVarEngine,TeamsEngine,ReferralProgram,VolumeDiscountProgram,VolumeRebateProgram,BlockchainClient,ProtocolUpgradeService,EthCallEngine,BalanceChecker,PartiesEngine,TxCache,EthereumOracleVerifier,Codec
    41  
    42  var (
    43  	ErrChainEventFromNonValidator             = errors.New("chain event emitted from a non-validator node")
    44  	ErrUnsupportedChainEvent                  = errors.New("unsupported chain event")
    45  	ErrNodeSignatureFromNonValidator          = errors.New("node signature not sent by validator")
    46  	ErrNodeSignatureWithNonValidatorMasterKey = errors.New("node signature not signed with validator master key")
    47  	ErrMarketBatchInstructionTooBig           = func(got, expected uint64) error {
    48  		return fmt.Errorf("market batch instructions too big, got(%d), expected(%d)", got, expected)
    49  	}
    50  	ErrParentMarketAlreadySucceeded = errors.New("parent market already was already succeeded")
    51  )
    52  
    53  type TimeService interface {
    54  	GetTimeNow() time.Time
    55  	GetTimeLastBatch() time.Time
    56  	NotifyOnTick(...func(context.Context, time.Time))
    57  	SetTimeNow(context.Context, time.Time)
    58  }
    59  
    60  type EpochService interface {
    61  	NotifyOnEpoch(f func(context.Context, types.Epoch), r func(context.Context, types.Epoch))
    62  	OnBlockEnd(ctx context.Context)
    63  }
    64  
    65  type DelegationEngine interface {
    66  	Delegate(ctx context.Context, party string, nodeID string, amount *num.Uint) error
    67  	UndelegateAtEndOfEpoch(ctx context.Context, party string, nodeID string, amount *num.Uint) error
    68  	UndelegateNow(ctx context.Context, party string, nodeID string, amount *num.Uint) error
    69  	ProcessEpochDelegations(ctx context.Context, epoch types.Epoch) []*types.ValidatorData
    70  	Hash() []byte
    71  }
    72  
    73  //nolint:interfacebloat
    74  type ExecutionEngine interface {
    75  	CheckCanSubmitOrderOrLiquidityCommitment(party, market string) error
    76  	CheckOrderSubmissionForSpam(orderSubmission *types.OrderSubmission, party string) error
    77  
    78  	// orders stuff
    79  	SubmitOrder(ctx context.Context, orderSubmission *types.OrderSubmission, party string, idgen common.IDGenerator, orderID string) (*types.OrderConfirmation, error)
    80  	CancelOrder(ctx context.Context, order *types.OrderCancellation, party string, idgen common.IDGenerator) ([]*types.OrderCancellationConfirmation, error)
    81  	AmendOrder(ctx context.Context, order *types.OrderAmendment, party string, idgen common.IDGenerator) (*types.OrderConfirmation, error)
    82  
    83  	// stop orders stuff
    84  	SubmitStopOrders(ctx context.Context, stopOrdersSubmission *types.StopOrdersSubmission, party string, idgen common.IDGenerator, stopOrderID1, stopOrderID2 *string) (*types.OrderConfirmation, error)
    85  	CancelStopOrders(ctx context.Context, stopOrdersCancellation *types.StopOrdersCancellation, party string, idgen common.IDGenerator) error
    86  
    87  	// Future stuff
    88  	SubmitMarket(ctx context.Context, marketConfig *types.Market, proposer string, oos time.Time) error
    89  	UpdateMarket(ctx context.Context, marketConfig *types.Market) error
    90  	RejectMarket(ctx context.Context, marketid string) error
    91  	StartOpeningAuction(ctx context.Context, marketid string) error
    92  	SucceedMarket(ctx context.Context, successor, parent string) error
    93  
    94  	// Spot stuff
    95  	SubmitSpotMarket(ctx context.Context, marketConfig *types.Market, proposer string, oos time.Time) error
    96  	UpdateSpotMarket(ctx context.Context, marketConfig *types.Market) error
    97  
    98  	// LP stuff
    99  	SubmitLiquidityProvision(ctx context.Context, sub *types.LiquidityProvisionSubmission, party, deterministicID string) error
   100  	CancelLiquidityProvision(ctx context.Context, order *types.LiquidityProvisionCancellation, party string) error
   101  	AmendLiquidityProvision(ctx context.Context, order *types.LiquidityProvisionAmendment, party string, deterministicID string) error
   102  	VerifyUpdateMarketState(changes *types.MarketStateUpdateConfiguration) error
   103  	UpdateMarketState(ctx context.Context, changes *types.MarketStateUpdateConfiguration) error
   104  	Hash() []byte
   105  
   106  	// End of block
   107  	BlockEnd(ctx context.Context)
   108  	BeginBlock(ctx context.Context, duration time.Duration)
   109  
   110  	// Margin mode
   111  	UpdateMarginMode(ctx context.Context, party, marketID string, marginMode types.MarginMode, marginFactor num.Decimal) error
   112  	// default chain ID, can be removed once we've upgraded to v0.74
   113  	OnChainIDUpdate(uint64) error
   114  
   115  	SubmitAMM(ctx context.Context, sub *types.SubmitAMM, deterministicID string) error
   116  	AmendAMM(ctx context.Context, sub *types.AmendAMM, deterministicID string) error
   117  	CancelAMM(ctx context.Context, sub *types.CancelAMM, deterministicID string) error
   118  
   119  	// add this method here for testing, this is the exec engine interface used by the gastimator.
   120  	GetMarketCounters() map[string]*types.MarketCounters
   121  	NewProtocolAutomatedPurchase(ctx context.Context, ID string, automatedPurchaseConfig *types.NewProtocolAutomatedPurchaseChanges) error
   122  }
   123  
   124  type GovernanceEngine interface {
   125  	SubmitProposal(context.Context, types.ProposalSubmission, string, string) (*governance.ToSubmit, error)
   126  	SubmitBatchProposal(context.Context, types.BatchProposalSubmission, string, string) ([]*governance.ToSubmit, error)
   127  	FinaliseEnactment(ctx context.Context, prop *types.Proposal)
   128  	AddVote(context.Context, types.VoteSubmission, string) error
   129  	OnTick(context.Context, time.Time) ([]*governance.ToEnact, []*governance.VoteClosed)
   130  	RejectProposal(context.Context, *types.Proposal, types.ProposalError, error) error
   131  	RejectBatchProposal(context.Context, string, types.ProposalError, error) error
   132  	Hash() []byte
   133  	OnChainIDUpdate(uint64) error
   134  }
   135  
   136  //nolint:interfacebloat
   137  type Stats interface {
   138  	IncTotalCreateOrder()
   139  	AddCurrentTradesInBatch(i uint64)
   140  	AddTotalTrades(i uint64) uint64
   141  	IncTotalOrders()
   142  	IncCurrentOrdersInBatch()
   143  	IncTotalCancelOrder()
   144  	IncTotalAmendOrder()
   145  	// batch stats
   146  	IncTotalBatches()
   147  	NewBatch()
   148  	TotalOrders() uint64
   149  	TotalBatches() uint64
   150  	SetAverageOrdersPerBatch(i uint64)
   151  	SetBlockDuration(uint64)
   152  	CurrentOrdersInBatch() uint64
   153  	CurrentTradesInBatch() uint64
   154  	SetOrdersPerSecond(i uint64)
   155  	SetTradesPerSecond(i uint64)
   156  	CurrentEventsInBatch() uint64
   157  	SetEventsPerSecond(uint64)
   158  	// blockchain stats
   159  	IncTotalTxCurrentBatch()
   160  	IncHeight()
   161  	Height() uint64
   162  	SetAverageTxPerBatch(i uint64)
   163  	SetAverageTxSizeBytes(i uint64)
   164  	SetTotalTxLastBatch(i uint64)
   165  	SetTotalTxCurrentBatch(i uint64)
   166  	TotalTxCurrentBatch() uint64
   167  	TotalTxLastBatch() uint64
   168  	SetHash(string)
   169  	SetHeight(uint64)
   170  }
   171  
   172  type Assets interface {
   173  	NewAsset(ctx context.Context, ref string, assetSrc *types.AssetDetails) (string, error)
   174  	StageAssetUpdate(*types.Asset) error
   175  	Get(assetID string) (*assets.Asset, error)
   176  	IsEnabled(string) bool
   177  	EnactPendingAsset(assetID string)
   178  }
   179  
   180  //nolint:interfacebloat
   181  type ValidatorTopology interface {
   182  	Len() int
   183  	IsValidatorVegaPubKey(pk string) bool
   184  	IsValidatorNodeID(nodeID string) bool
   185  	AllVegaPubKeys() []string
   186  	IsValidator() bool
   187  	AddKeyRotate(ctx context.Context, nodeID string, currentBlockHeight uint64, kr *commandspb.KeyRotateSubmission) error
   188  	ProcessEthereumKeyRotation(ctx context.Context, nodeID string, kr *commandspb.EthereumKeyRotateSubmission, verify func(message, signature []byte, hexAddress string) error) error
   189  	BeginBlock(ctx context.Context, blockHeight uint64, proposer string)
   190  	GetValidatorPowerUpdates() []abcitypes.ValidatorUpdate
   191  	ProcessAnnounceNode(ctx context.Context, nr *commandspb.AnnounceNode) error
   192  	ProcessValidatorHeartbeat(context.Context, *commandspb.ValidatorHeartbeat, func(message, signature, pubkey []byte) error, func(message, signature []byte, hexAddress string) error) error
   193  	AddForwarder(ID string)
   194  	IssueSignatures(ctx context.Context, submitter, nodeID, chainID string, kind types.NodeSignatureKind) error
   195  }
   196  
   197  // Broker - the event bus.
   198  type Broker interface {
   199  	Send(e events.Event)
   200  	SetStreaming(on bool) bool
   201  	StreamingEnabled() bool
   202  	SocketClient() broker.SocketClient
   203  }
   204  
   205  // Notary.
   206  type Notary interface {
   207  	StartAggregate(resID string, kind commandspb.NodeSignatureKind, signature []byte)
   208  	RegisterSignature(ctx context.Context, pubKey string, ns commandspb.NodeSignature) error
   209  	IsSigned(context.Context, string, commandspb.NodeSignatureKind) ([]commandspb.NodeSignature, bool)
   210  }
   211  
   212  // Witness ...
   213  type Witness interface {
   214  	AddNodeCheck(ctx context.Context, nv *commandspb.NodeVote, key crypto.PublicKey) error
   215  }
   216  
   217  // EvtForwarder ...
   218  type EvtForwarder interface {
   219  	Ack(*commandspb.ChainEvent) bool
   220  }
   221  
   222  // EvtForwarderHeartbeat ...
   223  type EvtForwarderHeartbeat interface {
   224  	ProcessHeartbeat(string, string, uint64, uint64) error
   225  }
   226  
   227  // Banking ..
   228  //
   229  //nolint:interfacebloat
   230  type Banking interface {
   231  	EnableBuiltinAsset(context.Context, string) error
   232  	DepositBuiltinAsset(context.Context, *types.BuiltinAssetDeposit, string, uint64) error
   233  	WithdrawBuiltinAsset(context.Context, string, string, string, *num.Uint) error
   234  	EnableERC20(context.Context, *types.ERC20AssetList, string, uint64, uint64, string, string) error
   235  	UpdateERC20(context.Context, *types.ERC20AssetLimitsUpdated, string, uint64, uint64, string, string) error
   236  	DepositERC20(context.Context, *types.ERC20Deposit, string, uint64, uint64, string, string) error
   237  	WithdrawERC20(context.Context, string, string, string, *num.Uint, *types.Erc20WithdrawExt) error
   238  	ERC20WithdrawalEvent(context.Context, *types.ERC20Withdrawal, uint64, string, string) error
   239  	TransferFunds(context.Context, *types.TransferFunds) error
   240  	CancelTransferFunds(context.Context, *types.CancelTransferFunds) error
   241  	BridgeStopped(context.Context, bool, string, uint64, uint64, string, string) error
   242  	BridgeResumed(context.Context, bool, string, uint64, uint64, string, string) error
   243  	CheckTransfer(t *types.TransferBase) error
   244  	NewGovernanceTransfer(ctx context.Context, ID, reference string, transferConfig *types.NewTransferConfiguration) error
   245  	VerifyGovernanceTransfer(transfer *types.NewTransferConfiguration) error
   246  	VerifyCancelGovernanceTransfer(transferID string) error
   247  	CancelGovTransfer(ctx context.Context, ID string) error
   248  	OnBlockEnd(ctx context.Context, now time.Time)
   249  }
   250  
   251  // NetworkParameters ...
   252  type NetworkParameters interface {
   253  	Update(ctx context.Context, key, value string) error
   254  	DispatchChanges(ctx context.Context)
   255  	IsUpdateAllowed(key string) error
   256  	GetInt(key string) (int64, error)
   257  	GetJSONStruct(key string, v netparams.Reset) error
   258  }
   259  
   260  type Oracle struct {
   261  	Engine                    OraclesEngine
   262  	Adaptors                  OracleAdaptors
   263  	EthereumOraclesVerifier   EthereumOracleVerifier
   264  	EthereumL2OraclesVerifier EthereumOracleVerifier
   265  }
   266  
   267  type OraclesEngine interface {
   268  	BroadcastData(context.Context, dscommon.Data) error
   269  	ListensToSigners(dscommon.Data) bool
   270  	HasMatch(data dscommon.Data) (bool, error)
   271  }
   272  
   273  type OracleAdaptors interface {
   274  	Normalise(crypto.PublicKey, commandspb.OracleDataSubmission) (*dscommon.Data, error)
   275  }
   276  
   277  type EthereumOracleVerifier interface {
   278  	ProcessEthereumContractCallResult(callEvent ethcall.ContractCallEvent) error
   279  }
   280  
   281  type Limits interface {
   282  	CanProposeMarket() bool
   283  	CanProposeAsset() bool
   284  	CanProposeSpotMarket() bool
   285  	CanProposePerpsMarket() bool
   286  	CanUseAMMPool() bool
   287  	CanTrade() bool
   288  }
   289  
   290  type StakeVerifier interface {
   291  	ProcessStakeRemoved(ctx context.Context, event *types.StakeRemoved) error
   292  	ProcessStakeDeposited(ctx context.Context, event *types.StakeDeposited) error
   293  }
   294  
   295  type StakingAccounts interface {
   296  	Hash() []byte
   297  	ProcessStakeTotalSupply(ctx context.Context, event *types.StakeTotalSupply) error
   298  }
   299  
   300  type ERC20MultiSigTopology interface {
   301  	ProcessSignerEvent(event *types.SignerEvent) error
   302  	ProcessThresholdEvent(event *types.SignerThresholdSetEvent) error
   303  }