-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathUUserInterface.pas
More file actions
1302 lines (1143 loc) · 42.7 KB
/
UUserInterface.pas
File metadata and controls
1302 lines (1143 loc) · 42.7 KB
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 UUserInterface;
{ Copyright (c) 2018 by Herman Schoenfeld
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
Acknowledgements:
- Albert Molina: portions of code copied from https://github.com/PascalCoin/PascalCoin/blob/Releases/2.1.6/Units/Forms/UFRMWallet.pas
THIS LICENSE HEADER MUST NOT BE REMOVED.
}
{$mode delphi}
interface
{$I ..\config.inc}
uses
SysUtils, Classes, Forms, Controls, {$IFDEF WINDOWS}Windows,{$ENDIF} ExtCtrls,
Dialogs, LCLType,
UCommon, UCommon.UI,
UBlockChain, UAccounts, UNode, UWallet, UConst, UFolderHelper, UGridUtils, URPC, UPoolMining,
ULog, UThread, UNetProtocol, UCrypto, UBaseTypes, UPCDataTypes,
UFRMMainForm, UCTRLSyncronization, UFRMAccountExplorer, UFRMOperationExplorer, UFRMPendingOperations, UFRMOperation,
UFRMLogs, UFRMMessages, UFRMNodes, UFRMBlockExplorer, UFRMWalletKeys, UPCOrderedLists {$IFDEF TESTNET},UFRMRandomOperations, UAccountKeyStorage{$ENDIF};
type
{ TUserInterfaceState }
TUserInterfaceState = (uisLoading, uisLoaded, uisDiscoveringPeers, uisSyncronizingBlockchain, uisActive, uisIsolated, uisDisconnected, uisError);
{ TUserInterface }
TUserInterface = class
private type
{ TLoadingThread }
TLoadingThread = Class(TPCThread)
private
FLastTC : TTickCount;
FMessage : String;
FCurPos : Int64;
FTotalCount : Int64;
procedure OnProgressNotify(sender : TObject; const message : String; curPos, totalCount : Int64);
procedure ThreadSafeNotify;
procedure ThreadSafeNotifyLoaded;
protected
procedure BCExecute; override;
End;
private
// Root-form
FUILock : TPCCriticalSection; static;
// Subforms
FAccountExplorer : TFRMAccountExplorer; static;
FPendingOperationForm : TFRMPendingOperations; static;
FOperationsExplorerForm : TFRMOperationExplorer; static;
FBlockExplorerForm : TFRMBlockExplorer; static;
FLogsForm : TFRMLogs; static;
FNodesForm : TFRMNodes; static;
FMessagesForm : TFRMMessages; static;
// Components
FRPCServer : TRPCServer; static;
FPoolMiningServer : TPoolMiningServer; static;
// Local fields
FStarted : boolean; static;
FMainForm : TFRMMainForm; static;
FIsActivated : Boolean; static;
FUpdating : Boolean; static;
FLog : TLog; static;
FNode : TNode; static;
FTimerUpdateStatus: TTimer; static;
FTrayIcon: TTrayIcon; static;
FNodeNotifyEvents : TNodeNotifyEvents; static;
FStatusBar0Text : AnsiString; static;
FStatusBar1Text : AnsiString; static;
FStatusBar2Text : AnsiString; static;
FMessagesNotificationText : AnsiString; static;
FDisplayedStartupSyncDialog : boolean; static;
FAppStarted : TNotifyManyEvent; static;
FLoading : TProgressNotifyMany; static;
FLoaded : TNotifyManyEvent; static;
FStateChanged : TNotifyManyEvent; static;
FAccountsChanged : TNotifyManyEvent; static;
FBlocksChanged : TNotifyManyEvent; static;
FReceivedHelloMessage : TNotifyManyEvent; static;
FNodeMessageEvent : TNodeMessageManyEvent; static;
FNetStatisticsChanged : TNotifyManyEvent; static;
FNetConnectionsUpdated : TNotifyManyEvent; static;
FNetNodeServersUpdated : TNotifyManyEvent; static;
FNetBlackListUpdated : TNotifyManyEvent; static;
FMiningServerNewBlockFound : TNotifyManyEvent; static;
FUIRefreshTimer : TNotifyManyEvent; static;
FState : TUserInterfaceState; static;
FStateText : String; static;
FLoadingThread : TThread; static;
// Getters/Setters
class function GetEnabled : boolean; static;
class procedure SetEnabled(ABool: boolean); static;
class procedure SetState(AState : TUserInterfaceState); static;
// Handlers
class procedure OnSettingsChanged(Sender: TObject);
class procedure OnLoaded(Sender: TObject);
class procedure OnUITimerRefresh(Sender: TObject);
class procedure OnReceivedHelloMessage(Sender: TObject);
class procedure OnMiningServerNewBlockFound(Sender: TObject);
class procedure OnSubFormDestroyed(Sender: TObject);
class procedure OnTrayIconDblClick(Sender: TObject);
// Aux
class procedure NotifyLoadedEvent(Sender: TObject);
class procedure NotifyLoadingEvent(Sender: TObject; const message : String; curPos, totalCount : Int64);
class procedure NotifyStateChanged(Sender: TObject);
class procedure NotifyAccountsChangedEvent(Sender: TObject);
class procedure NotifyBlocksChangedEvent(Sender: TObject);
class procedure NotifyReceivedHelloMessageEvent(Sender: TObject);
class procedure NotifyNodeMessageEventEvent(NetConnection: TNetConnection; MessageData: String);
class procedure NotifyNetStatisticsChangedEvent(Sender: TObject);
class procedure NotifyNetConnectionsUpdatedEvent(Sender: TObject);
class procedure NotifyNetNodeServersUpdatedEvent(Sender: TObject);
class procedure NotifyNetBlackListUpdatedEvent(Sender: TObject);
class procedure NotifyMiningServerNewBlockFoundEvent(Sender: TObject);
class procedure NotifyUIRefreshTimerEvent(Sender: TObject);
public
// Properties
class property Enabled : boolean read GetEnabled write SetEnabled;
class property Started : boolean read FStarted;
class property State : TUserInterfaceState read FState write SetState;
class property StateText : string read FStateText;
class property Node : TNode read FNode;
class property Log : TLog read FLog;
class property PoolMiningServer : TPoolMiningServer read FPoolMiningServer;
// Events
class property AppStarted : TNotifyManyEvent read FAppStarted;
class property Loading : TProgressNotifyMany read FLoading;
class property Loaded : TNotifyManyEvent read FLoaded;
class property StateChanged : TNotifyManyEvent read FStateChanged;
class property AccountsChanged : TNotifyManyEvent read FAccountsChanged;
class property BlocksChanged : TNotifyManyEvent read FBlocksChanged;
class property ReceivedHelloMessage : TNotifyManyEvent read FReceivedHelloMessage;
class property NodeMessageEvent : TNodeMessageManyEvent read FNodeMessageEvent;
class property NetStatisticsChanged : TNotifyManyEvent read FNetStatisticsChanged;
class property NetConnectionsUpdated : TNotifyManyEvent read FNetConnectionsUpdated;
class property NetNodeServersUpdated : TNotifyManyEvent read FNetNodeServersUpdated;
class property NetBlackListUpdated : TNotifyManyEvent read FNetBlackListUpdated;
class property MiningServerNewBlockFound : TNotifyManyEvent read FMiningServerNewBlockFound;
class property UIRefreshTimer : TNotifyManyEvent read FUIRefreshTimer;
// Methods
class procedure StartApplication(mainForm : TForm);
class procedure ExitApplication;
class procedure RunInBackground;
class procedure RunInForeground;
class procedure CheckNodeIsReady;
{$IFDEF TESTNET}
{$IFDEF TESTING_NO_POW_CHECK}
class procedure CreateABlock;
{$ENDIF}
{$ENDIF}
// Show Dialogs
class procedure ShowSendDialog(const AAccounts : array of Cardinal);
class procedure ShowChangeKeyDialog(const AAccounts : array of Cardinal);
class procedure ShowSellAccountsDialog(const AAccounts : array of Cardinal);
class procedure ShowDelistAccountsDialog(const AAccounts : array of Cardinal);
class procedure ShowChangeAccountInfoDialog(const AAccounts : array of Cardinal);
class procedure ShowBuyAccountDialog(const AAccounts : array of Cardinal);
class procedure ShowAboutBox(parentForm : TForm);
class procedure ShowOptionsDialog(parentForm: TForm);
class procedure ShowAccountInfoDialog(parentForm: TForm; const account : Cardinal); overload;
class procedure ShowAccountInfoDialog(parentForm: TForm; const account : TAccount); overload;
class procedure ShowOperationInfoDialog(parentForm: TForm; const ophash : AnsiString); overload;
class procedure ShowOperationInfoDialog(parentForm: TForm; const operation : TOperationResume); overload;
class procedure ShowAccountOperationInfoDialog(parentForm: TForm; const account : TAccount; const operation : TOperationResume); overload;
class procedure ShowNewOperationDialog(parentForm : TForm; accounts : TOrderedCardinalList; defaultFee : Cardinal);
class procedure ShowSeedNodesDialog(parentForm : TForm);
class procedure ShowPrivateKeysDialog(parentForm: TForm);
class procedure ShowMemoText(parentForm: TForm; const ATitle : AnsiString; text : utf8string); overload;
class procedure ShowMemoText(parentForm: TForm; const ATitle : AnsiString; text : TStrings); overload;
class procedure UnlockWallet(parentForm: TForm);
class procedure ChangeWalletPassword(parentForm: TForm);
{$IFDEF TESTNET}
class procedure ShowPublicKeysDialog(parentForm: TForm);
class procedure ShowRandomOperationsDialog(parentForm: TForm);
{$ENDIF}
class procedure ShowInfo(parentForm : TForm; const ACaption, APrompt : String);
class procedure ShowWarning(parentForm : TForm; const ACaption, APrompt : String);
class procedure ShowError(parentForm : TForm; const ACaption, APrompt : String);
class function AskQuestion(parentForm: TForm; AType:TMsgDlgType; const ACaption, APrompt : String; buttons: TMsgDlgButtons) : TMsgDlgBtn;
class function AskEnterString(parentForm: TForm; const ACaption, APrompt : String; var Value : String) : Boolean;
class function AskEnterProtectedString(parentForm: TForm; const ACaption, APrompt : String; var Value : String) : Boolean;
// Show sub-forms
class procedure ShowAccountExplorer;
class procedure ShowBlockExplorer;
class procedure ShowOperationsExplorer;
class procedure ShowPendingOperations;
class procedure ShowMessagesForm;
class procedure ShowNodesForm;
class procedure ShowLogsForm;
class procedure ShowWallet;
class procedure ShowSyncDialog;
end;
{ Exceptions }
EUserInterface = class(Exception);
implementation
uses
Generics.Collections, UFRMAbout, UFRMNodesIp, UFRMPascalCoinWalletConfig, UFRMPayloadDecoder, UFRMMemoText,
UFileStorage, UTime, USettings, UCoreUtils, UMemory,
UWIZOperation, UWIZSendPASC, UWIZChangeKey, UWIZEnlistAccountForSale, UWIZDelistAccountFromSale, UWIZChangeAccountInfo, UWIZBuyAccount, UCoreObjects;
{ TUserInterface.TLoadingThread }
procedure TUserInterface.TLoadingThread.OnProgressNotify(sender: TObject; const message: String; curPos, totalCount: Int64);
var pct : String;
begin
If TPlatform.GetElapsedMilliseconds(FLastTC)>250 then begin
FLastTC := TPlatform.GetTickCount;
FMessage := Message;
FCurPos := curPos;
FTotalCount := totalCount;
Queue(ThreadSafeNotify);
end;
end;
procedure TUserInterface.TLoadingThread.ThreadSafeNotify;
begin
TUserInterface.NotifyLoadingEvent(Self, FMessage, FCurPos, FTotalCount);
end;
procedure TUserInterface.TLoadingThread.ThreadSafeNotifyLoaded;
begin
TUserInterface.State := uisLoaded;
end;
procedure TUserInterface.TLoadingThread.BCExecute;
Var currentProcess : String;
begin
FLastTC := 0;
FMessage := '';
FCurPos := 0;
FTotalCount:=0;
// Read Operations saved from disk
TNode.Node.InitSafeboxAndOperations($FFFFFFFF,OnProgressNotify); // New Build 2.1.4 to load pending operations buffer
TNode.Node.AutoDiscoverNodes(CT_Discover_IPs);
TNode.Node.NetServer.Active := true;
FLastTC := 0;
FMessage := '';
FCurPos := 0;
FTotalCount:=0;
if (TNode.Node.Bank.BlocksCount<=1) then begin
while (Not Terminated) And (Not TNode.Node.IsReady(currentProcess) Or (TNode.Node.Bank.BlocksCount<=1)) do begin
Queue( ThreadSafeNotify );
Sleep(200);
end;
end;
if Not Terminated then begin
Queue(ThreadSafeNotifyLoaded);
end;
TUserInterface.FLoadingThread := nil;
end;
{%region UI Lifecyle}
class procedure TUserInterface.StartApplication(mainForm : TForm);
Var ips : AnsiString;
nsarr : TNodeServerAddressArray;
begin
inherited;
if FIsActivated then exit;
FIsActivated := true;
try
// Initialize crypto module
TCrypto.InitCrypto;
// Create UI lock
FUILock := TPCCriticalSection.Create('TUserInterface.UILock');
// Initialise field defaults
FIsActivated := false;
FStarted := false;
FRPCServer := Nil;
FNode := Nil;
FPoolMiningServer := Nil;
FNodeNotifyEvents := nil;
FUpdating := false;
FStatusBar0Text := '';
FStatusBar1Text := '';
FStatusBar2Text := '';
FMessagesNotificationText := '';
// Create root form and dependent components
FMainForm := mainForm as TFRMMainForm;
FMainForm.CloseAction := caNone; // wallet is destroyed on ExitApplication
if (FMainForm = nil)
then raise Exception.Create('Main form is not TWallet');
FTrayIcon := TTrayIcon.Create(FMainForm);
FTrayIcon.OnDblClick := OnTrayIconDblClick;
{$IFNDEF LCLCarbon}
FTrayIcon.Visible := true;
{$ENDIF}
FTrayIcon.Hint := FMainForm.Caption;
FTrayIcon.BalloonTitle := 'Restoring the window.';
FTrayIcon.BalloonHint := 'Double click the system tray icon to restore Pascal Coin';
FTrayIcon.BalloonFlags := bfInfo;
{$IFNDEF LCLCarbon}
FTrayIcon.Show;
{$ENDIF}
FDisplayedStartupSyncDialog:=false;
// Create the UI refresh timer
FTimerUpdateStatus := TTimer.Create(FMainForm);
FTimerUpdateStatus.Enabled := false;
FTimerUpdateStatus.OnTimer := NotifyUIRefreshTimerEvent;
FUIRefreshTimer.Add(OnUITimerRefresh);
// Create log
FLog := TLog.Create(nil); // independent component
// FLog.OnNewLog:= OnNewLog;
FLog.SaveTypes := [];
// Create data directories
If Not ForceDirectories(TNode.GetPascalCoinDataFolder) then
raise Exception.Create('Cannot create dir: '+TNode.GetPascalCoinDataFolder);
// Load settings
TSettings.Load;
TSettings.OnChanged.Add(OnSettingsChanged);
// Open Wallet
TWallet.Load;
// Load peer list
ips := TSettings.TryConnectOnlyWithThisFixedServers;
TNode.DecodeIpStringToNodeServerAddressArray(ips,nsarr);
TNetData.NetData.DiscoverFixedServersOnly(nsarr);
setlength(nsarr,0);
// Start Node
FNode := TNode.Node;
FNode.NetServer.Port := TSettings.InternetServerPort;
FNode.PeerCache := TSettings.PeerCache+';'+CT_Discover_IPs;
FReceivedHelloMessage.Add(OnReceivedHelloMessage);
// Subscribe to Node events (TODO refactor with FNotifyEvents)
FNodeNotifyEvents := TNodeNotifyEvents.Create(FMainForm);
FNodeNotifyEvents.OnBlocksChanged := NotifyBlocksChangedEvent;
FNodeNotifyEvents.OnNodeMessageEvent := NotifyNodeMessageEventEvent;
// Start RPC server
FRPCServer := TRPCServer.Create;
FRPCServer.WalletKeys := TWallet.Keys;
FRPCServer.Active := TSettings.JsonRpcPortEnabled;
FRPCServer.ValidIPs := TSettings.JsonRpcAllowedIPs;
TWallet.Keys.SafeBox := FNode.Bank.SafeBox;
// Initialise Database
FNode.Bank.StorageClass := TFileStorage;
TFileStorage(FNode.Bank.Storage).DatabaseFolder := TNode.GetPascalCoinDataFolder+PathDelim+'Data';
TFileStorage(FNode.Bank.Storage).Initialize;
// Reading database
State := uisLoading;
FLoaded.Add(OnLoaded);
FLoadingThread := TLoadingThread.Create(true);
FLoadingThread.FreeOnTerminate := true;
FLoadingThread.Suspended := False;
// Init
TNetData.NetData.OnReceivedHelloMessage := NotifyReceivedHelloMessageEvent;
TNetData.NetData.OnStatisticsChanged := NotifyNetStatisticsChangedEvent;
TNetData.NetData.OnNetConnectionsUpdated := NotifyNetConnectionsUpdatedEvent;
TNetData.NetData.OnNodeServersUpdated := NotifyNetNodeServersUpdatedEvent;
TNetData.NetData.OnBlackListUpdated := NotifyNetBlackListUpdatedEvent;
// open the sync dialog
FStarted := true;
FAppStarted.Invoke(nil);
Except
On E:Exception do begin
E.Message := 'An error occurred during initialization. Application cannot continue:'+#10+#10+E.Message+#10+#10+'Application will close...';
Application.MessageBox(PChar(E.Message),PChar(Application.Title),MB_ICONERROR+MB_OK);
Halt;
end;
end;
// Notify accounts changed
NotifyAccountsChangedEvent(FMainForm);
// Show sync dialog
ShowSyncDialog;
// Final loading sequence
TSettings.RunCount := TSettings.RunCount + 1;
if TSettings.RunCount = 1 then begin
ShowAboutBox(nil);
end;
TSettings.Save;
end;
class procedure TUserInterface.ExitApplication;
var
i : Integer;
step : String;
begin
// Exit application
TLog.NewLog(ltinfo,Classname,'Quit Application - START');
Try
step := 'Deregistering events';
TSettings.OnChanged.Remove(OnSettingsChanged);
FUIRefreshTimer.Remove(OnUITimerRefresh);
FReceivedHelloMessage.Remove(OnReceivedHelloMessage);
FLoaded.Remove(OnLoaded);
FUIRefreshTimer.Remove(OnUITimerRefresh);
step := 'Saving Settings';
TSettings.Save;
// Destroys root form, non-modal forms and all their attached components
step := 'Destroying UI graph';
FMainForm.Destroy;
FMainForm := nil; // destroyed by FWallet
FAccountExplorer := nil; // destroyed by FWallet
FPendingOperationForm := nil; // destroyed by FWallet
FOperationsExplorerForm := nil; // destroyed by FWallet
FBlockExplorerForm := nil; // destroyed by FWallet
FLogsForm := nil; // destroyed by FWallet
FNodesForm := nil; // destroyed by FWallet
FMessagesForm := nil; // destroyed by FWallet
FTrayIcon := nil; // destroyed by FWallet
FNodeNotifyEvents := nil; // destroyed by FWallet
step := 'Destroying components';
FreeAndNil(FRPCServer);
FreeAndNil(FPoolMiningServer);
step := 'Assigning nil events';
FLog.OnNewLog :=Nil;
TNetData.NetData.OnReceivedHelloMessage := Nil;
TNetData.NetData.OnStatisticsChanged := Nil;
TNetData.NetData.OnNetConnectionsUpdated := Nil;
TNetData.NetData.OnNodeServersUpdated := Nil;
TNetData.NetData.OnBlackListUpdated := Nil;
step := 'Assigning Nil to TNetData';
TNetData.NetData.OnReceivedHelloMessage := Nil;
TNetData.NetData.OnStatisticsChanged := Nil;
step := 'Desactivating Node';
TNode.Node.NetServer.Active := false;
FNode := Nil;
// Destroy NetData
TNetData.NetData.Free;
step := 'Processing messages 1';
Application.ProcessMessages;
step := 'Destroying Node';
TNode.Node.Free;
step := 'Processing messages 2';
Application.ProcessMessages;
FreeAndNil(FUILock);
Except
On E:Exception do begin
TLog.NewLog(lterror,Classname,'Error quiting application step: '+step+' Errors ('+E.ClassName+'): ' +E.Message);
end;
End;
TLog.NewLog(ltinfo,Classname,'Error quiting application - END');
FreeAndNil(FLog);
Application.Terminate;
end;
class procedure TUserInterface.RunInBackground;
begin
FMainForm.Hide();
FMainForm.WindowState := wsMinimized;
FTimerUpdateStatus.Enabled := false;
FTrayIcon.Visible := True;
FTrayIcon.ShowBalloonHint;
end;
class procedure TUserInterface.RunInForeground;
begin
FTrayIcon.Visible := False;
FTimerUpdateStatus.Enabled := true;
FMainForm.Show();
FMainForm.WindowState := wsNormal;
Application.BringToFront();
end;
{%endregion}
{%region UI Handlers }
class procedure TUserInterface.OnTrayIconDblClick(Sender: TObject);
begin
RunInForeground;
end;
class procedure TUserInterface.OnSubFormDestroyed(Sender: TObject);
begin
FUILock.Acquire;
try
if Sender = FAccountExplorer then
FAccountExplorer := nil // form free's on close
else if Sender = FPendingOperationForm then
FPendingOperationForm := nil // form free's on close
else if Sender = FOperationsExplorerForm then
FOperationsExplorerForm := nil // form free's on close
else if Sender = FBlockExplorerForm then
FBlockExplorerForm := nil // form free's on close
else if Sender = FLogsForm then
FLogsForm := nil // form free's on close
else if Sender = FNodesForm then
FNodesForm := nil // form free's on close
else if Sender = FMessagesForm then
FMessagesForm := nil
else
raise Exception.Create('Internal Error: [NotifySubFormDestroyed] encountered an unknown sub-form instance');
finally
FUILock.Release;
end;
end;
class procedure TUserInterface.OnLoaded(Sender: TObject);
var LLockedMempool : TPCOperationsComp;
begin
// Start timer
FTimerUpdateStatus.Interval := 1000;
FTimerUpdateStatus.Enabled := true;
FPoolMiningServer := TPoolMiningServer.Create;
FPoolMiningServer.Port := TSettings.MinerServerRpcPort;
FPoolMiningServer.MinerAccountKey := TWallet.MiningKey;
FPoolMiningServer.MinerPayload := TEncoding.ANSI.GetBytes(TSettings.MinerName);
LLockedMempool := FNode.LockMempoolWrite;
try
LLockedMempool.AccountKey := TWallet.MiningKey;
finally
FNode.UnlockMempoolWrite;
end;
FPoolMiningServer.Active := TSettings.MinerServerRpcActive;
FPoolMiningServer.OnMiningServerNewBlockFound := NotifyMiningServerNewBlockFoundEvent;
State := uisLoaded;
ShowWallet;
end;
class procedure TUserInterface.OnUITimerRefresh(Sender: TObject);
var
LActive, LDiscoveringPeers, LGettingNewBlockchain, LRemoteHasBiggerBlock, LNoConnections : boolean;
LState : TUserInterfaceState;
LLocalTip, LRemoteTip : Cardinal;
LMsg : AnsiString;
begin
LState := FState;
LActive := FNode.NetServer.Active;
LDiscoveringPeers := TNetData.NetData.IsDiscoveringServers;
LGettingNewBlockchain := TNetData.NetData.IsGettingNewBlockChainFromClient(LMsg);
LLocalTip := Node.Bank.BlocksCount;
LRemoteTip := TNetData.NetData.MaxRemoteOperationBlock.block;
LRemoteHasBiggerBlock := LRemoteTip > LLocalTip;
LNoConnections := TNetData.NetData.NetStatistics.ActiveConnections = 0;
if LActive then begin
if LDiscoveringPeers then
LState := uisDiscoveringPeers;
if LGettingNewBlockchain OR LRemoteHasBiggerBlock then
LState := uisSyncronizingBlockchain;
if LNoConnections then
LState := uisIsolated;
if (NOT LDiscoveringPeers) AND (NOT LGettingNewBlockchain) AND (NOT LRemoteHasBiggerBlock) AND (NOT LNoConnections) then
LState := uisActive;
end else LState := uisDisconnected;
State := LState;
end;
class procedure TUserInterface.OnSettingsChanged(Sender: TObject);
var
wa : Boolean;
i : Integer;
LLockedMempool : TPCOperationsComp;
begin
if TSettings.SaveLogFiles then begin
if TSettings.SaveDebugLogs then
FLog.SaveTypes := CT_TLogTypes_ALL
else
FLog.SaveTypes := CT_TLogTypes_DEFAULT;
FLog.FileName := TNode.GetPascalCoinDataFolder+PathDelim+'PascalCointWallet.log';
end else begin
FLog.SaveTypes := [];
FLog.FileName := '';
end;
if Assigned(FNode) then begin
wa := FNode.NetServer.Active;
FNode.NetServer.Port := TSettings.InternetServerPort;
FNode.NetServer.Active := wa;
LLockedMempool := FNode.LockMempoolWrite;
try
LLockedMempool.BlockPayload := TEncoding.ANSI.GetBytes(TSettings.MinerName);
finally
FNode.UnlockMempoolWrite;
end;
FNode.NodeLogFilename := TNode.GetPascalCoinDataFolder+PathDelim+'blocks.log';
end;
if Assigned(FPoolMiningServer) then begin
if FPoolMiningServer.Port <> TSettings.MinerServerRpcPort then begin
FPoolMiningServer.Active := false;
FPoolMiningServer.Port := TSettings.MinerServerRpcPort;
end;
FPoolMiningServer.Active :=TSettings.MinerServerRpcActive;
FPoolMiningServer.UpdateAccountAndPayload(TWallet.MiningKey, TEncoding.ANSI.GetBytes(TSettings.MinerName));
end;
if Assigned(FRPCServer) then begin
FRPCServer.Active := TSettings.RpcPortEnabled;
FRPCServer.ValidIPs := TSettings.RpcAllowedIPs;
end;
end;
class procedure TUserInterface.OnReceivedHelloMessage(Sender: TObject);
Var nsarr : TNodeServerAddressArray;
i : Integer;
s : AnsiString;
begin
// Internal handler
// No lock required
//CheckMining;
// Update node servers Peer Cache
nsarr := TNetData.NetData.NodeServersAddresses.GetValidNodeServers(true,0);
s := '';
for i := low(nsarr) to High(nsarr) do begin
if (s<>'') then s := s+';';
s := s + nsarr[i].ip+':'+IntToStr( nsarr[i].port );
end;
TSettings.PeerCache := s;
end;
class procedure TUserInterface.OnMiningServerNewBlockFound(Sender: TObject);
begin
FPoolMiningServer.MinerAccountKey := TWallet.MiningKey;
end;
{%endregion}
{%region Show Dialogs}
class procedure TUserInterface.ShowSendDialog(const AAccounts : array of Cardinal);
var
Scoped: TDisposables;
wiz: TWIZSendPASCWizard;
model: TWIZOperationsModel;
begin
wiz := Scoped.AddObject(TWIZSendPASCWizard.Create(nil)) as TWIZSendPASCWizard;
model := TWIZOperationsModel.Create(wiz, omtSendPasc);
model.Account.SelectedAccounts := TNode.Node.GetAccounts(AAccounts, True);
model.Account.Count := Length(model.Account.SelectedAccounts);
wiz.Start(model);
end;
class procedure TUserInterface.ShowChangeKeyDialog(const AAccounts : array of Cardinal);
var
Scoped: TDisposables;
wiz: TWIZChangeKeyWizard;
model: TWIZOperationsModel;
begin
wiz := Scoped.AddObject(TWIZChangeKeyWizard.Create(nil)) as TWIZChangeKeyWizard;
model := TWIZOperationsModel.Create(wiz, omtChangeKey);
model.Account.SelectedAccounts := TNode.Node.GetAccounts(AAccounts, True);
model.Account.Count := Length(model.Account.SelectedAccounts);
wiz.Start(model);
end;
class procedure TUserInterface.ShowSellAccountsDialog(const AAccounts : array of Cardinal);
var
Scoped: TDisposables;
wiz: TWIZEnlistAccountForSaleWizard;
model: TWIZOperationsModel;
begin
wiz := Scoped.AddObject(TWIZEnlistAccountForSaleWizard.Create(nil)) as TWIZEnlistAccountForSaleWizard;
model := TWIZOperationsModel.Create(wiz, omtEnlistAccountForSale);
model.Account.SelectedAccounts := TNode.Node.GetAccounts(AAccounts, True);
model.Account.Count := Length(model.Account.SelectedAccounts);
wiz.Start(model);
end;
class procedure TUserInterface.ShowDelistAccountsDialog(const AAccounts : array of Cardinal);
var
Scoped: TDisposables;
wiz: TWIZDelistAccountFromSaleWizard;
model: TWIZOperationsModel;
begin
wiz := Scoped.AddObject(TWIZDelistAccountFromSaleWizard.Create(nil)) as TWIZDelistAccountFromSaleWizard;
model := TWIZOperationsModel.Create(wiz, omtDelistAccountFromSale);
model.Account.SelectedAccounts := TNode.Node.GetAccounts(AAccounts, True);
model.Account.Count := Length(model.Account.SelectedAccounts);
wiz.Start(model);
end;
class procedure TUserInterface.ShowChangeAccountInfoDialog(
const AAccounts: array of Cardinal);
var
Scoped: TDisposables;
wiz: TWIZChangeAccountInfoWizard;
model: TWIZOperationsModel;
begin
wiz := Scoped.AddObject(TWIZChangeAccountInfoWizard.Create(nil)) as TWIZChangeAccountInfoWizard;
model := TWIZOperationsModel.Create(wiz, omtChangeInfo);
model.Account.SelectedAccounts := TNode.Node.GetAccounts(AAccounts, True);
model.Account.Count := Length(model.Account.SelectedAccounts);
wiz.Start(model);
end;
class procedure TUserInterface.ShowBuyAccountDialog(
const AAccounts: array of Cardinal);
var
Scoped: TDisposables;
wiz: TWIZBuyAccountWizard;
model: TWIZOperationsModel;
begin
wiz := Scoped.AddObject(TWIZBuyAccountWizard.Create(nil)) as TWIZBuyAccountWizard;
model := TWIZOperationsModel.Create(wiz, omtBuyAccount);
model.Account.SelectedAccounts := TNode.Node.GetAccounts(AAccounts, True);
model.Account.Count := Length(model.Account.SelectedAccounts);
wiz.Start(model);
end;
class procedure TUserInterface.ShowAboutBox(parentForm : TForm);
begin
with TFRMAbout.Create(parentForm) do
try
ShowModal;
finally
Free;
end;
end;
class procedure TUserInterface.ShowOptionsDialog(parentForm: TForm);
begin
With TFRMPascalCoinWalletConfig.Create(parentForm) do
try
ShowModal
finally
Free;
end;
end;
class procedure TUserInterface.ShowOperationInfoDialog(parentForm: TForm; const ophash: AnsiString);
begin
with TFRMPayloadDecoder.Create(parentForm) do
try
Init(CT_TOperationResume_NUL);
if ophash <> '' then
DoFind(ophash);
Position := poMainFormCenter;
ShowModal;
finally
Free;
end;
end;
class procedure TUserInterface.ShowOperationInfoDialog(parentForm: TForm; const operation : TOperationResume); overload;
begin
with TFRMPayloadDecoder.Create(parentForm) do
try
Init(operation);
Position := poMainFormCenter;
ShowModal;
finally
Free;
end;
end;
class procedure TUserInterface.ShowAccountInfoDialog(parentForm: TForm; const account: Cardinal);
begin
if account >= TUserInterface.Node.Bank.AccountsCount then
raise EUserInterface.Create('Account not found');
ShowAccountInfoDialog(parentForm, TUserInterface.Node.GetAccount(account));
end;
class procedure TUserInterface.ShowAccountInfoDialog(parentForm: TForm; const account : TAccount); overload;
begin
ShowMemoText(parentForm, Format('Account: %s', [account.GetAccountString]), account.GetInfoText(Self.Node.Bank));
end;
class procedure TUserInterface.ShowAccountOperationInfoDialog(parentForm: TForm; const account: TAccount; const operation : TOperationResume);
var text : utf8string;
begin
text := account.GetInfoText(Self.Node.Bank) + sLineBreak + sLineBreak + operation.GetInfoText(Self.Node.Bank);
ShowMemoText(parentForm, Format('Account/Operation: %s/%s', [account.GetAccountString, operation.GetPrintableOPHASH]), text);
end;
// TODO - refactor with accounts as ARRAY
class procedure TUserInterface.ShowNewOperationDialog(parentForm : TForm; accounts : TOrderedCardinalList; defaultFee : Cardinal);
begin
If accounts.Count = 0 then raise Exception.Create('No sender accounts provided');
CheckNodeIsReady;
With TFRMOperation.Create(parentForm) do
Try
SenderAccounts.CopyFrom(accounts);
DefaultFee := defaultFee;
WalletKeys := TWallet.Keys;
ShowModal;
Finally
Free;
End;
end;
class procedure TUserInterface.ShowSeedNodesDialog(parentForm : TForm);
Var FRM : TFRMNodesIp;
begin
FRM := TFRMNodesIp.Create(parentForm);
Try
FRM.ShowModal;
Finally
FRM.Free;
End;
end;
class procedure TUserInterface.ShowPrivateKeysDialog(parentForm: TForm);
Var FRM : TFRMWalletKeys;
begin
FRM := TFRMWalletKeys.Create(parentForm);
try
FRM.ShowModal;
finally
FRM.Free;
end;
end;
class procedure TUserInterface.ShowMemoText(parentForm: TForm; const ATitle : AnsiString; text : utf8string);
begin
with TFRMMemoText.Create(parentForm) do begin
try
Caption := ATitle;
Memo.Append(text);
Position := poMainFormCenter;
ShowModal;
finally
Free;
end;
end;
end;
class procedure TUserInterface.ShowMemoText(parentForm: TForm; const ATitle : AnsiString; text : TStrings);
begin
with TFRMMemoText.Create(parentForm) do begin
try
Caption := ATitle;
Memo.Lines.Assign(text);
Position := poMainFormCenter;
ShowModal;
finally
Free;
end;
end;
end;
class procedure TUserInterface.ChangeWalletPassword(parentForm: TForm);
var
pwd1,pwd2 : String;
locked : boolean;
begin
pwd1 := ''; pwd2 := '';
locked := (NOT TWallet.Keys.HasPassword) OR (NOT TWallet.Keys.IsValidPassword);
if Not AskEnterProtectedString(parentForm, 'Change password','Enter new password',pwd1)
then exit;
if trim(pwd1)<>pwd1 then
raise Exception.Create('Password cannot start or end with a space character');
if Not AskEnterProtectedString(parentForm, 'Change password', 'Enter new password again',pwd2)
then exit;
if pwd1<>pwd2 then
raise Exception.Create('Two passwords are different!');
TWallet.Keys.WalletPassword := pwd1;
if locked then
TWallet.Keys.LockWallet;
ShowWarning(parentform,
'Password Changed',
'Your password has been changed.' + #10+#10 +
'Please ensure you remember your password.'+#10+
'If you lose your password your accounts and funds will be lost forever.');
end;
{$IFDEF TESTNET}
class procedure TUserInterface.ShowRandomOperationsDialog(parentForm: TForm);
begin
with TFRMRandomOperations.Create(parentForm) do begin
try
SourceNode := TUserInterface.Node;
SourceWalletKeys := TWallet.Keys;
ShowModal;
finally
Free;
end;
end;
end;
class procedure TUserInterface.ShowPublicKeysDialog(parentForm: TForm);
var
sl : TStrings;
ak : TAccountKey;
i, nmin,nmax : Integer;
l : TList<Pointer>;
Pacsd : PAccountKeyStorageData;
acc : TAccount;
begin
sl := TStringList.Create;
try
for i:=0 to FNode.Bank.SafeBox.AccountsCount-1 do begin
acc := FNode.Bank.SafeBox.Account(i);
if acc.accountInfo.new_publicKey.EC_OpenSSL_NID<>0 then begin
sl.Add(Format('Account %d new public key %d %s',[acc.account,
acc.accountInfo.new_publicKey.EC_OpenSSL_NID,
TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(acc.accountInfo.new_publicKey))]));
end;
end;
l := TAccountKeyStorage.KS.LockList;
try
sl.Add(Format('%d public keys in TAccountKeyStorage data',[l.count]));
for i:=0 to l.count-1 do begin
Pacsd := l[i];
if (Pacsd^.counter<=0) then begin
sl.Add(Format('%d/%d public keys counter %d',[i+1,l.count,Pacsd^.counter]));
end;
if FNode.Bank.SafeBox.OrderedAccountKeysList.IndexOfAccountKey(Pacsd^.ptrAccountKey^)<0 then begin
sl.Add(Format('%d/%d public keys counter %d Type %d NOT FOUND %s',[i+1,l.count,Pacsd^.counter,
Pacsd^.ptrAccountKey^.EC_OpenSSL_NID,
TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(Pacsd^.ptrAccountKey^))]));
end;
end;
finally
TAccountKeyStorage.KS.UnlockList;
end;
sl.Add(Format('%d public keys in %d accounts',[FNode.Bank.SafeBox.OrderedAccountKeysList.Count,FNode.Bank.Safebox.AccountsCount]));
for i:=0 to FNode.Bank.SafeBox.OrderedAccountKeysList.Count-1 do begin
ak := FNode.Bank.SafeBox.OrderedAccountKeysList.AccountKey[i];
if ( FNode.Bank.SafeBox.OrderedAccountKeysList.AccountKeyList[i].Count > 0) then begin
nmin := FNode.Bank.SafeBox.OrderedAccountKeysList.AccountKeyList[i].Get(0);
nmax := FNode.Bank.SafeBox.OrderedAccountKeysList.AccountKeyList[i].Get( FNode.Bank.SafeBox.OrderedAccountKeysList.AccountKeyList[i].Count-1 );
end else begin
nmin := -1; nmax := -1;
end;
sl.Add(Format('%d/%d %d accounts (%d to %d) for key type %d %s',[
i+1,FNode.Bank.SafeBox.OrderedAccountKeysList.Count,
FNode.Bank.SafeBox.OrderedAccountKeysList.AccountKeyList[i].Count,
nmin,nmax,
ak.EC_OpenSSL_NID,
TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(ak)) ]));
end;
with TFRMMemoText.Create(parentForm) do begin
try
InitData('Keys in safebox',sl.Text);
ShowModal;
finally
Free;
end;
end;
finally
sl.Free;
end;
end;
{$IFDEF TESTING_NO_POW_CHECK}
class procedure TUserInterface.CreateABlock;
var
ops : TPCOperationsComp;
nba : TBlockAccount;
errors : AnsiString;