-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge PR #2720: x/mock/simulation cleanup and re-org
- Loading branch information
Showing
15 changed files
with
935 additions
and
740 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package simulation | ||
|
||
import ( | ||
"math/rand" | ||
|
||
"github.com/tendermint/tendermint/crypto" | ||
"github.com/tendermint/tendermint/crypto/ed25519" | ||
"github.com/tendermint/tendermint/crypto/secp256k1" | ||
|
||
sdk "github.com/cosmos/cosmos-sdk/types" | ||
) | ||
|
||
// Account contains a privkey, pubkey, address tuple | ||
// eventually more useful data can be placed in here. | ||
// (e.g. number of coins) | ||
type Account struct { | ||
PrivKey crypto.PrivKey | ||
PubKey crypto.PubKey | ||
Address sdk.AccAddress | ||
} | ||
|
||
// are two accounts equal | ||
func (acc Account) Equals(acc2 Account) bool { | ||
return acc.Address.Equals(acc2.Address) | ||
} | ||
|
||
// RandomAcc pick a random account from an array | ||
func RandomAcc(r *rand.Rand, accs []Account) Account { | ||
return accs[r.Intn( | ||
len(accs), | ||
)] | ||
} | ||
|
||
// RandomAccounts generates n random accounts | ||
func RandomAccounts(r *rand.Rand, n int) []Account { | ||
accs := make([]Account, n) | ||
for i := 0; i < n; i++ { | ||
// don't need that much entropy for simulation | ||
privkeySeed := make([]byte, 15) | ||
r.Read(privkeySeed) | ||
useSecp := r.Int63()%2 == 0 | ||
if useSecp { | ||
accs[i].PrivKey = secp256k1.GenPrivKeySecp256k1(privkeySeed) | ||
} else { | ||
accs[i].PrivKey = ed25519.GenPrivKeyFromSecret(privkeySeed) | ||
} | ||
accs[i].PubKey = accs[i].PrivKey.PubKey() | ||
accs[i].Address = sdk.AccAddress(accs[i].PubKey.Address()) | ||
} | ||
return accs | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package simulation | ||
|
||
import ( | ||
"fmt" | ||
"sort" | ||
) | ||
|
||
type eventStats map[string]uint | ||
|
||
func newEventStats() eventStats { | ||
events := make(map[string]uint) | ||
return events | ||
} | ||
|
||
func (es eventStats) tally(eventDesc string) { | ||
es[eventDesc]++ | ||
} | ||
|
||
// Pretty-print events as a table | ||
func (es eventStats) Print() { | ||
var keys []string | ||
for key := range es { | ||
keys = append(keys, key) | ||
} | ||
sort.Strings(keys) | ||
fmt.Printf("Event statistics: \n") | ||
for _, key := range keys { | ||
fmt.Printf(" % 60s => %d\n", key, es[key]) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package simulation | ||
|
||
import ( | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/cosmos/cosmos-sdk/baseapp" | ||
) | ||
|
||
// An Invariant is a function which tests a particular invariant. | ||
// If the invariant has been broken, it should return an error | ||
// containing a descriptive message about what happened. | ||
// The simulator will then halt and print the logs. | ||
type Invariant func(app *baseapp.BaseApp) error | ||
|
||
// group of Invarient | ||
type Invariants []Invariant | ||
|
||
// assertAll asserts the all invariants against application state | ||
func (invs Invariants) assertAll(t *testing.T, app *baseapp.BaseApp, | ||
event string, displayLogs func()) { | ||
|
||
for i := 0; i < len(invs); i++ { | ||
if err := invs[i](app); err != nil { | ||
fmt.Printf("Invariants broken after %s\n%s\n", event, err.Error()) | ||
displayLogs() | ||
t.Fatal() | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,201 @@ | ||
package simulation | ||
|
||
import ( | ||
"fmt" | ||
"math/rand" | ||
"sort" | ||
"testing" | ||
"time" | ||
|
||
abci "github.com/tendermint/tendermint/abci/types" | ||
cmn "github.com/tendermint/tendermint/libs/common" | ||
tmtypes "github.com/tendermint/tendermint/types" | ||
) | ||
|
||
type mockValidator struct { | ||
val abci.ValidatorUpdate | ||
livenessState int | ||
} | ||
|
||
type mockValidators map[string]mockValidator | ||
|
||
// get mockValidators from abci validators | ||
func newMockValidators(r *rand.Rand, abciVals []abci.ValidatorUpdate, | ||
params Params) mockValidators { | ||
|
||
validators := make(mockValidators) | ||
for _, validator := range abciVals { | ||
str := fmt.Sprintf("%v", validator.PubKey) | ||
liveliness := GetMemberOfInitialState(r, | ||
params.InitialLivenessWeightings) | ||
|
||
validators[str] = mockValidator{ | ||
val: validator, | ||
livenessState: liveliness, | ||
} | ||
} | ||
|
||
return validators | ||
} | ||
|
||
// TODO describe usage | ||
func (vals mockValidators) getKeys() []string { | ||
keys := make([]string, len(vals)) | ||
i := 0 | ||
for key := range vals { | ||
keys[i] = key | ||
i++ | ||
} | ||
sort.Strings(keys) | ||
return keys | ||
} | ||
|
||
//_________________________________________________________________________________ | ||
|
||
// randomProposer picks a random proposer from the current validator set | ||
func (vals mockValidators) randomProposer(r *rand.Rand) cmn.HexBytes { | ||
keys := vals.getKeys() | ||
if len(keys) == 0 { | ||
return nil | ||
} | ||
key := keys[r.Intn(len(keys))] | ||
proposer := vals[key].val | ||
pk, err := tmtypes.PB2TM.PubKey(proposer.PubKey) | ||
if err != nil { | ||
panic(err) | ||
} | ||
return pk.Address() | ||
} | ||
|
||
// updateValidators mimicks Tendermint's update logic | ||
// nolint: unparam | ||
func updateValidators(tb testing.TB, r *rand.Rand, params Params, | ||
current map[string]mockValidator, updates []abci.ValidatorUpdate, | ||
event func(string)) map[string]mockValidator { | ||
|
||
for _, update := range updates { | ||
str := fmt.Sprintf("%v", update.PubKey) | ||
|
||
if update.Power == 0 { | ||
if _, ok := current[str]; !ok { | ||
tb.Fatalf("tried to delete a nonexistent validator") | ||
} | ||
event("endblock/validatorupdates/kicked") | ||
delete(current, str) | ||
|
||
} else if mVal, ok := current[str]; ok { | ||
// validator already exists | ||
mVal.val = update | ||
event("endblock/validatorupdates/updated") | ||
|
||
} else { | ||
// Set this new validator | ||
current[str] = mockValidator{ | ||
update, | ||
GetMemberOfInitialState(r, params.InitialLivenessWeightings), | ||
} | ||
event("endblock/validatorupdates/added") | ||
} | ||
} | ||
|
||
return current | ||
} | ||
|
||
// RandomRequestBeginBlock generates a list of signing validators according to | ||
// the provided list of validators, signing fraction, and evidence fraction | ||
func RandomRequestBeginBlock(r *rand.Rand, params Params, | ||
validators mockValidators, pastTimes []time.Time, | ||
pastVoteInfos [][]abci.VoteInfo, | ||
event func(string), header abci.Header) abci.RequestBeginBlock { | ||
|
||
if len(validators) == 0 { | ||
return abci.RequestBeginBlock{ | ||
Header: header, | ||
} | ||
} | ||
|
||
voteInfos := make([]abci.VoteInfo, len(validators)) | ||
for i, key := range validators.getKeys() { | ||
mVal := validators[key] | ||
mVal.livenessState = params.LivenessTransitionMatrix.NextState(r, mVal.livenessState) | ||
signed := true | ||
|
||
if mVal.livenessState == 1 { | ||
// spotty connection, 50% probability of success | ||
// See https://github.com/golang/go/issues/23804#issuecomment-365370418 | ||
// for reasoning behind computing like this | ||
signed = r.Int63()%2 == 0 | ||
} else if mVal.livenessState == 2 { | ||
// offline | ||
signed = false | ||
} | ||
|
||
if signed { | ||
event("beginblock/signing/signed") | ||
} else { | ||
event("beginblock/signing/missed") | ||
} | ||
|
||
pubkey, err := tmtypes.PB2TM.PubKey(mVal.val.PubKey) | ||
if err != nil { | ||
panic(err) | ||
} | ||
voteInfos[i] = abci.VoteInfo{ | ||
Validator: abci.Validator{ | ||
Address: pubkey.Address(), | ||
Power: mVal.val.Power, | ||
}, | ||
SignedLastBlock: signed, | ||
} | ||
} | ||
|
||
// return if no past times | ||
if len(pastTimes) <= 0 { | ||
return abci.RequestBeginBlock{ | ||
Header: header, | ||
LastCommitInfo: abci.LastCommitInfo{ | ||
Votes: voteInfos, | ||
}, | ||
} | ||
} | ||
|
||
// TODO: Determine capacity before allocation | ||
evidence := make([]abci.Evidence, 0) | ||
for r.Float64() < params.EvidenceFraction { | ||
|
||
height := header.Height | ||
time := header.Time | ||
vals := voteInfos | ||
|
||
if r.Float64() < params.PastEvidenceFraction { | ||
height = int64(r.Intn(int(header.Height) - 1)) | ||
time = pastTimes[height] | ||
vals = pastVoteInfos[height] | ||
} | ||
validator := vals[r.Intn(len(vals))].Validator | ||
|
||
var totalVotingPower int64 | ||
for _, val := range vals { | ||
totalVotingPower += val.Validator.Power | ||
} | ||
|
||
evidence = append(evidence, | ||
abci.Evidence{ | ||
Type: tmtypes.ABCIEvidenceTypeDuplicateVote, | ||
Validator: validator, | ||
Height: height, | ||
Time: time, | ||
TotalVotingPower: totalVotingPower, | ||
}, | ||
) | ||
event("beginblock/evidence") | ||
} | ||
|
||
return abci.RequestBeginBlock{ | ||
Header: header, | ||
LastCommitInfo: abci.LastCommitInfo{ | ||
Votes: voteInfos, | ||
}, | ||
ByzantineValidators: evidence, | ||
} | ||
} |
Oops, something went wrong.