4 "github.com/vapor/application/mov/common"
5 "github.com/vapor/application/mov/contract"
6 "github.com/vapor/application/mov/database"
7 "github.com/vapor/application/mov/match"
8 "github.com/vapor/consensus/segwit"
9 dbm "github.com/vapor/database/leveldb"
10 "github.com/vapor/errors"
11 "github.com/vapor/math/checked"
12 "github.com/vapor/protocol/bc"
13 "github.com/vapor/protocol/bc/types"
16 const maxFeeRate = 0.05
19 errInvalidTradePairs = errors.New("The trade pairs in the tx input is invalid")
20 errStatusFailMustFalse = errors.New("status fail of transaction does not allow to be true")
21 errInputProgramMustP2WMCScript = errors.New("input program of trade tx must p2wmc script")
22 errExistCancelOrderInMatchedTx = errors.New("can't exist cancel order in the matched transaction")
23 errExistTradeInCancelOrderTx = errors.New("can't exist trade in the cancel order transaction")
24 errAmountOfFeeGreaterThanMaximum = errors.New("amount of fee greater than max fee amount")
25 errAssetIDMustUniqueInMatchedTx = errors.New("asset id must unique in matched transaction")
26 errRatioOfTradeLessThanZero = errors.New("ratio arguments must greater than zero")
27 errNumeratorOfRatioIsOverflow = errors.New("ratio numerator of contract args product input amount is overflow")
28 errLengthOfInputIsIncorrect = errors.New("length of matched tx input is not equals to actual matched tx input")
29 errSpendOutputIDIsIncorrect = errors.New("spend output id of matched tx is not equals to actual matched tx")
30 errRequestAmountLessThenOne = errors.New("request amount of order less than one")
33 // MovCore represent the core logic of the match module, which include generate match transactions before packing the block,
34 // verify the match transaction in block is correct, and update the order table according to the transaction.
36 movStore database.MovStore
37 startBlockHeight uint64
40 // NewMovCore return a instance of MovCore by path of mov db
41 func NewMovCore(dbBackend, dbDir string, startBlockHeight uint64) *MovCore {
42 movDB := dbm.NewDB("mov", dbBackend, dbDir)
43 return &MovCore{movStore: database.NewLevelDBMovStore(movDB), startBlockHeight: startBlockHeight}
46 // ApplyBlock parse pending order and cancel from the the transactions of block
47 // and add pending order to the dex db, remove cancel order from dex db.
48 func (m *MovCore) ApplyBlock(block *types.Block) error {
49 if block.Height < m.startBlockHeight {
53 if block.Height == m.startBlockHeight {
54 blockHash := block.Hash()
55 if err := m.movStore.InitDBState(block.Height, &blockHash); err != nil {
62 if err := m.validateMatchedTxSequence(block.Transactions); err != nil {
66 addOrders, deleteOrders, err := applyTransactions(block.Transactions)
71 return m.movStore.ProcessOrders(addOrders, deleteOrders, &block.BlockHeader)
75 @issue: I have two orders A and B, order A's seller program is order B and order B's seller program is order A.
76 Assume consensus node accept 0% fee and This two orders are the only two order of this trading pair, will this
77 become an infinite loop and DDoS attacks the whole network?
79 // BeforeProposalBlock return all transactions than can be matched, and the number of transactions cannot exceed the given capacity.
80 func (m *MovCore) BeforeProposalBlock(txs []*types.Tx, nodeProgram []byte, blockHeight uint64, gasLeft int64, isTimeout func() bool) ([]*types.Tx, error) {
81 if blockHeight <= m.startBlockHeight {
85 orderTable, err := buildOrderTable(m.movStore, txs)
90 matchEngine := match.NewEngine(orderTable, maxFeeRate, nodeProgram)
91 tradePairMap := make(map[string]bool)
92 tradePairIterator := database.NewTradePairIterator(m.movStore)
94 var packagedTxs []*types.Tx
95 for gasLeft > 0 && !isTimeout() && tradePairIterator.HasNext() {
96 tradePair := tradePairIterator.Next()
97 if tradePairMap[tradePair.Key()] {
100 tradePairMap[tradePair.Key()] = true
101 tradePairMap[tradePair.Reverse().Key()] = true
103 for gasLeft > 0 && !isTimeout() && matchEngine.HasMatchedTx(tradePair, tradePair.Reverse()) {
104 matchedTx, err := matchEngine.NextMatchedTx(tradePair, tradePair.Reverse())
109 gasUsed := calcMatchedTxGasUsed(matchedTx)
110 if gasLeft-gasUsed >= 0 {
111 packagedTxs = append(packagedTxs, matchedTx)
116 return packagedTxs, nil
119 // ChainStatus return the current block height and block hash in dex core
120 func (m *MovCore) ChainStatus() (uint64, *bc.Hash, error) {
121 state, err := m.movStore.GetMovDatabaseState()
126 return state.Height, state.Hash, nil
129 // DetachBlock parse pending order and cancel from the the transactions of block
130 // and add cancel order to the dex db, remove pending order from dex db.
131 func (m *MovCore) DetachBlock(block *types.Block) error {
132 if block.Height <= m.startBlockHeight {
136 deleteOrders, addOrders, err := applyTransactions(block.Transactions)
141 return m.movStore.ProcessOrders(addOrders, deleteOrders, &block.BlockHeader)
144 // IsDust block the transaction that are not generated by the match engine
145 func (m *MovCore) IsDust(tx *types.Tx) bool {
146 for _, input := range tx.Inputs {
147 if segwit.IsP2WMCScript(input.ControlProgram()) && !contract.IsCancelClauseSelector(input) {
154 // Name return the name of current module
155 func (m *MovCore) Name() string {
159 // StartHeight return the start block height of current module
160 func (m *MovCore) StartHeight() uint64 {
161 return m.startBlockHeight
164 // ValidateBlock no need to verify the block header, because the first module has been verified.
165 // just need to verify the transactions in the block.
166 func (m *MovCore) ValidateBlock(block *types.Block, verifyResults []*bc.TxVerifyResult) error {
167 return m.ValidateTxs(block.Transactions, verifyResults)
170 // ValidateTxs validate the trade transaction.
171 func (m *MovCore) ValidateTxs(txs []*types.Tx, verifyResults []*bc.TxVerifyResult) error {
172 for i, tx := range txs {
173 if err := m.ValidateTx(tx, verifyResults[i]); err != nil {
180 // ValidateTxs validate one transaction.
181 func (m *MovCore) ValidateTx(tx *types.Tx, verifyResult *bc.TxVerifyResult) error {
182 if common.IsMatchedTx(tx) {
183 if err := validateMatchedTx(tx, verifyResult); err != nil {
188 if common.IsCancelOrderTx(tx) {
189 if err := validateCancelOrderTx(tx, verifyResult); err != nil {
194 for _, output := range tx.Outputs {
195 if !segwit.IsP2WMCScript(output.ControlProgram()) {
198 if verifyResult.StatusFail {
199 return errStatusFailMustFalse
202 if err := validateMagneticContractArgs(output.AssetAmount().Amount, output.ControlProgram()); err != nil {
209 func validateCancelOrderTx(tx *types.Tx, verifyResult *bc.TxVerifyResult) error {
210 if verifyResult.StatusFail {
211 return errStatusFailMustFalse
214 for _, input := range tx.Inputs {
215 if !segwit.IsP2WMCScript(input.ControlProgram()) {
216 return errInputProgramMustP2WMCScript
219 if contract.IsTradeClauseSelector(input) {
220 return errExistTradeInCancelOrderTx
226 func validateMagneticContractArgs(fromAmount uint64, program []byte) error {
227 contractArgs, err := segwit.DecodeP2WMCProgram(program)
232 if contractArgs.RatioNumerator <= 0 || contractArgs.RatioDenominator <= 0 {
233 return errRatioOfTradeLessThanZero
236 if _, ok := checked.MulInt64(int64(fromAmount), contractArgs.RatioNumerator); !ok {
237 return errNumeratorOfRatioIsOverflow
240 if match.CalcRequestAmount(fromAmount, contractArgs) < 1 {
241 return errRequestAmountLessThenOne
246 func validateMatchedTx(tx *types.Tx, verifyResult *bc.TxVerifyResult) error {
247 if verifyResult.StatusFail {
248 return errStatusFailMustFalse
251 fromAssetIDMap := make(map[string]bool)
252 toAssetIDMap := make(map[string]bool)
253 for i, input := range tx.Inputs {
254 if !segwit.IsP2WMCScript(input.ControlProgram()) {
255 return errInputProgramMustP2WMCScript
258 if contract.IsCancelClauseSelector(input) {
259 return errExistCancelOrderInMatchedTx
262 order, err := common.NewOrderFromInput(tx, i)
267 fromAssetIDMap[order.FromAssetID.String()] = true
268 toAssetIDMap[order.ToAssetID.String()] = true
271 if len(fromAssetIDMap) != len(tx.Inputs) || len(toAssetIDMap) != len(tx.Inputs) {
272 return errAssetIDMustUniqueInMatchedTx
275 return validateMatchedTxFeeAmount(tx)
278 func validateMatchedTxFeeAmount(tx *types.Tx) error {
279 txFee, err := match.CalcMatchedTxFee(&tx.TxData, maxFeeRate)
284 for _, amount := range txFee {
285 if amount.FeeAmount > amount.MaxFeeAmount {
286 return errAmountOfFeeGreaterThanMaximum
293 @issue: the match package didn't support circle yet
295 func (m *MovCore) validateMatchedTxSequence(txs []*types.Tx) error {
296 orderTable, err := buildOrderTable(m.movStore, txs)
301 matchEngine := match.NewEngine(orderTable, maxFeeRate, nil)
302 for _, matchedTx := range txs {
303 if !common.IsMatchedTx(matchedTx) {
307 tradePairs, err := getSortedTradePairsFromMatchedTx(matchedTx)
312 actualMatchedTx, err := matchEngine.NextMatchedTx(tradePairs...)
317 if len(matchedTx.Inputs) != len(actualMatchedTx.Inputs) {
318 return errLengthOfInputIsIncorrect
321 spendOutputIDs := make(map[string]bool)
322 for _, input := range matchedTx.Inputs {
323 spendOutputID, err := input.SpentOutputID()
328 spendOutputIDs[spendOutputID.String()] = true
331 for _, input := range actualMatchedTx.Inputs {
332 spendOutputID, err := input.SpentOutputID()
337 if _, ok := spendOutputIDs[spendOutputID.String()]; !ok {
338 return errSpendOutputIDIsIncorrect
345 func applyTransactions(txs []*types.Tx) ([]*common.Order, []*common.Order, error) {
346 deleteOrderMap := make(map[string]*common.Order)
347 addOrderMap := make(map[string]*common.Order)
348 for _, tx := range txs {
349 addOrders, err := getAddOrdersFromTx(tx)
354 for _, order := range addOrders {
355 addOrderMap[order.Key()] = order
358 deleteOrders, err := getDeleteOrdersFromTx(tx)
363 for _, order := range deleteOrders {
364 deleteOrderMap[order.Key()] = order
368 addOrders, deleteOrders := mergeOrders(addOrderMap, deleteOrderMap)
369 return addOrders, deleteOrders, nil
373 @issue: if consensus node packed match transaction first then packed regular tx, this function's logic may make a valid block invalid
375 func buildOrderTable(store database.MovStore, txs []*types.Tx) (*match.OrderTable, error) {
376 var nonMatchedTxs []*types.Tx
377 for _, tx := range txs {
378 if !common.IsMatchedTx(tx) {
379 nonMatchedTxs = append(nonMatchedTxs, tx)
383 var arrivalAddOrders, arrivalDelOrders []*common.Order
384 for _, tx := range nonMatchedTxs {
385 addOrders, err := getAddOrdersFromTx(tx)
390 delOrders, err := getDeleteOrdersFromTx(tx)
395 arrivalAddOrders = append(arrivalAddOrders, addOrders...)
396 arrivalDelOrders = append(arrivalDelOrders, delOrders...)
399 return match.NewOrderTable(store, arrivalAddOrders, arrivalDelOrders), nil
402 func calcMatchedTxGasUsed(tx *types.Tx) int64 {
403 return int64(len(tx.Inputs))*150 + int64(tx.SerializedSize)
406 func getAddOrdersFromTx(tx *types.Tx) ([]*common.Order, error) {
407 var orders []*common.Order
408 for i, output := range tx.Outputs {
409 if output.OutputType() != types.IntraChainOutputType || !segwit.IsP2WMCScript(output.ControlProgram()) {
413 order, err := common.NewOrderFromOutput(tx, i)
418 orders = append(orders, order)
423 func getDeleteOrdersFromTx(tx *types.Tx) ([]*common.Order, error) {
424 var orders []*common.Order
425 for i, input := range tx.Inputs {
426 if input.InputType() != types.SpendInputType || !segwit.IsP2WMCScript(input.ControlProgram()) {
430 order, err := common.NewOrderFromInput(tx, i)
435 orders = append(orders, order)
440 func getSortedTradePairsFromMatchedTx(tx *types.Tx) ([]*common.TradePair, error) {
441 assetMap := make(map[bc.AssetID]bc.AssetID)
442 var firstTradePair *common.TradePair
443 for _, tx := range tx.Inputs {
444 contractArgs, err := segwit.DecodeP2WMCProgram(tx.ControlProgram())
449 assetMap[tx.AssetID()] = contractArgs.RequestedAsset
450 if firstTradePair == nil {
451 firstTradePair = &common.TradePair{FromAssetID: tx.AssetAmount().AssetId, ToAssetID: &contractArgs.RequestedAsset}
455 tradePairs := []*common.TradePair{firstTradePair}
456 for tradePair := firstTradePair; *tradePair.ToAssetID != *firstTradePair.FromAssetID; {
457 nextTradePairToAssetID, ok := assetMap[*tradePair.ToAssetID]
459 return nil, errInvalidTradePairs
462 tradePair = &common.TradePair{FromAssetID: tradePair.ToAssetID, ToAssetID: &nextTradePairToAssetID}
463 tradePairs = append(tradePairs, tradePair)
466 if len(tradePairs) != len(tx.Inputs) {
467 return nil, errInvalidTradePairs
469 return tradePairs, nil
472 func mergeOrders(addOrderMap, deleteOrderMap map[string]*common.Order) ([]*common.Order, []*common.Order) {
473 var deleteOrders, addOrders []*common.Order
474 for orderID, order := range addOrderMap {
475 if _, ok := deleteOrderMap[orderID]; ok {
476 delete(deleteOrderMap, orderID)
479 addOrders = append(addOrders, order)
482 for _, order := range deleteOrderMap {
483 deleteOrders = append(deleteOrders, order)
485 return addOrders, deleteOrders