Skip to content

Commit

Permalink
Test go file
Browse files Browse the repository at this point in the history
  • Loading branch information
zhugelianglongming committed Dec 29, 2022
1 parent efe7eb4 commit cf2a119
Show file tree
Hide file tree
Showing 157 changed files with 924 additions and 912 deletions.
4 changes: 0 additions & 4 deletions bcs/consensus/mock/mock_consensus.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package mock

import (
"errors"
"path/filepath"
"time"

Expand All @@ -17,12 +16,9 @@ import (

var (
BcName = "xuper5"
nodeIp = "/ip4/127.0.0.1/tcp/47101/p2p/QmVcSF4F7rTdsvUJqsik98tXRXMBUqL5DSuBpyYKVhjuG4"
priKey = `{"Curvname":"P-256","X":74695617477160058757747208220371236837474210247114418775262229497812962582435,"Y":51348715319124770392993866417088542497927816017012182211244120852620959209571,"D":29079635126530934056640915735344231956621504557963207107451663058887647996601}`
PubKey = `{"Curvname":"P-256","X":74695617477160058757747208220371236837474210247114418775262229497812962582435,"Y":51348715319124770392993866417088542497927816017012182211244120852620959209571}`
Miner = "dpzuVdosQrF2kmzumhVeFQZa1aYcdgFpN"

blockSetItemErr = errors.New("item invalid")
)

func NewFakeLogger() logs.Logger {
Expand Down
6 changes: 3 additions & 3 deletions bcs/consensus/pow/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func GetCompact(number *big.Int) (uint32, bool) {
func SetCompact(nCompact uint32) (*big.Int, bool, bool) {
nSize := nCompact >> 24
nWord := new(big.Int)
u := new(big.Int)
var u *big.Int
nCompactInt := big.NewInt(int64(nCompact))
// 0x00800000是一个符号位,故nWord仅为后23位
lowBits := big.NewInt(0x007fffff)
Expand Down Expand Up @@ -99,14 +99,14 @@ func unmarshalPowConfig(input []byte) (*PoWConfig, error) {
"defaultTarget": 0,
"maxTarget": 0,
}
for k, _ := range int32Map {
for k := range int32Map {
value, err := strconv.ParseInt(consCfg[k].(string), 10, 32)
if err != nil {
return nil, fmt.Errorf("marshal consensus config failed key %s set error", k)
}
int32Map[k] = int32(value)
}
for k, _ := range uint32Map {
for k := range uint32Map {
value, err := strconv.ParseInt(consCfg[k].(string), 10, 64)
if err != nil {
return nil, fmt.Errorf("marshal consensus config failed key %s set error", k)
Expand Down
16 changes: 8 additions & 8 deletions bcs/consensus/pow/pow.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ func (pow *PoWConsensus) CheckMinerMatch(ctx xcontext.XContext, block context.Bl
}
// 跟address比较
chkResult, _ := pow.Crypto.VerifyAddressUsingPublicKey(string(block.GetProposer()), k)
if chkResult == false {
if !chkResult {
ctx.GetLog().Warn("PoW::CheckMinerMatch::address is not match publickey", "miner", string(block.GetProposer()))
return false, err
}
Expand All @@ -245,7 +245,8 @@ func (pow *PoWConsensus) ProcessBeforeMiner(height, timestamp int64) ([]byte, []
}
bits, err := pow.refreshDifficulty(preBlock.GetBlockid(), tipHeight+1)
if err != nil {
pow.Stop()
// TODO: deal with error
_ = pow.Stop()
}
pow.targetBits = bits
store := &PoWStorage{
Expand Down Expand Up @@ -409,10 +410,7 @@ func (pow *PoWConsensus) IsProofed(blockID []byte, targetBits uint32) bool {
// 原xuperchain逻辑
target := big.NewInt(1)
target.Lsh(target, uint(256-targetBits))
if hash.Cmp(target) == 1 {
return false
}
return true
return hash.Cmp(target) != 1
}

// mining 为带副作用的函数,将直接对block进行操作,更改其原始值
Expand Down Expand Up @@ -440,14 +438,16 @@ func (pow *PoWConsensus) mining(task *mineTask) {
return
}
if pow.IsProofed(bid, pow.targetBits) {
task.block.SetItem("blockid", bid)
// TODO: deal with error
_ = task.block.SetItem("blockid", bid)
// 签名重置
s, err := pow.Crypto.SignECDSA(pow.Address.PrivateKey, bid)
if err != nil {
task.doDone(BlockSignErr)
return
}
task.block.SetItem("sign", s)
// TODO: deal with error
_ = task.block.SetItem("sign", s)
task.doDone(nil)
return
}
Expand Down
17 changes: 13 additions & 4 deletions bcs/consensus/pow/pow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,12 @@ func TestMining(t *testing.T) {
return
}
powC.targetBits = minTarget
powC.Start()
defer powC.Stop()
if err := powC.Start(); err != nil {
t.Fatal(err)
}
defer func() {
_ = powC.Stop()
}()
ps := PoWStorage{
TargetBits: minTarget,
}
Expand Down Expand Up @@ -315,7 +319,7 @@ func TestRefreshDifficulty(t *testing.T) {
t.Error("NewBlock error", err)
return
}
l, ok := powC.Ledger.(*kmock.FakeLedger)
l := powC.Ledger.(*kmock.FakeLedger)
err = l.Put(genesisB)
if err != nil {
t.Error("TestRefreshDifficulty put genesis err", "err", err)
Expand Down Expand Up @@ -409,6 +413,9 @@ func TestCheckMinerMatch(t *testing.T) {
}
by, _ := json.Marshal(ps)
b3, err := bmock.NewBlockWithStorage(3, cCtx.Crypto, cCtx.Address, by)
if err != nil {
t.Fatal(err)
}
c := cCtx.BaseCtx
_, err = i.CheckMinerMatch(&c, b3)
if err != nil {
Expand All @@ -423,5 +430,7 @@ func TestCompeteMaster(t *testing.T) {
return
}
i := NewPoWConsensus(*cCtx, getConsensusConf(getPoWConsensusConf()))
i.CompeteMaster(3)
if _, _, err := i.CompeteMaster(3); err != nil {
t.Fatal(err)
}
}
2 changes: 1 addition & 1 deletion bcs/consensus/single/single.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func (s *SingleConsensus) CheckMinerMatch(ctx xcontext.XContext, block cctx.Bloc
return false, err
}
chkResult, _ := s.ctx.Crypto.VerifyAddressUsingPublicKey(string(block.GetProposer()), k)
if chkResult == false {
if !chkResult {
ctx.GetLog().Warn("Single::CheckMinerMatch::address is not match publickey")
return false, err
}
Expand Down
12 changes: 9 additions & 3 deletions bcs/consensus/single/single_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,15 @@ func TestNewSingleConsensus(t *testing.T) {
if i := NewSingleConsensus(*cCtx, getWrongConsensusConf()); i != nil {
t.Error("NewSingleConsensus check name error")
}
i.Stop()
i.Start()
i.ProcessBeforeMiner(0, time.Now().UnixNano())
if err := i.Stop(); err != nil {
t.Fatal(err)
}
if err := i.Start(); err != nil {
t.Fatal(err)
}
if _, _, err := i.ProcessBeforeMiner(0, time.Now().UnixNano()); err != nil {
t.Fatal(err)
}
cCtx.XLog = nil
i = NewSingleConsensus(*cCtx, conf)
if i != nil {
Expand Down
2 changes: 1 addition & 1 deletion bcs/consensus/tdpos/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func buildConfigs(input []byte) (*tdposConfig, error) {
"block_num": 0,
"timestamp": 0,
}
for k, _ := range int64Map {
for k := range int64Map {
if _, ok := consCfg[k]; !ok {
if k == "version" {
continue
Expand Down
2 changes: 1 addition & 1 deletion bcs/consensus/tdpos/kernel_contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ func (tp *tdposConsensus) runGetTdposInfos(contractCtx contract.KContext) (*cont

// vote信息
voteMap := make(map[string]voteValue)
for candidate, _ := range nominateValue {
for candidate := range nominateValue {
// 读取投票存储
voteKey := fmt.Sprintf("%s_%d_%s%s", tp.status.Name, tp.status.Version, voteKeyPrefix, candidate)
res, err = contractCtx.Get(tp.election.bindContractBucket, []byte(voteKey))
Expand Down
47 changes: 27 additions & 20 deletions bcs/consensus/tdpos/kernel_contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,10 @@ func TestRunNominateCandidate(t *testing.T) {
}
// 1. 构造term存储
l, _ := cCtx.Ledger.(*kmock.FakeLedger)
l.Put(kmock.NewBlock(3))
l.Put(kmock.NewBlock(4))
l.Put(kmock.NewBlock(5))
l.Put(kmock.NewBlock(6))
_ = l.Put(kmock.NewBlock(3))
_ = l.Put(kmock.NewBlock(4))
_ = l.Put(kmock.NewBlock(5))
_ = l.Put(kmock.NewBlock(6))
// 2. 整理Block的共识存储
l.SetConsensusStorage(1, SetTdposStorage(1, nil))
l.SetConsensusStorage(2, SetTdposStorage(1, nil))
Expand Down Expand Up @@ -116,10 +116,10 @@ func TestRunRevokeCandidate(t *testing.T) {
}
// 1. 构造term存储
l, _ := cCtx.Ledger.(*kmock.FakeLedger)
l.Put(kmock.NewBlock(3))
l.Put(kmock.NewBlock(4))
l.Put(kmock.NewBlock(5))
l.Put(kmock.NewBlock(6))
_ = l.Put(kmock.NewBlock(3))
_ = l.Put(kmock.NewBlock(4))
_ = l.Put(kmock.NewBlock(5))
_ = l.Put(kmock.NewBlock(6))
// 2. 整理Block的共识存储
l.SetConsensusStorage(1, SetTdposStorage(1, nil))
l.SetConsensusStorage(2, SetTdposStorage(1, nil))
Expand All @@ -137,7 +137,9 @@ func TestRunRevokeCandidate(t *testing.T) {
i := NewTdposConsensus(*cCtx, getConfig(getTdposConsensusConf()))
tdpos, _ := i.(*tdposConsensus)
fakeCtx := mock.NewFakeKContext(NewRevokeNominateArgs(), NewM())
tdpos.runRevokeCandidate(fakeCtx)
if _, err := tdpos.runRevokeCandidate(fakeCtx); err != nil {
t.Fatal(err)
}
}

func TestRunVote(t *testing.T) {
Expand All @@ -148,10 +150,10 @@ func TestRunVote(t *testing.T) {
}
// 1. 构造term存储
l, _ := cCtx.Ledger.(*kmock.FakeLedger)
l.Put(kmock.NewBlock(3))
l.Put(kmock.NewBlock(4))
l.Put(kmock.NewBlock(5))
l.Put(kmock.NewBlock(6))
_ = l.Put(kmock.NewBlock(3))
_ = l.Put(kmock.NewBlock(4))
_ = l.Put(kmock.NewBlock(5))
_ = l.Put(kmock.NewBlock(6))
// 2. 整理Block的共识存储
l.SetConsensusStorage(1, SetTdposStorage(1, nil))
l.SetConsensusStorage(2, SetTdposStorage(1, nil))
Expand All @@ -169,7 +171,10 @@ func TestRunVote(t *testing.T) {
i := NewTdposConsensus(*cCtx, getConfig(getTdposConsensusConf()))
tdpos, _ := i.(*tdposConsensus)
fakeCtx := mock.NewFakeKContext(NewVoteArgs(), NewM())
tdpos.runVote(fakeCtx)
_, err = tdpos.runVote(fakeCtx)
if err != nil {
t.Fatal(err)
}
}
func TestRunRevokeVote(t *testing.T) {
cCtx, err := prepare(getTdposConsensusConf())
Expand All @@ -178,11 +183,11 @@ func TestRunRevokeVote(t *testing.T) {
return
}
// 1. 构造term存储
l, _ := cCtx.Ledger.(*kmock.FakeLedger)
l.Put(kmock.NewBlock(3))
l.Put(kmock.NewBlock(4))
l.Put(kmock.NewBlock(5))
l.Put(kmock.NewBlock(6))
l := cCtx.Ledger.(*kmock.FakeLedger)
_ = l.Put(kmock.NewBlock(3))
_ = l.Put(kmock.NewBlock(4))
_ = l.Put(kmock.NewBlock(5))
_ = l.Put(kmock.NewBlock(6))
// 2. 整理Block的共识存储
l.SetConsensusStorage(1, SetTdposStorage(1, nil))
l.SetConsensusStorage(2, SetTdposStorage(1, nil))
Expand All @@ -200,5 +205,7 @@ func TestRunRevokeVote(t *testing.T) {
i := NewTdposConsensus(*cCtx, getConfig(getTdposConsensusConf()))
tdpos, _ := i.(*tdposConsensus)
fakeCtx := mock.NewFakeKContext(NewNominateArgs(), NewM())
tdpos.runRevokeVote(fakeCtx)
if _, err := tdpos.runRevokeVote(fakeCtx); err != nil {
t.Fatal(err)
}
}
2 changes: 1 addition & 1 deletion bcs/consensus/tdpos/schedule.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ func (s *tdposSchedule) calTopKNominator(height int64) ([]string, error) {
return nil, err
}
var termBallotSli termBallotsSlice
for candidate, _ := range nominateValue {
for candidate := range nominateValue {
candidateBallot := &termBallots{
Address: candidate,
}
Expand Down
25 changes: 14 additions & 11 deletions bcs/consensus/tdpos/schedule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,19 +124,22 @@ func TestCalHisValidators(t *testing.T) {
}
s := NewSchedule(tdposCfg, cCtx.XLog, cCtx.Ledger, 1)
if s == nil {
t.Error("NewSchedule error.")
t.Fatal("NewSchedule error.")
}
// 1. 构造term存储
l, _ := s.ledger.(*kmock.FakeLedger)
l.Put(kmock.NewBlock(3))
l.Put(kmock.NewBlock(4))
l.Put(kmock.NewBlock(5))
l.Put(kmock.NewBlock(6))
l.Put(kmock.NewBlock(7))
l.Put(kmock.NewBlock(8))
l.Put(kmock.NewBlock(9))
l.Put(kmock.NewBlock(10))
l.Put(kmock.NewBlock(11))
l := s.ledger.(*kmock.FakeLedger)
if l == nil {
t.Fatal("nil FakeLedger")
}
_ = l.Put(kmock.NewBlock(3))
_ = l.Put(kmock.NewBlock(4))
_ = l.Put(kmock.NewBlock(5))
_ = l.Put(kmock.NewBlock(6))
_ = l.Put(kmock.NewBlock(7))
_ = l.Put(kmock.NewBlock(8))
_ = l.Put(kmock.NewBlock(9))
_ = l.Put(kmock.NewBlock(10))
_ = l.Put(kmock.NewBlock(11))
// 2. 整理Block的共识存储
l.SetConsensusStorage(1, SetTdposStorage(1, nil))
l.SetConsensusStorage(2, SetTdposStorage(1, nil))
Expand Down
6 changes: 1 addition & 5 deletions bcs/consensus/tdpos/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,8 @@ func (t *TdposStatus) GetCurrentTerm() int64 {

// 获取当前矿工信息
func (t *TdposStatus) GetCurrentValidatorsInfo() []byte {
var validators []string
for _, a := range t.election.validators {
validators = append(validators, a)
}
v := ValidatorsInfo{
Validators: validators,
Validators: t.election.validators,
Curterm: t.election.curTerm,
Miner: t.election.miner,
ContractInfo: "pls invoke getTdposInfos",
Expand Down
5 changes: 3 additions & 2 deletions bcs/consensus/tdpos/tdpos.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
)

func init() {
// ignore error, it will panic if error exist
consensus.Register("tdpos", NewTdposConsensus)
}

Expand Down Expand Up @@ -101,7 +102,7 @@ func NewTdposConsensus(cCtx cctx.ConsensusCtx, cCfg def.ConsensusConfig) consens
tdpos.kMethod = tdposKMethods

// 凡属于共识升级的逻辑,新建的Tdpos实例将直接将当前值置为true,原因是上一共识模块已经在当前值生成了高度为trigger height的区块,新的实例会再生成一边
timeKey := time.Now().Sub(time.Unix(0, 0)).Milliseconds() / tdpos.config.Period
timeKey := time.Since(time.Unix(0, 0)).Milliseconds() / tdpos.config.Period
tdpos.isProduce[timeKey] = true
return tdpos
}
Expand Down Expand Up @@ -365,7 +366,7 @@ func (tp *tdposConsensus) initBFT() error {
// 共识实例的挂起逻辑, 另: 若共识实例发现绑定block结构有误,会直接停掉当前共识实例并panic
func (tp *tdposConsensus) Stop() error {
// 注销合约方法
for method, _ := range tp.kMethod {
for method := range tp.kMethod {
// 若有历史句柄,删除老句柄
tp.contract.GetKernRegistry().UnregisterKernMethod(tp.election.bindContractBucket, method)
}
Expand Down
Loading

0 comments on commit cf2a119

Please sign in to comment.