2019-11-21 16:19:22 +00:00
|
|
|
package protocol
|
2019-07-17 22:25:42 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/ecdsa"
|
2019-07-30 06:14:13 +00:00
|
|
|
"database/sql"
|
2019-09-26 07:01:17 +00:00
|
|
|
"strings"
|
2019-07-17 22:25:42 +00:00
|
|
|
"time"
|
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
2019-07-17 22:25:42 +00:00
|
|
|
"github.com/pkg/errors"
|
2019-09-02 09:29:06 +00:00
|
|
|
"go.uber.org/zap"
|
2019-07-17 22:25:42 +00:00
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
"github.com/status-im/status-go/protocol/encryption"
|
|
|
|
"github.com/status-im/status-go/protocol/encryption/multidevice"
|
|
|
|
"github.com/status-im/status-go/protocol/encryption/sharedsecret"
|
|
|
|
"github.com/status-im/status-go/protocol/ens"
|
|
|
|
"github.com/status-im/status-go/protocol/identity/alias"
|
|
|
|
"github.com/status-im/status-go/protocol/identity/identicon"
|
|
|
|
"github.com/status-im/status-go/protocol/sqlite"
|
|
|
|
transport "github.com/status-im/status-go/protocol/transport/whisper"
|
|
|
|
whispertypes "github.com/status-im/status-go/protocol/transport/whisper/types"
|
|
|
|
protocol "github.com/status-im/status-go/protocol/types"
|
|
|
|
v1protocol "github.com/status-im/status-go/protocol/v1"
|
2019-07-17 22:25:42 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrChatIDEmpty = errors.New("chat ID is empty")
|
|
|
|
ErrNotImplemented = errors.New("not implemented")
|
2019-09-26 07:01:17 +00:00
|
|
|
|
|
|
|
errChatNotFound = errors.New("chat not found")
|
2019-07-17 22:25:42 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Messenger is a entity managing chats and messages.
|
|
|
|
// It acts as a bridge between the application and encryption
|
|
|
|
// layers.
|
|
|
|
// It needs to expose an interface to manage installations
|
|
|
|
// because installations are managed by the user.
|
|
|
|
// Similarly, it needs to expose an interface to manage
|
|
|
|
// mailservers because they can also be managed by the user.
|
|
|
|
type Messenger struct {
|
|
|
|
identity *ecdsa.PrivateKey
|
2019-07-30 06:14:13 +00:00
|
|
|
persistence *sqlitePersistence
|
2019-09-02 09:29:06 +00:00
|
|
|
transport *transport.WhisperServiceTransport
|
2019-07-17 22:25:42 +00:00
|
|
|
encryptor *encryption.Protocol
|
2019-09-02 09:29:06 +00:00
|
|
|
processor *messageProcessor
|
2019-07-26 07:17:29 +00:00
|
|
|
logger *zap.Logger
|
2019-07-17 22:25:42 +00:00
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
ownMessages []*v1protocol.Message
|
2019-07-17 22:25:42 +00:00
|
|
|
featureFlags featureFlags
|
|
|
|
messagesPersistenceEnabled bool
|
2019-07-26 07:17:29 +00:00
|
|
|
shutdownTasks []func() error
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type featureFlags struct {
|
|
|
|
genericDiscoveryTopicEnabled bool
|
|
|
|
// sendV1Messages indicates whether we should send
|
|
|
|
// messages compatible only with V1 and later.
|
|
|
|
// V1 messages adds additional wrapping
|
|
|
|
// which contains a signature and payload.
|
|
|
|
sendV1Messages bool
|
2019-07-26 07:17:29 +00:00
|
|
|
|
2019-07-30 18:39:16 +00:00
|
|
|
// datasync indicates whether direct messages should be sent exclusively
|
|
|
|
// using datasync, breaking change for non-v1 clients. Public messages
|
|
|
|
// are not impacted
|
2019-07-26 07:17:29 +00:00
|
|
|
datasync bool
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
type dbConfig struct {
|
|
|
|
dbPath string
|
|
|
|
dbKey string
|
|
|
|
}
|
|
|
|
|
2019-07-17 22:25:42 +00:00
|
|
|
type config struct {
|
|
|
|
onNewInstallationsHandler func([]*multidevice.Installation)
|
2019-08-27 12:04:15 +00:00
|
|
|
// This needs to be exposed until we move here mailserver logic
|
|
|
|
// as otherwise the client is not notified of a new filter and
|
|
|
|
// won't be pulling messages from mailservers until it reloads the chats/filters
|
|
|
|
onNegotiatedFilters func([]*transport.Filter)
|
2019-07-17 22:25:42 +00:00
|
|
|
// DEPRECATED: no need to expose it
|
|
|
|
onSendContactCodeHandler func(*encryption.ProtocolMessageSpec)
|
|
|
|
|
2019-08-09 07:03:10 +00:00
|
|
|
// Config for the envelopes monitor
|
|
|
|
envelopesMonitorConfig *transport.EnvelopesMonitorConfig
|
|
|
|
|
2019-07-17 22:25:42 +00:00
|
|
|
messagesPersistenceEnabled bool
|
|
|
|
featureFlags featureFlags
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
// A path to a database or a database instance is required.
|
|
|
|
// The database instance has a higher priority.
|
|
|
|
dbConfig dbConfig
|
|
|
|
db *sql.DB
|
|
|
|
|
2019-07-17 22:25:42 +00:00
|
|
|
logger *zap.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
type Option func(*config) error
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
func WithOnNewInstallationsHandler(h func([]*multidevice.Installation)) Option {
|
2019-07-17 22:25:42 +00:00
|
|
|
return func(c *config) error {
|
|
|
|
c.onNewInstallationsHandler = h
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-27 12:04:15 +00:00
|
|
|
func WithOnNegotiatedFilters(h func([]*transport.Filter)) Option {
|
2019-07-17 22:25:42 +00:00
|
|
|
return func(c *config) error {
|
2019-08-27 12:04:15 +00:00
|
|
|
c.onNegotiatedFilters = h
|
2019-07-17 22:25:42 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
func WithCustomLogger(logger *zap.Logger) Option {
|
2019-07-17 22:25:42 +00:00
|
|
|
return func(c *config) error {
|
|
|
|
c.logger = logger
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
func WithGenericDiscoveryTopicSupport() Option {
|
2019-07-17 22:25:42 +00:00
|
|
|
return func(c *config) error {
|
|
|
|
c.featureFlags.genericDiscoveryTopicEnabled = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
func WithMessagesPersistenceEnabled() Option {
|
2019-07-17 22:25:42 +00:00
|
|
|
return func(c *config) error {
|
|
|
|
c.messagesPersistenceEnabled = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
func WithDatabaseConfig(dbPath, dbKey string) Option {
|
2019-07-17 22:25:42 +00:00
|
|
|
return func(c *config) error {
|
2019-07-30 06:14:13 +00:00
|
|
|
c.dbConfig = dbConfig{dbPath: dbPath, dbKey: dbKey}
|
2019-07-17 22:25:42 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
func WithDatabase(db *sql.DB) Option {
|
|
|
|
return func(c *config) error {
|
|
|
|
c.db = db
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithSendV1Messages() Option {
|
2019-07-17 22:25:42 +00:00
|
|
|
return func(c *config) error {
|
|
|
|
c.featureFlags.sendV1Messages = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-26 07:17:29 +00:00
|
|
|
func WithDatasync() func(c *config) error {
|
|
|
|
return func(c *config) error {
|
|
|
|
c.featureFlags.datasync = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-09 07:03:10 +00:00
|
|
|
func WithEnvelopesMonitorConfig(emc *transport.EnvelopesMonitorConfig) Option {
|
|
|
|
return func(c *config) error {
|
|
|
|
c.envelopesMonitorConfig = emc
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-17 22:25:42 +00:00
|
|
|
func NewMessenger(
|
|
|
|
identity *ecdsa.PrivateKey,
|
2019-10-09 14:22:53 +00:00
|
|
|
shh whispertypes.Whisper,
|
2019-07-17 22:25:42 +00:00
|
|
|
installationID string,
|
|
|
|
opts ...Option,
|
|
|
|
) (*Messenger, error) {
|
|
|
|
var messenger *Messenger
|
|
|
|
|
|
|
|
c := config{}
|
|
|
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
if err := opt(&c); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
logger := c.logger
|
|
|
|
if c.logger == nil {
|
|
|
|
var err error
|
|
|
|
if logger, err = zap.NewDevelopment(); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to create a logger")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set default config fields.
|
|
|
|
if c.onNewInstallationsHandler == nil {
|
|
|
|
c.onNewInstallationsHandler = func(installations []*multidevice.Installation) {
|
|
|
|
sugar := logger.Sugar().With("site", "onNewInstallationsHandler")
|
|
|
|
for _, installation := range installations {
|
|
|
|
sugar.Infow(
|
|
|
|
"received a new installation",
|
|
|
|
"identity", installation.Identity,
|
|
|
|
"id", installation.ID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-08-27 12:04:15 +00:00
|
|
|
onNewSharedSecretHandler := func(secrets []*sharedsecret.Secret) {
|
|
|
|
filters, err := messenger.handleSharedSecrets(secrets)
|
|
|
|
if err != nil {
|
|
|
|
slogger := logger.With(zap.String("site", "onNewSharedSecretHandler"))
|
|
|
|
slogger.Warn("failed to process secrets", zap.Error(err))
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.onNegotiatedFilters != nil {
|
|
|
|
c.onNegotiatedFilters(filters)
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if c.onSendContactCodeHandler == nil {
|
|
|
|
c.onSendContactCodeHandler = func(messageSpec *encryption.ProtocolMessageSpec) {
|
|
|
|
slogger := logger.With(zap.String("site", "onSendContactCodeHandler"))
|
|
|
|
slogger.Info("received a SendContactCode request")
|
2019-09-02 09:29:06 +00:00
|
|
|
|
|
|
|
newMessage, err := messageSpecToWhisper(messageSpec)
|
|
|
|
if err != nil {
|
|
|
|
slogger.Warn("failed to convert spec to Whisper message", zap.Error(err))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-07-17 22:25:42 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
2019-09-02 09:29:06 +00:00
|
|
|
chatName := transport.ContactCodeTopic(&messenger.identity.PublicKey)
|
2019-10-09 14:22:53 +00:00
|
|
|
_, err = messenger.transport.SendPublic(ctx, newMessage, chatName)
|
2019-07-26 07:17:29 +00:00
|
|
|
if err != nil {
|
|
|
|
slogger.Warn("failed to send a contact code", zap.Error(err))
|
|
|
|
}
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
// Configure the database.
|
|
|
|
database := c.db
|
2019-09-26 09:26:33 +00:00
|
|
|
if c.db == nil && c.dbConfig == (dbConfig{}) {
|
|
|
|
return nil, errors.New("database instance or database path needs to be provided")
|
|
|
|
}
|
|
|
|
if c.db == nil {
|
2019-07-30 06:14:13 +00:00
|
|
|
logger.Info("opening a database", zap.String("dbPath", c.dbConfig.dbPath))
|
2019-09-26 09:26:33 +00:00
|
|
|
var err error
|
2019-07-30 06:14:13 +00:00
|
|
|
database, err = sqlite.Open(c.dbConfig.dbPath, c.dbConfig.dbKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to initialize database from the db config")
|
|
|
|
}
|
|
|
|
}
|
2019-09-26 09:26:33 +00:00
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
// Apply migrations for all components.
|
2019-09-26 09:26:33 +00:00
|
|
|
err := sqlite.Migrate(database)
|
2019-07-30 06:14:13 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to apply migrations")
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
// Initialize transport layer.
|
2019-07-17 22:25:42 +00:00
|
|
|
t, err := transport.NewWhisperServiceTransport(
|
|
|
|
shh,
|
|
|
|
identity,
|
2019-07-30 06:14:13 +00:00
|
|
|
database,
|
2019-07-17 22:25:42 +00:00
|
|
|
nil,
|
2019-08-09 07:03:10 +00:00
|
|
|
c.envelopesMonitorConfig,
|
2019-07-17 22:25:42 +00:00
|
|
|
logger,
|
2019-08-29 06:33:46 +00:00
|
|
|
transport.SetGenericDiscoveryTopicSupport(c.featureFlags.genericDiscoveryTopicEnabled),
|
2019-07-17 22:25:42 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to create a WhisperServiceTransport")
|
|
|
|
}
|
|
|
|
|
2019-07-30 06:14:13 +00:00
|
|
|
// Initialize encryption layer.
|
|
|
|
encryptionProtocol := encryption.New(
|
|
|
|
database,
|
2019-07-17 22:25:42 +00:00
|
|
|
installationID,
|
|
|
|
c.onNewInstallationsHandler,
|
2019-08-27 12:04:15 +00:00
|
|
|
onNewSharedSecretHandler,
|
2019-07-17 22:25:42 +00:00
|
|
|
c.onSendContactCodeHandler,
|
|
|
|
logger,
|
|
|
|
)
|
2019-07-26 07:17:29 +00:00
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
processor, err := newMessageProcessor(
|
|
|
|
identity,
|
2019-08-27 12:04:15 +00:00
|
|
|
database,
|
2019-09-02 09:29:06 +00:00
|
|
|
encryptionProtocol,
|
|
|
|
t,
|
2019-10-14 14:10:48 +00:00
|
|
|
newPersistentMessageHandler(&sqlitePersistence{db: database}),
|
2019-08-29 06:33:46 +00:00
|
|
|
logger,
|
2019-09-02 09:29:06 +00:00
|
|
|
c.featureFlags,
|
2019-07-26 07:17:29 +00:00
|
|
|
)
|
2019-08-27 12:04:15 +00:00
|
|
|
if err != nil {
|
2019-09-02 09:29:06 +00:00
|
|
|
return nil, errors.Wrap(err, "failed to create messageProcessor")
|
2019-08-27 12:04:15 +00:00
|
|
|
}
|
|
|
|
|
2019-07-17 22:25:42 +00:00
|
|
|
messenger = &Messenger{
|
|
|
|
identity: identity,
|
2019-07-30 06:14:13 +00:00
|
|
|
persistence: &sqlitePersistence{db: database},
|
2019-09-02 09:29:06 +00:00
|
|
|
transport: t,
|
2019-07-17 22:25:42 +00:00
|
|
|
encryptor: encryptionProtocol,
|
2019-09-02 09:29:06 +00:00
|
|
|
processor: processor,
|
2019-07-17 22:25:42 +00:00
|
|
|
featureFlags: c.featureFlags,
|
|
|
|
messagesPersistenceEnabled: c.messagesPersistenceEnabled,
|
|
|
|
shutdownTasks: []func() error{
|
2019-07-30 06:14:13 +00:00
|
|
|
database.Close,
|
2019-09-02 09:29:06 +00:00
|
|
|
t.Reset,
|
|
|
|
t.Stop,
|
|
|
|
func() error { processor.Stop(); return nil },
|
2019-07-17 22:25:42 +00:00
|
|
|
// Currently this often fails, seems like it's safe to ignore them
|
|
|
|
// https://github.com/uber-go/zap/issues/328
|
|
|
|
func() error { _ = logger.Sync; return nil },
|
|
|
|
},
|
|
|
|
logger: logger,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start all services immediately.
|
|
|
|
// TODO: consider removing identity as an argument to Start().
|
|
|
|
if err := encryptionProtocol.Start(identity); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Debug("messages persistence", zap.Bool("enabled", c.messagesPersistenceEnabled))
|
|
|
|
|
|
|
|
return messenger, nil
|
|
|
|
}
|
|
|
|
|
2019-08-29 06:33:46 +00:00
|
|
|
// Init analyzes chats and contacts in order to setup filters
|
|
|
|
// which are responsible for retrieving messages.
|
|
|
|
func (m *Messenger) Init() error {
|
|
|
|
logger := m.logger.With(zap.String("site", "Init"))
|
|
|
|
|
|
|
|
var (
|
|
|
|
publicChatIDs []string
|
|
|
|
publicKeys []*ecdsa.PublicKey
|
|
|
|
)
|
|
|
|
|
|
|
|
// Get chat IDs and public keys from the existing chats.
|
|
|
|
// TODO: Get only active chats by the query.
|
|
|
|
chats, err := m.Chats()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, chat := range chats {
|
|
|
|
if !chat.Active {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
switch chat.ChatType {
|
|
|
|
case ChatTypePublic:
|
|
|
|
publicChatIDs = append(publicChatIDs, chat.ID)
|
|
|
|
case ChatTypeOneToOne:
|
|
|
|
publicKeys = append(publicKeys, chat.PublicKey)
|
|
|
|
case ChatTypePrivateGroupChat:
|
|
|
|
for _, member := range chat.Members {
|
|
|
|
publicKey, err := member.PublicKey()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "invalid public key for member %s in chat %s", member.ID, chat.Name)
|
|
|
|
}
|
|
|
|
publicKeys = append(publicKeys, publicKey)
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return errors.New("invalid chat type")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get chat IDs and public keys from the contacts.
|
|
|
|
contacts, err := m.Contacts()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, contact := range contacts {
|
|
|
|
// We only need filters for contacts added by us and not blocked.
|
|
|
|
if !contact.IsAdded() || contact.IsBlocked() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
publicKey, err := contact.PublicKey()
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("failed to get contact's public key", zap.Error(err))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
publicKeys = append(publicKeys, publicKey)
|
|
|
|
}
|
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
_, err = m.transport.InitFilters(publicChatIDs, publicKeys)
|
2019-08-29 06:33:46 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-17 22:25:42 +00:00
|
|
|
// Shutdown takes care of ensuring a clean shutdown of Messenger
|
|
|
|
func (m *Messenger) Shutdown() (err error) {
|
|
|
|
for _, task := range m.shutdownTasks {
|
|
|
|
if tErr := task(); tErr != nil {
|
|
|
|
if err == nil {
|
|
|
|
// First error appeared.
|
|
|
|
err = tErr
|
|
|
|
} else {
|
|
|
|
// We return all errors. They will be concatenated in the order of occurrence,
|
|
|
|
// however, they will also be returned as a single error.
|
|
|
|
err = errors.Wrap(err, tErr.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-08-27 12:04:15 +00:00
|
|
|
func (m *Messenger) handleSharedSecrets(secrets []*sharedsecret.Secret) ([]*transport.Filter, error) {
|
2019-09-02 09:29:06 +00:00
|
|
|
logger := m.logger.With(zap.String("site", "handleSharedSecrets"))
|
|
|
|
var result []*transport.Filter
|
|
|
|
for _, secret := range secrets {
|
|
|
|
logger.Debug("received shared secret", zap.Binary("identity", crypto.FromECDSAPub(secret.Identity)))
|
2019-10-09 14:22:53 +00:00
|
|
|
fSecret := whispertypes.NegotiatedSecret{
|
2019-09-02 09:29:06 +00:00
|
|
|
PublicKey: secret.Identity,
|
|
|
|
Key: secret.Key,
|
|
|
|
}
|
|
|
|
filter, err := m.transport.ProcessNegotiatedSecret(fSecret)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
result = append(result, filter)
|
|
|
|
}
|
|
|
|
return result, nil
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) EnableInstallation(id string) error {
|
|
|
|
return m.encryptor.EnableInstallation(&m.identity.PublicKey, id)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) DisableInstallation(id string) error {
|
|
|
|
return m.encryptor.DisableInstallation(&m.identity.PublicKey, id)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) Installations() ([]*multidevice.Installation, error) {
|
|
|
|
return m.encryptor.GetOurInstallations(&m.identity.PublicKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) SetInstallationMetadata(id string, data *multidevice.InstallationMetadata) error {
|
|
|
|
return m.encryptor.SetInstallationMetadata(&m.identity.PublicKey, id, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NOT IMPLEMENTED
|
|
|
|
func (m *Messenger) SelectMailserver(id string) error {
|
|
|
|
return ErrNotImplemented
|
|
|
|
}
|
|
|
|
|
|
|
|
// NOT IMPLEMENTED
|
|
|
|
func (m *Messenger) AddMailserver(enode string) error {
|
|
|
|
return ErrNotImplemented
|
|
|
|
}
|
|
|
|
|
|
|
|
// NOT IMPLEMENTED
|
|
|
|
func (m *Messenger) RemoveMailserver(id string) error {
|
|
|
|
return ErrNotImplemented
|
|
|
|
}
|
|
|
|
|
|
|
|
// NOT IMPLEMENTED
|
|
|
|
func (m *Messenger) Mailservers() ([]string, error) {
|
|
|
|
return nil, ErrNotImplemented
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) Join(chat Chat) error {
|
2019-10-14 14:10:48 +00:00
|
|
|
switch chat.ChatType {
|
|
|
|
case ChatTypeOneToOne:
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.transport.JoinPrivate(chat.PublicKey)
|
2019-10-14 14:10:48 +00:00
|
|
|
case ChatTypePrivateGroupChat:
|
|
|
|
members, err := chat.MembersAsPublicKeys()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return m.transport.JoinGroup(members)
|
|
|
|
case ChatTypePublic:
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.transport.JoinPublic(chat.Name)
|
2019-10-14 14:10:48 +00:00
|
|
|
default:
|
|
|
|
return errors.New("chat is neither public nor private")
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) Leave(chat Chat) error {
|
2019-07-30 18:39:16 +00:00
|
|
|
if chat.PublicKey != nil {
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.transport.LeavePrivate(chat.PublicKey)
|
2019-07-30 18:39:16 +00:00
|
|
|
} else if chat.Name != "" {
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.transport.LeavePublic(chat.Name)
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
return errors.New("chat is neither public nor private")
|
|
|
|
}
|
|
|
|
|
2019-10-14 14:10:48 +00:00
|
|
|
// TODO: consider moving to a ChatManager ???
|
|
|
|
func (m *Messenger) CreateGroupChat(name string) (*Chat, error) {
|
|
|
|
chat := createGroupChat()
|
2019-11-21 16:19:22 +00:00
|
|
|
group, err := v1protocol.NewGroupWithCreator(name, m.identity)
|
2019-10-14 14:10:48 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
chat.updateChatFromProtocolGroup(group)
|
|
|
|
return &chat, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) AddMembersToChat(ctx context.Context, chat *Chat, members []*ecdsa.PublicKey) error {
|
|
|
|
group, err := newProtocolGroupFromChat(chat)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
encodedMembers := make([]string, len(members))
|
|
|
|
for idx, member := range members {
|
2019-11-21 16:19:22 +00:00
|
|
|
encodedMembers[idx] = protocol.EncodeHex(crypto.FromECDSAPub(member))
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
2019-11-21 16:19:22 +00:00
|
|
|
event := v1protocol.NewMembersAddedEvent(encodedMembers, group.NextClockValue())
|
2019-10-14 14:10:48 +00:00
|
|
|
err = group.ProcessEvent(&m.identity.PublicKey, event)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := m.propagateMembershipUpdates(ctx, group); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
chat.updateChatFromProtocolGroup(group)
|
|
|
|
return m.SaveChat(*chat)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) ConfirmJoiningGroup(ctx context.Context, chat *Chat) error {
|
|
|
|
group, err := newProtocolGroupFromChat(chat)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-11-21 16:19:22 +00:00
|
|
|
event := v1protocol.NewMemberJoinedEvent(
|
|
|
|
protocol.EncodeHex(crypto.FromECDSAPub(&m.identity.PublicKey)),
|
2019-10-14 14:10:48 +00:00
|
|
|
group.NextClockValue(),
|
|
|
|
)
|
|
|
|
err = group.ProcessEvent(&m.identity.PublicKey, event)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := m.propagateMembershipUpdates(ctx, group); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
chat.updateChatFromProtocolGroup(group)
|
|
|
|
return m.SaveChat(*chat)
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (m *Messenger) propagateMembershipUpdates(ctx context.Context, group *v1protocol.Group) error {
|
|
|
|
events := make([]v1protocol.MembershipUpdateEvent, len(group.Updates()))
|
2019-10-14 14:10:48 +00:00
|
|
|
for idx, event := range group.Updates() {
|
|
|
|
events[idx] = event.MembershipUpdateEvent
|
|
|
|
}
|
2019-11-21 16:19:22 +00:00
|
|
|
update := v1protocol.MembershipUpdate{
|
2019-10-14 14:10:48 +00:00
|
|
|
ChatID: group.ChatID(),
|
|
|
|
Events: events,
|
|
|
|
}
|
|
|
|
if err := update.Sign(m.identity); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
recipients, err := stringSliceToPublicKeys(group.Members(), true)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Filter out my key from the recipients
|
|
|
|
n := 0
|
|
|
|
for _, recipient := range recipients {
|
|
|
|
if !isPubKeyEqual(recipient, &m.identity.PublicKey) {
|
|
|
|
recipients[n] = recipient
|
|
|
|
n++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
recipients = recipients[:n]
|
|
|
|
// Finally send membership updates to all recipients.
|
|
|
|
_, err = m.processor.SendMembershipUpdate(
|
|
|
|
ctx,
|
|
|
|
recipients,
|
|
|
|
group.ChatID(),
|
2019-11-21 16:19:22 +00:00
|
|
|
[]v1protocol.MembershipUpdate{update},
|
2019-10-14 14:10:48 +00:00
|
|
|
group.NextClockValue(),
|
|
|
|
)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-30 18:39:16 +00:00
|
|
|
func (m *Messenger) SaveChat(chat Chat) error {
|
|
|
|
return m.persistence.SaveChat(chat)
|
|
|
|
}
|
|
|
|
|
2019-08-29 06:33:46 +00:00
|
|
|
func (m *Messenger) Chats() ([]*Chat, error) {
|
|
|
|
return m.persistence.Chats()
|
2019-07-30 18:39:16 +00:00
|
|
|
}
|
|
|
|
|
2019-08-20 11:20:25 +00:00
|
|
|
func (m *Messenger) DeleteChat(chatID string) error {
|
|
|
|
return m.persistence.DeleteChat(chatID)
|
2019-07-30 18:39:16 +00:00
|
|
|
}
|
|
|
|
|
2019-09-26 07:01:17 +00:00
|
|
|
func (m *Messenger) chatByID(id string) (*Chat, error) {
|
|
|
|
chats, err := m.persistence.Chats()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for _, c := range chats {
|
|
|
|
if c.ID == id {
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, errChatNotFound
|
|
|
|
}
|
|
|
|
|
2019-07-30 18:39:16 +00:00
|
|
|
func (m *Messenger) SaveContact(contact Contact) error {
|
2019-09-26 07:01:17 +00:00
|
|
|
identicon, err := identicon.GenerateBase64(contact.ID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
contact.Identicon = identicon
|
|
|
|
|
|
|
|
name, err := alias.GenerateFromPublicKeyString(contact.ID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
contact.Alias = name
|
|
|
|
|
2019-08-20 11:20:25 +00:00
|
|
|
return m.persistence.SaveContact(contact, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) BlockContact(contact Contact) ([]*Chat, error) {
|
|
|
|
return m.persistence.BlockContact(contact)
|
2019-07-30 18:39:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Messenger) Contacts() ([]*Contact, error) {
|
|
|
|
return m.persistence.Contacts()
|
|
|
|
}
|
|
|
|
|
2019-10-14 14:10:48 +00:00
|
|
|
func (m *Messenger) Send(ctx context.Context, chatID string, data []byte) ([][]byte, error) {
|
2019-09-26 07:01:17 +00:00
|
|
|
logger := m.logger.With(zap.String("site", "Send"), zap.String("chatID", chatID))
|
2019-09-02 09:29:06 +00:00
|
|
|
|
2019-09-26 07:01:17 +00:00
|
|
|
// A valid added chat is required.
|
|
|
|
chat, err := m.chatByID(chatID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
2019-07-30 18:39:16 +00:00
|
|
|
clock, err := m.persistence.LastMessageClock(chat.ID)
|
2019-07-17 22:25:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
logger.Debug("last message clock received", zap.Int64("clock", clock))
|
|
|
|
|
2019-10-14 14:10:48 +00:00
|
|
|
switch chat.ChatType {
|
|
|
|
case ChatTypeOneToOne:
|
2019-09-02 09:29:06 +00:00
|
|
|
logger.Debug("sending private message", zap.Binary("publicKey", crypto.FromECDSAPub(chat.PublicKey)))
|
2019-09-26 07:01:17 +00:00
|
|
|
id, message, err := m.processor.SendPrivate(ctx, chat.PublicKey, chat.ID, data, clock)
|
2019-07-17 22:25:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-10-14 14:10:48 +00:00
|
|
|
if err := m.cacheOwnMessage(chatID, id, message); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return [][]byte{id}, nil
|
|
|
|
case ChatTypePublic:
|
|
|
|
logger.Debug("sending public message", zap.String("chatName", chat.Name))
|
|
|
|
id, err := m.processor.SendPublic(ctx, chat.ID, data, clock)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return [][]byte{id}, nil
|
|
|
|
case ChatTypePrivateGroupChat:
|
|
|
|
logger.Debug("sending group message", zap.String("chatName", chat.Name))
|
|
|
|
recipients, err := chat.MembersAsPublicKeys()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
// Filter me out of recipients.
|
|
|
|
n := 0
|
|
|
|
for _, item := range recipients {
|
|
|
|
if !isPubKeyEqual(item, &m.identity.PublicKey) {
|
|
|
|
recipients[n] = item
|
|
|
|
n++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ids, messages, err := m.processor.SendGroup(ctx, recipients[:n], chat.ID, data, clock)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for idx, message := range messages {
|
|
|
|
if err := m.cacheOwnMessage(chatID, ids[idx], message); err != nil {
|
2019-07-17 22:25:42 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2019-10-14 14:10:48 +00:00
|
|
|
return ids, nil
|
|
|
|
default:
|
|
|
|
return nil, errors.New("chat is neither public nor private")
|
|
|
|
}
|
|
|
|
}
|
2019-07-17 22:25:42 +00:00
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (m *Messenger) cacheOwnMessage(chatID string, id []byte, message *v1protocol.Message) error {
|
2019-10-14 14:10:48 +00:00
|
|
|
// Save our message because it won't be received from the transport layer.
|
|
|
|
message.ID = id // a Message need ID to be properly stored in the db
|
|
|
|
message.SigPubKey = &m.identity.PublicKey
|
|
|
|
message.ChatID = chatID
|
2019-07-17 22:25:42 +00:00
|
|
|
|
2019-10-14 14:10:48 +00:00
|
|
|
if m.messagesPersistenceEnabled {
|
2019-11-21 16:19:22 +00:00
|
|
|
_, err := m.persistence.SaveMessages([]*v1protocol.Message{message})
|
2019-10-14 14:10:48 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
2019-10-14 14:10:48 +00:00
|
|
|
|
|
|
|
// Cache it to be returned in Retrieve().
|
|
|
|
m.ownMessages = append(m.ownMessages, message)
|
|
|
|
|
|
|
|
return nil
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SendRaw takes encoded data, encrypts it and sends through the wire.
|
|
|
|
// DEPRECATED
|
2019-08-09 07:03:10 +00:00
|
|
|
func (m *Messenger) SendRaw(ctx context.Context, chat Chat, data []byte) ([]byte, error) {
|
2019-07-30 18:39:16 +00:00
|
|
|
if chat.PublicKey != nil {
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.processor.SendPrivateRaw(ctx, chat.PublicKey, data)
|
2019-07-30 18:39:16 +00:00
|
|
|
} else if chat.Name != "" {
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.processor.SendPublicRaw(ctx, chat.Name, data)
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
2019-08-09 07:03:10 +00:00
|
|
|
return nil, errors.New("chat is neither public nor private")
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type RetrieveConfig struct {
|
|
|
|
From time.Time
|
|
|
|
To time.Time
|
|
|
|
latest bool
|
|
|
|
last24Hours bool
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
RetrieveLatest = RetrieveConfig{latest: true}
|
|
|
|
RetrieveLastDay = RetrieveConfig{latest: true, last24Hours: true}
|
|
|
|
)
|
|
|
|
|
2019-07-26 07:17:29 +00:00
|
|
|
// RetrieveAll retrieves all previously fetched messages
|
2019-11-21 16:19:22 +00:00
|
|
|
func (m *Messenger) RetrieveAll(ctx context.Context, c RetrieveConfig) ([]*v1protocol.Message, error) {
|
2019-09-26 07:01:17 +00:00
|
|
|
result, err := m.retrieveLatest(ctx)
|
2019-07-26 07:17:29 +00:00
|
|
|
if err != nil {
|
2019-09-26 07:01:17 +00:00
|
|
|
return nil, err
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
2019-09-26 07:01:17 +00:00
|
|
|
postProcess := newPostProcessor(m, postProcessorConfig{
|
|
|
|
MatchChat: true,
|
|
|
|
Persist: true,
|
|
|
|
})
|
|
|
|
result, err = postProcess.Run(result)
|
2019-07-17 22:25:42 +00:00
|
|
|
if err != nil {
|
2019-09-26 07:01:17 +00:00
|
|
|
return nil, errors.Wrap(err, "failed to post process messages")
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
retrievedMessages, err := m.retrieveSaved(ctx, c)
|
2019-07-26 07:17:29 +00:00
|
|
|
if err != nil {
|
2019-09-02 09:29:06 +00:00
|
|
|
return nil, errors.Wrap(err, "failed to get saved messages")
|
2019-07-26 07:17:29 +00:00
|
|
|
}
|
2019-09-02 09:29:06 +00:00
|
|
|
result = append(result, retrievedMessages...)
|
2019-07-26 07:17:29 +00:00
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
// Include own messages.
|
|
|
|
result = append(result, m.ownMessages...)
|
|
|
|
m.ownMessages = nil
|
2019-07-17 22:25:42 +00:00
|
|
|
|
2019-07-26 07:17:29 +00:00
|
|
|
return result, nil
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (m *Messenger) retrieveLatest(ctx context.Context) ([]*v1protocol.Message, error) {
|
2019-09-26 07:01:17 +00:00
|
|
|
latest, err := m.transport.RetrieveAllMessages()
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to retrieve messages")
|
|
|
|
}
|
|
|
|
|
2019-10-09 14:22:53 +00:00
|
|
|
logger := m.logger.With(zap.String("site", "retrieveLatest"))
|
2019-09-26 07:01:17 +00:00
|
|
|
logger.Debug("retrieved messages", zap.Int("count", len(latest)))
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
var result []*v1protocol.Message
|
2019-09-26 07:01:17 +00:00
|
|
|
for _, transpMessage := range latest {
|
|
|
|
protoMessages, err := m.processor.Process(transpMessage.Message)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
result = append(result, protoMessages...)
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (m *Messenger) retrieveSaved(ctx context.Context, c RetrieveConfig) (messages []*v1protocol.Message, err error) {
|
2019-07-17 22:25:42 +00:00
|
|
|
if !m.messagesPersistenceEnabled {
|
2019-09-02 09:29:06 +00:00
|
|
|
return nil, nil
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if !c.latest {
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.persistence.Messages(c.From, c.To)
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if c.last24Hours {
|
|
|
|
to := time.Now()
|
|
|
|
from := to.Add(-time.Hour * 24)
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.persistence.Messages(from, to)
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
return nil, nil
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED
|
2019-11-21 16:19:22 +00:00
|
|
|
func (m *Messenger) RetrieveRawAll() (map[transport.Filter][]*v1protocol.StatusMessage, error) {
|
2019-09-02 09:29:06 +00:00
|
|
|
chatWithMessages, err := m.transport.RetrieveRawAll()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
logger := m.logger.With(zap.String("site", "RetrieveRawAll"))
|
2019-11-21 16:19:22 +00:00
|
|
|
result := make(map[transport.Filter][]*v1protocol.StatusMessage)
|
2019-09-02 09:29:06 +00:00
|
|
|
|
|
|
|
for chat, messages := range chatWithMessages {
|
2019-10-09 14:22:53 +00:00
|
|
|
for _, shhMessage := range messages {
|
2019-09-02 09:29:06 +00:00
|
|
|
// TODO: fix this to use an exported method.
|
2019-11-06 16:23:11 +00:00
|
|
|
statusMessages, err := m.processor.handleMessages(shhMessage, true)
|
2019-09-02 09:29:06 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.Info("failed to decode messages", zap.Error(err))
|
|
|
|
continue
|
|
|
|
}
|
2019-09-26 07:01:17 +00:00
|
|
|
|
2019-11-15 08:52:28 +00:00
|
|
|
for _, msg := range statusMessages {
|
|
|
|
if msg.ParsedMessage != nil {
|
2019-11-21 16:19:22 +00:00
|
|
|
if textMessage, ok := msg.ParsedMessage.(v1protocol.Message); ok {
|
|
|
|
textMessage.Content = v1protocol.PrepareContent(textMessage.Content)
|
2019-11-15 08:52:28 +00:00
|
|
|
msg.ParsedMessage = textMessage
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
result[chat] = append(result[chat], statusMessages...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-06 16:23:11 +00:00
|
|
|
err = m.updateContactsFromMessages(result)
|
2019-09-26 07:01:17 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-09-02 09:29:06 +00:00
|
|
|
return result, nil
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (m *Messenger) updateContactsFromMessages(messages map[transport.Filter][]*v1protocol.StatusMessage) error {
|
2019-09-26 07:01:17 +00:00
|
|
|
allContactsMap := make(map[string]bool)
|
|
|
|
var allContacts []Contact
|
|
|
|
for _, chatMessages := range messages {
|
|
|
|
for _, message := range chatMessages {
|
|
|
|
publicKey := message.SigPubKey()
|
|
|
|
address := strings.ToLower(crypto.PubkeyToAddress(*publicKey).Hex())
|
|
|
|
|
|
|
|
if _, ok := allContactsMap[address]; ok {
|
|
|
|
continue
|
|
|
|
}
|
2019-11-04 10:08:22 +00:00
|
|
|
contact, err := buildContact(publicKey)
|
2019-09-26 07:01:17 +00:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
allContactsMap[address] = true
|
2019-11-04 10:08:22 +00:00
|
|
|
allContacts = append(allContacts, *contact)
|
2019-09-26 07:01:17 +00:00
|
|
|
}
|
|
|
|
}
|
2019-11-04 10:08:22 +00:00
|
|
|
return m.persistence.SetContactsGeneratedData(allContacts, nil)
|
2019-09-26 07:01:17 +00:00
|
|
|
}
|
|
|
|
|
2019-11-06 16:23:11 +00:00
|
|
|
func (m *Messenger) RequestHistoricMessages(
|
|
|
|
ctx context.Context,
|
|
|
|
peer []byte, // should be removed after mailserver logic is ported
|
|
|
|
from, to uint32,
|
|
|
|
cursor []byte,
|
|
|
|
) ([]byte, error) {
|
|
|
|
return m.transport.SendMessagesRequest(ctx, peer, from, to, cursor)
|
|
|
|
}
|
|
|
|
|
2019-07-17 22:25:42 +00:00
|
|
|
// DEPRECATED
|
2019-08-29 06:33:46 +00:00
|
|
|
func (m *Messenger) LoadFilters(filters []*transport.Filter) ([]*transport.Filter, error) {
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.transport.LoadFilters(filters)
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED
|
2019-08-29 06:33:46 +00:00
|
|
|
func (m *Messenger) RemoveFilters(filters []*transport.Filter) error {
|
2019-09-02 09:29:06 +00:00
|
|
|
return m.transport.RemoveFilters(filters)
|
2019-07-17 22:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED
|
|
|
|
func (m *Messenger) ConfirmMessagesProcessed(messageIDs [][]byte) error {
|
|
|
|
for _, id := range messageIDs {
|
|
|
|
if err := m.encryptor.ConfirmMessageProcessed(id); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2019-08-06 21:50:13 +00:00
|
|
|
|
|
|
|
// DEPRECATED: required by status-react.
|
|
|
|
func (m *Messenger) MessageByID(id string) (*Message, error) {
|
|
|
|
return m.persistence.MessageByID(id)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED: required by status-react.
|
2019-08-20 11:20:25 +00:00
|
|
|
func (m *Messenger) MessagesExist(ids []string) (map[string]bool, error) {
|
|
|
|
return m.persistence.MessagesExist(ids)
|
2019-08-06 21:50:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED: required by status-react.
|
|
|
|
func (m *Messenger) MessageByChatID(chatID, cursor string, limit int) ([]*Message, string, error) {
|
|
|
|
return m.persistence.MessageByChatID(chatID, cursor, limit)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED: required by status-react.
|
2019-08-20 11:20:25 +00:00
|
|
|
func (m *Messenger) SaveMessages(messages []*Message) error {
|
|
|
|
return m.persistence.SaveMessagesLegacy(messages)
|
2019-08-06 21:50:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED: required by status-react.
|
2019-08-20 11:20:25 +00:00
|
|
|
func (m *Messenger) DeleteMessage(id string) error {
|
|
|
|
return m.persistence.DeleteMessage(id)
|
2019-08-06 21:50:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED: required by status-react.
|
2019-08-20 11:20:25 +00:00
|
|
|
func (m *Messenger) DeleteMessagesByChatID(id string) error {
|
|
|
|
return m.persistence.DeleteMessagesByChatID(id)
|
2019-08-06 21:50:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED: required by status-react.
|
|
|
|
func (m *Messenger) MarkMessagesSeen(ids ...string) error {
|
|
|
|
return m.persistence.MarkMessagesSeen(ids...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DEPRECATED: required by status-react.
|
|
|
|
func (m *Messenger) UpdateMessageOutgoingStatus(id, newOutgoingStatus string) error {
|
|
|
|
return m.persistence.UpdateMessageOutgoingStatus(id, newOutgoingStatus)
|
|
|
|
}
|
2019-09-26 07:01:17 +00:00
|
|
|
|
|
|
|
// postProcessor performs a set of actions on newly retrieved messages.
|
|
|
|
// If persist is true, it saves the messages into the database.
|
|
|
|
// If matchChat is true, it matches each messages against a Chat instance.
|
|
|
|
type postProcessor struct {
|
|
|
|
myPublicKey *ecdsa.PublicKey
|
|
|
|
persistence *sqlitePersistence
|
|
|
|
logger *zap.Logger
|
|
|
|
|
|
|
|
config postProcessorConfig
|
|
|
|
}
|
|
|
|
|
|
|
|
type postProcessorConfig struct {
|
|
|
|
MatchChat bool // match each messages to a chat; may result in a new chat creation
|
|
|
|
Persist bool // if true, all sent and received user messages will be persisted
|
2019-11-15 08:52:28 +00:00
|
|
|
Parse bool // if true, it will parse the content
|
2019-09-26 07:01:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func newPostProcessor(m *Messenger, config postProcessorConfig) *postProcessor {
|
|
|
|
return &postProcessor{
|
|
|
|
myPublicKey: &m.identity.PublicKey,
|
|
|
|
persistence: m.persistence,
|
|
|
|
logger: m.logger,
|
|
|
|
config: config,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (p *postProcessor) Run(messages []*v1protocol.Message) ([]*v1protocol.Message, error) {
|
2019-09-26 07:01:17 +00:00
|
|
|
var err error
|
|
|
|
|
|
|
|
p.logger.Debug("running post processor", zap.Int("messages", len(messages)))
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
var fns []func([]*v1protocol.Message) ([]*v1protocol.Message, error)
|
2019-09-26 07:01:17 +00:00
|
|
|
|
|
|
|
// Order is important. Persisting messages should be always at the end.
|
|
|
|
if p.config.MatchChat {
|
|
|
|
fns = append(fns, p.matchMessages)
|
|
|
|
}
|
2019-11-15 08:52:28 +00:00
|
|
|
if p.config.Parse {
|
|
|
|
fns = append(fns, p.parseMessages)
|
|
|
|
}
|
2019-09-26 07:01:17 +00:00
|
|
|
if p.config.Persist {
|
|
|
|
fns = append(fns, p.saveMessages)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, fn := range fns {
|
|
|
|
messages, err = fn(messages)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return messages, nil
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (p *postProcessor) saveMessages(messages []*v1protocol.Message) ([]*v1protocol.Message, error) {
|
2019-09-26 07:01:17 +00:00
|
|
|
_, err := p.persistence.SaveMessages(messages)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return messages, nil
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (p *postProcessor) parseMessages(messages []*v1protocol.Message) ([]*v1protocol.Message, error) {
|
2019-11-15 08:52:28 +00:00
|
|
|
for _, m := range messages {
|
2019-11-21 16:19:22 +00:00
|
|
|
m.Content = v1protocol.PrepareContent(m.Content)
|
2019-11-15 08:52:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return messages, nil
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (p *postProcessor) matchMessages(messages []*v1protocol.Message) ([]*v1protocol.Message, error) {
|
2019-09-26 07:01:17 +00:00
|
|
|
chats, err := p.persistence.Chats()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
result := make([]*v1protocol.Message, 0, len(messages))
|
2019-09-26 07:01:17 +00:00
|
|
|
for _, message := range messages {
|
|
|
|
chat, err := p.matchMessage(message, chats)
|
|
|
|
if err != nil {
|
|
|
|
p.logger.Error("failed to match a chat to a message", zap.Error(err))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
message.ChatID = chat.ID
|
|
|
|
result = append(result, message)
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
func (p *postProcessor) matchMessage(message *v1protocol.Message, chats []*Chat) (*Chat, error) {
|
2019-11-04 10:08:22 +00:00
|
|
|
if message.SigPubKey == nil {
|
|
|
|
p.logger.Error("public key can't be empty")
|
|
|
|
return nil, errors.New("received a message with empty public key")
|
|
|
|
}
|
|
|
|
|
2019-09-26 07:01:17 +00:00
|
|
|
switch {
|
2019-11-21 16:19:22 +00:00
|
|
|
case message.MessageT == v1protocol.MessageTypePublicGroup:
|
2019-09-26 07:01:17 +00:00
|
|
|
// For public messages, all outgoing and incoming messages have the same chatID
|
|
|
|
// equal to a public chat name.
|
|
|
|
chatID := message.Content.ChatID
|
|
|
|
chat := findChatByID(chatID, chats)
|
|
|
|
if chat == nil {
|
|
|
|
return nil, errors.New("received a public message from non-existing chat")
|
|
|
|
}
|
|
|
|
return chat, nil
|
2019-11-21 16:19:22 +00:00
|
|
|
case message.MessageT == v1protocol.MessageTypePrivate && isPubKeyEqual(message.SigPubKey, p.myPublicKey):
|
2019-09-26 07:01:17 +00:00
|
|
|
// It's a private message coming from us so we rely on Message.Content.ChatID.
|
|
|
|
// If chat does not exist, it should be created to support multidevice synchronization.
|
|
|
|
chatID := message.Content.ChatID
|
|
|
|
chat := findChatByID(chatID, chats)
|
|
|
|
if chat == nil {
|
|
|
|
// TODO: this should be a three-word name used in the mobile client
|
|
|
|
newChat := CreateOneToOneChat(chatID[:8], message.SigPubKey)
|
|
|
|
if err := p.persistence.SaveChat(newChat); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to save newly created chat")
|
|
|
|
}
|
|
|
|
chat = &newChat
|
|
|
|
}
|
|
|
|
return chat, nil
|
2019-11-21 16:19:22 +00:00
|
|
|
case message.MessageT == v1protocol.MessageTypePrivate:
|
2019-09-26 07:01:17 +00:00
|
|
|
// It's an incoming private message. ChatID is calculated from the signature.
|
|
|
|
// If a chat does not exist, a new one is created and saved.
|
2019-11-21 16:19:22 +00:00
|
|
|
chatID := protocol.EncodeHex(crypto.FromECDSAPub(message.SigPubKey))
|
2019-09-26 07:01:17 +00:00
|
|
|
chat := findChatByID(chatID, chats)
|
|
|
|
if chat == nil {
|
|
|
|
// TODO: this should be a three-word name used in the mobile client
|
|
|
|
newChat := CreateOneToOneChat(chatID[:8], message.SigPubKey)
|
|
|
|
if err := p.persistence.SaveChat(newChat); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to save newly created chat")
|
|
|
|
}
|
|
|
|
chat = &newChat
|
|
|
|
}
|
|
|
|
return chat, nil
|
2019-11-21 16:19:22 +00:00
|
|
|
case message.MessageT == v1protocol.MessageTypePrivateGroup:
|
2019-09-26 07:01:17 +00:00
|
|
|
// In the case of a group message, ChatID is the same for all messages belonging to a group.
|
|
|
|
// It needs to be verified if the signature public key belongs to the chat.
|
|
|
|
chatID := message.Content.ChatID
|
|
|
|
chat := findChatByID(chatID, chats)
|
2019-11-04 10:08:22 +00:00
|
|
|
if chat == nil {
|
|
|
|
return nil, errors.New("received group chat message for non-existing chat")
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:19:22 +00:00
|
|
|
sigPubKeyHex := protocol.EncodeHex(crypto.FromECDSAPub(message.SigPubKey))
|
2019-09-26 07:01:17 +00:00
|
|
|
for _, member := range chat.Members {
|
|
|
|
if member.ID == sigPubKeyHex {
|
|
|
|
return chat, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, errors.New("did not find a matching group chat")
|
|
|
|
default:
|
|
|
|
return nil, errors.New("can not match a chat because there is no valid case")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Identicon returns an identicon based on the input string
|
|
|
|
func Identicon(id string) (string, error) {
|
|
|
|
return identicon.GenerateBase64(id)
|
|
|
|
}
|
|
|
|
|
2019-11-04 10:08:22 +00:00
|
|
|
// VerifyENSName verifies that a registered ENS name matches the expected public key
|
|
|
|
func (m *Messenger) VerifyENSNames(rpcEndpoint, contractAddress string, ensDetails []ens.ENSDetails) (map[string]ens.ENSResponse, error) {
|
|
|
|
verifier := ens.NewVerifier(m.logger)
|
|
|
|
|
|
|
|
ensResponse, err := verifier.CheckBatch(ensDetails, rpcEndpoint, contractAddress)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update contacts
|
|
|
|
var contacts []Contact
|
|
|
|
for _, details := range ensResponse {
|
|
|
|
if details.Error == nil {
|
|
|
|
contact, err := buildContact(details.PublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
contact.ENSVerified = details.Verified
|
|
|
|
contact.ENSVerifiedAt = details.VerifiedAt
|
|
|
|
contact.Name = details.Name
|
|
|
|
|
|
|
|
contacts = append(contacts, *contact)
|
|
|
|
} else {
|
|
|
|
m.logger.Warn("Failed to resolve ens name",
|
|
|
|
zap.String("name", details.Name),
|
|
|
|
zap.String("publicKey", details.PublicKeyString),
|
|
|
|
zap.Error(details.Error),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(contacts) != 0 {
|
|
|
|
err = m.persistence.SetContactsENSData(contacts)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ensResponse, nil
|
|
|
|
}
|
|
|
|
|
2019-09-26 07:01:17 +00:00
|
|
|
// GenerateAlias name returns the generated name given a public key hex encoded prefixed with 0x
|
|
|
|
func GenerateAlias(id string) (string, error) {
|
|
|
|
return alias.GenerateFromPublicKeyString(id)
|
|
|
|
}
|
2019-11-15 08:52:28 +00:00
|
|
|
|
|
|
|
// PrepareContent parses the content of a message and returns the parsed version
|
2019-11-21 16:19:22 +00:00
|
|
|
func (m *Messenger) PrepareContent(content v1protocol.Content) v1protocol.Content {
|
|
|
|
return v1protocol.PrepareContent(content)
|
2019-11-15 08:52:28 +00:00
|
|
|
}
|