Move signal logic into signal package

This commit is contained in:
Ivan Danyliuk 2018-05-03 09:35:58 +02:00
parent c8a553f9c1
commit 953c26e8cf
No known key found for this signature in database
GPG Key ID: 97ED33CE024E1DBF
29 changed files with 312 additions and 258 deletions

View File

@ -17,10 +17,10 @@ import (
"github.com/status-im/status-go/geth/notifications/push/fcm"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/rpc"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/geth/transactions"
"github.com/status-im/status-go/services/personal"
"github.com/status-im/status-go/sign"
"github.com/status-im/status-go/signal"
)
const (
@ -114,12 +114,7 @@ func (b *StatusBackend) StartNode(config *params.NodeConfig) error {
defer b.mu.Unlock()
if err := b.startNode(config); err != nil {
signal.Send(signal.Envelope{
Type: signal.EventNodeCrashed,
Event: signal.NodeCrashEvent{
Error: err,
},
})
signal.SendNodeCrashed(err)
return err
}
@ -137,7 +132,7 @@ func (b *StatusBackend) startNode(config *params.NodeConfig) (err error) {
if err = b.statusNode.Start(config); err != nil {
return
}
signal.Send(signal.Envelope{Type: signal.EventNodeStarted})
signal.SendNodeStarted()
b.transactor.SetNetworkID(config.NetworkID)
b.transactor.SetRPC(b.statusNode.RPCClient(), rpc.DefaultCallTimeout)
@ -155,7 +150,7 @@ func (b *StatusBackend) startNode(config *params.NodeConfig) (err error) {
}
b.log.Info("Account reselected")
signal.Send(signal.Envelope{Type: signal.EventNodeReady})
signal.SendNodeReady()
return nil
}
@ -172,7 +167,7 @@ func (b *StatusBackend) stopNode() error {
return node.ErrNoRunningNode
}
b.jailManager.Stop()
defer signal.Send(signal.Envelope{Type: signal.EventNodeStopped})
defer signal.SendNodeStopped()
return b.statusNode.Stop()
}
@ -205,7 +200,7 @@ func (b *StatusBackend) ResetChainData() error {
if err := b.statusNode.ResetChainData(&newcfg); err != nil {
return err
}
signal.Send(signal.Envelope{Type: signal.EventChainDataRemoved})
signal.SendChainDataRemoved()
return b.startNode(&newcfg)
}

View File

@ -6,19 +6,17 @@ import (
"strings"
"github.com/robertkrimen/otto"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/signal"
)
// Write provides the base function to write data to the underline writer
// for the underline otto vm.
func Write(fn otto.FunctionCall, w io.Writer, consoleEventName string) otto.Value {
signal.Send(signal.Envelope{
Type: consoleEventName,
Event: convertArgs(fn.ArgumentList),
})
func Write(fn otto.FunctionCall, w io.Writer) otto.Value {
args := convertArgs(fn.ArgumentList)
signal.SendConsole(args)
// Next print out the giving values.
fmt.Fprintf(w, "%s: %s", consoleEventName, formatForConsole(fn.ArgumentList))
fmt.Fprintf(w, "%s: %s", signal.EventVMConsole, formatForConsole(fn.ArgumentList))
return otto.UndefinedValue()
}

View File

@ -9,7 +9,7 @@ import (
"github.com/robertkrimen/otto"
"github.com/status-im/status-go/geth/jail/console"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/signal"
"github.com/stretchr/testify/suite"
)
@ -41,7 +41,7 @@ func (s *ConsoleTestSuite) TestConsoleLog() {
err := s.vm.Set("console", map[string]interface{}{
"log": func(fn otto.FunctionCall) otto.Value {
return console.Write(fn, &customWriter, "vm.console")
return console.Write(fn, &customWriter)
},
})
require.NoError(err)
@ -70,7 +70,7 @@ func (s *ConsoleTestSuite) TestObjectLogging() {
err := json.Unmarshal([]byte(event), &eventReceived)
require.NoError(err)
require.Equal(eventReceived.Type, "vm.console")
require.Equal(eventReceived.Type, signal.EventVMConsole)
require.NotEmpty(eventReceived.Event)
objectReceived := eventReceived.Event[0]
@ -80,7 +80,7 @@ func (s *ConsoleTestSuite) TestObjectLogging() {
err := s.vm.Set("console", map[string]interface{}{
"log": func(fn otto.FunctionCall) otto.Value {
return console.Write(fn, &customWriter, "vm.console")
return console.Write(fn, &customWriter)
},
})
require.NoError(err)

View File

@ -5,14 +5,7 @@ import (
"github.com/robertkrimen/otto"
"github.com/status-im/status-go/geth/jail/console"
"github.com/status-im/status-go/geth/signal"
)
const (
// EventSignal is a signal from jail.
EventSignal = "jail.signal"
// eventConsoleLog defines the event type for the console.log call.
eventConsoleLog = "vm.console.log"
"github.com/status-im/status-go/signal"
)
// registerWeb3Provider creates an object called "jeth",
@ -21,7 +14,7 @@ func registerWeb3Provider(jail *Jail, cell *Cell) error {
jeth := map[string]interface{}{
"console": map[string]interface{}{
"log": func(fn otto.FunctionCall) otto.Value {
return console.Write(fn, os.Stdout, eventConsoleLog)
return console.Write(fn, os.Stdout)
},
},
"send": createSendHandler(jail, cell),
@ -132,16 +125,7 @@ func createSendSignalHandler(cell *Cell) func(otto.FunctionCall) otto.Value {
return func(call otto.FunctionCall) otto.Value {
message := call.Argument(0).String()
signal.Send(signal.Envelope{
Type: EventSignal,
Event: struct {
ChatID string `json:"chat_id"`
Data string `json:"data"`
}{
ChatID: cell.id,
Data: message,
},
})
signal.SendJailSignal(cell.id, message)
// As it's a sync call, it's called already from a thread-safe context,
// thus using otto.Otto directly. Otherwise, it would try to acquire a lock again

View File

@ -14,7 +14,7 @@ import (
gethrpc "github.com/ethereum/go-ethereum/rpc"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/rpc"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/signal"
"github.com/stretchr/testify/suite"
)

View File

@ -13,6 +13,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/discv5"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/signal"
)
var (
@ -95,8 +96,7 @@ func (p *PeerPool) Start(server *p2p.Server) error {
p.topics = append(p.topics, topicPool)
}
// discovery must be already started when pool is started
SendDiscoveryStarted()
signal.SendDiscoveryStarted() // discovery must be already started when pool is started
p.events = make(chan *p2p.PeerEvent, 20)
p.serverSubscription = server.SubscribeEvents(p.events)
@ -120,7 +120,7 @@ func (p *PeerPool) startDiscovery(server *p2p.Server) error {
p.timeout = time.After(p.discServerTimeout)
p.mu.Unlock()
SendDiscoveryStarted()
signal.SendDiscoveryStarted()
return nil
}
@ -140,7 +140,7 @@ func (p *PeerPool) stopDiscovery(server *p2p.Server) {
t.StopSearch()
}
SendDiscoveryStopped()
signal.SendDiscoveryStopped()
}
// restartDiscovery and search for topics that have peer count below min

View File

@ -18,7 +18,7 @@ import (
"github.com/stretchr/testify/suite"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/signal"
)
type PeerPoolSimulationSuite struct {
@ -114,11 +114,11 @@ func (s *PeerPoolSimulationSuite) TestSingleTopicDiscoveryWithFailover() {
}
s.NoError(json.Unmarshal([]byte(jsonEvent), &envelope))
switch envelope.Type {
case DiscoveryStarted:
case signal.EventDiscoveryStarted:
poolEvents <- envelope.Type
case DiscoveryStopped:
case signal.EventDiscoveryStopped:
poolEvents <- envelope.Type
case DiscoverySummary:
case signal.EventDiscoverySummary:
poolEvents <- envelope.Type
var summary map[string]int
s.NoError(json.Unmarshal(envelope.Event, &summary))
@ -142,13 +142,13 @@ func (s *PeerPoolSimulationSuite) TestSingleTopicDiscoveryWithFailover() {
defer subscription.Unsubscribe()
s.NoError(peerPool.Start(s.peers[1]))
defer peerPool.Stop()
s.Equal(DiscoveryStarted, s.getPoolEvent(poolEvents))
s.Equal(signal.EventDiscoveryStarted, s.getPoolEvent(poolEvents))
connected := s.getPeerFromEvent(events, p2p.PeerEventTypeAdd)
s.Equal(s.peers[0].Self().ID, connected)
s.Equal(DiscoveryStopped, s.getPoolEvent(poolEvents))
s.Equal(signal.EventDiscoveryStopped, s.getPoolEvent(poolEvents))
s.Require().Nil(s.peers[1].DiscV5)
s.Require().Equal(DiscoverySummary, s.getPoolEvent(poolEvents))
s.Require().Equal(signal.EventDiscoverySummary, s.getPoolEvent(poolEvents))
summary := <-summaries
s.Len(summary, 1)
s.Contains(summary, "shh/6")
@ -159,19 +159,19 @@ func (s *PeerPoolSimulationSuite) TestSingleTopicDiscoveryWithFailover() {
disconnected := s.getPeerFromEvent(events, p2p.PeerEventTypeDrop)
s.Equal(connected, disconnected)
s.Require().Equal(DiscoverySummary, s.getPoolEvent(poolEvents))
s.Require().Equal(signal.EventDiscoverySummary, s.getPoolEvent(poolEvents))
summary = <-summaries
s.Len(summary, 0)
s.Equal(DiscoveryStarted, s.getPoolEvent(poolEvents))
s.Equal(signal.EventDiscoveryStarted, s.getPoolEvent(poolEvents))
s.Require().NotNil(s.peers[1].DiscV5)
register = NewRegister(topic)
s.Require().NoError(register.Start(s.peers[2]))
defer register.Stop()
s.Equal(s.peers[2].Self().ID, s.getPeerFromEvent(events, p2p.PeerEventTypeAdd))
s.Equal(DiscoveryStopped, s.getPoolEvent(poolEvents))
s.Require().Equal(DiscoverySummary, s.getPoolEvent(poolEvents))
s.Equal(signal.EventDiscoveryStopped, s.getPoolEvent(poolEvents))
s.Require().Equal(signal.EventDiscoverySummary, s.getPoolEvent(poolEvents))
summary = <-summaries
s.Len(summary, 1)
s.Contains(summary, "shh/6")
@ -210,10 +210,10 @@ func TestPeerPoolMaxPeersOverflow(t *testing.T) {
pool := NewPeerPool(nil, DefaultFastSync, DefaultSlowSync, nil, true)
require.NoError(t, pool.Start(peer))
require.Equal(t, DiscoveryStarted, <-signals)
require.Equal(t, signal.EventDiscoveryStarted, <-signals)
// without config, it will stop the discovery because all topic pools are satisfied
pool.events <- &p2p.PeerEvent{Type: p2p.PeerEventTypeAdd}
require.Equal(t, DiscoveryStopped, <-signals)
require.Equal(t, signal.EventDiscoveryStopped, <-signals)
require.Nil(t, peer.DiscV5)
// another peer added after discovery is stopped should not panic
pool.events <- &p2p.PeerEvent{Type: p2p.PeerEventTypeAdd}
@ -234,7 +234,7 @@ func TestPeerPoolDiscV5Timeout(t *testing.T) {
// In this case, a strange PeerEventTypeDrop event was emitted.
go func() {
switch typ := envelope.Type; typ {
case DiscoveryStarted, DiscoveryStopped:
case signal.EventDiscoveryStarted, signal.EventDiscoveryStopped:
signals <- envelope.Type
}
}()
@ -259,12 +259,12 @@ func TestPeerPoolDiscV5Timeout(t *testing.T) {
pool := NewPeerPool(nil, DefaultFastSync, DefaultSlowSync, nil, true)
pool.discServerTimeout = time.Millisecond * 100
require.NoError(t, pool.Start(server))
require.Equal(t, DiscoveryStarted, <-signals)
require.Equal(t, signal.EventDiscoveryStarted, <-signals)
// timeout after finding no peers
select {
case sig := <-signals:
require.Equal(t, DiscoveryStopped, sig)
require.Equal(t, signal.EventDiscoveryStopped, sig)
case <-time.After(pool.discServerTimeout * 2):
t.Fatal("timed out")
}
@ -272,12 +272,12 @@ func TestPeerPoolDiscV5Timeout(t *testing.T) {
// timeout after discovery restart
require.NoError(t, pool.restartDiscovery(server))
require.Equal(t, DiscoveryStarted, <-signals)
require.Equal(t, signal.EventDiscoveryStarted, <-signals)
require.NotNil(t, server.DiscV5)
pool.events <- &p2p.PeerEvent{Type: p2p.PeerEventTypeDrop} // required to turn the loop and pick up new timeout
select {
case sig := <-signals:
require.Equal(t, DiscoveryStopped, sig)
require.Equal(t, signal.EventDiscoveryStopped, sig)
case <-time.After(pool.discServerTimeout * 2):
t.Fatal("timed out")
}

View File

@ -2,34 +2,9 @@ package peers
import (
"github.com/ethereum/go-ethereum/p2p"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/signal"
)
const (
// DiscoveryStarted is sent when node discv5 was started.
DiscoveryStarted = "discovery.started"
// DiscoveryStopped is sent when discv5 server was stopped.
DiscoveryStopped = "discovery.stopped"
// DiscoverySummary is sent when peer is added or removed.
// it will be a map with capability=peer count k/v's.
DiscoverySummary = "discovery.summary"
)
// SendDiscoveryStarted sends discovery.started signal.
func SendDiscoveryStarted() {
signal.Send(signal.Envelope{
Type: DiscoveryStarted,
})
}
// SendDiscoveryStopped sends discovery.stopped signal.
func SendDiscoveryStopped() {
signal.Send(signal.Envelope{
Type: DiscoveryStopped,
})
}
// SendDiscoverySummary sends discovery.summary signal.
func SendDiscoverySummary(peers []*p2p.PeerInfo) {
summary := map[string]int{}
@ -38,8 +13,5 @@ func SendDiscoverySummary(peers []*p2p.PeerInfo) {
summary[cap]++
}
}
signal.Send(signal.Envelope{
Type: DiscoverySummary,
Event: summary,
})
signal.SendDiscoverySummary(summary)
}

View File

@ -33,9 +33,9 @@ import (
"github.com/status-im/status-go/geth/account"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/geth/transactions"
"github.com/status-im/status-go/sign"
"github.com/status-im/status-go/signal"
"github.com/status-im/status-go/static"
. "github.com/status-im/status-go/t/utils" //nolint: golint
)
@ -825,7 +825,7 @@ func testCompleteTransaction(t *testing.T) bool {
t.Errorf("cannot unmarshal event's JSON: %s. Error %q", jsonEvent, err)
return
}
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
t.Logf("transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string))
@ -902,7 +902,7 @@ func testCompleteMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocyc
t.Errorf("cannot unmarshal event's JSON: %s", jsonEvent)
return
}
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID = event["id"].(string)
t.Logf("transaction queued (will be completed in a single call, once aggregated): {id: %s}\n", txID)
@ -1034,7 +1034,7 @@ func testDiscardTransaction(t *testing.T) bool { //nolint: gocyclo
t.Errorf("cannot unmarshal event's JSON: %s", jsonEvent)
return
}
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID = event["id"].(string)
t.Logf("transaction queued (will be discarded soon): {id: %s}\n", txID)
@ -1072,7 +1072,7 @@ func testDiscardTransaction(t *testing.T) bool { //nolint: gocyclo
completeQueuedTransaction <- struct{}{} // so that timeout is aborted
}
if envelope.Type == sign.EventSignRequestFailed {
if envelope.Type == signal.EventSignRequestFailed {
event := envelope.Event.(map[string]interface{})
t.Logf("transaction return event received: {id: %s}\n", event["id"].(string))
@ -1148,7 +1148,7 @@ func testDiscardMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocycl
t.Errorf("cannot unmarshal event's JSON: %s", jsonEvent)
return
}
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID = event["id"].(string)
t.Logf("transaction queued (will be discarded soon): {id: %s}\n", txID)
@ -1161,7 +1161,7 @@ func testDiscardMultipleQueuedTransactions(t *testing.T) bool { //nolint: gocycl
txIDs <- txID
}
if envelope.Type == sign.EventSignRequestFailed {
if envelope.Type == signal.EventSignRequestFailed {
event := envelope.Event.(map[string]interface{})
t.Logf("transaction return event received: {id: %s}\n", event["id"].(string))
@ -1462,7 +1462,7 @@ func startTestNode(t *testing.T) <-chan struct{} {
return
}
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
}
if envelope.Type == signal.EventNodeStarted {
t.Log("Node started, but we wait till it be ready")

View File

@ -2,29 +2,18 @@ package shhext
import (
"github.com/ethereum/go-ethereum/common"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/signal"
)
// EnvelopeSignal includes hash of the envelope.
type EnvelopeSignal struct {
Hash common.Hash `json:"hash"`
}
// EnvelopeSignalHandler sends signals when envelope is sent or expired.
type EnvelopeSignalHandler struct{}
// EnvelopeSent triggered when envelope delivered atleast to 1 peer.
func (h EnvelopeSignalHandler) EnvelopeSent(hash common.Hash) {
signal.Send(signal.Envelope{
Type: signal.EventEnvelopeSent,
Event: EnvelopeSignal{Hash: hash},
})
signal.SendEnvelopeSent(hash)
}
// EnvelopeExpired triggered when envelope is expired but wasn't delivered to any peer.
func (h EnvelopeSignalHandler) EnvelopeExpired(hash common.Hash) {
signal.Send(signal.Envelope{
Type: signal.EventEnvelopeExpired,
Event: EnvelopeSignal{Hash: hash},
})
signal.SendEnvelopeExpired(hash)
}

View File

@ -4,27 +4,7 @@ import (
"context"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/status-im/status-go/geth/signal"
)
const (
// EventSignRequestAdded is triggered when send transaction request is queued
EventSignRequestAdded = "sign-request.queued"
// EventSignRequestFailed is triggered when send transaction request fails
EventSignRequestFailed = "sign-request.failed"
)
const (
// SignRequestNoErrorCode is sent when no error occurred.
SignRequestNoErrorCode = iota
// SignRequestDefaultErrorCode is every case when there is no special tx return code.
SignRequestDefaultErrorCode
// SignRequestPasswordErrorCode is sent when account failed verification.
SignRequestPasswordErrorCode
// SignRequestTimeoutErrorCode is sent when tx is timed out.
SignRequestTimeoutErrorCode
// SignRequestDiscardedErrorCode is sent when tx was discarded.
SignRequestDiscardedErrorCode
"github.com/status-im/status-go/signal"
)
const (
@ -47,60 +27,47 @@ func messageIDFromContext(ctx context.Context) string {
return ""
}
var txReturnCodes = map[error]int{
nil: SignRequestNoErrorCode,
keystore.ErrDecrypt: SignRequestPasswordErrorCode,
ErrSignReqTimedOut: SignRequestTimeoutErrorCode,
ErrSignReqDiscarded: SignRequestDiscardedErrorCode,
// SendSignRequestAdded sends a signal when a sign request is added.
func SendSignRequestAdded(request *Request) {
signal.SendSignRequestAdded(
signal.PendingRequestEvent{
ID: request.ID,
Args: request.Meta,
Method: request.Method,
MessageID: messageIDFromContext(request.context),
})
}
// PendingRequestEvent is a signal sent when a sign request is added
type PendingRequestEvent struct {
ID string `json:"id"`
Method string `json:"method"`
Args interface{} `json:"args"`
MessageID string `json:"message_id"`
}
// NotifyOnEnqueue sends a signal when a sign request is added
func NotifyOnEnqueue(request *Request) {
signal.Send(signal.Envelope{
Type: EventSignRequestAdded,
Event: PendingRequestEvent{
// SendSignRequestFailed sends a signal only if error had happened
func SendSignRequestFailed(request *Request, err error) {
signal.SendSignRequestFailed(
signal.PendingRequestEvent{
ID: request.ID,
Args: request.Meta,
Method: request.Method,
MessageID: messageIDFromContext(request.context),
},
})
err, sendTransactionErrorCode(err))
}
// PendingRequestErrorEvent is a signal sent when sign request has failed
type PendingRequestErrorEvent struct {
PendingRequestEvent
ErrorMessage string `json:"error_message"`
ErrorCode int `json:"error_code,string"`
}
const (
// SignRequestNoErrorCode is sent when no error occurred.
SignRequestNoErrorCode = iota
// SignRequestDefaultErrorCode is every case when there is no special tx return code.
SignRequestDefaultErrorCode
// SignRequestPasswordErrorCode is sent when account failed verification.
SignRequestPasswordErrorCode
// SignRequestTimeoutErrorCode is sent when tx is timed out.
SignRequestTimeoutErrorCode
// SignRequestDiscardedErrorCode is sent when tx was discarded.
SignRequestDiscardedErrorCode
)
// NotifyIfError sends a signal only if error had happened
func NotifyIfError(request *Request, err error) {
// we don't want to notify a user if tx was sent successfully
if err == nil {
return
}
signal.Send(signal.Envelope{
Type: EventSignRequestFailed,
Event: PendingRequestErrorEvent{
PendingRequestEvent: PendingRequestEvent{
ID: request.ID,
Args: request.Meta,
Method: request.Method,
MessageID: messageIDFromContext(request.context),
},
ErrorMessage: err.Error(),
ErrorCode: sendTransactionErrorCode(err),
},
})
var txReturnCodes = map[error]int{
nil: SignRequestNoErrorCode,
keystore.ErrDecrypt: SignRequestPasswordErrorCode,
ErrSignReqTimedOut: SignRequestTimeoutErrorCode,
ErrSignReqDiscarded: SignRequestDiscardedErrorCode,
}
func sendTransactionErrorCode(err error) int {

View File

@ -38,7 +38,7 @@ func (rs *PendingRequests) Add(ctx context.Context, method string, meta Meta, co
rs.requests[request.ID] = request
rs.log.Info("signing request is created", "ID", request.ID)
go NotifyOnEnqueue(request)
go SendSignRequestAdded(request)
return request, nil
}
@ -160,7 +160,10 @@ func (rs *PendingRequests) complete(request *Request, response Response, err err
request.locked = false
go NotifyIfError(request, err)
if err != nil {
// TODO(divan): do we need the goroutine here?
go SendSignRequestFailed(request, err)
}
if err != nil && isTransient(err) {
return

5
signal/doc.go Normal file
View File

@ -0,0 +1,5 @@
// Package signal implements event-based signalling interface between status-go
// and externally linked codebases like status-react or status-desktop.
// Events are send asynchronously using OS-specific linking mechanisms. See sources
// for implementation details.
package signal

View File

@ -0,0 +1,27 @@
package signal
const (
// EventDiscoveryStarted is sent when node discv5 was started.
EventDiscoveryStarted = "discovery.started"
// EventDiscoveryStopped is sent when discv5 server was stopped.
EventDiscoveryStopped = "discovery.stopped"
// EventDiscoverySummary is sent when peer is added or removed.
// it will be a map with capability=peer count k/v's.
EventDiscoverySummary = "discovery.summary"
)
// SendDiscoveryStarted sends discovery.started signal.
func SendDiscoveryStarted() {
send(EventDiscoveryStarted, nil)
}
// SendDiscoveryStopped sends discovery.stopped signal.
func SendDiscoveryStopped() {
send(EventDiscoveryStopped, nil)
}
// SendDiscoverySummary sends discovery.summary signal.
func SendDiscoverySummary(summary map[string]int) {
send(EventDiscoverySummary, summary)
}

25
signal/events_jail.go Normal file
View File

@ -0,0 +1,25 @@
package signal
// Jail related event names
const (
EventVMConsole = "vm.console"
EventJailSignal = "jail.signal"
)
// SendConsole is a signal sent when jail writes anything to console.
func SendConsole(args interface{}) {
send(EventVMConsole, args)
}
// SendJailSignal is nobody knows what.
// TODO(divan, adamb): investigate if this even needed.
func SendJailSignal(cellID, message string) {
send(EventJailSignal,
struct {
ChatID string `json:"chat_id"`
Data string `json:"data"`
}{
ChatID: cellID,
Data: message,
})
}

55
signal/events_node.go Normal file
View File

@ -0,0 +1,55 @@
package signal
const (
// EventNodeStarted is triggered when underlying node is started
EventNodeStarted = "node.started"
// EventNodeReady is triggered when underlying node is fully ready
// (consider backend to be fully registered)
EventNodeReady = "node.ready"
// EventNodeStopped is triggered when underlying node is fully stopped
EventNodeStopped = "node.stopped"
// EventNodeCrashed is triggered when node crashes
EventNodeCrashed = "node.crashed"
// EventChainDataRemoved is triggered when node's chain data is removed
EventChainDataRemoved = "chaindata.removed"
)
// NodeCrashEvent is special kind of error, used to report node crashes
type NodeCrashEvent struct {
Error string `json:"error"`
}
// SendNodeCrashed emits a signal when status node has crashed, and
// provides error description.
func SendNodeCrashed(err error) {
send(EventNodeCrashed,
NodeCrashEvent{
Error: err.Error(),
})
}
// SendNodeStarted emits a signal when status node has just started (but not
// finished startup yet).
func SendNodeStarted() {
send(EventNodeStarted, nil)
}
// SendNodeReady emits a signal when status node has started and successfully
// completed startup.
func SendNodeReady() {
send(EventNodeReady, nil)
}
// SendNodeStopped emits a signal when underlying node has stopped.
func SendNodeStopped() {
send(EventNodeStopped, nil)
}
// SendChainDataRemoved emits a signal when node's chain data has been removed.
func SendChainDataRemoved() {
send(EventChainDataRemoved, nil)
}

27
signal/events_shhext.go Normal file
View File

@ -0,0 +1,27 @@
package signal
import "github.com/ethereum/go-ethereum/common"
const (
// EventEnvelopeSent is triggered when envelope was sent at least to a one peer.
EventEnvelopeSent = "envelope.sent"
// EventEnvelopeExpired is triggered when envelop was dropped by a whisper without being sent
// to any peer
EventEnvelopeExpired = "envelope.expired"
)
// EnvelopeSignal includes hash of the envelope.
type EnvelopeSignal struct {
Hash common.Hash `json:"hash"`
}
// SendEnvelopeSent triggered when envelope delivered at least to 1 peer.
func SendEnvelopeSent(hash common.Hash) {
send(EventEnvelopeSent, EnvelopeSignal{hash})
}
// SendEnvelopeExpired triggered when envelope delivered at least to 1 peer.
func SendEnvelopeExpired(hash common.Hash) {
send(EventEnvelopeExpired, EnvelopeSignal{hash})
}

38
signal/events_sign.go Normal file
View File

@ -0,0 +1,38 @@
package signal
const (
// EventSignRequestAdded is triggered when send transaction request is queued
EventSignRequestAdded = "sign-request.queued"
// EventSignRequestFailed is triggered when send transaction request fails
EventSignRequestFailed = "sign-request.failed"
)
// PendingRequestEvent is a signal sent when a sign request is added
type PendingRequestEvent struct {
ID string `json:"id"`
Method string `json:"method"`
Args interface{} `json:"args"`
MessageID string `json:"message_id"`
}
// SendSignRequestAdded sends a signal when a sign request is added.
func SendSignRequestAdded(event PendingRequestEvent) {
send(EventSignRequestAdded, event)
}
// PendingRequestErrorEvent is a signal sent when sign request has failed
type PendingRequestErrorEvent struct {
PendingRequestEvent
ErrorMessage string `json:"error_message"`
ErrorCode int `json:"error_code,string"`
}
// SendSignRequestFailed sends a signal of failed sign request.
func SendSignRequestFailed(event PendingRequestEvent, err error, errCode int) {
send(EventSignRequestFailed,
PendingRequestErrorEvent{
PendingRequestEvent: event,
ErrorMessage: err.Error(),
ErrorCode: errCode,
})
}

View File

@ -14,30 +14,8 @@ import (
"github.com/ethereum/go-ethereum/log"
)
const (
// EventNodeStarted is triggered when underlying node is started
EventNodeStarted = "node.started"
// EventNodeReady is triggered when underlying node is fully ready
// (consider backend to be fully registered)
EventNodeReady = "node.ready"
// EventNodeStopped is triggered when underlying node is fully stopped
EventNodeStopped = "node.stopped"
// EventNodeCrashed is triggered when node crashes
EventNodeCrashed = "node.crashed"
// EventChainDataRemoved is triggered when node's chain data is removed
EventChainDataRemoved = "chaindata.removed"
// EventEnvelopeSent is triggered when envelope was sent atleast to a one peer.
EventEnvelopeSent = "envelope.sent"
// EventEnvelopeExpired is triggered when envelop was dropped by a whisper without being sent
// to any peer
EventEnvelopeExpired = "envelope.expired"
)
// All general log messages in this package should be routed through this logger.
var logger = log.New("package", "status-go/signal")
// Envelope is a general signal sent upward from node to RN app
type Envelope struct {
@ -45,21 +23,22 @@ type Envelope struct {
Event interface{} `json:"event"`
}
// NodeCrashEvent is special kind of error, used to report node crashes
type NodeCrashEvent struct {
Error error `json:"error"`
// NewEnvelope creates new envlope of given type and event payload.
func NewEnvelope(typ string, event interface{}) *Envelope {
return &Envelope{
Type: typ,
Event: event,
}
}
// All general log messages in this package should be routed through this logger.
var logger = log.New("package", "status-go/geth/signal")
// MarshalJSON implements the json.Marshaller interface.
func (e NodeCrashEvent) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Error string `json:"error"`
}{
Error: e.Error.Error(),
})
// send sends application signal (in JSON) upwards to application (via default notification handler)
func send(typ string, event interface{}) {
signal := NewEnvelope(typ, event)
data, err := json.Marshal(&signal)
if err != nil {
logger.Error("Marshalling signal envelope", "error", err)
}
C.StatusServiceSignalEvent(C.CString(string(data)))
}
// NodeNotificationHandler defines a handler able to process incoming node events.
@ -90,12 +69,6 @@ func TriggerDefaultNodeNotificationHandler(jsonEvent string) {
logger.Info("Notification received", "event", jsonEvent)
}
// Send sends application signal (JSON, normally) upwards to application (via default notification handler)
func Send(signal Envelope) {
data, _ := json.Marshal(&signal)
C.StatusServiceSignalEvent(C.CString(string(data)))
}
//export NotifyNode
//nolint: golint
func NotifyNode(jsonEvent *C.char) {

View File

@ -2,7 +2,6 @@ package signal
import (
"encoding/json"
"errors"
"fmt"
"testing"
@ -13,7 +12,7 @@ func TestNodeCrashEventJSONMarshalling(t *testing.T) {
errorMsg := "TestNodeCrashEventJSONMarshallingError"
expectedJSON := fmt.Sprintf(`{"error":"%s"}`, errorMsg)
nodeCrashEvent := &NodeCrashEvent{
Error: errors.New(errorMsg),
Error: errorMsg,
}
marshalled, err := json.Marshal(nodeCrashEvent)
require.NoError(t, err)

View File

@ -13,7 +13,7 @@ import (
"github.com/status-im/status-go/geth/api"
"github.com/status-im/status-go/geth/node"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/signal"
. "github.com/status-im/status-go/t/utils"
"github.com/stretchr/testify/suite"
)

View File

@ -13,8 +13,7 @@ import (
"github.com/status-im/status-go/geth/jail"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/sign"
"github.com/status-im/status-go/signal"
e2e "github.com/status-im/status-go/t/e2e"
. "github.com/status-im/status-go/t/utils"
"github.com/stretchr/testify/suite"
@ -133,7 +132,7 @@ func (s *JailRPCTestSuite) TestContractDeployment() {
unmarshalErr := json.Unmarshal([]byte(jsonEvent), &envelope)
s.NoError(unmarshalErr, "cannot unmarshal JSON: %s", jsonEvent)
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
s.T().Logf("transaction queued and will be completed shortly, id: %v", event["id"])
@ -291,7 +290,7 @@ func (s *JailRPCTestSuite) TestJailVMPersistence() {
s.T().Errorf("cannot unmarshal event's JSON: %s", jsonEvent)
return
}
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
s.T().Logf("Transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string))

View File

@ -12,7 +12,7 @@ import (
"github.com/status-im/status-go/geth/jail"
"github.com/status-im/status-go/geth/node"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/signal"
"github.com/status-im/status-go/static"
"github.com/status-im/status-go/t/e2e"
"github.com/stretchr/testify/suite"
@ -160,7 +160,7 @@ func (s *JailTestSuite) TestEventSignal() {
unmarshalErr := json.Unmarshal([]byte(jsonEvent), &envelope)
s.NoError(unmarshalErr)
if envelope.Type == jail.EventSignal {
if envelope.Type == signal.EventJailSignal {
event := envelope.Event.(map[string]interface{})
chatID, ok := event["chat_id"].(string)
s.True(ok, "chat id is required, but not found")

View File

@ -9,9 +9,8 @@ import (
"github.com/ethereum/go-ethereum/accounts/keystore"
acc "github.com/status-im/status-go/geth/account"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/services/personal"
"github.com/status-im/status-go/sign"
"github.com/status-im/status-go/signal"
e2e "github.com/status-im/status-go/t/e2e"
"github.com/stretchr/testify/suite"
@ -171,7 +170,7 @@ func (s *PersonalSignSuite) notificationHandlerNoAccountSelected(account string,
return func(jsonEvent string) {
s.notificationHandler(account, pass, acc.ErrNoAccountSelected)(jsonEvent)
envelope := unmarshalEnvelope(jsonEvent)
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
err := s.Backend.SelectAccount(TestConfig.Account1.Address, TestConfig.Account1.Password)
s.NoError(err)
}
@ -182,7 +181,7 @@ func (s *PersonalSignSuite) notificationHandlerNoAccountSelected(account string,
func (s *PersonalSignSuite) notificationHandler(account string, pass string, expectedError error) func(string) {
return func(jsonEvent string) {
envelope := unmarshalEnvelope(jsonEvent)
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
id := event["id"].(string)
s.T().Logf("Sign request added (will be completed shortly): {id: %s}\n", id)

View File

@ -7,9 +7,9 @@ import (
"github.com/status-im/status-go/geth/api"
"github.com/status-im/status-go/geth/node"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/geth/transactions"
"github.com/status-im/status-go/sign"
"github.com/status-im/status-go/signal"
. "github.com/status-im/status-go/t/utils" //nolint: golint
"github.com/stretchr/testify/suite"
)

View File

@ -16,9 +16,9 @@ import (
"github.com/ethereum/go-ethereum/log"
"github.com/status-im/status-go/geth/account"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/geth/transactions"
"github.com/status-im/status-go/sign"
"github.com/status-im/status-go/signal"
e2e "github.com/status-im/status-go/t/e2e"
. "github.com/status-im/status-go/t/utils"
"github.com/stretchr/testify/suite"
@ -57,7 +57,7 @@ func (s *TransactionsTestSuite) TestCallRPCSendTransaction() {
err := json.Unmarshal([]byte(rawSignal), &sg)
s.NoError(err)
if sg.Type == sign.EventSignRequestAdded {
if sg.Type == signal.EventSignRequestAdded {
event := sg.Event.(map[string]interface{})
//check for the correct method name
method := event["method"].(string)
@ -110,7 +110,7 @@ func (s *TransactionsTestSuite) TestCallRPCSendTransactionUpstream() {
err := json.Unmarshal([]byte(rawSignal), &signalEnvelope)
s.NoError(err)
if signalEnvelope.Type == sign.EventSignRequestAdded {
if signalEnvelope.Type == signal.EventSignRequestAdded {
event := signalEnvelope.Event.(map[string]interface{})
txID := event["id"].(string)
@ -165,8 +165,8 @@ func (s *TransactionsTestSuite) TestEmptyToFieldPreserved() {
}
err := json.Unmarshal([]byte(rawSignal), &sg)
s.NoError(err)
if sg.Type == sign.EventSignRequestAdded {
var event sign.PendingRequestEvent
if sg.Type == signal.EventSignRequestAdded {
var event signal.PendingRequestEvent
s.NoError(json.Unmarshal(sg.Event, &event))
args := event.Args.(map[string]interface{})
s.NotNil(args["from"])
@ -250,7 +250,7 @@ func (s *TransactionsTestSuite) setDefaultNodeNotificationHandler(signRequestRes
err := json.Unmarshal([]byte(jsonEvent), &envelope)
s.NoError(err, fmt.Sprintf("cannot unmarshal JSON: %s", jsonEvent))
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
log.Info("transaction queued (will be completed shortly)", "id", event["id"].(string))
@ -408,7 +408,7 @@ func (s *TransactionsTestSuite) TestSendEtherTxUpstream() {
err = json.Unmarshal([]byte(jsonEvent), &envelope)
s.NoError(err, "cannot unmarshal JSON: %s", jsonEvent)
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
log.Info("transaction queued (will be completed shortly)", "id", event["id"].(string))
@ -465,7 +465,7 @@ func (s *TransactionsTestSuite) TestDoubleCompleteQueuedTransactions() {
err := json.Unmarshal([]byte(jsonEvent), &envelope)
s.NoError(err, fmt.Sprintf("cannot unmarshal JSON: %s", jsonEvent))
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID := string(event["id"].(string))
log.Info("transaction queued (will be failed and completed on the second call)", "id", txID)
@ -488,7 +488,7 @@ func (s *TransactionsTestSuite) TestDoubleCompleteQueuedTransactions() {
close(completeQueuedTransaction)
}
if envelope.Type == sign.EventSignRequestFailed {
if envelope.Type == signal.EventSignRequestFailed {
event := envelope.Event.(map[string]interface{})
log.Info("transaction return event received", "id", event["id"].(string))
@ -543,7 +543,7 @@ func (s *TransactionsTestSuite) TestDiscardQueuedTransaction() {
err := json.Unmarshal([]byte(jsonEvent), &envelope)
s.NoError(err, fmt.Sprintf("cannot unmarshal JSON: %s", jsonEvent))
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID := string(event["id"].(string))
log.Info("transaction queued (will be discarded soon)", "id", txID)
@ -565,7 +565,7 @@ func (s *TransactionsTestSuite) TestDiscardQueuedTransaction() {
close(completeQueuedTransaction)
}
if envelope.Type == sign.EventSignRequestFailed {
if envelope.Type == signal.EventSignRequestFailed {
event := envelope.Event.(map[string]interface{})
log.Info("transaction return event received", "id", event["id"].(string))
@ -633,7 +633,7 @@ func (s *TransactionsTestSuite) TestDiscardMultipleQueuedTransactions() {
var envelope signal.Envelope
err := json.Unmarshal([]byte(jsonEvent), &envelope)
s.NoError(err)
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID := string(event["id"].(string))
log.Info("transaction queued (will be discarded soon)", "id", txID)
@ -643,7 +643,7 @@ func (s *TransactionsTestSuite) TestDiscardMultipleQueuedTransactions() {
txIDs <- txID
}
if envelope.Type == sign.EventSignRequestFailed {
if envelope.Type == signal.EventSignRequestFailed {
event := envelope.Event.(map[string]interface{})
log.Info("transaction return event received", "id", event["id"].(string))
@ -785,7 +785,7 @@ func (s *TransactionsTestSuite) sendConcurrentTransactions(testTxCount int) {
err := json.Unmarshal([]byte(jsonEvent), &envelope)
require.NoError(err, fmt.Sprintf("cannot unmarshal JSON: %s", jsonEvent))
if envelope.Type == sign.EventSignRequestAdded {
if envelope.Type == signal.EventSignRequestAdded {
event := envelope.Event.(map[string]interface{})
txID := string(event["id"].(string))
log.Info("transaction queued (will be completed in a single call, once aggregated)", "id", txID)

View File

@ -12,8 +12,7 @@ import (
whisper "github.com/ethereum/go-ethereum/whisper/whisperv6"
"github.com/status-im/status-go/geth/node"
"github.com/status-im/status-go/geth/params"
"github.com/status-im/status-go/geth/signal"
"github.com/status-im/status-go/services/shhext"
"github.com/status-im/status-go/signal"
"github.com/stretchr/testify/suite"
)
@ -57,7 +56,7 @@ func (s *WhisperExtensionSuite) TestSentSignal() {
s.NoError(json.Unmarshal([]byte(rawSignal), &sg))
if sg.Type == signal.EventEnvelopeSent {
var event shhext.EnvelopeSignal
var event signal.EnvelopeSignal
s.NoError(json.Unmarshal(sg.Event, &event))
confirmed <- event.Hash
}
@ -95,7 +94,7 @@ func (s *WhisperExtensionSuite) TestExpiredSignal() {
s.NoError(json.Unmarshal([]byte(rawSignal), &sg))
if sg.Type == signal.EventEnvelopeExpired {
var event shhext.EnvelopeSignal
var event signal.EnvelopeSignal
s.NoError(json.Unmarshal(sg.Event, &event))
expired <- event.Hash
}