-
Notifications
You must be signed in to change notification settings - Fork 13
/
mpblock.pas
799 lines (760 loc) · 27.4 KB
/
mpblock.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
unit mpBlock;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,MasterPaskalForm, fileutil, mpcoin, dialogs, math,
nosotime, nosodebug,nosogeneral,nosocrypto, nosounit, strutils,
nosopsos,nosowallcon,nosoheaders, nosoblock,nosonosocfg,nosonetwork,nosogvts,
nosomasternodes;
Procedure CrearBloqueCero();
Procedure BuildNewBlock(Numero,TimeStamp: Int64; TargetHash, Minero, Solucion:String);
//Function GetDiffHashrate(bestdiff:String):integer;
//Function BestHashReadeable(BestDiff:String):string;
//function GetDiffForNextBlock(UltimoBloque,Last20Average,lastblocktime,previous:integer):integer;
//function GetLast20Time(LastBlTime:integer):integer;
function GetBlockReward(BlNumber:int64):Int64;
Function GuardarBloque(NombreArchivo:string;Cabezera:BlockHeaderData;Ordenes:array of TOrderData;
PosPay:Int64;PoSnumber:integer;PosAddresses:array of TArrayPos;
MNsPay:int64;MNsNumber:Integer;MNsAddresses:array of TArrayPos):boolean;
{function LoadBlockDataHeader(BlockNumber:integer):BlockHeaderData;}
{function GetBlockTrxs(BlockNumber:integer):TBlockOrdersArray;}
Procedure UndoneLastBlock();
Function GetBlockPoSes(BlockNumber:integer): BlockArraysPos;
Function GetBlockMNs(BlockNumber:integer): BlockArraysPos;
Function RemoveBlocks(UpToBlock:int64):integer;
Function GEtNSLBlkOrdInfo(LineText:String):String;
implementation
Uses
mpDisk,mpProtocol, mpGui, mpparser, mpRed;
Function CreateDevPaymentOrder(number:integer;timestamp,amount:int64):TOrderData;
Begin
Result := Default(TOrderData);
Result.Block := number;
//Result.OrderID :='';
Result.OrderLines := 1;
Result.OrderType := 'PROJCT';
Result.TimeStamp := timestamp-1;
Result.Reference := 'null';
Result.TrxLine := 1;
Result.sender := 'COINBASE';
Result.Address := 'COINBASE';
Result.Receiver := 'NpryectdevepmentfundsGE';
Result.AmmountFee := 0;
Result.AmmountTrf := amount;
Result.Signature := 'COINBASE';
Result.TrfrID := GetTransferHash(Result.TimeStamp.ToString+'COINBASE'+'NpryectdevepmentfundsGE'+IntToStr(amount)+IntToStr(MyLastblock));
Result.OrderID := {GetOrderHash(}'1'+Result.TrfrID{)};
End;
Function CreateNosoPayOrder(number:integer;AddSend,AddReceive:string;timestamp,amount:int64):TOrderData;
Begin
Result := Default(TOrderData);
Result.Block := number;
Result.OrderLines := 1;
Result.OrderType := 'TRFR';
Result.TimeStamp := timestamp-1;
Result.Reference := 'null';
Result.TrxLine := 1;
Result.sender := AddSend;
Result.Address := AddSend;
Result.Receiver := AddReceive;
Result.AmmountFee := 0;
Result.AmmountTrf := amount;
Result.Signature := 'Directive';
Result.TrfrID := GetTransferHash(Result.TimeStamp.ToString+'TRFR'+AddSend+IntToStr(amount)+IntToStr(MyLastblock));
Result.OrderID := GetOrderHash('1'+Result.TrfrID);
End;
// Build the default block 0
Procedure CrearBloqueCero();
Begin
BuildNewBlock(0,GenesysTimeStamp,'',adminhash,'');
if G_Launching then ToLog('console','Block GENESYS (0) created.'); //'Block 0 created.'
if G_Launching then OutText('✓ Block 0 created',false,1);
End;
// Crea un bloque nuevo con la informacion suministrada
Procedure BuildNewBlock(Numero,TimeStamp: int64; TargetHash, Minero, Solucion:String);
var
BlockHeader : BlockHeaderData;
StartBlockTime : int64 = 0;
MinerFee : int64 = 0;
ListaOrdenes : Array of TOrderData;
IgnoredTrxs : Array of TOrderData;
Filename : String;
Contador : integer = 0;
OperationAddress : string = '';
errored : boolean = false;
PoWTotalReward : int64;
ArrayLastBlockTrxs : TBlockOrdersArray;
ExistsInLastBlock : boolean;
Count2 : integer;
NewMNs, ExpiredMNs : integer;
DevsTotalReward : int64 = 0;
DevOrder : TOrderData;
PoScount : integer = 0;
PosRequired, PosReward: int64;
PoSTotalReward : int64 = 0;
PoSAddressess : array of TArrayPos;
MNsCount : integer;
MNsReward : int64;
MNsTotalReward : int64 =0;
MNsAddressess : array of TArrayPos;
ThisParam : String;
MNsFileText : String = '';
GVTsTransfered : integer = 0;
NosoPayData : string = '';
NPDOrder : TOrderData;
NPDBlock : integer;
NPDSource : string;
NPDTarget : string;
NPDAmount : int64;
BlockTrfrs : integer = 0;
Begin
if WO_skipBlocks then exit;
if GetCFGDataStr(0) = 'STOP' then
begin
ClearAllPending;
exit;
end;
if AnsiContainsStr(GetCFGDataStr(0),'EMPTY') then ClearAllPending;
BuildingBlock := Numero;
BeginPerformance('BuildNewBlock');
if ((numero>0) and (Timestamp < lastblockdata.TimeEnd)) then
begin
ToLog('console','New block '+IntToStr(numero)+' : Invalid timestamp');
ToLog('console','Blocks can not be added until '+TimestampToDate(GenesysTimeStamp));
errored := true;
end;
if TimeStamp > UTCTime+5 then
begin
ToLog('console','New block '+IntToStr(numero)+' : Invalid timestamp');
ToLog('console','Timestamp '+IntToStr(TimeStamp)+' is '+IntToStr(TimeStamp-UTCTime)+' seconds in the future');
errored := true;
end;
if not errored then
begin
if Numero = 0 then StartBlockTime := 1531896783
else StartBlockTime := LastBlockData.TimeEnd+1;
FileName := BlockDirectory + IntToStr(Numero)+'.blk';
SetLength(ListaOrdenes,0);
SetLength(IgnoredTrxs,0);
// Generate summary copy
CreateSumaryBackup();
// Generate GVT copy
EnterCriticalSection(CSGVTsArray);
trydeletefile(GVTsFilename+'.bak');
copyfile(GVTsFilename,GVTsFilename+'.bak');
LeaveCriticalSection(CSGVTsArray);
// Processs pending orders
EnterCriticalSection(CSPending);
BeginPerformance('NewBLOCK_PENDING');
ArrayLastBlockTrxs := Default(TBlockOrdersArray);
ArrayLastBlockTrxs := GetBlockTrxs(MyLastBlock);
ResetBlockRecords;
for contador := 0 to length(ArrayPoolTXs)-1 do
begin
// Version 0.2.1Ga1 reverification starts
if ArrayPoolTXs[contador].TimeStamp < LastBlockData.TimeStart then
continue;
//{
ExistsInLastBlock := false;
for count2 := 0 to length(ArrayLastBlockTrxs)-1 do
begin
if ArrayLastBlockTrxs[count2].TrfrID = ArrayPoolTXs[contador].TrfrID then
begin
ExistsInLastBlock := true ;
break;
end;
end;
if ExistsInLastBlock then continue;
if ( (ArrayPoolTXs[contador].TimeStamp+60 > TimeStamp) or (BlockTrfrs>=2000) ) then
begin
if ArrayPoolTXs[contador].TimeStamp < TimeStamp+600 then
insert(ArrayPoolTXs[contador],IgnoredTrxs,length(IgnoredTrxs));
continue;
end;
if ArrayPoolTXs[contador].OrderType='CUSTOM' then
begin
OperationAddress := GetAddressFromPublicKey(ArrayPoolTXs[contador].sender);
if IsCustomizacionValid(OperationAddress,ArrayPoolTXs[contador].Receiver,numero) then
begin
minerfee := minerfee+ArrayPoolTXs[contador].AmmountFee;
ArrayPoolTXs[contador].Block:=numero;
ArrayPoolTXs[contador].sender:=OperationAddress;
insert(ArrayPoolTXs[contador],ListaOrdenes,length(listaordenes));
Inc(BlockTrfrs);
end;
end;
if ArrayPoolTXs[contador].OrderType='TRFR' then
begin
OperationAddress := ArrayPoolTXs[contador].Address;
if SummaryValidPay(OperationAddress,ArrayPoolTXs[contador].AmmountFee+ArrayPoolTXs[contador].AmmountTrf,numero) then
begin
minerfee := minerfee+ArrayPoolTXs[contador].AmmountFee;
CreditTo(ArrayPoolTXs[contador].Receiver,ArrayPoolTXs[contador].AmmountTrf,numero);
ArrayPoolTXs[contador].Block:=numero;
ArrayPoolTXs[contador].sender:=OperationAddress;
insert(ArrayPoolTXs[contador],ListaOrdenes,length(listaordenes));
Inc(BlockTrfrs);
end;
end;
if ( (ArrayPoolTXs[contador].OrderType='SNDGVT') and ( ArrayPoolTXs[contador].sender = AdminPubKey) ) then
begin
OperationAddress := GetAddressFromPublicKey(ArrayPoolTXs[contador].sender);
if GetAddressBalanceIndexed(OperationAddress)< ArrayPoolTXs[contador].AmmountFee then continue;
if ChangeGVTOwner(StrToIntDef(ArrayPoolTXs[contador].Reference,100),OperationAddress,ArrayPoolTXs[contador].Receiver)=0 then
begin
minerfee := minerfee+ArrayPoolTXs[contador].AmmountFee;
Inc(GVTsTransfered);
SummaryValidPay(OperationAddress,ArrayPoolTXs[contador].AmmountFee,numero);
ArrayPoolTXs[contador].Block:=numero;
ArrayPoolTXs[contador].sender:=OperationAddress;
insert(ArrayPoolTXs[contador],ListaOrdenes,length(listaordenes));
end;
end;
end;
// Proyect payments
if GetCFGDataStr(6) <>'' then
begin
NosoPayData := GetCFGDataStr(6);
NosoPayData :=StringReplace(NosoPayData,':','',[rfReplaceAll, rfIgnoreCase]);
NosoPayData :=StringReplace(NosoPayData,',',' ',[rfReplaceAll, rfIgnoreCase]);
NPDBlock := StrToIntdef(Parameter(NosoPayData,0),0);
if NPDBlock = numero then
begin
NPDSource := Parameter(NosoPayData,1);
NPDTarget := Parameter(NosoPayData,2);
if ( (IsValidHashAddress(NPDTarget)) and (IsValidHashAddress(NPDSource)) ) then
begin
NPDAmount := StrToInt64def(Parameter(NosoPayData,3),0);
if NPDAmount > 0 then
begin
if SummaryValidPay(NPDSource,NPDamount,NPDBlock) then
begin
CreditTo(NPDTarget,NPDAmount,NPDBlock);
NPDOrder := CreateNosoPayOrder(NPDBlock,NPDSource,NPDTarget,TimeStamp,NPDAmount);
insert(NPDOrder,ListaOrdenes,length(listaordenes));
RemoveCFGData(GetCFGDataStr(6),6);
end;
end;
end;
end;
end;
// Project funds payment
if numero >= PoSBlockEnd then
begin
DevsTotalReward := ((GetBlockReward(Numero)+MinerFee)*GetDevPercentage(Numero)) div 10000;
DevORder := CreateDevPaymentOrder(numero,TimeStamp,DevsTotalReward);
CreditTo('NpryectdevepmentfundsGE',DevsTotalReward,numero);
insert(DevORder,ListaOrdenes,length(listaordenes));
end;
if GVTsTransfered>0 then
begin
SaveGVTs;
UpdateMyGVTsList;
end;
TRY
SetLength(ArrayPoolTXs,0);
ArrayPoolTXs := copy(IgnoredTrxs,0,length(IgnoredTrxs));
EXCEPT on E:Exception do
begin
ToLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'Error asigning pending to Ignored');
end;
END; {TRY}
SetLength(IgnoredTrxs,0);
EndPerformance('NewBLOCK_PENDING');
LeaveCriticalSection(CSPending);
//PoS payment
BeginPerformance('NewBLOCK_PoS');
if numero >= PoSBlockStart then
begin
SetLength(PoSAddressess,0);
PoSReward := 0;
PosCount := 0;
PosTotalReward := 0;
if numero < PosBlockEnd then
begin
PosRequired := (GetSupply(numero)*PosStackCoins) div 10000;
PoScount := length(PoSAddressess);
PosTotalReward := ((GetBlockReward(Numero)+MinerFee)*GetPoSPercentage(Numero)) div 10000;
PosReward := PosTotalReward div PoScount;
PosTotalReward := PoSCount * PosReward;
//pay POS
for contador := 0 to length(PoSAddressess)-1 do
CreditTo(PoSAddressess[contador].address,PosReward,numero);
end;
end;
EndPerformance('NewBLOCK_PoS');
// Masternodes processing
BeginPerformance('NewBLOCK_MNs');
CreditMNVerifications();
MNsFileText := GetMNsAddresses(MyLastBlock);
SaveMNsFile(MNsFileText);
FillNodeList;
ClearMNsChecks();
ClearMNsList();
ClearReceivedMNs();
if numero >= MNBlockStart then
begin
SetLength(MNsAddressess,0);
Contador := 1;
Repeat
begin
ThisParam := Parameter(MNsFileText,contador);
if ThisParam<> '' then
begin
ThisParam := StringReplace(ThisParam,':',' ',[rfReplaceAll]);
ThisParam := Parameter(ThisParam,1);
SetLength(MNsAddressess,length(MNsAddressess)+1);
MNsAddressess[length(MNsAddressess)-1].address:=ThisParam;
end;
Inc(contador);
end;
until ThisParam = '';
MNsCount := Length(MNsAddressess);
MNsTotalReward := ((GetBlockReward(Numero)+MinerFee)*GetMNsPercentage(Numero,GetCFGDataStr(0))) div 10000;
if MNsCount>0 then MNsReward := MNsTotalReward div MNsCount
else MNsReward := 0;
MNsTotalReward := MNsCount * MNsReward;
NewMNs := 0;
For contador := 0 to length(MNsAddressess)-1 do
begin
CreditTo(MNsAddressess[contador].address,MNsReward,numero);
if AddLockedMM(MNsAddressess[contador].address,numero) then Inc(NewMNs);
end;
EndPerformance('NewBLOCK_MNs');
end;// End of MNS payment procecessing
// ***END MASTERNODES PROCESSING***
// Reset Order hashes received
ClearReceivedOrdersIDs;
// Miner payment
PoWTotalReward := (GetBlockReward(Numero)+MinerFee)-PosTotalReward-MNsTotalReward-DevsTotalReward;
CreditTo(Minero,PoWTotalReward,numero);
// Update summary lastblock
CreditTo(AdminHash,0,numero);
// Save summary file
BeginPerformance('NewBLOCK_SaveSum');
UpdateSummaryChanges();
EndPerformance('NewBLOCK_SaveSum');
SummaryLastop := numero;
// Limpiar las pendientes
ClearWallPendings;
// Definir la cabecera del bloque *****
BlockHeader := Default(BlockHeaderData);
BlockHeader.Number := Numero;
BlockHeader.TimeStart:= StartBlockTime;
BlockHeader.TimeEnd:= timeStamp;
BlockHeader.TimeTotal:= TimeStamp - StartBlockTime;
BlockHeader.TimeLast20:=0;//GetLast20Time(BlockHeader.TimeTotal);
BlockHeader.TrxTotales:=length(ListaOrdenes);
if numero = 0 then BlockHeader.Difficult:= InitialBlockDiff
else if ( (numero>0) and (numero<53000) ) then BlockHeader.Difficult:= 0
else BlockHeader.Difficult := PoSCount;
BlockHeader.TargetHash:=TargetHash;
//if protocolo = 1 then BlockHeader.Solution:= Solucion
BlockHeader.Solution:= Solucion+' '+{GetNMSData.Diff}'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF1'+' '+PoWTotalReward.ToString+' '+MNsTotalReward.ToString+' '+PosTotalReward.ToString;
if numero = 0 then BlockHeader.Solution:='';
if numero = 0 then BlockHeader.LastBlockHash:='NOSO GENESYS BLOCK'
else BlockHeader.LastBlockHash:=MyLastBlockHash;
if numero<53000 then BlockHeader.NxtBlkDiff:= 0{MNsReward}//GetDiffForNextBlock(numero,BlockHeader.TimeLast20,BlockHeader.TimeTotal,BlockHeader.Difficult);
else BlockHeader.NxtBlkDiff := MNsCount;
BlockHeader.AccountMiner:=Minero;
BlockHeader.MinerFee:=MinerFee;
BlockHeader.Reward:=GetBlockReward(Numero);
// Fin de la cabecera -----
// Guardar bloque al disco
if not GuardarBloque(FileName,BlockHeader,ListaOrdenes,PosReward,PosCount,PoSAddressess,
MNsReward, MNsCount,MNsAddressess) then
ToLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'*****CRITICAL*****'+slinebreak+'Error building block: '+numero.ToString);
BuildNMSBlock := 0;
ZipSumary;
SetLength(ListaOrdenes,0);
SetLength(PoSAddressess,0);
// Actualizar informacion
MyLastBlock := Numero;
MyLastBlockHash := HashMD5File(BlockDirectory+IntToStr(MyLastBlock)+'.blk');
LastBlockData := LoadBlockDataHeader(MyLastBlock);
SetSummaryHash;
SetMNsHash;
// Actualizar el arvhivo de cabeceras
AddRecordToHeaders(Numero,MyLastBlockHash,MySumarioHash);
SetResumenHash;
if ( (Numero>0) and (form1.Server.Active) ) then
begin
OutgoingMsjsAdd(ProtocolLine(ping));
end;
CheckForMyPending;
U_DirPanel := true;
ExpiredMNs := ClearExpiredLockedMNs(numero);
SavePSOFileToDisk(Numero);
OutText(format('Block built: %d (%d ms) MNs: + %d / - %d',[numero,EndPerformance('BuildNewBlock'),NewMNs, ExpiredMNs]),true);
end
else
begin
OutText('Failed to build the block',true);
end;
BuildingBlock := 0;
U_DataPanel := true;
End;
{
Function GetDiffHashrate(bestdiff:String):integer;
var
counter :integer= 0;
Begin
repeat
counter := counter+1;
until bestdiff[counter]<> '0';
Result := (Counter-1)*100;
if bestdiff[counter]='1' then Result := Result+50;
if bestdiff[counter]='2' then Result := Result+25;
if bestdiff[counter]='3' then Result := Result+12;
if bestdiff[counter]='4' then Result := Result+6;
//if bestdiff[counter]='5' then Result := Result+3;
End;
}
{
Function BestHashReadeable(BestDiff:String):string;
var
counter :integer = 0;
Begin
if bestdiff = '' then BestDiff := 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
repeat
counter := counter+1;
until bestdiff[counter]<> '0';
Result := (Counter-1).ToString+'.';
if counter<length(BestDiff) then Result := Result+bestdiff[counter];
End;
}
{
// Devuelve cuantos caracteres compondran el targethash del siguiente bloque
function GetDiffForNextBlock(UltimoBloque,Last20Average, lastblocktime,previous:integer):integer;
Begin
result := previous;
if UltimoBloque < 21 then result := InitialBlockDiff
else
begin
if Last20Average < SecondsPerBlock then
begin
if lastblocktime<SecondsPerBlock then result := Previous+1
end
else if Last20Average > SecondsPerBlock then
begin
if lastblocktime>SecondsPerBlock then result := Previous-1
end
else result := previous;
end;
End;
}
{
// Hace el calculo del tiempo promedio empleado en los ultimos 20 bloques
function GetLast20Time(LastBlTime:integer):integer;
var
Part1, Part2 : integer;
Begin
if LastBlockData.Number<21 then result := SecondsPerBlock
else
begin
Part1 := LastBlockData.TimeLast20 * 19 div 20;
Part2 := LastBlTime div 20;
result := Part1 + Part2;
end;
End;
}
// RETURNS THE MINING REWARD FOR A BLOCK
function GetBlockReward(BlNumber:int64):Int64;
var
NumHalvings : int64;
Begin
if BlNumber = 0 then result := PremineAmount
else if ((BlNumber > 0) and (blnumber < BlockHalvingInterval*(HalvingSteps+1))) then
begin
numHalvings := BlNumber div BlockHalvingInterval;
result := InitialReward div ( 2**NumHalvings );
end
else result := 0;
End;
// Guarda el archivo de bloque en disco
Function GuardarBloque(NombreArchivo:string;Cabezera:BlockHeaderData;
Ordenes:array of TOrderData;
PosPay:Int64;PoSnumber:integer;PosAddresses:array of TArrayPos;
MNsPay:int64;MNsNumber:Integer;MNsAddresses:array of TArrayPos):boolean;
var
MemStr: TMemoryStream;
NumeroOrdenes : int64;
counter : integer;
Begin
result := true;
BeginPerformance('GuardarBloque');
NumeroOrdenes := Cabezera.TrxTotales;
MemStr := TMemoryStream.Create;
TRY
MemStr.Write(Cabezera,Sizeof(Cabezera));
for counter := 0 to NumeroOrdenes-1 do
MemStr.Write(Ordenes[counter],Sizeof(Ordenes[Counter]));
if Cabezera.Number>=PoSBlockStart then
begin
MemStr.Write(PosPay,Sizeof(PosPay));
MemStr.Write(PoSnumber,Sizeof(PoSnumber));
for counter := 0 to PoSnumber-1 do
MemStr.Write(PosAddresses[counter],Sizeof(PosAddresses[Counter]));
end;
if Cabezera.Number>=MNBlockStart then
begin
MemStr.Write(MNsPay,Sizeof(MNsPay));
MemStr.Write(MNsnumber,Sizeof(MNsnumber));
for counter := 0 to MNsNumber-1 do
begin
MemStr.Write(MNsAddresses[counter],Sizeof(MNsAddresses[Counter]));
end;
end;
MemStr.SaveToFile(NombreArchivo);
EXCEPT On E :Exception do
begin
ToLog('console','Error saving block to disk: '+E.Message);
result := false;
end;
END{Try};
MemStr.Free;
EndPerformance('GuardarBloque');
End;
{
// Carga la informacion del bloque
function LoadBlockDataHeader(BlockNumber:integer):BlockHeaderData;
var
MemStr: TMemoryStream;
Header : BlockHeaderData;
ArchData : String;
Begin
Header := Default(BlockHeaderData);
ArchData := BlockDirectory+IntToStr(BlockNumber)+'.blk';
MemStr := TMemoryStream.Create;
TRY
MemStr.LoadFromFile(ArchData);
MemStr.Position := 0;
MemStr.Read(Header, SizeOf(Header));
EXCEPT ON E:Exception do
begin
ToLog('console','Error loading Header from block '+IntToStr(BlockNumber)+':'+E.Message);
end;
END{Try};
MemStr.Free;
Result := header;
End;
}
{
// Devuelve las transacciones del bloque
function GetBlockTrxs(BlockNumber:integer):TBlockOrdersArray;
var
ArrTrxs : TBlockOrdersArray;
MemStr: TMemoryStream;
Header : BlockHeaderData;
ArchData : String;
counter : integer;
TotalTrxs, totalposes : integer;
posreward : int64;
Begin
Setlength(ArrTrxs,0);
ArchData := BlockDirectory+IntToStr(BlockNumber)+'.blk';
MemStr := TMemoryStream.Create;
try
MemStr.LoadFromFile(ArchData);
MemStr.Position := 0;
MemStr.Read(Header, SizeOf(Header));
TotalTrxs := header.TrxTotales;
SetLength(ArrTrxs,TotalTrxs);
For Counter := 0 to TotalTrxs-1 do
MemStr.Read(ArrTrxs[Counter],Sizeof(ArrTrxs[Counter])); // read each record
Except on E: Exception do // nothing, the block is not founded
end;
MemStr.Free;
Result := ArrTrxs;
End;
}
Function GetBlockPoSes(BlockNumber:integer): BlockArraysPos;
var
resultado : BlockArraysPos;
ArrTrxs : TBlockOrdersArray;
ArchData : String;
MemStr: TMemoryStream;
Header : BlockHeaderData;
TotalTrxs, totalposes : integer;
posreward : int64;
counter : integer;
Begin
Setlength(resultado,0);
ArchData := BlockDirectory+IntToStr(BlockNumber)+'.blk';
MemStr := TMemoryStream.Create;
try
MemStr.LoadFromFile(ArchData);
MemStr.Position := 0;
MemStr.Read(Header, SizeOf(Header));
TotalTrxs := header.TrxTotales;
SetLength(ArrTrxs,TotalTrxs);
For Counter := 0 to TotalTrxs-1 do
MemStr.Read(ArrTrxs[Counter],Sizeof(ArrTrxs[Counter])); // read each record
MemStr.Read(posreward, SizeOf(int64));
MemStr.Read(totalposes, SizeOf(integer));
SetLength(resultado,totalposes);
For Counter := 0 to totalposes-1 do
MemStr.Read(resultado[Counter].address,Sizeof(resultado[Counter]));
SetLength(resultado,totalposes+1);
resultado[length(resultado)-1].address := IntToStr(posreward);
Except on E: Exception do // nothing, the block is not found
end;
MemStr.Free;
Result := resultado;
end;
Function GetBlockMNs(BlockNumber:integer): BlockArraysPos;
var
resultado : BlockArraysPos;
ArrayPos : BlockArraysPos;
ArrTrxs : TBlockOrdersArray;
ArchData : String;
MemStr: TMemoryStream;
Header : BlockHeaderData;
TotalTrxs, totalposes, totalMNs : integer;
posreward,MNreward : int64;
counter : integer;
Begin
Setlength(resultado,0);
Setlength(ArrayPos,0);
if blocknumber <MNBlockStart then
begin
result := resultado;
exit;
end;
ArchData := BlockDirectory+IntToStr(BlockNumber)+'.blk';
MemStr := TMemoryStream.Create;
TRY
// HEADERS
MemStr.LoadFromFile(ArchData);
MemStr.Position := 0;
MemStr.Read(Header, SizeOf(Header));
// TRXS LIST
TotalTrxs := header.TrxTotales;
SetLength(ArrTrxs,TotalTrxs);
For Counter := 0 to TotalTrxs-1 do
MemStr.Read(ArrTrxs[Counter],Sizeof(ArrTrxs[Counter])); // read each record
// POS INFO
MemStr.Read(posreward, SizeOf(int64));
MemStr.Read(totalposes, SizeOf(integer));
SetLength(ArrayPos,totalposes);
For Counter := 0 to totalposes-1 do
MemStr.Read(ArrayPos[Counter].address,Sizeof(ArrayPos[Counter]));
// MNS INFO
MemStr.Read(MNReward, SizeOf(MNReward));
MemStr.Read(totalMNs, SizeOf(totalMNs));
SetLength(resultado,totalMNs);
For Counter := 0 to totalMNs-1 do
begin
MemStr.Read(resultado[Counter].address,Sizeof(resultado[Counter]));
end;
SetLength(resultado,totalMNs+1);
resultado[length(resultado)-1].address := IntToStr(MNReward);
EXCEPT on E: Exception do // nothing, the block is not founded
ToLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'EXCEPTION on MNs file data:'+E.Message)
END; {TRY}
MemStr.Free;
Result := resultado;
end;
// Deshacer el ultimo bloque
Procedure UndoneLastBlock();
Const
Highest : integer = 0;
var
blocknumber : integer;
Begin
blocknumber:= MyLastBlock;
if BlockNumber < Highest then
begin
ToLog('Console','Can not undo block '+mylastblock.ToString);
exit;
end
else Highest := BlockNumber;
if BlockNumber = 0 then exit;
if MyConStatus = 3 then
begin
MyConStatus := 2;
//if Form1.Server.Active then Form1.Server.Active := false;
ClearMNsChecks();
ClearMNsList();
ClearAllPending;
ClearReceivedOrdersIDs;
end;
// recover summary
RestoreSumaryBackup();
CreateSumaryIndex;
// recover GVTs file
EnterCriticalSection(CSGVTsArray);
trydeletefile(GVTsFilename);
copyfile(GVTsFilename+'.bak',GVTsFilename);
LeaveCriticalSection(CSGVTsArray);
GetGVTsFileData();
UpdateMyGVTsList;
// Actualizar la cartera
UpdateWalletFromSumario();
// actualizar el archivo de cabeceras
RemoveHeadersLastRecord;
// Borrar archivo del ultimo bloque
trydeletefile(BlockDirectory +IntToStr(MyLastBlock)+'.blk');
// Actualizar mi informacion
MyLastBlock := GetMyLastUpdatedBlock;
MyLastBlockHash := HashMD5File(BlockDirectory+IntToStr(MyLastBlock)+'.blk');
LastBlockData := LoadBlockDataHeader(MyLastBlock);
SetResumenHAsh;
ToLog('console','****************************');
ToLog('console','Block undone: '+IntToStr(blocknumber)); //'Block undone: '
ToLog('console','****************************');
ToLog('events',TimeToStr(now)+'Block Undone: '+IntToStr(blocknumber));
ToDeepDeb('Block undone: '+Blocknumber.ToString);
U_DataPanel := true;
End;
Function RemoveBlocks(UpToBlock:int64):integer;
var
Last : int64;
Begin
Result := 0;
Repeat
Last := GetMyLastUpdatedBlock;
If Last >= UpToBlock then
begin
trydeletefile(BlockDirectory +IntToStr(Last)+'.blk');
Inc(Result);
end;
until Last < UpToBlock;
MyLastBlock := GetMyLastUpdatedBlock;
End;
Function GEtNSLBlkOrdInfo(LineText:String):String;
var
ParamBlock : String;
BlkNumber : integer;
OrdersArray : TBlockOrdersArray;
Cont : integer;
ThisOrder : string = '';
Begin
BeginPErformance('GEtNSLBlkOrdInfo');
Result := 'NSLBLKORD ';
ParamBlock := UpperCase(Parameter(LineText,1));
If paramblock = 'LAST' then BlkNumber := MyLastBlock
else BlkNumber := StrToIntDef(ParamBlock,-1);
if ( (BlkNumber<0) or (BlkNumber<MyLastBlock-4000) or (BlkNumber>MyLastBlock) ) then Result := Result+'ERROR'
else
begin
Result := Result+BlkNumber.ToString+' ';
OrdersArray := Default(TBlockOrdersArray);
OrdersArray := GetBlockTrxs(BlkNumber);
if Length(OrdersArray)>0 then
begin
For Cont := 0 to LEngth(OrdersArray)-1 do
begin
if OrdersArray[cont].OrderType='TRFR' then
begin
ThisOrder := ThisOrder+OrdersArray[Cont].sender+':'+OrdersArray[Cont].Receiver+':'+OrdersArray[Cont].AmmountTrf.ToString+':'+
OrdersArray[Cont].Reference+':'+OrdersArray[Cont].OrderID+' ';
end;
end;
end;
Result := Result+ThisOrder;
Result := Trim(Result)
end;
EndPErformance('GEtNSLBlkOrdInfo');
End;
END. // END UNIT