mirror of
https://github.com/tendermint/tendermint.git
synced 2026-07-08 09:06:52 +00:00
chore: Format and fix lints (#9336)
* make format Signed-off-by: Thane Thomson <connect@thanethomson.com> * Fix linting directives Signed-off-by: Thane Thomson <connect@thanethomson.com> * make mockery Signed-off-by: Thane Thomson <connect@thanethomson.com> * Appease CI linter Signed-off-by: Thane Thomson <connect@thanethomson.com> * Appease CI linter Signed-off-by: Thane Thomson <connect@thanethomson.com> Signed-off-by: Thane Thomson <connect@thanethomson.com>
This commit is contained in:
@@ -162,7 +162,7 @@ func TestValUpdates(t *testing.T) {
|
||||
|
||||
makeApplyBlock(t, kvstore, 2, diff, tx1, tx2, tx3)
|
||||
|
||||
vals1 = append(vals[:nInit-2], vals[nInit+1]) // nolint: gocritic
|
||||
vals1 = append(vals[:nInit-2], vals[nInit+1]) //nolint: gocritic
|
||||
vals2 = kvstore.Validators()
|
||||
valsEqual(t, vals1, vals2)
|
||||
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
Package server is used to start a new ABCI server.
|
||||
|
||||
It contains two server implementation:
|
||||
* gRPC server
|
||||
* socket server
|
||||
|
||||
- gRPC server
|
||||
- socket server
|
||||
*/
|
||||
package server
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"io"
|
||||
|
||||
"github.com/gogo/protobuf/proto"
|
||||
|
||||
"github.com/tendermint/tendermint/libs/protoio"
|
||||
)
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ func TestBcStatusResponseMessageValidateBasic(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:lll // ignore line length in tests
|
||||
//nolint:lll // ignore line length in tests
|
||||
func TestBlockchainMessageVectors(t *testing.T) {
|
||||
block := types.MakeBlock(int64(3), []types.Tx{types.Tx("Hello World")}, nil, nil)
|
||||
block.Version.Block = 11 // overwrite updated protocol version
|
||||
|
||||
@@ -410,6 +410,7 @@ func (pool *BlockPool) sendError(err error, peerID p2p.ID) {
|
||||
}
|
||||
|
||||
// for debugging purposes
|
||||
//
|
||||
//nolint:unused
|
||||
func (pool *BlockPool) debug() string {
|
||||
pool.mtx.Lock()
|
||||
|
||||
@@ -303,7 +303,7 @@ func (bcR *Reactor) poolRoutine(stateSynced bool) {
|
||||
|
||||
case <-statusUpdateTicker.C:
|
||||
// ask for status updates
|
||||
go bcR.BroadcastStatusRequest() // nolint: errcheck
|
||||
go bcR.BroadcastStatusRequest() //nolint: errcheck
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ func killProc(pid uint64, dir string) error {
|
||||
// pipe STDERR output from tailing the Tendermint process to a file
|
||||
//
|
||||
// NOTE: This will only work on UNIX systems.
|
||||
cmd := exec.Command("tail", "-f", fmt.Sprintf("/proc/%d/fd/2", pid)) // nolint: gosec
|
||||
cmd := exec.Command("tail", "-f", fmt.Sprintf("/proc/%d/fd/2", pid)) //nolint: gosec
|
||||
|
||||
outFile, err := os.Create(filepath.Join(dir, "stacktrace.out"))
|
||||
if err != nil {
|
||||
|
||||
@@ -67,7 +67,7 @@ func copyConfig(home, dir string) error {
|
||||
func dumpProfile(dir, addr, profile string, debug int) error {
|
||||
endpoint := fmt.Sprintf("%s/debug/pprof/%s?debug=%d", addr, profile, debug)
|
||||
|
||||
resp, err := http.Get(endpoint) // nolint: gosec
|
||||
resp, err := http.Get(endpoint) //nolint: gosec
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to query for %s profile: %w", profile, err)
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ func TestBlockSyncConfigValidateBasic(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestConsensusConfig_ValidateBasic(t *testing.T) {
|
||||
// nolint: lll
|
||||
//nolint: lll
|
||||
testcases := map[string]struct {
|
||||
modify func(*ConsensusConfig)
|
||||
expectErr bool
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/go-kit/kit/metrics"
|
||||
|
||||
cstypes "github.com/tendermint/tendermint/consensus/types"
|
||||
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
|
||||
"github.com/tendermint/tendermint/types"
|
||||
|
||||
@@ -314,7 +314,7 @@ func TestWALMsgProto(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:lll //ignore line length for tests
|
||||
//nolint:lll //ignore line length for tests
|
||||
func TestConsMsgsVectors(t *testing.T) {
|
||||
date := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC)
|
||||
psh := types.PartSetHeader{
|
||||
|
||||
@@ -692,7 +692,7 @@ func capture() {
|
||||
// Ensure basic validation of structs is functioning
|
||||
|
||||
func TestNewRoundStepMessageValidateBasic(t *testing.T) {
|
||||
testCases := []struct { // nolint: maligned
|
||||
testCases := []struct { //nolint: maligned
|
||||
expectErr bool
|
||||
messageRound int32
|
||||
messageLastCommitRound int32
|
||||
@@ -731,7 +731,7 @@ func TestNewRoundStepMessageValidateBasic(t *testing.T) {
|
||||
|
||||
func TestNewRoundStepMessageValidateHeight(t *testing.T) {
|
||||
initialHeight := int64(10)
|
||||
testCases := []struct { // nolint: maligned
|
||||
testCases := []struct { //nolint: maligned
|
||||
expectErr bool
|
||||
messageLastCommitRound int32
|
||||
messageHeight int64
|
||||
@@ -881,7 +881,7 @@ func TestHasVoteMessageValidateBasic(t *testing.T) {
|
||||
invalidSignedMsgType tmproto.SignedMsgType = 0x03
|
||||
)
|
||||
|
||||
testCases := []struct { // nolint: maligned
|
||||
testCases := []struct { //nolint: maligned
|
||||
expectErr bool
|
||||
messageRound int32
|
||||
messageIndex int32
|
||||
@@ -926,7 +926,7 @@ func TestVoteSetMaj23MessageValidateBasic(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
testCases := []struct { // nolint: maligned
|
||||
testCases := []struct { //nolint: maligned
|
||||
expectErr bool
|
||||
messageRound int32
|
||||
messageHeight int64
|
||||
|
||||
@@ -292,7 +292,7 @@ func (w *crashingWAL) Start() error { return w.next.Start() }
|
||||
func (w *crashingWAL) Stop() error { return w.next.Stop() }
|
||||
func (w *crashingWAL) Wait() { w.next.Wait() }
|
||||
|
||||
//------------------------------------------------------------------------------------------
|
||||
// ------------------------------------------------------------------------------------------
|
||||
type testSim struct {
|
||||
GenesisState sm.State
|
||||
Config *cfg.Config
|
||||
|
||||
+1
-1
@@ -2006,7 +2006,7 @@ func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {
|
||||
// If the vote height is off, we'll just ignore it,
|
||||
// But if it's a conflicting sig, add it to the cs.evpool.
|
||||
// If it's otherwise invalid, punish peer.
|
||||
// nolint: gocritic
|
||||
//nolint: gocritic
|
||||
if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
|
||||
if cs.privValidatorPubKey == nil {
|
||||
return false, errPubKeyIsNotSet
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"golang.org/x/crypto/openpgp/armor" // nolint: staticcheck
|
||||
"golang.org/x/crypto/openpgp/armor" //nolint: staticcheck
|
||||
)
|
||||
|
||||
func EncodeArmor(blockType string, headers map[string]string, data []byte) string {
|
||||
|
||||
+12
-13
@@ -12,20 +12,19 @@ second pre-image attacks. Hence, use this library with caution.
|
||||
Otherwise you might run into similar issues as, e.g., in early Bitcoin:
|
||||
https://bitcointalk.org/?topic=102395
|
||||
|
||||
*
|
||||
/ \
|
||||
/ \
|
||||
/ \
|
||||
/ \
|
||||
* *
|
||||
/ \ / \
|
||||
/ \ / \
|
||||
/ \ / \
|
||||
* * * h6
|
||||
/ \ / \ / \
|
||||
h0 h1 h2 h3 h4 h5
|
||||
*
|
||||
/ \
|
||||
/ \
|
||||
/ \
|
||||
/ \
|
||||
* *
|
||||
/ \ / \
|
||||
/ \ / \
|
||||
/ \ / \
|
||||
* * * h6
|
||||
/ \ / \ / \
|
||||
h0 h1 h2 h3 h4 h5
|
||||
|
||||
TODO(ismail): add 2nd pre-image protection or clarify further on how we use this and why this secure.
|
||||
|
||||
*/
|
||||
package merkle
|
||||
|
||||
@@ -85,8 +85,8 @@ func (op ValueOp) Run(args [][]byte) ([][]byte, error) {
|
||||
|
||||
bz := new(bytes.Buffer)
|
||||
// Wrap <op.Key, vhash> to hash the KVPair.
|
||||
encodeByteSlice(bz, op.key) // nolint: errcheck // does not error
|
||||
encodeByteSlice(bz, vhash) // nolint: errcheck // does not error
|
||||
encodeByteSlice(bz, op.key) //nolint: errcheck // does not error
|
||||
encodeByteSlice(bz, vhash) //nolint: errcheck // does not error
|
||||
kvhash := leafHash(bz.Bytes())
|
||||
|
||||
if !bytes.Equal(kvhash, op.Proof.LeafHash) {
|
||||
|
||||
@@ -47,10 +47,10 @@ func HashFromByteSlices(items [][]byte) []byte {
|
||||
//
|
||||
// These preliminary results suggest:
|
||||
//
|
||||
// 1. The performance of the HashFromByteSlice is pretty good
|
||||
// 2. Go has low overhead for recursive functions
|
||||
// 3. The performance of the HashFromByteSlice routine is dominated
|
||||
// by the actual hashing of data
|
||||
// 1. The performance of the HashFromByteSlice is pretty good
|
||||
// 2. Go has low overhead for recursive functions
|
||||
// 3. The performance of the HashFromByteSlice routine is dominated
|
||||
// by the actual hashing of data
|
||||
//
|
||||
// Although this work is in no way exhaustive, point #3 suggests that
|
||||
// optimization of this routine would need to take an alternative
|
||||
|
||||
@@ -9,13 +9,13 @@ import (
|
||||
"math/big"
|
||||
|
||||
secp256k1 "github.com/btcsuite/btcd/btcec"
|
||||
"golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format
|
||||
"golang.org/x/crypto/ripemd160" //nolint: staticcheck // necessary for Bitcoin address format
|
||||
|
||||
"github.com/tendermint/tendermint/crypto"
|
||||
tmjson "github.com/tendermint/tendermint/libs/json"
|
||||
)
|
||||
|
||||
//-------------------------------------
|
||||
// -------------------------------------
|
||||
const (
|
||||
PrivKeyName = "tendermint/PrivKeySecp256k1"
|
||||
PubKeyName = "tendermint/PubKeySecp256k1"
|
||||
@@ -124,8 +124,8 @@ func GenPrivKeySecp256k1(secret []byte) PrivKey {
|
||||
|
||||
// used to reject malleable signatures
|
||||
// see:
|
||||
// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93
|
||||
// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39
|
||||
// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93
|
||||
// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39
|
||||
var secp256k1halfN = new(big.Int).Rsh(secp256k1.S256().N, 1)
|
||||
|
||||
// Sign creates an ECDSA signature on curve Secp256k1, using SHA256 on the msg.
|
||||
|
||||
+5
-5
@@ -97,11 +97,11 @@ func (evpool *Pool) PendingEvidence(maxBytes int64) ([]types.Evidence, int64) {
|
||||
|
||||
// Update takes both the new state and the evidence committed at that height and performs
|
||||
// the following operations:
|
||||
// 1. Take any conflicting votes from consensus and use the state's LastBlockTime to form
|
||||
// DuplicateVoteEvidence and add it to the pool.
|
||||
// 2. Update the pool's state which contains evidence params relating to expiry.
|
||||
// 3. Moves pending evidence that has now been committed into the committed pool.
|
||||
// 4. Removes any expired evidence based on both height and time.
|
||||
// 1. Take any conflicting votes from consensus and use the state's LastBlockTime to form
|
||||
// DuplicateVoteEvidence and add it to the pool.
|
||||
// 2. Update the pool's state which contains evidence params relating to expiry.
|
||||
// 3. Moves pending evidence that has now been committed into the committed pool.
|
||||
// 4. Removes any expired evidence based on both height and time.
|
||||
func (evpool *Pool) Update(state sm.State, ev types.EvidenceList) {
|
||||
// sanity check
|
||||
if state.LastBlockHeight <= evpool.state.LastBlockHeight {
|
||||
|
||||
@@ -369,7 +369,7 @@ func exampleVote(t byte) *types.Vote {
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:lll //ignore line length for tests
|
||||
//nolint:lll //ignore line length for tests
|
||||
func TestEvidenceVectors(t *testing.T) {
|
||||
|
||||
val := &types.Validator{
|
||||
|
||||
+10
-9
@@ -102,13 +102,14 @@ func (evpool *Pool) verify(evidence types.Evidence) error {
|
||||
|
||||
// VerifyLightClientAttack verifies LightClientAttackEvidence against the state of the full node. This involves
|
||||
// the following checks:
|
||||
// - the common header from the full node has at least 1/3 voting power which is also present in
|
||||
// the conflicting header's commit
|
||||
// - 2/3+ of the conflicting validator set correctly signed the conflicting block
|
||||
// - the nodes trusted header at the same height as the conflicting header has a different hash
|
||||
// - the common header from the full node has at least 1/3 voting power which is also present in
|
||||
// the conflicting header's commit
|
||||
// - 2/3+ of the conflicting validator set correctly signed the conflicting block
|
||||
// - the nodes trusted header at the same height as the conflicting header has a different hash
|
||||
//
|
||||
// CONTRACT: must run ValidateBasic() on the evidence before verifying
|
||||
// must check that the evidence has not expired (i.e. is outside the maximum age threshold)
|
||||
//
|
||||
// must check that the evidence has not expired (i.e. is outside the maximum age threshold)
|
||||
func VerifyLightClientAttack(e *types.LightClientAttackEvidence, commonHeader, trustedHeader *types.SignedHeader,
|
||||
commonVals *types.ValidatorSet, now time.Time, trustPeriod time.Duration) error {
|
||||
// In the case of lunatic attack there will be a different commonHeader height. Therefore the node perform a single
|
||||
@@ -154,10 +155,10 @@ func VerifyLightClientAttack(e *types.LightClientAttackEvidence, commonHeader, t
|
||||
|
||||
// VerifyDuplicateVote verifies DuplicateVoteEvidence against the state of full node. This involves the
|
||||
// following checks:
|
||||
// - the validator is in the validator set at the height of the evidence
|
||||
// - the height, round, type and validator address of the votes must be the same
|
||||
// - the block ID's must be different
|
||||
// - The signatures must both be valid
|
||||
// - the validator is in the validator set at the height of the evidence
|
||||
// - the height, round, type and validator address of the votes must be the same
|
||||
// - the block ID's must be different
|
||||
// - The signatures must both be valid
|
||||
func VerifyDuplicateVote(e *types.DuplicateVoteEvidence, chainID string, valSet *types.ValidatorSet) error {
|
||||
_, val := valSet.GetByAddress(e.VoteA.ValidatorAddress)
|
||||
if val == nil {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/tendermint/tendermint/types"
|
||||
)
|
||||
|
||||
|
||||
@@ -17,7 +17,8 @@ const (
|
||||
// all other modules).
|
||||
//
|
||||
// Example:
|
||||
// ParseLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout), "info")
|
||||
//
|
||||
// ParseLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout), "info")
|
||||
func ParseLogLevel(lvl string, logger log.Logger, defaultLogLevelValue string) (log.Logger, error) {
|
||||
if lvl == "" {
|
||||
return nil, errors.New("empty log level")
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
const MaxLength = int(^uint(0) >> 1)
|
||||
|
||||
/*
|
||||
|
||||
CElement is an element of a linked-list
|
||||
Traversal from a CElement is goroutine-safe.
|
||||
|
||||
@@ -41,7 +40,6 @@ the for-loop. Use sync.Cond when you need serial access to the
|
||||
"condition". In our case our condition is if `next != nil || removed`,
|
||||
and there's no reason to serialize that condition for goroutines
|
||||
waiting on NextWait() (since it's just a read operation).
|
||||
|
||||
*/
|
||||
type CElement struct {
|
||||
mtx tmsync.RWMutex
|
||||
|
||||
@@ -68,6 +68,7 @@ func TestSmall(t *testing.T) {
|
||||
|
||||
// This test is quite hacky because it relies on SetFinalizer
|
||||
// which isn't guaranteed to run at all.
|
||||
//
|
||||
//nolint:unused,deadcode
|
||||
func _TestGCFifo(t *testing.T) {
|
||||
if runtime.GOARCH != "amd64" {
|
||||
@@ -117,6 +118,7 @@ func _TestGCFifo(t *testing.T) {
|
||||
|
||||
// This test is quite hacky because it relies on SetFinalizer
|
||||
// which isn't guaranteed to run at all.
|
||||
//
|
||||
//nolint:unused,deadcode
|
||||
func _TestGCRandom(t *testing.T) {
|
||||
if runtime.GOARCH != "amd64" {
|
||||
|
||||
@@ -39,10 +39,10 @@ type Monitor struct {
|
||||
// weight of each sample in the exponential moving average (EMA) calculation.
|
||||
// The exact formulas are:
|
||||
//
|
||||
// sampleTime = currentTime - prevSampleTime
|
||||
// sampleRate = byteCount / sampleTime
|
||||
// weight = 1 - exp(-sampleTime/windowSize)
|
||||
// newRate = weight*sampleRate + (1-weight)*oldRate
|
||||
// sampleTime = currentTime - prevSampleTime
|
||||
// sampleRate = byteCount / sampleTime
|
||||
// weight = 1 - exp(-sampleTime/windowSize)
|
||||
// newRate = weight*sampleRate + (1-weight)*oldRate
|
||||
//
|
||||
// The default values for sampleRate and windowSize (if <= 0) are 100ms and 1s,
|
||||
// respectively.
|
||||
|
||||
+7
-8
@@ -13,12 +13,12 @@
|
||||
// compatibility with e.g. Javascript (which uses 64-bit floats for numbers, having 53-bit
|
||||
// precision):
|
||||
//
|
||||
// int32(32) // Output: 32
|
||||
// uint32(32) // Output: 32
|
||||
// int64(64) // Output: "64"
|
||||
// uint64(64) // Output: "64"
|
||||
// int(64) // Output: "64"
|
||||
// uint(64) // Output: "64"
|
||||
// int32(32) // Output: 32
|
||||
// uint32(32) // Output: 32
|
||||
// int64(64) // Output: "64"
|
||||
// uint64(64) // Output: "64"
|
||||
// int(64) // Output: "64"
|
||||
// uint(64) // Output: "64"
|
||||
//
|
||||
// Encoding of other scalars follows encoding/json:
|
||||
//
|
||||
@@ -50,7 +50,7 @@
|
||||
// Times are encoded as encoding/json, in RFC3339Nano format, but requiring UTC time zone (with zero
|
||||
// times emitted as "0001-01-01T00:00:00Z" as with encoding/json):
|
||||
//
|
||||
// time.Date(2020, 6, 8, 16, 21, 28, 123, time.FixedZone("UTC+2", 2*60*60))
|
||||
// time.Date(2020, 6, 8, 16, 21, 28, 123, time.FixedZone("UTC+2", 2*60*60))
|
||||
// // Output: "2020-06-08T14:21:28.000000123Z"
|
||||
// time.Time{} // Output: "0001-01-01T00:00:00Z"
|
||||
// (*time.Time)(nil) // Output: null
|
||||
@@ -95,5 +95,4 @@
|
||||
//
|
||||
// Struct{Car: &Car{Wheels: 4}, Vehicle: &Car{Wheels: 4}}
|
||||
// // Output: {"Car": {"Wheels: 4"}, "Vehicle": {"type":"vehicle/car","value":{"Wheels":4}}}
|
||||
//
|
||||
package json
|
||||
|
||||
+11
-10
@@ -69,18 +69,19 @@ func (l *filter) Error(msg string, keyvals ...interface{}) {
|
||||
// Allow*With methods, it is used as the logger's level.
|
||||
//
|
||||
// Examples:
|
||||
// logger = log.NewFilter(logger, log.AllowError(), log.AllowInfoWith("module", "crypto"))
|
||||
// logger.With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto"
|
||||
//
|
||||
// logger = log.NewFilter(logger, log.AllowError(),
|
||||
// log.AllowInfoWith("module", "crypto"),
|
||||
// log.AllowNoneWith("user", "Sam"))
|
||||
// logger.With("module", "crypto", "user", "Sam").Info("Hello") # returns nil
|
||||
// logger = log.NewFilter(logger, log.AllowError(), log.AllowInfoWith("module", "crypto"))
|
||||
// logger.With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto"
|
||||
//
|
||||
// logger = log.NewFilter(logger,
|
||||
// log.AllowError(),
|
||||
// log.AllowInfoWith("module", "crypto"), log.AllowNoneWith("user", "Sam"))
|
||||
// logger.With("user", "Sam").With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto user=Sam"
|
||||
// logger = log.NewFilter(logger, log.AllowError(),
|
||||
// log.AllowInfoWith("module", "crypto"),
|
||||
// log.AllowNoneWith("user", "Sam"))
|
||||
// logger.With("module", "crypto", "user", "Sam").Info("Hello") # returns nil
|
||||
//
|
||||
// logger = log.NewFilter(logger,
|
||||
// log.AllowError(),
|
||||
// log.AllowInfoWith("module", "crypto"), log.AllowNoneWith("user", "Sam"))
|
||||
// logger.With("user", "Sam").With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto user=Sam"
|
||||
func (l *filter) With(keyvals ...interface{}) Logger {
|
||||
keyInAllowedKeyvals := false
|
||||
|
||||
|
||||
+3
-3
@@ -22,9 +22,9 @@ type Logger interface {
|
||||
//
|
||||
// If w implements the following interface, so does the returned writer.
|
||||
//
|
||||
// interface {
|
||||
// Fd() uintptr
|
||||
// }
|
||||
// interface {
|
||||
// Fd() uintptr
|
||||
// }
|
||||
func NewSyncWriter(w io.Writer) io.Writer {
|
||||
return kitlog.NewSyncWriter(w)
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ func (l tmfmtLogger) Log(keyvals ...interface{}) error {
|
||||
switch keyvals[i] {
|
||||
case kitlevel.Key():
|
||||
excludeIndexes = append(excludeIndexes, i)
|
||||
switch keyvals[i+1].(type) { // nolint:gocritic
|
||||
switch keyvals[i+1].(type) { //nolint:gocritic
|
||||
case string:
|
||||
lvl = keyvals[i+1].(string)
|
||||
case kitlevel.Value:
|
||||
|
||||
@@ -83,10 +83,9 @@ func benchmarkRunnerKitlog(b *testing.B, logger kitlog.Logger, f func(kitlog.Log
|
||||
}
|
||||
}
|
||||
|
||||
//nolint: errcheck // ignore errors
|
||||
var (
|
||||
baseMessage = func(logger kitlog.Logger) { logger.Log("foo_key", "foo_value") }
|
||||
withMessage = func(logger kitlog.Logger) { kitlog.With(logger, "a", "b").Log("d", "f") }
|
||||
baseMessage = func(logger kitlog.Logger) { logger.Log("foo_key", "foo_value") } //nolint:errcheck
|
||||
withMessage = func(logger kitlog.Logger) { kitlog.With(logger, "a", "b").Log("d", "f") } //nolint:errcheck
|
||||
)
|
||||
|
||||
// These test are designed to be run with the race detector.
|
||||
|
||||
+18
-18
@@ -12,25 +12,25 @@
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// q, err := query.New("account.name='John'")
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// ctx, cancel := context.WithTimeout(context.Background(), 1 * time.Second)
|
||||
// defer cancel()
|
||||
// subscription, err := pubsub.Subscribe(ctx, "johns-transactions", q)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// q, err := query.New("account.name='John'")
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// ctx, cancel := context.WithTimeout(context.Background(), 1 * time.Second)
|
||||
// defer cancel()
|
||||
// subscription, err := pubsub.Subscribe(ctx, "johns-transactions", q)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// for {
|
||||
// select {
|
||||
// case msg <- subscription.Out():
|
||||
// // handle msg.Data() and msg.Events()
|
||||
// case <-subscription.Cancelled():
|
||||
// return subscription.Err()
|
||||
// }
|
||||
// }
|
||||
// for {
|
||||
// select {
|
||||
// case msg <- subscription.Out():
|
||||
// // handle msg.Data() and msg.Events()
|
||||
// case <-subscription.Cancelled():
|
||||
// return subscription.Err()
|
||||
// }
|
||||
// }
|
||||
package pubsub
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package query provides a parser for a custom query format:
|
||||
//
|
||||
// abci.invoice.number=22 AND abci.invoice.owner=Ivan
|
||||
// abci.invoice.number=22 AND abci.invoice.owner=Ivan
|
||||
//
|
||||
// See query.peg for the grammar, which is a https://en.wikipedia.org/wiki/Parsing_expression_grammar.
|
||||
// More: https://github.com/PhilippeSigaud/Pegged/wiki/PEG-Basics
|
||||
|
||||
@@ -43,9 +43,10 @@ func (s *Subscription) Out() <-chan Message {
|
||||
return s.out
|
||||
}
|
||||
|
||||
// nolint: misspell
|
||||
// Cancelled returns a channel that's closed when the subscription is
|
||||
// terminated and supposed to be used in a select statement.
|
||||
//
|
||||
//nolint:misspell
|
||||
func (s *Subscription) Cancelled() <-chan struct{} {
|
||||
return s.canceled
|
||||
}
|
||||
@@ -54,7 +55,8 @@ func (s *Subscription) Cancelled() <-chan struct{} {
|
||||
// If the channel is closed, Err returns a non-nil error explaining why:
|
||||
// - ErrUnsubscribed if the subscriber choose to unsubscribe,
|
||||
// - ErrOutOfCapacity if the subscriber is not pulling messages fast enough
|
||||
// and the channel returned by Out became full,
|
||||
// and the channel returned by Out became full,
|
||||
//
|
||||
// After Err returns a non-nil error, successive calls to Err return the same
|
||||
// error.
|
||||
func (s *Subscription) Err() error {
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ func (r *Rand) init() {
|
||||
}
|
||||
|
||||
func (r *Rand) reset(seed int64) {
|
||||
r.rand = mrand.New(mrand.NewSource(seed)) // nolint:gosec // G404: Use of weak random number generator
|
||||
r.rand = mrand.New(mrand.NewSource(seed)) //nolint:gosec
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
|
||||
+11
-9
@@ -109,7 +109,9 @@ func (c *Client) detectDivergence(ctx context.Context, primaryTrace []*types.Lig
|
||||
//
|
||||
// 1: errConflictingHeaders -> there may have been an attack on this light client
|
||||
// 2: errBadWitness -> the witness has either not responded, doesn't have the header or has given us an invalid one
|
||||
// Note: In the case of an invalid header we remove the witness
|
||||
//
|
||||
// Note: In the case of an invalid header we remove the witness
|
||||
//
|
||||
// 3: nil -> the hashes of the two headers match
|
||||
func (c *Client) compareNewHeaderWithWitness(ctx context.Context, errc chan error, h *types.SignedHeader,
|
||||
witness provider.Provider, witnessIndex int) {
|
||||
@@ -275,16 +277,16 @@ func (c *Client) handleConflictingHeaders(
|
||||
// it has received from another and preforms verifySkipping at the heights of each of the intermediate
|
||||
// headers in the trace until it reaches the divergentHeader. 1 of 2 things can happen.
|
||||
//
|
||||
// 1. The light client verifies a header that is different to the intermediate header in the trace. This
|
||||
// is the bifurcation point and the light client can create evidence from it
|
||||
// 2. The source stops responding, doesn't have the block or sends an invalid header in which case we
|
||||
// return the error and remove the witness
|
||||
// 1. The light client verifies a header that is different to the intermediate header in the trace. This
|
||||
// is the bifurcation point and the light client can create evidence from it
|
||||
// 2. The source stops responding, doesn't have the block or sends an invalid header in which case we
|
||||
// return the error and remove the witness
|
||||
//
|
||||
// CONTRACT:
|
||||
// 1. Trace can not be empty len(trace) > 0
|
||||
// 2. The last block in the trace can not be of a lower height than the target block
|
||||
// trace[len(trace)-1].Height >= targetBlock.Height
|
||||
// 3. The
|
||||
// 1. Trace can not be empty len(trace) > 0
|
||||
// 2. The last block in the trace can not be of a lower height than the target block
|
||||
// trace[len(trace)-1].Height >= targetBlock.Height
|
||||
// 3. The
|
||||
func (c *Client) examineConflictingHeaderAgainstTrace(
|
||||
ctx context.Context,
|
||||
trace []*types.LightBlock,
|
||||
|
||||
@@ -216,6 +216,6 @@ func validateHeight(height int64) (*int64, error) {
|
||||
// exponential backoff (with jitter)
|
||||
// 0.5s -> 2s -> 4.5s -> 8s -> 12.5 with 1s variation
|
||||
func backoffTimeout(attempt uint16) time.Duration {
|
||||
// nolint:gosec // G404: Use of weak random number generator
|
||||
//nolint:gosec // G404: Use of weak random number generator
|
||||
return time.Duration(500*attempt*attempt)*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond
|
||||
}
|
||||
|
||||
@@ -62,7 +62,6 @@ func makeHealthFunc(c *lrpc.Client) rpcHealthFunc {
|
||||
|
||||
type rpcStatusFunc func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error)
|
||||
|
||||
// nolint: interfacer
|
||||
func makeStatusFunc(c *lrpc.Client) rpcStatusFunc {
|
||||
return func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) {
|
||||
return c.Status(ctx.Context())
|
||||
@@ -259,8 +258,8 @@ type rpcABCIQueryFunc func(ctx *rpctypes.Context, path string,
|
||||
|
||||
func makeABCIQueryFunc(c *lrpc.Client) rpcABCIQueryFunc {
|
||||
return func(ctx *rpctypes.Context, path string, data bytes.HexBytes,
|
||||
height int64, prove bool) (*ctypes.ResultABCIQuery, error) {
|
||||
|
||||
height int64, prove bool,
|
||||
) (*ctypes.ResultABCIQuery, error) {
|
||||
return c.ABCIQueryWithOptions(ctx.Context(), path, data, rpcclient.ABCIQueryOptions{
|
||||
Height: height,
|
||||
Prove: prove,
|
||||
@@ -278,7 +277,6 @@ func makeABCIInfoFunc(c *lrpc.Client) rpcABCIInfoFunc {
|
||||
|
||||
type rpcBroadcastEvidenceFunc func(ctx *rpctypes.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error)
|
||||
|
||||
// nolint: interfacer
|
||||
func makeBroadcastEvidenceFunc(c *lrpc.Client) rpcBroadcastEvidenceFunc {
|
||||
return func(ctx *rpctypes.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) {
|
||||
return c.BroadcastEvidence(ctx.Context(), ev)
|
||||
|
||||
@@ -27,6 +27,7 @@ var errNegOrZeroHeight = errors.New("negative or zero height")
|
||||
type KeyPathFunc func(path string, key []byte) (merkle.KeyPath, error)
|
||||
|
||||
// LightClient is an interface that contains functionality needed by Client from the light client.
|
||||
//
|
||||
//go:generate ../../scripts/mockery_generate.sh LightClient
|
||||
type LightClient interface {
|
||||
ChainID() string
|
||||
|
||||
+18
-18
@@ -19,13 +19,13 @@ var (
|
||||
// VerifyNonAdjacent verifies non-adjacent untrustedHeader against
|
||||
// trustedHeader. It ensures that:
|
||||
//
|
||||
// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned)
|
||||
// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned)
|
||||
// c) trustLevel ([1/3, 1]) of trustedHeaderVals (or trustedHeaderNextVals)
|
||||
// signed correctly (if not, ErrNewValSetCantBeTrusted is returned)
|
||||
// d) more than 2/3 of untrustedVals have signed h2
|
||||
// (otherwise, ErrInvalidHeader is returned)
|
||||
// e) headers are non-adjacent.
|
||||
// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned)
|
||||
// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned)
|
||||
// c) trustLevel ([1/3, 1]) of trustedHeaderVals (or trustedHeaderNextVals)
|
||||
// signed correctly (if not, ErrNewValSetCantBeTrusted is returned)
|
||||
// d) more than 2/3 of untrustedVals have signed h2
|
||||
// (otherwise, ErrInvalidHeader is returned)
|
||||
// e) headers are non-adjacent.
|
||||
//
|
||||
// maxClockDrift defines how much untrustedHeader.Time can drift into the
|
||||
// future.
|
||||
@@ -81,12 +81,12 @@ func VerifyNonAdjacent(
|
||||
// VerifyAdjacent verifies directly adjacent untrustedHeader against
|
||||
// trustedHeader. It ensures that:
|
||||
//
|
||||
// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned)
|
||||
// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned)
|
||||
// c) untrustedHeader.ValidatorsHash equals trustedHeader.NextValidatorsHash
|
||||
// d) more than 2/3 of new validators (untrustedVals) have signed h2
|
||||
// (otherwise, ErrInvalidHeader is returned)
|
||||
// e) headers are adjacent.
|
||||
// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned)
|
||||
// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned)
|
||||
// c) untrustedHeader.ValidatorsHash equals trustedHeader.NextValidatorsHash
|
||||
// d) more than 2/3 of new validators (untrustedVals) have signed h2
|
||||
// (otherwise, ErrInvalidHeader is returned)
|
||||
// e) headers are adjacent.
|
||||
//
|
||||
// maxClockDrift defines how much untrustedHeader.Time can drift into the
|
||||
// future.
|
||||
@@ -212,12 +212,12 @@ func HeaderExpired(h *types.SignedHeader, trustingPeriod time.Duration, now time
|
||||
// VerifyBackwards verifies an untrusted header with a height one less than
|
||||
// that of an adjacent trusted header. It ensures that:
|
||||
//
|
||||
// a) untrusted header is valid
|
||||
// b) untrusted header has a time before the trusted header
|
||||
// c) that the LastBlockID hash of the trusted header is the same as the hash
|
||||
// of the trusted header
|
||||
// a) untrusted header is valid
|
||||
// b) untrusted header has a time before the trusted header
|
||||
// c) that the LastBlockID hash of the trusted header is the same as the hash
|
||||
// of the trusted header
|
||||
//
|
||||
// For any of these cases ErrInvalidHeader is returned.
|
||||
// For any of these cases ErrInvalidHeader is returned.
|
||||
func VerifyBackwards(untrustedHeader, trustedHeader *types.Header) error {
|
||||
if err := untrustedHeader.ValidateBasic(); err != nil {
|
||||
return ErrInvalidHeader{err}
|
||||
|
||||
@@ -194,7 +194,9 @@ func (mem *CListMempool) TxsWaitChan() <-chan struct{} {
|
||||
|
||||
// It blocks if we're waiting on Update() or Reap().
|
||||
// cb: A callback from the CheckTx command.
|
||||
// It gets called from another goroutine.
|
||||
//
|
||||
// It gets called from another goroutine.
|
||||
//
|
||||
// CONTRACT: Either cb will get called, or err returned.
|
||||
//
|
||||
// Safe for concurrent use by multiple goroutines.
|
||||
@@ -310,7 +312,7 @@ func (mem *CListMempool) reqResCb(
|
||||
}
|
||||
|
||||
// Called from:
|
||||
// - resCbFirstTime (lock not held) if tx is valid
|
||||
// - resCbFirstTime (lock not held) if tx is valid
|
||||
func (mem *CListMempool) addTx(memTx *mempoolTx) {
|
||||
e := mem.txs.PushBack(memTx)
|
||||
mem.txsMap.Store(memTx.tx.Key(), e)
|
||||
@@ -319,8 +321,8 @@ func (mem *CListMempool) addTx(memTx *mempoolTx) {
|
||||
}
|
||||
|
||||
// Called from:
|
||||
// - Update (lock held) if tx was committed
|
||||
// - resCbRecheck (lock not held) if tx was invalidated
|
||||
// - Update (lock held) if tx was committed
|
||||
// - resCbRecheck (lock not held) if tx was invalidated
|
||||
func (mem *CListMempool) removeTx(tx types.Tx, elem *clist.CElement, removeFromCache bool) {
|
||||
mem.txs.Remove(elem)
|
||||
elem.DetachPrev()
|
||||
|
||||
+22
-23
@@ -6,35 +6,34 @@ Adding new p2p.Reactor(s)
|
||||
|
||||
To add a new p2p.Reactor, use the CustomReactors option:
|
||||
|
||||
node, err := NewNode(
|
||||
config,
|
||||
privVal,
|
||||
nodeKey,
|
||||
clientCreator,
|
||||
genesisDocProvider,
|
||||
dbProvider,
|
||||
metricsProvider,
|
||||
logger,
|
||||
CustomReactors(map[string]p2p.Reactor{"CUSTOM": customReactor}),
|
||||
)
|
||||
node, err := NewNode(
|
||||
config,
|
||||
privVal,
|
||||
nodeKey,
|
||||
clientCreator,
|
||||
genesisDocProvider,
|
||||
dbProvider,
|
||||
metricsProvider,
|
||||
logger,
|
||||
CustomReactors(map[string]p2p.Reactor{"CUSTOM": customReactor}),
|
||||
)
|
||||
|
||||
Replacing existing p2p.Reactor(s)
|
||||
|
||||
To replace the built-in p2p.Reactor, use the CustomReactors option:
|
||||
|
||||
node, err := NewNode(
|
||||
config,
|
||||
privVal,
|
||||
nodeKey,
|
||||
clientCreator,
|
||||
genesisDocProvider,
|
||||
dbProvider,
|
||||
metricsProvider,
|
||||
logger,
|
||||
CustomReactors(map[string]p2p.Reactor{"BLOCKCHAIN": customBlockchainReactor}),
|
||||
)
|
||||
node, err := NewNode(
|
||||
config,
|
||||
privVal,
|
||||
nodeKey,
|
||||
clientCreator,
|
||||
genesisDocProvider,
|
||||
dbProvider,
|
||||
metricsProvider,
|
||||
logger,
|
||||
CustomReactors(map[string]p2p.Reactor{"BLOCKCHAIN": customBlockchainReactor}),
|
||||
)
|
||||
|
||||
The list of existing reactors can be found in CustomReactors documentation.
|
||||
|
||||
*/
|
||||
package node
|
||||
|
||||
+26
-30
@@ -51,7 +51,7 @@ import (
|
||||
tmtime "github.com/tendermint/tendermint/types/time"
|
||||
"github.com/tendermint/tendermint/version"
|
||||
|
||||
_ "net/http/pprof" // nolint: gosec // securely exposed on separate, optional port
|
||||
_ "net/http/pprof" //nolint: gosec // securely exposed on separate, optional port
|
||||
|
||||
_ "github.com/lib/pq" // provide the psql db driver
|
||||
)
|
||||
@@ -145,12 +145,12 @@ type blockSyncReactor interface {
|
||||
// WARNING: using any name from the below list of the existing reactors will
|
||||
// result in replacing it with the custom one.
|
||||
//
|
||||
// - MEMPOOL
|
||||
// - BLOCKCHAIN
|
||||
// - CONSENSUS
|
||||
// - EVIDENCE
|
||||
// - PEX
|
||||
// - STATESYNC
|
||||
// - MEMPOOL
|
||||
// - BLOCKCHAIN
|
||||
// - CONSENSUS
|
||||
// - EVIDENCE
|
||||
// - PEX
|
||||
// - STATESYNC
|
||||
func CustomReactors(reactors map[string]p2p.Reactor) Option {
|
||||
return func(n *Node) {
|
||||
for name, reactor := range reactors {
|
||||
@@ -272,7 +272,6 @@ func createAndStartIndexerService(
|
||||
eventBus *types.EventBus,
|
||||
logger log.Logger,
|
||||
) (*txindex.IndexerService, txindex.TxIndexer, indexer.BlockIndexer, error) {
|
||||
|
||||
var (
|
||||
txIndexer txindex.TxIndexer
|
||||
blockIndexer indexer.BlockIndexer
|
||||
@@ -321,8 +320,8 @@ func doHandshake(
|
||||
genDoc *types.GenesisDoc,
|
||||
eventBus types.BlockEventPublisher,
|
||||
proxyApp proxy.AppConns,
|
||||
consensusLogger log.Logger) error {
|
||||
|
||||
consensusLogger log.Logger,
|
||||
) error {
|
||||
handshaker := cs.NewHandshaker(stateStore, state, blockStore, genDoc)
|
||||
handshaker.SetLogger(consensusLogger)
|
||||
handshaker.SetEventBus(eventBus)
|
||||
@@ -372,7 +371,6 @@ func createMempoolAndMempoolReactor(
|
||||
memplMetrics *mempl.Metrics,
|
||||
logger log.Logger,
|
||||
) (mempl.Mempool, p2p.Reactor) {
|
||||
|
||||
switch config.Mempool.Version {
|
||||
case cfg.MempoolV1:
|
||||
mp := mempoolv1.NewTxMempool(
|
||||
@@ -423,8 +421,8 @@ func createMempoolAndMempoolReactor(
|
||||
}
|
||||
|
||||
func createEvidenceReactor(config *cfg.Config, dbProvider DBProvider,
|
||||
stateDB dbm.DB, blockStore *store.BlockStore, logger log.Logger) (*evidence.Reactor, *evidence.Pool, error) {
|
||||
|
||||
stateDB dbm.DB, blockStore *store.BlockStore, logger log.Logger,
|
||||
) (*evidence.Reactor, *evidence.Pool, error) {
|
||||
evidenceDB, err := dbProvider(&DBContext{"evidence", config})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -446,8 +444,8 @@ func createBlockchainReactor(config *cfg.Config,
|
||||
blockExec *sm.BlockExecutor,
|
||||
blockStore *store.BlockStore,
|
||||
blockSync bool,
|
||||
logger log.Logger) (bcReactor p2p.Reactor, err error) {
|
||||
|
||||
logger log.Logger,
|
||||
) (bcReactor p2p.Reactor, err error) {
|
||||
switch config.BlockSync.Version {
|
||||
case "v0":
|
||||
bcReactor = bc.NewReactor(state.Copy(), blockExec, blockStore, blockSync)
|
||||
@@ -471,8 +469,8 @@ func createConsensusReactor(config *cfg.Config,
|
||||
csMetrics *cs.Metrics,
|
||||
waitSync bool,
|
||||
eventBus *types.EventBus,
|
||||
consensusLogger log.Logger) (*cs.Reactor, *cs.State) {
|
||||
|
||||
consensusLogger log.Logger,
|
||||
) (*cs.Reactor, *cs.State) {
|
||||
consensusState := cs.NewState(
|
||||
config.Consensus,
|
||||
state.Copy(),
|
||||
@@ -574,8 +572,8 @@ func createSwitch(config *cfg.Config,
|
||||
evidenceReactor *evidence.Reactor,
|
||||
nodeInfo p2p.NodeInfo,
|
||||
nodeKey *p2p.NodeKey,
|
||||
p2pLogger log.Logger) *p2p.Switch {
|
||||
|
||||
p2pLogger log.Logger,
|
||||
) *p2p.Switch {
|
||||
sw := p2p.NewSwitch(
|
||||
config.P2P,
|
||||
transport,
|
||||
@@ -597,8 +595,8 @@ func createSwitch(config *cfg.Config,
|
||||
}
|
||||
|
||||
func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch,
|
||||
p2pLogger log.Logger, nodeKey *p2p.NodeKey) (pex.AddrBook, error) {
|
||||
|
||||
p2pLogger log.Logger, nodeKey *p2p.NodeKey,
|
||||
) (pex.AddrBook, error) {
|
||||
addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
|
||||
addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
|
||||
|
||||
@@ -624,8 +622,8 @@ func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch,
|
||||
}
|
||||
|
||||
func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config,
|
||||
sw *p2p.Switch, logger log.Logger) *pex.Reactor {
|
||||
|
||||
sw *p2p.Switch, logger log.Logger,
|
||||
) *pex.Reactor {
|
||||
// TODO persistent peers ? so we can have their DNS addrs saved
|
||||
pexReactor := pex.NewReactor(addrBook,
|
||||
&pex.ReactorConfig{
|
||||
@@ -647,7 +645,8 @@ func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config,
|
||||
// startStateSync starts an asynchronous state sync process, then switches to block sync mode.
|
||||
func startStateSync(ssR *statesync.Reactor, bcR blockSyncReactor, conR *cs.Reactor,
|
||||
stateProvider statesync.StateProvider, config *cfg.StateSyncConfig, blockSync bool,
|
||||
stateStore sm.Store, blockStore *store.BlockStore, state sm.State) error {
|
||||
stateStore sm.Store, blockStore *store.BlockStore, state sm.State,
|
||||
) error {
|
||||
ssR.Logger.Info("Starting state sync")
|
||||
|
||||
if stateProvider == nil {
|
||||
@@ -709,8 +708,8 @@ func NewNode(config *cfg.Config,
|
||||
dbProvider DBProvider,
|
||||
metricsProvider MetricsProvider,
|
||||
logger log.Logger,
|
||||
options ...Option) (*Node, error) {
|
||||
|
||||
options ...Option,
|
||||
) (*Node, error) {
|
||||
blockStore, stateDB, err := initDBs(config, dbProvider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1209,7 +1208,6 @@ func (n *Node) startRPC() ([]net.Listener, error) {
|
||||
}
|
||||
|
||||
return listeners, nil
|
||||
|
||||
}
|
||||
|
||||
// startPrometheusServer starts a Prometheus HTTP server, listening for metrics
|
||||
@@ -1370,9 +1368,7 @@ func makeNodeInfo(
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var (
|
||||
genesisDocKey = []byte("genesisDoc")
|
||||
)
|
||||
var genesisDocKey = []byte("genesisDoc")
|
||||
|
||||
// LoadStateFromDBOrGenesisDocProvider attempts to load the state from the
|
||||
// database, or creates one using the given genesisDocProvider. On success this also
|
||||
|
||||
@@ -62,6 +62,7 @@ The byte id and the relative priorities of each `Channel` are configured upon
|
||||
initialization of the connection.
|
||||
|
||||
There are two methods for sending messages:
|
||||
|
||||
func (m MConnection) Send(chID byte, msgBytes []byte) bool {}
|
||||
func (m MConnection) TrySend(chID byte, msgBytes []byte}) bool {}
|
||||
|
||||
|
||||
+16
-16
@@ -51,7 +51,7 @@ func TestMConnectionSendFlushStop(t *testing.T) {
|
||||
clientConn := createTestMConnection(client)
|
||||
err := clientConn.Start()
|
||||
require.Nil(t, err)
|
||||
defer clientConn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer clientConn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
msg := []byte("abc")
|
||||
assert.True(t, clientConn.Send(0x01, msg))
|
||||
@@ -89,7 +89,7 @@ func TestMConnectionSend(t *testing.T) {
|
||||
mconn := createTestMConnection(client)
|
||||
err := mconn.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
msg := []byte("Ant-Man")
|
||||
assert.True(t, mconn.Send(0x01, msg))
|
||||
@@ -128,12 +128,12 @@ func TestMConnectionReceive(t *testing.T) {
|
||||
mconn1 := createMConnectionWithCallbacks(client, onReceive, onError)
|
||||
err := mconn1.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn1.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn1.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
mconn2 := createTestMConnection(server)
|
||||
err = mconn2.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn2.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn2.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
msg := []byte("Cyclops")
|
||||
assert.True(t, mconn2.Send(0x01, msg))
|
||||
@@ -156,7 +156,7 @@ func TestMConnectionStatus(t *testing.T) {
|
||||
mconn := createTestMConnection(client)
|
||||
err := mconn.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
status := mconn.Status()
|
||||
assert.NotNil(t, status)
|
||||
@@ -179,7 +179,7 @@ func TestMConnectionPongTimeoutResultsInError(t *testing.T) {
|
||||
mconn := createMConnectionWithCallbacks(client, onReceive, onError)
|
||||
err := mconn.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
serverGotPing := make(chan struct{})
|
||||
go func() {
|
||||
@@ -218,7 +218,7 @@ func TestMConnectionMultiplePongsInTheBeginning(t *testing.T) {
|
||||
mconn := createMConnectionWithCallbacks(client, onReceive, onError)
|
||||
err := mconn.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// sending 3 pongs in a row (abuse)
|
||||
protoWriter := protoio.NewDelimitedWriter(server)
|
||||
@@ -273,7 +273,7 @@ func TestMConnectionMultiplePings(t *testing.T) {
|
||||
mconn := createMConnectionWithCallbacks(client, onReceive, onError)
|
||||
err := mconn.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// sending 3 pings in a row (abuse)
|
||||
// see https://github.com/tendermint/tendermint/issues/1190
|
||||
@@ -322,7 +322,7 @@ func TestMConnectionPingPongs(t *testing.T) {
|
||||
mconn := createMConnectionWithCallbacks(client, onReceive, onError)
|
||||
err := mconn.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
serverGotPing := make(chan struct{})
|
||||
go func() {
|
||||
@@ -380,7 +380,7 @@ func TestMConnectionStopsAndReturnsError(t *testing.T) {
|
||||
mconn := createMConnectionWithCallbacks(client, onReceive, onError)
|
||||
err := mconn.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
if err := client.Close(); err != nil {
|
||||
t.Error(err)
|
||||
@@ -492,8 +492,8 @@ func TestMConnectionReadErrorLongMessage(t *testing.T) {
|
||||
chOnRcv := make(chan struct{})
|
||||
|
||||
mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr)
|
||||
defer mconnClient.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconnServer.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconnClient.Stop() //nolint:errcheck // ignore for tests
|
||||
defer mconnServer.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
mconnServer.onReceive = func(chID byte, msgBytes []byte) {
|
||||
chOnRcv <- struct{}{}
|
||||
@@ -528,8 +528,8 @@ func TestMConnectionReadErrorLongMessage(t *testing.T) {
|
||||
func TestMConnectionReadErrorUnknownMsgType(t *testing.T) {
|
||||
chOnErr := make(chan struct{})
|
||||
mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr)
|
||||
defer mconnClient.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconnServer.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconnClient.Stop() //nolint:errcheck // ignore for tests
|
||||
defer mconnServer.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// send msg with unknown msg type
|
||||
_, err := protoio.NewDelimitedWriter(mconnClient.conn).WriteMsg(&types.Header{ChainID: "x"})
|
||||
@@ -545,7 +545,7 @@ func TestMConnectionTrySend(t *testing.T) {
|
||||
mconn := createTestMConnection(client)
|
||||
err := mconn.Start()
|
||||
require.Nil(t, err)
|
||||
defer mconn.Stop() // nolint:errcheck // ignore for tests
|
||||
defer mconn.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
msg := []byte("Semicolon-Woman")
|
||||
resultCh := make(chan string, 2)
|
||||
@@ -564,7 +564,7 @@ func TestMConnectionTrySend(t *testing.T) {
|
||||
assert.Equal(t, "TrySend", <-resultCh)
|
||||
}
|
||||
|
||||
// nolint:lll //ignore line length for tests
|
||||
//nolint:lll //ignore line length for tests
|
||||
func TestConnVectors(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error {
|
||||
|
||||
func (fc *FuzzedConnection) randomDuration() time.Duration {
|
||||
maxDelayMillis := int(fc.config.MaxDelay.Nanoseconds() / 1000)
|
||||
return time.Millisecond * time.Duration(tmrand.Int()%maxDelayMillis) // nolint: gas
|
||||
return time.Millisecond * time.Duration(tmrand.Int()%maxDelayMillis) //nolint: gas
|
||||
}
|
||||
|
||||
// implements the fuzz (delay, kill conn)
|
||||
|
||||
@@ -33,7 +33,7 @@ func TestNodeInfoValidate(t *testing.T) {
|
||||
}{
|
||||
{
|
||||
"Too Many Channels",
|
||||
func(ni *DefaultNodeInfo) { ni.Channels = append(channels, byte(maxNumChannels)) }, // nolint: gocritic
|
||||
func(ni *DefaultNodeInfo) { ni.Channels = append(channels, byte(maxNumChannels)) }, //nolint: gocritic
|
||||
true,
|
||||
},
|
||||
{"Duplicate Channel", func(ni *DefaultNodeInfo) { ni.Channels = dupChannels }, true},
|
||||
|
||||
@@ -94,16 +94,16 @@ func (ka *knownAddress) removeBucketRef(bucketIdx int) int {
|
||||
}
|
||||
|
||||
/*
|
||||
An address is bad if the address in question is a New address, has not been tried in the last
|
||||
minute, and meets one of the following criteria:
|
||||
An address is bad if the address in question is a New address, has not been tried in the last
|
||||
minute, and meets one of the following criteria:
|
||||
|
||||
1) It claims to be from the future
|
||||
2) It hasn't been seen in over a week
|
||||
3) It has failed at least three times and never succeeded
|
||||
4) It has failed ten times in the last week
|
||||
1) It claims to be from the future
|
||||
2) It hasn't been seen in over a week
|
||||
3) It has failed at least three times and never succeeded
|
||||
4) It has failed ten times in the last week
|
||||
|
||||
All addresses that meet these criteria are assumed to be worthless and not
|
||||
worth keeping hold of.
|
||||
All addresses that meet these criteria are assumed to be worthless and not
|
||||
worth keeping hold of.
|
||||
*/
|
||||
func (ka *knownAddress) isBad() bool {
|
||||
// Is Old --> good
|
||||
|
||||
+15
-15
@@ -58,6 +58,7 @@ func TestPEXReactorAddRemovePeer(t *testing.T) {
|
||||
}
|
||||
|
||||
// --- FAIL: TestPEXReactorRunning (11.10s)
|
||||
//
|
||||
// pex_reactor_test.go:411: expected all switches to be connected to at
|
||||
// least one peer (switches: 0 => {outbound: 1, inbound: 0}, 1 =>
|
||||
// {outbound: 0, inbound: 1}, 2 => {outbound: 0, inbound: 0}, )
|
||||
@@ -66,7 +67,6 @@ func TestPEXReactorAddRemovePeer(t *testing.T) {
|
||||
// if any peer (who we already connected to) has the same IP. Even though local
|
||||
// peers have different IP addresses, they all have the same underlying remote
|
||||
// IP: 127.0.0.1.
|
||||
//
|
||||
func TestPEXReactorRunning(t *testing.T) {
|
||||
N := 3
|
||||
switches := make([]*p2p.Switch, N)
|
||||
@@ -214,7 +214,7 @@ func TestCheckSeeds(t *testing.T) {
|
||||
// 1. test creating peer with no seeds works
|
||||
peerSwitch := testCreateDefaultPeer(dir, 0)
|
||||
require.Nil(t, peerSwitch.Start())
|
||||
peerSwitch.Stop() // nolint:errcheck // ignore for tests
|
||||
peerSwitch.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 2. create seed
|
||||
seed := testCreateSeed(dir, 1, []*p2p.NetAddress{}, []*p2p.NetAddress{})
|
||||
@@ -222,7 +222,7 @@ func TestCheckSeeds(t *testing.T) {
|
||||
// 3. test create peer with online seed works
|
||||
peerSwitch = testCreatePeerWithSeed(dir, 2, seed)
|
||||
require.Nil(t, peerSwitch.Start())
|
||||
peerSwitch.Stop() // nolint:errcheck // ignore for tests
|
||||
peerSwitch.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 4. test create peer with all seeds having unresolvable DNS fails
|
||||
badPeerConfig := &ReactorConfig{
|
||||
@@ -231,7 +231,7 @@ func TestCheckSeeds(t *testing.T) {
|
||||
}
|
||||
peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig)
|
||||
require.Error(t, peerSwitch.Start())
|
||||
peerSwitch.Stop() // nolint:errcheck // ignore for tests
|
||||
peerSwitch.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 5. test create peer with one good seed address succeeds
|
||||
badPeerConfig = &ReactorConfig{
|
||||
@@ -241,7 +241,7 @@ func TestCheckSeeds(t *testing.T) {
|
||||
}
|
||||
peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig)
|
||||
require.Nil(t, peerSwitch.Start())
|
||||
peerSwitch.Stop() // nolint:errcheck // ignore for tests
|
||||
peerSwitch.Stop() //nolint:errcheck // ignore for tests
|
||||
}
|
||||
|
||||
func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) {
|
||||
@@ -253,12 +253,12 @@ func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) {
|
||||
// 1. create seed
|
||||
seed := testCreateSeed(dir, 0, []*p2p.NetAddress{}, []*p2p.NetAddress{})
|
||||
require.Nil(t, seed.Start())
|
||||
defer seed.Stop() // nolint:errcheck // ignore for tests
|
||||
defer seed.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 2. create usual peer with only seed configured.
|
||||
peer := testCreatePeerWithSeed(dir, 1, seed)
|
||||
require.Nil(t, peer.Start())
|
||||
defer peer.Stop() // nolint:errcheck // ignore for tests
|
||||
defer peer.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 3. check that the peer connects to seed immediately
|
||||
assertPeersWithTimeout(t, []*p2p.Switch{peer}, 10*time.Millisecond, 3*time.Second, 1)
|
||||
@@ -273,18 +273,18 @@ func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) {
|
||||
// 1. create peer
|
||||
peerSwitch := testCreateDefaultPeer(dir, 1)
|
||||
require.Nil(t, peerSwitch.Start())
|
||||
defer peerSwitch.Stop() // nolint:errcheck // ignore for tests
|
||||
defer peerSwitch.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 2. Create seed which knows about the peer
|
||||
peerAddr := peerSwitch.NetAddress()
|
||||
seed := testCreateSeed(dir, 2, []*p2p.NetAddress{peerAddr}, []*p2p.NetAddress{peerAddr})
|
||||
require.Nil(t, seed.Start())
|
||||
defer seed.Stop() // nolint:errcheck // ignore for tests
|
||||
defer seed.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 3. create another peer with only seed configured.
|
||||
secondPeer := testCreatePeerWithSeed(dir, 3, seed)
|
||||
require.Nil(t, secondPeer.Start())
|
||||
defer secondPeer.Stop() // nolint:errcheck // ignore for tests
|
||||
defer secondPeer.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 4. check that the second peer connects to seed immediately
|
||||
assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 3*time.Second, 1)
|
||||
@@ -307,13 +307,13 @@ func TestPEXReactorSeedMode(t *testing.T) {
|
||||
sw.SetAddrBook(book)
|
||||
err = sw.Start()
|
||||
require.NoError(t, err)
|
||||
defer sw.Stop() // nolint:errcheck // ignore for tests
|
||||
defer sw.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
assert.Zero(t, sw.Peers().Size())
|
||||
|
||||
peerSwitch := testCreateDefaultPeer(dir, 1)
|
||||
require.NoError(t, peerSwitch.Start())
|
||||
defer peerSwitch.Stop() // nolint:errcheck // ignore for tests
|
||||
defer peerSwitch.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
// 1. Test crawlPeers dials the peer
|
||||
pexR.crawlPeers([]*p2p.NetAddress{peerSwitch.NetAddress()})
|
||||
@@ -346,13 +346,13 @@ func TestPEXReactorDoesNotDisconnectFromPersistentPeerInSeedMode(t *testing.T) {
|
||||
sw.SetAddrBook(book)
|
||||
err = sw.Start()
|
||||
require.NoError(t, err)
|
||||
defer sw.Stop() // nolint:errcheck // ignore for tests
|
||||
defer sw.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
assert.Zero(t, sw.Peers().Size())
|
||||
|
||||
peerSwitch := testCreateDefaultPeer(dir, 1)
|
||||
require.NoError(t, peerSwitch.Start())
|
||||
defer peerSwitch.Stop() // nolint:errcheck // ignore for tests
|
||||
defer peerSwitch.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
err = sw.AddPersistentPeers([]string{peerSwitch.NetAddress().String()})
|
||||
require.NoError(t, err)
|
||||
@@ -618,7 +618,7 @@ func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*p2p.NetAddress)
|
||||
book := NewAddrBook(filepath.Join(dir, "addrbookSeed.json"), false)
|
||||
book.SetLogger(log.TestingLogger())
|
||||
for j := 0; j < len(knownAddrs); j++ {
|
||||
book.AddAddress(knownAddrs[j], srcAddrs[j]) // nolint:errcheck // ignore for tests
|
||||
book.AddAddress(knownAddrs[j], srcAddrs[j]) //nolint:errcheck // ignore for tests
|
||||
book.MarkGood(knownAddrs[j].ID)
|
||||
}
|
||||
sw.SetAddrBook(book)
|
||||
|
||||
+2
-2
@@ -379,8 +379,8 @@ func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
|
||||
// to the PEX/Addrbook to find the peer with the addr again
|
||||
// NOTE: this will keep trying even if the handshake or auth fails.
|
||||
// TODO: be more explicit with error types so we only retry on certain failures
|
||||
// - ie. if we're getting ErrDuplicatePeer we can stop
|
||||
// because the addrbook got us the peer back already
|
||||
// - ie. if we're getting ErrDuplicatePeer we can stop
|
||||
// because the addrbook got us the peer back already
|
||||
func (sw *Switch) reconnectToPeer(addr *NetAddress) {
|
||||
if sw.reconnecting.Has(string(addr.ID)) {
|
||||
return
|
||||
|
||||
@@ -72,6 +72,7 @@ func TestTrustMetricCopyNilPointer(t *testing.T) {
|
||||
}
|
||||
|
||||
// XXX: This test fails non-deterministically
|
||||
//
|
||||
//nolint:unused,deadcode
|
||||
func _TestTrustMetricStopPause(t *testing.T) {
|
||||
// The TestTicker will provide manual control over
|
||||
|
||||
+1
-1
@@ -202,7 +202,7 @@ func localIPv4() (net.IP, error) {
|
||||
}
|
||||
|
||||
func getServiceURL(rootURL string) (url, urnDomain string, err error) {
|
||||
r, err := http.Get(rootURL) // nolint: gosec
|
||||
r, err := http.Get(rootURL) //nolint: gosec
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
+4
-6
@@ -1,13 +1,12 @@
|
||||
/*
|
||||
|
||||
Package privval provides different implementations of the types.PrivValidator.
|
||||
|
||||
FilePV
|
||||
# FilePV
|
||||
|
||||
FilePV is the simplest implementation and developer default.
|
||||
It uses one file for the private key and another to store state.
|
||||
|
||||
SignerListenerEndpoint
|
||||
# SignerListenerEndpoint
|
||||
|
||||
SignerListenerEndpoint establishes a connection to an external process,
|
||||
like a Key Management Server (KMS), using a socket.
|
||||
@@ -15,15 +14,14 @@ SignerListenerEndpoint listens for the external KMS process to dial in.
|
||||
SignerListenerEndpoint takes a listener, which determines the type of connection
|
||||
(ie. encrypted over tcp, or unencrypted over unix).
|
||||
|
||||
SignerDialerEndpoint
|
||||
# SignerDialerEndpoint
|
||||
|
||||
SignerDialerEndpoint is a simple wrapper around a net.Conn. It's used by both IPCVal and TCPVal.
|
||||
|
||||
SignerClient
|
||||
# SignerClient
|
||||
|
||||
SignerClient handles remote validator connections that provide signing services.
|
||||
In production, it's recommended to wrap it with RetrySignerClient to avoid
|
||||
termination in case of temporary errors.
|
||||
|
||||
*/
|
||||
package privval
|
||||
|
||||
@@ -57,7 +57,7 @@ func exampleProposal() *types.Proposal {
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:lll // ignore line length for tests
|
||||
//nolint:lll // ignore line length for tests
|
||||
func TestPrivvalVectors(t *testing.T) {
|
||||
pk := ed25519.GenPrivKeyFromSecret([]byte("it's a secret")).PubKey()
|
||||
ppk, err := cryptoenc.PubKeyToProto(pk)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/go-kit/kit/metrics"
|
||||
|
||||
abcicli "github.com/tendermint/tendermint/abci/client"
|
||||
"github.com/tendermint/tendermint/abci/types"
|
||||
)
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestAppConns_Failure(t *testing.T) {
|
||||
}()
|
||||
|
||||
quitCh := make(chan struct{})
|
||||
var recvQuitCh <-chan struct{} // nolint:gosimple
|
||||
var recvQuitCh <-chan struct{} //nolint:gosimple
|
||||
recvQuitCh = quitCh
|
||||
|
||||
clientCreatorMock := &mocks.ClientCreator{}
|
||||
|
||||
+15
-15
@@ -39,24 +39,24 @@ the example for more details.
|
||||
|
||||
Example:
|
||||
|
||||
c, err := New("http://192.168.1.10:26657", "/websocket")
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
c, err := New("http://192.168.1.10:26657", "/websocket")
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
|
||||
// call Start/Stop if you're subscribing to events
|
||||
err = c.Start()
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
defer c.Stop()
|
||||
// call Start/Stop if you're subscribing to events
|
||||
err = c.Start()
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
defer c.Stop()
|
||||
|
||||
res, err := c.Status()
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
res, err := c.Status()
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
|
||||
// handle result
|
||||
// handle result
|
||||
*/
|
||||
type HTTP struct {
|
||||
remote string
|
||||
|
||||
@@ -47,7 +47,6 @@ var _ client.Client = Client{}
|
||||
|
||||
// Call is used by recorders to save a call and response.
|
||||
// It can also be used to configure mock responses.
|
||||
//
|
||||
type Call struct {
|
||||
Name string
|
||||
Args interface{}
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ type peers interface {
|
||||
Peers() p2p.IPeerSet
|
||||
}
|
||||
|
||||
//----------------------------------------------
|
||||
// ----------------------------------------------
|
||||
// Environment contains objects and interfaces used by the RPC. It is expected
|
||||
// to be setup once during startup.
|
||||
type Environment struct {
|
||||
|
||||
@@ -30,7 +30,7 @@ const (
|
||||
// the remote server.
|
||||
//
|
||||
// WSClient is safe for concurrent use by multiple goroutines.
|
||||
type WSClient struct { // nolint: maligned
|
||||
type WSClient struct { //nolint: maligned
|
||||
conn *websocket.Conn
|
||||
|
||||
Address string // IP:PORT or /path/to/socket
|
||||
@@ -265,7 +265,7 @@ func (c *WSClient) dial() error {
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
}
|
||||
rHeader := http.Header{}
|
||||
conn, _, err := dialer.Dial(c.protocol+"://"+c.Address+c.Endpoint, rHeader) // nolint:bodyclose
|
||||
conn, _, err := dialer.Dial(c.protocol+"://"+c.Address+c.Endpoint, rHeader) //nolint:bodyclose
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ func TestWSClientReconnectsAfterReadFailure(t *testing.T) {
|
||||
defer s.Close()
|
||||
|
||||
c := startClient(t, "//"+s.Listener.Addr().String())
|
||||
defer c.Stop() // nolint:errcheck // ignore for tests
|
||||
defer c.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
wg.Add(1)
|
||||
go callWgDoneOnResult(t, c, &wg)
|
||||
@@ -104,7 +104,7 @@ func TestWSClientReconnectsAfterWriteFailure(t *testing.T) {
|
||||
s := httptest.NewServer(h)
|
||||
|
||||
c := startClient(t, "//"+s.Listener.Addr().String())
|
||||
defer c.Stop() // nolint:errcheck // ignore for tests
|
||||
defer c.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
wg.Add(2)
|
||||
go callWgDoneOnResult(t, c, &wg)
|
||||
@@ -132,7 +132,7 @@ func TestWSClientReconnectFailure(t *testing.T) {
|
||||
s := httptest.NewServer(h)
|
||||
|
||||
c := startClient(t, "//"+s.Listener.Addr().String())
|
||||
defer c.Stop() // nolint:errcheck // ignore for tests
|
||||
defer c.Stop() //nolint:errcheck // ignore for tests
|
||||
|
||||
go func() {
|
||||
for {
|
||||
@@ -181,7 +181,7 @@ func TestNotBlockingOnStop(t *testing.T) {
|
||||
timeout := 2 * time.Second
|
||||
s := httptest.NewServer(&myHandler{})
|
||||
c := startClient(t, "//"+s.Listener.Addr().String())
|
||||
c.Call(context.Background(), "a", make(map[string]interface{})) // nolint:errcheck // ignore for tests
|
||||
c.Call(context.Background(), "a", make(map[string]interface{})) //nolint:errcheck // ignore for tests
|
||||
// Let the readRoutine get around to blocking
|
||||
time.Sleep(time.Second)
|
||||
passCh := make(chan struct{})
|
||||
|
||||
@@ -176,8 +176,9 @@ func arrayParamsToArgs(
|
||||
// array.
|
||||
//
|
||||
// Example:
|
||||
// rpcFunc.args = [rpctypes.Context string]
|
||||
// rpcFunc.argNames = ["arg"]
|
||||
//
|
||||
// rpcFunc.args = [rpctypes.Context string]
|
||||
// rpcFunc.argNames = ["arg"]
|
||||
func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte) ([]reflect.Value, error) {
|
||||
const argsOffset = 1
|
||||
|
||||
@@ -237,5 +238,5 @@ func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[st
|
||||
buf.WriteString("</body></html>")
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(200)
|
||||
w.Write(buf.Bytes()) // nolint: errcheck
|
||||
w.Write(buf.Bytes()) //nolint: errcheck
|
||||
}
|
||||
|
||||
@@ -215,15 +215,17 @@ func (resp RPCResponse) String() string {
|
||||
}
|
||||
|
||||
// From the JSON-RPC 2.0 spec:
|
||||
//
|
||||
// If there was an error in detecting the id in the Request object (e.g. Parse
|
||||
// error/Invalid Request), it MUST be Null.
|
||||
// error/Invalid Request), it MUST be Null.
|
||||
func RPCParseError(err error) RPCResponse {
|
||||
return NewRPCErrorResponse(nil, -32700, "Parse error. Invalid JSON", err.Error())
|
||||
}
|
||||
|
||||
// From the JSON-RPC 2.0 spec:
|
||||
//
|
||||
// If there was an error in detecting the id in the Request object (e.g. Parse
|
||||
// error/Invalid Request), it MUST be Null.
|
||||
// error/Invalid Request), it MUST be Null.
|
||||
func RPCInvalidRequestError(id jsonrpcid, err error) RPCResponse {
|
||||
return NewRPCErrorResponse(id, -32600, "Invalid Request", err.Error())
|
||||
}
|
||||
@@ -276,9 +278,12 @@ type Context struct {
|
||||
// RemoteAddr returns the remote address (usually a string "IP:port").
|
||||
// If neither HTTPReq nor WSConn is set, an empty string is returned.
|
||||
// HTTP:
|
||||
// http.Request#RemoteAddr
|
||||
//
|
||||
// http.Request#RemoteAddr
|
||||
//
|
||||
// WS:
|
||||
// result of GetRemoteAddr
|
||||
//
|
||||
// result of GetRemoteAddr
|
||||
func (ctx *Context) RemoteAddr() string {
|
||||
if ctx.HTTPReq != nil {
|
||||
return ctx.HTTPReq.RemoteAddr
|
||||
@@ -291,10 +296,13 @@ func (ctx *Context) RemoteAddr() string {
|
||||
// Context returns the request's context.
|
||||
// The returned context is always non-nil; it defaults to the background context.
|
||||
// HTTP:
|
||||
// The context is canceled when the client's connection closes, the request
|
||||
// is canceled (with HTTP/2), or when the ServeHTTP method returns.
|
||||
//
|
||||
// The context is canceled when the client's connection closes, the request
|
||||
// is canceled (with HTTP/2), or when the ServeHTTP method returns.
|
||||
//
|
||||
// WS:
|
||||
// The context is canceled when the client's connections closes.
|
||||
//
|
||||
// The context is canceled when the client's connections closes.
|
||||
func (ctx *Context) Context() context.Context {
|
||||
if ctx.HTTPReq != nil {
|
||||
return ctx.HTTPReq.Context()
|
||||
@@ -307,7 +315,6 @@ func (ctx *Context) Context() context.Context {
|
||||
//----------------------------------------
|
||||
// SOCKETS
|
||||
|
||||
//
|
||||
// Determine if its a unix or tcp socket.
|
||||
// If tcp, must specify the port; `0.0.0.0` will return incorrectly as "unix" since there's no port
|
||||
// TODO: deprecate
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
metricsdiff "github.com/tendermint/tendermint/scripts/metricsgen/metricsdiff"
|
||||
)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
metricsgen "github.com/tendermint/tendermint/scripts/metricsgen"
|
||||
)
|
||||
|
||||
|
||||
@@ -132,7 +132,7 @@ func (p *snapshotPool) GetPeer(snapshot *snapshot) p2p.Peer {
|
||||
if len(peers) == 0 {
|
||||
return nil
|
||||
}
|
||||
return peers[rand.Intn(len(peers))] // nolint:gosec // G404: Use of weak random number generator
|
||||
return peers[rand.Intn(len(peers))] //nolint:gosec // G404: Use of weak random number generator
|
||||
}
|
||||
|
||||
// GetPeers returns the peers for a snapshot.
|
||||
|
||||
+7
-6
@@ -17,9 +17,9 @@ import (
|
||||
BlockStore is a simple low level store for blocks.
|
||||
|
||||
There are three types of information stored:
|
||||
- BlockMeta: Meta information about each block
|
||||
- Block part: Parts of each block, aggregated w/ PartSet
|
||||
- Commit: The commit part of each block, for gossiping precommit votes
|
||||
- BlockMeta: Meta information about each block
|
||||
- Block part: Parts of each block, aggregated w/ PartSet
|
||||
- Commit: The commit part of each block, for gossiping precommit votes
|
||||
|
||||
Currently the precommit signatures are duplicated in the Block parts as
|
||||
well as the Commit. In the future this may change, perhaps by moving
|
||||
@@ -325,9 +325,10 @@ func (bs *BlockStore) PruneBlocks(height int64) (uint64, error) {
|
||||
// SaveBlock persists the given block, blockParts, and seenCommit to the underlying db.
|
||||
// blockParts: Must be parts of the block
|
||||
// seenCommit: The +2/3 precommits that were seen which committed at height.
|
||||
// If all the nodes restart after committing a block,
|
||||
// we need this to reload the precommits to catch-up nodes to the
|
||||
// most recent height. Otherwise they'd stall at H-1.
|
||||
//
|
||||
// If all the nodes restart after committing a block,
|
||||
// we need this to reload the precommits to catch-up nodes to the
|
||||
// most recent height. Otherwise they'd stall at H-1.
|
||||
func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
|
||||
if block == nil {
|
||||
panic("BlockStore can only save a non-nil block")
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// nolint: gosec
|
||||
package app
|
||||
|
||||
import (
|
||||
@@ -29,7 +28,7 @@ type SnapshotStore struct {
|
||||
// NewSnapshotStore creates a new snapshot store.
|
||||
func NewSnapshotStore(dir string) (*SnapshotStore, error) {
|
||||
store := &SnapshotStore{dir: dir}
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := store.loadMetadata(); err != nil {
|
||||
@@ -71,7 +70,7 @@ func (s *SnapshotStore) saveMetadata() error {
|
||||
// save the file to a new file and move it to make saving atomic.
|
||||
newFile := filepath.Join(s.dir, "metadata.json.new")
|
||||
file := filepath.Join(s.dir, "metadata.json")
|
||||
err = os.WriteFile(newFile, bz, 0644) // nolint: gosec
|
||||
err = os.WriteFile(newFile, bz, 0o644) //nolint: gosec
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -92,7 +91,7 @@ func (s *SnapshotStore) Create(state *State) (abci.Snapshot, error) {
|
||||
Hash: hashItems(state.Values),
|
||||
Chunks: byteChunks(bz),
|
||||
}
|
||||
err = os.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", state.Height)), bz, 0644)
|
||||
err = os.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", state.Height)), bz, 0o644) //nolint:gosec
|
||||
if err != nil {
|
||||
return abci.Snapshot{}, err
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
//nolint: gosec
|
||||
package app
|
||||
|
||||
import (
|
||||
@@ -12,8 +11,10 @@ import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const stateFileName = "app_state.json"
|
||||
const prevStateFileName = "prev_app_state.json"
|
||||
const (
|
||||
stateFileName = "app_state.json"
|
||||
prevStateFileName = "prev_app_state.json"
|
||||
)
|
||||
|
||||
// State is the application state.
|
||||
type State struct {
|
||||
@@ -81,7 +82,7 @@ func (s *State) save() error {
|
||||
// We write the state to a separate file and move it to the destination, to
|
||||
// make it atomic.
|
||||
newFile := fmt.Sprintf("%v.new", s.currentFile)
|
||||
err = os.WriteFile(newFile, bz, 0644)
|
||||
err = os.WriteFile(newFile, bz, 0o644) //nolint:gosec
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write state to %q: %w", s.currentFile, err)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
//nolint: gosec
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -58,12 +57,12 @@ func NewCLI() *CLI {
|
||||
|
||||
// generate generates manifests in a directory.
|
||||
func (cli *CLI) generate(dir string, groups int) error {
|
||||
err := os.MkdirAll(dir, 0755)
|
||||
err := os.MkdirAll(dir, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
manifests, err := Generate(rand.New(rand.NewSource(randomSeed)))
|
||||
manifests, err := Generate(rand.New(rand.NewSource(randomSeed))) //nolint:gosec
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
//nolint: goconst
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -56,6 +55,8 @@ func LoadConfig(file string) (*Config, error) {
|
||||
|
||||
// Validate validates the configuration. We don't do exhaustive config
|
||||
// validation here, instead relying on Testnet.Validate() to handle it.
|
||||
//
|
||||
//nolint:goconst
|
||||
func (cfg Config) Validate() error {
|
||||
switch {
|
||||
case cfg.ChainID == "":
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
//nolint: gosec
|
||||
package e2e
|
||||
|
||||
import (
|
||||
@@ -26,9 +25,11 @@ const (
|
||||
networkIPv6 = "fd80:b10c::/48"
|
||||
)
|
||||
|
||||
type Mode string
|
||||
type Protocol string
|
||||
type Perturbation string
|
||||
type (
|
||||
Mode string
|
||||
Protocol string
|
||||
Perturbation string
|
||||
)
|
||||
|
||||
const (
|
||||
ModeValidator Mode = "validator"
|
||||
@@ -396,7 +397,7 @@ func (t Testnet) ArchiveNodes() []*Node {
|
||||
// RandomNode returns a random non-seed node.
|
||||
func (t Testnet) RandomNode() *Node {
|
||||
for {
|
||||
node := t.Nodes[rand.Intn(len(t.Nodes))]
|
||||
node := t.Nodes[rand.Intn(len(t.Nodes))] //nolint:gosec
|
||||
if node.Mode != ModeSeed {
|
||||
return node
|
||||
}
|
||||
@@ -459,7 +460,7 @@ type keyGenerator struct {
|
||||
|
||||
func newKeyGenerator(seed int64) *keyGenerator {
|
||||
return &keyGenerator{
|
||||
random: rand.New(rand.NewSource(seed)),
|
||||
random: rand.New(rand.NewSource(seed)), //nolint:gosec
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
@@ -234,7 +234,7 @@ func getRandomValidatorIndex(privVals []types.MockPV, vals *types.ValidatorSet)
|
||||
}
|
||||
|
||||
func readPrivKey(keyFilePath string) (crypto.PrivKey, error) {
|
||||
keyJSONBytes, err := ioutil.ReadFile(keyFilePath)
|
||||
keyJSONBytes, err := os.ReadFile(keyFilePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
//nolint: gosec
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -10,7 +9,7 @@ import (
|
||||
|
||||
// execute executes a shell command.
|
||||
func exec(args ...string) error {
|
||||
cmd := osexec.Command(args[0], args[1:]...)
|
||||
cmd := osexec.Command(args[0], args[1:]...) //nolint:gosec
|
||||
out, err := cmd.CombinedOutput()
|
||||
switch err := err.(type) {
|
||||
case nil:
|
||||
@@ -24,7 +23,7 @@ func exec(args ...string) error {
|
||||
|
||||
// execVerbose executes a shell command while displaying its output.
|
||||
func execVerbose(args ...string) error {
|
||||
cmd := osexec.Command(args[0], args[1:]...)
|
||||
cmd := osexec.Command(args[0], args[1:]...) //nolint:gosec
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd.Run()
|
||||
|
||||
@@ -57,7 +57,7 @@ func NewCLI() *CLI {
|
||||
return err
|
||||
}
|
||||
|
||||
r := rand.New(rand.NewSource(randomSeed)) // nolint: gosec
|
||||
r := rand.New(rand.NewSource(randomSeed)) //nolint: gosec
|
||||
|
||||
chLoadResult := make(chan error)
|
||||
ctx, loadCancel := context.WithCancel(context.Background())
|
||||
@@ -203,7 +203,7 @@ func NewCLI() *CLI {
|
||||
|
||||
return InjectEvidence(
|
||||
cmd.Context(),
|
||||
rand.New(rand.NewSource(randomSeed)), // nolint: gosec
|
||||
rand.New(rand.NewSource(randomSeed)), //nolint: gosec
|
||||
cli.testnet,
|
||||
amount,
|
||||
)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// nolint: gosec
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -52,7 +51,7 @@ func Setup(testnet *e2e.Testnet) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = os.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0644)
|
||||
err = os.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0o644) //nolint:gosec
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -75,7 +74,7 @@ func Setup(testnet *e2e.Testnet) error {
|
||||
if node.Mode == e2e.ModeLight && strings.Contains(dir, "app") {
|
||||
continue
|
||||
}
|
||||
err := os.MkdirAll(dir, 0755)
|
||||
err := os.MkdirAll(dir, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -91,7 +90,7 @@ func Setup(testnet *e2e.Testnet) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = os.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0644)
|
||||
err = os.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0o644) //nolint:gosec
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -400,5 +399,5 @@ func UpdateConfigStateSync(node *e2e.Node, height int64, hash []byte) error {
|
||||
}
|
||||
bz = regexp.MustCompile(`(?m)^trust_height =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_height = %v`, height)))
|
||||
bz = regexp.MustCompile(`(?m)^trust_hash =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_hash = "%X"`, hash)))
|
||||
return os.WriteFile(cfgPath, bz, 0644)
|
||||
return os.WriteFile(cfgPath, bz, 0o644) //nolint:gosec
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// nolint: gosec
|
||||
package addr
|
||||
|
||||
import (
|
||||
@@ -25,7 +24,7 @@ func Fuzz(data []byte) int {
|
||||
}
|
||||
|
||||
// Also, make sure PickAddress always returns a non-nil address.
|
||||
bias := rand.Intn(100)
|
||||
bias := rand.Intn(100) //nolint:gosec
|
||||
if p := addrBook.PickAddress(bias); p == nil {
|
||||
panic(fmt.Sprintf("picked a nil address (bias: %d, addrBook size: %v)",
|
||||
bias, addrBook.Size()))
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// nolint: gosec
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -26,7 +25,7 @@ func initCorpus(baseDir string) {
|
||||
|
||||
// create "corpus" directory
|
||||
corpusDir := filepath.Join(baseDir, "corpus")
|
||||
if err := os.MkdirAll(corpusDir, 0755); err != nil {
|
||||
if err := os.MkdirAll(corpusDir, 0o755); err != nil {
|
||||
log.Fatalf("Creating %q err: %v", corpusDir, err)
|
||||
}
|
||||
|
||||
@@ -48,7 +47,8 @@ func initCorpus(baseDir string) {
|
||||
log.Fatalf("can't marshal %v: %v", addr, err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filename, bz, 0644); err != nil {
|
||||
//nolint:gosec
|
||||
if err := os.WriteFile(filename, bz, 0o644); err != nil {
|
||||
log.Fatalf("can't write %v to %q: %v", addr, filename, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// nolint: gosec
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -21,11 +20,12 @@ func main() {
|
||||
initCorpus(*baseDir)
|
||||
}
|
||||
|
||||
//nolint:gosec
|
||||
func initCorpus(rootDir string) {
|
||||
log.SetFlags(0)
|
||||
|
||||
corpusDir := filepath.Join(rootDir, "corpus")
|
||||
if err := os.MkdirAll(corpusDir, 0755); err != nil {
|
||||
if err := os.MkdirAll(corpusDir, 0o755); err != nil {
|
||||
log.Fatalf("Creating %q err: %v", corpusDir, err)
|
||||
}
|
||||
sizes := []int{0, 1, 2, 17, 5, 31}
|
||||
@@ -72,7 +72,7 @@ func initCorpus(rootDir string) {
|
||||
|
||||
filename := filepath.Join(rootDir, "corpus", fmt.Sprintf("%d", n))
|
||||
|
||||
if err := os.WriteFile(filename, bz, 0644); err != nil {
|
||||
if err := os.WriteFile(filename, bz, 0o644); err != nil {
|
||||
log.Fatalf("can't write %X to %q: %v", bz, filename, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// nolint: gosec
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -20,7 +19,7 @@ func initCorpus(baseDir string) {
|
||||
log.SetFlags(0)
|
||||
|
||||
corpusDir := filepath.Join(baseDir, "corpus")
|
||||
if err := os.MkdirAll(corpusDir, 0755); err != nil {
|
||||
if err := os.MkdirAll(corpusDir, 0o755); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -38,7 +37,8 @@ func initCorpus(baseDir string) {
|
||||
for i, datum := range data {
|
||||
filename := filepath.Join(corpusDir, fmt.Sprintf("%d", i))
|
||||
|
||||
if err := os.WriteFile(filename, []byte(datum), 0644); err != nil {
|
||||
//nolint:gosec
|
||||
if err := os.WriteFile(filename, []byte(datum), 0o644); err != nil {
|
||||
log.Fatalf("can't write %v to %q: %v", datum, filename, err)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -211,7 +211,7 @@ func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) BlockID {
|
||||
|
||||
var nilBytes []byte
|
||||
|
||||
// This follows RFC-6962, i.e. `echo -n '' | sha256sum`
|
||||
// This follows RFC-6962, i.e. `echo -n ” | sha256sum`
|
||||
var emptyBytes = []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8,
|
||||
0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
|
||||
0x78, 0x52, 0xb8, 0x55}
|
||||
|
||||
+2
-2
@@ -23,7 +23,7 @@ type EventBusSubscriber interface {
|
||||
|
||||
type Subscription interface {
|
||||
Out() <-chan tmpubsub.Message
|
||||
Cancelled() <-chan struct{} // nolint: misspell
|
||||
Cancelled() <-chan struct{} //nolint: misspell
|
||||
Err() error
|
||||
}
|
||||
|
||||
@@ -227,7 +227,7 @@ func (b *EventBus) PublishEventValidatorSetUpdates(data EventDataValidatorSetUpd
|
||||
return b.Publish(EventValidatorSetUpdates, data)
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// -----------------------------------------------------------------------------
|
||||
type NopEventBus struct{}
|
||||
|
||||
func (NopEventBus) Subscribe(
|
||||
|
||||
+3
-3
@@ -4,9 +4,9 @@ import "reflect"
|
||||
|
||||
// Go lacks a simple and safe way to see if something is a typed nil.
|
||||
// See:
|
||||
// - https://dave.cheney.net/2017/08/09/typed-nils-in-go-2
|
||||
// - https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I/discussion
|
||||
// - https://github.com/golang/go/issues/21538
|
||||
// - https://dave.cheney.net/2017/08/09/typed-nils-in-go-2
|
||||
// - https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I/discussion
|
||||
// - https://github.com/golang/go/issues/21538
|
||||
func isTypedNil(o interface{}) bool {
|
||||
rv := reflect.ValueOf(o)
|
||||
switch rv.Kind() {
|
||||
|
||||
+18
-13
@@ -411,14 +411,17 @@ func processChanges(origChanges []*Validator) (updates, removals []*Validator, e
|
||||
//
|
||||
// Inputs:
|
||||
// updates - a list of proper validator changes, i.e. they have been verified by processChanges for duplicates
|
||||
// and invalid values.
|
||||
//
|
||||
// and invalid values.
|
||||
//
|
||||
// vals - the original validator set. Note that vals is NOT modified by this function.
|
||||
// removedPower - the total voting power that will be removed after the updates are verified and applied.
|
||||
//
|
||||
// Returns:
|
||||
// tvpAfterUpdatesBeforeRemovals - the new total voting power if these updates would be applied without the removals.
|
||||
// Note that this will be < 2 * MaxTotalVotingPower in case high power validators are removed and
|
||||
// validators are added/ updated with high power values.
|
||||
//
|
||||
// Note that this will be < 2 * MaxTotalVotingPower in case high power validators are removed and
|
||||
// validators are added/ updated with high power values.
|
||||
//
|
||||
// err - non-nil if the maximum allowed total voting power would be exceeded
|
||||
func verifyUpdates(
|
||||
@@ -467,8 +470,9 @@ func numNewValidators(updates []*Validator, vals *ValidatorSet) int {
|
||||
// 'updates' parameter must be a list of unique validators to be added or updated.
|
||||
//
|
||||
// 'updatedTotalVotingPower' is the total voting power of a set where all updates would be applied but
|
||||
// not the removals. It must be < 2*MaxTotalVotingPower and may be close to this limit if close to
|
||||
// MaxTotalVotingPower will be removed. This is still safe from overflow since MaxTotalVotingPower is maxInt64/8.
|
||||
//
|
||||
// not the removals. It must be < 2*MaxTotalVotingPower and may be close to this limit if close to
|
||||
// MaxTotalVotingPower will be removed. This is still safe from overflow since MaxTotalVotingPower is maxInt64/8.
|
||||
//
|
||||
// No changes are made to the validator set 'vals'.
|
||||
func computeNewPriorities(updates []*Validator, vals *ValidatorSet, updatedTotalVotingPower int64) {
|
||||
@@ -638,14 +642,15 @@ func (vals *ValidatorSet) updateWithChangeSet(changes []*Validator, allowDeletes
|
||||
|
||||
// UpdateWithChangeSet attempts to update the validator set with 'changes'.
|
||||
// It performs the following steps:
|
||||
// - validates the changes making sure there are no duplicates and splits them in updates and deletes
|
||||
// - verifies that applying the changes will not result in errors
|
||||
// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities
|
||||
// across old and newly added validators are fair
|
||||
// - computes the priorities of new validators against the final set
|
||||
// - applies the updates against the validator set
|
||||
// - applies the removals against the validator set
|
||||
// - performs scaling and centering of priority values
|
||||
// - validates the changes making sure there are no duplicates and splits them in updates and deletes
|
||||
// - verifies that applying the changes will not result in errors
|
||||
// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities
|
||||
// across old and newly added validators are fair
|
||||
// - computes the priorities of new validators against the final set
|
||||
// - applies the updates against the validator set
|
||||
// - applies the removals against the validator set
|
||||
// - performs scaling and centering of priority values
|
||||
//
|
||||
// If an error is detected during verification steps, it is returned and the validator set
|
||||
// is not changed.
|
||||
func (vals *ValidatorSet) UpdateWithChangeSet(changes []*Validator) error {
|
||||
|
||||
@@ -1641,7 +1641,7 @@ func TestValidatorSetProtoBuf(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
//---------------------
|
||||
// ---------------------
|
||||
// Sort validators by priority and address
|
||||
type validatorsByPriority []*Validator
|
||||
|
||||
@@ -1682,9 +1682,8 @@ func (tvals testValsByVotingPower) Swap(i, j int) {
|
||||
tvals[i], tvals[j] = tvals[j], tvals[i]
|
||||
}
|
||||
|
||||
//-------------------------------------
|
||||
// -------------------------------------
|
||||
// Benchmark tests
|
||||
//
|
||||
func BenchmarkUpdates(b *testing.B) {
|
||||
const (
|
||||
n = 100
|
||||
|
||||
+32
-30
@@ -25,38 +25,38 @@ const (
|
||||
type P2PID string
|
||||
|
||||
/*
|
||||
VoteSet helps collect signatures from validators at each height+round for a
|
||||
predefined vote type.
|
||||
VoteSet helps collect signatures from validators at each height+round for a
|
||||
predefined vote type.
|
||||
|
||||
We need VoteSet to be able to keep track of conflicting votes when validators
|
||||
double-sign. Yet, we can't keep track of *all* the votes seen, as that could
|
||||
be a DoS attack vector.
|
||||
We need VoteSet to be able to keep track of conflicting votes when validators
|
||||
double-sign. Yet, we can't keep track of *all* the votes seen, as that could
|
||||
be a DoS attack vector.
|
||||
|
||||
There are two storage areas for votes.
|
||||
1. voteSet.votes
|
||||
2. voteSet.votesByBlock
|
||||
There are two storage areas for votes.
|
||||
1. voteSet.votes
|
||||
2. voteSet.votesByBlock
|
||||
|
||||
`.votes` is the "canonical" list of votes. It always has at least one vote,
|
||||
if a vote from a validator had been seen at all. Usually it keeps track of
|
||||
the first vote seen, but when a 2/3 majority is found, votes for that get
|
||||
priority and are copied over from `.votesByBlock`.
|
||||
`.votes` is the "canonical" list of votes. It always has at least one vote,
|
||||
if a vote from a validator had been seen at all. Usually it keeps track of
|
||||
the first vote seen, but when a 2/3 majority is found, votes for that get
|
||||
priority and are copied over from `.votesByBlock`.
|
||||
|
||||
`.votesByBlock` keeps track of a list of votes for a particular block. There
|
||||
are two ways a &blockVotes{} gets created in `.votesByBlock`.
|
||||
1. the first vote seen by a validator was for the particular block.
|
||||
2. a peer claims to have seen 2/3 majority for the particular block.
|
||||
`.votesByBlock` keeps track of a list of votes for a particular block. There
|
||||
are two ways a &blockVotes{} gets created in `.votesByBlock`.
|
||||
1. the first vote seen by a validator was for the particular block.
|
||||
2. a peer claims to have seen 2/3 majority for the particular block.
|
||||
|
||||
Since the first vote from a validator will always get added in `.votesByBlock`
|
||||
, all votes in `.votes` will have a corresponding entry in `.votesByBlock`.
|
||||
Since the first vote from a validator will always get added in `.votesByBlock`
|
||||
, all votes in `.votes` will have a corresponding entry in `.votesByBlock`.
|
||||
|
||||
When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its
|
||||
votes are copied into `.votes`.
|
||||
When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its
|
||||
votes are copied into `.votes`.
|
||||
|
||||
All this is memory bounded because conflicting votes only get added if a peer
|
||||
told us to track that block, each peer only gets to tell us 1 such block, and,
|
||||
there's only a limited number of peers.
|
||||
All this is memory bounded because conflicting votes only get added if a peer
|
||||
told us to track that block, each peer only gets to tell us 1 such block, and,
|
||||
there's only a limited number of peers.
|
||||
|
||||
NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64.
|
||||
NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64.
|
||||
*/
|
||||
type VoteSet struct {
|
||||
chainID string
|
||||
@@ -133,8 +133,10 @@ func (voteSet *VoteSet) Size() int {
|
||||
|
||||
// Returns added=true if vote is valid and new.
|
||||
// Otherwise returns err=ErrVote[
|
||||
// UnexpectedStep | InvalidIndex | InvalidAddress |
|
||||
// InvalidSignature | InvalidBlockHash | ConflictingVotes ]
|
||||
//
|
||||
// UnexpectedStep | InvalidIndex | InvalidAddress |
|
||||
// InvalidSignature | InvalidBlockHash | ConflictingVotes ]
|
||||
//
|
||||
// Duplicate votes return added=false, err=nil.
|
||||
// Conflicting votes return added=*, err=ErrVoteConflictingVotes.
|
||||
// NOTE: vote should not be mutated after adding.
|
||||
@@ -644,10 +646,10 @@ func (voteSet *VoteSet) MakeCommit() *Commit {
|
||||
//--------------------------------------------------------------------------------
|
||||
|
||||
/*
|
||||
Votes for a particular block
|
||||
There are two ways a *blockVotes gets created for a blockKey.
|
||||
1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false)
|
||||
2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true)
|
||||
Votes for a particular block
|
||||
There are two ways a *blockVotes gets created for a blockKey.
|
||||
1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false)
|
||||
2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true)
|
||||
*/
|
||||
type blockVotes struct {
|
||||
peerMaj23 bool // peer claims to have maj23
|
||||
|
||||
Reference in New Issue
Block a user