2019-07-26 07:17:29 +00:00
|
|
|
package datasync
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
2019-09-02 09:29:06 +00:00
|
|
|
|
2019-07-26 07:17:29 +00:00
|
|
|
"github.com/golang/protobuf/proto"
|
|
|
|
datasyncnode "github.com/vacp2p/mvds/node"
|
|
|
|
datasyncproto "github.com/vacp2p/mvds/protobuf"
|
|
|
|
datasynctransport "github.com/vacp2p/mvds/transport"
|
|
|
|
"go.uber.org/zap"
|
2020-01-02 09:10:19 +00:00
|
|
|
|
|
|
|
datasyncpeer "github.com/status-im/status-go/protocol/datasync/peer"
|
2019-07-26 07:17:29 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type DataSync struct {
|
|
|
|
*datasyncnode.Node
|
2019-11-15 08:52:28 +00:00
|
|
|
// DataSyncNodeTransport is the implementation of the datasync transport interface.
|
2019-07-26 07:17:29 +00:00
|
|
|
*DataSyncNodeTransport
|
|
|
|
logger *zap.Logger
|
|
|
|
sendingEnabled bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(node *datasyncnode.Node, transport *DataSyncNodeTransport, sendingEnabled bool, logger *zap.Logger) *DataSync {
|
|
|
|
return &DataSync{Node: node, DataSyncNodeTransport: transport, sendingEnabled: sendingEnabled, logger: logger}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *DataSync) Handle(sender *ecdsa.PublicKey, payload []byte) [][]byte {
|
|
|
|
var payloads [][]byte
|
|
|
|
logger := d.logger.With(zap.String("site", "Handle"))
|
|
|
|
|
|
|
|
datasyncMessage, err := unwrap(payload)
|
|
|
|
// If it failed to decode is not a protobuf message, if it successfully decoded but body is empty, is likedly a protobuf wrapped message
|
|
|
|
if err != nil || !datasyncMessage.IsValid() {
|
|
|
|
logger.Debug("handling non-datasync message", zap.Error(err), zap.Bool("datasyncMessage.IsValid()", datasyncMessage.IsValid()))
|
|
|
|
// Not a datasync message, return unchanged
|
|
|
|
payloads = append(payloads, payload)
|
|
|
|
} else {
|
|
|
|
logger.Debug("handling datasync message")
|
|
|
|
// datasync message
|
|
|
|
for _, message := range datasyncMessage.Messages {
|
|
|
|
payloads = append(payloads, message.Body)
|
|
|
|
}
|
|
|
|
if d.sendingEnabled {
|
2019-11-15 08:52:28 +00:00
|
|
|
d.add(sender, datasyncMessage)
|
2019-07-26 07:17:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return payloads
|
|
|
|
}
|
|
|
|
|
2019-11-15 08:52:28 +00:00
|
|
|
func (d *DataSync) Stop() {
|
|
|
|
d.Node.Stop()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *DataSync) add(publicKey *ecdsa.PublicKey, datasyncMessage datasyncproto.Payload) {
|
|
|
|
packet := datasynctransport.Packet{
|
|
|
|
Sender: datasyncpeer.PublicKeyToPeerID(*publicKey),
|
|
|
|
Payload: datasyncMessage,
|
|
|
|
}
|
|
|
|
d.DataSyncNodeTransport.AddPacket(packet)
|
|
|
|
}
|
|
|
|
|
2019-07-26 07:17:29 +00:00
|
|
|
func unwrap(payload []byte) (datasyncPayload datasyncproto.Payload, err error) {
|
|
|
|
err = proto.Unmarshal(payload, &datasyncPayload)
|
|
|
|
return
|
|
|
|
}
|