forked from PascalCoinDev/PascalCoin
-
Notifications
You must be signed in to change notification settings - Fork 32
/
UNetProtocol.pas
5332 lines (5056 loc) · 211 KB
/
UNetProtocol.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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit UNetProtocol;
{ Copyright (c) 2016 by Albert Molina
Distributed under the MIT software license, see the accompanying file LICENSE
or visit http://www.opensource.org/licenses/mit-license.php.
This unit is a part of the PascalCoin Project, an infinitely scalable
cryptocurrency. Find us here:
Web: https://www.pascalcoin.org
Source: https://github.com/PascalCoin/PascalCoin
If you like it, consider a donation using Bitcoin:
16K3HCZRhFUtM8GdWRcfKeaa6KsuyxZaYk
THIS LICENSE HEADER MUST NOT BE REMOVED.
}
{$I ./../config.inc}
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
Uses
{$IFnDEF FPC}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
{$ELSE}
{$ENDIF}
UBlockChain, Classes, SysUtils, UAccounts, UThread,
UCrypto, UTCPIP, SyncObjs, UBaseTypes, UCommon, UPCOrderedLists,
UPCDataTypes,
{$IFNDEF FPC}System.Generics.Collections,System.Generics.Defaults
{$ELSE}Generics.Collections,Generics.Defaults{$ENDIF},
{$IFDEF USE_ABSTRACTMEM}UPCAbstractMem, UAbstractMemBlockchainStorage,{$ENDIF}
UNetProtection;
Const
CT_MagicRequest = $0001;
CT_MagicResponse = $0002;
CT_MagicAutoSend = $0003;
CT_NetOp_Hello = $0001; // Sends my last operationblock + servers. Receive last operationblock + servers + same operationblock number of sender
CT_NetOp_Error = $0002;
CT_NetOp_Message = $0003;
CT_NetOp_GetBlockHeaders = $0005; // Sends from and to. Receive a number of OperationsBlock to check
CT_NetOp_GetBlocks = $0010;
CT_NetOp_NewBlock = $0011;
CT_NetOp_NewBlock_Fast_Propagation = $0012; // New V4 protocol: Allows PIP-0015 Fast block propagation
CT_NetOp_GetBlockchainOperations = $0013; // New V4 protocol: Allows PIP-0015 Fast block propagation
CT_NetOp_AddOperations = $0020;
CT_NetOp_GetSafeBox = $0021; // V2 Protocol: Allows to send/receive Safebox in chunk parts
CT_NetOp_GetPendingOperations = $0030; // Obtain pending operations
CT_NetOp_GetAccount = $0031; // Obtain account info
CT_NetOp_GetPubkeyAccounts = $0032; // Obtain public key accounts
CT_NetOp_Reserved_Start = $1000; // This will provide a reserved area
CT_NetOp_Reserved_End = $1FFF; // End of reserved area
CT_NetOp_ERRORCODE_NOT_IMPLEMENTED = $00FF;// This will be error code returned when using Reserved area and Op is not implemented
CT_NetError_InvalidProtocolVersion = $0001;
CT_NetError_IPBlackListed = $0002;
CT_NetError_NotFound = $0003;
CT_NetError_InvalidDataBufferInfo = $0010;
CT_NetError_InternalServerError = $0011;
CT_NetError_InvalidNewAccount = $0012;
CT_NetError_SafeboxNotFound = $0020;
CT_NetError_NotAvailable = $0021;
CT_LAST_CONNECTION_BY_SERVER_MAX_MINUTES = 60*60*3;
CT_LAST_CONNECTION_MAX_MINUTES = 60*60;
CT_MAX_NODESERVERS_ON_HELLO = 10;
CT_MIN_NODESERVERS_BUFFER = 50;
CT_MAX_NODESERVERS_BUFFER = 300;
CT_MAX_OPS_PER_BLOCKCHAINOPERATIONS = 10000;
CT_MAX_SAFEBOXCHUNK_BLOCKS = 30000;
CT_MIN_NetProtocol_Use_Aggregated_Hashrate = 12;
Type
{
Net Protocol:
3 different types: Request,Response or Auto-send
Request: <Magic Net Identification (4b)><request (2b)><operation (2b)><0x0000 (2b)><request_id(4b)><protocol info(4b)><data_length(4b)><request_data (data_length bytes)>
Response: <Magic Net Identification (4b)><response (2b)><operation (2b)><error_code (2b)><request_id(4b)><protocol info(4b)><data_length(4b)><response_data (data_length bytes)>
Auto-send: <Magic Net Identification (4b)><autosend (2b)><operation (2b)><0x0000 (2b)><0x00000000 (4b)><protocol info(4b)><data_length(4b)><data (data_length bytes)>
Min size: 4b+2b+2b+2b+4b+4b+4b = 22 bytes
Max size: (depends on last 4 bytes) = 22..(2^32)-1
}
TNetTransferType = (ntp_unknown, ntp_request, ntp_response, ntp_autosend);
TNetProtocolVersion = Record
protocol_version,
protocol_available : Word;
end;
TNetHeaderData = Record
header_type : TNetTransferType;
protocol : TNetProtocolVersion;
operation : Word;
request_id : Cardinal;
buffer_data_length : Cardinal;
//
is_error : Boolean;
error_code : Integer;
error_text : String;
end;
TNetConnection = Class;
TNodeServerAddress = Record
ip : String;
port : Word;
last_connection : Cardinal;
last_connection_by_server : Cardinal;
last_connection_by_me : Cardinal;
//
netConnection : TNetConnection;
its_myself : Boolean;
last_attempt_to_connect : TDateTime;
total_failed_attemps_to_connect : Integer;
is_blacklisted : Boolean; // Build 1.4.4
BlackListText : String;
end;
TNodeServerAddressArray = Array of TNodeServerAddress;
PNodeServerAddress = ^TNodeServerAddress;
TNetData = Class;
// This will maintain a list sorted by 2 values: ip/port and netConnection in thread safe mode
// Using this object, NodeServerAddress can be more high in length and also more quick to search
{ TOrderedServerAddressListTS }
TOrderedServerAddressListTS = Class
private
FAllowDeleteOnClean: Boolean;
FNetData : TNetData;
FCritical : TPCCriticalSection;
FListByIp : TList<Pointer>;
FListByNetConnection : TList<Pointer>;
Procedure SecuredDeleteFromListByIp(index : Integer);
Function SecuredFindByIp(const ip : String; port : Word; var Index: Integer): Boolean;
Function SecuredFindByNetConnection(const search : TNetConnection; var Index: Integer): Boolean;
protected
function DeleteNetConnection(netConnection : TNetConnection) : Boolean;
public
Constructor Create(ANetData : TNetData);
Destructor Destroy; Override;
Procedure Clear;
Function Count : Integer;
Function CleanBlackList(forceCleanAll : Boolean) : Integer;
procedure CleanNodeServersList;
Function LockList : TList<Pointer>;
Procedure UnlockList;
procedure ResetConnectAttempts;
function IsBlackListed(const ip: String; out AReason : string): Boolean; overload;
function IsBlackListed(const ip: String): Boolean; overload;
function GetNodeServerAddress(const ip : String; port:Word; CanAdd : Boolean; var nodeServerAddress : TNodeServerAddress) : Boolean;
procedure SetNodeServerAddress(const nodeServerAddress : TNodeServerAddress);
Procedure UpdateNetConnection(netConnection : TNetConnection);
procedure GetNodeServersToConnnect(maxNodes : Integer; useArray : Boolean; var nsa : TNodeServerAddressArray);
Function GetValidNodeServers(OnlyWhereIConnected : Boolean; Max : Integer): TNodeServerAddressArray;
property AllowDeleteOnClean : Boolean read FAllowDeleteOnClean write FAllowDeleteOnClean;
End;
TNetMessage_Hello = Record
last_operation : TOperationBlock;
servers_address : Array of TNodeServerAddress;
end;
TNetRequestRegistered = Record
NetClient : TNetConnection;
Operation : Word;
RequestId : Cardinal;
SendTime : TDateTime;
end;
TNetStatistics = Record
ActiveConnections : Integer; // All connections wiht "connected" state
ClientsConnections : Integer; // All clients connected to me like a server with "connected" state
ServersConnections : Integer; // All servers where I'm connected
ServersConnectionsWithResponse : Integer; // All servers where I'm connected and I've received data
TotalConnections : Integer;
TotalClientsConnections : Integer;
TotalServersConnections : Integer;
BytesReceived : Int64;
BytesSend : Int64;
NodeServersListCount : Integer;
NodeServersDeleted : Integer;
end;
{ TNetDataNotifyEventsThread ensures that notifications of TNetData object
will be in main Thread calling a Synchronized method }
TNetDataNotifyEventsThread = Class(TPCThread)
private
FNetData: TNetData;
FNotifyOnReceivedHelloMessage : Boolean;
FNotifyOnStatisticsChanged : Boolean;
FNotifyOnNetConnectionsUpdated : Boolean;
FNotifyOnNodeServersUpdated : Boolean;
FNotifyOnBlackListUpdated : Boolean;
protected
procedure SynchronizedNotify;
procedure BCExecute; override;
public
Constructor Create(ANetData : TNetData);
End;
TNetClientsDestroyThread = Class(TPCThread)
private
FNetData : TNetData;
FTerminatedAllConnections : Boolean;
protected
procedure BCExecute; override;
public
Constructor Create(NetData : TNetData);
Procedure WaitForTerminatedAllConnections;
End;
TThreadCheckConnections = Class(TPCThread)
private
FNetData : TNetData;
FLastCheckTS : TTickCount;
protected
procedure BCExecute; override;
public
Constructor Create(NetData : TNetData);
End;
{ TNetworkAdjustedTime }
TNetworkAdjustedTime = Class
private
FOffsetLimit: Integer;
FTimesList : TPCThreadList<Pointer>;
FTimeOffset : Integer;
FTotalCounter : Integer;
Function IndexOfClientIp(list : TList<Pointer>; const clientIp : String) : Integer;
Procedure UpdateMedian(list : TList<Pointer>);
public
constructor Create;
destructor Destroy; override;
procedure UpdateIp(const clientIp : String; clientTimestamp : Cardinal);
procedure AddNewIp(const clientIp : String; clientTimestamp : Cardinal);
procedure RemoveIp(const clientIp : String);
function GetAdjustedTime : Cardinal;
property TimeOffset : Integer read FTimeOffset;
function GetMaxAllowedTimestampForNewBlock : Cardinal;
property OffsetLimit : Integer read FOffsetLimit write FOffsetLimit;
end;
TProcessReservedAreaMessage = procedure (netData : TNetData; senderConnection : TNetConnection; const HeaderData : TNetHeaderData; receivedData : TStream; responseData : TStream) of object;
TGetNewBlockchainFromClientDownloadNewSafebox = procedure (netData : TNetData; clientConnection : TNetConnection; my_blocks_count, client_blocks_count : Integer; var download_new_safebox : Boolean) of object;
TNetData = Class(TComponent)
private
FMaxNodeServersAddressesBuffer: Integer;
FMaxServersConnected: Integer;
FMinServersConnected: Integer;
FNetDataNotifyEventsThread : TNetDataNotifyEventsThread;
FNodePrivateKey : TECPrivateKey;
FNetConnections : TPCThreadList<TNetConnection>;
FNodeServersAddresses : TOrderedServerAddressListTS;
FLastRequestId : Cardinal;
FOnProcessReservedAreaMessage: TProcessReservedAreaMessage;
FRegisteredRequests : TPCThreadList<Pointer>;
FIsDiscoveringServers : Boolean;
FLockGettingNewBlockChainFromClient : TPCCriticalSection;
FNewBlockChainFromClientStatus : String;
FOnConnectivityChanged : TNotifyManyEvent;
FOnNetConnectionsUpdated: TNotifyEvent;
FOnNodeServersUpdated: TNotifyEvent;
FOnBlackListUpdated: TNotifyEvent;
FThreadCheckConnections : TThreadCheckConnections;
FOnReceivedHelloMessage: TNotifyEvent;
FNetStatistics: TNetStatistics;
FOnStatisticsChanged: TNotifyEvent;
FMaxRemoteOperationBlock : TOperationBlock;
FFixedServers : TNodeServerAddressArray;
FNetClientsDestroyThread : TNetClientsDestroyThread;
FNetConnectionsActive: Boolean;
FMaxConnections : Integer;
FNetworkAdjustedTime : TNetworkAdjustedTime;
FIpInfos : TIpInfos;
FMinFutureBlocksToDownloadNewSafebox: Integer;
FOnGetNewBlockchainFromClientDownloadNewSafebox: TGetNewBlockchainFromClientDownloadNewSafebox;
Procedure IncStatistics(incActiveConnections,incClientsConnections,incServersConnections,incServersConnectionsWithResponse : Integer; incBytesReceived, incBytesSend : Int64);
procedure SetMaxNodeServersAddressesBuffer(AValue: Integer);
procedure SetMaxServersConnected(AValue: Integer);
procedure SetMinServersConnected(AValue: Integer);
procedure SetNetConnectionsActive(const Value: Boolean);
procedure SetMinFutureBlocksToDownloadNewSafebox(const Value: Integer);
procedure OnDownloadingSafeboxProgressNotify(sender : TObject; const mesage : String; curPos, totalCount : Int64);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
Procedure DiscoverServersTerminated(Sender : TObject);
procedure DoProcessReservedAreaMessage(senderConnection : TNetConnection; const headerData : TNetHeaderData; receivedData : TStream; responseData : TStream); virtual;
public
Class function HeaderDataToText(const HeaderData : TNetHeaderData) : String;
Class function ExtractHeaderInfo(buffer : TStream; var HeaderData : TNetHeaderData; DataBuffer : TStream; var IsValidHeaderButNeedMoreData : Boolean) : Boolean;
Class Function OperationToText(operation : Word) : String;
// Only 1 NetData
Class Function NetData : TNetData;
Class Function NetDataExists : Boolean;
//
Constructor Create(AOwner : TComponent); override;
Destructor Destroy; override;
Function Bank : TPCBank;
Function NewRequestId : Cardinal;
Procedure RegisterRequest(Sender: TNetConnection; operation : Word; request_id : Cardinal);
Function UnRegisterRequest(Sender: TNetConnection; operation : Word; request_id : Cardinal) : Boolean;
Function PendingRequest(Sender : TNetConnection; var requests_data : String ) : Integer;
Procedure AddServer(NodeServerAddress : TNodeServerAddress);
//
Procedure DiscoverFixedServersOnly(const FixedServers : TNodeServerAddressArray);
//
Function ConnectionsCountAll : Integer;
Function ConnectionsCountServerClients : Integer;
Function ConnectionsCountClients : Integer;
Function GetConnection(index : Integer; var NetConnection : TNetConnection) : Boolean;
Function ConnectionsCount(CountOnlyNetClients : Boolean) : Integer;
Function Connection(index : Integer) : TNetConnection;
Function ConnectionExistsAndActive(ObjectPointer : TObject) : Boolean;
Function ConnectionExists(ObjectPointer : TObject) : Boolean;
Function ConnectionLock(Sender : TObject; ObjectPointer : TObject; MaxWaitMiliseconds : Cardinal) : Boolean;
Procedure ConnectionUnlock(ObjectPointer : TObject);
Function FindConnectionByClientRandomValue(Sender : TNetConnection) : TNetConnection;
Procedure DiscoverServers;
Procedure DisconnectClients;
procedure OnReadingNewSafeboxProgressNotify(sender : TObject; const mesage : String; curPos, totalCount : Int64);
Procedure GetNewBlockChainFromClient(Connection : TNetConnection; const why : String);
Property NodeServersAddresses : TOrderedServerAddressListTS read FNodeServersAddresses;
Property NetConnections : TPCThreadList<TNetConnection> read FNetConnections;
Property NetStatistics : TNetStatistics read FNetStatistics;
Property IsDiscoveringServers : Boolean read FIsDiscoveringServers;
function IsGettingNewBlockChainFromClient(var status : String) : Boolean;
Property MaxRemoteOperationBlock : TOperationBlock read FMaxRemoteOperationBlock;
Property NodePrivateKey : TECPrivateKey read FNodePrivateKey;
property OnConnectivityChanged : TNotifyManyEvent read FOnConnectivityChanged;
Property OnNetConnectionsUpdated : TNotifyEvent read FOnNetConnectionsUpdated write FOnNetConnectionsUpdated;
Property OnNodeServersUpdated : TNotifyEvent read FOnNodeServersUpdated write FOnNodeServersUpdated;
Property OnBlackListUpdated : TNotifyEvent read FOnBlackListUpdated write FOnBlackListUpdated;
Property OnReceivedHelloMessage : TNotifyEvent read FOnReceivedHelloMessage write FOnReceivedHelloMessage;
Property OnStatisticsChanged : TNotifyEvent read FOnStatisticsChanged write FOnStatisticsChanged;
property OnGetNewBlockchainFromClientDownloadNewSafebox : TGetNewBlockchainFromClientDownloadNewSafebox read FOnGetNewBlockchainFromClientDownloadNewSafebox write FOnGetNewBlockchainFromClientDownloadNewSafebox;
procedure NotifyConnectivityChanged;
Procedure NotifyNetConnectionUpdated;
Procedure NotifyNodeServersUpdated;
Procedure NotifyBlackListUpdated;
Procedure NotifyReceivedHelloMessage;
Procedure NotifyStatisticsChanged;
Property NetConnectionsActive : Boolean read FNetConnectionsActive write SetNetConnectionsActive;
Property NetworkAdjustedTime : TNetworkAdjustedTime read FNetworkAdjustedTime;
Property MaxNodeServersAddressesBuffer : Integer read FMaxNodeServersAddressesBuffer write SetMaxNodeServersAddressesBuffer;
Property OnProcessReservedAreaMessage : TProcessReservedAreaMessage read FOnProcessReservedAreaMessage write FOnProcessReservedAreaMessage;
Property MinServersConnected : Integer read FMinServersConnected write SetMinServersConnected;
Property MaxServersConnected : Integer read FMaxServersConnected write SetMaxServersConnected;
Property IpInfos : TIpInfos read FIpInfos;
Property MinFutureBlocksToDownloadNewSafebox : Integer read FMinFutureBlocksToDownloadNewSafebox write SetMinFutureBlocksToDownloadNewSafebox;
End;
{ TNetConnection }
TNetConnection = Class(TComponent)
private
FIsConnecting: Boolean;
FTcpIpClient : TNetTcpIpClient;
FRemoteOperationBlock : TOperationBlock;
FRemoteAccumulatedWork : UInt64;
FRemoteAggregatedHashrate : TBigNum;
FLastHelloTS : TTickCount;
FLastDataReceivedTS : TTickCount;
FLastDataSendedTS : TTickCount;
FClientBufferRead : TStream;
FNetLock : TPCCriticalSection;
FIsWaitingForResponse : Boolean;
FTimestampDiff : Integer;
FIsMyselfServer : Boolean;
FClientPublicKey : TAccountKey;
FCreatedTime: TDateTime;
FClientAppVersion: String;
FDoFinalizeConnection : Boolean;
FNetProtocolVersion: TNetProtocolVersion;
FAlertedForNewProtocolAvailable : Boolean;
FHasReceivedData : Boolean;
FIsDownloadingBlocks : Boolean;
FRandomWaitSecondsSendHello : Cardinal;
FBufferLock : TPCCriticalSection;
FBufferReceivedOperationsHash : TOrderedRawList;
FBufferToSendOperations : TOperationsHashTree;
FClientTimestampIp : String;
function GetConnected: Boolean;
procedure SetConnected(const Value: Boolean);
procedure TcpClient_OnConnect(Sender: TObject);
procedure TcpClient_OnDisconnect(Sender: TObject);
procedure DoProcessBuffer;
Procedure DoProcess_Hello(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_Message(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetBlocks_Request(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetBlocks_Response(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetBlockchainOperations_Request(AHeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetOperationsBlock_Request(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_NewBlock(AHeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_AddOperations(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetSafeBox_Request(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetPendingOperations_Request(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetAccount_Request(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetPubkeyAccounts_Request(HeaderData : TNetHeaderData; DataBuffer: TStream);
Procedure DoProcess_GetPendingOperations;
Procedure SetClient(Const Value : TNetTcpIpClient);
Function ReadTcpClientBuffer(MaxWaitMiliseconds : Cardinal; var HeaderData : TNetHeaderData; BufferData : TStream) : Boolean;
function GetClient: TNetTcpIpClient;
protected
Procedure Send(NetTranferType : TNetTransferType; operation, errorcode : Word; request_id : Integer; DataBuffer : TStream);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
Procedure SendError(NetTranferType : TNetTransferType; operation, request_id : Integer; error_code : Integer; const error_text : String);
public
Constructor Create(AOwner : TComponent); override;
Destructor Destroy; override;
Procedure DoSend(ANetTranferType: TNetTransferType; AOperation, AErrorcode: Word; ARequest_id: Integer; ADataBuffer: TStream);
Function DoSendAndWaitForResponse(operation: Word; RequestId: Integer; SendDataBuffer, ReceiveDataBuffer: TStream; MaxWaitTime : Cardinal; var HeaderData : TNetHeaderData) : Boolean;
Function ConnectTo(ServerIP: String; ServerPort:Word) : Boolean;
Property Connected : Boolean read GetConnected write SetConnected;
Property IsConnecting : Boolean read FIsConnecting;
Procedure DisconnectInvalidClient(ItsMyself : Boolean; Const why : String);
Function Send_Hello(NetTranferType : TNetTransferType; request_id : Integer) : Boolean;
Function Send_NewBlockFound(Const NewBlock : TPCOperationsComp) : Boolean;
Function Send_GetBlocks(StartAddress, quantity : Cardinal; var request_id : Cardinal) : Boolean;
Function Send_AddOperations(Operations : TOperationsHashTree) : Boolean;
Function Send_Message(Const TheMessage : String) : Boolean;
Function AddOperationsToBufferForSend(Operations : TOperationsHashTree) : Integer;
Property Client : TNetTcpIpClient read GetClient;
Function ClientRemoteAddr : String;
property TimestampDiff : Integer read FTimestampDiff;
property RemoteOperationBlock : TOperationBlock read FRemoteOperationBlock;
//
Property NetProtocolVersion : TNetProtocolVersion read FNetProtocolVersion;
//
Property IsMyselfServer : Boolean read FIsMyselfServer;
Property CreatedTime : TDateTime read FCreatedTime;
Property ClientAppVersion : String read FClientAppVersion write FClientAppVersion;
Procedure FinalizeConnection;
End;
TNetClient = Class;
TNetClientThread = Class(TPCThread)
private
FNetClient : TNetClient;
protected
procedure BCExecute; override;
public
Constructor Create(NetClient : TNetClient; AOnTerminateThread : TNotifyEvent);
End;
TNetClient = Class(TNetConnection)
private
FNetClientThread : TNetClientThread;
Procedure OnNetClientThreadTerminated(Sender : TObject);
public
Constructor Create(AOwner : TComponent); override;
Destructor Destroy; override;
End;
TNetServerClient = Class(TNetConnection);
{ TNetServer }
TNetServer = Class(TNetTcpIpServer)
private
protected
Procedure OnNewIncommingConnection(Sender : TObject; Client : TNetTcpIpClient); override;
procedure SetActive(const Value: Boolean); override;
procedure SetMaxConnections(AValue: Integer); override;
public
Constructor Create; override;
End;
TThreadDiscoverConnection = Class(TPCThread)
FNodeServerAddress : TNodeServerAddress;
protected
procedure BCExecute; override;
public
Constructor Create(NodeServerAddress: TNodeServerAddress; NotifyOnTerminate : TNotifyEvent);
End;
{ TThreadGetNewBlockChainFromClient }
TThreadGetNewBlockChainFromClient = Class(TPCThread)
protected
procedure BCExecute; override;
public
Constructor Create;
End;
Const
CT_TNodeServerAddress_NUL : TNodeServerAddress = (ip:'';port:0;last_connection:0;last_connection_by_server:0; last_connection_by_me:0; netConnection:nil;its_myself:false;last_attempt_to_connect:0;total_failed_attemps_to_connect:0;is_blacklisted:false;BlackListText:'');
CT_TNetStatistics_NUL : TNetStatistics = (ActiveConnections:0;ClientsConnections:0;ServersConnections:0;ServersConnectionsWithResponse:0;TotalConnections:0;TotalClientsConnections:0;TotalServersConnections:0;BytesReceived:0;BytesSend:0;NodeServersListCount:0;NodeServersDeleted:0);
implementation
uses
UConst, ULog, UNode, UTime, UPCEncryption, UChunk,
UPCOperationsBlockValidator, UPCOperationsSignatureValidator, UOpTransaction, UPCDownloadSafebox,
UPCTemporalFileStream;
Const
CT_NetTransferType : Array[TNetTransferType] of String = ('Unknown','Request','Response','Autosend');
CT_NetHeaderData : TNetHeaderData = (header_type:ntp_unknown;protocol:(protocol_version:0;protocol_available:0);operation:0;request_id:0;buffer_data_length:0;is_error:false;error_code:0;error_text:'');
{ TOrderedServerAddressListTS }
function TOrderedServerAddressListTS.CleanBlackList(forceCleanAll : Boolean) : Integer;
Var P : PNodeServerAddress;
i : Integer;
begin
CleanNodeServersList;
// This procedure cleans old blacklisted IPs
Result := 0;
FCritical.Acquire;
Try
for i := FListByIp.Count - 1 downto 0 do begin
P := FListByIp[i];
// Is an old blacklisted IP? (More than 1 hour)
If (P^.is_blacklisted) AND
((forceCleanAll) OR ((P^.last_connection+(CT_LAST_CONNECTION_MAX_MINUTES)) < (UnivDateTimeToUnix(DateTime2UnivDateTime(now))))) then begin
if (AllowDeleteOnClean) then begin
SecuredDeleteFromListByIp(i);
end else begin
P^.is_blacklisted:=False;
end;
inc(Result);
end;
end;
Finally
FCritical.Release;
End;
if (Result>0) then FNetData.NotifyBlackListUpdated;
end;
procedure TOrderedServerAddressListTS.CleanNodeServersList;
var i : Integer;
nsa : TNodeServerAddress;
currunixtimestamp : Cardinal;
begin
If Not (FAllowDeleteOnClean) then Exit;
currunixtimestamp := UnivDateTimeToUnix(DateTime2UnivDateTime(now));
FCritical.Acquire;
Try
i := FListByIp.Count-1;
while (i>=0) do begin
nsa := PNodeServerAddress( FListByIp[i] )^;
If (Not (nsa.is_blacklisted)) // Not blacklisted
And ((nsa.netConnection = Nil) // No connection
OR // Connected but a lot of time without data...
((Assigned(nsa.netConnection)) AND ((nsa.last_connection + (CT_LAST_CONNECTION_MAX_MINUTES)) < currunixtimestamp )))
And (
(nsa.total_failed_attemps_to_connect>0)
OR
(
// I've not connected CT_LAST_CONNECTION_MAX_MINUTES minutes before
((nsa.last_connection + (CT_LAST_CONNECTION_MAX_MINUTES)) < (currunixtimestamp))
And // Others have connected CT_LAST_CONNECTION_BY_SERVER_MAX_MINUTES minutes before
((nsa.last_connection_by_server + (CT_LAST_CONNECTION_BY_SERVER_MAX_MINUTES)) < (currunixtimestamp))
And
((nsa.last_connection>0) Or (nsa.last_connection_by_server>0))
))
And (
(nsa.last_connection_by_me=0)
Or
((nsa.last_connection_by_me + 86400) < (currunixtimestamp)) // Not connected in 24 hours
)
then begin
TLog.NewLog(ltdebug,ClassName,Format('Delete node server address: %s : %d last_connection:%d last_connection_by_server:%d total_failed_attemps:%d last_attempt_to_connect:%s ',
[nsa.ip,nsa.port,nsa.last_connection,nsa.last_connection_by_server,nsa.total_failed_attemps_to_connect,FormatDateTime('dd/mm/yyyy hh:nn:ss',nsa.last_attempt_to_connect)]));
SecuredDeleteFromListByIp(i);
end;
dec(i);
end;
finally
FCritical.Release;
end;
end;
procedure TOrderedServerAddressListTS.Clear;
Var P : PNodeServerAddress;
i : Integer;
begin
FCritical.Acquire;
Try
for i := 0 to FListByIp.Count - 1 do begin
P := FListByIp[i];
Dispose(P);
end;
inc(FNetData.FNetStatistics.NodeServersDeleted,FListByIp.count);
FListByIp.Clear;
FListByNetConnection.Clear;
FNetData.FNetStatistics.NodeServersListCount := 0;
finally
FCritical.Release;
end;
end;
function TOrderedServerAddressListTS.Count: Integer;
begin
FCritical.Acquire;
try
Result := FListByIp.Count;
finally
FCritical.Release;
end;
end;
constructor TOrderedServerAddressListTS.Create(ANetData : TNetData);
begin
FNetData := ANetData;
FCritical := TPCCriticalSection.Create(Classname);
FListByIp := TList<Pointer>.Create;
FListByNetConnection := TList<Pointer>.Create;
FAllowDeleteOnClean := True;
end;
function TOrderedServerAddressListTS.DeleteNetConnection(netConnection: TNetConnection) : Boolean;
Var i : Integer;
begin
FCritical.Acquire;
Try
If SecuredFindByNetConnection(netConnection,i) then begin
PNodeServerAddress( FListByNetConnection[i] )^.netConnection := Nil;
FListByNetConnection.Delete(i);
Result := True;
end else Result := False;
Finally
FCritical.Release;
end;
end;
destructor TOrderedServerAddressListTS.Destroy;
begin
Clear;
FreeAndNil(FCritical);
FreeAndNil(FListByIp);
FreeAndNil(FListByNetConnection);
inherited Destroy;
end;
function TOrderedServerAddressListTS.GetNodeServerAddress(const ip: String; port: Word; CanAdd: Boolean; var nodeServerAddress: TNodeServerAddress): Boolean;
Var i : Integer;
P : PNodeServerAddress;
begin
FCritical.Acquire;
Try
if SecuredFindByIp(ip,port,i) then begin
P := FListByIp.Items[i];
nodeServerAddress := P^;
Result := True;
end else if CanAdd then begin
New(P);
P^ := CT_TNodeServerAddress_NUL;
P^.ip := ip;
P^.port := port;
FListByIp.Insert(i,P);
nodeServerAddress := P^;
Result := True
end else begin
nodeServerAddress := CT_TNodeServerAddress_NUL;
Result := False;
end;
Finally
FCritical.Release;
End;
end;
procedure TOrderedServerAddressListTS.GetNodeServersToConnnect(maxNodes: Integer; useArray : Boolean; var nsa: TNodeServerAddressArray);
Procedure sw(l : TList<Pointer>);
Var i,j,x,y : Integer;
begin
if l.Count<=1 then exit;
j := Random(l.Count)*3;
for i := 0 to j do begin
x := Random(l.Count);
y := Random(l.Count);
if x<>y then l.Exchange(x,y);
end;
end;
Function IsValid(Const ns : TNodeServerAddress) : Boolean;
Begin
Result := (Not Assigned(ns.netConnection)) AND (Not IsBlackListed(ns.ip)) AND (Not ns.its_myself) And
((ns.last_attempt_to_connect=0) Or ((ns.last_attempt_to_connect+EncodeTime(0,3,0,0)<now))) And
((ns.total_failed_attemps_to_connect<3) Or (ns.last_attempt_to_connect+EncodeTime(0,10,0,0)<now));
End;
Var i,j, iStart : Integer;
P : PNodeServerAddress;
l : TList<Pointer>;
ns : TNodeServerAddress;
begin
FCritical.Acquire;
Try
l := TList<Pointer>.Create;
Try
if useArray then begin
for i := 0 to High(nsa) do begin
If GetNodeServerAddress(nsa[i].ip,nsa[i].port,true,ns) then begin
if IsValid(ns) then begin
new(P);
P^ := ns;
l.Add(P);
end;
end;
end;
SetLength(nsa,0);
end else begin
SetLength(nsa,0);
if FListByIp.Count>0 then begin
iStart := Random(FListByIp.Count);
i := iStart;
j := FListByIp.Count;
while (l.Count<maxNodes) And (i<j) do begin
P := FListByIp[i];
If (Not Assigned(P.netConnection)) AND (Not IsBlackListed(P^.ip)) AND (Not P^.its_myself) And
((P^.last_attempt_to_connect=0) Or ((P^.last_attempt_to_connect+EncodeTime(0,3,0,0)<now))) And
((P^.total_failed_attemps_to_connect<3) Or (P^.last_attempt_to_connect+EncodeTime(0,10,0,0)<now)) then begin
l.Add(P);
end;
// Second round
inc(i);
if (i>=j) and (iStart>0) then begin
j := iStart;
iStart := 0;
i := 0;
end;
end;
end;
end;
if (l.Count>0) then begin
sw(l);
if l.Count<maxNodes then setLength(nsa,l.Count)
else setLength(nsa,maxNodes);
for i := 0 to high(nsa) do begin
nsa[i] := PNodeServerAddress(l[i])^;
end;
end;
Finally
if useArray then begin
for i := 0 to l.Count - 1 do begin
P := l[i];
Dispose(P);
end;
end;
l.Free;
End;
Finally
FCritical.Release;
end;
end;
function TOrderedServerAddressListTS.GetValidNodeServers(OnlyWhereIConnected: Boolean; Max: Integer): TNodeServerAddressArray;
var i,j,iStart : Integer;
nsa : TNodeServerAddress;
currunixtimestamp : Cardinal;
begin
SetLength(Result,0);
currunixtimestamp := UnivDateTimeToUnix(DateTime2UnivDateTime(now));
CleanNodeServersList;
// Save other node servers
FCritical.Acquire;
try
If Max>0 then iStart := Random(FListByIp.Count)
else iStart := 0;
i := iStart;
j := FListByIp.Count;
while ((length(Result)<Max) Or (Max<=0)) And (i<j) do begin
nsa := PNodeServerAddress( FListByIp[i] )^;
if (Not IsBlackListed(nsa.ip))
And
( // I've connected 1h before
((nsa.last_connection>0) And ((Assigned(nsa.netConnection)) Or ((nsa.last_connection + (CT_LAST_CONNECTION_MAX_MINUTES)) > (currunixtimestamp))))
Or // Others have connected 3h before
((nsa.last_connection_by_server>0) And ((nsa.last_connection_by_server + (CT_LAST_CONNECTION_BY_SERVER_MAX_MINUTES)) > (currunixtimestamp)))
Or // Peer cache
((nsa.last_connection=0) And (nsa.last_connection_by_server=0))
)
And
( // Never tried to connect or successfully connected
(nsa.total_failed_attemps_to_connect=0)
)
And
( (Not nsa.its_myself) Or (nsa.port=CT_NetServer_Port) )
And
(
(Not OnlyWhereIConnected)
Or
(nsa.last_connection>0)
)
then begin
SetLength(Result,length(Result)+1);
Result[high(Result)] := nsa;
end;
// Second round
inc(i);
if (i>=j) and (iStart>0) then begin
j := iStart;
iStart := 0;
i := 0;
end;
end;
finally
FCritical.Release;
end;
end;
function TOrderedServerAddressListTS.IsBlackListed(const ip: String; out AReason : string): Boolean;
Var i : Integer;
P : PNodeServerAddress;
begin
Result := false;
AReason := '';
FCritical.Acquire;
Try
SecuredFindByIp(ip,0,i);
// Position will be the first by IP:
while (i<FListByIp.Count) And (Not Result) do begin
P := PNodeServerAddress(FListByIp[i]);
if Not SameStr(P^.ip,ip) then exit;
if P^.is_blacklisted then begin
Result := Not P^.its_myself;
AReason := P^.BlackListText;
end;
inc(i);
end;
Finally
FCritical.Release;
End;
end;
function TOrderedServerAddressListTS.IsBlackListed(const ip: String): Boolean;
var LReason : String;
begin
Result := IsBlackListed(ip,LReason);
end;
function TOrderedServerAddressListTS.LockList: TList<Pointer>;
begin
FCritical.Acquire;
Result := FListByIp;
end;
procedure TOrderedServerAddressListTS.ResetConnectAttempts;
Var P : PNodeServerAddress;
i : Integer;
begin
CleanNodeServersList;
FCritical.Acquire;
Try
for i := FListByIp.Count - 1 downto 0 do begin
P := FListByIp[i];
P^.last_connection := 0;
P^.last_connection_by_server := 0;
P^.last_connection_by_me := 0;
P^.last_attempt_to_connect := 0;
end;
Finally
FCritical.Release;
End;
end;
procedure TOrderedServerAddressListTS.SecuredDeleteFromListByIp(index: Integer);
Var P : PNodeServerAddress;
i2 : Integer;
begin
P := FListByIp.Items[index];
if (Assigned(P^.netConnection)) then begin
If SecuredFindByNetConnection(P^.netConnection,i2) then begin
FListByNetConnection.Delete(i2);
end else TLog.NewLog(ltError,ClassName,'DEV ERROR 20180201-1 NetConnection not found!');
end;
Dispose(P);
FListByIp.Delete(index);
dec(FNetData.FNetStatistics.NodeServersListCount);
inc(FNetData.FNetStatistics.NodeServersDeleted);
end;
function TOrderedServerAddressListTS.SecuredFindByIp(const ip: String; port: Word; var Index: Integer): Boolean;
var L, H, I, C: Integer;
PN : PNodeServerAddress;
begin
Result := False;
L := 0;
H := FListByIp.Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
PN := FListByIp.Items[I];
C := CompareStr( PN.ip, ip );
If (C=0) then begin
C := PN.port-port;
end;
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
L := I;
end;
end;
end;
Index := L;
end;
function TOrderedServerAddressListTS.SecuredFindByNetConnection(const search: TNetConnection; var Index: Integer): Boolean;
var L, H, I: Integer;
PN : PNodeServerAddress;
C : PtrInt;
begin
Result := False;
L := 0;
H := FListByNetConnection.Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
PN := FListByNetConnection.Items[I];
C := PtrInt(PN.netConnection) - PtrInt(search);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
L := I;
end;
end;
end;
Index := L;
end;
procedure TOrderedServerAddressListTS.SetNodeServerAddress(
const nodeServerAddress: TNodeServerAddress);
Var i : Integer;
P : PNodeServerAddress;
begin
FCritical.Acquire;
Try
if SecuredFindByIp(nodeServerAddress.ip,nodeServerAddress.port,i) then begin
P := FListByIp.Items[i];
if (P^.netConnection<>nodeServerAddress.netConnection) then begin
// Updated netConnection
if Assigned(P^.netConnection) then begin
// Delete old value
if Not DeleteNetConnection(P^.netConnection) then TLog.NewLog(lterror,Classname,Format('DEV ERROR 20180205-1 %s %d',[nodeServerAddress.ip,nodeServerAddress.port]));
end;
end;
P^ := nodeServerAddress;
end else begin
New(P);
P^ := nodeServerAddress;
FListByIp.Insert(i,P);
Inc(FNetData.FNetStatistics.NodeServersListCount);
TLog.NewLog(ltdebug,Classname,'Adding new server: '+NodeServerAddress.ip+':'+Inttostr(NodeServerAddress.port));
end;
if Assigned(nodeServerAddress.netConnection) then begin
If Not SecuredFindByNetConnection(nodeServerAddress.netConnection,i) then begin
FListByNetConnection.Insert(i,P);
end;
end;
Finally
FCritical.Release;
end;
end;
procedure TOrderedServerAddressListTS.UnlockList;
begin
FCritical.Release;
end;
procedure TOrderedServerAddressListTS.UpdateNetConnection(netConnection: TNetConnection);
Var i : Integer;
begin
FCritical.Acquire;
Try
If SecuredFindByNetConnection(netConnection,i) then begin
PNodeServerAddress(FListByNetConnection[i])^.last_connection := (UnivDateTimeToUnix(DateTime2UnivDateTime(now)));
PNodeServerAddress(FListByNetConnection[i])^.total_failed_attemps_to_connect := 0;
end;
Finally
FCritical.Release;