2019-07-26 07:17:29 +00:00
package datasync
import (
"context"
"crypto/ecdsa"
"errors"
2020-01-02 09:10:19 +00:00
2019-07-26 07:17:29 +00:00
"github.com/golang/protobuf/proto"
"github.com/vacp2p/mvds/protobuf"
"github.com/vacp2p/mvds/state"
"github.com/vacp2p/mvds/transport"
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
)
var errNotInitialized = errors . New ( "Datasync transport not initialized" )
2020-02-10 11:22:37 +00:00
type NodeTransport struct {
2019-07-26 07:17:29 +00:00
packets chan transport . Packet
2019-08-09 07:03:10 +00:00
dispatch func ( context . Context , * ecdsa . PublicKey , [ ] byte , * protobuf . Payload ) error
2019-07-26 07:17:29 +00:00
}
2020-02-10 11:22:37 +00:00
func NewNodeTransport ( ) * NodeTransport {
return & NodeTransport {
2019-07-26 07:17:29 +00:00
packets : make ( chan transport . Packet ) ,
}
}
2020-02-10 11:22:37 +00:00
func ( t * NodeTransport ) Init ( dispatch func ( context . Context , * ecdsa . PublicKey , [ ] byte , * protobuf . Payload ) error ) {
2019-07-26 07:17:29 +00:00
t . dispatch = dispatch
}
2020-02-10 11:22:37 +00:00
func ( t * NodeTransport ) AddPacket ( p transport . Packet ) {
2019-07-26 07:17:29 +00:00
t . packets <- p
}
2020-02-10 11:22:37 +00:00
func ( t * NodeTransport ) Watch ( ) transport . Packet {
2019-07-26 07:17:29 +00:00
return <- t . packets
}
2020-02-10 11:22:37 +00:00
func ( t * NodeTransport ) Send ( _ state . PeerID , peer state . PeerID , payload protobuf . Payload ) error {
2019-07-26 07:17:29 +00:00
if t . dispatch == nil {
return errNotInitialized
}
data , err := proto . Marshal ( & payload )
if err != nil {
return err
}
2020-02-10 11:22:37 +00:00
publicKey , err := datasyncpeer . IDToPublicKey ( peer )
2019-07-26 07:17:29 +00:00
if err != nil {
return err
}
2019-08-09 07:03:10 +00:00
return t . dispatch ( context . TODO ( ) , publicKey , data , & payload )
2019-07-26 07:17:29 +00:00
}
// CalculateSendTime calculates the next epoch
// at which a message should be sent.
func CalculateSendTime ( count uint64 , time int64 ) int64 {
return time + int64 ( count * 2 ) // @todo this should match that time is increased by whisper periods, aka we only retransmit the first time when a message has expired.
}