Paperchain is a blockchain-based distributed application for taking contemporaneous notes that are cryptographically verifiable.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.3 KiB

package server
import (
"bufio"
"fmt"
"io"
"log"
"micah.mp/paperchain/chain"
"net"
)
var bcServer chan []chain.Block
func Serve(addr string, port string) {
server, err := net.Listen("tcp", addr+":"+port)
if server == nil {
panic("couldn't start listening: " + err.Error())
}
defer server.Close()
conns := clientConns(server)
for {
go handleConn(<-conns)
}
}
func clientConns(listener net.Listener) chan net.Conn {
ch := make(chan net.Conn)
i := 0
go func() {
for {
client, err := listener.Accept()
if client == nil {
fmt.Printf("couldn't accept: " + err.Error())
continue
}
i++
fmt.Printf("%d: %v <-> %v\n", i, client.LocalAddr(), client.RemoteAddr())
ch <- client
}
}()
return ch
}
func handleConn(conn net.Conn) {
defer conn.Close()
_, _ = io.WriteString(conn, "Enter a new note:")
scanner := bufio.NewScanner(conn)
go func() {
for scanner.Scan() {
note := scanner.Text()
newBlock, err := chain.GenerateBlock(chain.Blockchain[len(chain.Blockchain)-1], note)
if err != nil {
log.Println(err)
continue
}
if chain.IsBlockValid(newBlock, chain.Blockchain[len(chain.Blockchain)-1]) {
newBlockchain := append(chain.Blockchain, newBlock)
chain.ReplaceChain(newBlockchain)
}
bcServer <- chain.Blockchain
_, _ = io.WriteString(conn, "\nEnter a new note:")
}
}()
}