/
NetworkService.java
330 lines (296 loc) · 12.1 KB
/
NetworkService.java
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.service;
import burstcoin.observer.ObserverProperties;
import burstcoin.observer.event.NetworkUpdateEvent;
import burstcoin.observer.service.model.MiningInfo;
import burstcoin.observer.bean.NetworkBean;
import burstcoin.observer.bean.NetworkState;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Component
public class NetworkService
{
private static Log LOG = LogFactory.getLog(NetworkService.class);
@Autowired
private ObjectMapper objectMapper;
@Autowired
private HttpClient httpClient;
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private JavaMailSender mailSender;
private Timer timer = new Timer();
// blockHeight -> genSig -> domains
private Map<Long, Map<String, Set<String>>> genSigLookup = new HashMap<>();
private Long lastBlockWithSameGenSig;
private boolean forkMailSend = false;
private Long lastBlockWithSameGenSigMailSend = 0L;
private Map<String, NetworkState> previousStateLookup = new HashMap<>();
@PostConstruct
private void postConstruct()
{
LOG.info("Started repeating 'check network' task.");
startCheckNetworkTask();
}
private void startCheckNetworkTask()
{
timer.schedule(new TimerTask()
{
@Override
public void run()
{
try
{
Map<String, MiningInfo> miningInfoLookup = new HashMap<>();
// update compare wallets data
for(String networkServerUrls : ObserverProperties.getNetworkServerUrls())
{
MiningInfo miningInfo = getMiningInfo(networkServerUrls);
if(miningInfo != null)
{
miningInfoLookup.put(networkServerUrls, miningInfo);
}
else
{
miningInfoLookup.put(networkServerUrls, null);
}
}
List<NetworkBean> networkBeans = new ArrayList<>();
for(Map.Entry<String, MiningInfo> entry : miningInfoLookup.entrySet())
{
MiningInfo miningInfo = entry.getValue();
String domain = entry.getKey().replace("http://", "").replace("https://", "");
if(miningInfo != null && miningInfo.getGenerationSignature() != null)
{
networkBeans.add(new NetworkBean(String.valueOf(miningInfo.getHeight()), domain, entry.getKey(), miningInfo.getBaseTarget(),
miningInfo.getGenerationSignature().substring(0, 25) + "...",
String.valueOf(miningInfo.getTargetDeadline())));
}
else
{
networkBeans.add(new NetworkBean(domain));
}
}
Collections.sort(networkBeans, new Comparator<NetworkBean>()
{
@Override
public int compare(NetworkBean o1, NetworkBean o2)
{
return o1.getBaseTarget().compareTo(o2.getBaseTarget());
}
});
Collections.sort(networkBeans, new Comparator<NetworkBean>()
{
@Override
public int compare(NetworkBean o1, NetworkBean o2)
{
return o2.getHeight().compareTo(o1.getHeight());
}
});
// update genSig Lookup
int numberOfNotAvailableDomains = 0;
for(NetworkBean networkBean : networkBeans)
{
if(networkBean.getAvailable())
{
Long height = Long.valueOf(networkBean.getHeight());
if(!genSigLookup.containsKey(height))
{
genSigLookup.put(height, new HashMap<>());
}
Map<String, Set<String>> subMap = genSigLookup.get(height);
if(!subMap.containsKey(networkBean.getGenerationSignature()))
{
subMap.put(networkBean.getGenerationSignature(), new HashSet<>());
}
Set<String> domains = subMap.get(networkBean.getGenerationSignature());
domains.add(networkBean.getDomain());
}
else
{
// N/A
numberOfNotAvailableDomains++;
}
}
List<Long> order = new ArrayList<>(genSigLookup.keySet());
Collections.sort(order);
Collections.reverse(order);
Iterator<Long> iterator = order.iterator();
lastBlockWithSameGenSig = null;
while(iterator.hasNext() && lastBlockWithSameGenSig == null)
{
Long nextHeight = iterator.next();
if(genSigLookup.get(nextHeight).size() == 1) // only one known genSig for height
{
// number of domains with same genSig = all domains without N/A
if(networkBeans.size() - numberOfNotAvailableDomains == genSigLookup.get(nextHeight).values().iterator().next().size())
{
lastBlockWithSameGenSig = nextHeight;
}
}
}
long maxHeight = 0;
for(NetworkBean networkBean : networkBeans)
{
if(networkBean.getAvailable())
{
maxHeight = Math.max(Long.valueOf(networkBean.getHeight()), maxHeight);
}
}
boolean appStartedAfterForkHappened = lastBlockWithSameGenSig == null;
boolean sendMail = false;
for(NetworkBean networkBean : networkBeans)
{
if(networkBean.getAvailable())
{
Long height = Long.valueOf(networkBean.getHeight());
Set<String> domainsWithSameGenSigForBlock = genSigLookup.get(height).get(networkBean.getGenerationSignature());
if(genSigLookup.get(height).size() > 1 && domainsWithSameGenSigForBlock.size() < (networkBeans.size() - numberOfNotAvailableDomains) / 2)
{
networkBean.setState(NetworkState.FORKED);
sendMail = true;
}
if(height + 4 < maxHeight) // when the wallet is 4 blocks behind -> stuck
{
if(!networkBean.getState().equals(NetworkState.FORKED)) // if it's forked, then ignore the stuck-check, because forks may also be behind
{
networkBean.setState(NetworkState.STUCK);
if(ObserverProperties.isEnableStuckNotify()
&& (!previousStateLookup.containsKey(networkBean.getDomain())
|| !previousStateLookup.get(networkBean.getDomain()).equals(NetworkState.STUCK))) //send only once
{
sendMessage("Burstcoin-Observer - Stuck at block: " + networkBean.getHeight(),
networkBean.getDomain() + "\r\n" + "Please check: " + ObserverProperties.getObserverUrl());
}
}
}
}
}
if(sendMail && !forkMailSend)
{
if(ObserverProperties.isEnableForkNotify()
&& (appStartedAfterForkHappened || (lastBlockWithSameGenSigMailSend != null && !lastBlockWithSameGenSig
.equals(lastBlockWithSameGenSigMailSend))))
{
forkMailSend = true;
// ensure only one mail send per lastBlockWithSameGenSig e.g. if forked wallet pops off blocks over and over again
lastBlockWithSameGenSigMailSend = lastBlockWithSameGenSig;
sendMessage("Burstcoin-Observer - Fork after block: " + lastBlockWithSameGenSig, "Please check: " + ObserverProperties.getObserverUrl());
}
}
else if(!sendMail && !appStartedAfterForkHappened)
{
forkMailSend = false;
}
// store the network state for next check-loop
for(NetworkBean networkBean : networkBeans)
{
if(networkBean.getAvailable() && networkBean.getDomain() != null)
{
previousStateLookup.put(networkBean.getDomain(), networkBean.getState());
}
}
publisher.publishEvent(new NetworkUpdateEvent(networkBeans, lastBlockWithSameGenSig));
}
catch(Exception e)
{
LOG.error("Failed receiving Network data.");
}
}
}, 200, ObserverProperties.getNetworkRefreshInterval());
}
private void sendMessage(String subject, String message)
{
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(ObserverProperties.getMailReceiver());
mailMessage.setReplyTo(ObserverProperties.getMailReplyTo());
mailMessage.setFrom(ObserverProperties.getMailSender());
mailMessage.setSubject(subject);
mailMessage.setText(message);
mailSender.send(mailMessage);
}
private MiningInfo getMiningInfo(String server)
{
MiningInfo result = null;
try
{
ContentResponse response;
response = httpClient.newRequest(server + "/burst?requestType=getMiningInfo")
.timeout(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS)
.send();
result = objectMapper.readValue(response.getContentAsString(), MiningInfo.class);
}
catch(TimeoutException timeoutException)
{
LOG.warn("Unable to get mining info caused by connectionTimeout, currently '" + (ObserverProperties.getConnectionTimeout() / 1000)
+ " sec.' try increasing it!");
}
catch(Exception e)
{
LOG.trace("Unable to get mining info from wallet (maybe devV2): " + e.getMessage());
}
if(result == null)
{
try
{
// maybe server is dev v2 pool api
ContentResponse response = httpClient.newRequest(server + "/pool/getMiningInfo")
.timeout(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS)
.send();
result = objectMapper.readValue(response.getContentAsString(), MiningInfo.class);
}
catch(TimeoutException timeoutException)
{
LOG.warn("Unable to get mining info caused by connectionTimeout, currently '" + (ObserverProperties.getConnectionTimeout() / 1000)
+ " sec.' try increasing it!");
}
catch(Exception e)
{
LOG.info("Unable to get mining info from wallet for '" + server + "'");
}
}
return result;
}
}