This repository has been archived by the owner on Sep 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nosoconsensus.pas
438 lines (391 loc) · 11.3 KB
/
nosoconsensus.pas
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
unit nosoconsensus;
{
nosoconsensus 1.0
January 20th, 2023
Noso Unit to get a consensus
Requires: nosodebug, nosotime, nosogeneral
}
{$mode ObjFPC}{$H+}
INTERFACE
uses
Classes, SysUtils, strutils,
nosodebug, nosotime, nosogeneral, nosocrypto;
Type
TThreadNodeStatus = class(TThread)
private
Slot: Integer;
protected
procedure Execute; override;
public
constructor Create(const CreatePaused: Boolean;TSlot:Integer);
end;
TThreadAutoConsensus = class(TThread)
protected
Procedure Execute; override;
public
Constructor Create(CreateSuspended : boolean);
end;
TConsensus = array of string[32];
TNodeConsensus = record
host : string;
port : integer;
Data : string;
ConStr : string[32];
Block : integer;
Peers : integer;
end;
TConsensusData = record
Value : string;
count : integer;
end;
Function OpenThreadsValue():integer;
Function CalculateConsensus(NodesList:string = ''):TConsensus;
Function GetConsensus(LData : integer = 0): string;
Function GetRandonNode():String;
Function GetConHash(ILine:String):String;
Procedure SetNodesArray(NodesList:string);
Function GetNodesArrayIndex(LIndex:integer):TNodeConsensus;
Function GetNodesArrayCount():Integer;
Procedure StartAutoConsensus();
Procedure StopAutoConsensus();
Const
cLastBlock = 2;
cHeaders = 5;
cMNsHash = 8;
cMNsCount = 9;
cLBHash = 10;
cLBTimeEnd = 12;
cSumHash = 17;
cGVTsHash = 18;
cCFGHash = 19;
var
Consensus : TConsensus;
NConsensus : array[0..20] of string = ({0}'Resume','Peers','LBlock','Pending','Delta',
{5}'Headers','Version','UTCTime','MNsHash','MNsCount',
{10}'LBHash','BestDiff','LBTimeEnd','LBMiner','ChecksCount',
{15}'LBPoW','LBDiff','Summary','GVTs','NosoCFG',
{20}'PSOHash');
Css_TotalNodes : integer = 0;
Css_ReachedNodes : integer = 0;
Css_ValidNodes : Integer = 0;
Css_Percentage : Integer = 0;
Css_Completed : boolean = false;
LastConsensusTime : int64 = 0;
IMPLEMENTATION
var
NodesArray : array of TNodeConsensus;
CSNodesArray : TRTLCriticalSection;
OpenThreads : integer;
ReachedNodes : integer;
CSOpenThreads : TRTLCriticalSection;
CSConsensus : TRTLCriticalSection;
KeepAutoCon : Boolean = false;
RunningConsensus : boolean = false;
ActiveRound : int64 = 0;
{$REGION Thread auto update}
Procedure StartAutoConsensus();
var
AutoThread : TThreadAutoConsensus;
Begin
if KeepAutoCon then exit;
Keepautocon := true;
AutoThread := TThreadAutoConsensus.Create(true);
AutoThread.FreeOnTerminate:=true;
AutoThread.Start;
End;
Procedure StopAutoConsensus();
Begin
Keepautocon := false;
End;
Constructor TThreadAutoConsensus.Create(CreateSuspended : boolean);
Begin
inherited Create(CreateSuspended);
End;
Procedure TThreadAutoConsensus.Execute;
Begin
Repeat
if ((BlockAge>=0) and (BlockAge<5)) then LastConsensusTime := 0;
if ( ((BlockAge>=5) and (BlockAge<585)) and (LastConsensusTime+60<UTCTime) )then
begin
LastConsensusTime := UTCTime;
CalculateConsensus();
end;
Sleep(100);
until ((terminated) or (Not KeepAutoCon));
End;
{$ENDREGION}
{$REGION Open threads}
Procedure DecOpenThreads(Reached : boolean);
Begin
EnterCriticalSection(CSOpenThreads);
Dec(OpenThreads);
if reached then Inc(ReachedNodes);
LeaveCriticalSection(CSOpenThreads);
End;
Function OpenThreadsValue():integer;
Begin
EnterCriticalSection(CSOpenThreads);
Result := OpenThreads;
LeaveCriticalSection(CSOpenThreads);
End;
Function GetNodeIndex(index:integer):TNodeConsensus;
Begin
EnterCriticalSection(CSNodesArray);
Result := NodesArray[index];
LeaveCriticalSection(CSNodesArray);
End;
{$ENDREGION}
{$REGION Thread consulting node}
Constructor TThreadNodeStatus.Create(const CreatePaused: Boolean; TSlot:Integer);
Begin
inherited Create(CreatePaused);
Slot := TSlot;
FreeOnTerminate := True;
End;
Procedure TThreadNodeStatus.Execute;
var
ThisNode : TNodeConsensus;
ReadedLine : string;
Reached : boolean = false;
ConHash : string = '';
MyRound : int64;
Begin
MyRound := ActiveRound;
ThisNode := GetNodeIndex(slot);
ReadedLine := RequestLineToPeer(ThisNode.host,ThisNode.port,'NODESTATUS');
if copy(ReadedLine,1,10) = 'NODESTATUS' then
begin
ConHash := GetConHash(ReadedLine);
ReadedLine := StringReplace(ReadedLine,'NODESTATUS',ConHash,[rfReplaceAll, rfIgnoreCase]);
ThisNode.Data:= ReadedLine;
ThisNode.ConStr:=ConHash;
ThisNode.Peers:=StrToIntDef(Parameter(ReadedLine,1),0);
ThisNode.Block:=StrToIntDef(Parameter(ReadedLine,2),0);
reached := true;
end
else
begin
ThisNode.Data:= '';
ThisNode.ConStr:='';
ThisNode.Peers:= 0;
ThisNode.Block:= 0;
end;
if MyRound = ActiveRound then
begin
EnterCriticalSection(CSNodesArray);
NodesArray[slot] := ThisNode;
LeaveCriticalSection(CSNodesArray);
DecOpenThreads(Reached);
end;
End;
{$ENDREGION}
Function GetConHash(ILine:String):String;
Begin
Result := '';
Result := HashMD5String(Parameter(ILine,2)+copy(Parameter(ILine,5),0,5)+copy(Parameter(ILine,8),0,5)+
copy(Parameter(ILine,10),0,5)+copy(Parameter(ILine,17),0,5)+
copy(Parameter(ILine,18),0,5)+copy(Parameter(ILine,19),0,5));
End;
{Gets a random ip and port node}
Function GetRandonNode():String;
var
LNumber : integer;
Begin
result := '';
EnterCriticalSection(CSNodesArray);
LNumber := random(length(NodesArray));
Result := Format('%s %d',[NodesArray[LNumber].host,NodesArray[LNumber].port]);
LeaveCriticalSection(CSNodesArray);
End;
{Set the values for the array of nodes}
Procedure SetNodesArray(NodesList:string);
var
counter : integer;
MyArray : array of string;
Begin
Repeat
sleep(1);
until not RunningConsensus;
setlength(NodesArray,0);
NodesList := Trim(StringReplace(NodesList,':',' ',[rfReplaceAll, rfIgnoreCase]));
MyArray := SplitString(NodesList,' ');
EnterCriticalSection(CSNodesArray);
for counter := 0 to high(MyArray) do
begin
MyArray[counter] := StringReplace(MyArray[counter],';',' ',[rfReplaceAll, rfIgnoreCase]);
Setlength(NodesArray,length(NodesArray)+1);
NodesArray[length(NodesArray)-1].host := Parameter(MyArray[counter],0) ;
NodesArray[length(NodesArray)-1].port := StrToIntDef(Parameter(MyArray[counter],1),8080);
NodesArray[length(NodesArray)-1].data := '';
NodesArray[length(NodesArray)-1].ConStr := '';
NodesArray[length(NodesArray)-1].Block := 0;
NodesArray[length(NodesArray)-1].peers := 0;
end;
LeaveCriticalSection(CSNodesArray);
LastConsensusTime := 0;
End;
Function GetNodesArrayIndex(LIndex:integer):TNodeConsensus;
Begin
result := default(TNodeConsensus);
EnterCriticalSection(CSNodesArray);
if LIndex < length(NodesArray) then
result := NodesArray[LIndex];
LeaveCriticalSection(CSNodesArray);
End;
Function GetNodesArrayCount():Integer;
Begin
EnterCriticalSection(CSNodesArray);
Result := length(NodesArray);
LeaveCriticalSection(CSNodesArray);
End;
Function CalculateConsensus(NodesList:string = ''):TConsensus;
var
counter : integer;
count2 : integer;
ParamNumber : integer = 1;
ThisThread : TThreadNodeStatus;
isFinished : boolean = false;
ArrayCon : array of TConsensusData;
ThisHigh : string;
ConHash : string;
ValidNodes : integer = 0;
EndTime : int64;
Procedure AddValue(Tvalue:String);
var
counter : integer;
ThisItem : TConsensusData;
Begin
for counter := 0 to length(ArrayCon)-1 do
begin
if Tvalue = ArrayCon[counter].Value then
begin
ArrayCon[counter].count+=1;
Exit;
end;
end;
ThisItem.Value:=Tvalue;
ThisItem.count:=1;
Insert(ThisITem,ArrayCon,length(ArrayCon));
End;
Function GetHighest():string;
var
maximum : integer = 0;
counter : integer;
MaxIndex : integer = 0;
Begin
result := '';
if length(ArrayCon) > 0 then
begin
for counter := 0 to high(ArrayCon) do
begin
if ArrayCon[counter].count> maximum then
begin
maximum := ArrayCon[counter].count;
MaxIndex := counter;
end;
end;
result := ArrayCon[MaxIndex].Value;
end;
End;
Begin
BeginPerformance('CalculateConsensus');
RunningConsensus := true;
SetLength(Result,0);
if NodesList <> '' then SetNodesArray(NodesList);
OpenThreads := length(NodesArray);
ReachedNodes := 0;
ActiveRound := UTCTime;
for counter := 0 to high(NodesArray) do
begin
ThisThread := TThreadNodeStatus.Create(True,counter);
ThisThread.FreeOnTerminate:=true;
ThisThread.Start;
Sleep(1);
end;
EndTime := UTCTime+5;
Repeat
sleep(1);
until ( (OpenThreadsValue<= 0) or (UTCTime >= EndTime) );
ActiveRound := 0;
// Get the consensus hash
SetLength(ArrayCon,0);
for counter := 0 to high(NodesArray) do
begin
if Parameter(NodesArray[counter].Data,0) <> '' then
AddValue(Parameter(NodesArray[counter].Data,0));
end;
ConHash := GetHighest;
if conhash = '' then
begin
for count2 := 0 to length(NConsensus)-1 do
begin
insert('',result,0);
end;
Css_TotalNodes := length(NodesArray);
Css_ReachedNodes := Reachednodes;
Css_ValidNodes := ValidNodes;
if ReachedNodes >0 then Css_Percentage := (ValidNodes * 100) div ReachedNodes
else Css_Percentage := 0;
EnterCriticalSection(CSConsensus);
setlength(consensus,0);
Consensus := copy(result,0,length(result));
LeaveCriticalSection(CSConsensus);
Css_Completed := false;
RunningConsensus := false;
Dec(LastConsensusTime,50);
EndPerformance('CalculateConsensus');
exit;
end;
insert(ConHash,result,0);
// Fill the consensus
Repeat
SetLength(ArrayCon,0);
for counter := 0 to high(NodesArray) do
begin
if Parameter(NodesArray[counter].Data,0) = ConHash then
begin
AddValue(Parameter(NodesArray[counter].Data,paramnumber));
if ParamNumber = 1 then Inc(ValidNodes);
end;
end;
ThisHigh := GetHighest;
if thishigh = '' then isFinished := true
else insert(ThisHigh,result,length(Result));
Inc(ParamNumber);
until isFinished;
Css_TotalNodes := length(NodesArray);
Css_ReachedNodes := Reachednodes;
Css_ValidNodes := ValidNodes;
if ReachedNodes >0 then Css_Percentage := (ValidNodes * 100) div ReachedNodes
else Css_Percentage := 0;
EnterCriticalSection(CSConsensus);
setlength(consensus,0);
Consensus := copy(result,0,length(result));
LeaveCriticalSection(CSConsensus);
Css_Completed := true;
RunningConsensus := false;
EndPerformance('CalculateConsensus');
End;
Function GetConsensus(LData : integer = 0): string;
Begin
Result := '';
EnterCriticalSection(CSConsensus);
TRY
Result := Consensus[LData];
EXCEPT on E:Exception do
begin
end;
END;
LeaveCriticalSection(CSConsensus);
End;
INITIALIZATION
Randomize;
setlength(NodesArray,0);
InitCriticalSection(CSNodesArray);
InitCriticalSection(CSOpenThreads);
InitCriticalSection(CSConsensus);
FINALIZATION
DoneCriticalSection(CSNodesArray);
DoneCriticalSection(CSOpenThreads);
DoneCriticalSection(CSConsensus);
END. {END UNIT}