/// <summary> /// Initializes an instance of a profile server simulator. /// </summary> /// <param name="Name">Name of the instance.</param> /// <param name="IpAddress">IP address on which this server will listen.</param> /// <param name="BasePort">Base port from which specific interface port numbers are calculated.</param> /// <param name="Keys">Cryptographic keys of this server instance, or null if they should be generated.</param> /// <param name="Location">Location of the profile server.</param> public ProfileServer(string Name, IPAddress IpAddress, int BasePort, KeysEd25519 Keys = null, GpsLocation Location = null) { log = NLog.LogManager.GetLogger("Test.ProfileServer." + Name); log.Trace("(IpAddress:'{0}',BasePort:{1})", IpAddress, BasePort); keys = Keys != null ? Keys : Ed25519.GenerateKeys(); location = Location != null ? Location : new GpsLocation(0, 0); name = Name; ipAddress = IpAddress; primaryPort = BasePort; serverNeighborPort = BasePort + 1; clientNonCustomerPort = BasePort + 2; primaryListener = new TcpListener(ipAddress, primaryPort); primaryListener.Server.LingerState = new LingerOption(true, 0); primaryListener.Server.NoDelay = true; serverNeighborListener = new TcpListener(ipAddress, serverNeighborPort); serverNeighborListener.Server.LingerState = new LingerOption(true, 0); serverNeighborListener.Server.NoDelay = true; clientNonCustomerListener = new TcpListener(ipAddress, clientNonCustomerPort); clientNonCustomerListener.Server.LingerState = new LingerOption(true, 0); clientNonCustomerListener.Server.NoDelay = true; tlsCertificate = new X509Certificate2("ps.pfx"); messageList = new List <IncomingServerMessage>(); log.Trace("(-)"); }
/// <summary> /// Creates a new identity client. /// </summary> /// <param name="Name">Identity name.</param> /// <param name="Type">Identity type.</param> /// <param name="Location">Initial GPS location.</param> /// <param name="ImageMask">File name mask in the images folder that define which images can be randomly selected for profile image.</param> /// <param name="ImageChance">An integer between 0 and 100 that specifies the chance of each instance to have a profile image set.</param> public IdentityClient(string Name, string Type, GpsLocation Location, string ImageMask, int ImageChance) { log = new Logger("NetworkSimulator.IdentityClient", "[" + Name + "] "); log.Trace("(Name:'{0}',Type:'{1}',Location:{2},ImageMask:'{3}',ImageChance:{4})", Name, Type, Location, ImageMask, ImageChance); name = Name; type = Type; location = Location; extraData = null; bool hasImage = Helpers.Rng.NextDouble() < (double)ImageChance / 100; if (hasImage) { imageFileName = GetImageFileByMask(ImageMask); profileImage = imageFileName != null?File.ReadAllBytes(imageFileName) : null; } version = SemVer.V100; keys = Ed25519.GenerateKeys(); identityId = Crypto.Sha256(keys.PublicKey); messageBuilder = new PsMessageBuilder(0, new List <SemVer>() { SemVer.V100 }, keys); profileInitialized = false; hostingActive = false; log.Trace("(-)"); }
public void Ed25519KeyPairs() { byte[] privateKey = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; KeysEd25519 keys = Ed25519.GenerateKeys(privateKey); Assert.Equal("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F9B62773323EF41A11834824194E55164D325EB9CDCC10DDDA7D10ADE4FBD8F6D", keys.ExpandedPrivateKeyHex); Assert.Equal("9B62773323EF41A11834824194E55164D325EB9CDCC10DDDA7D10ADE4FBD8F6D", keys.PublicKeyHex); }
/// <summary> /// Initializes the instance. /// </summary> /// <param name="IdBase">Base for message numbering.</param> /// <param name="ProtocolVersion">Protocol version in binary form.</param> /// <param name="Keys">Keys that represent the client's identity.</param> public ProtocolClient(uint IdBase, byte[] ProtocolVersion, KeysEd25519 Keys) { client = new TcpClient(); client.NoDelay = true; client.LingerState = new LingerOption(true, 0); keys = Keys; MessageBuilder = new MessageBuilder(IdBase, new List <byte[]>() { ProtocolVersion }, keys); }
public void Ed25519GenerateSignVerifyTest() { byte[] privateKey = Encoding.UTF8.GetBytes("12345678901234567890123456789012"); KeysEd25519 keys = Ed25519.GenerateKeys(privateKey); string message = "This is message"; byte[] signature = Ed25519.Sign(message, keys.ExpandedPrivateKey); string signatureString = signature.ToHex(); Assert.Equal("85F2D841785E01E1D7C87E6354E8FBF525227A1C3C10C5F58FEE1BDA6C126EE941FD84AE76188AD0FB2B5FBBDE839F9097E7D8AE79463F4B0A534E80C916C70D", signatureString); Assert.Equal(true, Ed25519.Verify(signature, message, keys.PublicKey)); Assert.Equal(false, Ed25519.Verify(signature, message + "x", keys.PublicKey)); }
/// <summary> /// Initializes the database, or loads database configuration if the database already exists. /// </summary> /// <returns>true if the function succeeds, false otherwise.</returns> public bool InitializeDbSettings() { log.Trace("()"); bool res = false; CanIpnsLastSequenceNumber = 0; CanProfileServerContactInformationChanged = false; using (UnitOfWork unitOfWork = new UnitOfWork()) { log.Trace("Loading database settings."); Setting initialized = unitOfWork.SettingsRepository.Get(s => s.Name == "Initialized").FirstOrDefault(); if ((initialized != null) && (!string.IsNullOrEmpty(initialized.Value)) && (initialized.Value == "true")) { Setting privateKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "PrivateKeyHex").FirstOrDefault(); Setting publicKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "PublicKeyHex").FirstOrDefault(); Setting expandedPrivateKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "ExpandedPrivateKeyHex").FirstOrDefault(); Setting networkInterface = unitOfWork.SettingsRepository.Get(s => s.Name == "NetworkInterface").FirstOrDefault(); Setting primaryPort = unitOfWork.SettingsRepository.Get(s => s.Name == "PrimaryPort").FirstOrDefault(); Setting canIpnsLastSequenceNumber = unitOfWork.SettingsRepository.Get(s => s.Name == "CanIpnsLastSequenceNumber").FirstOrDefault(); Setting canProfileServerContactInformationHash = unitOfWork.SettingsRepository.Get(s => s.Name == "CanProfileServerContactInformationHash").FirstOrDefault(); if ((privateKeyHex != null) && (!string.IsNullOrEmpty(privateKeyHex.Value)) && (publicKeyHex != null) && (!string.IsNullOrEmpty(publicKeyHex.Value)) && (expandedPrivateKeyHex != null) && (!string.IsNullOrEmpty(expandedPrivateKeyHex.Value)) && (primaryPort != null) && (networkInterface != null) && (!string.IsNullOrEmpty(networkInterface.Value)) && (canIpnsLastSequenceNumber != null) && (canProfileServerContactInformationHash != null) && (!string.IsNullOrEmpty(canProfileServerContactInformationHash.Value))) { Keys = new KeysEd25519(); Keys.PrivateKeyHex = privateKeyHex.Value; Keys.PrivateKey = Crypto.FromHex(Keys.PrivateKeyHex); Keys.PublicKeyHex = publicKeyHex.Value; Keys.PublicKey = Crypto.FromHex(Keys.PublicKeyHex); Keys.ExpandedPrivateKeyHex = expandedPrivateKeyHex.Value; Keys.ExpandedPrivateKey = Crypto.FromHex(Keys.ExpandedPrivateKeyHex); bool error = false; if (!UInt64.TryParse(canIpnsLastSequenceNumber.Value, out CanIpnsLastSequenceNumber)) { log.Error("Invalid CanIpnsLastSequenceNumber value '{0}' in the database.", canIpnsLastSequenceNumber.Value); error = true; } if (!error) { CanProfileServerContactInformationHash = Base58Encoding.Encoder.DecodeRaw(canProfileServerContactInformationHash.Value); if (CanProfileServerContactInformationHash == null) { log.Error("Invalid CanProfileServerContactInformationHash value '{0}' in the database.", canProfileServerContactInformationHash.Value); error = true; } } if (!error) { // Database settings contain information on previous network interface and primary port values. // If they are different to what was found in the configuration file, it means the contact // information of the profile server changed. Such a change must be propagated to profile server's // CAN records. string configNetworkInterface = ServerInterface.ToString(); if (configNetworkInterface != networkInterface.Value) { log.Info("Network interface address in configuration file is different from the database value."); CanProfileServerContactInformationChanged = true; } string configPrimaryPort = ServerRoles.GetRolePort(ServerRole.Primary).ToString(); if (configPrimaryPort != primaryPort.Value) { log.Info("Primary port in configuration file is different from the database value."); CanProfileServerContactInformationChanged = true; } } res = !error; } else { log.Error("Database settings are corrupted, DB has to be reinitialized."); } } if (!res) { log.Info("Database settings are not initialized, initializing now ..."); unitOfWork.SettingsRepository.Clear(); unitOfWork.Save(); Keys = Ed25519.GenerateKeys(); Setting privateKey = new Setting("PrivateKeyHex", Keys.PrivateKeyHex); unitOfWork.SettingsRepository.Insert(privateKey); Setting publicKey = new Setting("PublicKeyHex", Keys.PublicKeyHex); unitOfWork.SettingsRepository.Insert(publicKey); Setting expandedPrivateKey = new Setting("ExpandedPrivateKeyHex", Keys.ExpandedPrivateKeyHex); unitOfWork.SettingsRepository.Insert(expandedPrivateKey); Setting networkInterface = new Setting("NetworkInterface", ServerInterface.ToString()); unitOfWork.SettingsRepository.Insert(networkInterface); Setting primaryPort = new Setting("PrimaryPort", ServerRoles.GetRolePort(ServerRole.Primary).ToString()); unitOfWork.SettingsRepository.Insert(primaryPort); Setting canIpnsLastSequenceNumber = new Setting("CanIpnsLastSequenceNumber", "0"); unitOfWork.SettingsRepository.Insert(canIpnsLastSequenceNumber); initialized = new Setting("Initialized", "true"); unitOfWork.SettingsRepository.Insert(initialized); if (unitOfWork.Save()) { log.Info("Database initialized successfully."); CanProfileServerContactInformationChanged = true; res = true; } else { log.Error("Unable to save settings to DB."); } } } if (res) { log.Debug("Server public key hex is '{0}'.", Keys.PublicKeyHex); log.Debug("Server network ID is '{0}'.", Crypto.Sha256(Keys.PublicKey).ToHex()); log.Debug("Server network ID in CAN endoing is '{0}'.", Network.CAN.CanApi.PublicKeyToId(Keys.PublicKey).ToBase58()); log.Debug("Server primary interface is '{0}:{1}'.", ServerInterface, ServerRoles.GetRolePort(ServerRole.Primary)); } log.Trace("(-):{0}", res); return(res); }
/// <summary> /// Initializes the database, or loads database configuration if the database already exists. /// </summary> /// <returns>true if the function succeeds, false otherwise.</returns> public bool InitializeDbSettings() { log.Trace("()"); bool res = false; CanIpnsLastSequenceNumber = 0; CanProximityServerContactInformationChanged = false; using (UnitOfWork unitOfWork = new UnitOfWork()) { log.Trace("Loading database settings."); Setting initialized = unitOfWork.SettingsRepository.Get(s => s.Name == "Initialized").FirstOrDefault(); if ((initialized != null) && (!string.IsNullOrEmpty(initialized.Value)) && (initialized.Value == "true")) { Setting privateKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "PrivateKeyHex").FirstOrDefault(); Setting publicKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "PublicKeyHex").FirstOrDefault(); Setting expandedPrivateKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "ExpandedPrivateKeyHex").FirstOrDefault(); Setting externalServerAddress = unitOfWork.SettingsRepository.Get(s => s.Name == "ExternalServerAddress").FirstOrDefault(); Setting primaryPort = unitOfWork.SettingsRepository.Get(s => s.Name == "PrimaryPort").FirstOrDefault(); Setting canIpnsLastSequenceNumber = unitOfWork.SettingsRepository.Get(s => s.Name == "CanIpnsLastSequenceNumber").FirstOrDefault(); Setting canProximityServerContactInformationHash = unitOfWork.SettingsRepository.Get(s => s.Name == "CanProximityServerContactInformationHash").FirstOrDefault(); Setting locLocationLatitude = unitOfWork.SettingsRepository.Get(s => s.Name == "LocLocationLatitude").FirstOrDefault(); Setting locLocationLongitude = unitOfWork.SettingsRepository.Get(s => s.Name == "LocLocationLongitude").FirstOrDefault(); bool havePrivateKey = (privateKeyHex != null) && !string.IsNullOrEmpty(privateKeyHex.Value); bool havePublicKey = (publicKeyHex != null) && !string.IsNullOrEmpty(publicKeyHex.Value); bool haveExpandedPrivateKey = (expandedPrivateKeyHex != null) && !string.IsNullOrEmpty(expandedPrivateKeyHex.Value); bool havePrimaryPort = primaryPort != null; bool haveExternalServerAddress = (externalServerAddress != null) && !string.IsNullOrEmpty(externalServerAddress.Value); bool haveCanIpnsLastSequenceNumber = canIpnsLastSequenceNumber != null; bool haveCanContactInformationHash = (canProximityServerContactInformationHash != null) && !string.IsNullOrEmpty(canProximityServerContactInformationHash.Value); if (havePrivateKey && havePublicKey && haveExpandedPrivateKey && havePrimaryPort && haveExternalServerAddress && haveCanIpnsLastSequenceNumber) { Keys = new KeysEd25519(); Keys.PrivateKeyHex = privateKeyHex.Value; Keys.PrivateKey = Keys.PrivateKeyHex.FromHex(); Keys.PublicKeyHex = publicKeyHex.Value; Keys.PublicKey = Keys.PublicKeyHex.FromHex(); Keys.ExpandedPrivateKeyHex = expandedPrivateKeyHex.Value; Keys.ExpandedPrivateKey = Keys.ExpandedPrivateKeyHex.FromHex(); bool error = false; if (!UInt64.TryParse(canIpnsLastSequenceNumber.Value, out CanIpnsLastSequenceNumber)) { log.Error("Invalid CanIpnsLastSequenceNumber value '{0}' in the database.", canIpnsLastSequenceNumber.Value); error = true; } if (!error) { if (haveCanContactInformationHash) { CanProximityServerContactInformationHash = Base58Encoding.Encoder.DecodeRaw(canProximityServerContactInformationHash.Value); if (CanProximityServerContactInformationHash == null) { log.Error("Invalid CanProximityServerContactInformationHash value '{0}' in the database.", canProximityServerContactInformationHash.Value); error = true; } } else { CanProximityServerContactInformationChanged = true; } } if (!error) { // Database settings contain information on previous external network address and primary port values. // If they are different to what was found in the configuration file, it means the contact // information of the proximity server changed. Such a change must be propagated to proximity server's // CAN records. string configExternalServerAddress = ExternalServerAddress.ToString(); if (configExternalServerAddress != externalServerAddress.Value) { log.Info("Network interface address in configuration file is different from the database value."); CanProximityServerContactInformationChanged = true; } string configPrimaryPort = ServerRoles.GetRolePort((uint)ServerRole.Primary).ToString(); if (configPrimaryPort != primaryPort.Value) { log.Info("Primary port in configuration file is different from the database value."); CanProximityServerContactInformationChanged = true; } } if (!error) { if ((locLocationLatitude != null) && (locLocationLongitude != null)) { decimal lat; decimal lon; if (decimal.TryParse(locLocationLatitude.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out lat) && decimal.TryParse(locLocationLongitude.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out lon)) { LocLocation = new GpsLocation(lat, lon); log.Info("Server GPS location is [{0}].", LocLocation); } } } res = !error; } else { log.Error("Database settings are corrupted, DB has to be reinitialized."); if (!havePrivateKey) { log.Debug("Private key is missing."); } if (!havePublicKey) { log.Debug("Public key is missing."); } if (!haveExpandedPrivateKey) { log.Debug("Expanded private key is missing."); } if (!havePrimaryPort) { log.Debug("Primary port is missing."); } if (!haveExternalServerAddress) { log.Debug("External server address is missing."); } if (!haveCanIpnsLastSequenceNumber) { log.Debug("Last CAN IPNS sequence number is missing."); } if (!haveCanContactInformationHash) { log.Debug("CAN contact information hash is missing."); } } } if (!res) { log.Info("Database settings are not initialized, initializing now ..."); unitOfWork.SettingsRepository.Clear(); unitOfWork.Save(); Keys = Ed25519.GenerateKeys(); Setting privateKey = new Setting("PrivateKeyHex", Keys.PrivateKeyHex); unitOfWork.SettingsRepository.Insert(privateKey); Setting publicKey = new Setting("PublicKeyHex", Keys.PublicKeyHex); unitOfWork.SettingsRepository.Insert(publicKey); Setting expandedPrivateKey = new Setting("ExpandedPrivateKeyHex", Keys.ExpandedPrivateKeyHex); unitOfWork.SettingsRepository.Insert(expandedPrivateKey); Setting externalServerAddress = new Setting("ExternalServerAddress", ExternalServerAddress.ToString()); unitOfWork.SettingsRepository.Insert(externalServerAddress); Setting primaryPort = new Setting("PrimaryPort", ServerRoles.GetRolePort((uint)ServerRole.Primary).ToString()); unitOfWork.SettingsRepository.Insert(primaryPort); Setting canIpnsLastSequenceNumber = new Setting("CanIpnsLastSequenceNumber", "0"); unitOfWork.SettingsRepository.Insert(canIpnsLastSequenceNumber); initialized = new Setting("Initialized", "true"); unitOfWork.SettingsRepository.Insert(initialized); if (unitOfWork.Save()) { log.Info("Database initialized successfully."); CanProximityServerContactInformationChanged = true; res = true; } else { log.Error("Unable to save settings to DB."); } } } if (res) { Settings["Keys"] = Keys; Settings["CanIpnsLastSequenceNumber"] = CanIpnsLastSequenceNumber; Settings["CanProximityServerContactInformationHash"] = CanProximityServerContactInformationHash; Settings["CanProximityServerContactInformationChanged"] = CanProximityServerContactInformationChanged; log.Debug("Server public key hex is '{0}'.", Keys.PublicKeyHex); log.Debug("Server network ID is '{0}'.", Crypto.Sha256(Keys.PublicKey).ToHex()); log.Debug("Server network ID in CAN encoding is '{0}'.", CanApi.PublicKeyToId(Keys.PublicKey).ToBase58()); log.Debug("Server primary external contact is '{0}:{1}'.", ExternalServerAddress, ServerRoles.GetRolePort((uint)ServerRole.Primary)); } log.Trace("(-):{0}", res); return(res); }
/// <summary> /// Initializes the database, or loads database configuration if the database already exists. /// </summary> /// <returns>true if the function succeeds, false otherwise.</returns> public bool InitializeDbSettings() { log.Trace("()"); bool res = false; using (UnitOfWork unitOfWork = new UnitOfWork()) { log.Trace("Loading database settings."); Setting privateKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "PrivateKeyHex").FirstOrDefault(); Setting publicKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "PublicKeyHex").FirstOrDefault(); Setting expandedPrivateKeyHex = unitOfWork.SettingsRepository.Get(s => s.Name == "ExpandedPrivateKeyHex").FirstOrDefault(); if ((privateKeyHex != null) && (!string.IsNullOrEmpty(privateKeyHex.Value)) && (publicKeyHex != null) && (!string.IsNullOrEmpty(publicKeyHex.Value)) && (expandedPrivateKeyHex != null) && (!string.IsNullOrEmpty(expandedPrivateKeyHex.Value))) { Keys = new KeysEd25519(); Keys.PrivateKeyHex = privateKeyHex.Value; Keys.PrivateKey = Crypto.FromHex(Keys.PrivateKeyHex); Keys.PublicKeyHex = publicKeyHex.Value; Keys.PublicKey = Crypto.FromHex(Keys.PublicKeyHex); Keys.ExpandedPrivateKeyHex = expandedPrivateKeyHex.Value; Keys.ExpandedPrivateKey = Crypto.FromHex(Keys.ExpandedPrivateKeyHex); res = true; } else { log.Info("Database settings are not initialized, initializing now ..."); Keys = Ed25519.GenerateKeys(); Setting privateKey = new Setting("PrivateKeyHex", Keys.PrivateKeyHex); Setting publicKey = new Setting("PublicKeyHex", Keys.PublicKeyHex); Setting expandedPrivateKey = new Setting("ExpandedPrivateKeyHex", Keys.ExpandedPrivateKeyHex); unitOfWork.SettingsRepository.Insert(privateKey); unitOfWork.SettingsRepository.Insert(publicKey); unitOfWork.SettingsRepository.Insert(expandedPrivateKey); if (unitOfWork.Save()) { log.Info("Database initialized successfully."); res = true; } else { log.Error("Unable to save settings to DB."); } } } if (res) { log.Debug("Server public key hex is '{0}'.", Keys.PublicKeyHex); } log.Trace("(-):{0}", res); return(res); }