-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
95 lines (84 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
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"bufio"
"fmt"
"github.com/davecgh/go-spew/spew"
"github.com/joho/godotenv"
"io"
"log"
"net"
"os"
"strconv"
"time"
)
// bcServer handles incoming concurrent blocks.
var bcServer chan []Block
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
bcServer = make(chan []Block)
t := time.Now()
genesisBlock := Block{0, t.String(), 0, "", "",1,""}
spew.Dump(genesisBlock)
Blockchain = append(Blockchain, genesisBlock)
server, err := net.Listen("tcp", ":"+os.Getenv("ADDR"))
if err != nil {
log.Fatal(err)
}
defer server.Close()
for {
conn, err := server.Accept()
fmt.Println("Received new connection")
if err != nil {
log.Fatal(err)
}
go handleConn(conn)
}
}
func handleConn(conn net.Conn) {
defer func() {
fmt.Println("\nClosing connection")
conn.Close()
}()
io.WriteString(conn, "Enter a new BPM:")
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
bpm, err := strconv.Atoi(scanner.Text())
if err != nil {
log.Printf("%v not a number: %v", scanner.Text(), err)
continue
}
newBlock, err := generateBlock(getLastBlock(), bpm)
if err != nil {
log.Printf("Failed generating new block. error:%v", err)
continue
}
if isBlockValid(newBlock, getLastBlock()) {
newBlockchain := append(Blockchain, newBlock) //TODO:danger concurrently modifying a shared variable
replaceChain(newBlockchain)
}
fmt.Printf("\nAdded new blockchain with index:%d and BPM:%d", newBlock.Index, bpm)
//bcServer <- Blockchain
io.WriteString(conn, "\nEnter a new BPM:")
}
/*
go func() {
every30Secs := time.NewTicker(time.Duration(30) * time.Second)
defer every30Secs.Stop()
for {
select {
case <-every30Secs.C:
output, err := json.Marshal(Blockchain)
if err != nil {
log.Fatal(err)
return // end goroutine
}
io.WriteString(conn, string(output))
break
}
}
}()
*/
}