/
node.go
225 lines (204 loc) · 5.25 KB
/
node.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package node
import (
"context"
"encoding/json"
"log"
"time"
"github.com/driemworks/mercury-blockchain/core"
"github.com/driemworks/mercury-blockchain/state"
"github.com/ethereum/go-ethereum/common"
"github.com/sirupsen/logrus"
"github.com/libp2p/go-libp2p-core/host"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/raphamorim/go-rainbow"
)
const miningIntervalSeconds = 15
type Node struct {
datadir string
ip string
port uint64
miner common.Address
state *state.State
pendingTXs map[string]state.SignedTx
archivedTXs map[string]state.SignedTx
newSyncedBlocks chan state.Block
newMinedBlocks chan core.MessageTransport
newPendingTXs chan core.MessageTransport
isMining bool
name string
tls bool
host host.Host
pubsub *pubsub.PubSub
}
func NewNode(name string, datadir string, miner string, ip string, port uint64, tls bool) *Node {
minerAddress := state.NewAddress(miner)
return &Node{
name: name,
datadir: datadir,
miner: minerAddress,
ip: ip,
port: port,
pendingTXs: make(map[string]state.SignedTx),
archivedTXs: make(map[string]state.SignedTx),
newSyncedBlocks: make(chan state.Block),
newMinedBlocks: make(chan core.MessageTransport),
newPendingTXs: make(chan core.MessageTransport, 10000),
isMining: false,
tls: tls,
}
}
func (n *Node) Run(ctx context.Context, ip string, port int, rpcHost string, rpcPort uint64, peer string, name string) error {
state, err := state.NewStateFromDisk(n.datadir)
if err != nil {
return err
}
defer state.Close()
n.state = state
go func() {
err := n.runRPCServer("", "", rpcHost, rpcPort)
if err != nil {
log.Fatalln(err)
}
}()
go func() {
err := n.mine(ctx)
if err != nil {
log.Fatalln(err)
}
}()
err = n.runLibp2pNode(ctx, ip, port, peer, name)
if err != nil {
return err
}
return nil
}
func (n *Node) mine(ctx context.Context) error {
var miningCtx context.Context
var stopCurrentMining context.CancelFunc
ticker := time.NewTicker(time.Second * miningIntervalSeconds)
for {
select {
case <-ticker.C:
go func() {
if len(n.pendingTXs) > 0 && !n.isMining {
n.isMining = true
miningCtx, stopCurrentMining = context.WithCancel(ctx)
err := n.minePendingTXs(miningCtx)
if err != nil {
logrus.Errorln(err)
}
n.isMining = false
}
}()
case block, _ := <-n.newSyncedBlocks:
if n.isMining {
blockHash, _ := block.Hash()
logrus.Infoln("Peer mined next Block '%s' faster :(\n", rainbow.Yellow(blockHash.Hex()))
n.removeMinedPendingTXs(block)
stopCurrentMining()
}
case <-ctx.Done():
ticker.Stop()
return nil
}
}
}
func (n *Node) minePendingTXs(ctx context.Context) error {
blockToMine := NewPendingBlock(
n.state.LatestBlockHash(),
n.state.NextBlockNumber(),
n.miner,
n.getPendingTXsAsArray(),
)
minedBlock, err := Mine(ctx, blockToMine)
if err != nil {
return err
}
n.removeMinedPendingTXs(minedBlock)
_, _, err = n.state.AddBlock(minedBlock)
if err != nil {
return err
}
blockBytes, err := json.Marshal(minedBlock)
if err != nil {
return err
}
n.newMinedBlocks <- core.MessageTransport{blockBytes}
return nil
}
func (n *Node) removeMinedPendingTXs(block state.Block) {
if len(block.TXs) > 0 && len(n.pendingTXs) > 0 {
logrus.Infoln("Updating in-memory Pending TXs Pool")
}
for _, tx := range block.TXs {
txHash, _ := tx.Hash()
if _, exists := n.pendingTXs[txHash.Hex()]; exists {
logrus.Infof("Archiving mined TX: %s\n", rainbow.Yellow(txHash.Hex()))
n.archivedTXs[txHash.Hex()] = tx
delete(n.pendingTXs, txHash.Hex())
}
}
}
/**
Add a pending transaction to the node's pending transactions array
*/
func (n *Node) AddPendingTX(tx state.SignedTx) error {
txHash, err := tx.Hash()
if err != nil {
return err
}
_, isAlreadyPending := n.pendingTXs[txHash.Hex()]
_, isArchived := n.archivedTXs[txHash.Hex()]
if !isAlreadyPending && !isArchived {
txJSON, err := json.Marshal(tx)
if err != nil {
return err
}
prettyTxJSON, err := core.PrettyPrintJSON(txJSON)
if err != nil {
return err
}
logrus.Infof("Adding pending transactions: \n%s\n", &prettyTxJSON)
tmpFrom := n.state.Catalog[tx.Author]
// if tmpFrom.Balance <= 0 {
// // for now...
// tmpFrom.Balance = 10
// // return fmt.Errorf("Insufficient balance")
// }
tmpFrom.Balance -= 1
n.pendingTXs[txHash.Hex()] = tx
n.state.Catalog[tx.Author] = tmpFrom
n.state.PendingAccount2Nonce[tx.Author]++
}
return nil
}
func (n *Node) getPendingTXsAsArray() []state.SignedTx {
txs := make([]state.SignedTx, len(n.pendingTXs))
i := 0
for _, tx := range n.pendingTXs {
txs[i] = tx
i++
}
return txs
}
func (n *Node) Join(ctx context.Context, topicName string,
bufSize int, onMessage core.MessageHandler,
msgChan chan core.MessageTransport) error {
topic, err := n.pubsub.Join(topicName)
if err != nil {
return err
}
sub, err := topic.Subscribe()
if err != nil {
return err
}
ch := &core.PubSubWrapper{
Topic: topic,
Sub: sub,
Self: n.host.ID(),
Data: make(chan core.MessageTransport, bufSize),
}
go ch.ReadLoop(ctx, onMessage)
go ch.Publish(ctx, msgChan)
return nil
}