Fix make lint warnings (#417)

fixed make lint warnings
cleared linter_exclude_list.txt
removed some commented code
fixed comments from #388
This commit is contained in:
b00ris 2017-10-20 12:06:22 +03:00 committed by Ivan Tomilov
parent ad9a8777a8
commit e911666b5d
41 changed files with 297 additions and 314 deletions

View file

@ -84,51 +84,51 @@ lint-deps:
gometalinter --install
lint-cur:
gometalinter --disable-all --enable=deadcode extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
gometalinter --disable-all --enable=deadcode $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
lint: ##@tests Run meta linter on code
@echo "Linter: go vet\n--------------------"
@gometalinter --disable-all --enable=vet extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=vet $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: go vet --shadow\n--------------------"
@gometalinter --disable-all --enable=vetshadow extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=vetshadow $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: gofmt\n--------------------"
@gometalinter --disable-all --enable=gofmt extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=gofmt $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: goimports\n--------------------"
@gometalinter --disable-all --enable=goimports extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=goimports $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: golint\n--------------------"
@gometalinter --disable-all --enable=golint extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=golint $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: deadcode\n--------------------"
@gometalinter --disable-all --enable=deadcode extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=deadcode $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: misspell\n--------------------"
@gometalinter --disable-all --enable=misspell extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=misspell $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: unparam\n--------------------"
@gometalinter --disable-all --deadline 45s --enable=unparam extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --deadline 45s --enable=unparam $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: unused\n--------------------"
@gometalinter --disable-all --deadline 45s --enable=unused extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --deadline 45s --enable=unused $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: gocyclo\n--------------------"
@gometalinter --disable-all --enable=gocyclo extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=gocyclo --cyclo-over=20 $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: errcheck\n--------------------"
@gometalinter --disable-all --enable=errcheck extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=errcheck $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: dupl\n--------------------"
@gometalinter --disable-all --enable=dupl extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --exclude='.*_test.go' --disable-all --enable=dupl --dupl-threshold=100 extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: ineffassign\n--------------------"
@gometalinter --disable-all --enable=ineffassign extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=ineffassign $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: interfacer\n--------------------"
@gometalinter --disable-all --enable=interfacer extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=interfacer $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: unconvert\n--------------------"
@gometalinter --disable-all --enable=unconvert extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=unconvert $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: goconst\n--------------------"
@gometalinter --disable-all --enable=goconst extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=goconst $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: staticcheck\n--------------------"
@gometalinter --disable-all --deadline 45s --enable=staticcheck extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --deadline 45s --enable=staticcheck $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: gas\n--------------------"
@gometalinter --disable-all --enable=gas extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=gas $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: varcheck\n--------------------"
@gometalinter --disable-all --deadline 60s --enable=varcheck extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --deadline 60s --enable=varcheck $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: structcheck\n--------------------"
@gometalinter --disable-all --enable=structcheck extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --enable=structcheck $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@echo "Linter: gosimple\n--------------------"
@gometalinter --disable-all --deadline 45s --enable=gosimple extkeys cmd/... geth/... | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
@gometalinter $(LINT_EXCLUDE) --disable-all --deadline 45s --enable=gosimple $(LINT_FOLDERS) | grep -v -f ./static/config/linter_exclude_list.txt || echo "OK!"
mock-install: ##@other Install mocking tools
go get -u github.com/golang/mock/mockgen
@ -158,3 +158,7 @@ ci: mock-install mock test-coverage test-e2e ##@tests Run all tests in CI
clean: ##@other Cleanup
rm -fr build/bin/*
rm coverage.out coverage-all.out coverage.html
LINT_EXCLUDE := --exclude='.*_mock.go' --exclude='geth/jail/doc.go'
LINT_FOLDERS := extkeys cmd/... geth/... e2e/...

View file

@ -14,6 +14,7 @@ import (
"github.com/status-im/status-go/helpers/profiling"
)
//GenerateConfig for status node
//export GenerateConfig
func GenerateConfig(datadir *C.char, networkID C.int, devMode C.int) *C.char {
config, err := params.NewNodeConfig(C.GoString(datadir), uint64(networkID), devMode == 1)
@ -29,6 +30,7 @@ func GenerateConfig(datadir *C.char, networkID C.int, devMode C.int) *C.char {
return C.CString(string(outBytes))
}
//StartNode - start Status node
//export StartNode
func StartNode(configJSON *C.char) *C.char {
config, err := params.LoadNodeConfig(C.GoString(configJSON))
@ -40,12 +42,14 @@ func StartNode(configJSON *C.char) *C.char {
return makeJSONResponse(err)
}
//StopNode - stop status node
//export StopNode
func StopNode() *C.char {
_, err := statusAPI.StopNodeAsync()
return makeJSONResponse(err)
}
//ValidateNodeConfig validates config for status node
//export ValidateNodeConfig
func ValidateNodeConfig(configJSON *C.char) *C.char {
var resp common.APIDetailedResponse
@ -88,52 +92,24 @@ func ValidateNodeConfig(configJSON *C.char) *C.char {
return C.CString(string(respJSON))
}
//ResetChainData remove chain data from data directory
//export ResetChainData
func ResetChainData() *C.char {
_, err := statusAPI.ResetChainDataAsync()
return makeJSONResponse(err)
}
//CallRPC calls status node via rpc
//export CallRPC
func CallRPC(inputJSON *C.char) *C.char {
outputJSON := statusAPI.CallRPC(C.GoString(inputJSON))
return C.CString(outputJSON)
}
//export ResumeNode
func ResumeNode() *C.char {
err := fmt.Errorf("%v: %v", common.ErrDeprecatedMethod.Error(), "ResumeNode")
return makeJSONResponse(err)
}
//export StopNodeRPCServer
func StopNodeRPCServer() *C.char {
err := fmt.Errorf("%v: %v", common.ErrDeprecatedMethod.Error(), "StopNodeRPCServer")
return makeJSONResponse(err)
}
//export StartNodeRPCServer
func StartNodeRPCServer() *C.char {
err := fmt.Errorf("%v: %v", common.ErrDeprecatedMethod.Error(), "StartNodeRPCServer")
return makeJSONResponse(err)
}
//export PopulateStaticPeers
func PopulateStaticPeers() *C.char {
err := fmt.Errorf("%v: %v", common.ErrDeprecatedMethod.Error(), "PopulateStaticPeers")
return makeJSONResponse(err)
}
//export AddPeer
func AddPeer(url *C.char) *C.char {
err := fmt.Errorf("%v: %v", common.ErrDeprecatedMethod.Error(), "AddPeer")
return makeJSONResponse(err)
}
//CreateAccount is equivalent to creating an account from the command line,
// just modified to handle the function arg passing
//export CreateAccount
func CreateAccount(password *C.char) *C.char {
// This is equivalent to creating an account from the command line,
// just modified to handle the function arg passing
address, pubKey, mnemonic, err := statusAPI.CreateAccount(C.GoString(password))
errString := ""
@ -152,6 +128,7 @@ func CreateAccount(password *C.char) *C.char {
return C.CString(string(outBytes))
}
//CreateChildAccount creates sub-account
//export CreateChildAccount
func CreateChildAccount(parentAddress, password *C.char) *C.char {
address, pubKey, err := statusAPI.CreateChildAccount(C.GoString(parentAddress), C.GoString(password))
@ -171,6 +148,7 @@ func CreateChildAccount(parentAddress, password *C.char) *C.char {
return C.CString(string(outBytes))
}
//RecoverAccount re-creates master key using given details
//export RecoverAccount
func RecoverAccount(password, mnemonic *C.char) *C.char {
address, pubKey, err := statusAPI.RecoverAccount(C.GoString(password), C.GoString(mnemonic))
@ -191,27 +169,29 @@ func RecoverAccount(password, mnemonic *C.char) *C.char {
return C.CString(string(outBytes))
}
//VerifyAccountPassword verifies account password
//export VerifyAccountPassword
func VerifyAccountPassword(keyStoreDir, address, password *C.char) *C.char {
_, err := statusAPI.VerifyAccountPassword(C.GoString(keyStoreDir), C.GoString(address), C.GoString(password))
return makeJSONResponse(err)
}
//Login loads a key file (for a given address), tries to decrypt it using the password, to verify ownership
// if verified, purges all the previous identities from Whisper, and injects verified key as shh identity
//export Login
func Login(address, password *C.char) *C.char {
// loads a key file (for a given address), tries to decrypt it using the password, to verify ownership
// if verified, purges all the previous identities from Whisper, and injects verified key as shh identity
err := statusAPI.SelectAccount(C.GoString(address), C.GoString(password))
return makeJSONResponse(err)
}
//Logout is equivalent to clearing whisper identities
//export Logout
func Logout() *C.char {
// This is equivalent to clearing whisper identities
err := statusAPI.Logout()
return makeJSONResponse(err)
}
//CompleteTransaction instructs backend to complete sending of a given transaction
//export CompleteTransaction
func CompleteTransaction(id, password *C.char) *C.char {
txHash, err := statusAPI.CompleteTransaction(common.QueuedTxID(C.GoString(id)), C.GoString(password))
@ -236,6 +216,7 @@ func CompleteTransaction(id, password *C.char) *C.char {
return C.CString(string(outBytes))
}
//CompleteTransactions instructs backend to complete sending of multiple transactions
//export CompleteTransactions
func CompleteTransactions(ids, password *C.char) *C.char {
out := common.CompleteTransactionsResult{}
@ -274,6 +255,7 @@ func CompleteTransactions(ids, password *C.char) *C.char {
return C.CString(string(outBytes))
}
//DiscardTransaction discards a given transaction from transaction queue
//export DiscardTransaction
func DiscardTransaction(id *C.char) *C.char {
err := statusAPI.DiscardTransaction(common.QueuedTxID(C.GoString(id)))
@ -297,6 +279,7 @@ func DiscardTransaction(id *C.char) *C.char {
return C.CString(string(outBytes))
}
//DiscardTransactions discards given multiple transactions from transaction queue
//export DiscardTransactions
func DiscardTransactions(ids *C.char) *C.char {
out := common.DiscardTransactionsResult{}
@ -334,37 +317,43 @@ func DiscardTransactions(ids *C.char) *C.char {
return C.CString(string(outBytes))
}
//InitJail setup initial JavaScript
//export InitJail
func InitJail(js *C.char) {
statusAPI.JailBaseJS(C.GoString(js))
}
//Parse creates a new jail cell context and executes provided JavaScript code
//export Parse
func Parse(chatID *C.char, js *C.char) *C.char {
res := statusAPI.JailParse(C.GoString(chatID), C.GoString(js))
return C.CString(res)
}
//Call executes given JavaScript function
//export Call
func Call(chatID *C.char, path *C.char, params *C.char) *C.char {
res := statusAPI.JailCall(C.GoString(chatID), C.GoString(path), C.GoString(params))
return C.CString(res)
}
//StartCPUProfile runs pprof for cpu
//export StartCPUProfile
func StartCPUProfile(dataDir *C.char) *C.char {
err := profiling.StartCPUProfile(C.GoString(dataDir))
return makeJSONResponse(err)
}
//StopCPUProfiling stops pprof for cpu
//export StopCPUProfiling
func StopCPUProfiling() *C.char {
func StopCPUProfiling() *C.char { //nolint: deadcode
err := profiling.StopCPUProfile()
return makeJSONResponse(err)
}
//WriteHeapProfile starts pprof for heap
//export WriteHeapProfile
func WriteHeapProfile(dataDir *C.char) *C.char {
func WriteHeapProfile(dataDir *C.char) *C.char { //nolint: deadcode
err := profiling.WriteHeapFile(C.GoString(dataDir))
return makeJSONResponse(err)
}
@ -384,6 +373,7 @@ func makeJSONResponse(err error) *C.char {
return C.CString(string(outBytes))
}
// Notify sends push notification by given token
//export Notify
func Notify(token *C.char) *C.char {
res := statusAPI.Notify(C.GoString(token))

View file

@ -45,12 +45,6 @@ var (
Value: params.RopstenNetworkID,
}
// LightEthEnabledFlag flags whether LES is enabled or not
LightEthEnabledFlag = cli.BoolFlag{
Name: "les",
Usage: "LES protocol enabled",
}
// WhisperEnabledFlag flags whether Whisper is enabled or not
WhisperEnabledFlag = cli.BoolFlag{
Name: "shh",

View file

@ -19,13 +19,15 @@ import (
"fmt"
"context"
"github.com/status-im/status-go/geth/account"
"github.com/status-im/status-go/geth/common"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/geth/txqueue"
"github.com/status-im/status-go/static"
. "github.com/status-im/status-go/testing"
. "github.com/status-im/status-go/testing" //nolint: golint
"github.com/stretchr/testify/require"
)
@ -197,7 +199,8 @@ func testGetDefaultConfig(t *testing.T) bool {
return true
}
// @TODO(adam): quarantined this test until it uses a different directory.
//@TODO(adam): quarantined this test until it uses a different directory.
//nolint: deadcode
func testResetChainData(t *testing.T) bool {
t.Skip()
@ -221,7 +224,7 @@ func testResetChainData(t *testing.T) bool {
return true
}
func testStopResumeNode(t *testing.T) bool {
func testStopResumeNode(t *testing.T) bool { //nolint: gocyclo
// to make sure that we start with empty account (which might get populated during previous tests)
if err := statusAPI.Logout(); err != nil {
t.Fatal(err)
@ -326,14 +329,14 @@ func testCallRPC(t *testing.T) bool {
rawResponse := CallRPC(C.CString(`{"jsonrpc":"2.0","method":"web3_sha3","params":["0x68656c6c6f20776f726c64"],"id":64}`))
received := C.GoString(rawResponse)
if expected != received {
t.Errorf("unexpected reponse: expected: %v, got: %v", expected, received)
t.Errorf("unexpected response: expected: %v, got: %v", expected, received)
return false
}
return true
}
func testCreateChildAccount(t *testing.T) bool {
func testCreateChildAccount(t *testing.T) bool { //nolint: gocyclo
// to make sure that we start with empty account (which might get populated during previous tests)
if err := statusAPI.Logout(); err != nil {
t.Fatal(err)
@ -469,7 +472,7 @@ func testCreateChildAccount(t *testing.T) bool {
return true
}
func testRecoverAccount(t *testing.T) bool {
func testRecoverAccount(t *testing.T) bool { //nolint: gocyclo
keyStore, _ := statusAPI.NodeManager().AccountKeyStore()
// create an account
@ -582,7 +585,7 @@ func testRecoverAccount(t *testing.T) bool {
return true
}
func testAccountSelect(t *testing.T) bool {
func testAccountSelect(t *testing.T) bool { //nolint: gocyclo
// test to see if the account was injected in whisper
whisperService, err := statusAPI.NodeManager().WhisperService()
if err != nil {
@ -770,7 +773,7 @@ func testCompleteTransaction(t *testing.T) bool {
})
// this call blocks, up until Complete Transaction is called
txCheckHash, err := statusAPI.SendTransaction(nil, common.SendTxArgs{
txCheckHash, err := statusAPI.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -801,7 +804,7 @@ func testCompleteTransaction(t *testing.T) bool {
return true
}
func testCompleteMultipleQueuedTransactions(t *testing.T) bool {
func testCompleteMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocyclo
txQueue := statusAPI.TxQueueManager().TransactionQueue()
txQueue.Reset()
@ -835,7 +838,7 @@ func testCompleteMultipleQueuedTransactions(t *testing.T) bool {
// this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called
sendTx := func() {
txHashCheck, err := statusAPI.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := statusAPI.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -934,7 +937,7 @@ func testCompleteMultipleQueuedTransactions(t *testing.T) bool {
return true
}
func testDiscardTransaction(t *testing.T) bool {
func testDiscardTransaction(t *testing.T) bool { //nolint: gocyclo
txQueue := statusAPI.TxQueueManager().TransactionQueue()
txQueue.Reset()
@ -1018,7 +1021,7 @@ func testDiscardTransaction(t *testing.T) bool {
})
// this call blocks, and should return when DiscardQueuedTransaction() is called
txHashCheck, err := statusAPI.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := statusAPI.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -1046,7 +1049,7 @@ func testDiscardTransaction(t *testing.T) bool {
return true
}
func testDiscardMultipleQueuedTransactions(t *testing.T) bool {
func testDiscardMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocyclo
txQueue := statusAPI.TxQueueManager().TransactionQueue()
txQueue.Reset()
@ -1109,7 +1112,7 @@ func testDiscardMultipleQueuedTransactions(t *testing.T) bool {
// this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called
sendTx := func() {
txHashCheck, err := statusAPI.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := statusAPI.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -1355,9 +1358,6 @@ func startTestNode(t *testing.T) <-chan struct{} {
t.Log("Node started, but we wait till it be ready")
}
if envelope.Type == signal.EventNodeReady {
// manually add static nodes (LES auto-discovery is not stable yet)
PopulateStaticPeers()
// sync
if syncRequired {
t.Logf("Sync is required, it will take %d seconds", TestConfig.Node.SyncSeconds)
@ -1387,6 +1387,7 @@ func startTestNode(t *testing.T) <-chan struct{} {
return waitForNodeStart
}
//nolint: deadcode
func testValidateNodeConfig(t *testing.T, config string, fn func(common.APIDetailedResponse)) {
result := ValidateNodeConfig(C.CString(config))

View file

@ -37,7 +37,7 @@ func (s *APITestSuite) SetupTest() {
func (s *APITestSuite) TestCHTUpdate() {
tmpDir, err := ioutil.TempDir(os.TempDir(), "cht-updates")
s.NoError(err)
defer os.RemoveAll(tmpDir)
defer os.RemoveAll(tmpDir) //nolint: errcheck
configJSON := `{
"NetworkId": ` + strconv.Itoa(params.RopstenNetworkID) + `,
@ -45,14 +45,9 @@ func (s *APITestSuite) TestCHTUpdate() {
"LogLevel": "INFO",
"RPCEnabled": true
}`
//nodeConfig, err := params.LoadNodeConfig(configJSON)
_, err = params.LoadNodeConfig(configJSON)
s.NoError(err)
// start node
//nodeConfig.DevMode = true
//s.api.StartNode(nodeConfig)
//s.api.StopNode()
// TODO(tiabc): Test that CHT is really updated.
}
@ -121,7 +116,8 @@ func (s *APITestSuite) TestRaceConditions() {
}
time.Sleep(2 * time.Second) // so that we see some logs
s.api.StopNode() // just in case we have a node running
// just in case we have a node running
s.api.StopNode() //nolint: errcheck
}
func (s *APITestSuite) TestCellsRemovedAfterSwitchAccount() {
@ -137,7 +133,7 @@ func (s *APITestSuite) TestCellsRemovedAfterSwitchAccount() {
require.NoError(err)
err = s.api.StartNode(config)
require.NoError(err)
defer s.api.StopNode()
defer s.api.StopNode() //nolint: errcheck
address1, _, _, err := s.api.AccountManager().CreateAccount(TestConfig.Account1.Password)
require.NoError(err)
@ -149,16 +145,16 @@ func (s *APITestSuite) TestCellsRemovedAfterSwitchAccount() {
require.NoError(err)
for i := 0; i < itersCount; i++ {
_, err := s.api.JailManager().NewCell(getChatId(i))
require.NoError(err)
_, e := s.api.JailManager().NewCell(getChatId(i))
require.NoError(e)
}
err = s.api.SelectAccount(address2, TestConfig.Account2.Password)
require.NoError(err)
for i := 0; i < itersCount; i++ {
_, err := s.api.JailManager().Cell(getChatId(i))
require.Error(err)
_, e := s.api.JailManager().Cell(getChatId(i))
require.Error(e)
}
}
@ -174,7 +170,7 @@ func (s *APITestSuite) TestLogoutRemovesCells() {
require.NoError(err)
err = s.api.StartNode(config)
require.NoError(err)
defer s.api.StopNode()
defer s.api.StopNode() //nolint: errcheck
address1, _, _, err := s.api.AccountManager().CreateAccount(TestConfig.Account1.Password)
require.NoError(err)

View file

@ -94,22 +94,26 @@ func (s *APIBackendTestSuite) TestRaceConditions() {
log.Info("CreateAccount()")
address, pubKey, mnemonic, err := s.Backend.AccountManager().CreateAccount("password")
s.T().Logf("CreateAccount(), error: %v (address: %v, pubKey: %v, mnemonic: %v)", err, address, pubKey, mnemonic)
if err == nil {
// SelectAccount
log.Info("CreateAccount()")
err = s.Backend.AccountManager().SelectAccount(address, "password")
s.T().Logf("SelectAccount(%v, %v), error: %v", address, "password", err)
// CreateChildAccount
log.Info("CreateChildAccount()")
address, pubKey, err := s.Backend.AccountManager().CreateChildAccount(address, "password")
s.T().Logf("CreateAccount(), error: %v (address: %v, pubKey: %v)", err, address, pubKey)
// RecoverAccount
log.Info("RecoverAccount()")
address, pubKey, err = s.Backend.AccountManager().RecoverAccount("password", mnemonic)
s.T().Logf("RecoverAccount(), error: %v (address: %v, pubKey: %v)", err, address, pubKey)
if err != nil {
progress <- struct{}{}
return
}
// SelectAccount
log.Info("CreateAccount()")
err = s.Backend.AccountManager().SelectAccount(address, "password")
s.T().Logf("SelectAccount(%v, %v), error: %v", address, "password", err)
// CreateChildAccount
log.Info("CreateChildAccount()")
address, pubKey, err = s.Backend.AccountManager().CreateChildAccount(address, "password")
s.T().Logf("CreateAccount(), error: %v (address: %v, pubKey: %v)", err, address, pubKey)
// RecoverAccount
log.Info("RecoverAccount()")
address, pubKey, err = s.Backend.AccountManager().RecoverAccount("password", mnemonic)
s.T().Logf("RecoverAccount(), error: %v (address: %v, pubKey: %v)", err, address, pubKey)
progress <- struct{}{}
},
func(config *params.NodeConfig) {

View file

@ -123,8 +123,10 @@ func (s *JailRPCTestSuite) TestContractDeployment() {
var txHash gethcommon.Hash
signal.SetDefaultNodeNotificationHandler(func(jsonEvent string) {
var envelope signal.Envelope
var err error
var (
envelope signal.Envelope
err error
)
err = json.Unmarshal([]byte(jsonEvent), &envelope)
s.NoError(err, "cannot unmarshal JSON: %s", jsonEvent)
@ -280,7 +282,7 @@ func (s *JailRPCTestSuite) TestJailVMPersistence() {
var wg sync.WaitGroup
signal.SetDefaultNodeNotificationHandler(func(jsonEvent string) {
var envelope signal.Envelope
if err := json.Unmarshal([]byte(jsonEvent), &envelope); err != nil {
if e := json.Unmarshal([]byte(jsonEvent), &envelope); e != nil {
s.T().Errorf("cannot unmarshal event's JSON: %s", jsonEvent)
return
}
@ -290,8 +292,8 @@ func (s *JailRPCTestSuite) TestJailVMPersistence() {
//var txHash common.Hash
txID := event["id"].(string)
txHash, err := s.Backend.CompleteTransaction(common.QueuedTxID(txID), TestConfig.Account1.Password)
s.NoError(err, "cannot complete queued transaction[%v]: %v", event["id"], err)
txHash, e := s.Backend.CompleteTransaction(common.QueuedTxID(txID), TestConfig.Account1.Password)
s.NoError(e, "cannot complete queued transaction[%v]: %v", event["id"], e)
s.T().Logf("Transaction complete: https://ropsten.etherscan.io/tx/%s", txHash.Hex())
}
@ -305,8 +307,8 @@ func (s *JailRPCTestSuite) TestJailVMPersistence() {
s.T().Logf("CALL START: %v %v", tc.command, tc.params)
response := jail.Call(testChatID, tc.command, tc.params)
if err := tc.validator(response); err != nil {
s.T().Errorf("failed test validation: %v, err: %v", tc.command, err)
if e := tc.validator(response); e != nil {
s.T().Errorf("failed test validation: %v, err: %v", tc.command, e)
}
s.T().Logf("CALL END: %v %v", tc.command, tc.params)
}(tc)

View file

@ -20,7 +20,6 @@ const (
var (
baseStatusJSCode = string(static.MustAsset("testdata/jail/status.js"))
txJSCode = string(static.MustAsset("testdata/jail/tx-send/tx-send.js"))
)
func TestJailTestSuite(t *testing.T) {
@ -177,6 +176,7 @@ func (s *JailTestSuite) TestJailCellsRemovedAfterStop() {
counter++;
}, 1000);
`)
require.NoError(err)
}
s.jail.Stop()

View file

@ -335,11 +335,11 @@ func (s *ManagerTestSuite) TestRaceConditions() {
progress := make(chan struct{}, cnt)
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
nodeConfig1, err := e2e.MakeTestNodeConfig(params.RopstenNetworkID)
s.NoError(err)
nodeConfig1, e := e2e.MakeTestNodeConfig(params.RopstenNetworkID)
s.NoError(e)
nodeConfig2, err := e2e.MakeTestNodeConfig(params.RinkebyNetworkID)
s.NoError(err)
nodeConfig2, e := e2e.MakeTestNodeConfig(params.RinkebyNetworkID)
s.NoError(e)
nodeConfigs := []*params.NodeConfig{nodeConfig1, nodeConfig2}
@ -446,7 +446,9 @@ func (s *ManagerTestSuite) TestRaceConditions() {
}
time.Sleep(2 * time.Second) // so that we see some logs
nodeStopped, _ := s.NodeManager.StopNode() // just in case we have a node running
nodeStopped, e := s.NodeManager.StopNode() // just in case we have a node running
s.NoError(e)
if nodeStopped != nil {
<-nodeStopped
}
@ -502,6 +504,6 @@ func (s *ManagerTestSuite) TestNodeStartCrash() {
}
// cleanup
s.NodeManager.StopNode()
s.NodeManager.StopNode() //nolint: errcheck
signal.ResetDefaultNodeNotificationHandler()
}

View file

@ -2,8 +2,6 @@ package rpc
import (
"context"
"encoding/json"
"net/http"
"sync"
"testing"
"time"
@ -15,21 +13,6 @@ import (
"github.com/stretchr/testify/suite"
)
type txRequest struct {
Method string `json:"method"`
Version string `json:"jsonrpc"`
ID int `json:"id,omitempty"`
Payload json.RawMessage `json:"params,omitempty"`
}
type service struct {
Handler http.HandlerFunc
}
func (s service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.Handler(w, r)
}
func TestRPCTestSuite(t *testing.T) {
suite.Run(t, new(RPCTestSuite))
}
@ -149,7 +132,7 @@ func (s *RPCTestSuite) TestCallRawResult() {
jsonResult := client.CallRaw(`{"jsonrpc":"2.0","method":"shh_version","params":[],"id":67}`)
s.Equal(`{"jsonrpc":"2.0","id":67,"result":"5.0"}`, jsonResult)
s.NodeManager.StopNode()
s.NodeManager.StopNode() //nolint: errcheck
}
// TestCallContextResult checks if result passed to CallContext

View file

@ -10,7 +10,7 @@ import (
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/status-im/status-go/geth/common"
"github.com/status-im/status-go/geth/params"
. "github.com/status-im/status-go/testing"
. "github.com/status-im/status-go/testing" //nolint: golint
)
// TestNodeOption is a callback passed to StartTestNode which alters its config.

View file

@ -8,6 +8,8 @@ import (
"testing"
"time"
"context"
"github.com/ethereum/go-ethereum/accounts/keystore"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
@ -22,11 +24,6 @@ import (
"github.com/stretchr/testify/suite"
)
const (
txSendFolder = "testdata/jail/tx-send/"
testChatID = "testChat"
)
func TestTransactionsTestSuite(t *testing.T) {
suite.Run(t, new(TransactionsTestSuite))
}
@ -49,12 +46,12 @@ func (s *TransactionsTestSuite) TestCallRPCSendTransaction() {
var txHash gethcommon.Hash
signal.SetDefaultNodeNotificationHandler(func(rawSignal string) {
var signal signal.Envelope
err := json.Unmarshal([]byte(rawSignal), &signal)
var sg signal.Envelope
err := json.Unmarshal([]byte(rawSignal), &sg)
s.NoError(err)
if signal.Type == txqueue.EventTransactionQueued {
event := signal.Event.(map[string]interface{})
if sg.Type == txqueue.EventTransactionQueued {
event := sg.Event.(map[string]interface{})
txID := event["id"].(string)
txHash, err = s.Backend.CompleteTransaction(common.QueuedTxID(txID), TestConfig.Account1.Password)
s.NoError(err, "cannot complete queued transaction %s", txID)
@ -210,7 +207,7 @@ func (s *TransactionsTestSuite) TestSendContractTx() {
byteCode, err := hexutil.Decode(`0x6060604052341561000c57fe5b5b60a58061001b6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680636ffa1caa14603a575bfe5b3415604157fe5b60556004808035906020019091905050606b565b6040518082815260200191505060405180910390f35b60008160020290505b9190505600a165627a7a72305820ccdadd737e4ac7039963b54cee5e5afb25fa859a275252bdcf06f653155228210029`)
s.NoError(err)
txHashCheck, err := s.Backend.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: nil, // marker, contract creation is expected
//Value: (*hexutil.Big)(new(big.Int).Mul(big.NewInt(1), gethcommon.Ether)),
@ -296,7 +293,7 @@ func (s *TransactionsTestSuite) TestSendEtherTx() {
})
// this call blocks, up until Complete Transaction is called
txHashCheck, err := s.Backend.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -377,7 +374,7 @@ func (s *TransactionsTestSuite) TestSendEtherOnStatusChainTx() {
})
// this call blocks, up until Complete Transaction is called
txHashCheck, err := s.Backend.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -433,7 +430,7 @@ func (s *TransactionsTestSuite) TestSendEtherTxUpstream() {
// This call blocks, up until Complete Transaction is called.
// Explicitly not setting Gas to get it estimated.
txHashCheck, err := s.Backend.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
GasPrice: (*hexutil.Big)(big.NewInt(28000000000)),
@ -509,7 +506,7 @@ func (s *TransactionsTestSuite) TestDoubleCompleteQueuedTransactions() {
})
// this call blocks, and should return on *second* attempt to CompleteTransaction (w/ the correct password)
txHashCheck, err := s.Backend.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -590,7 +587,7 @@ func (s *TransactionsTestSuite) TestDiscardQueuedTransaction() {
})
// this call blocks, and should return when DiscardQueuedTransaction() is called
txHashCheck, err := s.Backend.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -641,7 +638,7 @@ func (s *TransactionsTestSuite) TestCompleteMultipleQueuedTransactions() {
// this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called
sendTx := func() {
txHashCheck, err := s.Backend.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -757,7 +754,7 @@ func (s *TransactionsTestSuite) TestDiscardMultipleQueuedTransactions() {
// this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called
sendTx := func() {
txHashCheck, err := s.Backend.SendTransaction(nil, common.SendTxArgs{
txHashCheck, err := s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{
From: common.FromAddress(TestConfig.Account1.Address),
To: common.ToAddress(TestConfig.Account2.Address),
Value: (*hexutil.Big)(big.NewInt(1000000000000)),
@ -861,8 +858,8 @@ func (s *TransactionsTestSuite) TestEvictionOfQueuedTransactions() {
s.Zero(txQueue.Count(), "transaction count should be zero")
for i := 0; i < 10; i++ {
go s.Backend.SendTransaction(nil, common.SendTxArgs{}) // nolint: errcheck
for j := 0; j < 10; j++ {
go s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{}) // nolint: errcheck
}
time.Sleep(2 * time.Second) // FIXME(tiabc): more reliable synchronization to ensure all transactions are enqueued
@ -872,7 +869,7 @@ func (s *TransactionsTestSuite) TestEvictionOfQueuedTransactions() {
s.Equal(10, txQueue.Count(), "transaction count should be 10")
for i := 0; i < txqueue.DefaultTxQueueCap+5; i++ { // stress test by hitting with lots of goroutines
go s.Backend.SendTransaction(nil, common.SendTxArgs{}) // nolint: errcheck
go s.Backend.SendTransaction(context.TODO(), common.SendTxArgs{}) // nolint: errcheck
}
time.Sleep(3 * time.Second)

View file

@ -25,7 +25,6 @@ const (
whisperMessage3 = `test message 4 ("" -> "", anon broadcast)`
whisperMessage4 = `test message 5 ("" -> K1, encrypted anon broadcast)`
whisperMessage5 = `test message 6 (K2 -> K1, signed+encrypted, to us)`
testChatID = "testChat"
)
var (
@ -61,7 +60,7 @@ func (s *WhisperJailTestSuite) GetAccountKey(account struct {
}) (*keystore.Key, string, error) {
accountManager := s.Backend.AccountManager()
_, accountKey1, err := accountManager.AddressToDecryptedAccount(TestConfig.Account1.Address, TestConfig.Account1.Password)
_, accountKey1, err := accountManager.AddressToDecryptedAccount(account.Address, account.Password)
if err != nil {
return nil, "", err
}

View file

@ -253,7 +253,7 @@ func contains(wordList *WordList, e string) bool {
return false
}
func padByteSlice(slice []byte, length int) []byte {
func padByteSlice(slice []byte, length int) []byte { //nolint: unparam
newSlice := make([]byte, length-len(slice))
return append(newSlice, slice...)
}

View file

@ -43,6 +43,7 @@ func splitHMAC(seed, salt []byte) (secretKey, chainCode []byte, err error) {
// paddedAppend appends the src byte slice to dst, returning the new slice.
// If the length of the source is smaller than the passed size, leading zero
// bytes are appended to the dst slice before appending src.
// nolint: unparam
func paddedAppend(size uint, dst, src []byte) []byte {
for i := 0; i < int(size)-len(src); i++ {
dst = append(dst, 0)

View file

@ -156,16 +156,16 @@ func (m *Manager) VerifyAccountPassword(keyStoreDir, address, password string) (
return nil
}
rawKeyFile, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("invalid account key file: %v", err)
rawKeyFile, e := ioutil.ReadFile(path)
if e != nil {
return fmt.Errorf("invalid account key file: %v", e)
}
var accountKey struct {
Address string `json:"address"`
}
if err := json.Unmarshal(rawKeyFile, &accountKey); err != nil {
return fmt.Errorf("failed to read key file: %s", err)
if e := json.Unmarshal(rawKeyFile, &accountKey); e != nil {
return fmt.Errorf("failed to read key file: %s", e)
}
if gethcommon.HexToAddress("0x"+accountKey.Address).Hex() == addressObj.Hex() {
@ -226,7 +226,8 @@ func (m *Manager) SelectAccount(address, password string) error {
return err
}
if err := whisperService.SelectKeyPair(accountKey.PrivateKey); err != nil {
err = whisperService.SelectKeyPair(accountKey.PrivateKey)
if err != nil {
return ErrWhisperIdentityInjectionFailure
}

View file

@ -20,11 +20,11 @@ func TestVerifyAccountPassword(t *testing.T) {
acctManager := account.NewManager(nil)
keyStoreDir, err := ioutil.TempDir(os.TempDir(), "accounts")
require.NoError(t, err)
defer os.RemoveAll(keyStoreDir)
defer os.RemoveAll(keyStoreDir) //nolint: errcheck
emptyKeyStoreDir, err := ioutil.TempDir(os.TempDir(), "accounts_empty")
require.NoError(t, err)
defer os.RemoveAll(emptyKeyStoreDir)
defer os.RemoveAll(emptyKeyStoreDir) //nolint: errcheck
// import account keys
require.NoError(t, common.ImportTestAccount(keyStoreDir, "test-account1.pk"))
@ -97,7 +97,7 @@ func TestVerifyAccountPassword(t *testing.T) {
func TestVerifyAccountPasswordWithAccountBeforeEIP55(t *testing.T) {
keyStoreDir, err := ioutil.TempDir("", "status-accounts-test")
require.NoError(t, err)
defer os.RemoveAll(keyStoreDir)
defer os.RemoveAll(keyStoreDir) //nolint: errcheck
// Import keys and make sure one was created before EIP55 introduction.
err = common.ImportTestAccount(keyStoreDir, "test-account1-before-eip55.pk")

View file

@ -199,6 +199,7 @@ func (api *StatusAPI) JailBaseJS(js string) {
api.b.jailManager.BaseJS(js)
}
// Notify sends a push notification to the device with the given token.
// TODO(oskarth): API package this stuff
func (api *StatusAPI) Notify(token string) string {
log.Debug("Notify", "token", token)

View file

@ -98,7 +98,9 @@ func (m *StatusBackend) onNodeStart(nodeStarted <-chan struct{}, backendReady ch
log.Error("Handler registration failed", "err", err)
}
m.accountManager.ReSelectAccount()
if err := m.accountManager.ReSelectAccount(); err != nil {
log.Error("Reselect account failed", "err", err)
}
log.Info("Account reselected")
close(backendReady)

View file

@ -26,12 +26,15 @@ func newCell(id string, ottoVM *otto.Otto) (*Cell, error) {
lo := loop.New(cellVM)
registerVMHandlers(cellVM, lo)
err := registerVMHandlers(cellVM, lo)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
// start event loop in background
go lo.Run(ctx)
go lo.Run(ctx) //nolint: errcheck
return &Cell{
VM: cellVM,
@ -50,11 +53,7 @@ func registerVMHandlers(v *vm.VM, lo *loop.Loop) error {
}
// FetchAPI functions
if err := fetch.Define(v, lo); err != nil {
return err
}
return nil
return fetch.Define(v, lo)
}
// Stop halts event loop associated with cell.

View file

@ -151,7 +151,7 @@ func (s *CellTestSuite) TestJailFetchPromise() {
body := `{"key": "value"}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(body))
w.Write([]byte(body)) //nolint: errcheck
}))
defer server.Close()
@ -227,7 +227,7 @@ func (s *CellTestSuite) TestJailFetchCatch() {
require.Equal("Error", name.String())
_, err = e.Object().Get("message")
require.NoError(err)
case <-time.After(1 * time.Second):
case <-time.After(3 * time.Second):
require.Fail("test timed out")
}
}
@ -238,7 +238,7 @@ func (s *CellTestSuite) TestJailFetchRace() {
body := `{"key": "value"}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(body))
w.Write([]byte(body)) //nolint: errcheck
}))
defer server.Close()
require := s.Require()
@ -288,7 +288,7 @@ func (s *CellTestSuite) TestJailFetchRace() {
require.Equal("Error", name.String())
_, err = e.Object().Get("message")
require.NoError(err)
case <-time.After(1 * time.Second):
case <-time.After(3 * time.Second):
require.Fail("test timed out")
return
}
@ -309,7 +309,7 @@ func (s *CellTestSuite) TestJailLoopCancel() {
require.NotNil(cell)
var count int
err = cell.Set("__captureResponse", func(val string) otto.Value {
err = cell.Set("__captureResponse", func(val string) otto.Value { //nolint: unparam
count++
return otto.UndefinedValue()
})

View file

@ -37,7 +37,7 @@ func registerHandlers(jail *Jail, cell common.JailCell, chatID string) error {
}
// register send handler
if err = registerHandler("send", makeSendHandler(jail, cell)); err != nil {
if err = registerHandler("send", makeSendHandler(jail)); err != nil {
return err
}
@ -60,11 +60,8 @@ func registerHandlers(jail *Jail, cell common.JailCell, chatID string) error {
return err
}
registerHandler = statusSignals.Object().Set
if err = registerHandler("sendSignal", makeSignalHandler(chatID)); err != nil {
return err
}
return nil
return registerHandler("sendSignal", makeSignalHandler(chatID))
}
// makeAsyncSendHandler returns jeth.sendAsync() handler.
@ -87,8 +84,7 @@ func makeAsyncSendHandler(jail *Jail, cellInt common.JailCell) func(call otto.Fu
}
// makeSendHandler returns jeth.send() and jeth.sendAsync() handler
// TODO(tiabc): get rid of an extra parameter.
func makeSendHandler(jail *Jail, cellInt common.JailCell) func(call otto.FunctionCall) otto.Value {
func makeSendHandler(jail *Jail) func(call otto.FunctionCall) otto.Value {
return func(call otto.FunctionCall) otto.Value {
return jail.Send(call)
}

View file

@ -55,32 +55,42 @@ func (t *fetchTask) Execute(vm *vm.VM, l *loop.Loop) error {
vm.Lock()
defer vm.Unlock()
t.jsRes.Set("status", t.status)
t.jsRes.Set("statusText", t.statusText)
err := t.jsRes.Set("status", t.status)
if err != nil {
return err
}
err = t.jsRes.Set("statusText", t.statusText)
if err != nil {
return err
}
h := mustValue(t.jsRes.Get("headers")).Object()
for k, vs := range t.headers {
for _, v := range vs {
if _, err := h.Call("append", k, v); err != nil {
if _, err = h.Call("append", k, v); err != nil {
return err
}
}
}
t.jsRes.Set("_body", string(t.body))
if _, err := t.cb.Call(otto.NullValue(), arguments...); err != nil {
err = t.jsRes.Set("_body", string(t.body))
if err != nil {
return err
}
return nil
_, err = t.cb.Call(otto.NullValue(), arguments...)
return err
}
func (t *fetchTask) Cancel() {
}
// Define fetch
func Define(vm *vm.VM, l *loop.Loop) error {
return DefineWithHandler(vm, l, nil)
}
//DefineWithHandler fetch with handler
func DefineWithHandler(vm *vm.VM, l *loop.Loop, h http.Handler) error {
if err := promise.Define(vm, l); err != nil {
return err
@ -94,11 +104,12 @@ func DefineWithHandler(vm *vm.VM, l *loop.Loop, h http.Handler) error {
return err
}
if _, err := vm.Run(s); err != nil {
_, err = vm.Run(s)
if err != nil {
return err
}
vm.Set("__private__fetch_execute", func(c otto.FunctionCall) otto.Value {
err = vm.Set("__private__fetch_execute", func(c otto.FunctionCall) otto.Value {
jsReq := c.Argument(0).Object()
jsRes := c.Argument(1).Object()
cb := c.Argument(2)
@ -122,9 +133,9 @@ func DefineWithHandler(vm *vm.VM, l *loop.Loop, h http.Handler) error {
go func() {
defer l.Ready(t)
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
t.err = err
req, rqErr := http.NewRequest(method, urlStr, body)
if rqErr != nil {
t.err = rqErr
return
}
@ -138,15 +149,15 @@ func DefineWithHandler(vm *vm.VM, l *loop.Loop, h http.Handler) error {
t.headers = res.Header()
t.body = res.Body.Bytes()
} else {
res, err := http.DefaultClient.Do(req)
if err != nil {
t.err = err
res, e := http.DefaultClient.Do(req)
if e != nil {
t.err = e
return
}
d, err := ioutil.ReadAll(res.Body)
if err != nil {
t.err = err
d, e := ioutil.ReadAll(res.Body)
if e != nil {
t.err = e
return
}
@ -160,5 +171,5 @@ func DefineWithHandler(vm *vm.VM, l *loop.Loop, h http.Handler) error {
return otto.UndefinedValue()
})
return nil
return err
}

View file

@ -18,7 +18,7 @@ import (
func (s *FetchSuite) TestFetch() {
ch := make(chan struct{})
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
w.Write([]byte("hello")) //nolint: errcheck
ch <- struct{}{}
})
@ -28,7 +28,7 @@ func (s *FetchSuite) TestFetch() {
err = s.loop.Eval(`fetch('` + s.srv.URL + `').then(function(r) {
return r.text();
}).then(function(d) {
if (d.indexOf('hellox') === -1) {
if (d.indexOf('hello') === -1) {
throw new Error('what');
}
});`)
@ -43,7 +43,7 @@ func (s *FetchSuite) TestFetch() {
func (s *FetchSuite) TestFetchCallback() {
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
w.Write([]byte("hello")) //nolint: errcheck
})
err := fetch.Define(s.vm, s.loop)
@ -74,7 +74,7 @@ func (s *FetchSuite) TestFetchHeaders() {
w.Header().Add("header-two", "2a")
w.Header().Add("header-two", "2b")
w.Write([]byte("hello"))
w.Write([]byte("hello")) //nolint: errcheck
})
err := fetch.Define(s.vm, s.loop)
@ -106,7 +106,7 @@ func (s *FetchSuite) TestFetchJSON() {
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// these spaces are here so we can disambiguate between this and the
// re-encoded data the javascript below spits out
w.Write([]byte("[ 1 , 2 , 3 ]"))
w.Write([]byte("[ 1 , 2 , 3 ]")) //nolint: errcheck
})
err := fetch.Define(s.vm, s.loop)
@ -135,7 +135,7 @@ func (s *FetchSuite) TestFetchWithHandler() {
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// these spaces are here so we can disambiguate between this and the
// re-encoded data the javascript below spits out
w.Write([]byte("[ 1 , 2 , 3 ]"))
w.Write([]byte("[ 1 , 2 , 3 ]")) //nolint: errcheck
})
err := fetch.DefineWithHandler(s.vm, s.loop, s.mux)
@ -162,7 +162,7 @@ func (s *FetchSuite) TestFetchWithHandler() {
func (s *FetchSuite) TestFetchWithHandlerParallel() {
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
w.Write([]byte("hello")) //nolint: errcheck
})
err := fetch.DefineWithHandler(s.vm, s.loop, s.mux)
@ -211,7 +211,7 @@ func (s *FetchSuite) SetupTest() {
s.vm = vm.New(o)
s.loop = loop.New(s.vm)
go s.loop.Run(context.Background())
go s.loop.Run(context.Background()) //nolint: errcheck
}
func (s *FetchSuite) TearDownSuite() {

View file

@ -2,21 +2,12 @@ package loop
import (
"context"
"fmt"
"sync"
"sync/atomic"
"github.com/status-im/status-go/geth/jail/internal/vm"
)
func formatTask(t Task) string {
if t == nil {
return "<nil>"
}
return fmt.Sprintf("<%T> %d", t, t.GetID())
}
// Task represents something that the event loop can schedule and run.
//
// Task describes two operations that will almost always be boilerplate,
@ -108,11 +99,8 @@ func (l *Loop) Ready(t Task) {
// Eval executes some code in the VM associated with the loop and returns an
// error if that execution fails.
func (l *Loop) Eval(s interface{}) error {
if _, err := l.vm.Run(s); err != nil {
return err
}
return nil
_, err := l.vm.Run(s)
return err
}
func (l *Loop) processTask(t Task) error {
@ -155,5 +143,4 @@ func (l *Loop) Run(ctx context.Context) error {
return context.Canceled
}
}
return nil
}

View file

@ -66,6 +66,7 @@ func (e EvalTask) Cancel() {}
// Execute runs the EvalTask's otto.Script in the vm provided, pushing the
// resultant return value and error (or nil) into the associated channels.
// If the execution results in an error, it will return that error.
// nolint: unparam
func (e EvalTask) Execute(vm *vm.VM, l *loop.Loop) error {
v, err := vm.Run(e.Script)
e.Value <- v
@ -114,6 +115,7 @@ func (c CallTask) Cancel() {}
// Execute calls the associated function (not necessarily in the given vm),
// pushing the resultant return value and error (or nil) into the associated
// channels. If the call results in an error, it will return that error.
// nolint: unparam
func (c CallTask) Execute(vm *vm.VM, l *loop.Loop) error {
// vm is not used directly here, but underlying
// FunctionCall in CallTask likely does use it,

View file

@ -7,6 +7,7 @@ import (
"github.com/robertkrimen/otto"
)
// Define process
func Define(vm *otto.Otto, argv []string) error {
if v, err := vm.Get("process"); err != nil {
return err

View file

@ -6,6 +6,7 @@ import (
"github.com/status-im/status-go/geth/jail/internal/vm"
)
//Define jail promise
func Define(vm *vm.VM, l *loop.Loop) error {
if v, err := vm.Get("Promise"); err != nil {
return err

View file

@ -89,7 +89,7 @@ func (s *PromiseSuite) SetupTest() {
s.vm = vm.New(o)
s.loop = loop.New(s.vm)
go s.loop.Run(context.Background())
go s.loop.Run(context.Background()) //nolint: errcheck
err := promise.Define(s.vm, s.loop)
s.NoError(err)

View file

@ -14,6 +14,7 @@ var minDelay = map[bool]int64{
false: 4,
}
//Define jail timers
func Define(vm *vm.VM, l *loop.Loop) error {
if v, err := vm.Get("setTimeout"); err != nil {
return err
@ -39,18 +40,26 @@ func Define(vm *vm.VM, l *loop.Loop) error {
l.Ready(t)
})
value, err := call.Otto.ToValue(t)
if err != nil {
panic(err)
value, newTimerErr := call.Otto.ToValue(t)
if newTimerErr != nil {
panic(newTimerErr)
}
return value
}
}
vm.Set("setTimeout", newTimer(false))
vm.Set("setInterval", newTimer(true))
vm.Set("setImmediate", func(call otto.FunctionCall) otto.Value {
err := vm.Set("setTimeout", newTimer(false))
if err != nil {
return err
}
err = vm.Set("setInterval", newTimer(true))
if err != nil {
return err
}
err = vm.Set("setImmediate", func(call otto.FunctionCall) otto.Value {
t := &timerTask{
duration: time.Millisecond,
call: call,
@ -61,13 +70,16 @@ func Define(vm *vm.VM, l *loop.Loop) error {
l.Ready(t)
})
value, err := call.Otto.ToValue(t)
value, setImmediateErr := call.Otto.ToValue(t)
if err != nil {
panic(err)
panic(setImmediateErr)
}
return value
})
if err != nil {
return err
}
clearTimeout := func(call otto.FunctionCall) otto.Value {
v, _ := call.Argument(0).Export()
@ -79,11 +91,18 @@ func Define(vm *vm.VM, l *loop.Loop) error {
return otto.UndefinedValue()
}
vm.Set("clearTimeout", clearTimeout)
vm.Set("clearInterval", clearTimeout)
vm.Set("clearImmediate", clearTimeout)
err = vm.Set("clearTimeout", clearTimeout)
if err != nil {
return err
}
return nil
err = vm.Set("clearInterval", clearTimeout)
if err != nil {
return err
}
err = vm.Set("clearImmediate", clearTimeout)
return err
}
type timerTask struct {

View file

@ -107,7 +107,7 @@ func (s *TimersSuite) SetupTest() {
s.vm = vm.New(o)
s.loop = loop.New(s.vm)
go s.loop.Run(context.Background())
go s.loop.Run(context.Background()) //nolint: errcheck
err := timers.Define(s.vm, s.loop)
s.NoError(err)

View file

@ -17,6 +17,7 @@ var (
// FIXME(tiabc): Get rid of this global variable. Move it to a constructor or initialization.
web3JSCode = static.MustAsset("scripts/web3.js")
//ErrInvalidJail - error jail init env
ErrInvalidJail = errors.New("jail environment is not properly initialized")
)
@ -216,6 +217,7 @@ func newResultResponse(vm *otto.Otto, result interface{}) otto.Value {
// throwJSException panics on an otto.Value. The Otto VM will recover from the
// Go panic and throw msg as a JavaScript error.
// nolint: unparam
func throwJSException(msg error) otto.Value {
val, err := otto.ToValue(msg.Error())
if err != nil {

View file

@ -30,7 +30,7 @@ func TestLogLevels(t *testing.T) {
}
var buf bytes.Buffer
// log-comaptible handler that writes log in the buffer
// log-compatible handler that writes log in the buffer
handler := log.FuncHandler(func(r *log.Record) error {
_, err := buf.Write([]byte(r.Msg))
return err
@ -54,11 +54,12 @@ func TestLogFile(t *testing.T) {
file, err := ioutil.TempFile("", "statusim_log_test")
require.NoError(t, err)
defer file.Close()
defer file.Close() //nolint: errcheck
// setup log
SetLevel("INFO")
SetLogFile(file.Name())
err = SetLogFile(file.Name())
require.NoError(t, err)
// test log output to file
Info(info)

View file

@ -32,6 +32,8 @@ var (
)
// NodeManager manages Status node (which abstracts contained geth node)
// nolint: golint
// should be fixed at https://github.com/status-im/status-go/issues/200
type NodeManager struct {
sync.RWMutex
config *params.NodeConfig // Status node configuration

View file

@ -525,7 +525,8 @@ func (c *NodeConfig) DefaultStatusChainGenesisBlock() (*core.Genesis, error) {
}
var genesis *core.Genesis
if err := json.Unmarshal([]byte(genesisJSON), &genesis); err != nil {
err = json.Unmarshal(genesisJSON, &genesis)
if err != nil {
return nil, fmt.Errorf("cannot unmarshal status-chain-genesis.json: %s", err)
}
return genesis, nil

View file

@ -69,11 +69,13 @@ func Send(signal Envelope) {
}
//export NotifyNode
func NotifyNode(jsonEvent *C.char) { // nolint: golint
//nolint: golint
func NotifyNode(jsonEvent *C.char) {
notificationHandler(C.GoString(jsonEvent))
}
//export TriggerTestSignal
func TriggerTestSignal() { // nolint: golint
//nolint: golint
func TriggerTestSignal() {
C.StatusServiceSignalEvent(C.CString(`{"answer": 42}`))
}

View file

@ -22,12 +22,18 @@ const (
)
var (
ErrQueuedTxIDNotFound = errors.New("transaction hash not found")
ErrQueuedTxTimedOut = errors.New("transaction sending timed out")
ErrQueuedTxDiscarded = errors.New("transaction has been discarded")
ErrQueuedTxInProgress = errors.New("transaction is in progress")
//ErrQueuedTxIDNotFound - error transaction hash not found
ErrQueuedTxIDNotFound = errors.New("transaction hash not found")
//ErrQueuedTxTimedOut - error transaction sending timed out
ErrQueuedTxTimedOut = errors.New("transaction sending timed out")
//ErrQueuedTxDiscarded - error transaction discarded
ErrQueuedTxDiscarded = errors.New("transaction has been discarded")
//ErrQueuedTxInProgress - error transaction in progress
ErrQueuedTxInProgress = errors.New("transaction is in progress")
//ErrQueuedTxAlreadyProcessed - error transaction has already processed
ErrQueuedTxAlreadyProcessed = errors.New("transaction has been already processed")
ErrInvalidCompleteTxSender = errors.New("transaction can only be completed by the same account which created it")
//ErrInvalidCompleteTxSender - error transaction with invalid sender
ErrInvalidCompleteTxSender = errors.New("transaction can only be completed by the same account which created it")
)
// TxQueue is capped container that holds pending transactions
@ -122,7 +128,8 @@ func (q *TxQueue) enqueueLoop() {
select {
case queuedTx := <-q.incomingPool:
log.Info("transaction enqueued requested", "tx", queuedTx.ID)
q.Enqueue(queuedTx)
err := q.Enqueue(queuedTx)
log.Warn("transaction enqueued error", "tx", err)
log.Info("transaction enqueued", "tx", queuedTx.ID)
case <-q.stopped:
log.Info("transaction queue's enqueue loop stopped")

View file

@ -139,7 +139,8 @@ func (m *Manager) CompleteTransaction(id common.QueuedTxID, password string) (ge
return gethcommon.Hash{}, err
}
if err := m.txQueue.StartProcessing(queuedTx); err != nil {
err = m.txQueue.StartProcessing(queuedTx)
if err != nil {
return gethcommon.Hash{}, err
}
defer m.txQueue.StopProcessing(queuedTx)
@ -165,29 +166,28 @@ func (m *Manager) CompleteTransaction(id common.QueuedTxID, password string) (ge
// Send the transaction finally.
var hash gethcommon.Hash
var txErr error
if config.UpstreamConfig.Enabled {
hash, txErr = m.completeRemoteTransaction(queuedTx, password)
hash, err = m.completeRemoteTransaction(queuedTx, password)
} else {
hash, txErr = m.completeLocalTransaction(queuedTx, password)
hash, err = m.completeLocalTransaction(queuedTx, password)
}
// when incorrect sender tries to complete the account,
// notify and keep tx in queue (so that correct sender can complete)
if txErr == keystore.ErrDecrypt {
log.Warn("failed to complete transaction", "err", txErr)
m.NotifyOnQueuedTxReturn(queuedTx, txErr)
return hash, txErr
if err == keystore.ErrDecrypt {
log.Warn("failed to complete transaction", "err", err)
m.NotifyOnQueuedTxReturn(queuedTx, err)
return hash, err
}
log.Info("finally completed transaction", "id", queuedTx.ID, "hash", hash, "err", txErr)
log.Info("finally completed transaction", "id", queuedTx.ID, "hash", hash, "err", err)
queuedTx.Hash = hash
queuedTx.Err = txErr
queuedTx.Err = err
queuedTx.Done <- struct{}{}
return hash, txErr
return hash, err
}
func (m *Manager) completeLocalTransaction(queuedTx *common.QueuedTx, password string) (gethcommon.Hash, error) {
@ -219,11 +219,8 @@ func (m *Manager) completeRemoteTransaction(queuedTx *common.QueuedTx, password
return emptyHash, err
}
if _, err := m.accountManager.VerifyAccountPassword(
config.KeyStoreDir,
selectedAcct.Address.String(),
password,
); err != nil {
_, err = m.accountManager.VerifyAccountPassword(config.KeyStoreDir, selectedAcct.Address.String(), password)
if err != nil {
log.Warn("failed to verify account", "account", selectedAcct.Address.String(), "error", err.Error())
return emptyHash, err
}
@ -234,7 +231,8 @@ func (m *Manager) completeRemoteTransaction(queuedTx *common.QueuedTx, password
var txCount hexutil.Uint
client := m.nodeManager.RPCClient()
if err := client.CallContext(ctx, &txCount, "eth_getTransactionCount", queuedTx.Args.From, "pending"); err != nil {
err = client.CallContext(ctx, &txCount, "eth_getTransactionCount", queuedTx.Args.From, "pending")
if err != nil {
return emptyHash, err
}
@ -305,12 +303,12 @@ func (m *Manager) estimateGas(args common.SendTxArgs) (*hexutil.Big, error) {
var gasPrice hexutil.Big
if args.GasPrice != nil {
gasPrice = (hexutil.Big)(*args.GasPrice)
gasPrice = *args.GasPrice
}
var value hexutil.Big
if args.Value != nil {
value = (hexutil.Big)(*args.Value)
value = *args.Value
}
params := struct {
@ -476,7 +474,7 @@ func (m *Manager) sendTransactionErrorCode(err error) string {
}
// SetTransactionReturnHandler sets a handler that will be called
// when a transaction is about to return or when a recoverable error occured.
// when a transaction is about to return or when a recoverable error occurred.
// Recoverable error is, for instance, wrong password.
func (m *Manager) SetTransactionReturnHandler(fn common.EnqueuedTxReturnHandler) {
m.txQueue.SetTxReturnHandler(fn)

View file

@ -81,8 +81,8 @@ func (s *TxQueueTestSuite) TestCompleteTransaction() {
s.NoError(err)
go func() {
_, err := txQueueManager.CompleteTransaction(tx.ID, TestConfig.Account1.Password)
s.Equal(errTxAssumedSent, err)
_, errCompleteTransaction := txQueueManager.CompleteTransaction(tx.ID, TestConfig.Account1.Password)
s.Equal(errTxAssumedSent, errCompleteTransaction)
}()
err = txQueueManager.WaitForTransaction(tx)
@ -137,9 +137,9 @@ func (s *TxQueueTestSuite) TestCompleteTransactionMultipleTimes() {
wg.Add(1)
go func() {
defer wg.Done()
_, err := txQueueManager.CompleteTransaction(tx.ID, TestConfig.Account1.Password)
_, errCompleteTransaction := txQueueManager.CompleteTransaction(tx.ID, TestConfig.Account1.Password)
mu.Lock()
completeTxErrors[err]++
completeTxErrors[errCompleteTransaction]++
mu.Unlock()
}()
}
@ -266,8 +266,8 @@ func (s *TxQueueTestSuite) TestDiscardTransaction() {
s.NoError(err)
go func() {
err := txQueueManager.DiscardTransaction(tx.ID)
s.NoError(err)
discardErr := txQueueManager.DiscardTransaction(tx.ID)
s.NoError(discardErr)
}()
err = txQueueManager.WaitForTransaction(tx)

View file

@ -8,6 +8,7 @@ import (
"github.com/status-im/status-go/geth/signal"
)
//ErrTxQueueRunFailure - error running transaction queue
var ErrTxQueueRunFailure = errors.New("error running transaction queue")
// HaltOnPanic recovers from panic, logs issue, sends upward notification, and exits

View file

@ -1,24 +0,0 @@
comment on exported function CreateAccount should be of the form "CreateAccount ..." (golint)
comment on exported function CreateChildAccount should be of the form "CreateChildAccount ..." (golint)
comment on exported function RecoverAccount should be of the form "RecoverAccount ..." (golint)
comment on exported function Login should be of the form "Login ..." (golint)
comment on exported function Logout should be of the form "Logout ..." (golint)
comment on exported function CompleteTransaction should be of the form "CompleteTransaction ..." (golint)
comment on exported function CompleteTransactions should be of the form "CompleteTransactions ..." (golint)
comment on exported function DiscardTransaction should be of the form "DiscardTransaction ..." (golint)
comment on exported function DiscardTransactions should be of the form "DiscardTransactions ..." (golint)
comment on exported function GenerateConfig should be of the form "GenerateConfig ..." (golint)
comment on exported function StartNode should be of the form "StartNode ..." (golint)
comment on exported function StopNode should be of the form "StopNode ..." (golint)
comment on exported function ResumeNode should be of the form "ResumeNode ..." (golint)
comment on exported function ResetChainData should be of the form "ResetChainData ..." (golint)
comment on exported function StopNodeRPCServer should be of the form "StopNodeRPCServer ..." (golint)
comment on exported function StartNodeRPCServer should be of the form "StartNodeRPCServer ..." (golint)
comment on exported function InitJail should be of the form "InitJail ..." (golint)
comment on exported function Parse should be of the form "Parse ..." (golint)
comment on exported function Call should be of the form "Call ..." (golint)
comment on exported function PopulateStaticPeers should be of the form "PopulateStaticPeers ..." (golint)
comment on exported function AddPeer should be of the form "AddPeer ..." (golint)
comment on exported function NotifyNode should be of the form "NotifyNode ..." (golint)
comment on exported function TriggerTestSignal should be of the form "TriggerTestSignal ..." (golint)
comment on exported function VerifyAccountPassword should be of the form "VerifyAccountPassword ..." (golint)