-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminerpool.go
More file actions
95 lines (82 loc) · 2 KB
/
minerpool.go
File metadata and controls
95 lines (82 loc) · 2 KB
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
package minerpool
import (
"math"
)
// MinerPool enables communication between miners
type MinerPool struct {
miners []miner.Miner
broadcastBc chan Blockchain
}
// New creates a MinerPool with the same blockchain
// across miners, and sets up a communication channel for miners
func New(miners []Miner) *MinerPool {
bcbc := make(chan Blockchain)
mp := &MinerPool{miners: miners, broadcastBC: bcbc}
go mp.listen()
return mp
}
// listen broadcasts incoming blockchains to all miners
func (mp *MinerPool) listen() {
for {
bcbc := <-mp.broadcastBc
for _, m := range m.miners {
mp.ReceiveBlockchain(bcbc)
}
}
}
// NewTransaction notifies all miners of an incoming transaction
func (mp *MinerPool) NewTransaction(tx Transaction) {
for _, m := range mp.miners {
go m.NewTransaction(tx, mp.broadcastBc)
}
}
// GetBalance finds the balance for an address that
// the majority of miners agree on
func (mp *MinerPool) GetBalance(address) {
var bals map[int]int
for _, m := range m.miners {
bal := m.GetBalance(address)
bals[bal]++
}
majBal := 0
for _, b := range bals {
majBal = math.Max(majBal, b)
}
return majBal
}
// Blockchains retrieves all of the miners blockchains
func (mp *MinerPool) Blockchains() []Blockchain {
var bcs []Blockchain
for _, m := range mp.miners {
bcs = append(bcs, m.Blockchain())
}
return bcs
}
// Blockchain retrieves the blockchain that the majority
// of miners agree on
func (mp *MinerPool) Blockchain() Blockchain {
bcs := mp.Blockchains()
var bcCount map[string]int
for _, bc := range bcs {
bcCount[bc]++
}
majBC := 0
for _, bc = range bcCount {
majBC = math.Max(majBC, bcCount[bc])
}
return majBC
}
// AddMiner adds a miner to the pool
func (mp *MinerPool) AddMiner(m Miner) {
mp.miners = append(mp.miners, m)
}
// Remove miner removes a miner from the pool
func (mp *MinerPool) RemoveMiner(address string) {
var miners []Miner
for _, m := range mp.miners {
if !m.Address == address {
miners = append(miners, m)
}
}
mp.miners = miners
}