-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
83 lines (67 loc) · 1.89 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
package main
import (
"bytes"
"fmt"
"log"
"strconv"
"time"
"github.com/hitenjain14/go-blockchain/core"
"github.com/hitenjain14/go-blockchain/crypto"
"github.com/hitenjain14/go-blockchain/network"
"github.com/sirupsen/logrus"
)
func main() {
trLocal := network.NewLocalTransport(network.NetAddr("local"))
trRemoteA := network.NewLocalTransport(network.NetAddr("remote_a"))
trRemoteB := network.NewLocalTransport(network.NetAddr("remote_b"))
trRemoteC := network.NewLocalTransport(network.NetAddr("remote_c"))
trLocal.Connect(trRemoteA)
trRemoteA.Connect(trRemoteB)
trRemoteB.Connect(trRemoteC)
trRemoteA.Connect(trLocal)
initRemoteServers([]network.Transport{trRemoteA, trRemoteB, trRemoteC})
go func() {
for {
if err := sendTransaction(trRemoteA, trLocal.Addr()); err != nil {
logrus.Error(err)
}
time.Sleep(2 * time.Second)
}
}()
privKey := crypto.GeneratePrivateKey()
localServer := makeServer("local", trLocal, &privKey)
localServer.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 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 sendTransaction(tr network.Transport, to network.NetAddr) error {
privKey := crypto.GeneratePrivateKey()
data := []byte(strconv.FormatInt(time.Now().UnixNano(), 10))
tx := core.NewTransaction([]byte(data))
if err := tx.Sign(privKey); err != nil {
return err
}
buf := &bytes.Buffer{}
if err := tx.Encode(core.NewGobTxEncoder(buf)); err != nil {
return err
}
msg := network.NewMessage(network.MessageTypeTx, buf.Bytes())
return tr.SendMessage(to, msg.Bytes())
}