Merge branch 'feature/abci++ppp'

This commit is contained in:
Sergio Mena
2022-08-22 17:16:17 +02:00
114 changed files with 6444 additions and 2452 deletions
+7 -6
View File
@@ -137,22 +137,22 @@ func (b *Block) Hash() tmbytes.HexBytes {
// MakePartSet returns a PartSet containing parts of a serialized block.
// This is the form in which the block is gossipped to peers.
// CONTRACT: partSize is greater than zero.
func (b *Block) MakePartSet(partSize uint32) *PartSet {
func (b *Block) MakePartSet(partSize uint32) (*PartSet, error) {
if b == nil {
return nil
return nil, errors.New("nil block")
}
b.mtx.Lock()
defer b.mtx.Unlock()
pbb, err := b.ToProto()
if err != nil {
panic(err)
return nil, err
}
bz, err := proto.Marshal(pbb)
if err != nil {
panic(err)
return nil, err
}
return NewPartSetFromData(bz, partSize)
return NewPartSetFromData(bz, partSize), nil
}
// HashesTo is a convenience function that checks if a block hashes to the given argument.
@@ -509,7 +509,8 @@ func (h *Header) StringIndented(indent string) string {
indent, h.LastResultsHash,
indent, h.EvidenceHash,
indent, h.ProposerAddress,
indent, h.Hash())
indent, h.Hash(),
)
}
// ToProto converts Header to protobuf
+23 -10
View File
@@ -41,7 +41,8 @@ func TestBlockAddEvidence(t *testing.T) {
commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
require.NoError(t, err)
ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
ev, err := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
require.NoError(t, err)
evList := []Evidence{ev}
block := MakeBlock(h, txs, commit, evList)
@@ -61,7 +62,8 @@ func TestBlockValidateBasic(t *testing.T) {
commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
require.NoError(t, err)
ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
ev, err := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
require.NoError(t, err)
evList := []Evidence{ev}
testCases := []struct {
@@ -110,15 +112,20 @@ func TestBlockHash(t *testing.T) {
}
func TestBlockMakePartSet(t *testing.T) {
assert.Nil(t, (*Block)(nil).MakePartSet(2))
bps, err := (*Block)(nil).MakePartSet(2)
assert.Error(t, err)
assert.Nil(t, bps)
partSet := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).MakePartSet(1024)
partSet, err := MakeBlock(int64(3), []Tx{Tx("Hello World")}, nil, nil).MakePartSet(1024)
require.NoError(t, err)
assert.NotNil(t, partSet)
assert.EqualValues(t, 1, partSet.Total())
}
func TestBlockMakePartSetWithEvidence(t *testing.T) {
assert.Nil(t, (*Block)(nil).MakePartSet(2))
bps, err := (*Block)(nil).MakePartSet(2)
assert.Error(t, err)
assert.Nil(t, bps)
lastID := makeBlockIDRandom()
h := int64(3)
@@ -127,10 +134,13 @@ func TestBlockMakePartSetWithEvidence(t *testing.T) {
commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
require.NoError(t, err)
ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
ev, err := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
require.NoError(t, err)
evList := []Evidence{ev}
partSet := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList).MakePartSet(512)
partSet, err := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList).MakePartSet(512)
require.NoError(t, err)
assert.NotNil(t, partSet)
assert.EqualValues(t, 4, partSet.Total())
}
@@ -144,7 +154,8 @@ func TestBlockHashesTo(t *testing.T) {
commit, err := MakeCommit(lastID, h-1, 1, voteSet, vals, time.Now())
require.NoError(t, err)
ev := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
ev, err := NewMockDuplicateVoteEvidenceWithValidator(h, time.Now(), vals[0], "block-test-chain")
require.NoError(t, err)
evList := []Evidence{ev}
block := MakeBlock(h, []Tx{Tx("Hello World")}, commit, evList)
@@ -635,7 +646,8 @@ func TestBlockProtoBuf(t *testing.T) {
b2 := MakeBlock(h, []Tx{Tx([]byte{1})}, c1, []Evidence{})
b2.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
evi := NewMockDuplicateVoteEvidence(h, evidenceTime, "block-test-chain")
evi, err := NewMockDuplicateVoteEvidence(h, evidenceTime, "block-test-chain")
require.NoError(t, err)
b2.Evidence = EvidenceData{Evidence: EvidenceList{evi}}
b2.EvidenceHash = b2.Evidence.Hash()
@@ -699,7 +711,8 @@ func TestDataProtoBuf(t *testing.T) {
// TestEvidenceDataProtoBuf ensures parity in converting to and from proto.
func TestEvidenceDataProtoBuf(t *testing.T) {
const chainID = "mychain"
ev := NewMockDuplicateVoteEvidence(math.MaxInt64, time.Now(), chainID)
ev, err := NewMockDuplicateVoteEvidence(math.MaxInt64, time.Now(), chainID)
require.NoError(t, err)
data := &EvidenceData{Evidence: EvidenceList{ev}}
_ = data.ByteSize()
testCases := []struct {
+2 -1
View File
@@ -285,7 +285,8 @@ func TestEventBusPublishEventNewEvidence(t *testing.T) {
}
})
ev := NewMockDuplicateVoteEvidence(1, time.Now(), "test-chain-id")
ev, err := NewMockDuplicateVoteEvidence(1, time.Now(), "test-chain-id")
require.NoError(t, err)
query := "tm.event='NewEvidence'"
evSub, err := eventBus.Subscribe(context.Background(), "test", tmquery.MustParse(query))
+50 -26
View File
@@ -20,13 +20,13 @@ import (
// Evidence represents any provable malicious activity by a validator.
// Verification logic for each evidence is part of the evidence module.
type Evidence interface {
ABCI() []abci.Evidence // forms individual evidence to be sent to the application
Bytes() []byte // bytes which comprise the evidence
Hash() []byte // hash of the evidence
Height() int64 // height of the infraction
String() string // string format of the evidence
Time() time.Time // time of the infraction
ValidateBasic() error // basic consistency check
ABCI() []abci.Misbehavior // forms individual evidence to be sent to the application
Bytes() []byte // bytes which comprise the evidence
Hash() []byte // hash of the evidence
Height() int64 // height of the infraction
String() string // string format of the evidence
Time() time.Time // time of the infraction
ValidateBasic() error // basic consistency check
}
//--------------------------------------------------------------------------------------
@@ -45,15 +45,20 @@ type DuplicateVoteEvidence struct {
var _ Evidence = &DuplicateVoteEvidence{}
// NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given
// two conflicting votes. If one of the votes is nil, evidence returned is nil as well
func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *ValidatorSet) *DuplicateVoteEvidence {
// two conflicting votes. If either of the votes is nil, the val set is nil or the voter is
// not in the val set, an error is returned
func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *ValidatorSet,
) (*DuplicateVoteEvidence, error) {
var voteA, voteB *Vote
if vote1 == nil || vote2 == nil || valSet == nil {
return nil
if vote1 == nil || vote2 == nil {
return nil, errors.New("missing vote")
}
if valSet == nil {
return nil, errors.New("missing validator set")
}
idx, val := valSet.GetByAddress(vote1.ValidatorAddress)
if idx == -1 {
return nil
return nil, fmt.Errorf("validator %s not in validator set", vote1.ValidatorAddress.String())
}
if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 {
@@ -69,13 +74,13 @@ func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *V
TotalVotingPower: valSet.TotalVotingPower(),
ValidatorPower: val.VotingPower,
Timestamp: blockTime,
}
}, nil
}
// ABCI returns the application relevant representation of the evidence
func (dve *DuplicateVoteEvidence) ABCI() []abci.Evidence {
return []abci.Evidence{{
Type: abci.EvidenceType_DUPLICATE_VOTE,
func (dve *DuplicateVoteEvidence) ABCI() []abci.Misbehavior {
return []abci.Misbehavior{{
Type: abci.MisbehaviorType_DUPLICATE_VOTE,
Validator: abci.Validator{
Address: dve.VoteA.ValidatorAddress,
Power: dve.ValidatorPower,
@@ -199,12 +204,12 @@ type LightClientAttackEvidence struct {
var _ Evidence = &LightClientAttackEvidence{}
// ABCI forms an array of abci evidence for each byzantine validator
func (l *LightClientAttackEvidence) ABCI() []abci.Evidence {
abciEv := make([]abci.Evidence, len(l.ByzantineValidators))
// ABCI forms an array of abci.Misbehavior for each byzantine validator
func (l *LightClientAttackEvidence) ABCI() []abci.Misbehavior {
abciEv := make([]abci.Misbehavior, len(l.ByzantineValidators))
for idx, val := range l.ByzantineValidators {
abciEv[idx] = abci.Evidence{
Type: abci.EvidenceType_LIGHT_CLIENT_ATTACK,
abciEv[idx] = abci.Misbehavior{
Type: abci.MisbehaviorType_LIGHT_CLIENT_ATTACK,
Validator: TM2PB.Validator(val),
Height: l.Height(),
Time: l.Timestamp,
@@ -459,6 +464,16 @@ func (evl EvidenceList) Has(evidence Evidence) bool {
return false
}
// ToABCI converts the evidence list to a slice of the ABCI protobuf messages
// for use when communicating the evidence to an application.
func (evl EvidenceList) ToABCI() []abci.Misbehavior {
var el []abci.Misbehavior
for _, e := range evl {
el = append(el, e.ABCI()...)
}
return el
}
//------------------------------------------ PROTO --------------------------------------
// EvidenceToProto is a generalized function for encoding evidence that conforms to the
@@ -554,23 +569,32 @@ func (err *ErrEvidenceOverflow) Error() string {
// unstable - use only for testing
// assumes the round to be 0 and the validator index to be 0
func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) *DuplicateVoteEvidence {
func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) (*DuplicateVoteEvidence, error) {
val := NewMockPV()
return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID)
}
// assumes voting power to be 10 and validator to be the only one in the set
func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time,
pv PrivValidator, chainID string) *DuplicateVoteEvidence {
pubKey, _ := pv.GetPubKey()
pv PrivValidator, chainID string) (*DuplicateVoteEvidence, error) {
pubKey, err := pv.GetPubKey()
if err != nil {
return nil, err
}
val := NewValidator(pubKey, 10)
voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
vA := voteA.ToProto()
_ = pv.SignVote(chainID, vA)
err = pv.SignVote(chainID, vA)
if err != nil {
return nil, err
}
voteA.Signature = vA.Signature
voteB := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time)
vB := voteB.ToProto()
_ = pv.SignVote(chainID, vB)
err = pv.SignVote(chainID, vB)
if err != nil {
return nil, err
}
voteB.Signature = vB.Signature
return NewDuplicateVoteEvidence(voteA, voteB, time, NewValidatorSet([]*Validator{val}))
}
+8 -6
View File
@@ -43,7 +43,8 @@ func randomDuplicateVoteEvidence(t *testing.T) *DuplicateVoteEvidence {
func TestDuplicateVoteEvidence(t *testing.T) {
const height = int64(13)
ev := NewMockDuplicateVoteEvidence(height, time.Now(), "mock-chain-id")
ev, err := NewMockDuplicateVoteEvidence(height, time.Now(), "mock-chain-id")
require.NoError(t, err)
assert.Equal(t, ev.Hash(), tmhash.Sum(ev.Bytes()))
assert.NotNil(t, ev.String())
assert.Equal(t, ev.Height(), height)
@@ -82,7 +83,8 @@ func TestDuplicateVoteEvidenceValidation(t *testing.T) {
vote1 := makeVote(t, val, chainID, math.MaxInt32, math.MaxInt64, math.MaxInt32, 0x02, blockID, defaultVoteTime)
vote2 := makeVote(t, val, chainID, math.MaxInt32, math.MaxInt64, math.MaxInt32, 0x02, blockID2, defaultVoteTime)
valSet := NewValidatorSet([]*Validator{val.ExtractIntoValidator(10)})
ev := NewDuplicateVoteEvidence(vote1, vote2, defaultVoteTime, valSet)
ev, err := NewDuplicateVoteEvidence(vote1, vote2, defaultVoteTime, valSet)
require.NoError(t, err)
tc.malleateEvidence(ev)
assert.Equal(t, tc.expectErr, ev.ValidateBasic() != nil, "Validate Basic had an unexpected result")
})
@@ -224,7 +226,8 @@ func TestLightClientAttackEvidenceValidation(t *testing.T) {
}
func TestMockEvidenceValidateBasic(t *testing.T) {
goodEvidence := NewMockDuplicateVoteEvidence(int64(1), time.Now(), "mock-chain-id")
goodEvidence, err := NewMockDuplicateVoteEvidence(int64(1), time.Now(), "mock-chain-id")
require.NoError(t, err)
assert.Nil(t, goodEvidence.ValidateBasic())
}
@@ -245,9 +248,8 @@ func makeVote(
vpb := v.ToProto()
err = val.SignVote(chainID, vpb)
if err != nil {
panic(err)
}
require.NoError(t, err)
v.Signature = vpb.Signature
return v
}
+8 -9
View File
@@ -12,7 +12,6 @@ import (
tmbytes "github.com/tendermint/tendermint/libs/bytes"
tmjson "github.com/tendermint/tendermint/libs/json"
tmos "github.com/tendermint/tendermint/libs/os"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
)
@@ -37,13 +36,13 @@ type GenesisValidator struct {
// GenesisDoc defines the initial conditions for a tendermint blockchain, in particular its validator set.
type GenesisDoc struct {
GenesisTime time.Time `json:"genesis_time"`
ChainID string `json:"chain_id"`
InitialHeight int64 `json:"initial_height"`
ConsensusParams *tmproto.ConsensusParams `json:"consensus_params,omitempty"`
Validators []GenesisValidator `json:"validators,omitempty"`
AppHash tmbytes.HexBytes `json:"app_hash"`
AppState json.RawMessage `json:"app_state,omitempty"`
GenesisTime time.Time `json:"genesis_time"`
ChainID string `json:"chain_id"`
InitialHeight int64 `json:"initial_height"`
ConsensusParams *ConsensusParams `json:"consensus_params,omitempty"`
Validators []GenesisValidator `json:"validators,omitempty"`
AppHash tmbytes.HexBytes `json:"app_hash"`
AppState json.RawMessage `json:"app_state,omitempty"`
}
// SaveAs is a utility method for saving GenensisDoc as a JSON file.
@@ -83,7 +82,7 @@ func (genDoc *GenesisDoc) ValidateAndComplete() error {
if genDoc.ConsensusParams == nil {
genDoc.ConsensusParams = DefaultConsensusParams()
} else if err := ValidateConsensusParams(*genDoc.ConsensusParams); err != nil {
} else if err := genDoc.ConsensusParams.ValidateBasic(); err != nil {
return err
}
+101 -25
View File
@@ -5,7 +5,8 @@ import (
"fmt"
"time"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/tendermint/tendermint/crypto/tmhash"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
@@ -19,11 +20,52 @@ const (
// MaxBlockPartsCount is the maximum number of block parts.
MaxBlockPartsCount = (MaxBlockSizeBytes / BlockPartSizeBytes) + 1
ABCIPubKeyTypeEd25519 = ed25519.KeyType
ABCIPubKeyTypeSecp256k1 = secp256k1.KeyType
)
var ABCIPubKeyTypesToNames = map[string]string{
ABCIPubKeyTypeEd25519: ed25519.PubKeyName,
ABCIPubKeyTypeSecp256k1: secp256k1.PubKeyName,
}
// ConsensusParams contains consensus critical parameters that determine the
// validity of blocks.
type ConsensusParams struct {
Block BlockParams `json:"block"`
Evidence EvidenceParams `json:"evidence"`
Validator ValidatorParams `json:"validator"`
Version VersionParams `json:"version"`
}
// BlockParams define limits on the block size and gas plus minimum time
// between blocks.
type BlockParams struct {
MaxBytes int64 `json:"max_bytes"`
MaxGas int64 `json:"max_gas"`
}
// EvidenceParams determine how we handle evidence of malfeasance.
type EvidenceParams struct {
MaxAgeNumBlocks int64 `json:"max_age_num_blocks"` // only accept new evidence more recent than this
MaxAgeDuration time.Duration `json:"max_age_duration"`
MaxBytes int64 `json:"max_bytes"`
}
// ValidatorParams restrict the public key types validators can use.
// NOTE: uses ABCI pubkey naming, not Amino names.
type ValidatorParams struct {
PubKeyTypes []string `json:"pub_key_types"`
}
type VersionParams struct {
App uint64 `json:"app"`
}
// DefaultConsensusParams returns a default ConsensusParams.
func DefaultConsensusParams() *tmproto.ConsensusParams {
return &tmproto.ConsensusParams{
func DefaultConsensusParams() *ConsensusParams {
return &ConsensusParams{
Block: DefaultBlockParams(),
Evidence: DefaultEvidenceParams(),
Validator: DefaultValidatorParams(),
@@ -32,17 +74,16 @@ func DefaultConsensusParams() *tmproto.ConsensusParams {
}
// DefaultBlockParams returns a default BlockParams.
func DefaultBlockParams() tmproto.BlockParams {
return tmproto.BlockParams{
MaxBytes: 22020096, // 21MB
MaxGas: -1,
TimeIotaMs: 1000, // 1s
func DefaultBlockParams() BlockParams {
return BlockParams{
MaxBytes: 22020096, // 21MB
MaxGas: -1,
}
}
// DefaultEvidenceParams returns a default EvidenceParams.
func DefaultEvidenceParams() tmproto.EvidenceParams {
return tmproto.EvidenceParams{
func DefaultEvidenceParams() EvidenceParams {
return EvidenceParams{
MaxAgeNumBlocks: 100000, // 27.8 hrs at 1block/s
MaxAgeDuration: 48 * time.Hour,
MaxBytes: 1048576, // 1MB
@@ -51,19 +92,19 @@ func DefaultEvidenceParams() tmproto.EvidenceParams {
// DefaultValidatorParams returns a default ValidatorParams, which allows
// only ed25519 pubkeys.
func DefaultValidatorParams() tmproto.ValidatorParams {
return tmproto.ValidatorParams{
func DefaultValidatorParams() ValidatorParams {
return ValidatorParams{
PubKeyTypes: []string{ABCIPubKeyTypeEd25519},
}
}
func DefaultVersionParams() tmproto.VersionParams {
return tmproto.VersionParams{
AppVersion: 0,
func DefaultVersionParams() VersionParams {
return VersionParams{
App: 0,
}
}
func IsValidPubkeyType(params tmproto.ValidatorParams, pubkeyType string) bool {
func IsValidPubkeyType(params ValidatorParams, pubkeyType string) bool {
for i := 0; i < len(params.PubKeyTypes); i++ {
if params.PubKeyTypes[i] == pubkeyType {
return true
@@ -74,7 +115,7 @@ func IsValidPubkeyType(params tmproto.ValidatorParams, pubkeyType string) bool {
// Validate validates the ConsensusParams to ensure all values are within their
// allowed limits, and returns an error if they are not.
func ValidateConsensusParams(params tmproto.ConsensusParams) error {
func (params ConsensusParams) ValidateBasic() error {
if params.Block.MaxBytes <= 0 {
return fmt.Errorf("block.MaxBytes must be greater than 0. Got %d",
params.Block.MaxBytes)
@@ -89,11 +130,6 @@ func ValidateConsensusParams(params tmproto.ConsensusParams) error {
params.Block.MaxGas)
}
if params.Block.TimeIotaMs <= 0 {
return fmt.Errorf("block.TimeIotaMs must be greater than 0. Got %v",
params.Block.TimeIotaMs)
}
if params.Evidence.MaxAgeNumBlocks <= 0 {
return fmt.Errorf("evidence.MaxAgeNumBlocks must be greater than 0. Got %d",
params.Evidence.MaxAgeNumBlocks)
@@ -134,7 +170,7 @@ func ValidateConsensusParams(params tmproto.ConsensusParams) error {
// Only the Block.MaxBytes and Block.MaxGas are included in the hash.
// This allows the ConsensusParams to evolve more without breaking the block
// protocol. No need for a Merkle tree here, just a small struct to hash.
func HashConsensusParams(params tmproto.ConsensusParams) []byte {
func (params ConsensusParams) Hash() []byte {
hasher := tmhash.New()
hp := tmproto.HashedParams{
@@ -156,7 +192,7 @@ func HashConsensusParams(params tmproto.ConsensusParams) []byte {
// Update returns a copy of the params with updates from the non-zero fields of p2.
// NOTE: note: must not modify the original
func UpdateConsensusParams(params tmproto.ConsensusParams, params2 *abci.ConsensusParams) tmproto.ConsensusParams {
func (params ConsensusParams) Update(params2 *tmproto.ConsensusParams) ConsensusParams {
res := params // explicit copy
if params2 == nil {
@@ -179,7 +215,47 @@ func UpdateConsensusParams(params tmproto.ConsensusParams, params2 *abci.Consens
res.Validator.PubKeyTypes = append([]string{}, params2.Validator.PubKeyTypes...)
}
if params2.Version != nil {
res.Version.AppVersion = params2.Version.AppVersion
res.Version.App = params2.Version.App
}
return res
}
func (params *ConsensusParams) ToProto() tmproto.ConsensusParams {
return tmproto.ConsensusParams{
Block: &tmproto.BlockParams{
MaxBytes: params.Block.MaxBytes,
MaxGas: params.Block.MaxGas,
},
Evidence: &tmproto.EvidenceParams{
MaxAgeNumBlocks: params.Evidence.MaxAgeNumBlocks,
MaxAgeDuration: params.Evidence.MaxAgeDuration,
MaxBytes: params.Evidence.MaxBytes,
},
Validator: &tmproto.ValidatorParams{
PubKeyTypes: params.Validator.PubKeyTypes,
},
Version: &tmproto.VersionParams{
App: params.Version.App,
},
}
}
func ConsensusParamsFromProto(pbParams tmproto.ConsensusParams) ConsensusParams {
return ConsensusParams{
Block: BlockParams{
MaxBytes: pbParams.Block.MaxBytes,
MaxGas: pbParams.Block.MaxGas,
},
Evidence: EvidenceParams{
MaxAgeNumBlocks: pbParams.Evidence.MaxAgeNumBlocks,
MaxAgeDuration: pbParams.Evidence.MaxAgeDuration,
MaxBytes: pbParams.Evidence.MaxBytes,
},
Validator: ValidatorParams{
PubKeyTypes: pbParams.Validator.PubKeyTypes,
},
Version: VersionParams{
App: pbParams.Version.App,
},
}
}
+72 -54
View File
@@ -8,7 +8,6 @@ import (
"github.com/stretchr/testify/assert"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
@@ -19,77 +18,73 @@ var (
func TestConsensusParamsValidation(t *testing.T) {
testCases := []struct {
params tmproto.ConsensusParams
params ConsensusParams
valid bool
}{
// test block params
0: {makeParams(1, 0, 10, 2, 0, valEd25519), true},
1: {makeParams(0, 0, 10, 2, 0, valEd25519), false},
2: {makeParams(47*1024*1024, 0, 10, 2, 0, valEd25519), true},
3: {makeParams(10, 0, 10, 2, 0, valEd25519), true},
4: {makeParams(100*1024*1024, 0, 10, 2, 0, valEd25519), true},
5: {makeParams(101*1024*1024, 0, 10, 2, 0, valEd25519), false},
6: {makeParams(1024*1024*1024, 0, 10, 2, 0, valEd25519), false},
7: {makeParams(1024*1024*1024, 0, 10, -1, 0, valEd25519), false},
8: {makeParams(1, 0, -10, 2, 0, valEd25519), false},
0: {makeParams(1, 0, 2, 0, valEd25519), true},
1: {makeParams(0, 0, 2, 0, valEd25519), false},
2: {makeParams(47*1024*1024, 0, 2, 0, valEd25519), true},
3: {makeParams(10, 0, 2, 0, valEd25519), true},
4: {makeParams(100*1024*1024, 0, 2, 0, valEd25519), true},
5: {makeParams(101*1024*1024, 0, 2, 0, valEd25519), false},
6: {makeParams(1024*1024*1024, 0, 2, 0, valEd25519), false},
// test evidence params
9: {makeParams(1, 0, 10, 0, 0, valEd25519), false},
10: {makeParams(1, 0, 10, 2, 2, valEd25519), false},
11: {makeParams(1000, 0, 10, 2, 1, valEd25519), true},
12: {makeParams(1, 0, 10, -1, 0, valEd25519), false},
7: {makeParams(1, 0, 0, 0, valEd25519), false},
8: {makeParams(1, 0, 2, 2, valEd25519), false},
9: {makeParams(1000, 0, 2, 1, valEd25519), true},
10: {makeParams(1, 0, -1, 0, valEd25519), false},
// test no pubkey type provided
13: {makeParams(1, 0, 10, 2, 0, []string{}), false},
11: {makeParams(1, 0, 2, 0, []string{}), false},
// test invalid pubkey type provided
14: {makeParams(1, 0, 10, 2, 0, []string{"potatoes make good pubkeys"}), false},
12: {makeParams(1, 0, 2, 0, []string{"potatoes make good pubkeys"}), false},
}
for i, tc := range testCases {
if tc.valid {
assert.NoErrorf(t, ValidateConsensusParams(tc.params), "expected no error for valid params (#%d)", i)
assert.NoErrorf(t, tc.params.ValidateBasic(), "expected no error for valid params (#%d)", i)
} else {
assert.Errorf(t, ValidateConsensusParams(tc.params), "expected error for non valid params (#%d)", i)
assert.Errorf(t, tc.params.ValidateBasic(), "expected error for non valid params (#%d)", i)
}
}
}
func makeParams(
blockBytes, blockGas int64,
blockTimeIotaMs int64,
evidenceAge int64,
maxEvidenceBytes int64,
pubkeyTypes []string,
) tmproto.ConsensusParams {
return tmproto.ConsensusParams{
Block: tmproto.BlockParams{
MaxBytes: blockBytes,
MaxGas: blockGas,
TimeIotaMs: blockTimeIotaMs,
) ConsensusParams {
return ConsensusParams{
Block: BlockParams{
MaxBytes: blockBytes,
MaxGas: blockGas,
},
Evidence: tmproto.EvidenceParams{
Evidence: EvidenceParams{
MaxAgeNumBlocks: evidenceAge,
MaxAgeDuration: time.Duration(evidenceAge),
MaxBytes: maxEvidenceBytes,
},
Validator: tmproto.ValidatorParams{
Validator: ValidatorParams{
PubKeyTypes: pubkeyTypes,
},
}
}
func TestConsensusParamsHash(t *testing.T) {
params := []tmproto.ConsensusParams{
makeParams(4, 2, 10, 3, 1, valEd25519),
makeParams(1, 4, 10, 3, 1, valEd25519),
makeParams(1, 2, 10, 4, 1, valEd25519),
makeParams(2, 5, 10, 7, 1, valEd25519),
makeParams(1, 7, 10, 6, 1, valEd25519),
makeParams(9, 5, 10, 4, 1, valEd25519),
makeParams(7, 8, 10, 9, 1, valEd25519),
makeParams(4, 6, 10, 5, 1, valEd25519),
params := []ConsensusParams{
makeParams(4, 2, 3, 1, valEd25519),
makeParams(1, 4, 3, 1, valEd25519),
makeParams(1, 2, 4, 1, valEd25519),
makeParams(2, 5, 7, 1, valEd25519),
makeParams(1, 7, 6, 1, valEd25519),
makeParams(9, 5, 4, 1, valEd25519),
makeParams(7, 8, 9, 1, valEd25519),
makeParams(4, 6, 5, 1, valEd25519),
}
hashes := make([][]byte, len(params))
for i := range params {
hashes[i] = HashConsensusParams(params[i])
hashes[i] = params[i].Hash()
}
// make sure there are no duplicates...
@@ -104,21 +99,21 @@ func TestConsensusParamsHash(t *testing.T) {
func TestConsensusParamsUpdate(t *testing.T) {
testCases := []struct {
params tmproto.ConsensusParams
updates *abci.ConsensusParams
updatedParams tmproto.ConsensusParams
params ConsensusParams
updates *tmproto.ConsensusParams
updatedParams ConsensusParams
}{
// empty updates
{
makeParams(1, 2, 10, 3, 0, valEd25519),
&abci.ConsensusParams{},
makeParams(1, 2, 10, 3, 0, valEd25519),
makeParams(1, 2, 3, 0, valEd25519),
&tmproto.ConsensusParams{},
makeParams(1, 2, 3, 0, valEd25519),
},
// fine updates
{
makeParams(1, 2, 10, 3, 0, valEd25519),
&abci.ConsensusParams{
Block: &abci.BlockParams{
makeParams(1, 2, 3, 0, valEd25519),
&tmproto.ConsensusParams{
Block: &tmproto.BlockParams{
MaxBytes: 100,
MaxGas: 200,
},
@@ -131,21 +126,44 @@ func TestConsensusParamsUpdate(t *testing.T) {
PubKeyTypes: valSecp256k1,
},
},
makeParams(100, 200, 10, 300, 50, valSecp256k1),
makeParams(100, 200, 300, 50, valSecp256k1),
},
}
for _, tc := range testCases {
assert.Equal(t, tc.updatedParams, UpdateConsensusParams(tc.params, tc.updates))
assert.Equal(t, tc.updatedParams, tc.params.Update(tc.updates))
}
}
func TestConsensusParamsUpdate_AppVersion(t *testing.T) {
params := makeParams(1, 2, 10, 3, 0, valEd25519)
params := makeParams(1, 2, 3, 0, valEd25519)
assert.EqualValues(t, 0, params.Version.AppVersion)
assert.EqualValues(t, 0, params.Version.App)
updated := UpdateConsensusParams(params,
&abci.ConsensusParams{Version: &tmproto.VersionParams{AppVersion: 1}})
updated := params.Update(
&tmproto.ConsensusParams{Version: &tmproto.VersionParams{App: 1}})
assert.EqualValues(t, 1, updated.Version.AppVersion)
assert.EqualValues(t, 1, updated.Version.App)
}
func TestProto(t *testing.T) {
params := []ConsensusParams{
makeParams(4, 2, 3, 1, valEd25519),
makeParams(1, 4, 3, 1, valEd25519),
makeParams(1, 2, 4, 1, valEd25519),
makeParams(2, 5, 7, 1, valEd25519),
makeParams(1, 7, 6, 1, valEd25519),
makeParams(9, 5, 4, 1, valEd25519),
makeParams(7, 8, 9, 1, valEd25519),
makeParams(4, 6, 5, 1, valEd25519),
}
for i := range params {
pbParams := params[i].ToProto()
oriParams := ConsensusParamsFromProto(pbParams)
assert.Equal(t, params[i], oriParams)
}
}
-28
View File
@@ -3,27 +3,10 @@ package types
import (
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/crypto/secp256k1"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
//-------------------------------------------------------
// Use strings to distinguish types in ABCI messages
const (
ABCIPubKeyTypeEd25519 = ed25519.KeyType
ABCIPubKeyTypeSecp256k1 = secp256k1.KeyType
)
// TODO: Make non-global by allowing for registration of more pubkey types
var ABCIPubKeyTypesToNames = map[string]string{
ABCIPubKeyTypeEd25519: ed25519.PubKeyName,
ABCIPubKeyTypeSecp256k1: secp256k1.PubKeyName,
}
//-------------------------------------------------------
// TM2PB is used for converting Tendermint ABCI to protobuf ABCI.
@@ -97,17 +80,6 @@ func (tm2pb) ValidatorUpdates(vals *ValidatorSet) []abci.ValidatorUpdate {
return validators
}
func (tm2pb) ConsensusParams(params *tmproto.ConsensusParams) *abci.ConsensusParams {
return &abci.ConsensusParams{
Block: &abci.BlockParams{
MaxBytes: params.Block.MaxBytes,
MaxGas: params.Block.MaxGas,
},
Evidence: &params.Evidence,
Validator: &params.Validator,
}
}
// XXX: panics on nil or unknown pubkey type
func (tm2pb) NewValidatorUpdate(pubkey crypto.PubKey, power int64) abci.ValidatorUpdate {
pubkeyABCI, err := cryptoenc.PubKeyToProto(pubkey)
-8
View File
@@ -52,14 +52,6 @@ func TestABCIValidators(t *testing.T) {
assert.Equal(t, tmValExpected, tmVals[0])
}
func TestABCIConsensusParams(t *testing.T) {
cp := DefaultConsensusParams()
abciCP := TM2PB.ConsensusParams(cp)
cp2 := UpdateConsensusParams(*cp, abciCP)
assert.Equal(t, *cp, cp2)
}
type pubKeyEddie struct{}
func (pubKeyEddie) Address() Address { return []byte{} }
+48 -16
View File
@@ -45,13 +45,8 @@ type Txs []Tx
// Hash returns the Merkle root hash of the transaction hashes.
// i.e. the leaves of the tree are the hashes of the txs.
func (txs Txs) Hash() []byte {
// These allocations will be removed once Txs is switched to [][]byte,
// ref #2603. This is because golang does not allow type casting slices without unsafe
txBzs := make([][]byte, len(txs))
for i := 0; i < len(txs); i++ {
txBzs[i] = txs[i].Hash()
}
return merkle.HashFromByteSlices(txBzs)
hl := txs.hashList()
return merkle.HashFromByteSlices(hl)
}
// Index returns the index of this transaction in the list, or -1 if not found
@@ -74,16 +69,9 @@ func (txs Txs) IndexByHash(hash []byte) int {
return -1
}
// Proof returns a simple merkle proof for this node.
// Panics if i < 0 or i >= len(txs)
// TODO: optimize this!
func (txs Txs) Proof(i int) TxProof {
l := len(txs)
bzs := make([][]byte, l)
for i := 0; i < l; i++ {
bzs[i] = txs[i].Hash()
}
root, proofs := merkle.ProofsFromByteSlices(bzs)
hl := txs.hashList()
root, proofs := merkle.ProofsFromByteSlices(hl)
return TxProof{
RootHash: root,
@@ -92,6 +80,50 @@ func (txs Txs) Proof(i int) TxProof {
}
}
func (txs Txs) hashList() [][]byte {
hl := make([][]byte, len(txs))
for i := 0; i < len(txs); i++ {
hl[i] = txs[i].Hash()
}
return hl
}
// Txs is a slice of transactions. Sorting a Txs value orders the transactions
// lexicographically.
func (txs Txs) Len() int { return len(txs) }
func (txs Txs) Swap(i, j int) { txs[i], txs[j] = txs[j], txs[i] }
func (txs Txs) Less(i, j int) bool {
return bytes.Compare(txs[i], txs[j]) == -1
}
func ToTxs(txl [][]byte) Txs {
txs := make([]Tx, 0, len(txl))
for _, tx := range txl {
txs = append(txs, tx)
}
return txs
}
func (txs Txs) Validate(maxSizeBytes int64) error {
var size int64
for _, tx := range txs {
size += int64(len(tx))
if size > maxSizeBytes {
return fmt.Errorf("transaction data size exceeds maximum %d", maxSizeBytes)
}
}
return nil
}
// ToSliceOfBytes converts a Txs to slice of byte slices.
func (txs Txs) ToSliceOfBytes() [][]byte {
txBzs := make([][]byte, len(txs))
for i := 0; i < len(txs); i++ {
txBzs[i] = txs[i]
}
return txBzs
}
// TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree.
type TxProof struct {
RootHash tmbytes.HexBytes `json:"root_hash"`
+5 -5
View File
@@ -2,6 +2,7 @@ package types
import (
"bytes"
"math/rand"
"testing"
"github.com/stretchr/testify/assert"
@@ -20,11 +21,6 @@ func makeTxs(cnt, size int) Txs {
return txs
}
func randInt(low, high int) int {
off := tmrand.Int() % (high - low)
return low + off
}
func TestTxIndex(t *testing.T) {
for i := 0; i < 20; i++ {
txs := makeTxs(15, 60)
@@ -149,3 +145,7 @@ func assertBadProof(t *testing.T, root []byte, bad []byte, good TxProof) {
}
}
}
func randInt(low, high int) int {
return rand.Intn(high-low) + low
}
+16
View File
@@ -220,6 +220,22 @@ func (vote *Vote) ToProto() *tmproto.Vote {
}
}
func VotesToProto(votes []*Vote) []*tmproto.Vote {
if votes == nil {
return nil
}
res := make([]*tmproto.Vote, 0, len(votes))
for _, vote := range votes {
v := vote.ToProto()
// protobuf crashes when serializing "repeated" fields with nil elements
if v != nil {
res = append(res, v)
}
}
return res
}
// FromProto converts a proto generetad type to a handwritten type
// return type, nil if everything converts safely, otherwise nil, error
func VoteFromProto(pv *tmproto.Vote) (*Vote, error) {
+8
View File
@@ -226,6 +226,13 @@ func (voteSet *VoteSet) getVote(valIndex int32, blockKey string) (vote *Vote, ok
return nil, false
}
func (voteSet *VoteSet) GetVotes() []*Vote {
if voteSet == nil {
return nil
}
return voteSet.votes
}
// Assumes signature is valid.
// If conflicting vote exists, returns it.
func (voteSet *VoteSet) addVerifiedVote(
@@ -627,6 +634,7 @@ func (voteSet *VoteSet) MakeCommit() *Commit {
if commitSig.ForBlock() && !v.BlockID.Equals(*voteSet.maj23) {
commitSig = NewCommitSigAbsent()
}
commitSigs[i] = commitSig
}