Skip to content

Commit

Permalink
Release v1.2.3
Browse files Browse the repository at this point in the history
  • Loading branch information
oykmnk authored Aug 19, 2019
2 parents 7daa451 + 00f7074 commit 72f9592
Show file tree
Hide file tree
Showing 8 changed files with 278 additions and 24 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ P2Chat - is a core local messenger library, which based on Libp2p stack.

P2Chat basicaly supports discovery through **mDNS** service and support messaging via **PubSub**

It supports next features:
It supports following features:
- devices autodiscovery by `Rendezvous string`
- topic list exchanging between peers
- autoconnect group chats by `PubSub`
Expand All @@ -12,7 +12,8 @@ It supports next features:


## Building
Require go version >=1.12 , so make sure your `go version` is okay
Require go version >=1.12 , so make sure your `go version` is okay.
**WARNING!** Building happen only when this project locates outside of GOPATH environment.

```bash
$ git clone https://github.com/MoonSHRD/p2chat
Expand Down
18 changes: 15 additions & 3 deletions api/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ Flags:
- 0x0: Generic message
- 0x1: Request to get existing PubSub topics at the network
- 0x2: Response to the request for topics (ack)
- 0x3: Request to ask peers for their MatrixID
- 0x4: Response to the request for peers identity
*/
const (
FLAG_GENERIC_MESSAGE int = 0x0
FLAG_TOPICS_REQUEST int = 0x1
FLAG_TOPICS_RESPONSE int = 0x2
FlagGenericMessage int = 0x0
FlagTopicsRequest int = 0x1
FlagTopicsResponse int = 0x2
FlagIdentityRequest int = 0x3
FlagIdentityResponse int = 0x4
)

// BaseMessage is the basic message format of our protocol
Expand All @@ -24,3 +28,11 @@ type GetTopicsRespondMessage struct {
BaseMessage
Topics []string `json:"topics"`
}

// GetIdentityRespondMessage is the format of the message to answer of request for peer identity
// Flag: 0x4
type GetIdentityRespondMessage struct {
BaseMessage
Multiaddress string `json:"multiaddress"`
MatrixID string `json:"matrix_id"`
}
6 changes: 3 additions & 3 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func newTopic(topic string) {
return
case msg := <-incomingMessages:
{
handler.HandleIncomingMessage(msg, func(textMessage pkg.TextMessage) {
handler.HandleIncomingMessage(serviceTopic, msg, func(textMessage pkg.TextMessage) {
fmt.Printf("%s \x1b[32m%s\x1b[0m> ", textMessage.From, textMessage.Body)
})
}
Expand Down Expand Up @@ -135,7 +135,7 @@ func writeTopic(topic string) {
}
message := &api.BaseMessage{
Body: text,
Flag: api.FLAG_GENERIC_MESSAGE,
Flag: api.FlagGenericMessage,
}

sendData, err := json.Marshal(message)
Expand Down Expand Up @@ -204,7 +204,7 @@ func main() {
// Set global PubSub object
pubSub = pb

handler = pkg.NewHandler(pb, serviceTopic, &networkTopics)
handler = pkg.NewHandler(pb, serviceTopic, sourceMultiAddr.String(), &networkTopics)

// Randezvous string = service tag
// Disvover all peers with our service (all ms devices)
Expand Down
162 changes: 162 additions & 0 deletions cmd/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package main

import (
"context"
"crypto/rand"
"encoding/json"
"fmt"
"testing"
"time"

"github.com/MoonSHRD/p2chat/api"
"github.com/MoonSHRD/p2chat/pkg"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/peerstore"
"github.com/libp2p/go-libp2p-core/protocol"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/phayes/freeport"
)

const (
numberOfNodes = 3
serviceTag = "moonshard"
)

var (
testHosts []host.Host
testContexts []context.Context
testHandlers []pkg.Handler
testPubsubs []*pubsub.PubSub
testSubscriptions []*pubsub.Subscription
peerChan chan peer.AddrInfo
)

// Creates mock host object
func createHost() (context.Context, host.Host, error) {
ctx, _ /* cancel */ := context.WithCancel(context.Background())
// defer cancel()

prvKey, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, rand.Reader)
if err != nil {
return nil, nil, err
}

port, err := freeport.GetFreePort()
if err != nil {
return nil, nil, err
}

host, err := libp2p.New(
ctx,
libp2p.Identity(prvKey),
libp2p.ListenAddrStrings(fmt.Sprintf("/ip4/0.0.0.0/tcp/%v", port)),
)
if err != nil {
return nil, nil, err
}

return ctx, host, nil
}

func TestCreateHosts(t *testing.T) {
for i := 0; i < numberOfNodes; i++ {
tempCtx, tempHost, err := createHost()
if err != nil {
t.Fatal(err)
}

testHosts = append(testHosts, tempHost)
testContexts = append(testContexts, tempCtx)
}
}

func TestMDNS(t *testing.T) {
for i := 0; i < numberOfNodes; i++ {
pb, err := pubsub.NewFloodsubWithProtocols(context.Background(), testHosts[i], []protocol.ID{protocol.ID("/moonshard/1.0.0")}, pubsub.WithMessageSigning(true), pubsub.WithStrictSignatureVerification(true))
if err != nil {
t.Fatal(err)
}

testPubsubs = append(testPubsubs, pb)
testHandlers = append(testHandlers, pkg.NewHandler(pb, serviceTag, &networkTopics))

peerChan = pkg.InitMDNS(testContexts[i], testHosts[i], serviceTag)

subscription, err := pb.Subscribe(serviceTag)
if err != nil {
t.Fatal(err)
}
testSubscriptions = append(testSubscriptions, subscription)

fmt.Println("Waiting for correct set up of PubSub...")
time.Sleep(3 * time.Second)

for j := 0; j < i; j++ {
select {
case peer := <-peerChan:
testHosts[i].Peerstore().AddAddr(peer.ID, peer.Addrs[0], peerstore.PermanentAddrTTL)

if err := testHosts[i].Connect(testContexts[i], peer); err != nil {
t.Fatal(err)
}
default:
}
}
}
}

// Checks whether all nodes are connected to each other
func TestGetPeers(t *testing.T) {
for _, handler := range testHandlers {
if len(handler.GetPeers(serviceTag)) != numberOfNodes-1 {
t.Fatal("Not all nodes are connected to each other.")
}
}
}

// Sends message to service topic
func TestSendMessage(t *testing.T) {
message := &api.BaseMessage{
Body: fmt.Sprintf("%s send 'hello test'", testHosts[0].ID()),
Flag: api.FlagGenericMessage,
}

sendData, err := json.Marshal(message)
if err != nil {
t.Fatal("Error occurred when marshalling message object")
}

err = testPubsubs[0].Publish(serviceTag, sendData)
if err != nil {
t.Fatal("Error occurred when publishing")
}
}

// Grabs message from service topic
func TestGetMessage(t *testing.T) {
for _, sub := range testSubscriptions[1:] {
message, err := sub.Next(context.Background())
if err != nil {
t.Fatal(err)
}

decodedMessage := &api.BaseMessage{}
json.Unmarshal(message.Data, decodedMessage)

originalMessage := fmt.Sprintf("%s send 'hello test'", testHosts[0].ID())
if decodedMessage.Body != originalMessage {
t.Fatal("Message not does not match")
}
}
}

func TestCloseHosts(t *testing.T) {
for _, host := range testHosts {
if err := host.Close(); err != nil {
t.Fatal(fmt.Sprintf("Failed when closing host %v", host.ID()))
}
}
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ require (
github.com/libp2p/go-libp2p-core v0.0.6

github.com/libp2p/go-libp2p-pubsub v0.1.0
github.com/libp2p/go-libp2p-swarm v0.1.0
github.com/multiformats/go-multiaddr v0.0.4
github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo=
github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/opentracing/opentracing-go v1.0.2 h1:3jA2P6O1F9UOrWVpwrIo17pu01KWvNWg4X946/Y5Zwg=
github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2 h1:JhzVVoYvbOACxoUmOs6V/G4D5nPVUW73rKvXxP4XUJc=
github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down
Loading

0 comments on commit 72f9592

Please sign in to comment.