-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
116 lines (101 loc) · 2.65 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"bufio"
"fmt"
"net"
"strings"
"sync"
)
type Transaction struct {
transaction string
added_to_block bool
}
type Peer struct {
IP string
Port string
}
var bootstrapNode = Peer{IP: "127.0.0.1", Port: "8000"}
var peers []Peer
var connections = make(map[net.Conn]bool)
var mutex = &sync.Mutex{}
var Ledger = make(map[string][]Transaction)
var transactions = []Transaction{}
// hello
func main() {
var wg sync.WaitGroup
// Start the bootstrap node
wg.Add(1)
go startServer(bootstrapNode, &wg)
wg.Wait()
}
func startServer(peer Peer, wg *sync.WaitGroup) {
defer wg.Done()
ln, _ := net.Listen("tcp", net.JoinHostPort(peer.IP, peer.Port))
defer ln.Close()
for {
conn, _ := ln.Accept()
mutex.Lock()
connections[conn] = true
mutex.Unlock()
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
peerAddress := conn.RemoteAddr().String()
if err != nil {
// If there's an error, it means there's no more data to read from the connection
break
}
var PeerExist = false
for i := range peers {
if peers[i].IP == strings.Split(peerAddress, ":")[0] &&
peers[i].Port == strings.Split(peerAddress, ":")[1] {
PeerExist = true
break
}
}
if PeerExist == false {
// If a new peer is registering, add it to the list of peers
fmt.Println("Registering.......")
mutex.Lock()
peers = append(peers, Peer{IP: strings.Split(peerAddress, ":")[0], Port: strings.Split(peerAddress, ":")[1]})
mutex.Unlock()
fmt.Println("Peer ", peerAddress, " has been registered.")
}
// Only print out the message if it's not empty
if strings.TrimSpace(message) != "" {
var ValidTransaction = true
for i := range transactions {
if transactions[i].transaction == message {
ValidTransaction = false
break
}
}
fmt.Println("Message from", conn.RemoteAddr().String(), ":", message)
{
// Otherwise, broadcast the message to all other clients
mutex.Lock()
for clientConn := range connections {
if ValidTransaction == true {
transactions = append(transactions, Transaction{transaction: message, added_to_block: false})
Ledger[clientConn.LocalAddr().String()] = transactions
//fmt.Println(clientConn.RemoteAddr().String())
}
if clientConn != conn && ValidTransaction == true {
fmt.Fprint(clientConn, message)
} else if clientConn == conn && ValidTransaction == false {
fmt.Fprint(clientConn, "Transaction not valid.")
}
}
mutex.Unlock()
}
}
}
}
//Bootstrap Node added
//Peer2Peer added
//Create P2P network task completed