DevClientApp.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using PCC.App.Security;
  2. using PCC.Common.AssemblyInject.Interfaces;
  3. using PCC.Common.EventBus;
  4. using PCC.App;
  5. namespace PCC.DevClient;
  6. internal class DevClientApp(DevClientPccConfigManager configManager, TrustedPeerManager tpm, IEventBus eventBus, ILogger<DevClientApp> logger) : IAssemblyInjectSyncInitStarStop
  7. {
  8. public void Init()
  9. {
  10. logger.LogInformation("init");
  11. eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_CX>(OnConnected);
  12. eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_RX>(OnRx);
  13. }
  14. public void Start()
  15. {
  16. logger.LogInformation("starting...");
  17. byte[] myPri, myPub;
  18. if (configManager.Instance.MyKeyPrivate == null || configManager.Instance.MyKeyPublic == null)
  19. {
  20. logger.LogInformation("Generating 8192bit RSA key... be patient, may take up to 30 seconds...");
  21. (myPub, myPri) = RsaUtility.GeneratePKCS1(8192);
  22. configManager.Instance.MyKeyPrivate = Convert.ToBase64String(myPri, Base64FormattingOptions.None);
  23. configManager.Instance.MyKeyPublic = Convert.ToBase64String(myPub, Base64FormattingOptions.None);
  24. configManager.Save();
  25. logger.LogInformation("RSA key generated and saved.");
  26. }
  27. else
  28. {
  29. myPri = Convert.FromBase64String(configManager.Instance.MyKeyPrivate);
  30. myPub = Convert.FromBase64String(configManager.Instance.MyKeyPublic);
  31. }
  32. eventBus.Publish(new TrustedPeerManager.TPM_EVT_CMD_INIT(myPub, myPri));
  33. logger.LogInformation("Your public key for share to trusted peer: " + configManager.Instance.MyKeyPublic);
  34. if (configManager.Instance.TrustPeerKeyPub == null || configManager.Instance.TrustPeerHost == null || configManager.Instance.TrustPeerPort == null)
  35. {
  36. logger.LogError($"Missing config one of `{nameof(configManager.Instance.TrustPeerKeyPub)}' or `{nameof(configManager.Instance.TrustPeerHost)}' or `{nameof(configManager.Instance.TrustPeerPort)}', please obtain from trusted peer, HALT");
  37. return;
  38. }
  39. var tpk = Convert.FromBase64String(configManager.Instance.TrustPeerKeyPub);
  40. var tph = configManager.Instance.TrustPeerHost!;
  41. var tpp = configManager.Instance.TrustPeerPort!.Value;
  42. var peerId = tpm.AddTrustPeer(tpk, tph, tpp);
  43. tpm.ConnectToPeerAsync(peerId);
  44. }
  45. private void OnConnected(TrustedPeerManager.TPM_EVT_PEER_CX obj)
  46. {
  47. logger.LogInformation("Connected");
  48. tpm.SendToPeer(obj.PeerId, "Brr连上了?"u8.ToArray());
  49. }
  50. private void OnRx(TrustedPeerManager.TPM_EVT_PEER_RX obj)
  51. {
  52. logger.LogInformation("Rx:" + Convert.ToHexString(obj.block));
  53. }
  54. public void Stop()
  55. {
  56. logger.LogInformation("stop");
  57. eventBus.Publish<TrustedPeerManager.TPM_EVT_CMD_SHUTDOWN>();
  58. }
  59. }