• R/O
  • HTTP
  • SSH
  • HTTPS

vapor: 提交

Golang implemented sidechain for Bytom


Commit MetaInfo

修订版37774d27fc6ec5f3d80d9d7de7245d4f5037039d (tree)
时间2020-03-21 11:37:06
作者Paladz <yzhu101@uott...>
CommiterGitHub

Log Message

last review (#519)

* last review

* edit for code review

* fix test case

Co-authored-by: paladz <453256728@qq.com>

更改概述

差异

--- 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
8383
8484 func (e *Engine) addPartialTradeOrder(tx *types.Tx) error {
8585 for i, output := range tx.Outputs {
86- if !segwit.IsP2WMCScript(output.ControlProgram()) {
86+ if !segwit.IsP2WMCScript(output.ControlProgram()) || output.AssetAmount().Amount == 0 {
8787 continue
8888 }
8989
@@ -182,9 +182,9 @@ func CalcReceivedAmount(orders []*common.Order) ([]*bc.AssetAmount, []*bc.AssetA
182182 for i, receivedAmount := range receivedAmounts {
183183 oppositeShouldPayAmount := shouldPayAmounts[calcOppositeIndex(len(orders), i)]
184184 if oppositeShouldPayAmount.Amount > receivedAmount.Amount {
185- assetId := oppositeShouldPayAmount.AssetId
185+ assetID := oppositeShouldPayAmount.AssetId
186186 amount := oppositeShouldPayAmount.Amount - receivedAmount.Amount
187- priceDiffs = append(priceDiffs, &bc.AssetAmount{AssetId: assetId, Amount: amount})
187+ priceDiffs = append(priceDiffs, &bc.AssetAmount{AssetId: assetID, Amount: amount})
188188 }
189189 }
190190 return receivedAmounts, priceDiffs
--- a/application/mov/mov_core.go
+++ b/application/mov/mov_core.go
@@ -30,39 +30,34 @@ var (
3030 errRewardProgramIsWrong = errors.New("the reward program is not correct")
3131 )
3232
33-// MovCore represent the core logic of the match module, which include generate match transactions before packing the block,
33+// Core represent the core logic of the match module, which include generate match transactions before packing the block,
3434 // verify the match transaction in block is correct, and update the order table according to the transaction.
35-type MovCore struct {
35+type Core struct {
3636 movStore database.MovStore
3737 startBlockHeight uint64
3838 }
3939
40-// NewMovCore return a instance of MovCore by path of mov db
41-func NewMovCore(dbBackend, dbDir string, startBlockHeight uint64) *MovCore {
40+// NewCore return a instance of Core by path of mov db
41+func NewCore(dbBackend, dbDir string, startBlockHeight uint64) *Core {
4242 movDB := dbm.NewDB("mov", dbBackend, dbDir)
43- return &MovCore{movStore: database.NewLevelDBMovStore(movDB), startBlockHeight: startBlockHeight}
43+ return &Core{movStore: database.NewLevelDBMovStore(movDB), startBlockHeight: startBlockHeight}
4444 }
4545
46-// NewMovCoreWithDB return a instance of MovCore by movStore
47-func NewMovCoreWithDB(store *database.LevelDBMovStore, startBlockHeight uint64) *MovCore {
48- return &MovCore{movStore: store, startBlockHeight: startBlockHeight}
46+// NewCoreWithDB return a instance of Core by movStore
47+func NewCoreWithDB(store *database.LevelDBMovStore, startBlockHeight uint64) *Core {
48+ return &Core{movStore: store, startBlockHeight: startBlockHeight}
4949 }
5050
5151 // ApplyBlock parse pending order and cancel from the the transactions of block
5252 // and add pending order to the dex db, remove cancel order from dex db.
53-func (m *MovCore) ApplyBlock(block *types.Block) error {
53+func (m *Core) ApplyBlock(block *types.Block) error {
5454 if block.Height < m.startBlockHeight {
5555 return nil
5656 }
5757
5858 if block.Height == m.startBlockHeight {
5959 blockHash := block.Hash()
60- if err := m.movStore.InitDBState(block.Height, &blockHash); err != nil {
61- return err
62- }
63-
64- // the next block can send orders
65- return nil
60+ return m.movStore.InitDBState(block.Height, &blockHash)
6661 }
6762
6863 if err := m.validateMatchedTxSequence(block.Transactions); err != nil {
@@ -78,7 +73,7 @@ func (m *MovCore) ApplyBlock(block *types.Block) error {
7873 }
7974
8075 // BeforeProposalBlock return all transactions than can be matched, and the number of transactions cannot exceed the given capacity.
81-func (m *MovCore) BeforeProposalBlock(txs []*types.Tx, blockHeight uint64, gasLeft int64, isTimeout func() bool) ([]*types.Tx, error) {
76+func (m *Core) BeforeProposalBlock(txs []*types.Tx, blockHeight uint64, gasLeft int64, isTimeout func() bool) ([]*types.Tx, error) {
8277 if blockHeight <= m.startBlockHeight {
8378 return nil, nil
8479 }
@@ -101,7 +96,7 @@ func (m *MovCore) BeforeProposalBlock(txs []*types.Tx, blockHeight uint64, gasLe
10196 }
10297
10398 // ChainStatus return the current block height and block hash in dex core
104-func (m *MovCore) ChainStatus() (uint64, *bc.Hash, error) {
99+func (m *Core) ChainStatus() (uint64, *bc.Hash, error) {
105100 state, err := m.movStore.GetMovDatabaseState()
106101 if err != nil {
107102 return 0, nil, err
@@ -112,7 +107,7 @@ func (m *MovCore) ChainStatus() (uint64, *bc.Hash, error) {
112107
113108 // DetachBlock parse pending order and cancel from the the transactions of block
114109 // and add cancel order to the dex db, remove pending order from dex db.
115-func (m *MovCore) DetachBlock(block *types.Block) error {
110+func (m *Core) DetachBlock(block *types.Block) error {
116111 if block.Height < m.startBlockHeight {
117112 return nil
118113 }
@@ -126,7 +121,7 @@ func (m *MovCore) DetachBlock(block *types.Block) error {
126121 }
127122
128123 // IsDust block the transaction that are not generated by the match engine
129-func (m *MovCore) IsDust(tx *types.Tx) bool {
124+func (m *Core) IsDust(tx *types.Tx) bool {
130125 for _, input := range tx.Inputs {
131126 if segwit.IsP2WMCScript(input.ControlProgram()) && !contract.IsCancelClauseSelector(input) {
132127 return true
@@ -136,18 +131,18 @@ func (m *MovCore) IsDust(tx *types.Tx) bool {
136131 }
137132
138133 // Name return the name of current module
139-func (m *MovCore) Name() string {
134+func (m *Core) Name() string {
140135 return "MOV"
141136 }
142137
143138 // StartHeight return the start block height of current module
144-func (m *MovCore) StartHeight() uint64 {
139+func (m *Core) StartHeight() uint64 {
145140 return m.startBlockHeight
146141 }
147142
148143 // ValidateBlock no need to verify the block header, because the first module has been verified.
149144 // just need to verify the transactions in the block.
150-func (m *MovCore) ValidateBlock(block *types.Block, verifyResults []*bc.TxVerifyResult) error {
145+func (m *Core) ValidateBlock(block *types.Block, verifyResults []*bc.TxVerifyResult) error {
151146 for i, tx := range block.Transactions {
152147 if err := m.ValidateTx(tx, verifyResults[i], block.Height); err != nil {
153148 return err
@@ -157,7 +152,15 @@ func (m *MovCore) ValidateBlock(block *types.Block, verifyResults []*bc.TxVerify
157152 }
158153
159154 // ValidateTx validate one transaction.
160-func (m *MovCore) ValidateTx(tx *types.Tx, verifyResult *bc.TxVerifyResult, blockHeight uint64) error {
155+func (m *Core) ValidateTx(tx *types.Tx, verifyResult *bc.TxVerifyResult, blockHeight uint64) error {
156+ if blockHeight <= m.startBlockHeight {
157+ return nil
158+ }
159+
160+ if verifyResult.StatusFail {
161+ return errStatusFailMustFalse
162+ }
163+
161164 if common.IsMatchedTx(tx) {
162165 if err := validateMatchedTx(tx, verifyResult, blockHeight); err != nil {
163166 return err
@@ -172,9 +175,6 @@ func (m *MovCore) ValidateTx(tx *types.Tx, verifyResult *bc.TxVerifyResult, bloc
172175 if !segwit.IsP2WMCScript(output.ControlProgram()) {
173176 continue
174177 }
175- if verifyResult.StatusFail {
176- return errStatusFailMustFalse
177- }
178178
179179 if err := validateMagneticContractArgs(output.AssetAmount(), output.ControlProgram()); err != nil {
180180 return err
@@ -211,18 +211,16 @@ func calcFeeAmount(matchedTx *types.Tx) (map[bc.AssetID]*matchedTxFee, error) {
211211 if assetFeeMap[*assetAmount.AssetId].amount <= 0 {
212212 delete(assetFeeMap, *assetAmount.AssetId)
213213 }
214- } else {
214+ } else if assetFeeMap[*assetAmount.AssetId].rewardProgram == nil {
215215 assetFeeMap[*assetAmount.AssetId].rewardProgram = output.ControlProgram()
216+ } else {
217+ return nil, errors.Wrap(errRewardProgramIsWrong, "double reward program")
216218 }
217219 }
218220 return assetFeeMap, nil
219221 }
220222
221223 func validateCancelOrderTx(tx *types.Tx, verifyResult *bc.TxVerifyResult) error {
222- if verifyResult.StatusFail {
223- return errStatusFailMustFalse
224- }
225-
226224 for _, input := range tx.Inputs {
227225 if !segwit.IsP2WMCScript(input.ControlProgram()) {
228226 return errInputProgramMustP2WMCScript
@@ -256,10 +254,6 @@ func validateMagneticContractArgs(fromAssetAmount bc.AssetAmount, program []byte
256254 }
257255
258256 func validateMatchedTx(tx *types.Tx, verifyResult *bc.TxVerifyResult, blockHeight uint64) error {
259- if verifyResult.StatusFail {
260- return errStatusFailMustFalse
261- }
262-
263257 fromAssetIDMap := make(map[string]bool)
264258 toAssetIDMap := make(map[string]bool)
265259 for i, input := range tx.Inputs {
@@ -314,7 +308,7 @@ func validateMatchedTxFee(tx *types.Tx, blockHeight uint64) error {
314308 return feeStrategy.Validate(receivedAmount, feeAmounts)
315309 }
316310
317-func (m *MovCore) validateMatchedTxSequence(txs []*types.Tx) error {
311+func (m *Core) validateMatchedTxSequence(txs []*types.Tx) error {
318312 orderBook := match.NewOrderBook(m.movStore, nil, nil)
319313 for _, tx := range txs {
320314 if common.IsMatchedTx(tx) {
@@ -404,15 +398,8 @@ func decodeTxsOrders(txs []*types.Tx) ([]*common.Order, []*common.Order, error)
404398 }
405399
406400 func buildOrderBook(store database.MovStore, txs []*types.Tx) (*match.OrderBook, error) {
407- var nonMatchedTxs []*types.Tx
408- for _, tx := range txs {
409- if !common.IsMatchedTx(tx) {
410- nonMatchedTxs = append(nonMatchedTxs, tx)
411- }
412- }
413-
414401 var arrivalAddOrders, arrivalDelOrders []*common.Order
415- for _, tx := range nonMatchedTxs {
402+ for _, tx := range txs {
416403 addOrders, err := getAddOrdersFromTx(tx)
417404 if err != nil {
418405 return nil, err
@@ -437,6 +424,10 @@ func getAddOrdersFromTx(tx *types.Tx) ([]*common.Order, error) {
437424 continue
438425 }
439426
427+ if output.AssetAmount().Amount == 0 {
428+ continue
429+ }
430+
440431 order, err := common.NewOrderFromOutput(tx, i)
441432 if err != nil {
442433 return nil, err
--- a/application/mov/mov_core_test.go
+++ b/application/mov/mov_core_test.go
@@ -264,7 +264,7 @@ func TestApplyBlock(t *testing.T) {
264264 t.Fatal(err)
265265 }
266266
267- movCore := &MovCore{movStore: store}
267+ movCore := &Core{movStore: store}
268268 if err := c.blockFunc(movCore, c.block); err != c.wantError {
269269 t.Errorf("#%d(%s):apply block want error(%v), got error(%v)", i, c.desc, c.wantError, err)
270270 }
@@ -515,7 +515,8 @@ func TestValidateBlock(t *testing.T) {
515515 }
516516
517517 for i, c := range cases {
518- movCore := &MovCore{}
518+ movCore := &Core{}
519+ c.block.Height = 3456786543
519520 if err := movCore.ValidateBlock(c.block, c.verifyResults); err != c.wantError {
520521 t.Errorf("#%d(%s):validate block want error(%v), got error(%v)", i, c.desc, c.wantError, err)
521522 }
@@ -539,22 +540,22 @@ func TestCalcMatchedTxFee(t *testing.T) {
539540 tx: mock.MatchedTxs[1].TxData,
540541 },
541542 {
542- desc: "fee refund in tx",
543- maxFeeRate: 0.05,
543+ desc: "fee refund in tx",
544+ maxFeeRate: 0.05,
544545 wantMatchedTxFee: map[bc.AssetID]*matchedTxFee{
545546 mock.ETH: {amount: 25, rewardProgram: mock.RewardProgram},
546547 mock.BTC: {amount: 1, rewardProgram: mock.RewardProgram},
547548 },
548- tx: mock.MatchedTxs[2].TxData,
549+ tx: mock.MatchedTxs[2].TxData,
549550 },
550551 {
551- desc: "no price diff",
552- maxFeeRate: 0.05,
552+ desc: "no price diff",
553+ maxFeeRate: 0.05,
553554 wantMatchedTxFee: map[bc.AssetID]*matchedTxFee{
554555 mock.ETH: {amount: 1, rewardProgram: mock.RewardProgram},
555556 mock.BTC: {amount: 1, rewardProgram: mock.RewardProgram},
556557 },
557- tx: mock.MatchedTxs[0].TxData,
558+ tx: mock.MatchedTxs[0].TxData,
558559 },
559560 }
560561
@@ -642,7 +643,7 @@ func TestBeforeProposalBlock(t *testing.T) {
642643 t.Fatal(err)
643644 }
644645
645- movCore := &MovCore{movStore: store}
646+ movCore := &Core{movStore: store}
646647 gotMatchedTxs, err := movCore.BeforeProposalBlock(nil, 2, c.gasLeft, func() bool { return false })
647648 if err != nil {
648649 t.Fatal(err)
@@ -795,7 +796,7 @@ func TestValidateMatchedTxSequence(t *testing.T) {
795796 t.Fatal(err)
796797 }
797798
798- movCore := &MovCore{movStore: store}
799+ movCore := &Core{movStore: store}
799800 if err := movCore.validateMatchedTxSequence(c.transactions); err != c.wantError {
800801 t.Errorf("#%d(%s):wanet error(%v), got error(%v)", i, c.desc, c.wantError, err)
801802 }
@@ -805,13 +806,13 @@ func TestValidateMatchedTxSequence(t *testing.T) {
805806 }
806807 }
807808
808-type testFun func(movCore *MovCore, block *types.Block) error
809+type testFun func(movCore *Core, block *types.Block) error
809810
810-func applyBlock(movCore *MovCore, block *types.Block) error {
811+func applyBlock(movCore *Core, block *types.Block) error {
811812 return movCore.ApplyBlock(block)
812813 }
813814
814-func detachBlock(movCore *MovCore, block *types.Block) error {
815+func detachBlock(movCore *Core, block *types.Block) error {
815816 return movCore.DetachBlock(block)
816817 }
817818
--- a/blockchain/txbuilder/signing_instruction.go
+++ b/blockchain/txbuilder/signing_instruction.go
@@ -8,6 +8,7 @@ import (
88 "github.com/bytom/vapor/errors"
99 )
1010
11+// AddDataWitness append data to the witness array
1112 func (si *SigningInstruction) AddDataWitness(data chainjson.HexBytes) {
1213 dw := DataWitness(data)
1314 si.WitnessComponents = append(si.WitnessComponents, &dw)
--- a/cmd/vapord/commands/root.go
+++ b/cmd/vapord/commands/root.go
@@ -15,6 +15,7 @@ var (
1515 config = cfg.DefaultConfig()
1616 )
1717
18+// RootCmd is the command for run node
1819 var RootCmd = &cobra.Command{
1920 Use: "vapord",
2021 Short: "Multiple asset management.",
--- a/common/bytes.go
+++ b/common/bytes.go
@@ -6,6 +6,7 @@ import (
66 "encoding/hex"
77 )
88
9+// FromHex convert hex byte string to []byte
910 func FromHex(s string) []byte {
1011 if len(s) > 1 {
1112 if s[0:2] == "0x" {
@@ -19,21 +20,25 @@ func FromHex(s string) []byte {
1920 return nil
2021 }
2122
23+// Bytes2Hex convert byte array to string
2224 func Bytes2Hex(d []byte) string {
2325 return hex.EncodeToString(d)
2426 }
2527
28+// Hex2Bytes convert hex string to byte array
2629 func Hex2Bytes(str string) []byte {
2730 h, _ := hex.DecodeString(str)
2831 return h
2932 }
3033
34+// Unit64ToBytes convert uint64 to bytes
3135 func Unit64ToBytes(n uint64) []byte {
3236 buf := make([]byte, 8)
3337 binary.LittleEndian.PutUint64(buf, n)
3438 return buf
3539 }
3640
41+// BytesToUnit64 convert bytes to uint64
3742 func BytesToUnit64(b []byte) uint64 {
3843 return binary.LittleEndian.Uint64(b)
3944 }
--- a/common/crossin_asset.go
+++ b/common/crossin_asset.go
@@ -4,6 +4,7 @@ import (
44 "encoding/json"
55 )
66
7+// IsOpenFederationIssueAsset check if the asset definition satisfy ofmf asset
78 func IsOpenFederationIssueAsset(rawDefinitionByte []byte) bool {
89 var defMap map[string]interface{}
910 if err := json.Unmarshal(rawDefinitionByte, &defMap); err != nil {
--- a/common/sort.go
+++ /dev/null
@@ -1,23 +0,0 @@
1-package common
2-
3-// timeSorter implements sort.Interface to allow a slice of timestamps to
4-// be sorted.
5-type TimeSorter []uint64
6-
7-// Len returns the number of timestamps in the slice. It is part of the
8-// sort.Interface implementation.
9-func (s TimeSorter) Len() int {
10- return len(s)
11-}
12-
13-// Swap swaps the timestamps at the passed indices. It is part of the
14-// sort.Interface implementation.
15-func (s TimeSorter) Swap(i, j int) {
16- s[i], s[j] = s[j], s[i]
17-}
18-
19-// Less returns whether the timstamp with index i should sort before the
20-// timestamp with index j. It is part of the sort.Interface implementation.
21-func (s TimeSorter) Less(i, j int) bool {
22- return s[i] < s[j]
23-}
--- a/consensus/general.go
+++ b/consensus/general.go
@@ -254,6 +254,7 @@ func BytomMainNetParams(vaporParam *Params) *Params {
254254 return &Params{Bech32HRPSegwit: bech32HRPSegwit}
255255 }
256256
257+// InitActiveNetParams load the config by chain ID
257258 func InitActiveNetParams(chainID string) error {
258259 var exist bool
259260 if ActiveNetParams, exist = NetParams[chainID]; !exist {
--- a/database/account_store.go
+++ b/database/account_store.go
@@ -45,7 +45,7 @@ func accountIndexKey(xpubs []chainkd.XPub) []byte {
4545 return append(AccountIndexPrefix, hash[:]...)
4646 }
4747
48-func Bip44ContractIndexKey(accountID string, change bool) []byte {
48+func bip44ContractIndexKey(accountID string, change bool) []byte {
4949 key := append(ContractIndexPrefix, []byte(accountID)...)
5050 if change {
5151 return append(key, 0x01)
@@ -96,7 +96,7 @@ func (store *AccountStore) InitBatch() acc.AccountStore {
9696 // CommitBatch commit batch
9797 func (store *AccountStore) CommitBatch() error {
9898 if store.batch == nil {
99- return errors.New("AccountStore commit fail, store batch is nil.")
99+ return errors.New("accountStore commit fail, store batch is nil")
100100 }
101101 store.batch.Write()
102102 store.batch = nil
@@ -119,8 +119,8 @@ func (store *AccountStore) DeleteAccount(account *acc.Account) error {
119119 }
120120
121121 // delete bip44 contract index
122- batch.Delete(Bip44ContractIndexKey(account.ID, false))
123- batch.Delete(Bip44ContractIndexKey(account.ID, true))
122+ batch.Delete(bip44ContractIndexKey(account.ID, false))
123+ batch.Delete(bip44ContractIndexKey(account.ID, true))
124124
125125 // delete contract index
126126 batch.Delete(contractIndexKey(account.ID))
@@ -216,7 +216,7 @@ func (store *AccountStore) GetAccountIndex(xpubs []chainkd.XPub) uint64 {
216216 // GetBip44ContractIndex get bip44 contract index
217217 func (store *AccountStore) GetBip44ContractIndex(accountID string, change bool) uint64 {
218218 index := uint64(0)
219- if rawIndexBytes := store.db.Get(Bip44ContractIndexKey(accountID, change)); rawIndexBytes != nil {
219+ if rawIndexBytes := store.db.Get(bip44ContractIndexKey(accountID, change)); rawIndexBytes != nil {
220220 index = common.BytesToUnit64(rawIndexBytes)
221221 }
222222 return index
@@ -367,9 +367,9 @@ func (store *AccountStore) SetAccountIndex(account *acc.Account) {
367367 // SetBip44ContractIndex set contract index
368368 func (store *AccountStore) SetBip44ContractIndex(accountID string, change bool, index uint64) {
369369 if store.batch == nil {
370- store.db.Set(Bip44ContractIndexKey(accountID, change), common.Unit64ToBytes(index))
370+ store.db.Set(bip44ContractIndexKey(accountID, change), common.Unit64ToBytes(index))
371371 } else {
372- store.batch.Set(Bip44ContractIndexKey(accountID, change), common.Unit64ToBytes(index))
372+ store.batch.Set(bip44ContractIndexKey(accountID, change), common.Unit64ToBytes(index))
373373 }
374374 }
375375
--- a/database/utxo_view.go
+++ b/database/utxo_view.go
@@ -1,12 +1,12 @@
11 package database
22
33 import (
4- "github.com/golang/protobuf/proto"
54 dbm "github.com/bytom/vapor/database/leveldb"
65 "github.com/bytom/vapor/database/storage"
76 "github.com/bytom/vapor/errors"
87 "github.com/bytom/vapor/protocol/bc"
98 "github.com/bytom/vapor/protocol/state"
9+ "github.com/golang/protobuf/proto"
1010 )
1111
1212 const utxoPreFix = "UT:"
@@ -91,6 +91,7 @@ func saveUtxoView(batch dbm.Batch, view *state.UtxoViewpoint) error {
9191 return nil
9292 }
9393
94+// SaveUtxoView is export for intergation test
9495 func SaveUtxoView(batch dbm.Batch, view *state.UtxoViewpoint) error {
9596 return saveUtxoView(batch, view)
9697 }
--- a/database/wallet_store.go
+++ b/database/wallet_store.go
@@ -31,6 +31,7 @@ const (
3131 recoveryKey //recoveryKey key for db store recovery info.
3232 )
3333
34+// pre-define variables
3435 var (
3536 walletStore = []byte("WS:")
3637 SUTXOPrefix = append(walletStore, sutxoPrefix, colon)
@@ -66,10 +67,12 @@ func calcUnconfirmedTxKey(formatKey string) []byte {
6667 return append(UnconfirmedTxPrefix, []byte(formatKey)...)
6768 }
6869
70+// CalcGlobalTxIndexKey calculate tx hash index key
6971 func CalcGlobalTxIndexKey(txID string) []byte {
7072 return append(GlobalTxIndexPrefix, []byte(txID)...)
7173 }
7274
75+// CalcGlobalTxIndex calcuate the block index + position index key
7376 func CalcGlobalTxIndex(blockHash *bc.Hash, position uint64) []byte {
7477 txIdx := make([]byte, 40)
7578 copy(txIdx[:32], blockHash.Bytes())
@@ -109,7 +112,7 @@ func (store *WalletStore) InitBatch() wallet.WalletStore {
109112 // CommitBatch commit batch
110113 func (store *WalletStore) CommitBatch() error {
111114 if store.batch == nil {
112- return errors.New("WalletStore commit fail, store batch is nil.")
115+ return errors.New("walletStore commit fail, store batch is nil")
113116 }
114117
115118 store.batch.Write()
@@ -347,6 +350,7 @@ func (store *WalletStore) ListAccountUTXOs(id string, isSmartContract bool) ([]*
347350 return confirmedUTXOs, nil
348351 }
349352
353+// ListTransactions list tx by filter args
350354 func (store *WalletStore) ListTransactions(accountID string, StartTxID string, count uint, unconfirmed bool) ([]*query.AnnotatedTx, error) {
351355 annotatedTxs := []*query.AnnotatedTx{}
352356 var startKey []byte
--- a/math/algorithm.go
+++ b/math/algorithm.go
@@ -1,5 +1,6 @@
11 package math
22
3+// MinUint64 return the min of x and y
34 func MinUint64(x, y uint64) uint64 {
45 if x < y {
56 return x
--- a/node/node.go
+++ b/node/node.go
@@ -5,6 +5,7 @@ import (
55 "errors"
66 "net"
77 "net/http"
8+ // debug tool
89 _ "net/http/pprof"
910 "path/filepath"
1011 "reflect"
@@ -84,7 +85,7 @@ func NewNode(config *cfg.Config) *Node {
8485 accessTokens := accesstoken.NewStore(tokenDB)
8586
8687 dispatcher := event.NewDispatcher()
87- movCore := mov.NewMovCore(config.DBBackend, config.DBDir(), consensus.ActiveNetParams.MovStartHeight)
88+ movCore := mov.NewCore(config.DBBackend, config.DBDir(), consensus.ActiveNetParams.MovStartHeight)
8889 assetFilter := protocol.NewAssetFilter(config.CrossChain.AssetWhitelist)
8990 txPool := protocol.NewTxPool(store, []protocol.DustFilterer{movCore, assetFilter}, dispatcher)
9091 chain, err := protocol.NewChain(store, txPool, []protocol.Protocoler{movCore}, dispatcher)
@@ -177,7 +178,7 @@ func Rollback(config *cfg.Config, targetHeight uint64) error {
177178 store := database.NewStore(coreDB)
178179
179180 dispatcher := event.NewDispatcher()
180- movCore := mov.NewMovCore(config.DBBackend, config.DBDir(), consensus.ActiveNetParams.MovStartHeight)
181+ movCore := mov.NewCore(config.DBBackend, config.DBDir(), consensus.ActiveNetParams.MovStartHeight)
181182 txPool := protocol.NewTxPool(store, []protocol.DustFilterer{movCore}, dispatcher)
182183 chain, err := protocol.NewChain(store, txPool, []protocol.Protocoler{movCore}, dispatcher)
183184 if err != nil {
@@ -235,7 +236,7 @@ func checkConfig(chain *protocol.Chain, config *cfg.Config) error {
235236 typedInput := genesisBlock.Transactions[0].Inputs[0].TypedInput
236237 if v, ok := typedInput.(*types.CoinbaseInput); ok {
237238 if !reflect.DeepEqual(fedpegScript, v.Arbitrary) {
238- return errors.New("config xpubs don't equal genesis block xpubs.")
239+ return errors.New("config xpubs don't equal genesis block xpubs")
239240 }
240241 }
241242 return nil
@@ -272,6 +273,7 @@ func (n *Node) initAndstartAPIServer() {
272273 n.api.StartServer(*listenAddr)
273274 }
274275
276+// OnStart implements BaseService
275277 func (n *Node) OnStart() error {
276278 if n.miningEnable {
277279 if _, err := n.wallet.AccountMgr.GetMiningAddress(); err != nil {
@@ -303,6 +305,7 @@ func (n *Node) OnStart() error {
303305 return nil
304306 }
305307
308+// OnStop implements BaseService
306309 func (n *Node) OnStop() {
307310 n.notificationMgr.Shutdown()
308311 n.notificationMgr.WaitForShutdown()
@@ -316,6 +319,7 @@ func (n *Node) OnStop() {
316319 n.eventDispatcher.Stop()
317320 }
318321
322+// RunForever listen to the stop signal
319323 func (n *Node) RunForever() {
320324 // Sleep forever and then...
321325 cmn.TrapSignal(func() {
--- a/protocol/asset_filter.go
+++ b/protocol/asset_filter.go
@@ -7,14 +7,15 @@ import (
77 "github.com/bytom/vapor/protocol/bc/types"
88 )
99
10-type assetFilter struct {
10+// AssetFilter is struct for allow open federation asset cross chain
11+type AssetFilter struct {
1112 whitelist map[string]struct{}
1213 }
1314
1415 // NewAssetFilter returns a assetFilter according a whitelist,
1516 // which is a strings list cancated via comma
16-func NewAssetFilter(whitelist string) *assetFilter {
17- af := &assetFilter{whitelist: make(map[string]struct{})}
17+func NewAssetFilter(whitelist string) *AssetFilter {
18+ af := &AssetFilter{whitelist: make(map[string]struct{})}
1819 af.whitelist[consensus.BTMAssetID.String()] = struct{}{}
1920 for _, assetID := range strings.Split(whitelist, ",") {
2021 af.whitelist[strings.ToLower(assetID)] = struct{}{}
@@ -25,7 +26,7 @@ func NewAssetFilter(whitelist string) *assetFilter {
2526 // IsDust implements the DustFilterer interface.
2627 // It filters a transaction as long as there is one asset neither BTM or in the whitelist
2728 // No need to check the output assets types becauese they must have been cover in input assets types
28-func (af *assetFilter) IsDust(tx *types.Tx) bool {
29+func (af *AssetFilter) IsDust(tx *types.Tx) bool {
2930 for _, input := range tx.Inputs {
3031 if _, ok := input.TypedInput.(*types.CrossChainInput); !ok {
3132 continue
--- a/protocol/bbft.go
+++ b/protocol/bbft.go
@@ -240,6 +240,10 @@ func (c *Chain) signBlockHeader(blockHeader *types.BlockHeader) ([]byte, error)
240240 return nil, err
241241 }
242242
243+ if len(blockHeader.Get(node.Order)) != 0 {
244+ return nil, nil
245+ }
246+
243247 if err := c.checkDoubleSign(blockHeader, node.XPub.String()); err == errDoubleSignBlock {
244248 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String()}).Warn("current node has double sign the block")
245249 return nil, nil
@@ -247,10 +251,6 @@ func (c *Chain) signBlockHeader(blockHeader *types.BlockHeader) ([]byte, error)
247251 return nil, err
248252 }
249253
250- if signature := blockHeader.Get(node.Order); len(signature) != 0 {
251- return nil, nil
252- }
253-
254254 signature := xprv.Sign(blockHeader.Hash().Bytes())
255255 blockHeader.Set(node.Order, signature)
256256 return signature, nil
--- a/protocol/bc/types/block.go
+++ b/protocol/bc/types/block.go
@@ -102,6 +102,7 @@ func (b *Block) readFrom(r *blockchain.Reader) error {
102102 return nil
103103 }
104104
105+// WriteTo write block to io.Writer
105106 func (b *Block) WriteTo(w io.Writer) (int64, error) {
106107 ew := errors.NewWriter(w)
107108 if err := b.writeTo(ew, SerBlockFull); err != nil {
--- a/protocol/bc/types/block_witness.go
+++ b/protocol/bc/types/block_witness.go
@@ -6,6 +6,7 @@ import (
66 "github.com/bytom/vapor/encoding/blockchain"
77 )
88
9+// BlockWitness save the consensus node sign
910 type BlockWitness struct {
1011 // Witness is a vector of arguments for validating this block.
1112 Witness [][]byte
@@ -21,6 +22,7 @@ func (bw *BlockWitness) writeTo(w io.Writer) error {
2122 return err
2223 }
2324
25+// Set save data to index position
2426 func (bw *BlockWitness) Set(index uint64, data []byte) {
2527 if uint64(len(bw.Witness)) <= index {
2628 newWitness := make([][]byte, index+1, index+1)
@@ -30,12 +32,14 @@ func (bw *BlockWitness) Set(index uint64, data []byte) {
3032 bw.Witness[index] = data
3133 }
3234
35+// Delete remove data from index position
3336 func (bw *BlockWitness) Delete(index uint64) {
3437 if uint64(len(bw.Witness)) > index {
3538 bw.Witness[index] = nil
3639 }
3740 }
3841
42+// Get return data from index position
3943 func (bw *BlockWitness) Get(index uint64) []byte {
4044 if uint64(len(bw.Witness)) > index {
4145 return bw.Witness[index]
--- 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
2828 }
2929 }
3030
31+// OutputType implement the txout interface
3132 func (it *CrossChainOutput) OutputType() uint8 { return CrossChainOutputType }
--- 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
2828 }
2929 }
3030
31+// OutputType implement the txout interface
3132 func (it *IntraChainOutput) OutputType() uint8 { return IntraChainOutputType }
--- 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
3030 }
3131 }
3232
33+// OutputType implement the txout interface
3334 func (it *VoteOutput) OutputType() uint8 { return VoteOutputType }
--- a/protocol/block.go
+++ b/protocol/block.go
@@ -104,6 +104,7 @@ func (c *Chain) connectBlock(block *types.Block) (err error) {
104104 if err != nil {
105105 return err
106106 }
107+
107108 if err := consensusResult.ApplyBlock(block); err != nil {
108109 return err
109110 }
--- a/protocol/protocol.go
+++ b/protocol/protocol.go
@@ -19,6 +19,7 @@ const (
1919 maxKnownTxs = 32768 // Maximum transactions hashes to keep in the known list (prevent DOS)
2020 )
2121
22+// Protocoler is interface for layer 2 consensus protocol
2223 type Protocoler interface {
2324 Name() string
2425 StartHeight() uint64
@@ -173,6 +174,7 @@ func (c *Chain) InMainChain(hash bc.Hash) bool {
173174 return *blockHash == hash
174175 }
175176
177+// SubProtocols return list of layer 2 consensus protocol
176178 func (c *Chain) SubProtocols() []Protocoler {
177179 return c.subProtocols
178180 }
--- a/protocol/store.go
+++ b/protocol/store.go
@@ -9,6 +9,7 @@ import (
99 "github.com/bytom/vapor/protocol/state"
1010 )
1111
12+// predefine errors
1213 var (
1314 ErrNotFoundConsensusResult = errors.New("can't find the vote result by given sequence")
1415 )
--- a/protocol/txpool.go
+++ b/protocol/txpool.go
@@ -43,10 +43,12 @@ var (
4343 ErrDustTx = errors.New("transaction is dust tx")
4444 )
4545
46+// DustFilterer is inerface for dust transaction filter rule
4647 type DustFilterer interface {
4748 IsDust(tx *types.Tx) bool
4849 }
4950
51+// TxMsgEvent is message wrap for subscribe event
5052 type TxMsgEvent struct{ TxMsg *TxPoolMsg }
5153
5254 // TxDesc store tx and related info for mining strategy
--- 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
101101 return errors.Wrapf(validateResult.err, "validate of transaction %d of %d", i, len(b.Transactions))
102102 }
103103
104- // for support flash swap running on vapor, status fail txs need to be
105- // rejected. Or the attacker can steal BTM from any BTM/* trade pair by
106- // using status fail charge fee rule.
107- if b.Height >= consensus.ActiveNetParams.MovStartHeight && validateResult.err != nil {
108- return errors.New("the chain currently didn't support status fail tx")
109- }
110-
111104 if err := b.TransactionStatus.SetStatus(i, validateResult.err != nil); err != nil {
112105 return err
113106 }
--- a/test/rollback_test.go
+++ b/test/rollback_test.go
@@ -1445,7 +1445,7 @@ func TestRollback(t *testing.T) {
14451445 consensus.ActiveNetParams.RoundVoteBlockNums = c.RoundVoteBlockNums
14461446
14471447 movDB := dbm.NewDB("mov_db", "leveldb", "mov_db")
1448- movCore := mov.NewMovCoreWithDB(movDatabase.NewLevelDBMovStore(movDB), c.movStartHeight)
1448+ movCore := mov.NewCoreWithDB(movDatabase.NewLevelDBMovStore(movDB), c.movStartHeight)
14491449
14501450 blockDB := dbm.NewDB("block_db", "leveldb", "block_db")
14511451 store := database.NewStore(blockDB)
Show on old repository browser