2using System.Collections.Generic;
4using System.Text.RegularExpressions;
5using System.Threading.Tasks;
27 internal static readonly Regex FromSaveUnsaved =
new Regex(
@"Waher[.]Persistence[.]Files[.]ObjectBTreeFile[.+]<SaveUnsaved>\w*[.]\w*",
28 RegexOptions.Compiled | RegexOptions.Singleline);
29 internal static readonly Regex FromUpdateObject =
new Regex(
@"Waher[.]Persistence[.]Files[.]ObjectBTreeFile[.+]<UpdateObject>\w*[.]\w*",
30 RegexOptions.Compiled | RegexOptions.Singleline);
31 internal static readonly Regex GatewayStartup =
new Regex(
@"Waher[.]IoTGateway[.]Gateway([.]Start|[.+]<Start>\w*[.]\w*)*",
32 RegexOptions.Compiled | RegexOptions.Singleline);
33 internal static readonly Regex LegalComponent =
new Regex(
@"Waher[.]Service[.]IoTBroker[.]Legal[.]LegalComponent[.](ApplyHandler|UpdateState|CreateContractHandler|SignContractHandler|ObsoleteContractHandler|DeleteContractHandler|UpdateContractHandler)",
34 RegexOptions.Compiled | RegexOptions.Singleline);
35 internal static readonly Regex PaiwiseComponent =
new Regex(
@"Waher[.]Service[.]IoTBroker[.]Paiwise[.]PaiwiseProcessor[.]GenerateContractualPaymentUri",
36 RegexOptions.Compiled | RegexOptions.Singleline);
37 internal static readonly Regex NeuroFeaturesComponent =
new Regex(
@"Waher[.]Service[.]IoTBroker[.]NeuroFeatures[.]NeuroFeaturesProcessor[.]CreateTokens",
38 RegexOptions.Compiled | RegexOptions.Singleline);
39 internal static readonly Regex UnitTests =
new Regex(
@"Waher[.]Service[.]IoTBroker[.]Test[.](LegalIdentitiesTests|SmartContractsTests)",
40 RegexOptions.Compiled | RegexOptions.Singleline);
41 private static readonly
object[] approvedSources =
new object[]
51 NeuroFeaturesComponent
53 private static readonly
object[] approvedSources2 =
new object[]
63 NeuroFeaturesComponent,
67 private string dataProtectionAgreementId =
string.Empty;
68 private byte[] privateKey =
null;
69 private byte[] salt =
null;
70 private int collectionTimeSeconds = 5 * 60;
71 private int blockSizeThreshold = 1 * 1024 * 1024;
94 return this.privateKey;
99 if (!(this.privateKey is
null))
102 this.privateKey = value;
115 if (this.CheckKey() && this.
ObjectId != Guid.Empty)
138 if (!(this.salt is
null))
148 [DefaultValueStringEmpty]
154 return this.dataProtectionAgreementId;
159 if (!
string.IsNullOrEmpty(this.dataProtectionAgreementId))
162 this.dataProtectionAgreementId = value;
182 private bool CheckKey()
186 if (this.privateKey is
null)
193 if (this.salt is
null)
212 get => this.collectionTimeSeconds;
213 set => this.collectionTimeSeconds = value;
221 get => this.blockSizeThreshold;
222 set => this.blockSizeThreshold = value;
233 public override string Resource =>
"/Settings/Ledger.md";
272 TimeSpan.FromSeconds(
this.collectionTimeSeconds),
this.blockSizeThreshold,
this.salt,
"Default",
280 if (!(RepairedCollections is
null))
282 foreach (
string Collection
in RepairedCollections)
283 this.AddRepairNoteFile(Collection);
287 if (File.Exists(FileName))
297 File.Delete(FileName);
304 catch (Exception ex2)
310 string[] ToRepair = Directory.GetFiles(this.RepairFolder,
"*.txt", SearchOption.TopDirectoryOnly);
311 foreach (
string FileName2
in ToRepair)
313 string CollectionName = Path.GetFileName(FileName2);
314 CollectionName = CollectionName.Substring(0, CollectionName.Length - 4);
321 await Provider.RepairRegistry();
323 await Provider.RepairCollection(CollectionName);
329 File.Delete(FileName2);
336 catch (Exception ex2)
343 Log.
Warning(
"Ledger settings changed. Restart the system for changes to take effect.");
349 private string RepairFolder
353 string Result = Path.Combine(this.LedgerFolder,
"Repair");
354 if (!Directory.Exists(Result))
355 Directory.CreateDirectory(Result);
361 private string AddRepairNoteFile(
string Collection)
363 string FileName = Path.Combine(this.RepairFolder, Collection +
".txt");
367 if (!File.Exists(FileName))
368 File.WriteAllText(FileName, DateTime.UtcNow.ToString());
385 string FileName = this.AddRepairNoteFile(e.
Collection);
387 lock (this.repairQueue)
391 this.repairQueue.AddLast(FileName);
395 this.repairing =
true;
398 while (!
string.IsNullOrEmpty(FileName))
400 string CollectionName = Path.GetFileName(FileName);
401 CollectionName = CollectionName.Substring(0, CollectionName.Length - 4);
404 await Provider.RepairRegistry();
406 await Provider.RepairCollection(CollectionName);
410 File.Delete(FileName);
417 lock (this.repairQueue)
419 if (this.repairQueue.First is
null)
422 this.repairing =
false;
426 FileName = this.repairQueue.First.Value;
427 this.repairQueue.RemoveFirst();
438 private readonly LinkedList<string> repairQueue =
new LinkedList<string>();
439 private bool repairing =
false;
447 return Task.FromResult(
true);
456 this.setLedgerProperties = WebServer.
Register(
"/Settings/SetLedgerProperties",
null, this.SetLedgerProperties,
true,
false,
true);
458 return base.InitSetup(WebServer);
467 WebServer.
Unregister(this.setLedgerProperties);
469 return base.UnregisterSetup(WebServer);
485 if (!(Obj is IDictionary<string, object> Data))
488 if (!Data.TryGetValue(
"collectionTime", out Obj) ||
489 !(Obj is
string CollectionTimeStr) ||
490 !
int.TryParse(CollectionTimeStr, out
int CollectionTime) ||
491 CollectionTime <= 0 ||
492 CollectionTime > 3600)
497 if (!Data.TryGetValue(
"blockSizeThreshold", out Obj) ||
498 !(Obj is
string BlockSizeThresholdStr) ||
503 throw new BadRequestException(
"Block Size Threshold can be between 1 and 1073741824 bytes (1 GB).");
506 this.collectionTimeSeconds = CollectionTime;
511 Response.StatusCode = 200;
520 public static byte[]
Sign(
byte[] Data)
527 return instance?.ed448?.
Sign(Data);
536 public static byte[]
Sign(Stream Data)
543 return instance?.ed448?.
Sign(Data);
552 public static bool Verify(
byte[] Data,
byte[] Signature)
554 return instance?.ed448?.
Verify(Data, instance?.
PublicKey, Signature) ??
false;
574 if (!
string.IsNullOrEmpty(Value))
576 if (!
int.TryParse(Value, out
int i))
579 return Task.FromResult(
false);
582 if (i < 1 || i > 3600)
585 return Task.FromResult(
false);
588 this.collectionTimeSeconds = i;
592 if (!
string.IsNullOrEmpty(Value))
594 if (!
int.TryParse(Value, out
int i))
597 return Task.FromResult(
false);
600 if (i < 1 || i > 1073741824)
603 return Task.FromResult(
false);
606 this.blockSizeThreshold = i;
609 return Task.FromResult(
true);
Static class managing the application event log. Applications and services log events on this static ...
static void Exception(Exception Exception, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, params KeyValuePair< string, object >[] Tags)
Logs an exception. Event type will be determined by the severity of the exception.
static void Warning(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs a warning event.
static void Error(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs an error event.
static void Informational(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs an informational event.
Static class managing the runtime environment of the IoT Gateway.
static IUser AssertUserAuthenticated(HttpRequest Request, string Privilege)
Makes sure a request is being made from a session with a successful user login.
static byte[] NextBytes(int NrBytes)
Generates an array of random bytes.
static string AppDataFolder
Application data folder.
static string[] RepairedCollections
Collections repaired during startup.
static DomainConfiguration Instance
Current instance of configuration.
Abstract base class for system configurations.
void LogEnvironmentVariableInvalidRangeError(int Min, int Max, string EnvironmentVariable, object Value)
Logs an error to the event log, telling the operator an environment variable value is not within a va...
void LogEnvironmentVariableInvalidIntegerError(string EnvironmentVariable, object Value)
Logs an error to the event log, telling the operator an environment variable value is not a valid int...
static XmppConfiguration Instance
Current instance of configuration.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
Represents an HTTP request.
bool HasData
If the request has data.
async Task< object > DecodeDataAsync()
Decodes data sent in request.
Base class for all HTTP resources.
Represets a response of an HTTP client request.
Implements an HTTP server.
HttpResource Register(HttpResource Resource)
Registers a resource with the server.
bool Unregister(HttpResource Resource)
Unregisters a resource from the server.
Event arguments for collection events.
string Collection
Collection
Static interface for database persistence. In order to work, a database provider has to be assigned t...
static async Task UpdateLazy(object Object)
Updates an object in the database, if unlocked. If locked, object will be updated at next opportunity...
static async Task Update(object Object)
Updates an object in the database.
Static interface for ledger persistence. In order to work, a ledger provider has to be assigned to it...
static void Register(ILedgerProvider LedgerProvider)
Registers a ledger provider for use from the static Ledger class, throughout the lifetime of the appl...
static bool Locked
If the datbase provider has been locked for the rest of the run-time of the application.
static bool HasProvider
If a ledger provider is registered.
static ILedgerProvider Provider
Registered ledger provider.
async Task RepairRegistry()
Make sure block reference objects match existing blocks.
Contains a reference to a block in the ledger.
const string BlockReferencesCollection
Collection housing all block references.
Contains information about a language.
Task< string > GetStringAsync(Type Type, int Id, string Default)
Gets the string value of a string ID. If no such string exists, a string is created with the default ...
Static class containing methods that can be used to make sure calls are made from appropriate locatio...
static void CallFromSource(params string[] Sources)
Makes sure the call is made from one of the listed sources.
Edwards448 Elliptic Curve, as defined in RFC7748 and RFC8032: https://tools.ietf.org/html/rfc7748 htt...
override bool Verify(byte[] Data, byte[] PublicKey, byte[] Signature)
Verifies a signature of Data made by the EdDSA algorithm.
override byte[] Sign(byte[] Data)
Creates a signature of Data using the EdDSA algorithm.
override string CurveName
Name of curve.
virtual byte[] PublicKey
Encoded public key
Implements the SHA3-512 hash function, as defined in section 6.1 in the NIST FIPS 202: https://nvlpub...
override Task< bool > SimplifiedConfiguration()
Simplified configuration by configuring simple default values.
override int Priority
Priority of the setting. Configurations are sorted in ascending order.
override Task InitSetup(HttpServer WebServer)
Initializes the setup object.
static bool Verify(byte[] Data, byte[] Signature)
Verifies a digital signature, supposedly made by the ledger.
const string NEURO_LEDGER_COLLECTION
Collection time in seconds.
override void SetStaticInstance(ISystemConfiguration Configuration)
Sets the static instance of the configuration.
int CollectionTimeSeconds
Maximum time during which entries in a block are being collected, in seconds.
string LedgerFolder
Ledger folder.
override Task< bool > EnvironmentConfiguration()
Environment configuration by configuring values available in environment variables.
int BlockSizeThreshold
Blocks are generated before the collection time elapses, if reaching this size.
static byte[] Sign(byte[] Data)
Signs data with the private key of the ledger.
override string Resource
Resource to be redirected to, to perform the configuration.
static byte[] Sign(Stream Data)
Signs data with the private key of the ledger.
override async Task ConfigureSystem()
Is called during startup to configure the system.
string DataProtectionAgreementId
Data Protection Agreement to use before allowing access to the Neuro-Ledger.
static LedgerConfiguration Instance
Current instance of configuration.
LedgerConfiguration()
Ledger configuration
string SignatureAlgorithm
Name of signature algorithm.
override Task UnregisterSetup(HttpServer WebServer)
Unregisters the setup object.
byte[] PrivateKey
Private key used for signatures.
override string ConfigPrivilege
Minimum required privilege for a user to be allowed to change the configuration defined by the class.
override Task< string > Title(Language Language)
Gets a title for the system configuration.
byte[] PublicKey
Public key used to validate signatures.
byte[] Salt
Private key used for signatures.
const string NEURO_LEDGER_MAXSIZE
Maximum size of blocks, in bytes.
Interface for system configurations. The gateway will scan all module for system configuration classe...