-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (57 loc) · 2.32 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
package main
import (
"blockchain-learning/internal/blockchain"
"blockchain-learning/internal/transaction"
"fmt"
)
// difficulty for mining (number of leading zeros in the block's hash)
const difficulty = 4
func main() {
// -------------------------
// Setup Network A (2 nodes)
// -------------------------
nodeA1 := blockchain.NewBlockchain()
nodeA2 := blockchain.NewBlockchain()
// Connect them (A1 <-> A2)
nodeA1.AddPeer(&nodeA2, difficulty)
nodeA1.AddTransaction(transaction.NewTransaction("System", "Alice", 100))
nodeA1.AddTransaction(transaction.NewTransaction("Alice", "Bob", 50))
nodeA1.AddTransaction(transaction.NewTransaction("Bob", "Charlie", 20))
nodeA1.MineNewBlock(difficulty)
nodeA2.AddTransaction(transaction.NewTransaction("Charlie", "Dave", 10))
nodeA2.MineNewBlock(difficulty)
// At this point, Network A has a shared ledger with 2 blocks of custom transactions after the genesis.
// -------------------------
// Setup Network B (2 nodes)
// -------------------------
nodeB1 := blockchain.NewBlockchain()
nodeB2 := blockchain.NewBlockchain()
// Connect them (B1 <-> B2)
nodeB1.AddPeer(&nodeB2, difficulty)
// Add some transactions to nodeB1 and mine a block
nodeB1.AddTransaction(transaction.NewTransaction("System", "Eve", 50))
nodeB1.AddTransaction(transaction.NewTransaction("Eve", "Frank", 30))
nodeB1.AddTransaction(transaction.NewTransaction("Frank", "George", 15))
nodeB1.MineNewBlock(difficulty)
// Add a transaction to nodeB2 and mine another block
nodeB2.AddTransaction(transaction.NewTransaction("George", "Helen", 5))
nodeB2.MineNewBlock(difficulty)
// Now, Network B also has a separate ledger with its own transactions.
// -------------------------
// Connect the two networks
// -------------------------
// We link nodeA1 with nodeB1, acting as a bridge between Network A and Network B.
nodeA1.AddPeer(&nodeB1, difficulty)
// -------------------------
// Print Results
// -------------------------
fmt.Println("\n--- Final State After Joining Networks ---")
fmt.Println("\nBalances (from Node A1 perspective):")
nodeA1.PrintBalances()
fmt.Println("\nBalances (from Node A2 perspective):")
nodeA2.PrintBalances()
fmt.Println("\nBalances (from Node B1 perspective):")
nodeB1.PrintBalances()
fmt.Println("\nBalances (from Node B2 perspective):")
nodeB2.PrintBalances()
}