HOME 5 months ago
parent
commit
a334be153a

+ 2 - 3
.gitignore

@@ -4,9 +4,8 @@
 
 # Project-specific files
 
-PCC.DevClient/PCC-Config.json
-PCC.DevServer/PCC-Config.json
-PCC.Peer/PCC-Config.json
+PCC.DevClient/PCC-DEV-Config.json
+PCC.DevServer/PCC-DEV-Config.json
 
 # User-specific files
 *.suo

+ 78 - 51
PCC.DevClient/DevClientApp.cs

@@ -1,85 +1,112 @@
-using System.Security.Cryptography;
+using System.Text;
 using PCC.App.Security;
 using PCC.Common.AssemblyInject.Interfaces;
 using PCC.Common.EventBus;
 using PCC.App.Tpm;
+using PCC.DevShared.Configuration;
 
 namespace PCC.DevClient;
 
-internal class DevClientApp(DevClientPccConfigManager configManager, TrustedPeerManager tpm, IEventBus eventBus, ILogger<DevClientApp> logger) : IAssemblyInjectSyncInitStarStop
+internal class DevClientApp(
+    PccDevConfigManagerBase configManager,
+    IPeerInfoProvider peerInfoProvider,
+    TrustedPeerManager tpm,
+    IEventBus eventBus,
+    ILogger<DevClientApp> logger) : IAssemblyInjectSyncInitStarStop
 {
+    private ILocalPeerInfo? _local;
+    private IRemotePeerInfo? _remote;
+
+
     public void Init()
     {
         logger.LogInformation("init");
-        //eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_CX>(OnConnected);
-        //eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_RX>(OnRx);
-        //eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_DX>(OnDx);
-        //eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_XX>(OnXx);
+        eventBus.Subscript<TPM_EVT_LISTENER_STATUS_CHANGED>(OnListenerStatusChanged);
+        eventBus.Subscript<TPM_EVT_OUTBOUND_CON_STATUS_CHANGED>(OnOutboundStatusChanged);
+        eventBus.Subscript<TPM_EVT_OUTBOUND_CON_ERROR>(OnOutboundConnectionError);
+        eventBus.Subscript<TPM_EVT_OUTBOUND_RX>(OnOutboundRx);
+        eventBus.Subscript<TPM_EVT_OUTBOUND_TX>(OnOutboundTx);
+    }
+
+    private void OnListenerStatusChanged(TPM_EVT_LISTENER_STATUS_CHANGED obj)
+    {
+        logger.LogInformation($"Listener {obj.Status} {obj.Exception?.Message}");
+        if (obj.Status == TPM_EVT_LISTEN_STATUS.STARTED)
+        {
+            if (_remote != null)
+            {
+                tpm.ConnectToPeerAsync(_local.PeerId, _remote.PeerId);
+            }
+        }
+    }
+
+    private void OnOutboundStatusChanged(TPM_EVT_OUTBOUND_CON_STATUS_CHANGED obj)
+    {
+        switch (obj.Status)
+        {
+            case TPM_EVT_OUTBOUND_CON_STATUS.HANDSHAKE_OK:
+                logger.LogInformation($"OB ST {obj.Status} L{obj.LocalPeerId} R{obj.RemotePeerId}");
+                tpm.SendToPeer(_local.PeerId, _remote.PeerId, "Brrr汉字SendDddd"u8.ToArray());
+                break;
+            case TPM_EVT_OUTBOUND_CON_STATUS.CONNECTION_ATTEMPT:
+            case TPM_EVT_OUTBOUND_CON_STATUS.HANDSHAKE_ATTEMPT:
+            case TPM_EVT_OUTBOUND_CON_STATUS.DISCONNECTED:
+                logger.LogInformation($"OB ST {obj.Status} L{obj.LocalPeerId} R{obj.RemotePeerId}");
+                break;
+
+            default:
+            case TPM_EVT_OUTBOUND_CON_STATUS.INVALID:
+            case TPM_EVT_OUTBOUND_CON_STATUS.SECURE_WARN_TIMESTAMP_SKEW:
+                logger.LogWarning($"OB ST {obj.Status} L{obj.LocalPeerId} R{obj.RemotePeerId}");
+                break;
+
+            case TPM_EVT_OUTBOUND_CON_STATUS.HANDSHAKE_FAIL_ACK_NOT_MATCHED:
+            case TPM_EVT_OUTBOUND_CON_STATUS.SECURE_ALERT_REPLAY_ATTACK_DETECT:
+                logger.LogError($"OB ST {obj.Status} L{obj.LocalPeerId} R{obj.RemotePeerId}");
+                break;
+        }
+    }
+
+    private void OnOutboundTx(TPM_EVT_OUTBOUND_TX obj)
+    {
+        logger.LogInformation($"OB Tx L{obj.LocalPeerId} R{obj.RemotePeerId} {Encoding.UTF8.GetString(obj.payload.Span)}");
+    }
+
+    private void OnOutboundRx(TPM_EVT_OUTBOUND_RX obj)
+    {
+        logger.LogInformation($"OB Rx L{obj.LocalPeerId} R{obj.RemotePeerId} {Encoding.UTF8.GetString(obj.payload.Span)}");
+    }
+
+    private void OnOutboundConnectionError(TPM_EVT_OUTBOUND_CON_ERROR obj)
+    {
+        logger.LogError(obj.Exception, $"OB ERR L{obj.LocalPeerId} R{obj.RemotePeerId}");
     }
 
     public void Start()
     {
         logger.LogInformation("starting...");
 
-        byte[] myPri, myPub;
         if (configManager.Instance.MyKeyPrivate == null || configManager.Instance.MyKeyPublic == null)
         {
             logger.LogInformation("Generating 8192bit RSA key... be patient, may take up to 30 seconds...");
-            (myPub, myPri) = RsaUtility.GeneratePKCS1(8192);
+            var (myPub, myPri) = RsaUtility.GeneratePKCS1(8192);
             configManager.Instance.MyKeyPrivate = Convert.ToBase64String(myPri, Base64FormattingOptions.None);
             configManager.Instance.MyKeyPublic = Convert.ToBase64String(myPub, Base64FormattingOptions.None);
             configManager.Save();
-            logger.LogInformation("RSA key generated and saved.");
-        }
-        else
-        {
-            myPri = Convert.FromBase64String(configManager.Instance.MyKeyPrivate);
-            myPub = Convert.FromBase64String(configManager.Instance.MyKeyPublic);
+            logger.LogInformation("RSA key generated and saved. Please fill conf and RESTART.");
         }
 
-        //eventBus.Publish(new TrustedPeerManager.TPM_EVT_CMD_INIT(myPub, myPri));
-        //logger.LogInformation("Your public key for share to trusted peer: " + configManager.Instance.MyKeyPublic);
 
-        //if (configManager.Instance.TrustPeerKeyPub == null || configManager.Instance.TrustPeerHost == null || configManager.Instance.TrustPeerPort == null)
-        //{
-        //    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");
-        //    return;
-        //}
+        _local = peerInfoProvider.PeerInfo.FirstOrDefault();
+        if (_local != null)
+        {
+            _remote = _local.TrustedRemotePeers.FirstOrDefault();
 
-        //var tpk = Convert.FromBase64String(configManager.Instance.TrustPeerKeyPub);
-        //var tph = configManager.Instance.TrustPeerHost!;
-        //var tpp = configManager.Instance.TrustPeerPort!.Value;
+        }
 
-        //var peerId = tpm.AddPeer(tpk, tph, tpp);
-        //tpm.ConnectToPeerAsync(peerId);
     }
 
-    //private void OnConnected(TrustedPeerManager.TPM_EVT_PEER_CX obj)
-    //{
-    //    logger.LogInformation("Connected");
-    //    var payload = "Brr连上了?"u8.ToArray();
-    //    logger.LogInformation($"Send payload {Convert.ToHexString(SHA256.HashData(payload))}");
-    //    tpm.SendToPeer(obj.PeerId, payload);
-    //}
-
-    //private void OnRx(TrustedPeerManager.TPM_EVT_PEER_RX obj)
-    //{
-    //    logger.LogInformation("Rx:" + Convert.ToHexString(obj.payload.Span));
-    //}
-
-    //private void OnDx(TrustedPeerManager.TPM_EVT_PEER_DX obj)
-    //{
-    //    logger.LogInformation("Dx:" + obj.PeerId);
-    //}
-
-    //private void OnXx(TrustedPeerManager.TPM_EVT_PEER_XX obj)
-    //{
-    //    logger.LogWarning($"有内鬼,终止交易! {obj.Kind} {obj.PeerId}");
-    //}
-
     public void Stop()
     {
-        logger.LogInformation("stop");
-    //    eventBus.Publish<TrustedPeerManager.TPM_EVT_CMD_SHUTDOWN>();
     }
 }

+ 9 - 6
PCC.DevClient/DevClientAssemblyInjectImplement.cs

@@ -1,10 +1,13 @@
-using PCC.App.Configuration;
-using PCC.App.Tpm;
-using PCC.Common.AssemblyInject.Interfaces;
+using PCC.App.Tpm;
 using PCC.Common.EventBus;
+using PCC.Common.Networking;
+using PCC.DevShared;
+using PCC.DevShared.Configuration;
 
 namespace PCC.DevClient;
 
-internal class DevClientPccConfigManager : PccConfigManagerBase;
-internal class DevClientEventBus(ILogger<DevClientEventBus> logger) : InProcessEventBusBase(logger), IAssemblyInjectSingleton<IEventBus>;
-internal class DevClientTpm(IPeerInfoProvider provider, IEventBus eventBus, ILogger<DevClientTpm> tpm) : TrustedPeerManager(provider, eventBus, tpm), IAssemblyInjectSingleton<TrustedPeerManager>;
+internal class DevClientPccConfigManager : PccDevConfigManagerBase;
+internal class DevPeerInfoProvider(PccDevConfigManagerBase conf) : DevPeerInfoProviderBase(conf);
+
+internal class DevClientEventBus(ILogger<DevClientEventBus> logger) : InProcessEventBusBase(logger);
+internal class DevClientTpm(IPeerInfoProvider provider, IEventBus eventBus, ILogger<DevClientTpm> logger,ILogger<KestrelTcpServer> ktsLogger) : TrustedPeerManager(provider, eventBus, logger,ktsLogger);

+ 1 - 0
PCC.DevClient/PCC.DevClient.csproj

@@ -8,6 +8,7 @@
   </PropertyGroup>
 
   <ItemGroup>
+    <ProjectReference Include="..\PCC.DevShared\PCC.DevShared.csproj" />
     <ProjectReference Include="..\PCC.Shared\PCC.Shared.csproj" />
   </ItemGroup>
 

+ 67 - 69
PCC.DevServer/DevServerApp.cs

@@ -1,111 +1,109 @@
-using System.Net;
-using System.Security.Cryptography;
+using System.Security.Cryptography;
 using System.Text;
 using PCC.App.Security;
 using PCC.App.Tpm;
 using PCC.Common.AssemblyInject.Interfaces;
 using PCC.Common.EventBus;
-using PCC.Common.Networking;
+using PCC.DevShared.Configuration;
 
 namespace PCC.DevServer;
 
 internal class DevServerApp(
-    DevServerPccConfigManager configManager,
+    PccDevConfigManagerBase configManager,
+    IPeerInfoProvider peerInfoProvider,
     TrustedPeerManager tpm,
     IEventBus eventBus,
-    ILogger<DevServerApp> logger,
-    ILogger<KestrelTcpServer> ktsLogger) : IAssemblyInjectSyncInitStarStop
+    ILogger<DevServerApp> logger) : IAssemblyInjectSyncInitStarStop
 {
-    private KestrelTcpServer _tcpServer;
+    private ILocalPeerInfo? _local;
+    private IRemotePeerInfo? _remote;
 
     public void Init()
     {
         logger.LogInformation("init");
-        //eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_IX>(OnIncome);
-        //eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_RX>(OnRx);
-        //eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_DX>(OnDx);
-        //eventBus.Subscript<TrustedPeerManager.TPM_EVT_PEER_XX>(OnXx);
+
+        eventBus.Subscript<TPM_EVT_LISTENER_STATUS_CHANGED>(OnListenerStatusChanged);
+        eventBus.Subscript<TPM_EVT_INBOUND_CON_ACCEPTED>(OnInboundAccepted);
+        eventBus.Subscript<TPM_EVT_INBOUND_CON_STATUS_CHANGED>(OnInboundStatusChanged);
+        eventBus.Subscript<TPM_EVT_INBOUND_CON_ERROR>(OnInboundConnectionError);
+        eventBus.Subscript<TPM_EVT_INBOUND_RX>(OnInboundRx);
+        eventBus.Subscript<TPM_EVT_INBOUND_TX>(OnInboundTx);
     }
 
     public void Start()
     {
         logger.LogInformation("starting...");
 
-        byte[] myPri, myPub;
         if (configManager.Instance.MyKeyPrivate == null || configManager.Instance.MyKeyPublic == null)
         {
             logger.LogInformation("Generating 8192bit RSA key... be patient, may take up to 30 seconds...");
-            (myPub, myPri) = RsaUtility.GeneratePKCS1(8192);
+            var (myPub, myPri) = RsaUtility.GeneratePKCS1(8192);
             configManager.Instance.MyKeyPrivate = Convert.ToBase64String(myPri, Base64FormattingOptions.None);
             configManager.Instance.MyKeyPublic = Convert.ToBase64String(myPub, Base64FormattingOptions.None);
             configManager.Save();
-            logger.LogInformation("RSA key generated and saved.");
+            logger.LogInformation("RSA key generated and saved. Please fill conf and RESTART.");
         }
-        else
+
+
+        _local = peerInfoProvider.PeerInfo.FirstOrDefault();
+        if (_local != null)
         {
-            myPri = Convert.FromBase64String(configManager.Instance.MyKeyPrivate);
-            myPub = Convert.FromBase64String(configManager.Instance.MyKeyPublic);
+            _remote = _local.TrustedRemotePeers.FirstOrDefault();
+
         }
+    }
+
+    private void OnInboundTx(TPM_EVT_INBOUND_TX obj)
+    {
+        logger.LogInformation($"IB Tx L{obj.LocalPeerId} R{obj.RemotePeerId} {Encoding.UTF8.GetString(obj.payload.Span)}");
 
-        //eventBus.Publish(new TrustedPeerManager.TPM_EVT_CMD_INIT(myPub, myPri));
-
-        //logger.LogInformation("Your public key for share to trusted peer: " + configManager.Instance.MyKeyPublic);
-
-        //if (configManager.Instance.ListenPort == null || false == IPAddress.TryParse(configManager.Instance.ListenAddress, out _))
-        //{
-        //    logger.LogError($"Missing config `{nameof(configManager.Instance.ListenPort)}' or `{nameof(configManager.Instance.ListenAddress)}', HALT");
-        //    return;
-        //}
-
-        //if (configManager.Instance.TrustPeerKeyPub == null)
-        //{
-        //    logger.LogError($"Missing config `{nameof(configManager.Instance.TrustPeerKeyPub)}',  please obtain from trusted peer, HALT");
-        //    return;
-        //}
-
-        ////warn just example for server
-        //tpm.AddPeer(Convert.FromBase64String(configManager.Instance.TrustPeerKeyPub), "", 0);
-
-        //_tcpServer = new KestrelTcpServer(configManager.Instance.ListenAddress, configManager.Instance.ListenPort.Value, tpm.HandleIncomingPeerAsync, ktsLogger);
-        //Task.Run(async () =>
-        //{
-        //    try
-        //    {
-        //        await _tcpServer.StartAsync();
-        //    }
-        //    catch (Exception e)
-        //    {
-        //        logger.LogError(e, "Start TCP server");
-        //    }
-        //});
     }
 
-    //private void OnIncome(TrustedPeerManager.TPM_EVT_PEER_IX obj)
-    //{
-    //    logger.LogInformation("Income:" + obj.PeerId);
-    //}
+    private void OnInboundRx(TPM_EVT_INBOUND_RX obj)
+    {
+        logger.LogInformation($"IB Rx L{obj.LocalPeerId} R{obj.RemotePeerId} {Encoding.UTF8.GetString(obj.payload.Span)}");
 
-    //private void OnRx(TrustedPeerManager.TPM_EVT_PEER_RX obj)
-    //{
-    //    logger.LogInformation($"Rx from <{obj.PeerId}>");
-    //    logger.LogInformation($"Rx content: {Encoding.UTF8.GetString(obj.payload.Span)}");
-    //    tpm.SendToPeer(obj.PeerId, SHA256.HashData(obj.payload.Span));
-    //}
+        tpm.SendToPeer(_local.PeerId, obj.RemotePeerId, SHA256.HashData(obj.payload.Span));
+    }
 
-    //private void OnDx(TrustedPeerManager.TPM_EVT_PEER_DX obj)
-    //{
-    //    logger.LogInformation("Disconnected:" + obj.PeerId);
-    //}
+    private void OnInboundConnectionError(TPM_EVT_INBOUND_CON_ERROR obj)
+    {
+        logger.LogError(obj.Exception, $"IB ERR L{obj.LocalPeerId} R{obj.RemotePeerId} C{obj.ConnectionId}");
+    }
 
-    //private void OnXx(TrustedPeerManager.TPM_EVT_PEER_XX obj)
-    //{
-    //    logger.LogWarning($"有内鬼,终止交易! {obj.Kind} {obj.PeerId}");
-    //}
+    private void OnInboundStatusChanged(TPM_EVT_INBOUND_CON_STATUS_CHANGED obj)
+    {
+        switch (obj.Status)
+        {
+            case TPM_EVT_INBOUND_CON_STATUS.HANDSHAKE_FAIL_NOT_TRUSTED:
+            case TPM_EVT_INBOUND_CON_STATUS.SECURE_ALERT_REPLAY_ATTACK_DETECT:
+                logger.LogError($"IB ST {obj.Status} L{obj.LocalPeerId} R{obj.RemotePeerId} C{obj.ConnectionId}");
+                break;
+
+            default:
+            case TPM_EVT_INBOUND_CON_STATUS.INVALID:
+            case TPM_EVT_INBOUND_CON_STATUS.SECURE_WARN_TIMESTAMP_SKEW:
+                logger.LogWarning($"IB ST {obj.Status} L{obj.LocalPeerId} R{obj.RemotePeerId} C{obj.ConnectionId}");
+                break;
+
+            case TPM_EVT_INBOUND_CON_STATUS.HANDSHAKE_OK:
+            case TPM_EVT_INBOUND_CON_STATUS.DISCONNECTED:
+                logger.LogInformation($"IB ST {obj.Status} L{obj.LocalPeerId} R{obj.RemotePeerId} C{obj.ConnectionId}");
+                break;
+        }
+    }
+
+    private void OnInboundAccepted(TPM_EVT_INBOUND_CON_ACCEPTED obj)
+    {
+        logger.LogInformation($"Inbound accepted {obj.RemoteEndpoint} {obj.ConnectionId}");
+    }
+
+    private void OnListenerStatusChanged(TPM_EVT_LISTENER_STATUS_CHANGED obj)
+    {
+        logger.LogInformation($"Listener {obj.Status} {obj.Exception?.Message}");
+    }
 
     public void Stop()
     {
-    //    logger.LogInformation("stop");
-    //    _ = _tcpServer.StopAsync(); //FAF
-    //    eventBus.Publish(new TrustedPeerManager.TPM_EVT_CMD_SHUTDOWN());
     }
 }

+ 8 - 5
PCC.DevServer/DevServerAssemblyInjectImplement.cs

@@ -1,10 +1,13 @@
-using PCC.App.Configuration;
-using PCC.App.Tpm;
+using PCC.App.Tpm;
 using PCC.Common.AssemblyInject.Interfaces;
 using PCC.Common.EventBus;
+using PCC.Common.Networking;
+using PCC.DevShared;
+using PCC.DevShared.Configuration;
 
 namespace PCC.DevServer;
 
-internal class DevServerPccConfigManager : PccConfigManagerBase;
-internal class DevServerEventBus(ILogger<DevServerEventBus> logger) : InProcessEventBusBase(logger), IAssemblyInjectSingleton<IEventBus>;
-internal class DevServerTpm(IPeerInfoProvider provider, IEventBus eventBus, ILogger<DevServerTpm> tpm) : TrustedPeerManager(provider, eventBus, tpm), IAssemblyInjectSingleton<TrustedPeerManager>;
+internal class DevServerPccConfigManager : PccDevConfigManagerBase;
+internal class DevPeerInfoProvider(PccDevConfigManagerBase conf) : DevPeerInfoProviderBase(conf);
+internal class DevServerEventBus(ILogger<DevServerEventBus> logger) : InProcessEventBusBase(logger);
+internal class DevServerTpm(IPeerInfoProvider provider, IEventBus eventBus, ILogger<DevServerTpm> logger, ILogger<KestrelTcpServer> ktsLogger) : TrustedPeerManager(provider, eventBus, logger, ktsLogger);

+ 15 - 5
PCC.DevServer/DevServerProgram.cs

@@ -15,10 +15,20 @@ builder.Services.AddAssemblyInject<Program>();
 
 var host = builder.Build();
 
-await host.RunAsync();
-
+try
+{
+    await host.RunAsync();
+}
+catch (Exception e)
+{
+    Console.WriteLine(e);
+    throw;
+}
+finally
+{
 #if DEBUG
-Console.WriteLine();
-Console.Write("Finished, press ENTER to exit...");
-Console.ReadLine();
+    Console.WriteLine();
+    Console.Write("Finished, press ENTER to exit...");
+    Console.ReadLine();
 #endif
+}

+ 1 - 0
PCC.DevServer/PCC.DevServer.csproj

@@ -8,6 +8,7 @@
   </PropertyGroup>
 
   <ItemGroup>
+    <ProjectReference Include="..\PCC.DevShared\PCC.DevShared.csproj" />
     <ProjectReference Include="..\PCC.Shared\PCC.Shared.csproj" />
   </ItemGroup>
 

+ 2 - 2
PCC.Shared/App/Configuration/PccConfigFile.cs

@@ -1,6 +1,6 @@
-namespace PCC.App.Configuration;
+namespace PCC.DevShared.Configuration;
 
-public class PccConfigFile
+public class PccDevConfigFile
 {
     public string? MyKeyPrivate { get; set; }
     public string? MyKeyPublic { get; set; }

+ 5 - 5
PCC.Shared/App/Configuration/PccConfigManagerBase.cs

@@ -1,17 +1,17 @@
 using System.Text.Json;
 using PCC.Common.AssemblyInject.Interfaces;
 
-namespace PCC.App.Configuration;
+namespace PCC.DevShared.Configuration;
 
-public abstract class PccConfigManagerBase : IAssemblyInjectSyncInitStarStop
+public abstract class PccDevConfigManagerBase : IAssemblyInjectSyncInitStarStop<PccDevConfigManagerBase>
 {
-    private const string FileName = "PCC-Config.json";
-    public PccConfigFile Instance { get; private set; } = new();
+    private const string FileName = "PCC-DEV-Config.json";
+    public PccDevConfigFile Instance { get; private set; } = new();
 
     public void Load()
     {
         if (File.Exists(FileName))
-            Instance = JsonSerializer.Deserialize<PccConfigFile>(File.ReadAllText(FileName))!;
+            Instance = JsonSerializer.Deserialize<PccDevConfigFile>(File.ReadAllText(FileName))!;
     }
 
     public void Save() => File.WriteAllText(FileName, JsonSerializer.Serialize(Instance));

+ 64 - 0
PCC.DevShared/DevPeerInfoProviderBase.cs

@@ -0,0 +1,64 @@
+using PCC.App.Tpm;
+using PCC.Common.AssemblyInject.Interfaces;
+using PCC.DevShared.Configuration;
+
+namespace PCC.DevShared;
+
+public class DevPeerInfoProviderBase(PccDevConfigManagerBase config) : IPeerInfoProvider, IAssemblyInjectSyncInitStarStop<IPeerInfoProvider>
+{
+    private ICollection<ILocalPeerInfo>? _peerInfo;
+
+    public ICollection<ILocalPeerInfo>? PeerInfo
+    {
+        get
+        {
+            if(_peerInfo == null) Start();
+            return _peerInfo;
+        }   
+        private set => _peerInfo = value;
+    }
+
+
+    public void Init()
+    {
+
+    }
+
+    public void Start()
+    {
+        if (_peerInfo != null) return;
+
+        var conf = config.Instance;
+
+        var mPri = conf.MyKeyPrivate;
+        var mPub = conf.MyKeyPublic;
+        var mLisA = conf.ListenAddress;
+        var mLisP = conf.ListenPort;
+
+        var tPub = conf.TrustPeerKeyPub;
+        var tLisA = conf.TrustPeerHost;
+        var tLisP = conf.TrustPeerPort;
+
+        if (new object[] { mPri, mPub, mLisA, mLisP, tPub, tLisA, tLisP }.Any(p => p == null))
+        {
+            PeerInfo = [];
+            return;
+        }
+
+        var remote = new RemotePeerInfo(Convert.FromBase64String(tPub), tLisA, tLisP.Value);
+
+        var local = new LocalPeerInfo(
+            Convert.FromBase64String(mPub),
+            Convert.FromBase64String(mPri),
+            mLisA, mLisP.Value, [remote]
+
+        );
+
+        PeerInfo = [local];
+    }
+
+    public void Stop()
+    {
+
+    }
+}

+ 13 - 0
PCC.DevShared/PCC.DevShared.csproj

@@ -0,0 +1,13 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>net8.0</TargetFramework>
+    <ImplicitUsings>enable</ImplicitUsings>
+    <Nullable>enable</Nullable>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <ProjectReference Include="..\PCC.Shared\PCC.Shared.csproj" />
+  </ItemGroup>
+
+</Project>

+ 5 - 1
PCC.Shared/App/Security/TimestampNonceManager.cs

@@ -106,7 +106,11 @@ public class TimestampNonceManager : IDisposable
     private void CleanupTimerCallback(object? state)
     {
         var now = DateTime.UtcNow;
-        foreach (var item in _holds.Where(p => now - p.Value >= _expiration)) _holds.TryRemove(item.Key, out _);
+        foreach (var item in _holds.Where(p => now - p.Value >= _expiration))
+        {
+            //TODO: debug trace logging 
+            _holds.TryRemove(item.Key, out _);
+        }
     }
 
     private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);

+ 1 - 1
PCC.Shared/App/Tpm/Configs.cs

@@ -23,7 +23,7 @@ public interface ILocalPeerInfo
 public class LocalPeerInfo(byte[] publicKey, byte[] privateKey, string address, int port, ICollection<IRemotePeerInfo> remotePeers) : ILocalPeerInfo
 {
     //public RSA PublicKey { get; } = RsaUtility.FromPKCS1PublicKey(publicKey);
-    public RSA PrivateKey { get; } = RsaUtility.FromPKCS1PublicKey(privateKey);
+    public RSA PrivateKey { get; } = RsaUtility.FromPKCS1PrivateKey(privateKey);
 
     public string PeerId { get; } = Convert.ToHexString(SHA256.HashData(publicKey));
     public string Address { get; } = address;

+ 2 - 2
PCC.Shared/App/Tpm/Events.cs

@@ -2,9 +2,9 @@
 
 namespace PCC.App.Tpm;
 
-public record TPM_EVT_LISTENER_STATUS_CHANGED(string LocalPeerId, TPM_EVT_INBOUND_LISTEN_STATUS Status, Exception? Exception = null);
+public record TPM_EVT_LISTENER_STATUS_CHANGED(string LocalPeerId, TPM_EVT_LISTEN_STATUS Status, Exception? Exception = null);
 
-public enum TPM_EVT_INBOUND_LISTEN_STATUS
+public enum TPM_EVT_LISTEN_STATUS
 {
     INVALID = 0,
     STARTING,

+ 10 - 10
PCC.Shared/App/Tpm/LocalPeerManager.cs

@@ -25,14 +25,14 @@ internal class LocalPeerManager
     private readonly ConcurrentDictionary<string, EncryptedTcpPeer> _connectedInbound = new();
     private readonly ConcurrentDictionary<string, EncryptedTcpPeer> _connectedOutbound = new();
 
-    public LocalPeerManager(SocketConnectionContextFactory sckConnectionContextFactory, TimestampNonceManager nonceManager, ILocalPeerInfo localPeer, IEventBus eventBus, ILogger<TrustedPeerManager> logger)
+    public LocalPeerManager(SocketConnectionContextFactory sckConnectionContextFactory, TimestampNonceManager nonceManager, ILocalPeerInfo localPeer, IEventBus eventBus, ILogger<TrustedPeerManager> logger, ILogger<KestrelTcpServer> ktsLogger)
     {
         _sckConnectionContextFactory = sckConnectionContextFactory;
         _nonceManager = nonceManager;
         _localPeer = localPeer;
         _eventBus = eventBus;
 
-        _listener = new(localPeer.Address, localPeer.Port, HandleInboundConnection, (ILogger<KestrelTcpServer>)logger);
+        _listener = new(localPeer.Address, localPeer.Port, HandleInboundConnection, ktsLogger);
         _trustedRemotePeers = new(localPeer.TrustedRemotePeers.ToDictionary(p => p.PeerId));
     }
 
@@ -184,8 +184,6 @@ internal class LocalPeerManager
 
                         return;
                     }
-
-                    _eventBus.Publish(new TPM_EVT_OUTBOUND_CON_STATUS_CHANGED(TPM_EVT_OUTBOUND_CON_STATUS.HANDSHAKE_OK, _localPeer.PeerId, remotePeerId));
                 }
 
                 //replace exist connection
@@ -193,6 +191,8 @@ internal class LocalPeerManager
 
                 _connectedOutbound[remotePeerId] = epOutbound;
 
+                _eventBus.Publish(new TPM_EVT_OUTBOUND_CON_STATUS_CHANGED(TPM_EVT_OUTBOUND_CON_STATUS.HANDSHAKE_OK, _localPeer.PeerId, remotePeerId));
+
                 while (true) // start RxCycle
                 {
                     var rxb = await epOutbound.RxBlockAsync();
@@ -266,13 +266,13 @@ internal class LocalPeerManager
         {
             try
             {
-                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_INBOUND_LISTEN_STATUS.STARTING));
+                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_LISTEN_STATUS.STARTING));
                 await _listener.StartAsync();
-                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_INBOUND_LISTEN_STATUS.STARTED));
+                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_LISTEN_STATUS.STARTED));
             }
             catch (Exception ex)
             {
-                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_INBOUND_LISTEN_STATUS.START_FAIL, ex));
+                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_LISTEN_STATUS.START_FAIL, ex));
             }
         });
     }
@@ -283,13 +283,13 @@ internal class LocalPeerManager
         {
             try
             {
-                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_INBOUND_LISTEN_STATUS.STOPPING));
+                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_LISTEN_STATUS.STOPPING));
                 await _listener.StopAsync();
-                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_INBOUND_LISTEN_STATUS.STOPPED));
+                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_LISTEN_STATUS.STOPPED));
             }
             catch (Exception ex)
             {
-                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_INBOUND_LISTEN_STATUS.STOP_FAIL, ex));
+                _eventBus.Publish(new TPM_EVT_LISTENER_STATUS_CHANGED(_localPeer.PeerId, TPM_EVT_LISTEN_STATUS.STOP_FAIL, ex));
             }
         });
 

+ 7 - 4
PCC.Shared/App/Tpm/TrustedPeerManager.cs

@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets;
 using PCC.App.Security;
 using PCC.Common.AssemblyInject.Interfaces;
 using PCC.Common.EventBus;
+using PCC.Common.Networking;
 
 namespace PCC.App.Tpm;
 
@@ -15,7 +16,7 @@ namespace PCC.App.Tpm;
 
 // ACK: SHA256(incoming payload)
 
-public abstract class TrustedPeerManager(IPeerInfoProvider peerInfoProvider, IEventBus eventBus, ILogger<TrustedPeerManager> logger) : IAssemblyInjectSyncInitStarStop
+public abstract class TrustedPeerManager(IPeerInfoProvider peerInfoProvider, IEventBus eventBus, ILogger<TrustedPeerManager> logger, ILogger<KestrelTcpServer> ktsLogger) : IAssemblyInjectSyncInitStarStop<TrustedPeerManager>
 {
     private const int NONCE_LENGTH_BYTES = 16;
     private const int NONCE_EXPIRE_SECOND = 60;
@@ -28,7 +29,8 @@ public abstract class TrustedPeerManager(IPeerInfoProvider peerInfoProvider, IEv
     private TimestampNonceManager? _nonceManager;
 
     public void Init()
-    { }
+    {
+    }
 
     public void Start()
     {
@@ -36,7 +38,7 @@ public abstract class TrustedPeerManager(IPeerInfoProvider peerInfoProvider, IEv
 
         foreach (var item in peerInfoProvider.PeerInfo)
         {
-            _localPeers[item.PeerId] = new LocalPeerManager(_connectionContextFactory, _nonceManager, item, eventBus, logger);
+            _localPeers[item.PeerId] = new LocalPeerManager(_connectionContextFactory, _nonceManager, item, eventBus, logger, ktsLogger);
         }
 
         foreach (var item in _localPeers.Values) item.Start();
@@ -54,7 +56,8 @@ public abstract class TrustedPeerManager(IPeerInfoProvider peerInfoProvider, IEv
     public void AddOrReplaceLocalPeer(ILocalPeerInfo localPeerInfo)
     {
         RemoveLocalPeer(localPeerInfo.PeerId);
-        _localPeers[localPeerInfo.PeerId] = new LocalPeerManager(_connectionContextFactory, _nonceManager, localPeerInfo, eventBus, logger);
+        var newLocal = _localPeers[localPeerInfo.PeerId] = new LocalPeerManager(_connectionContextFactory, _nonceManager, localPeerInfo, eventBus, logger, ktsLogger);
+        Task.Run(newLocal.Start);
     }
 
     public bool AddOrReplaceRemotePeer(string localPeerId, IRemotePeerInfo remotePeerInfo)

+ 1 - 1
PCC.Shared/Common/AssemblyInject/Interfaces/IAssemblyInjectSyncInitStarStop.cs

@@ -7,7 +7,7 @@ public interface IAssemblyInjectSyncInitStarStop : IAssemblyInjectSingleton
     void Stop();
 }
 
-public interface AssemblyInjectSyncInitStarStop<T> : IAssemblyInjectSyncInitStarStop, IAssemblyInjectSingleton<T>
+public interface IAssemblyInjectSyncInitStarStop<T> : IAssemblyInjectSyncInitStarStop, IAssemblyInjectSingleton<T>
 {
 
 }

+ 24 - 10
PCC.Shared/Common/AssemblyInject/Services/AssemblyInjectSyncStartStopWorker.cs

@@ -15,14 +15,6 @@ internal class AssemblyInjectSyncStartStopWorker<T> : IHostedService
 
         _logger.LogInformation("Activating Singleton Component...");
 
-        _services = typeof(T).Assembly.GetTypes()
-            .Where(typeof(IAssemblyInjectSyncInitStarStop).IsAssignableFrom)
-            .Where(p => p.IsInterface == false && p.IsAbstract == false)
-            .OrderBy(p => p.Name)
-            .Select(serviceProvider.GetRequiredService)
-            .Cast<IAssemblyInjectSyncInitStarStop>()
-            .ToArray();
-
         //单例组件
         var serviceTypes = new HashSet<Type>();
         foreach (var svcType in typeof(T).Assembly.GetTypes()
@@ -34,7 +26,7 @@ internal class AssemblyInjectSyncStartStopWorker<T> : IHostedService
 
             foreach (var type in gsi)
             {
-                var addAs = type.GetGenericArguments().First()!;
+                var addAs = type.GetGenericArguments().First();
                 serviceTypes.Add(addAs);
             }
         }
@@ -61,6 +53,29 @@ internal class AssemblyInjectSyncStartStopWorker<T> : IHostedService
                 _logger.LogInformation($"Singleton Component Active {service.GetType().FullName}");
             }
         }
+
+        _services = typeof(T).Assembly.GetTypes()
+            .Where(typeof(IAssemblyInjectSyncInitStarStop).IsAssignableFrom)
+            .Where(p => p.IsInterface == false && p.IsAbstract == false)
+            .OrderBy(p => p.Name)
+            .SelectMany(p =>
+            {
+                var gsi = p.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssemblyInjectSyncInitStarStop<>)).ToArray();
+                return gsi.Length == 0 ? [p] : gsi.Select(gi => gi.GetGenericArguments().First());
+            })
+            .Distinct()
+            .Select(type => (type, serviceProvider.GetService(type)))
+            .Where(p =>
+            {
+                if (p.Item2 == null)
+                {
+                    logger.LogWarning($"Encounter null in IAssemblyInjectSyncInitStarStop: {p.type.FullName}");
+                    return false;
+                }
+                return true;
+            }).Select(p => p.Item2)
+            .Cast<IAssemblyInjectSyncInitStarStop>()
+            .ToArray();
     }
 
     public Task StartAsync(CancellationToken cancellationToken)
@@ -81,7 +96,6 @@ internal class AssemblyInjectSyncStartStopWorker<T> : IHostedService
             _logger.LogInformation($"All components initialized.");
         }
 
-
         _logger.LogInformation($"Starting...");
 
         if (_services.Count == 0)

+ 4 - 2
PCC.Shared/Common/EventBus/InProcessEventBusBase.cs

@@ -1,6 +1,8 @@
-namespace PCC.Common.EventBus;
+using PCC.Common.AssemblyInject.Interfaces;
 
-public abstract class InProcessEventBusBase(ILogger<InProcessEventBusBase> logger) : IEventBus
+namespace PCC.Common.EventBus;
+
+public abstract class InProcessEventBusBase(ILogger<InProcessEventBusBase> logger) : IEventBus, IAssemblyInjectSingleton<IEventBus>
 {
     private readonly Dictionary<Type, HashSet<Delegate>> _dicTypeToHandlers = [];
 

+ 7 - 0
PeerConnectiveChat.sln

@@ -29,6 +29,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "@", "@", "{EA0D1837-557F-4A
 		.gitignore = .gitignore
 	EndProjectSection
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PCC.DevShared", "PCC.DevShared\PCC.DevShared.csproj", "{CACDC336-1A1D-4AE6-9669-35FAAE83872B}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -55,6 +57,10 @@ Global
 		{9C41616A-2BAA-4121-B216-43434BAC037C}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{9C41616A-2BAA-4121-B216-43434BAC037C}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{9C41616A-2BAA-4121-B216-43434BAC037C}.Release|Any CPU.Build.0 = Release|Any CPU
+		{CACDC336-1A1D-4AE6-9669-35FAAE83872B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{CACDC336-1A1D-4AE6-9669-35FAAE83872B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{CACDC336-1A1D-4AE6-9669-35FAAE83872B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{CACDC336-1A1D-4AE6-9669-35FAAE83872B}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE
@@ -64,6 +70,7 @@ Global
 		{E2F41203-FA66-4189-BA95-4C2340AEA2D9} = {BB7D9471-11D4-43E1-A20E-950804067D86}
 		{A41020AF-E3C5-4996-ADA1-898638E01D7B} = {16F65C6D-F87B-4338-A018-95B51300836E}
 		{9C41616A-2BAA-4121-B216-43434BAC037C} = {358268D7-BA63-4BA7-8463-49BAA86247BA}
+		{CACDC336-1A1D-4AE6-9669-35FAAE83872B} = {BB7D9471-11D4-43E1-A20E-950804067D86}
 	EndGlobalSection
 	GlobalSection(ExtensibilityGlobals) = postSolution
 		SolutionGuid = {10125EDB-0DAC-4D7F-B20F-5562F6189CBD}