github.com/badrootd/nibiru-cometbft@v0.37.5-0.20240307173500-2a75559eee9b/internal/test/commit.go (about) 1 package test 2 3 import ( 4 "fmt" 5 "time" 6 7 cmtproto "github.com/badrootd/nibiru-cometbft/proto/tendermint/types" 8 sm "github.com/badrootd/nibiru-cometbft/state" 9 "github.com/badrootd/nibiru-cometbft/types" 10 ) 11 12 func MakeCommitFromVoteSet(blockID types.BlockID, voteSet *types.VoteSet, validators []types.PrivValidator, now time.Time) (*types.Commit, error) { 13 // all sign 14 for i := 0; i < len(validators); i++ { 15 pubKey, err := validators[i].GetPubKey() 16 if err != nil { 17 return nil, err 18 } 19 vote := &types.Vote{ 20 ValidatorAddress: pubKey.Address(), 21 ValidatorIndex: int32(i), 22 Height: voteSet.GetHeight(), 23 Round: voteSet.GetRound(), 24 Type: cmtproto.PrecommitType, 25 BlockID: blockID, 26 Timestamp: now, 27 } 28 29 v := vote.ToProto() 30 31 if err := validators[i].SignVote(voteSet.ChainID(), v); err != nil { 32 return nil, err 33 } 34 vote.Signature = v.Signature 35 if _, err := voteSet.AddVote(vote); err != nil { 36 return nil, err 37 } 38 } 39 40 return voteSet.MakeCommit(), nil 41 } 42 43 func MakeVoteSet(lastState sm.State, round int32) *types.VoteSet { 44 return types.NewVoteSet(lastState.ChainID, lastState.LastBlockHeight+1, round, cmtproto.PrecommitType, lastState.NextValidators) 45 } 46 47 func MakeCommit(blockID types.BlockID, height int64, round int32, valSet *types.ValidatorSet, privVals []types.PrivValidator, chainID string, now time.Time) (*types.Commit, error) { 48 sigs := make([]types.CommitSig, len(valSet.Validators)) 49 for i := 0; i < len(valSet.Validators); i++ { 50 sigs[i] = types.NewCommitSigAbsent() 51 } 52 53 for _, privVal := range privVals { 54 pk, err := privVal.GetPubKey() 55 if err != nil { 56 return nil, err 57 } 58 addr := pk.Address() 59 60 idx, _ := valSet.GetByAddress(addr) 61 if idx < 0 { 62 return nil, fmt.Errorf("validator with address %s not in validator set", addr) 63 } 64 65 vote := &types.Vote{ 66 ValidatorAddress: addr, 67 ValidatorIndex: idx, 68 Height: height, 69 Round: round, 70 Type: cmtproto.PrecommitType, 71 BlockID: blockID, 72 Timestamp: now, 73 } 74 75 v := vote.ToProto() 76 77 if err := privVal.SignVote(chainID, v); err != nil { 78 return nil, err 79 } 80 81 sigs[idx] = types.CommitSig{ 82 BlockIDFlag: types.BlockIDFlagCommit, 83 ValidatorAddress: addr, 84 Timestamp: now, 85 Signature: v.Signature, 86 } 87 } 88 89 return types.NewCommit(height, round, blockID, sigs), nil 90 }