Browse Source

Merge pull request #41 from tendermint/metalinter

add metalinter to Makefile & apply some fixes
pull/1782/head
Ethan Buchman 7 years ago
committed by GitHub
parent
commit
a6e6b58c6b
15 changed files with 98 additions and 78 deletions
  1. +38
    -2
      Makefile
  2. +0
    -6
      _gen.go
  3. +1
    -1
      armor.go
  4. +1
    -1
      bcrypt/bcrypt.go
  5. +4
    -4
      embed_test.go
  6. +2
    -2
      example_test.go
  7. +7
    -8
      hd/address.go
  8. +13
    -9
      hd/hd_test.go
  9. +3
    -9
      keys/cryptostore/holder.go
  10. +7
    -7
      keys/cryptostore/holder_test.go
  11. +2
    -1
      keys/server/helpers.go
  12. +9
    -15
      keys/storage/filestorage/main.go
  13. +2
    -4
      keys/storage/memstorage/main.go
  14. +2
    -2
      keys/wordcodec_test.go
  15. +7
    -7
      keys/wordlist/wordlist.go

+ 38
- 2
Makefile View File

@ -2,10 +2,12 @@
GOTOOLS = \ GOTOOLS = \
github.com/Masterminds/glide \ github.com/Masterminds/glide \
github.com/jteeuwen/go-bindata/go-bindata
github.com/jteeuwen/go-bindata/go-bindata \
github.com/alecthomas/gometalinter
REPO:=github.com/tendermint/go-crypto REPO:=github.com/tendermint/go-crypto
all: get_vendor_deps test
all: get_vendor_deps metalinter_test test
test: test:
go test `glide novendor` go test `glide novendor`
@ -31,3 +33,37 @@ codegen:
@echo "--> regenerating all interface wrappers" @echo "--> regenerating all interface wrappers"
@gen @gen
@echo "Done!" @echo "Done!"
metalinter: ensure_tools
@gometalinter --install
gometalinter --vendor --deadline=600s --enable-all --disable=lll ./...
metalinter_test: ensure_tools
@gometalinter --install
gometalinter --vendor --deadline=600s --disable-all \
--enable=deadcode \
--enable=gas \
--enable=goconst \
--enable=gocyclo \
--enable=gosimple \
--enable=ineffassign \
--enable=interfacer \
--enable=maligned \
--enable=megacheck \
--enable=misspell \
--enable=safesql \
--enable=staticcheck \
--enable=structcheck \
--enable=unconvert \
--enable=unused \
--enable=vetshadow \
--enable=vet \
--enable=varcheck \
./...
#--enable=dupl \
#--enable=errcheck \
#--enable=goimports \
#--enable=golint \ <== comments on anything exported
#--enable=gotype \
#--enable=unparam \

+ 0
- 6
_gen.go View File

@ -1,6 +0,0 @@
package main
import (
_ "github.com/tendermint/go-wire/gen"
_ "github.com/clipperhouse/stringer"
)

+ 1
- 1
armor.go View File

@ -22,7 +22,7 @@ func EncodeArmor(blockType string, headers map[string]string, data []byte) strin
if err != nil { if err != nil {
PanicSanity("Error encoding ascii armor: " + err.Error()) PanicSanity("Error encoding ascii armor: " + err.Error())
} }
return string(buf.Bytes())
return buf.String()
} }
func DecodeArmor(armorStr string) (blockType string, headers map[string]string, data []byte, err error) { func DecodeArmor(armorStr string) (blockType string, headers map[string]string, data []byte, err error) {


+ 1
- 1
bcrypt/bcrypt.go View File

@ -50,7 +50,7 @@ func (ih InvalidHashPrefixError) Error() string {
type InvalidCostError int type InvalidCostError int
func (ic InvalidCostError) Error() string { func (ic InvalidCostError) Error() string {
return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost))
return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost)) // nolint: unconvert
} }
const ( const (


+ 4
- 4
embed_test.go View File

@ -73,8 +73,8 @@ func TestEncodeDemo(t *testing.T) {
// Try to encode as binary // Try to encode as binary
b, err := data.ToWire(tc.in) b, err := data.ToWire(tc.in)
if assert.Nil(err, "%d: %#v", i, tc.in) { if assert.Nil(err, "%d: %#v", i, tc.in) {
err := data.FromWire(b, tc.out)
if assert.Nil(err) {
err2 := data.FromWire(b, tc.out)
if assert.Nil(err2) {
assert.Equal(tc.expected, tc.out.String()) assert.Equal(tc.expected, tc.out.String())
} }
} }
@ -82,8 +82,8 @@ func TestEncodeDemo(t *testing.T) {
// Try to encode it as json // Try to encode it as json
j, err := data.ToJSON(tc.in) j, err := data.ToJSON(tc.in)
if assert.Nil(err, "%d: %#v", i, tc.in) { if assert.Nil(err, "%d: %#v", i, tc.in) {
err := data.FromJSON(j, tc.out)
if assert.Nil(err) {
err2 := data.FromJSON(j, tc.out)
if assert.Nil(err2) {
assert.Equal(tc.expected, tc.out.String()) assert.Equal(tc.expected, tc.out.String())
} }
} }


+ 2
- 2
example_test.go View File

@ -20,14 +20,14 @@ import (
"github.com/tendermint/go-crypto" "github.com/tendermint/go-crypto"
) )
func Example_Sha256() {
func ExampleSha256() {
sum := crypto.Sha256([]byte("This is Tendermint")) sum := crypto.Sha256([]byte("This is Tendermint"))
fmt.Printf("%x\n", sum) fmt.Printf("%x\n", sum)
// Output: // Output:
// f91afb642f3d1c87c17eb01aae5cb65c242dfdbe7cf1066cc260f4ce5d33b94e // f91afb642f3d1c87c17eb01aae5cb65c242dfdbe7cf1066cc260f4ce5d33b94e
} }
func Example_Ripemd160() {
func ExampleRipemd160() {
sum := crypto.Ripemd160([]byte("This is Tendermint")) sum := crypto.Ripemd160([]byte("This is Tendermint"))
fmt.Printf("%x\n", sum) fmt.Printf("%x\n", sum)
// Output: // Output:


+ 7
- 8
hd/address.go View File

@ -11,7 +11,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"hash" "hash"
"log"
"math/big" "math/big"
"strconv" "strconv"
"strings" "strings"
@ -86,8 +85,7 @@ func ComputeTxId(rawTxHex string) string {
return HexEncode(ReverseBytes(CalcHash256(HexDecode(rawTxHex)))) return HexEncode(ReverseBytes(CalcHash256(HexDecode(rawTxHex))))
} }
// Private methods...
/*
func printKeyInfo(privKeyBytes []byte, pubKeyBytes []byte, chain []byte) { func printKeyInfo(privKeyBytes []byte, pubKeyBytes []byte, chain []byte) {
if pubKeyBytes == nil { if pubKeyBytes == nil {
pubKeyBytes = PubKeyBytesFromPrivKeyBytes(privKeyBytes, true) pubKeyBytes = PubKeyBytesFromPrivKeyBytes(privKeyBytes, true)
@ -99,6 +97,7 @@ func printKeyInfo(privKeyBytes []byte, pubKeyBytes []byte, chain []byte) {
addr, addr,
HexEncode(chain)) HexEncode(chain))
} }
*/
func DerivePrivateKeyForPath(privKeyBytes []byte, chain []byte, path string) []byte { func DerivePrivateKeyForPath(privKeyBytes []byte, chain []byte, path string) []byte {
data := privKeyBytes data := privKeyBytes
@ -144,7 +143,7 @@ func DerivePublicKeyForPath(pubKeyBytes []byte, chain []byte, path string) []byt
} }
func DerivePrivateKey(privKeyBytes []byte, chain []byte, i uint32, prime bool) ([]byte, []byte) { func DerivePrivateKey(privKeyBytes []byte, chain []byte, i uint32, prime bool) ([]byte, []byte) {
data := []byte{}
var data []byte
if prime { if prime {
i = i | 0x80000000 i = i | 0x80000000
data = append([]byte{byte(0)}, privKeyBytes...) data = append([]byte{byte(0)}, privKeyBytes...)
@ -177,11 +176,11 @@ func addPoints(a []byte, b []byte) []byte {
panic(err) panic(err)
} }
sumX, sumY := btcec.S256().Add(ap.X, ap.Y, bp.X, bp.Y) sumX, sumY := btcec.S256().Add(ap.X, ap.Y, bp.X, bp.Y)
sum := (*btcec.PublicKey)(&btcec.PublicKey{
sum := &btcec.PublicKey{
Curve: btcec.S256(), Curve: btcec.S256(),
X: sumX, X: sumX,
Y: sumY, Y: sumY,
})
}
return sum.SerializeCompressed() return sum.SerializeCompressed()
} }
@ -248,11 +247,11 @@ func WIFFromPrivKeyBytes(privKeyBytes []byte, compress bool) string {
func PubKeyBytesFromPrivKeyBytes(privKeyBytes []byte, compress bool) (pubKeyBytes []byte) { func PubKeyBytesFromPrivKeyBytes(privKeyBytes []byte, compress bool) (pubKeyBytes []byte) {
x, y := btcec.S256().ScalarBaseMult(privKeyBytes) x, y := btcec.S256().ScalarBaseMult(privKeyBytes)
pub := (*btcec.PublicKey)(&btcec.PublicKey{
pub := &btcec.PublicKey{
Curve: btcec.S256(), Curve: btcec.S256(),
X: x, X: x,
Y: y, Y: y,
})
}
if compress { if compress {
return pub.SerializeCompressed() return pub.SerializeCompressed()


+ 13
- 9
hd/hd_test.go View File

@ -2,9 +2,9 @@ package hd
import ( import (
"bytes" "bytes"
"crypto/hmac"
"crypto/sha512"
"encoding/binary"
//"crypto/hmac"
//"crypto/sha512"
//"encoding/binary"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
@ -15,10 +15,10 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tyler-smith/go-bip39" "github.com/tyler-smith/go-bip39"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/mndrix/btcutil"
"github.com/tyler-smith/go-bip32"
//"github.com/btcsuite/btcd/chaincfg"
//"github.com/btcsuite/btcutil/hdkeychain"
//"github.com/mndrix/btcutil"
//"github.com/tyler-smith/go-bip32"
"github.com/tendermint/go-crypto" "github.com/tendermint/go-crypto"
) )
@ -33,7 +33,7 @@ type addrData struct {
} }
// NOTE: atom fundraiser address // NOTE: atom fundraiser address
var hdPath string = "m/44'/118'/0'/0/0"
// var hdPath string = "m/44'/118'/0'/0/0"
var hdToAddrTable []addrData var hdToAddrTable []addrData
func init() { func init() {
@ -109,12 +109,14 @@ func TestReverseBytes(t *testing.T) {
} }
} }
/*
func ifExit(err error, n int) { func ifExit(err error, n int) {
if err != nil { if err != nil {
fmt.Println(n, err) fmt.Println(n, err)
os.Exit(1) os.Exit(1)
} }
} }
*/
func gocrypto(seed []byte) ([]byte, []byte, []byte) { func gocrypto(seed []byte) ([]byte, []byte, []byte) {
@ -131,6 +133,7 @@ func gocrypto(seed []byte) ([]byte, []byte, []byte) {
return HexDecode(priv), privBytes, pubBytes return HexDecode(priv), privBytes, pubBytes
} }
/*
func btcsuite(seed []byte) ([]byte, []byte, []byte) { func btcsuite(seed []byte) ([]byte, []byte, []byte) {
fmt.Println("HD") fmt.Println("HD")
masterKey, err := hdkeychain.NewMaster(seed, &chaincfg.MainNetParams) masterKey, err := hdkeychain.NewMaster(seed, &chaincfg.MainNetParams)
@ -207,9 +210,9 @@ func tylerSmith(seed []byte) ([]byte, []byte, []byte) {
pub := k.PublicKey().Key pub := k.PublicKey().Key
return masterKey.Key, priv, pub return masterKey.Key, priv, pub
} }
*/
// Benchmarks // Benchmarks
var revBytesCases = [][]byte{ var revBytesCases = [][]byte{
nil, nil,
[]byte(""), []byte(""),
@ -238,5 +241,6 @@ func BenchmarkReverseBytes(b *testing.B) {
// sink is necessary to ensure if the compiler tries // sink is necessary to ensure if the compiler tries
// to smart, that it won't optimize away the benchmarks. // to smart, that it won't optimize away the benchmarks.
if sink != nil { if sink != nil {
_ = sink
} }
} }

+ 3
- 9
keys/cryptostore/holder.go View File

@ -24,15 +24,9 @@ func New(coder Encoder, store keys.Storage, codec keys.Codec) Manager {
} }
} }
// exists just to make sure we fulfill the Signer interface
func (s Manager) assertSigner() keys.Signer {
return s
}
// exists just to make sure we fulfill the Manager interface
func (s Manager) assertKeyManager() keys.Manager {
return s
}
// assert Manager satisfies keys.Signer and keys.Manager interfaces
var _ keys.Signer = Manager{}
var _ keys.Manager = Manager{}
// Create adds a new key to the storage engine, returning error if // Create adds a new key to the storage engine, returning error if
// another key already stored under this name // another key already stored under this name


+ 7
- 7
keys/cryptostore/holder_test.go View File

@ -50,22 +50,22 @@ func TestKeyManagement(t *testing.T) {
assert.NotNil(err) assert.NotNil(err)
// list shows them in order // list shows them in order
keys, err := cstore.List()
keyS, err := cstore.List()
require.Nil(err) require.Nil(err)
require.Equal(2, len(keys))
require.Equal(2, len(keyS))
// note these are in alphabetical order // note these are in alphabetical order
assert.Equal(n2, keys[0].Name)
assert.Equal(n1, keys[1].Name)
assert.Equal(i2.PubKey, keys[0].PubKey)
assert.Equal(n2, keyS[0].Name)
assert.Equal(n1, keyS[1].Name)
assert.Equal(i2.PubKey, keyS[0].PubKey)
// deleting a key removes it // deleting a key removes it
err = cstore.Delete("bad name", "foo") err = cstore.Delete("bad name", "foo")
require.NotNil(err) require.NotNil(err)
err = cstore.Delete(n1, p1) err = cstore.Delete(n1, p1)
require.Nil(err) require.Nil(err)
keys, err = cstore.List()
keyS, err = cstore.List()
require.Nil(err) require.Nil(err)
assert.Equal(1, len(keys))
assert.Equal(1, len(keyS))
_, err = cstore.Get(n1) _, err = cstore.Get(n1)
assert.NotNil(err) assert.NotNil(err)


+ 2
- 1
keys/server/helpers.go View File

@ -5,6 +5,7 @@ for key management, transaction signing, and query validation.
Please read the README and godoc to see how to Please read the README and godoc to see how to
configure the server for your application. configure the server for your application.
*/ */
package server package server
import ( import (
@ -12,8 +13,8 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
data "github.com/tendermint/go-wire/data"
"github.com/tendermint/go-crypto/keys/server/types" "github.com/tendermint/go-crypto/keys/server/types"
data "github.com/tendermint/go-wire/data"
"github.com/pkg/errors" "github.com/pkg/errors"
) )


+ 9
- 15
keys/storage/filestorage/main.go View File

@ -22,13 +22,14 @@ import (
const ( const (
// BlockType is the type of block. // BlockType is the type of block.
BlockType = "Tendermint Light Client" BlockType = "Tendermint Light Client"
// PrivExt is the extension for private keys. // PrivExt is the extension for private keys.
PrivExt = "tlc" PrivExt = "tlc"
// PubExt is the extensions for public keys. // PubExt is the extensions for public keys.
PubExt = "pub" PubExt = "pub"
keyPerm = os.FileMode(0600) keyPerm = os.FileMode(0600)
pubPerm = os.FileMode(0644)
// pubPerm = os.FileMode(0644)
dirPerm = os.FileMode(0700) dirPerm = os.FileMode(0700)
) )
@ -51,10 +52,8 @@ func New(dir string) FileStore {
return FileStore{dir} return FileStore{dir}
} }
// assertStorage just makes sure we implement the proper Storage interface
func (s FileStore) assertStorage() keys.Storage {
return s
}
// assert FileStore satisfies keys.Storage
var _ keys.Storage = FileStore{}
// Put creates two files, one with the public info as json, the other // Put creates two files, one with the public info as json, the other
// with the (encoded) private key as gpg ascii-armor style // with the (encoded) private key as gpg ascii-armor style
@ -90,11 +89,10 @@ func (s FileStore) Get(name string) (salt []byte, key []byte, info keys.Info, er
// Info for all keys located in this directory. // Info for all keys located in this directory.
func (s FileStore) List() (keys.Infos, error) { func (s FileStore) List() (keys.Infos, error) {
dir, err := os.Open(s.keyDir) dir, err := os.Open(s.keyDir)
defer dir.Close()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "List Keys") return nil, errors.Wrap(err, "List Keys")
} }
defer dir.Close()
names, err := dir.Readdirnames(0) names, err := dir.Readdirnames(0)
if err != nil { if err != nil {
@ -142,11 +140,10 @@ func (s FileStore) nameToPaths(name string) (pub, priv string) {
func readInfo(path string) (info keys.Info, err error) { func readInfo(path string) (info keys.Info, err error) {
f, err := os.Open(path) f, err := os.Open(path)
defer f.Close()
if err != nil { if err != nil {
return info, errors.Wrap(err, "Reading data") return info, errors.Wrap(err, "Reading data")
} }
defer f.Close()
d, err := ioutil.ReadAll(f) d, err := ioutil.ReadAll(f)
if err != nil { if err != nil {
@ -171,11 +168,10 @@ func readInfo(path string) (info keys.Info, err error) {
func read(path string) (salt, key []byte, name string, err error) { func read(path string) (salt, key []byte, name string, err error) {
f, err := os.Open(path) f, err := os.Open(path)
defer f.Close()
if err != nil { if err != nil {
return nil, nil, "", errors.Wrap(err, "Reading data") return nil, nil, "", errors.Wrap(err, "Reading data")
} }
defer f.Close()
d, err := ioutil.ReadAll(f) d, err := ioutil.ReadAll(f)
if err != nil { if err != nil {
@ -209,11 +205,10 @@ func read(path string) (salt, key []byte, name string, err error) {
func writeInfo(path string, info keys.Info) error { func writeInfo(path string, info keys.Info) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, keyPerm) f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, keyPerm)
defer f.Close()
if err != nil { if err != nil {
return errors.Wrap(err, "Writing data") return errors.Wrap(err, "Writing data")
} }
defer f.Close()
headers := map[string]string{"name": info.Name} headers := map[string]string{"name": info.Name}
text := crypto.EncodeArmor(BlockType, headers, info.PubKey.Bytes()) text := crypto.EncodeArmor(BlockType, headers, info.PubKey.Bytes())
@ -224,11 +219,10 @@ func writeInfo(path string, info keys.Info) error {
func write(path, name string, salt, key []byte) error { func write(path, name string, salt, key []byte) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, keyPerm) f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, keyPerm)
defer f.Close()
if err != nil { if err != nil {
return errors.Wrap(err, "Writing data") return errors.Wrap(err, "Writing data")
} }
defer f.Close()
headers := map[string]string{ headers := map[string]string{
"name": name, "name": name,


+ 2
- 4
keys/storage/memstorage/main.go View File

@ -24,10 +24,8 @@ func New() MemStore {
return MemStore{} return MemStore{}
} }
// assertStorage just makes sure we implement the Storage interface
func (s MemStore) assertStorage() keys.Storage {
return s
}
// assert MemStore satisfies keys.Storage
var _ keys.Storage = MemStore{}
// Put adds the given key, returns an error if it another key // Put adds the given key, returns an error if it another key
// is already stored under this name // is already stored under this name


+ 2
- 2
keys/wordcodec_test.go View File

@ -119,8 +119,8 @@ func TestCheckInvalidLists(t *testing.T) {
w, err := codec.BytesToWords(data) w, err := codec.BytesToWords(data)
if tc.valid { if tc.valid {
assert.Nil(err, "%d: %+v", i, err) assert.Nil(err, "%d: %+v", i, err)
b, err := codec.WordsToBytes(w)
assert.Nil(err, "%d: %+v", i, err)
b, err1 := codec.WordsToBytes(w)
assert.Nil(err1, "%d: %+v", i, err1)
assert.Equal(data, b) assert.Equal(data, b)
} else { } else {
assert.NotNil(err, "%d", i) assert.NotNil(err, "%d", i)


+ 7
- 7
keys/wordlist/wordlist.go View File

@ -204,9 +204,9 @@ func AssetNames() []string {
// _bindata is a table, holding each asset generator, mapped to its name. // _bindata is a table, holding each asset generator, mapped to its name.
var _bindata = map[string]func() (*asset, error){ var _bindata = map[string]func() (*asset, error){
"keys/wordlist/chinese_simplified.txt": keysWordlistChinese_simplifiedTxt, "keys/wordlist/chinese_simplified.txt": keysWordlistChinese_simplifiedTxt,
"keys/wordlist/english.txt": keysWordlistEnglishTxt,
"keys/wordlist/japanese.txt": keysWordlistJapaneseTxt,
"keys/wordlist/spanish.txt": keysWordlistSpanishTxt,
"keys/wordlist/english.txt": keysWordlistEnglishTxt,
"keys/wordlist/japanese.txt": keysWordlistJapaneseTxt,
"keys/wordlist/spanish.txt": keysWordlistSpanishTxt,
} }
// AssetDir returns the file names below a certain // AssetDir returns the file names below a certain
@ -248,13 +248,14 @@ type bintree struct {
Func func() (*asset, error) Func func() (*asset, error)
Children map[string]*bintree Children map[string]*bintree
} }
var _bintree = &bintree{nil, map[string]*bintree{ var _bintree = &bintree{nil, map[string]*bintree{
"keys": &bintree{nil, map[string]*bintree{ "keys": &bintree{nil, map[string]*bintree{
"wordlist": &bintree{nil, map[string]*bintree{ "wordlist": &bintree{nil, map[string]*bintree{
"chinese_simplified.txt": &bintree{keysWordlistChinese_simplifiedTxt, map[string]*bintree{}}, "chinese_simplified.txt": &bintree{keysWordlistChinese_simplifiedTxt, map[string]*bintree{}},
"english.txt": &bintree{keysWordlistEnglishTxt, map[string]*bintree{}},
"japanese.txt": &bintree{keysWordlistJapaneseTxt, map[string]*bintree{}},
"spanish.txt": &bintree{keysWordlistSpanishTxt, map[string]*bintree{}},
"english.txt": &bintree{keysWordlistEnglishTxt, map[string]*bintree{}},
"japanese.txt": &bintree{keysWordlistJapaneseTxt, map[string]*bintree{}},
"spanish.txt": &bintree{keysWordlistSpanishTxt, map[string]*bintree{}},
}}, }},
}}, }},
}} }}
@ -305,4 +306,3 @@ func _filePath(dir, name string) string {
cannonicalName := strings.Replace(name, "\\", "/", -1) cannonicalName := strings.Replace(name, "\\", "/", -1)
return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...) return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...)
} }

Loading…
Cancel
Save