Fix issues reported by lint. Part of #1017

This commit is contained in:
Pedro Pombeiro 2018-06-12 18:50:25 +02:00 committed by Pedro Pombeiro
parent 3abfe3ffda
commit 354e23aaf5
28 changed files with 155 additions and 133 deletions

View File

@ -46,7 +46,7 @@ function extension {
fi
}
# Either set a local build environemnt, or pull any remote imports
# Either set a local build environment, or pull any remote imports
if [ "$EXT_GOPATH" != "" ]; then
# If local builds are requested, inject the sources
echo "Building locally $1..."

View File

@ -1,26 +1,25 @@
# Dependency Management
[`dep`](https://github.com/golang/dep) is a tool of choice when it comes to dependency management.
## How we use `dep`.
## How we use `dep`
1. Transitive dependencies of `go-ethereum`. The most important thing for us is
to be in-sync there. We want to reduce the regression scope.
Hence, we pin down all the dependencies of `go-ethereum` with SHAs in `Gopkg.toml` when
importing a new version of upstream. (This is considered a bad practice for
`dep` but we are willing to take the risk to keep consitency with the upstream).
2. Exclusive `status-go` dependencies. The policy there is to keep them as
`dep` but we are willing to take the risk to keep consistency with the upstream).
1. Exclusive `status-go` dependencies. The policy there is to keep them as
fresh as possible. Hence, no constraints for them in the `toml` file.
## Installing `dep`
`go get -u github.com/golang/dep/cmd/dep`
## Docs (worth reading)
1. [README](https://github.com/golang/dep/blob/master/README.md)
2. [F.A.Q.](https://github.com/golang/dep/blob/master/docs/FAQ.md)
1. [README](https://github.com/golang/dep/blob/master/README.md)
1. [F.A.Q.](https://github.com/golang/dep/blob/master/docs/FAQ.md)
## Checking-out all dependencies
@ -30,15 +29,17 @@
`Gopkg.lock` is kept inact if it is in-sync with `Gopkg.toml`. If the `toml`
file is changed, `dep ensure` will re-generate `Gopkg.lock` as well.
## Adding a new Dependency
(see [Adding a new dependency](https://github.com/golang/dep#adding-a-dependency))
1. `$ dep ensure -add github.com/foo/bar`
2. Commit changes.
(see [Adding a new dependency](https://github.com/golang/dep#adding-a-dependency))
1. `$ dep ensure -add github.com/foo/bar`
1. Commit changes.
## Updating a dependency
(see: [Changing a Dependency](https://github.com/golang/dep#changing-dependencies))
1. Update constraint in the `Gopkg.toml` file if needed.
2. Run `dep ensure -update github.com/foo/bar`
3. Commit changes.
@ -51,12 +52,11 @@ file is changed, `dep ensure` will re-generate `Gopkg.lock` as well.
Use the `update-geth` make target. For major releases, provide the GETH_BRANCH parameter. (e.g. `make update-geth GETH_BRANCH=release/1.9`). If there were any changes made, they will be committed while running this target.
## Commiting changes
## Committing changes
Make sure that you don't commit unnecessary changes to `Gopkg.toml` and
`Gopkg.lock`.
## Common issues
1. Relative imports and "Could not introduce package, as its subpackage does not contain usable Go code". See [this comment](https://github.com/golang/dep/issues/899#issuecomment-317904001) for more information.

View File

@ -26,7 +26,6 @@ from them nodes that are registered as a topic provider.
We can control how often this loop wil run, more about it in the next section.
Peer pool in status-go
----------------------
@ -35,12 +34,15 @@ without using a lot of resources in the long run. It achieves it by introducing
two modes of synchronization:
1. Fast mode.
Peer will run search loop quite often (every 500ms at the time of writing) with the
goal to visit as much nodes as possible and once it will find minimum amount of
peers with required capability it will swich to slow mode.
2. Slow mode.
1. Slow mode.
This mode might be useful to get information about new peers that can be used
later if initial set of peers will dissapear. Should run once in a 10m-30m.
later if initial set of peers disappears. Should run once in a 10m-30m.
However finding peers even with fast mode can take noticeable amount of time,
which is fine if node is a long-running, but will be a huge problem on a mobile
@ -48,5 +50,6 @@ device. To workaround such problem we will introduce a leveldb cache that will
maintain a list of peers that was used by a device before it went offline.
Another important detail of a peer pool is a support of min and max amount of peers:
- min is required to switch from fast to slow sync mode
- max is an upper limit that can be used by a single node

View File

@ -21,12 +21,19 @@ type ConnectionState struct {
// other types are also may be used.
type ConnectionType byte
const (
offline = "offline"
wifi = "wifi"
cellular = "cellular"
unknown = "unknown"
)
// NewConnectionType creates new ConnectionType from string.
func NewConnectionType(s string) ConnectionType {
switch s {
case "cellular":
case cellular:
return ConnectionCellular
case "wifi":
case wifi:
return ConnectionWifi
}
@ -43,17 +50,17 @@ const (
// String formats ConnectionState for logs. Implements Stringer.
func (c ConnectionState) String() string {
if c.Offline {
return "offline"
return offline
}
var typ string
switch c.Type {
case ConnectionWifi:
typ = "wifi"
typ = wifi
case ConnectionCellular:
typ = "cellular"
typ = cellular
default:
typ = "unknown"
typ = unknown
}
if c.Expensive {

View File

@ -37,13 +37,15 @@ func main() {
verbosity = flag.Int("verbosity", int(log.LvlInfo), "log verbosity (0-9)")
vmodule = flag.String("vmodule", "", "log verbosity pattern")
nursery = bootnodes{}
nodeKey *ecdsa.PrivateKey
err error
)
flag.Var(&nursery, "n", "These nodes are used to connect to the network if the table is empty and there are no known nodes in the database.")
flag.Parse()
glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
glogger.Verbosity(log.Lvl(*verbosity))
if err := glogger.Vmodule(*vmodule); err != nil {
if err = glogger.Vmodule(*vmodule); err != nil {
log.Crit("Failed to set glog verbosity", "value", *vmodule, "err", err)
}
log.Root().SetHandler(glogger)
@ -51,10 +53,6 @@ func main() {
if len(*nodeKeyFile) == 0 && len(*keydata) == 0 {
log.Crit("either `nodekey` or `keydata` must be provided")
}
var (
nodeKey *ecdsa.PrivateKey
err error
)
if len(*nodeKeyFile) != 0 {
nodeKey, err = crypto.LoadECDSA(*nodeKeyFile)
if err != nil {

View File

@ -14,12 +14,14 @@ import (
"github.com/status-im/status-go/api"
"github.com/status-im/status-go/cmd/statusd/debug"
"github.com/status-im/status-go/params"
"github.com/stretchr/testify/assert"
testifyAssert "github.com/stretchr/testify/assert"
)
const stopNodeCommandLine = "StopNode()"
// TestInvalidExpressions tests invalid expressions.
func TestInvalidExpressions(t *testing.T) {
assert := assert.New(t)
assert := testifyAssert.New(t)
startDebugging(assert)
@ -54,7 +56,7 @@ func TestInvalidExpressions(t *testing.T) {
// TestStartStopNode tests starting and stopping a node remotely.
func TestStartStopNode(t *testing.T) {
assert := assert.New(t)
assert := testifyAssert.New(t)
configJSON, cleanup, err := mkConfigJSON("start-stop-node")
assert.NoError(err)
defer cleanup()
@ -68,15 +70,14 @@ func TestStartStopNode(t *testing.T) {
assert.Len(replies, 1)
assert.Equal("[0] <nil>", replies[0])
commandLine = "StopNode()"
replies = sendCommandLine(assert, conn, commandLine)
replies = sendCommandLine(assert, conn, stopNodeCommandLine)
assert.Len(replies, 1)
assert.Equal("[0] <nil>", replies[0])
}
// TestCreateAccount tests creating an account on the server.
func TestCreateAccount(t *testing.T) {
assert := assert.New(t)
assert := testifyAssert.New(t)
configJSON, cleanup, err := mkConfigJSON("create-account")
assert.NoError(err)
defer cleanup()
@ -98,8 +99,7 @@ func TestCreateAccount(t *testing.T) {
assert.NotEqual("[2] <nil>", replies[2])
assert.Equal("[3] <nil>", replies[3])
commandLine = "StopNode()"
replies = sendCommandLine(assert, conn, commandLine)
replies = sendCommandLine(assert, conn, stopNodeCommandLine)
assert.Len(replies, 1)
assert.Equal("[0] <nil>", replies[0])
}
@ -107,7 +107,7 @@ func TestCreateAccount(t *testing.T) {
// TestSelectAccountLogout tests selecting an account on the server
// and logging out afterwards.
func TestSelectAccountLogout(t *testing.T) {
assert := assert.New(t)
assert := testifyAssert.New(t)
configJSON, cleanup, err := mkConfigJSON("select-account")
assert.NoError(err)
defer cleanup()
@ -141,8 +141,7 @@ func TestSelectAccountLogout(t *testing.T) {
assert.Len(replies, 1)
assert.Equal("[0] <nil>", replies[0])
commandLine = "StopNode()"
replies = sendCommandLine(assert, conn, commandLine)
replies = sendCommandLine(assert, conn, stopNodeCommandLine)
assert.Len(replies, 1)
assert.Equal("[0] <nil>", replies[0])
}
@ -157,7 +156,7 @@ var (
)
// startDebugging lazily creates or reuses a debug instance.
func startDebugging(assert *assert.Assertions) {
func startDebugging(assert *testifyAssert.Assertions) {
mu.Lock()
defer mu.Unlock()
if d == nil {
@ -188,14 +187,15 @@ func mkConfigJSON(name string) (string, func(), error) {
}
// connectDebug connects to the debug instance.
func connectDebug(assert *assert.Assertions) net.Conn {
func connectDebug(assert *testifyAssert.Assertions) net.Conn {
conn, err := net.Dial("tcp", ":51515")
assert.NoError(err)
return conn
}
// sendCommandLine sends a command line via the passed connection.
func sendCommandLine(assert *assert.Assertions, conn net.Conn, commandLine string) []string {
// nolint: interfacer
func sendCommandLine(assert *testifyAssert.Assertions, conn net.Conn, commandLine string) []string {
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
_, err := writer.WriteString(commandLine + "\n")

View File

@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/require"
)
// nolint: deadcode
func TestStatusFlag(t *testing.T) {
service := "status"

View File

@ -156,8 +156,8 @@ func main() {
exitCode := syncAndStopNode(interruptCh, backend.StatusNode(), *syncAndExit)
// Call was interrupted. Wait for graceful shutdown.
if exitCode == -1 {
if node := backend.StatusNode().GethNode(); node != nil {
node.Wait()
if gethNode := backend.StatusNode().GethNode(); gethNode != nil {
gethNode.Wait()
}
return
}
@ -165,10 +165,10 @@ func main() {
os.Exit(exitCode)
}
node := backend.StatusNode().GethNode()
if node != nil {
gethNode := backend.StatusNode().GethNode()
if gethNode != nil {
// wait till node has been stopped
node.Wait()
gethNode.Wait()
}
}
@ -183,8 +183,8 @@ func startDebug(backend *api.StatusBackend) error {
func startCollectingNodeMetrics(interruptCh <-chan struct{}, statusNode *node.StatusNode) {
logger.Info("Starting collecting node metrics")
node := statusNode.GethNode()
if node == nil {
gethNode := statusNode.GethNode()
if gethNode == nil {
logger.Error("Failed to run metrics because it could not get the node")
return
}
@ -192,7 +192,7 @@ func startCollectingNodeMetrics(interruptCh <-chan struct{}, statusNode *node.St
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
if err := nodemetrics.SubscribeServerEvents(ctx, node); err != nil {
if err := nodemetrics.SubscribeServerEvents(ctx, gethNode); err != nil {
logger.Error("Failed to subscribe server events", "error", err)
}
}()

View File

@ -104,6 +104,7 @@ type ExtendedKey struct {
CachedPubKeyData []byte // (non-serialized) used for memoization of public key (calculated from a private key)
}
// nolint: gas
const masterSecret = "Bitcoin seed"
// NewMaster creates new master node, root of HD chain/tree.

View File

@ -12,6 +12,11 @@ import (
"github.com/ethereum/go-ethereum/crypto"
)
const (
masterPrivKey1 = "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"
masterPrivKey2 = "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U"
)
func TestBIP32Vectors(t *testing.T) {
tests := []struct {
name string
@ -26,7 +31,7 @@ func TestBIP32Vectors(t *testing.T) {
"000102030405060708090a0b0c0d0e0f",
[]uint32{},
"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8",
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
masterPrivKey1,
},
{
"test vector 1 chain m/0H",
@ -69,7 +74,7 @@ func TestBIP32Vectors(t *testing.T) {
"fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542",
[]uint32{},
"xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB",
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
masterPrivKey2,
},
{
"test vector 2 chain m/0",
@ -176,8 +181,8 @@ func TestChildDerivation(t *testing.T) {
// derive public keys from private keys
getPrivateChildDerivationTests := func() []testCase {
// The private extended keys for test vectors in [BIP32].
testVec1MasterPrivKey := "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"
testVec2MasterPrivKey := "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U"
testVec1MasterPrivKey := masterPrivKey1
testVec2MasterPrivKey := masterPrivKey2
return []testCase{
// Test vector 1
@ -185,7 +190,7 @@ func TestChildDerivation(t *testing.T) {
name: "test vector 1 chain m",
master: testVec1MasterPrivKey,
path: []uint32{},
wantKey: "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
wantKey: masterPrivKey1,
},
{
name: "test vector 1 chain m/0",
@ -223,7 +228,7 @@ func TestChildDerivation(t *testing.T) {
name: "test vector 2 chain m",
master: testVec2MasterPrivKey,
path: []uint32{},
wantKey: "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
wantKey: masterPrivKey2,
},
{
name: "test vector 2 chain m/0",
@ -507,7 +512,7 @@ func TestErrors(t *testing.T) {
}
func TestBIP44ChildDerivation(t *testing.T) {
keyString := "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"
keyString := masterPrivKey1
derivedKey1String := "xprvA38t8tFW4vbuB7WJXEqMFmZqRrcZUKWqqMcGjjKjr2hbfvPhRtLLJGL4ayWG8shF1VkuUikVGodGshLiKRS7WrdsrGSVDQCY33qoPBxG2Kp"
derivedKey2String := "xprvA38t8tFW4vbuDgBNpekPnuMSfpWziDLdF7W9Zd3mPy6eDEkM5F17vk59RtVoFbNdBBq84EJf5CqdZhhEoBkAM4DXHQsDqvUxVnncfnDQEFg"

View File

@ -84,10 +84,10 @@ type Cell struct {
// NewCell encapsulates what we need to create a new jailCell from the
// provided vm and eventloop instance.
func NewCell(id string) (*Cell, error) {
vm := vm.New()
lo := loop.New(vm)
newVM := vm.New()
lo := loop.New(newVM)
err := registerVMHandlers(vm, lo)
err := registerVMHandlers(newVM, lo)
if err != nil {
return nil, err
}
@ -95,7 +95,7 @@ func NewCell(id string) (*Cell, error) {
ctx, cancel := context.WithCancel(context.Background())
loopStopped := make(chan struct{})
cell := Cell{
jsvm: vm,
jsvm: newVM,
id: id,
cancel: cancel,
loop: lo,
@ -180,8 +180,8 @@ func (c *Cell) Get(key string) (JSValue, error) {
if err != nil {
return JSValue{}, err
}
JSValue := JSValue{value: v}
return JSValue, nil
value := JSValue{value: v}
return value, nil
}
// GetObjectValue calls GetObjectValue on the underlying JavaScript VM and returns
@ -191,8 +191,8 @@ func (c *Cell) GetObjectValue(v otto.Value, name string) (JSValue, error) {
if err != nil {
return JSValue{}, err
}
JSValue := JSValue{value: v}
return JSValue, nil
value := JSValue{value: v}
return value, nil
}
// Run calls Run on the underlying JavaScript VM and returns
@ -202,8 +202,8 @@ func (c *Cell) Run(src interface{}) (JSValue, error) {
if err != nil {
return JSValue{}, err
}
JSValue := JSValue{value: v}
return JSValue, nil
value := JSValue{value: v}
return value, nil
}
// Call calls Call on the underlying JavaScript VM and returns
@ -213,6 +213,6 @@ func (c *Cell) Call(item string, this interface{}, args ...interface{}) (JSValue
if err != nil {
return JSValue{}, err
}
JSValue := JSValue{value: v}
return JSValue, nil
value := JSValue{value: v}
return value, nil
}

View File

@ -48,8 +48,8 @@ type LoopSuite struct {
func (s *LoopSuite) SetupTest() {
s.task = &DummyTask{}
vm := vm.New()
s.loop = New(vm)
newVM := vm.New()
s.loop = New(newVM)
ctx, cancel := context.WithCancel(context.Background())
s.cancel = cancel

View File

@ -24,6 +24,7 @@ const (
// EmptyResponse is returned when cell is successfully created and initialized
// but no additional JS was provided to the initialization method.
EmptyResponse = `{"result": ""}`
undefinedText = "undefined"
)
var (
@ -299,7 +300,7 @@ func newJailErrorResponse(err error) string {
func formatOttoValue(result otto.Value) otto.Value {
val := result.String()
if result.IsString() {
if val != "undefined" {
if val != undefinedText {
val = fmt.Sprintf(`"%s"`, strings.Replace(val, `"`, `\"`, -1))
result, _ = otto.ToValue(val)
}
@ -312,7 +313,7 @@ func formatOttoValue(result otto.Value) otto.Value {
// that is a valid JavaScript code.
func newJailResultResponse(value otto.Value) string {
res := value.String()
if res == "undefined" {
if res == undefinedText {
res = "null"
}
return `{"result":` + res + `}`

View File

@ -262,7 +262,7 @@ func (s *WMailServer) validateRequest(peerID []byte, request *whisper.Envelope)
f := whisper.Filter{KeySym: s.key}
decrypted := request.Open(&f)
if decrypted == nil {
log.Warn(fmt.Sprintf("Failed to decrypt p2p request"))
log.Warn("Failed to decrypt p2p request")
return false, 0, 0, nil
}

View File

@ -9,25 +9,25 @@ import (
)
func TestSubscribeServerEventsWithoutServer(t *testing.T) {
node, err := node.New(&node.Config{})
gethNode, err := node.New(&node.Config{})
require.NoError(t, err)
require.EqualError(t, SubscribeServerEvents(context.TODO(), node), "server is unavailable")
require.EqualError(t, SubscribeServerEvents(context.TODO(), gethNode), "server is unavailable")
}
func TestSubscribeServerEvents(t *testing.T) {
node, err := node.New(&node.Config{})
gethNode, err := node.New(&node.Config{})
require.NoError(t, err)
err = node.Start()
err = gethNode.Start()
require.NoError(t, err)
defer func() {
err := node.Stop()
err := gethNode.Stop()
require.NoError(t, err)
}()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
err := SubscribeServerEvents(ctx, node)
err := SubscribeServerEvents(ctx, gethNode)
require.NoError(t, err)
close(done)
}()

View File

@ -196,10 +196,10 @@ func activateShhService(stack *node.Node, config *params.NodeConfig, db *leveldb
return nil
}
if config.WhisperConfig.EnableNTPSync {
if err := stack.Register(func(*node.ServiceContext) (node.Service, error) {
if err = stack.Register(func(*node.ServiceContext) (node.Service, error) {
return timesource.Default(), nil
}); err != nil {
return err
return
}
}

View File

@ -34,7 +34,7 @@ func (s *NotifierTestSuite) TestNotifySuccess() {
ids := []string{"1"}
payload := fcmPayload
msg := make(map[string]string)
body := "body"
body := "body1"
msg["msg"] = body
s.fcmClientMock.EXPECT().SetNotificationPayload(&fcmPayload).Times(1)
@ -53,7 +53,7 @@ func (s *NotifierTestSuite) TestNotifyError() {
ids := []string{"1"}
payload := fcmPayload
msg := make(map[string]string)
body := "body"
body := "body2"
msg["msg"] = body
s.fcmClientMock.EXPECT().SetNotificationPayload(&fcmPayload).Times(1)

View File

@ -57,7 +57,7 @@ type jsonError struct {
}
// callRawContext performs a JSON-RPC call with already crafted JSON-RPC body and
// given context. It returns string in JSON format with response (successul or error).
// given context. It returns string in JSON format with response (successful or error).
//
// TODO(divan): this function exists for compatibility and uses default
// go-ethereum's RPC client under the hood. It adds some unnecessary overhead

View File

@ -35,9 +35,11 @@ func (s *DedupCacheTestSuite) TearDownTest() {
}
func (s *DedupCacheTestSuite) TestMultipleFilterIDs() {
filterID1 := "filter-id1"
filterID2 := "filter-id2"
filterID3 := "filter-id"
const (
filterID1 = "filter-id1"
filterID2 = "filter-id2"
filterID3 = "filter-id"
)
messagesFilter1 := generateMessages(10)
s.NoError(s.c.Put(filterID1, messagesFilter1))
@ -74,7 +76,7 @@ func (s *DedupCacheTestSuite) TestMultipleFilterIDs() {
}
func (s *DedupCacheTestSuite) TestCleaningUp() {
filterID := "filter-id"
const filterID = "filter1-id"
// - 2 days
s.c.now = func() time.Time { return time.Now().Add(-48 * time.Hour) }
messages2DaysOld := generateMessages(10)

View File

@ -2,8 +2,8 @@ package benchmarks
import (
"context"
"crypto/rand"
"fmt"
"math/rand"
"testing"
"github.com/ethereum/go-ethereum/node"
@ -43,7 +43,7 @@ func TestSendMessages(t *testing.T) {
require.NoError(t, err)
payload := make([]byte, *msgSize)
rand.Read(payload)
_, _ = rand.Read(payload)
envelopeEvents := make(chan whisper.EnvelopeEvent, 100)
sub := shhService.SubscribeEnvelopeEvents(envelopeEvents)

View File

@ -46,7 +46,7 @@ func (s *AccountsTestSuite) TestAccountsList() {
accounts, err = s.Backend.AccountManager().Accounts()
s.NoError(err)
s.Equal(1, len(accounts), "exactly single account is expected (main account)")
s.Equal(string(accounts[0].Hex()), address,
s.Equal(accounts[0].Hex(), address,
fmt.Sprintf("main account is not retured as the first key: got %s, expected %s", accounts[0].Hex(), "0x"+address))
// create sub-account 1
@ -57,8 +57,8 @@ func (s *AccountsTestSuite) TestAccountsList() {
accounts, err = s.Backend.AccountManager().Accounts()
s.NoError(err)
s.Equal(2, len(accounts), "exactly 2 accounts are expected (main + sub-account 1)")
s.Equal(string(accounts[0].Hex()), address, "main account is not retured as the first key")
s.Equal(string(accounts[1].Hex()), subAccount1, "subAcount1 not returned")
s.Equal(accounts[0].Hex(), address, "main account is not retured as the first key")
s.Equal(accounts[1].Hex(), subAccount1, "subAcount1 not returned")
// create sub-account 2, index automatically progresses
subAccount2, subPubKey2, err := s.Backend.AccountManager().CreateChildAccount("", TestConfig.Account1.Password)
@ -69,14 +69,14 @@ func (s *AccountsTestSuite) TestAccountsList() {
accounts, err = s.Backend.AccountManager().Accounts()
s.NoError(err)
s.Equal(3, len(accounts), "unexpected number of accounts")
s.Equal(string(accounts[0].Hex()), address, "main account is not retured as the first key")
s.Equal(accounts[0].Hex(), address, "main account is not retured as the first key")
subAccount1MatchesKey1 := string(accounts[1].Hex()) != "0x"+subAccount1
subAccount1MatchesKey2 := string(accounts[2].Hex()) != "0x"+subAccount1
subAccount1MatchesKey1 := accounts[1].Hex() != "0x"+subAccount1
subAccount1MatchesKey2 := accounts[2].Hex() != "0x"+subAccount1
s.False(!subAccount1MatchesKey1 && !subAccount1MatchesKey2, "subAcount1 not returned")
subAccount2MatchesKey1 := string(accounts[1].Hex()) != "0x"+subAccount2
subAccount2MatchesKey2 := string(accounts[2].Hex()) != "0x"+subAccount2
subAccount2MatchesKey1 := accounts[1].Hex() != "0x"+subAccount2
subAccount2MatchesKey2 := accounts[2].Hex() != "0x"+subAccount2
s.False(!subAccount2MatchesKey1 && !subAccount2MatchesKey2, "subAcount2 not returned")
}

View File

@ -119,7 +119,7 @@ func (s *APITestSuite) TestRaceConditions() {
}
for range progress {
cnt -= 1
cnt--
if cnt <= 0 {
break
}
@ -134,7 +134,7 @@ func (s *APITestSuite) TestCellsRemovedAfterSwitchAccount() {
const itersCount = 5
var (
require = s.Require()
getChatId = func(id int) string {
getChatID = func(id int) string {
return testChatID + strconv.Itoa(id)
}
)
@ -155,7 +155,7 @@ func (s *APITestSuite) TestCellsRemovedAfterSwitchAccount() {
require.NoError(err)
for i := 0; i < itersCount; i++ {
_, e := s.api.JailManager().CreateCell(getChatId(i))
_, e := s.api.JailManager().CreateCell(getChatID(i))
require.NoError(e)
}
@ -163,7 +163,7 @@ func (s *APITestSuite) TestCellsRemovedAfterSwitchAccount() {
require.NoError(err)
for i := 0; i < itersCount; i++ {
_, e := s.api.JailManager().Cell(getChatId(i))
_, e := s.api.JailManager().Cell(getChatID(i))
require.Error(e)
}
}

View File

@ -19,7 +19,8 @@ import (
)
const (
testChatID = "testChat"
testChatID = "testChat"
successJSON = `{"result":true}`
)
var (
@ -98,7 +99,6 @@ func (s *JailTestSuite) TestCreateAndInitCell() {
// Reinitialization preserves the JS environment, so the 'test' variable exists
// even though we didn't initialize it here (in the second room).
response = s.Jail.CreateAndInitCell("newChat2", "a")
expectedResponse = `{"result":2}`
s.Equal(expectedResponse, response)
// But this variable doesn't leak into other rooms.
@ -121,8 +121,8 @@ func (s *JailTestSuite) TestFunctionCall() {
s.Equal(expectedError, response)
// call extraFunc()
response = s.Jail.Call(testChatID, `["commands", "testCommand"]`, `{"val":12}`)
expectedResponse := `{"result":144}`
response = s.Jail.Call(testChatID, `["commands", "testCommand"]`, `{"val":11}`)
expectedResponse := `{"result":121}`
s.Equal(expectedResponse, response)
}
@ -136,7 +136,7 @@ func (s *JailTestSuite) TestFunctionCallTrue() {
// call extraFunc()
response := s.Jail.Call(testChatID, `["commands", "testCommandTrue"]`, `{"val":12}`)
expectedResponse := `{"result":true}`
expectedResponse := successJSON
s.Equal(expectedResponse, response)
}
@ -194,7 +194,7 @@ func (s *JailTestSuite) TestEventSignal() {
response, err := responseValue.Value().ToString()
s.NoError(err, "cannot parse result")
expectedResponse := `{"result":true}`
expectedResponse := successJSON
s.Equal(expectedResponse, response)
}
@ -234,7 +234,7 @@ func (s *JailTestSuite) TestSendSyncResponseOrder() {
go func(i int) {
defer wg.Done()
res := s.Jail.Call(testChatID, `["commands", "testCommand"]`, fmt.Sprintf(`{"val":%d}`, i))
if !strings.Contains(string(res), fmt.Sprintf("result\":%d", i*i)) {
if !strings.Contains(res, fmt.Sprintf("result\":%d", i*i)) {
errCh <- fmt.Errorf("result should be '%d', got %s", i*i, res)
}
}(i)
@ -243,7 +243,7 @@ func (s *JailTestSuite) TestSendSyncResponseOrder() {
go func(i int) {
defer wg.Done()
res := s.Jail.Call(testChatID, `["commands", "calculateGasPrice"]`, fmt.Sprintf(`%d`, i))
if strings.Contains(string(res), "error") {
if strings.Contains(res, "error") {
errCh <- fmt.Errorf("result should not contain 'error', got %s", res)
}
}(i)

View File

@ -24,6 +24,8 @@ import (
"github.com/stretchr/testify/suite"
)
const invalidTxID = "invalid-tx-id"
type initFunc func([]byte, *transactions.SendTxArgs)
func txURLString(result sign.Result) string {
@ -64,7 +66,7 @@ func (s *TransactionsTestSuite) TestCallRPCSendTransaction() {
s.Equal(params.SendTransactionMethodName, method)
txID := event["id"].(string)
signResult = s.Backend.ApproveSignRequest(string(txID), TestConfig.Account1.Password)
signResult = s.Backend.ApproveSignRequest(txID, TestConfig.Account1.Password)
s.NoError(signResult.Error, "cannot complete queued transaction %s", txID)
close(transactionCompleted)
}
@ -115,11 +117,11 @@ func (s *TransactionsTestSuite) TestCallRPCSendTransactionUpstream() {
txID := event["id"].(string)
// Complete with a wrong passphrase.
signResult = s.Backend.ApproveSignRequest(string(txID), "some-invalid-passphrase")
signResult = s.Backend.ApproveSignRequest(txID, "some-invalid-passphrase")
s.EqualError(signResult.Error, keystore.ErrDecrypt.Error(), "should return an error as the passphrase was invalid")
// Complete with a correct passphrase.
signResult = s.Backend.ApproveSignRequest(string(txID), TestConfig.Account2.Password)
signResult = s.Backend.ApproveSignRequest(txID, TestConfig.Account2.Password)
s.NoError(signResult.Error, "cannot complete queued transaction %s", txID)
close(transactionCompleted)
@ -257,7 +259,7 @@ func (s *TransactionsTestSuite) setDefaultNodeNotificationHandler(signRequestRes
// the first call will fail (we are not logged in, but trying to complete tx)
log.Info("trying to complete with no user logged in")
err = s.Backend.ApproveSignRequest(
string(event["id"].(string)),
event["id"].(string),
TestConfig.Account1.Password,
).Error
s.EqualError(
@ -271,7 +273,7 @@ func (s *TransactionsTestSuite) setDefaultNodeNotificationHandler(signRequestRes
err = s.Backend.SelectAccount(sampleAddress, TestConfig.Account1.Password)
s.NoError(err)
err = s.Backend.ApproveSignRequest(
string(event["id"].(string)),
event["id"].(string),
TestConfig.Account1.Password,
).Error
s.EqualError(
@ -284,7 +286,7 @@ func (s *TransactionsTestSuite) setDefaultNodeNotificationHandler(signRequestRes
log.Info("trying to complete with correct user, this should succeed")
s.NoError(s.Backend.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password))
result := s.Backend.ApproveSignRequest(
string(event["id"].(string)),
event["id"].(string),
TestConfig.Account1.Password,
)
if expectedError != nil {
@ -413,7 +415,7 @@ func (s *TransactionsTestSuite) TestSendEtherTxUpstream() {
log.Info("transaction queued (will be completed shortly)", "id", event["id"].(string))
signResult := s.Backend.ApproveSignRequest(
string(event["id"].(string)),
event["id"].(string),
TestConfig.Account1.Password,
)
s.NoError(signResult.Error, "cannot complete queued transaction[%v]", event["id"])
@ -467,7 +469,7 @@ func (s *TransactionsTestSuite) TestDoubleCompleteQueuedTransactions() {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID := string(event["id"].(string))
txID := event["id"].(string)
log.Info("transaction queued (will be failed and completed on the second call)", "id", txID)
// try with wrong password
@ -545,7 +547,7 @@ func (s *TransactionsTestSuite) TestDiscardQueuedTransaction() {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID := string(event["id"].(string))
txID := event["id"].(string)
log.Info("transaction queued (will be discarded soon)", "id", txID)
s.True(s.Backend.PendingSignRequests().Has(txID), "txqueue should still have test tx")
@ -635,7 +637,7 @@ func (s *TransactionsTestSuite) TestDiscardMultipleQueuedTransactions() {
s.NoError(err)
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID := string(event["id"].(string))
txID := event["id"].(string)
log.Info("transaction queued (will be discarded soon)", "id", txID)
s.True(s.Backend.PendingSignRequests().Has(txID),
@ -678,12 +680,12 @@ func (s *TransactionsTestSuite) TestDiscardMultipleQueuedTransactions() {
// wait for transactions, and discard immediately
discardTxs := func(txIDs []string) {
txIDs = append(txIDs, "invalid-tx-id")
txIDs = append(txIDs, invalidTxID)
// discard
discardResults := s.Backend.DiscardSignRequests(txIDs)
require.Len(discardResults, 1, "cannot discard txs: %v", discardResults)
require.Error(discardResults["invalid-tx-id"], sign.ErrSignReqNotFound, "cannot discard txs: %v", discardResults)
require.Error(discardResults[invalidTxID], sign.ErrSignReqNotFound, "cannot discard txs: %v", discardResults)
// try completing discarded transaction
completeResults := s.Backend.ApproveSignRequests(txIDs, TestConfig.Account1.Password)
@ -787,7 +789,7 @@ func (s *TransactionsTestSuite) sendConcurrentTransactions(testTxCount int) {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID := string(event["id"].(string))
txID := event["id"].(string)
log.Info("transaction queued (will be completed in a single call, once aggregated)", "id", txID)
txIDs <- txID
@ -807,18 +809,18 @@ func (s *TransactionsTestSuite) sendConcurrentTransactions(testTxCount int) {
// wait for transactions, and complete them in a single call
completeTxs := func(txIDs []string) {
txIDs = append(txIDs, "invalid-tx-id")
txIDs = append(txIDs, invalidTxID)
results := s.Backend.ApproveSignRequests(txIDs, TestConfig.Account1.Password)
s.Len(results, testTxCount+1)
s.EqualError(results["invalid-tx-id"].Error, sign.ErrSignReqNotFound.Error())
s.EqualError(results[invalidTxID].Error, sign.ErrSignReqNotFound.Error())
for txID, txResult := range results {
s.False(
txResult.Error != nil && txID != "invalid-tx-id",
txResult.Error != nil && txID != invalidTxID,
"invalid error for %s", txID,
)
s.False(
len(txResult.Response.Bytes()) < 1 && txID != "invalid-tx-id",
len(txResult.Response.Bytes()) < 1 && txID != invalidTxID,
"invalid hash (expected non empty hash): %s", txID,
)
log.Info("transaction complete", "URL", txURLString(txResult))

View File

@ -92,7 +92,7 @@ func (s *WhisperExtensionSuite) TestExpiredSignal() {
Type string
Event json.RawMessage
}
fmt.Println(string(rawSignal))
fmt.Println(rawSignal)
s.NoError(json.Unmarshal([]byte(rawSignal), &sg))
if sg.Type == signal.EventEnvelopeExpired {

View File

@ -19,6 +19,8 @@ import (
"github.com/stretchr/testify/suite"
)
const mailboxPassword = "status-offline-inbox"
type WhisperMailboxSuite struct {
suite.Suite
}
@ -60,7 +62,7 @@ func (s *WhisperMailboxSuite) TestRequestMessageFromMailboxAsync() {
s.Require().NoError(err)
// Generate mailbox symkey.
password := "status-offline-inbox"
password := mailboxPassword
MailServerKeyID, err := senderWhisperService.AddSymKeyFromPassword(password)
s.Require().NoError(err)
@ -168,7 +170,7 @@ func (s *WhisperMailboxSuite) TestRequestMessagesInGroupChat() {
charlieRPCClient := charlieBackend.StatusNode().RPCClient()
// Bob and charlie add the mailserver key.
password := "status-offline-inbox"
password := mailboxPassword
bobMailServerKeyID, err := bobWhisperService.AddSymKeyFromPassword(password)
s.Require().NoError(err)
charlieMailServerKeyID, err := charlieWhisperService.AddSymKeyFromPassword(password)

View File

@ -104,7 +104,7 @@ func (t *Transactor) validateAccount(args SendTxArgs, selectedAccount *account.S
}
func (t *Transactor) validateAndPropagate(selectedAccount *account.SelectedExtKey, args SendTxArgs) (hash gethcommon.Hash, err error) {
if err := t.validateAccount(args, selectedAccount); err != nil {
if err = t.validateAccount(args, selectedAccount); err != nil {
return hash, err
}
if !args.Valid() {

View File

@ -114,7 +114,7 @@ func (s *TxQueueTestSuite) setupTransactionPoolAPI(args SendTxArgs, returnNonce,
func (s *TxQueueTestSuite) rlpEncodeTx(args SendTxArgs, config *params.NodeConfig, account *account.SelectedExtKey, nonce *hexutil.Uint64, gas hexutil.Uint64, gasPrice *big.Int) hexutil.Bytes {
newTx := types.NewTransaction(
uint64(*nonce),
gethcommon.Address(*args.To),
*args.To,
args.Value.ToInt(),
uint64(gas),
gasPrice,