-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
101 lines (79 loc) · 2.13 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
96
97
98
99
100
101
package main
import (
"fmt"
"log"
"time"
"github.com/MalindaWMD/expt-blockchain-in-golang/internal"
)
type App struct {
bc *internal.Blockchain
pool *internal.Mempool
}
func main() {
bc := internal.NewBlockchain()
defer bc.DB.Close()
mempool := internal.NewMempool()
app := &App{
bc: bc,
pool: mempool,
}
from := "1kyGzAzYRdtfvmzo7xnr7wkjEVfDgEwudmovJ8TUaQpi14saATEfueW3dQUkLyGw8owPfsG6"
to := "121nTVYnA5gaSrTmU1upgkfjEJqYECZYKCfAANgA5U7ZoZGx3F8RhcWAmTjmkfj2CiJMpbbAC"
// // 1st time only
// ctx := bc.NewCoinbaseTransaction(from)
// bc.AddBlock([]*internal.Transaction{ctx})
fmt.Printf("\n%s balance: %d\n", from, app.balance(from))
fmt.Printf("%s balance: %d\n\n", to, app.balance(to))
// FROM 1 to 2
// app.send(from, to, 2)
// // FROM 2 to 1
app.send(to, from, 2)
// Initiate mining
app.MineTransactions()
// Listening for transaction broadcast
go func() {
for data := range bc.Boradcaster.ListenTransaction() {
fmt.Println("Received:", data)
for _, id := range data {
log.Printf("\tRemoving TX: %s from mempool.", id)
app.pool.Remove(id)
}
fmt.Println("Mempool size: ", len(app.pool.Transactions))
}
}()
// Listening for block broadcast
go func() {
// fmt.Println(bc.Boradcaster.ListenBlock())
for data := range bc.Boradcaster.ListenBlock() {
fmt.Println("Received block data:", data)
fmt.Printf("\n%s balance: %d\n", from, app.balance(from))
fmt.Printf("%s balance: %d\n\n", to, app.balance(to))
}
}()
// Keep it running
for {
time.Sleep(time.Second)
}
}
func (app *App) send(from, to string, amount int) *internal.Transaction {
tx, err := app.bc.NewTransaction(from, to, amount)
if err != nil {
log.Println("TX:", err)
}
// Add the mempool
if tx != nil {
app.pool.Add(tx)
fmt.Println("Mempool size: ", len(app.pool.Transactions))
}
return tx
}
func (app *App) balance(address string) int {
return app.bc.GetBalance(address)
}
// TODO: Implement an API to get transactions from mempool and separate mining
func (app *App) MineTransactions() {
// get transactions from mempool
txs := app.pool.Get(3)
// create block and mine
app.bc.AddBlock(txs)
}