From: Paladz Date: Sat, 21 Mar 2020 02:37:06 +0000 (+0800) Subject: last review (#519) X-Git-Url: http://git.osdn.net/view?a=commitdiff_plain;h=refs%2Fheads%2Fmov;p=bytom%2Fvapor.git last review (#519) * last review * edit for code review * fix test case Co-authored-by: paladz <453256728@qq.com> --- diff --git a/application/mov/match/engine.go b/application/mov/match/engine.go index f84f1194..77de1113 100644 --- a/application/mov/match/engine.go +++ b/application/mov/match/engine.go @@ -83,7 +83,7 @@ func (e *Engine) addMatchTxFeeOutput(txData *types.TxData, refunds []RefundAsset func (e *Engine) addPartialTradeOrder(tx *types.Tx) error { for i, output := range tx.Outputs { - if !segwit.IsP2WMCScript(output.ControlProgram()) { + if !segwit.IsP2WMCScript(output.ControlProgram()) || output.AssetAmount().Amount == 0 { continue } @@ -182,9 +182,9 @@ func CalcReceivedAmount(orders []*common.Order) ([]*bc.AssetAmount, []*bc.AssetA for i, receivedAmount := range receivedAmounts { oppositeShouldPayAmount := shouldPayAmounts[calcOppositeIndex(len(orders), i)] if oppositeShouldPayAmount.Amount > receivedAmount.Amount { - assetId := oppositeShouldPayAmount.AssetId + assetID := oppositeShouldPayAmount.AssetId amount := oppositeShouldPayAmount.Amount - receivedAmount.Amount - priceDiffs = append(priceDiffs, &bc.AssetAmount{AssetId: assetId, Amount: amount}) + priceDiffs = append(priceDiffs, &bc.AssetAmount{AssetId: assetID, Amount: amount}) } } return receivedAmounts, priceDiffs diff --git a/application/mov/mov_core.go b/application/mov/mov_core.go index 48aabe1c..a8386c29 100644 --- a/application/mov/mov_core.go +++ b/application/mov/mov_core.go @@ -30,39 +30,34 @@ var ( errRewardProgramIsWrong = errors.New("the reward program is not correct") ) -// MovCore represent the core logic of the match module, which include generate match transactions before packing the block, +// Core represent the core logic of the match module, which include generate match transactions before packing the block, // verify the match transaction in block is correct, and update the order table according to the transaction. -type MovCore struct { +type Core struct { movStore database.MovStore startBlockHeight uint64 } -// NewMovCore return a instance of MovCore by path of mov db -func NewMovCore(dbBackend, dbDir string, startBlockHeight uint64) *MovCore { +// NewCore return a instance of Core by path of mov db +func NewCore(dbBackend, dbDir string, startBlockHeight uint64) *Core { movDB := dbm.NewDB("mov", dbBackend, dbDir) - return &MovCore{movStore: database.NewLevelDBMovStore(movDB), startBlockHeight: startBlockHeight} + return &Core{movStore: database.NewLevelDBMovStore(movDB), startBlockHeight: startBlockHeight} } -// NewMovCoreWithDB return a instance of MovCore by movStore -func NewMovCoreWithDB(store *database.LevelDBMovStore, startBlockHeight uint64) *MovCore { - return &MovCore{movStore: store, startBlockHeight: startBlockHeight} +// NewCoreWithDB return a instance of Core by movStore +func NewCoreWithDB(store *database.LevelDBMovStore, startBlockHeight uint64) *Core { + return &Core{movStore: store, startBlockHeight: startBlockHeight} } // ApplyBlock parse pending order and cancel from the the transactions of block // and add pending order to the dex db, remove cancel order from dex db. -func (m *MovCore) ApplyBlock(block *types.Block) error { +func (m *Core) ApplyBlock(block *types.Block) error { if block.Height < m.startBlockHeight { return nil } if block.Height == m.startBlockHeight { blockHash := block.Hash() - if err := m.movStore.InitDBState(block.Height, &blockHash); err != nil { - return err - } - - // the next block can send orders - return nil + return m.movStore.InitDBState(block.Height, &blockHash) } if err := m.validateMatchedTxSequence(block.Transactions); err != nil { @@ -78,7 +73,7 @@ func (m *MovCore) ApplyBlock(block *types.Block) error { } // BeforeProposalBlock return all transactions than can be matched, and the number of transactions cannot exceed the given capacity. -func (m *MovCore) BeforeProposalBlock(txs []*types.Tx, blockHeight uint64, gasLeft int64, isTimeout func() bool) ([]*types.Tx, error) { +func (m *Core) BeforeProposalBlock(txs []*types.Tx, blockHeight uint64, gasLeft int64, isTimeout func() bool) ([]*types.Tx, error) { if blockHeight <= m.startBlockHeight { return nil, nil } @@ -101,7 +96,7 @@ func (m *MovCore) BeforeProposalBlock(txs []*types.Tx, blockHeight uint64, gasLe } // ChainStatus return the current block height and block hash in dex core -func (m *MovCore) ChainStatus() (uint64, *bc.Hash, error) { +func (m *Core) ChainStatus() (uint64, *bc.Hash, error) { state, err := m.movStore.GetMovDatabaseState() if err != nil { return 0, nil, err @@ -112,7 +107,7 @@ func (m *MovCore) ChainStatus() (uint64, *bc.Hash, error) { // DetachBlock parse pending order and cancel from the the transactions of block // and add cancel order to the dex db, remove pending order from dex db. -func (m *MovCore) DetachBlock(block *types.Block) error { +func (m *Core) DetachBlock(block *types.Block) error { if block.Height < m.startBlockHeight { return nil } @@ -126,7 +121,7 @@ func (m *MovCore) DetachBlock(block *types.Block) error { } // IsDust block the transaction that are not generated by the match engine -func (m *MovCore) IsDust(tx *types.Tx) bool { +func (m *Core) IsDust(tx *types.Tx) bool { for _, input := range tx.Inputs { if segwit.IsP2WMCScript(input.ControlProgram()) && !contract.IsCancelClauseSelector(input) { return true @@ -136,18 +131,18 @@ func (m *MovCore) IsDust(tx *types.Tx) bool { } // Name return the name of current module -func (m *MovCore) Name() string { +func (m *Core) Name() string { return "MOV" } // StartHeight return the start block height of current module -func (m *MovCore) StartHeight() uint64 { +func (m *Core) StartHeight() uint64 { return m.startBlockHeight } // ValidateBlock no need to verify the block header, because the first module has been verified. // just need to verify the transactions in the block. -func (m *MovCore) ValidateBlock(block *types.Block, verifyResults []*bc.TxVerifyResult) error { +func (m *Core) ValidateBlock(block *types.Block, verifyResults []*bc.TxVerifyResult) error { for i, tx := range block.Transactions { if err := m.ValidateTx(tx, verifyResults[i], block.Height); err != nil { return err @@ -157,7 +152,15 @@ func (m *MovCore) ValidateBlock(block *types.Block, verifyResults []*bc.TxVerify } // ValidateTx validate one transaction. -func (m *MovCore) ValidateTx(tx *types.Tx, verifyResult *bc.TxVerifyResult, blockHeight uint64) error { +func (m *Core) ValidateTx(tx *types.Tx, verifyResult *bc.TxVerifyResult, blockHeight uint64) error { + if blockHeight <= m.startBlockHeight { + return nil + } + + if verifyResult.StatusFail { + return errStatusFailMustFalse + } + if common.IsMatchedTx(tx) { if err := validateMatchedTx(tx, verifyResult, blockHeight); err != nil { return err @@ -172,9 +175,6 @@ func (m *MovCore) ValidateTx(tx *types.Tx, verifyResult *bc.TxVerifyResult, bloc if !segwit.IsP2WMCScript(output.ControlProgram()) { continue } - if verifyResult.StatusFail { - return errStatusFailMustFalse - } if err := validateMagneticContractArgs(output.AssetAmount(), output.ControlProgram()); err != nil { return err @@ -211,18 +211,16 @@ func calcFeeAmount(matchedTx *types.Tx) (map[bc.AssetID]*matchedTxFee, error) { if assetFeeMap[*assetAmount.AssetId].amount <= 0 { delete(assetFeeMap, *assetAmount.AssetId) } - } else { + } else if assetFeeMap[*assetAmount.AssetId].rewardProgram == nil { assetFeeMap[*assetAmount.AssetId].rewardProgram = output.ControlProgram() + } else { + return nil, errors.Wrap(errRewardProgramIsWrong, "double reward program") } } return assetFeeMap, nil } func validateCancelOrderTx(tx *types.Tx, verifyResult *bc.TxVerifyResult) error { - if verifyResult.StatusFail { - return errStatusFailMustFalse - } - for _, input := range tx.Inputs { if !segwit.IsP2WMCScript(input.ControlProgram()) { return errInputProgramMustP2WMCScript @@ -256,10 +254,6 @@ func validateMagneticContractArgs(fromAssetAmount bc.AssetAmount, program []byte } func validateMatchedTx(tx *types.Tx, verifyResult *bc.TxVerifyResult, blockHeight uint64) error { - if verifyResult.StatusFail { - return errStatusFailMustFalse - } - fromAssetIDMap := make(map[string]bool) toAssetIDMap := make(map[string]bool) for i, input := range tx.Inputs { @@ -314,7 +308,7 @@ func validateMatchedTxFee(tx *types.Tx, blockHeight uint64) error { return feeStrategy.Validate(receivedAmount, feeAmounts) } -func (m *MovCore) validateMatchedTxSequence(txs []*types.Tx) error { +func (m *Core) validateMatchedTxSequence(txs []*types.Tx) error { orderBook := match.NewOrderBook(m.movStore, nil, nil) for _, tx := range txs { if common.IsMatchedTx(tx) { @@ -404,15 +398,8 @@ func decodeTxsOrders(txs []*types.Tx) ([]*common.Order, []*common.Order, error) } func buildOrderBook(store database.MovStore, txs []*types.Tx) (*match.OrderBook, error) { - var nonMatchedTxs []*types.Tx - for _, tx := range txs { - if !common.IsMatchedTx(tx) { - nonMatchedTxs = append(nonMatchedTxs, tx) - } - } - var arrivalAddOrders, arrivalDelOrders []*common.Order - for _, tx := range nonMatchedTxs { + for _, tx := range txs { addOrders, err := getAddOrdersFromTx(tx) if err != nil { return nil, err @@ -437,6 +424,10 @@ func getAddOrdersFromTx(tx *types.Tx) ([]*common.Order, error) { continue } + if output.AssetAmount().Amount == 0 { + continue + } + order, err := common.NewOrderFromOutput(tx, i) if err != nil { return nil, err diff --git a/application/mov/mov_core_test.go b/application/mov/mov_core_test.go index a5045399..9b4e037e 100644 --- a/application/mov/mov_core_test.go +++ b/application/mov/mov_core_test.go @@ -264,7 +264,7 @@ func TestApplyBlock(t *testing.T) { t.Fatal(err) } - movCore := &MovCore{movStore: store} + movCore := &Core{movStore: store} if err := c.blockFunc(movCore, c.block); err != c.wantError { t.Errorf("#%d(%s):apply block want error(%v), got error(%v)", i, c.desc, c.wantError, err) } @@ -515,7 +515,8 @@ func TestValidateBlock(t *testing.T) { } for i, c := range cases { - movCore := &MovCore{} + movCore := &Core{} + c.block.Height = 3456786543 if err := movCore.ValidateBlock(c.block, c.verifyResults); err != c.wantError { t.Errorf("#%d(%s):validate block want error(%v), got error(%v)", i, c.desc, c.wantError, err) } @@ -539,22 +540,22 @@ func TestCalcMatchedTxFee(t *testing.T) { tx: mock.MatchedTxs[1].TxData, }, { - desc: "fee refund in tx", - maxFeeRate: 0.05, + desc: "fee refund in tx", + maxFeeRate: 0.05, wantMatchedTxFee: map[bc.AssetID]*matchedTxFee{ mock.ETH: {amount: 25, rewardProgram: mock.RewardProgram}, mock.BTC: {amount: 1, rewardProgram: mock.RewardProgram}, }, - tx: mock.MatchedTxs[2].TxData, + tx: mock.MatchedTxs[2].TxData, }, { - desc: "no price diff", - maxFeeRate: 0.05, + desc: "no price diff", + maxFeeRate: 0.05, wantMatchedTxFee: map[bc.AssetID]*matchedTxFee{ mock.ETH: {amount: 1, rewardProgram: mock.RewardProgram}, mock.BTC: {amount: 1, rewardProgram: mock.RewardProgram}, }, - tx: mock.MatchedTxs[0].TxData, + tx: mock.MatchedTxs[0].TxData, }, } @@ -642,7 +643,7 @@ func TestBeforeProposalBlock(t *testing.T) { t.Fatal(err) } - movCore := &MovCore{movStore: store} + movCore := &Core{movStore: store} gotMatchedTxs, err := movCore.BeforeProposalBlock(nil, 2, c.gasLeft, func() bool { return false }) if err != nil { t.Fatal(err) @@ -795,7 +796,7 @@ func TestValidateMatchedTxSequence(t *testing.T) { t.Fatal(err) } - movCore := &MovCore{movStore: store} + movCore := &Core{movStore: store} if err := movCore.validateMatchedTxSequence(c.transactions); err != c.wantError { t.Errorf("#%d(%s):wanet error(%v), got error(%v)", i, c.desc, c.wantError, err) } @@ -805,13 +806,13 @@ func TestValidateMatchedTxSequence(t *testing.T) { } } -type testFun func(movCore *MovCore, block *types.Block) error +type testFun func(movCore *Core, block *types.Block) error -func applyBlock(movCore *MovCore, block *types.Block) error { +func applyBlock(movCore *Core, block *types.Block) error { return movCore.ApplyBlock(block) } -func detachBlock(movCore *MovCore, block *types.Block) error { +func detachBlock(movCore *Core, block *types.Block) error { return movCore.DetachBlock(block) } diff --git a/blockchain/txbuilder/signing_instruction.go b/blockchain/txbuilder/signing_instruction.go index 6a111980..ba448d6f 100644 --- a/blockchain/txbuilder/signing_instruction.go +++ b/blockchain/txbuilder/signing_instruction.go @@ -8,6 +8,7 @@ import ( "github.com/bytom/vapor/errors" ) +// AddDataWitness append data to the witness array func (si *SigningInstruction) AddDataWitness(data chainjson.HexBytes) { dw := DataWitness(data) si.WitnessComponents = append(si.WitnessComponents, &dw) diff --git a/cmd/vapord/commands/root.go b/cmd/vapord/commands/root.go index ed4060d7..d534b2d5 100644 --- a/cmd/vapord/commands/root.go +++ b/cmd/vapord/commands/root.go @@ -15,6 +15,7 @@ var ( config = cfg.DefaultConfig() ) +// RootCmd is the command for run node var RootCmd = &cobra.Command{ Use: "vapord", Short: "Multiple asset management.", diff --git a/common/bytes.go b/common/bytes.go index db0cdc99..e899a1e4 100644 --- a/common/bytes.go +++ b/common/bytes.go @@ -6,6 +6,7 @@ import ( "encoding/hex" ) +// FromHex convert hex byte string to []byte func FromHex(s string) []byte { if len(s) > 1 { if s[0:2] == "0x" { @@ -19,21 +20,25 @@ func FromHex(s string) []byte { return nil } +// Bytes2Hex convert byte array to string func Bytes2Hex(d []byte) string { return hex.EncodeToString(d) } +// Hex2Bytes convert hex string to byte array func Hex2Bytes(str string) []byte { h, _ := hex.DecodeString(str) return h } +// Unit64ToBytes convert uint64 to bytes func Unit64ToBytes(n uint64) []byte { buf := make([]byte, 8) binary.LittleEndian.PutUint64(buf, n) return buf } +// BytesToUnit64 convert bytes to uint64 func BytesToUnit64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } diff --git a/common/crossin_asset.go b/common/crossin_asset.go index 8907ba29..9dbd729a 100644 --- a/common/crossin_asset.go +++ b/common/crossin_asset.go @@ -4,6 +4,7 @@ import ( "encoding/json" ) +// IsOpenFederationIssueAsset check if the asset definition satisfy ofmf asset func IsOpenFederationIssueAsset(rawDefinitionByte []byte) bool { var defMap map[string]interface{} if err := json.Unmarshal(rawDefinitionByte, &defMap); err != nil { diff --git a/common/sort.go b/common/sort.go deleted file mode 100644 index a476c922..00000000 --- a/common/sort.go +++ /dev/null @@ -1,23 +0,0 @@ -package common - -// timeSorter implements sort.Interface to allow a slice of timestamps to -// be sorted. -type TimeSorter []uint64 - -// Len returns the number of timestamps in the slice. It is part of the -// sort.Interface implementation. -func (s TimeSorter) Len() int { - return len(s) -} - -// Swap swaps the timestamps at the passed indices. It is part of the -// sort.Interface implementation. -func (s TimeSorter) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -// Less returns whether the timstamp with index i should sort before the -// timestamp with index j. It is part of the sort.Interface implementation. -func (s TimeSorter) Less(i, j int) bool { - return s[i] < s[j] -} diff --git a/consensus/general.go b/consensus/general.go index b413c783..799185e9 100644 --- a/consensus/general.go +++ b/consensus/general.go @@ -254,6 +254,7 @@ func BytomMainNetParams(vaporParam *Params) *Params { return &Params{Bech32HRPSegwit: bech32HRPSegwit} } +// InitActiveNetParams load the config by chain ID func InitActiveNetParams(chainID string) error { var exist bool if ActiveNetParams, exist = NetParams[chainID]; !exist { diff --git a/database/account_store.go b/database/account_store.go index 8d15bcf7..f392f1da 100644 --- a/database/account_store.go +++ b/database/account_store.go @@ -45,7 +45,7 @@ func accountIndexKey(xpubs []chainkd.XPub) []byte { return append(AccountIndexPrefix, hash[:]...) } -func Bip44ContractIndexKey(accountID string, change bool) []byte { +func bip44ContractIndexKey(accountID string, change bool) []byte { key := append(ContractIndexPrefix, []byte(accountID)...) if change { return append(key, 0x01) @@ -96,7 +96,7 @@ func (store *AccountStore) InitBatch() acc.AccountStore { // CommitBatch commit batch func (store *AccountStore) CommitBatch() error { if store.batch == nil { - return errors.New("AccountStore commit fail, store batch is nil.") + return errors.New("accountStore commit fail, store batch is nil") } store.batch.Write() store.batch = nil @@ -119,8 +119,8 @@ func (store *AccountStore) DeleteAccount(account *acc.Account) error { } // delete bip44 contract index - batch.Delete(Bip44ContractIndexKey(account.ID, false)) - batch.Delete(Bip44ContractIndexKey(account.ID, true)) + batch.Delete(bip44ContractIndexKey(account.ID, false)) + batch.Delete(bip44ContractIndexKey(account.ID, true)) // delete contract index batch.Delete(contractIndexKey(account.ID)) @@ -216,7 +216,7 @@ func (store *AccountStore) GetAccountIndex(xpubs []chainkd.XPub) uint64 { // GetBip44ContractIndex get bip44 contract index func (store *AccountStore) GetBip44ContractIndex(accountID string, change bool) uint64 { index := uint64(0) - if rawIndexBytes := store.db.Get(Bip44ContractIndexKey(accountID, change)); rawIndexBytes != nil { + if rawIndexBytes := store.db.Get(bip44ContractIndexKey(accountID, change)); rawIndexBytes != nil { index = common.BytesToUnit64(rawIndexBytes) } return index @@ -367,9 +367,9 @@ func (store *AccountStore) SetAccountIndex(account *acc.Account) { // SetBip44ContractIndex set contract index func (store *AccountStore) SetBip44ContractIndex(accountID string, change bool, index uint64) { if store.batch == nil { - store.db.Set(Bip44ContractIndexKey(accountID, change), common.Unit64ToBytes(index)) + store.db.Set(bip44ContractIndexKey(accountID, change), common.Unit64ToBytes(index)) } else { - store.batch.Set(Bip44ContractIndexKey(accountID, change), common.Unit64ToBytes(index)) + store.batch.Set(bip44ContractIndexKey(accountID, change), common.Unit64ToBytes(index)) } } diff --git a/database/utxo_view.go b/database/utxo_view.go index 81a7f28b..5f4de1ff 100644 --- a/database/utxo_view.go +++ b/database/utxo_view.go @@ -1,12 +1,12 @@ package database import ( - "github.com/golang/protobuf/proto" dbm "github.com/bytom/vapor/database/leveldb" "github.com/bytom/vapor/database/storage" "github.com/bytom/vapor/errors" "github.com/bytom/vapor/protocol/bc" "github.com/bytom/vapor/protocol/state" + "github.com/golang/protobuf/proto" ) const utxoPreFix = "UT:" @@ -91,6 +91,7 @@ func saveUtxoView(batch dbm.Batch, view *state.UtxoViewpoint) error { return nil } +// SaveUtxoView is export for intergation test func SaveUtxoView(batch dbm.Batch, view *state.UtxoViewpoint) error { return saveUtxoView(batch, view) } diff --git a/database/wallet_store.go b/database/wallet_store.go index d0bfa5ab..d50464b1 100644 --- a/database/wallet_store.go +++ b/database/wallet_store.go @@ -31,6 +31,7 @@ const ( recoveryKey //recoveryKey key for db store recovery info. ) +// pre-define variables var ( walletStore = []byte("WS:") SUTXOPrefix = append(walletStore, sutxoPrefix, colon) @@ -66,10 +67,12 @@ func calcUnconfirmedTxKey(formatKey string) []byte { return append(UnconfirmedTxPrefix, []byte(formatKey)...) } +// CalcGlobalTxIndexKey calculate tx hash index key func CalcGlobalTxIndexKey(txID string) []byte { return append(GlobalTxIndexPrefix, []byte(txID)...) } +// CalcGlobalTxIndex calcuate the block index + position index key func CalcGlobalTxIndex(blockHash *bc.Hash, position uint64) []byte { txIdx := make([]byte, 40) copy(txIdx[:32], blockHash.Bytes()) @@ -109,7 +112,7 @@ func (store *WalletStore) InitBatch() wallet.WalletStore { // CommitBatch commit batch func (store *WalletStore) CommitBatch() error { if store.batch == nil { - return errors.New("WalletStore commit fail, store batch is nil.") + return errors.New("walletStore commit fail, store batch is nil") } store.batch.Write() @@ -347,6 +350,7 @@ func (store *WalletStore) ListAccountUTXOs(id string, isSmartContract bool) ([]* return confirmedUTXOs, nil } +// ListTransactions list tx by filter args func (store *WalletStore) ListTransactions(accountID string, StartTxID string, count uint, unconfirmed bool) ([]*query.AnnotatedTx, error) { annotatedTxs := []*query.AnnotatedTx{} var startKey []byte diff --git a/math/algorithm.go b/math/algorithm.go index a5964965..791a70cd 100644 --- a/math/algorithm.go +++ b/math/algorithm.go @@ -1,5 +1,6 @@ package math +// MinUint64 return the min of x and y func MinUint64(x, y uint64) uint64 { if x < y { return x diff --git a/node/node.go b/node/node.go index 7640e8eb..313f55b2 100644 --- a/node/node.go +++ b/node/node.go @@ -5,6 +5,7 @@ import ( "errors" "net" "net/http" + // debug tool _ "net/http/pprof" "path/filepath" "reflect" @@ -84,7 +85,7 @@ func NewNode(config *cfg.Config) *Node { accessTokens := accesstoken.NewStore(tokenDB) dispatcher := event.NewDispatcher() - movCore := mov.NewMovCore(config.DBBackend, config.DBDir(), consensus.ActiveNetParams.MovStartHeight) + movCore := mov.NewCore(config.DBBackend, config.DBDir(), consensus.ActiveNetParams.MovStartHeight) assetFilter := protocol.NewAssetFilter(config.CrossChain.AssetWhitelist) txPool := protocol.NewTxPool(store, []protocol.DustFilterer{movCore, assetFilter}, dispatcher) chain, err := protocol.NewChain(store, txPool, []protocol.Protocoler{movCore}, dispatcher) @@ -177,7 +178,7 @@ func Rollback(config *cfg.Config, targetHeight uint64) error { store := database.NewStore(coreDB) dispatcher := event.NewDispatcher() - movCore := mov.NewMovCore(config.DBBackend, config.DBDir(), consensus.ActiveNetParams.MovStartHeight) + movCore := mov.NewCore(config.DBBackend, config.DBDir(), consensus.ActiveNetParams.MovStartHeight) txPool := protocol.NewTxPool(store, []protocol.DustFilterer{movCore}, dispatcher) chain, err := protocol.NewChain(store, txPool, []protocol.Protocoler{movCore}, dispatcher) if err != nil { @@ -235,7 +236,7 @@ func checkConfig(chain *protocol.Chain, config *cfg.Config) error { typedInput := genesisBlock.Transactions[0].Inputs[0].TypedInput if v, ok := typedInput.(*types.CoinbaseInput); ok { if !reflect.DeepEqual(fedpegScript, v.Arbitrary) { - return errors.New("config xpubs don't equal genesis block xpubs.") + return errors.New("config xpubs don't equal genesis block xpubs") } } return nil @@ -272,6 +273,7 @@ func (n *Node) initAndstartAPIServer() { n.api.StartServer(*listenAddr) } +// OnStart implements BaseService func (n *Node) OnStart() error { if n.miningEnable { if _, err := n.wallet.AccountMgr.GetMiningAddress(); err != nil { @@ -303,6 +305,7 @@ func (n *Node) OnStart() error { return nil } +// OnStop implements BaseService func (n *Node) OnStop() { n.notificationMgr.Shutdown() n.notificationMgr.WaitForShutdown() @@ -316,6 +319,7 @@ func (n *Node) OnStop() { n.eventDispatcher.Stop() } +// RunForever listen to the stop signal func (n *Node) RunForever() { // Sleep forever and then... cmn.TrapSignal(func() { diff --git a/protocol/asset_filter.go b/protocol/asset_filter.go index aef0dbd8..cd9fccd6 100644 --- a/protocol/asset_filter.go +++ b/protocol/asset_filter.go @@ -7,14 +7,15 @@ import ( "github.com/bytom/vapor/protocol/bc/types" ) -type assetFilter struct { +// AssetFilter is struct for allow open federation asset cross chain +type AssetFilter struct { whitelist map[string]struct{} } // NewAssetFilter returns a assetFilter according a whitelist, // which is a strings list cancated via comma -func NewAssetFilter(whitelist string) *assetFilter { - af := &assetFilter{whitelist: make(map[string]struct{})} +func NewAssetFilter(whitelist string) *AssetFilter { + af := &AssetFilter{whitelist: make(map[string]struct{})} af.whitelist[consensus.BTMAssetID.String()] = struct{}{} for _, assetID := range strings.Split(whitelist, ",") { af.whitelist[strings.ToLower(assetID)] = struct{}{} @@ -25,7 +26,7 @@ func NewAssetFilter(whitelist string) *assetFilter { // IsDust implements the DustFilterer interface. // It filters a transaction as long as there is one asset neither BTM or in the whitelist // No need to check the output assets types becauese they must have been cover in input assets types -func (af *assetFilter) IsDust(tx *types.Tx) bool { +func (af *AssetFilter) IsDust(tx *types.Tx) bool { for _, input := range tx.Inputs { if _, ok := input.TypedInput.(*types.CrossChainInput); !ok { continue diff --git a/protocol/bbft.go b/protocol/bbft.go index 3b3c317a..06b48591 100644 --- a/protocol/bbft.go +++ b/protocol/bbft.go @@ -240,6 +240,10 @@ func (c *Chain) signBlockHeader(blockHeader *types.BlockHeader) ([]byte, error) return nil, err } + if len(blockHeader.Get(node.Order)) != 0 { + return nil, nil + } + if err := c.checkDoubleSign(blockHeader, node.XPub.String()); err == errDoubleSignBlock { log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String()}).Warn("current node has double sign the block") return nil, nil @@ -247,10 +251,6 @@ func (c *Chain) signBlockHeader(blockHeader *types.BlockHeader) ([]byte, error) return nil, err } - if signature := blockHeader.Get(node.Order); len(signature) != 0 { - return nil, nil - } - signature := xprv.Sign(blockHeader.Hash().Bytes()) blockHeader.Set(node.Order, signature) return signature, nil diff --git a/protocol/bc/types/block.go b/protocol/bc/types/block.go index 654da54b..621935ad 100644 --- a/protocol/bc/types/block.go +++ b/protocol/bc/types/block.go @@ -102,6 +102,7 @@ func (b *Block) readFrom(r *blockchain.Reader) error { return nil } +// WriteTo write block to io.Writer func (b *Block) WriteTo(w io.Writer) (int64, error) { ew := errors.NewWriter(w) if err := b.writeTo(ew, SerBlockFull); err != nil { diff --git a/protocol/bc/types/block_witness.go b/protocol/bc/types/block_witness.go index a756cd3e..f05ddc3e 100644 --- a/protocol/bc/types/block_witness.go +++ b/protocol/bc/types/block_witness.go @@ -6,6 +6,7 @@ import ( "github.com/bytom/vapor/encoding/blockchain" ) +// BlockWitness save the consensus node sign type BlockWitness struct { // Witness is a vector of arguments for validating this block. Witness [][]byte @@ -21,6 +22,7 @@ func (bw *BlockWitness) writeTo(w io.Writer) error { return err } +// Set save data to index position func (bw *BlockWitness) Set(index uint64, data []byte) { if uint64(len(bw.Witness)) <= index { newWitness := make([][]byte, index+1, index+1) @@ -30,12 +32,14 @@ func (bw *BlockWitness) Set(index uint64, data []byte) { bw.Witness[index] = data } +// Delete remove data from index position func (bw *BlockWitness) Delete(index uint64) { if uint64(len(bw.Witness)) > index { bw.Witness[index] = nil } } +// Get return data from index position func (bw *BlockWitness) Get(index uint64) []byte { if uint64(len(bw.Witness)) > index { return bw.Witness[index] diff --git a/protocol/bc/types/crosschain_output.go b/protocol/bc/types/crosschain_output.go index 6c3222bf..017cbcbf 100644 --- a/protocol/bc/types/crosschain_output.go +++ b/protocol/bc/types/crosschain_output.go @@ -28,4 +28,5 @@ func NewCrossChainOutput(assetID bc.AssetID, amount uint64, controlProgram []byt } } +// OutputType implement the txout interface func (it *CrossChainOutput) OutputType() uint8 { return CrossChainOutputType } diff --git a/protocol/bc/types/intrachain_output.go b/protocol/bc/types/intrachain_output.go index 55e27736..efc74b35 100644 --- a/protocol/bc/types/intrachain_output.go +++ b/protocol/bc/types/intrachain_output.go @@ -28,4 +28,5 @@ func NewIntraChainOutput(assetID bc.AssetID, amount uint64, controlProgram []byt } } +// OutputType implement the txout interface func (it *IntraChainOutput) OutputType() uint8 { return IntraChainOutputType } diff --git a/protocol/bc/types/vote_output.go b/protocol/bc/types/vote_output.go index ffeb5957..673b2b50 100644 --- a/protocol/bc/types/vote_output.go +++ b/protocol/bc/types/vote_output.go @@ -30,4 +30,5 @@ func NewVoteOutput(assetID bc.AssetID, amount uint64, controlProgram []byte, vot } } +// OutputType implement the txout interface func (it *VoteOutput) OutputType() uint8 { return VoteOutputType } diff --git a/protocol/block.go b/protocol/block.go index 45e6fba9..52eab1bd 100644 --- a/protocol/block.go +++ b/protocol/block.go @@ -104,6 +104,7 @@ func (c *Chain) connectBlock(block *types.Block) (err error) { if err != nil { return err } + if err := consensusResult.ApplyBlock(block); err != nil { return err } diff --git a/protocol/protocol.go b/protocol/protocol.go index c0670828..a1cbb709 100644 --- a/protocol/protocol.go +++ b/protocol/protocol.go @@ -19,6 +19,7 @@ const ( maxKnownTxs = 32768 // Maximum transactions hashes to keep in the known list (prevent DOS) ) +// Protocoler is interface for layer 2 consensus protocol type Protocoler interface { Name() string StartHeight() uint64 @@ -173,6 +174,7 @@ func (c *Chain) InMainChain(hash bc.Hash) bool { return *blockHash == hash } +// SubProtocols return list of layer 2 consensus protocol func (c *Chain) SubProtocols() []Protocoler { return c.subProtocols } diff --git a/protocol/store.go b/protocol/store.go index 275efdb8..b108ab8c 100644 --- a/protocol/store.go +++ b/protocol/store.go @@ -9,6 +9,7 @@ import ( "github.com/bytom/vapor/protocol/state" ) +// predefine errors var ( ErrNotFoundConsensusResult = errors.New("can't find the vote result by given sequence") ) diff --git a/protocol/txpool.go b/protocol/txpool.go index 27d9a9b0..9413fe4e 100644 --- a/protocol/txpool.go +++ b/protocol/txpool.go @@ -43,10 +43,12 @@ var ( ErrDustTx = errors.New("transaction is dust tx") ) +// DustFilterer is inerface for dust transaction filter rule type DustFilterer interface { IsDust(tx *types.Tx) bool } +// TxMsgEvent is message wrap for subscribe event type TxMsgEvent struct{ TxMsg *TxPoolMsg } // TxDesc store tx and related info for mining strategy diff --git a/protocol/validation/block.go b/protocol/validation/block.go index 9be89a07..42920141 100644 --- a/protocol/validation/block.go +++ b/protocol/validation/block.go @@ -101,13 +101,6 @@ func ValidateBlock(b *bc.Block, parent *types.BlockHeader, rewards []state.Coinb return errors.Wrapf(validateResult.err, "validate of transaction %d of %d", i, len(b.Transactions)) } - // for support flash swap running on vapor, status fail txs need to be - // rejected. Or the attacker can steal BTM from any BTM/* trade pair by - // using status fail charge fee rule. - if b.Height >= consensus.ActiveNetParams.MovStartHeight && validateResult.err != nil { - return errors.New("the chain currently didn't support status fail tx") - } - if err := b.TransactionStatus.SetStatus(i, validateResult.err != nil); err != nil { return err } diff --git a/test/rollback_test.go b/test/rollback_test.go index 8dc77c56..d40f9ba7 100644 --- a/test/rollback_test.go +++ b/test/rollback_test.go @@ -1445,7 +1445,7 @@ func TestRollback(t *testing.T) { consensus.ActiveNetParams.RoundVoteBlockNums = c.RoundVoteBlockNums movDB := dbm.NewDB("mov_db", "leveldb", "mov_db") - movCore := mov.NewMovCoreWithDB(movDatabase.NewLevelDBMovStore(movDB), c.movStartHeight) + movCore := mov.NewCoreWithDB(movDatabase.NewLevelDBMovStore(movDB), c.movStartHeight) blockDB := dbm.NewDB("block_db", "leveldb", "block_db") store := database.NewStore(blockDB)