Skip to content

Commit

Permalink
example/: fix according to PR feedback.
Browse files Browse the repository at this point in the history
  • Loading branch information
Bun committed Apr 10, 2020
1 parent cb00a66 commit 0329b68
Show file tree
Hide file tree
Showing 14 changed files with 101 additions and 71 deletions.
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ unit-test: coverage.txt
exit -1; \
fi \
done;

PHONY += tss-example
tss-example:
cd example && go build
9 changes: 4 additions & 5 deletions example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ This example demonstrates a simple p2p application using our TSS library. Let's

## Build
```sh
> cd example/
> go build
> make tss-example
```

## Usage
Expand All @@ -15,15 +14,15 @@ First, we run 3 hosts on different terminals. These 3 nodes will try to connect

On node A,
```sh
> ./example -id 1 -config config/id-1.yaml
> ./example -config config/id-1.yaml
```

On node B,
```sh
> ./example -id 2 -config config/id-2.yaml
> ./example -config config/id-2.yaml
```

On node C,
```sh
> ./example -id 3 -config config/id-3.yaml
> ./example -config config/id-3.yaml
```
9 changes: 5 additions & 4 deletions example/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@ type DKGResult struct {
}

type Config struct {
Rank uint32 `yaml:"rank"`
Threshold Threshold `yaml:"threshold"`
Peers map[string]string `yaml:"peers"`
DKGResult DKGResult `yaml:"dkgResult"`
Port int64 `yaml:"port"`
Rank uint32 `yaml:"rank"`
Threshold Threshold `yaml:"threshold"`
Peers []int64 `yaml:"peers"`
DKGResult DKGResult `yaml:"dkgResult"`
}

func readYamlFile(filaPath string) (*Config, error) {
Expand Down
5 changes: 3 additions & 2 deletions example/config/id-1.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
port: 10001
rank: 0
threshold:
dkg: 3
signer: 2
reshare: 3
peers:
id-2: /ip4/127.0.0.1/tcp/10002/p2p/QmaBfzojpsiB8g8Vxq3UyP5hVe62VAasPCZQxWvzWwegTT
id-3: /ip4/127.0.0.1/tcp/10003/p2p/QmRQgen6wGvNBRfmBe7SF39qfGm1Y8Bju3ApXPJAzB23VC
- 10002
- 10003
5 changes: 3 additions & 2 deletions example/config/id-2.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
port: 10002
rank: 0
threshold:
dkg: 3
signer: 2
reshare: 3
peers:
id-1: /ip4/127.0.0.1/tcp/10001/p2p/QmQ61tPtDAaj4DdAYL4P7exDFG2UGQxUR1oq3bQKHHWxBy
id-3: /ip4/127.0.0.1/tcp/10003/p2p/QmRQgen6wGvNBRfmBe7SF39qfGm1Y8Bju3ApXPJAzB23VC
- 10001
- 10003
5 changes: 3 additions & 2 deletions example/config/id-3.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
port: 10003
rank: 0
threshold:
dkg: 3
signer: 2
reshare: 3
peers:
id-1: /ip4/127.0.0.1/tcp/10001/p2p/QmQ61tPtDAaj4DdAYL4P7exDFG2UGQxUR1oq3bQKHHWxBy
id-2: /ip4/127.0.0.1/tcp/10002/p2p/QmaBfzojpsiB8g8Vxq3UyP5hVe62VAasPCZQxWvzWwegTT
- 10001
- 10002
16 changes: 8 additions & 8 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,8 @@ const (
)

func main() {
id := flag.Uint64("id", 0, "id for this node")
configPath := flag.String("config", "", "config path")
flag.Parse()
if *id <= 0 {
log.Crit("Please provide id")
}
if *configPath == "" {
log.Crit("empty config path")
}
Expand All @@ -40,16 +36,20 @@ func main() {
log.Crit("Failed to read config file", "configPath", *configPath, err)
}

// For convenience, set port to id + 10000.
port := *id + 10000
// Make a host that listens on the given multiaddress.
host, err := makeBasicHost(port)
host, err := makeBasicHost(config.Port)
if err != nil {
log.Crit("Failed to create a basic host", "err", err)
}

// Create a new peer manager.
pm := newPeerManager(getID(*id), host, config.Peers)
pm := newPeerManager(getPeerIDFromPort(config.Port), host)
err = pm.addPeers(config.Peers)
if err != nil {
log.Crit("Failed to add peers", "err", err)
}

// Create a new service.
service, err := NewService(config, pm)
if err != nil {
log.Crit("Failed to new service", "err", err)
Expand Down
59 changes: 44 additions & 15 deletions example/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,13 @@ import (
)

// makeBasicHost creates a LibP2P host.
func makeBasicHost(port uint64) (host.Host, error) {
sourceMultiAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", port))

// Use the port number as the randomness source.
r := rand.New(rand.NewSource(int64(port)))
func makeBasicHost(port int64) (host.Host, error) {
sourceMultiAddr, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", port))
if err != nil {
return nil, err
}

// Generate a key pair for this host. We will use it at least
// to obtain a valid host ID.
priv, _, err := crypto.GenerateKeyPairWithReader(crypto.ECDSA, 2048, r)
priv, err := generateIdentity(port)
if err != nil {
return nil, err
}
Expand All @@ -56,8 +54,41 @@ func makeBasicHost(port uint64) (host.Host, error) {
return basicHost, nil
}

// getPeerAddr gets peer full address from port.
func getPeerAddr(port int64) (string, error) {
priv, err := generateIdentity(port)
if err != nil {
return "", err
}

pid, err := peer.IDFromPrivateKey(priv)
if err != nil {
return "", err
}
return fmt.Sprintf("/ip4/127.0.0.1/tcp/%d/p2p/%s", port, pid), nil
}

// getPeerIDFromPort gets peer ID from port.
func getPeerIDFromPort(port int64) string {
// For convenience, we set peer ID as "id-" + port
return fmt.Sprintf("id-%d", port)
}

// generateIdentity generates a fixed key pair by using port as random source.
func generateIdentity(port int64) (crypto.PrivKey, error) {
// Use the port as the randomness source in this example.
r := rand.New(rand.NewSource(port))

// Generate a key pair for this host.
priv, _, err := crypto.GenerateKeyPairWithReader(crypto.ECDSA, 2048, r)
if err != nil {
return nil, err
}
return priv, nil
}

// send sends the proto message to specified peer.
func send(host host.Host, target string, data proto.Message) error {
func send(ctx context.Context, host host.Host, target string, data proto.Message) error {
// Turn the destination into a multiaddr.
maddr, err := multiaddr.NewMultiaddr(target)
if err != nil {
Expand All @@ -68,11 +99,11 @@ func send(host host.Host, target string, data proto.Message) error {
// Extract the peer ID from the multiaddr.
info, err := peer.AddrInfoFromP2pAddr(maddr)
if err != nil {
log.Error("Cannot parse addr", "addr", maddr, "err", err)
log.Warn("Cannot parse addr", "addr", maddr, "err", err)
return err
}

s, err := host.NewStream(context.Background(), info.ID, dkgProtocol)
s, err := host.NewStream(ctx, info.ID, dkgProtocol)
if err != nil {
log.Warn("Cannot create a new stream", "from", host.ID(), "to", target, "err", err)
return err
Expand All @@ -81,13 +112,11 @@ func send(host host.Host, target string, data proto.Message) error {
err = writer.WriteMsg(data)
if err != nil {
log.Warn("Cannot write message to IO", "err", err)
s.Reset()
return err
}
err = helpers.FullClose(s)
if err != nil {
log.Warn("Cannot close the stream", "err", err)
s.Reset()
return err
}

Expand All @@ -96,7 +125,7 @@ func send(host host.Host, target string, data proto.Message) error {
}

// connect connects the host to the specified peer.
func connect(host host.Host, target string) error {
func connect(ctx context.Context, host host.Host, target string) error {
// Turn the destination into a multiaddr.
maddr, err := multiaddr.NewMultiaddr(target)
if err != nil {
Expand All @@ -112,7 +141,7 @@ func connect(host host.Host, target string) error {
}

// Connect the host to the peer.
err = host.Connect(context.Background(), *info)
err = host.Connect(ctx, *info)
if err != nil {
log.Warn("Failed to connect to peer", "err", err)
return err
Expand Down
23 changes: 18 additions & 5 deletions example/pm.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package main

import (
"context"
"sync"
"time"

Expand All @@ -28,11 +29,11 @@ type peerManager struct {
peers map[string]string
}

func newPeerManager(id string, host host.Host, peers map[string]string) *peerManager {
func newPeerManager(id string, host host.Host) *peerManager {
return &peerManager{
id: id,
host: host,
peers: peers,
peers: make(map[string]string),
}
}

Expand All @@ -45,8 +46,7 @@ func (p *peerManager) SelfID() string {
}

func (p *peerManager) MustSend(peerID string, message proto.Message) {
peerAddr := p.peers[peerID]
send(p.host, peerAddr, message)
send(context.Background(), p.host, p.peers[peerID], message)
}

// EnsureAllConnected connects the host to specified peer and sends the message to it.
Expand All @@ -60,13 +60,26 @@ func (p *peerManager) EnsureAllConnected() {
wg.Wait()
}

func (p *peerManager) addPeers(peerPorts []int64) error {
for _, peerPort := range peerPorts {
peerID := getPeerIDFromPort(peerPort)
peerAddr, err := getPeerAddr(peerPort)
if err != nil {
log.Warn("Cannot get peer address", "peerPort", peerPort, "peerID", peerID, "err", err)
return err
}
p.peers[peerID] = peerAddr
}
return nil
}

func connectToPeer(host host.Host, peerAddr string, wg *sync.WaitGroup) {
defer wg.Done()

logger := log.New("to", peerAddr)
for {
// Connect the host to the peer.
err := connect(host, peerAddr)
err := connect(context.Background(), host, peerAddr)
if err != nil {
logger.Warn("Failed to connect to peer", "err", err)
time.Sleep(3 * time.Second)
Expand Down
Empty file removed example/result/dkg/id-1.yaml
Empty file.
Empty file removed example/result/dkg/id-2.yaml
Empty file.
Empty file removed example/result/dkg/id-3.yaml
Empty file.
14 changes: 8 additions & 6 deletions example/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,21 +56,24 @@ func (p *service) Handle(s network.Stream) {
data := &dkg.Message{}
buf, err := ioutil.ReadAll(s)
if err != nil {
s.Reset()
log.Warn("Cannot read data from stream", "err", err)
return
}
s.Close()

// unmarshal it
proto.Unmarshal(buf, data)
err = proto.Unmarshal(buf, data)
if err != nil {
log.Error("Cannot unmarshal data", "err", err)
return
}

log.Info("Received request", "from", s.Conn().RemotePeer())
p.dkg.AddMessage(data)
err = p.dkg.AddMessage(data)
if err != nil {
log.Warn("Cannot add message to DKG", "err", err)
return
}
}

func (p *service) Process() {
Expand All @@ -80,9 +83,8 @@ func (p *service) Process() {

// 2. Connect the host to peers and send the peer message to them.
msg := p.dkg.GetPeerMessage()
peerIDs := getPeerIDs(p.pm.SelfID())
for _, peerID := range peerIDs {
p.pm.MustSend(peerID, msg)
for _, peerPort := range p.config.Peers {
p.pm.MustSend(getPeerIDFromPort(peerPort), msg)
}

// 3. Wait the dkg is done or failed
Expand Down
23 changes: 1 addition & 22 deletions example/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ import (
)

const (
typeDKG int = 0
typeSigner int = 1
typeReshare int = 2
typeDKG int = 0
)

func writeDKGResult(id string, result *dkg.Result) error {
Expand All @@ -50,25 +48,6 @@ func getFilePath(rType int, id string) string {
var resultType string
if rType == typeDKG {
resultType = "dkg"
} else if rType == typeSigner {
resultType = "signer"
} else if rType == typeReshare {
resultType = "reshare"
}
return fmt.Sprintf("result/%s/%s.yaml", resultType, id)
}

func getID(id uint64) string {
return fmt.Sprintf("id-%d", id)
}

func getPeerIDs(selfID string) []string {
var peerIDs []string
for i := uint64(1); i <= uint64(3); i++ {
peerID := getID(i)
if peerID != selfID {
peerIDs = append(peerIDs, peerID)
}
}
return peerIDs
}

0 comments on commit 0329b68

Please sign in to comment.