Skip to content
This repository was archived by the owner on Jun 13, 2025. It is now read-only.
1 change: 1 addition & 0 deletions chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ func (chain *Blockchain) AddBlock(block Block) {
if len(chain.Blocks) != 0 {
block.PreviousHash = chain.Blocks[len(chain.Blocks)-1].Hash
}
block.Hash = block.CalculateHash()
chain.Blocks = append(chain.Blocks, block)
}

Expand Down
4 changes: 3 additions & 1 deletion cmd/blockchain/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,10 @@ func main() {
Transactions: nil,
Timestamp: time.Now().Unix(),
Capacity: 5,
PreviousHash: "previousHash",
Nonce: 59349,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем тут хардкод nonce?

PreviousHash: blockchain.Blocks[len(blockchain.Blocks)-1].Hash,
}
block.Hash = block.CalculateHash()
node.BroadcastBlock(block)
default:
fmt.Println("Unknown message type")
Expand Down
41 changes: 41 additions & 0 deletions p2p/cronjob.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package p2p

import (
"blockchain/chain"
"context"
"fmt"
"net"
"time"
)

func task(ctx context.Context, node *Node, conn net.Conn, blockchain *chain.Blockchain) {
for {
select {
// проверяем не завершён ли ещё контекст и выходим, если завершён
case <-ctx.Done():
return

default:
// запросить длину блокчейна
_, err := conn.Write([]byte("Give me length of your blockchain!\n"))
if err != nil {
fmt.Println("Error writing to connection:", err)
node.RemoveConnection(conn.RemoteAddr().String())
return
}
}
// делаем паузу перед следующей итерацией
time.Sleep(time.Minute)
}
}

func cronjob(node *Node, conn net.Conn, blockchain *chain.Blockchain) {
// create a scheduler
// создаём контекст с функцией завершения
ctx, cancel := context.WithCancel(context.Background())
go task(ctx, node, conn, blockchain)
// делаем паузу, чтобы дать горутине поработать
time.Sleep(10 * time.Minute)
// завершаем контекст, чтобы завершить горутину
cancel()
}
58 changes: 49 additions & 9 deletions p2p/p2p.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net"
"os"
"strconv"
"strings"
"sync"
)
Expand Down Expand Up @@ -51,6 +52,7 @@ func (node *Node) StartServer(blockchain *chain.Blockchain) {
continue
}
go node.HandleConnection(conn, blockchain)
go cronjob(node, conn, blockchain)
}
}

Expand Down Expand Up @@ -157,11 +159,14 @@ func (node *Node) HandleConnection(conn net.Conn, blockchain *chain.Blockchain)
return
}
fmt.Println("Received Message:", message)

err = ProcessMessage(message, blockchain)
if err != nil {
fmt.Println("Error processing message:", err)
return
if strings.HasPrefix(message, "Length of Blockchain") {
node.ReadLenBlockchain(peerAddress, message)
} else {
err = ProcessMessage(message, blockchain)
if err != nil {
fmt.Println("Error processing message:", err)
return
}
}
}
}
Expand Down Expand Up @@ -218,6 +223,25 @@ func (node *Node) RemoveConnection(peerAddress string) {
}
}

func (node *Node) SentLenBlockchain(conn net.Conn, blockchain *chain.Blockchain) {
// Отправлять только длину валидного блокчейна
if !blockchain.IsValid() {
fmt.Println("Can't send Length, Blockchain is invalid")
return
}

num := len(blockchain.Blocks)
message := strconv.Itoa(num)
_, err := conn.Write([]byte("Length of Blockchain:" + message + "\n"))

if err != nil {
fmt.Println("Error writing to connection:", err)
node.RemoveConnection(conn.RemoteAddr().String())
return
}
fmt.Println("Sent Length of my Blockchain:", len(blockchain.Blocks))
Comment thread
valerydmitrieva marked this conversation as resolved.
}

func (node *Node) ReadData(conn net.Conn, blockchain *chain.Blockchain) {
reader := bufio.NewReader(conn)
for {
Expand All @@ -228,10 +252,15 @@ func (node *Node) ReadData(conn net.Conn, blockchain *chain.Blockchain) {
return
}
fmt.Println("Received in ReadData:", message)
err = ProcessMessage(message, blockchain)
if err != nil {
fmt.Println("Error processing message:", err)
return

if strings.HasPrefix(message, "Give me length of your blockchain") {
node.SentLenBlockchain(conn, blockchain)
} else {
err = ProcessMessage(message, blockchain)
if err != nil {
fmt.Println("Error processing message:", err)
return
}
}
}
}
Expand Down Expand Up @@ -271,3 +300,14 @@ func (node *Node) BroadcastBlock(block chain.Block) {
}
node.BroadcastMessage(string(blockJson))
}

func (node *Node) ReadLenBlockchain(address string, message string) {
// Get len of blockchain
message = strings.Split(message, ":")[1]
otherLenBlockchain, _ := strconv.Atoi(strings.TrimSpace(message))
fmt.Printf(
"Received len of blockhain: %d, peer address: %s\n",
otherLenBlockchain,
address,
)
}