Skip to content

Commit 24efa36

Browse files
committed
Enhance block handling and validation: add block ID checker, improve block retrieval, and refine validation logic
1 parent 1f61a82 commit 24efa36

7 files changed

Lines changed: 372 additions & 52 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@ go.work.sum
2929
/devkit/blocks
3030
/miner/blocks
3131
/wallet/wallets
32+
/node/blocks

devkit/devkit.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"crypto/sha256"
45
"fmt"
56
"math"
67
"nxtchain/nxtblock"
@@ -11,7 +12,7 @@ import (
1112
func main() {
1213
fmt.Println("NXTChain DevKit v0.1 - 2025\n__________________________")
1314

14-
fmt.Print("OPTIONS:\n0. GEN GENESIS BLOCK\n1. GEN BLOCK\n2. Difficulty Adjustment\n\nEnter option: ")
15+
fmt.Print("OPTIONS:\n0. GEN GENESIS BLOCK\n1. GEN BLOCK\n2. Difficulty Adjustment\n3. Block ID check\n\nEnter option: ")
1516
var option int
1617
fmt.Scanln(&option)
1718

@@ -22,10 +23,21 @@ func main() {
2223
GB()
2324
case 2:
2425
DFBC(10)
26+
case 3:
27+
BIDC()
2528
default:
2629
fmt.Println("Invalid option")
2730
}
2831
}
32+
33+
func BIDC() {
34+
// BLOCK ID CHECKER
35+
fmt.Println("Enter blockid parts:")
36+
var strparts string
37+
fmt.Scanln(&strparts)
38+
blockID := fmt.Sprintf("%x", sha256.Sum256([]byte(strparts)))
39+
fmt.Println("Block ID:", blockID)
40+
}
2941
func GGB() {
3042
fmt.Println("Generating genesis block...")
3143

miner/miner.go

Lines changed: 109 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,8 @@ func start(peer *gonetic.Peer) {
8080
if len(peer.GetConnectedPeers()) > 0 {
8181
nextutils.Debug("%s", "Starting syncronization...")
8282
nextutils.Debug("%s", "Syncing Blockchain...")
83-
syncBlockchain(peer)
8483
syncUTXODB(peer)
84+
syncBlockchain(peer)
8585
nextutils.Debug("%s", "Syncronization complete.")
8686
fmt.Println("+- SYNC COMPLETE -")
8787
break
@@ -126,7 +126,16 @@ func start(peer *gonetic.Peer) {
126126
for _, tx := range transactionMap {
127127
transactions = append(transactions, tx)
128128
}
129-
adjustDifficulty()
129+
allblocks, err := nxtblock.GetAllBlocks(blockdir)
130+
if err != nil {
131+
nextutils.Error("Error getting all blocks: %v", err)
132+
return
133+
}
134+
if len(allblocks)%10 != 0 {
135+
adjustDifficulty()
136+
} else {
137+
nextutils.Debug("%s", "No need to adjust difficulty")
138+
}
130139

131140
// * Create block
132141
newBlock, err := nxtblock.NewBlock(transactions, ruleset, minerWallet, minerCurrency, "I love NXT", latestBlock)
@@ -207,12 +216,27 @@ func start(peer *gonetic.Peer) {
207216
nextutils.NewLine()
208217
nextutils.Debug("%s", "Starting syncronization...")
209218
nextutils.Debug("%s", "Syncing Blockchain...")
210-
syncBlockchain(peer)
211219
syncUTXODB(peer)
220+
syncBlockchain(peer)
212221
nextutils.Debug("%s", "Syncronization complete.")
213222
fmt.Println("+- SYNC COMPLETE -")
214223
} else if strings.HasPrefix(input, "$restart") {
215224
start(peer)
225+
} else if strings.HasPrefix(input, "$validate") {
226+
blocks, err := nxtblock.GetAllBlocks(blockdir)
227+
if err != nil {
228+
nextutils.Error("Error getting all blocks: %v", err)
229+
continue
230+
}
231+
for _, block := range blocks {
232+
nextutils.Debug("Validating block: %s P: %s", block.Hash, block.PreviousHash)
233+
_, err := nxtblock.ValidatorValidateBlock(block, blockdir, ruleset)
234+
if err != nil {
235+
nextutils.Error("Error validating block: %v", err)
236+
continue
237+
}
238+
nextutils.Debug("Block is valid.")
239+
}
216240
}
217241
} else {
218242
peer.Broadcast(input)
@@ -222,7 +246,6 @@ func start(peer *gonetic.Peer) {
222246

223247
// * PEER OUTPUT HANDLER * //
224248
func handleEvents(event string, peer *gonetic.Peer) {
225-
adjustDifficulty()
226249
nextutils.Debug("%s", "[PEER EVENT] "+event)
227250

228251
// ~ PEER EVENTS ~ //
@@ -247,9 +270,9 @@ func handleEvents(event string, peer *gonetic.Peer) {
247270
requester = parts[1]
248271
}
249272
blockHeight := nxtblock.GetLocalBlockHeight(blockdir)
250-
peer.SendToPeer(requester, "RESPONSE_BLOCKHEIGHT_"+strconv.Itoa(blockHeight))
273+
peer.Broadcast("RESPONSE_BLOCKHEIGHT_" + strconv.Itoa(blockHeight))
251274
nextutils.Debug("%s", "[+] Sent block height to: "+requester+" ("+strconv.Itoa(blockHeight)+")")
252-
} else if strings.HasPrefix(event_body, "BLOCK_") {
275+
} else if isBlock := strings.HasPrefix(event_body, "BLOCK_"); isBlock {
253276
parts := strings.Split(event_body, "_")
254277
heightStr := parts[1]
255278
requester := parts[2]
@@ -269,7 +292,7 @@ func handleEvents(event string, peer *gonetic.Peer) {
269292
nextutils.Error("Error: %v", err)
270293
return
271294
}
272-
peer.SendToPeer(requester, "RESPONSE_BLOCK_"+blockStr)
295+
peer.Broadcast("RESPONSE_BLOCK_" + blockStr)
273296
nextutils.Debug("%s", "[+] Sent block to: "+requester)
274297

275298
} else if strings.HasPrefix(event_body, "UTXODB_") {
@@ -285,7 +308,7 @@ func handleEvents(event string, peer *gonetic.Peer) {
285308
nextutils.Error("Error: %v", err)
286309
return
287310
}
288-
peer.SendToPeer(requester, "RESPONSE_UTXODB_"+utxoDBStr)
311+
peer.Broadcast("RESPONSE_UTXODB_" + utxoDBStr)
289312
nextutils.Debug("%s", "[+] Sent UTXO DB to: "+requester+" ("+strconv.Itoa(len(utxoDB))+" entries)")
290313
}
291314

@@ -310,6 +333,18 @@ func handleEvents(event string, peer *gonetic.Peer) {
310333

311334
nextutils.Debug("Block height: %d (%d/%d responses)", blockHeight, totalResponses, remainingBlockHeights)
312335

336+
if totalResponses == 1 {
337+
go func() {
338+
time.Sleep(5 * time.Second)
339+
if totalResponses < remainingBlockHeights {
340+
nextutils.Debug("Timeout reached, proceeding with available responses")
341+
selectedHeight := getMostFrequentBlockHeight()
342+
nextutils.Debug("Selected block height for sync: %d", selectedHeight)
343+
startBlockchainSync(selectedHeight, peer)
344+
}
345+
}()
346+
}
347+
313348
if totalResponses >= remainingBlockHeights { // * ALL RESPONSES FOR A VALID * //
314349
selectedHeight := getMostFrequentBlockHeight()
315350
nextutils.Debug("Selected block height for sync: %d", selectedHeight)
@@ -329,11 +364,63 @@ func handleEvents(event string, peer *gonetic.Peer) {
329364

330365
nextutils.Debug("UTXO DB response from: %s (%d/%d responses)", peer.GetConnString(), totalUDBresponses, remainingDBs)
331366

367+
go func() {
368+
time.Sleep(5 * time.Second)
369+
if totalUDBresponses < remainingDBs {
370+
nextutils.Debug("Timeout reached, proceeding with available UTXO DB responses")
371+
selectedDB := getMostFrequentUTXODB()
372+
nextutils.Debug("Selected UTXO DB for sync: %v", selectedDB)
373+
nxtutxodb.SetUTXODatabase(selectedDB)
374+
}
375+
}()
376+
332377
if totalUDBresponses >= remainingDBs { // * ALL RESPONSES FOR A VALID * //
333378
selectedDB := getMostFrequentUTXODB()
334379
nextutils.Debug("Selected UTXO DB for sync: %v", selectedDB)
335380
nxtutxodb.SetUTXODatabase(selectedDB)
336381
}
382+
} else if strings.HasPrefix(event_body, "BLOCK_") {
383+
parts := strings.SplitN(event_body, "_", 2)
384+
if len(parts) < 2 {
385+
nextutils.Error("%s", "Invalid event body format: "+event_body)
386+
return
387+
}
388+
respObject := parts[1]
389+
newBlock, err := nxtblock.GetBlockSender(respObject)
390+
if err != nil {
391+
nextutils.Error("Error: %v", err)
392+
return
393+
}
394+
395+
nextutils.Debug("%s", "Validating block (ID: "+newBlock.Id+")...")
396+
valid, err := nxtblock.ValidatorValidateBlock(newBlock, blockdir, ruleset)
397+
if err != nil {
398+
nextutils.Error("%s", "Error: Block (ID: "+newBlock.Id+") is not valid")
399+
nextutils.Error("Error: %v", err)
400+
return
401+
}
402+
if !valid {
403+
nextutils.Error("%s", "Error: Block (ID: "+newBlock.Id+") is not valid")
404+
return
405+
}
406+
nextutils.Debug("%s", "Block (ID: "+newBlock.Id+") is valid. Saving block...")
407+
path := nxtblock.SaveBlock(newBlock, blockdir)
408+
nextutils.Debug("%s", "Block saved: "+path)
409+
nextutils.Debug("Updating UTXO database...")
410+
nxtblock.DeleteBlockUTXOs(newBlock.Transactions)
411+
nxtblock.ConvertBlockToUTXO(newBlock)
412+
413+
allblocks, err := nxtblock.GetAllBlocks(blockdir)
414+
if err != nil {
415+
nextutils.Error("Error getting all blocks: %v", err)
416+
return
417+
}
418+
if len(allblocks)%10 != 0 {
419+
adjustDifficulty()
420+
} else {
421+
nextutils.Debug("%s", "No need to adjust difficulty")
422+
}
423+
nextutils.Debug("UTXO database updated.")
337424
}
338425
case "NEW": // * NEW - NEUE OBJEKTE * //
339426
parts := strings.SplitN(event_body, "_", 2)
@@ -425,16 +512,20 @@ func startBlockchainSync(selectedHeight int, peer *gonetic.Peer) {
425512
nextutils.Debug("Starting blockchain sync for block height: %d", selectedHeight)
426513

427514
localHeight := nxtblock.GetLocalBlockHeight(blockdir)
428-
remainingBlockHeights = localHeight - selectedHeight
429-
total := float64(remainingBlockHeights)
430-
431-
for i := selectedHeight; i < localHeight; i++ {
432-
progress := float64(i-selectedHeight) / total * 100
433-
fmt.Printf("\rSynchronizing blocks: %.1f%% (%d/%d)", progress, i-selectedHeight, remainingBlockHeights)
434-
peer.Broadcast("RGET_BLOCK_" + strconv.Itoa(i) + "_" + peer.GetConnString())
515+
if selectedHeight > localHeight {
516+
remainingBlockHeights = selectedHeight - localHeight
517+
total := float64(remainingBlockHeights)
518+
519+
for i := localHeight; i < selectedHeight; i++ {
520+
progress := float64(i-localHeight) / total * 100
521+
nextutils.Info("\rSynchronizing blocks: %.1f%% (%d/%d)", progress, i-localHeight, remainingBlockHeights)
522+
peer.Broadcast("RGET_BLOCK_" + strconv.Itoa(i) + "_" + peer.GetConnString())
523+
}
524+
nextutils.Info("\rSynchronizing blocks: 100.0%% (%d/%d)\n", remainingBlockHeights, remainingBlockHeights)
525+
nextutils.Debug("Block synchronization requests completed")
526+
} else {
527+
nextutils.Debug("Local blockchain is ahead or equal to network height. No sync needed.")
435528
}
436-
fmt.Printf("\rSynchronizing blocks: 100.0%% (%d/%d)\n", remainingBlockHeights, remainingBlockHeights)
437-
nextutils.Debug("Block synchronization requests completed")
438529
}
439530
func getMostFrequentBlockHeight() int {
440531
var maxHeight, maxCount int
@@ -529,6 +620,7 @@ func adjustDifficulty() {
529620
configmanager.SetItem("ruleset", ruleset, &config, true)
530621
}
531622
nextutils.Debug("Difficulty should %s", direction)
623+
nextutils.Debug("New difficulty: %d", ruleset.Difficulty)
532624
time.Sleep(5 * time.Minute)
533625
}
534626

0 commit comments

Comments
 (0)