2019-07-26 07:17:29 +00:00
package datasync
import (
"crypto/ecdsa"
2021-02-23 15:47:45 +00:00
"errors"
2019-09-02 09:29:06 +00:00
2019-07-26 07:17:29 +00:00
"github.com/golang/protobuf/proto"
2023-12-15 16:16:18 +00:00
datasyncnode "github.com/status-im/mvds/node"
"github.com/status-im/mvds/protobuf"
datasyncproto "github.com/status-im/mvds/protobuf"
datasynctransport "github.com/status-im/mvds/transport"
2019-07-26 07:17:29 +00:00
"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
2020-02-10 11:22:37 +00:00
// NodeTransport is the implementation of the datasync transport interface.
* NodeTransport
2019-07-26 07:17:29 +00:00
logger * zap . Logger
sendingEnabled bool
}
2020-02-10 11:22:37 +00:00
func New ( node * datasyncnode . Node , transport * NodeTransport , sendingEnabled bool , logger * zap . Logger ) * DataSync {
return & DataSync { Node : node , NodeTransport : transport , sendingEnabled : sendingEnabled , logger : logger }
2019-07-26 07:17:29 +00:00
}
2023-12-15 11:50:47 +00:00
// Unwrap tries to unwrap datasync message and passes back the message to datasync in order to acknowledge any potential message and mark messages as acknowledged
func ( d * DataSync ) Unwrap ( sender * ecdsa . PublicKey , payload [ ] byte ) ( * protobuf . Payload , error ) {
2019-07-26 07:17:29 +00:00
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
2021-02-23 15:47:45 +00:00
if err != nil {
logger . Debug ( "Unwrapping datasync message failed" , zap . Error ( err ) )
2023-12-15 11:50:47 +00:00
return nil , err
2021-02-23 15:47:45 +00:00
} else if ! datasyncMessage . IsValid ( ) {
2023-12-15 11:50:47 +00:00
return nil , errors . New ( "handling non-datasync message" )
2019-07-26 07:17:29 +00:00
} else {
logger . Debug ( "handling datasync message" )
if d . sendingEnabled {
2023-12-15 16:16:18 +00:00
d . add ( sender , & datasyncMessage )
2019-07-26 07:17:29 +00:00
}
}
2023-12-15 11:50:47 +00:00
return & datasyncMessage , nil
2019-07-26 07:17:29 +00:00
}
2019-11-15 08:52:28 +00:00
func ( d * DataSync ) Stop ( ) {
d . Node . Stop ( )
}
2023-12-15 16:16:18 +00:00
func ( d * DataSync ) add ( publicKey * ecdsa . PublicKey , datasyncMessage * datasyncproto . Payload ) {
2019-11-15 08:52:28 +00:00
packet := datasynctransport . Packet {
Sender : datasyncpeer . PublicKeyToPeerID ( * publicKey ) ,
Payload : datasyncMessage ,
}
2020-02-10 11:22:37 +00:00
d . NodeTransport . AddPacket ( packet )
2019-11-15 08:52:28 +00:00
}
2019-07-26 07:17:29 +00:00
func unwrap ( payload [ ] byte ) ( datasyncPayload datasyncproto . Payload , err error ) {
err = proto . Unmarshal ( payload , & datasyncPayload )
return
}