-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
95 lines (78 loc) · 2.13 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"bytes"
"fmt"
"log"
"math/rand"
"strconv"
"time"
"github.com/rachit77/Eigen-Chain/core"
"github.com/rachit77/Eigen-Chain/crypto"
"github.com/rachit77/Eigen-Chain/network"
"github.com/sirupsen/logrus"
)
func main() {
trLocal := network.NewLocalTransport("LOCAL")
trRemoteA := network.NewLocalTransport("REMOTE_A")
trRemoteB := network.NewLocalTransport("REMOTE_B")
trRemoteC := network.NewLocalTransport("REMOTE_C")
trLocal.Connect(trRemoteA)
trRemoteA.Connect(trRemoteB)
trRemoteB.Connect(trRemoteC)
trRemoteA.Connect(trLocal)
initRemoteServers([]network.Transport{trRemoteA, trRemoteB, trRemoteC})
go func() {
for {
//trRemote.SendMessage(trLocal.Addr(), []byte("hello world"))
if err := sendTransaction(trRemoteA, trLocal.Addr()); err != nil {
logrus.Error(err)
}
time.Sleep(2 * time.Second)
}
}()
go func() {
time.Sleep(7 * time.Second)
trLate := network.NewLocalTransport("LATE_REMOTE")
trRemoteC.Connect(trLate)
lateServer := makeServer(string(trLate.Addr()), trLate, nil)
go lateServer.Start()
}()
privKey := crypto.GenaratePrivateKey()
localServer := makeServer("LOCAL", trLocal, &privKey)
localServer.Start()
}
func initRemoteServers(trs []network.Transport) {
for i := 0; i < len(trs); i++ {
id := fmt.Sprintf("REMOTE_%d", i)
s := makeServer(id, trs[i], nil)
go s.Start()
}
}
func makeServer(id string, tr network.Transport, pk *crypto.PrivateKey) *network.Server {
opts := network.ServerOpts{
PrivateKey: pk,
ID: id,
Transports: []network.Transport{tr},
}
s, err := network.NewServer(opts)
if err != nil {
log.Fatal(err)
}
return s
}
func sendTransaction(tr network.Transport, to network.NetAddr) error {
privKey := crypto.GenaratePrivateKey()
data := []byte(strconv.Itoa(rand.Intn(10000)))
tx := core.NewTransaction(data)
tx.Sign(privKey)
buf := &bytes.Buffer{}
// if err := tx.Encode(core.NewGobTxDecoder(buf)); err != nil {
// return err
// }
if err := tx.Encode(core.NewGobTxEncoder(buf)); err != nil {
return err
}
msg := network.NewMessage(network.MessageTypeTx, buf.Bytes())
tr.SendMessage(to, msg.Bytes())
return nil
}