4using System.Text.RegularExpressions;
5using System.Threading.Tasks;
28 internal static readonly Regex FromSaveUnsaved =
new Regex(
@"Waher[.]Persistence[.]Files[.]ObjectBTreeFile[.+]<?SaveUnsaved>?\w*[.]\w*",
29 RegexOptions.Compiled | RegexOptions.Singleline);
30 internal static readonly Regex FromUpdateObject =
new Regex(
@"Waher[.]Persistence[.]Files[.]ObjectBTreeFile[.+]<?UpdateObject>?\w*[.]\w*",
31 RegexOptions.Compiled | RegexOptions.Singleline);
32 internal static readonly Regex GatewayStartup =
new Regex(
@"Waher[.]IoTGateway[.]Gateway([.]Start|[.+]<?Start>?\w*[.]\w*)*",
33 RegexOptions.Compiled | RegexOptions.Singleline);
34 internal static readonly
string LegalComponent =
"Waher.Service.IoTBroker.Legal.LegalComponent";
35 internal static readonly
string PaiwiseComponent =
"Waher.Service.IoTBroker.Paiwise.PaiwiseProcessor";
36 internal static readonly
string NeuroFeaturesComponent =
"Waher.Service.IoTBroker.NeuroFeatures.NeuroFeaturesProcessor";
37 internal static readonly
string EDalerComponent =
"Waher.Service.IoTBroker.EDaler.EDalerProcessor";
38 internal static readonly
string MarketplaceComponent =
"Waher.Service.IoTBroker.Marketplace.MarketplaceProcessor";
39 internal static readonly
string SetContractState =
"Waher.Service.IoTBroker.WebServices.SetContractState";
40 internal static readonly Regex UnitTests =
new Regex(
@"Waher[.]Service[.]IoTBroker[.]Test[.](LegalIdentitiesTests|SmartContractsTests|AgentTests|EDalerTests|EDalerFederatedTests|MarketplaceTests|NeuroFeaturesTests|QuickLoginTests)",
41 RegexOptions.Compiled | RegexOptions.Singleline);
52 NeuroFeaturesComponent,
67 NeuroFeaturesComponent,
71 "System.Threading.PortableThreadPool+WorkerThread",
75 private string dataProtectionAgreementId =
string.Empty;
76 private byte[] privateKey =
null;
77 private byte[] salt =
null;
78 private int collectionTimeSeconds = 5 * 60;
79 private int blockSizeThreshold = 1 * 1024 * 1024;
102 return this.privateKey;
107 if (!(this.privateKey is
null))
110 this.privateKey = value;
123 if (this.CheckKey() && this.
ObjectId != Guid.Empty)
146 if (!(this.salt is
null))
156 [DefaultValueStringEmpty]
162 return this.dataProtectionAgreementId;
167 if (!
string.IsNullOrEmpty(this.dataProtectionAgreementId))
170 this.dataProtectionAgreementId = value;
190 private bool CheckKey()
194 if (this.privateKey is
null)
201 if (this.salt is
null)
220 get => this.collectionTimeSeconds;
221 set => this.collectionTimeSeconds = value;
229 get => this.blockSizeThreshold;
230 set => this.blockSizeThreshold = value;
241 public override string Resource =>
"/Settings/Ledger.md";
280 TimeSpan.FromSeconds(
this.collectionTimeSeconds),
this.blockSizeThreshold,
this.salt,
"Default",
288 if (!(RepairedCollections is
null))
290 foreach (
string Collection
in RepairedCollections)
291 this.AddRepairNoteFile(Collection);
295 if (File.Exists(FileName))
305 File.Delete(FileName);
312 catch (Exception ex2)
318 string[] ToRepair = Directory.GetFiles(this.RepairFolder,
"*.txt", SearchOption.TopDirectoryOnly);
319 foreach (
string FileName2
in ToRepair)
321 string CollectionName = Path.GetFileName(FileName2);
322 CollectionName = CollectionName[..^4];
329 await Provider.RepairRegistry();
331 await Provider.RepairCollection(CollectionName);
337 File.Delete(FileName2);
344 catch (Exception ex2)
351 Log.
Warning(
"Ledger settings changed. Restart the system for changes to take effect.");
357 private string RepairFolder
361 string Result = Path.Combine(this.LedgerFolder,
"Repair");
362 if (!Directory.Exists(Result))
363 Directory.CreateDirectory(Result);
369 private string AddRepairNoteFile(
string Collection)
371 string FileName = Path.Combine(this.RepairFolder, Collection +
".txt");
375 if (!File.Exists(FileName))
376 File.WriteAllText(FileName, DateTime.UtcNow.ToString());
393 string FileName = this.AddRepairNoteFile(e.
Collection);
395 lock (this.repairQueue)
399 this.repairQueue.AddLast(FileName);
403 this.repairing =
true;
406 while (!
string.IsNullOrEmpty(FileName))
408 string CollectionName = Path.GetFileName(FileName);
409 CollectionName = CollectionName[..^4];
412 await Provider.RepairRegistry();
414 await Provider.RepairCollection(CollectionName);
418 File.Delete(FileName);
425 lock (this.repairQueue)
427 if (this.repairQueue.First is
null)
430 this.repairing =
false;
434 FileName = this.repairQueue.First.Value;
435 this.repairQueue.RemoveFirst();
446 private readonly LinkedList<string> repairQueue =
new LinkedList<string>();
447 private bool repairing =
false;
455 return Task.FromResult(
true);
464 this.setLedgerProperties = WebServer.
Register(
"/Settings/SetLedgerProperties",
null, this.SetLedgerProperties,
true,
false,
true);
466 return base.InitSetup(WebServer);
475 WebServer.
Unregister(this.setLedgerProperties);
477 return base.UnregisterSetup(WebServer);
496 if (Content.
HasError || !(Content.
Decoded is IDictionary<string, object> Data))
502 if (!Data.TryGetValue(
"collectionTime", out
object Obj) ||
503 !(Obj is
string CollectionTimeStr) ||
504 !
int.TryParse(CollectionTimeStr, out
int CollectionTime) ||
505 CollectionTime <= 0 ||
506 CollectionTime > 3600)
512 if (!Data.TryGetValue(
"blockSizeThreshold", out Obj) ||
513 !(Obj is
string BlockSizeThresholdStr) ||
522 this.collectionTimeSeconds = CollectionTime;
527 Response.StatusCode = 200;
528 Response.StatusMessage =
"OK";
537 public static byte[]
Sign(
byte[] Data)
540 return instance?.ed448?.
Sign(Data);
549 public static byte[]
Sign(Stream Data)
552 return instance?.ed448?.
Sign(Data);
561 public static bool Verify(
byte[] Data,
byte[] Signature)
563 return instance?.ed448?.
Verify(Data, instance?.
PublicKey, Signature) ??
false;
583 if (!
string.IsNullOrEmpty(Value))
585 if (!
int.TryParse(Value, out
int i))
588 return Task.FromResult(
false);
591 if (i < 1 || i > 3600)
594 return Task.FromResult(
false);
597 this.collectionTimeSeconds = i;
601 if (!
string.IsNullOrEmpty(Value))
603 if (!
int.TryParse(Value, out
int i))
606 return Task.FromResult(
false);
609 if (i < 1 || i > 1073741824)
612 return Task.FromResult(
false);
615 this.blockSizeThreshold = i;
618 return Task.FromResult(
true);
Contains information about a response to a content request.
bool HasError
If an error occurred.
object Decoded
Decoded object.
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.
bool UseDomainName
If the server uses a domain name.
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< ContentResponse > DecodeDataAsync()
Decodes data sent in request.
Base class for all HTTP resources.
Represets a response of an HTTP client request.
async Task SendResponse()
Sends the response back to the client. If the resource is synchronous, there's no need to call this m...
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 ICallStackCheck[] Convert(params object[] Sources)
Converts an array of objects into an array of ICallStackCheck objects, assuming each listed source is...
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, bool BigEndian, byte[] Signature)
Verifies a signature of Data made by the EdDSA algorithm.
override byte[] Sign(byte[] Data, bool BigEndian)
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.
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...
Interface for call stack checks.