Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
ValidateContract.cs
1using System;
2using System.Collections.Generic;
3using System.Threading.Tasks;
4using Waher.Content;
11
13{
15 {
16 public ValidateContract()
17 : base("/ValidateContract")
18 {
19 }
20
21 public override bool HandlesSubPaths => false;
22 public override bool UserSessions => true;
23 public bool AllowsPOST => true;
24
25 public async Task POST(HttpRequest Request, HttpResponse Response)
26 {
27 Gateway.AssertUserAuthenticated(Request, "Admin.Legal.Validate.Contract");
28
29 if (!Request.HasData)
30 throw new BadRequestException();
31
32 object Obj = await Request.DecodeDataAsync();
33 if (!(Obj is Dictionary<string, object> RequestObj) ||
34 !RequestObj.TryGetValue("ContractId", out Obj) || !(Obj is string ContractId) ||
35 !RequestObj.TryGetValue("Purpose", out Obj) || !(Obj is string Purpose) ||
36 !RequestObj.TryGetValue("Password", out Obj) || !(Obj is string Password) ||
37 !RequestObj.TryGetValue("TabID", out Obj) || !(Obj is string TabID))
38 {
39 throw new BadRequestException();
40 }
41
42 if (ContractId.IndexOf('@') < 0)
43 throw new BadRequestException("Invalid contract identity.");
44
45 if (Gateway.ContractsClient is null)
46 throw new ServiceUnavailableException("Broker not connected to a legal service.");
47
48 Dictionary<string, object> ResponseObj;
49
50 try
51 {
53 ResponseObj = await this.Encode(Contract);
54 }
55 catch (Exception)
56 {
57 string PetitionId = Guid.NewGuid().ToString();
58
59 Purpose = Purpose.Trim();
60 if (string.IsNullOrEmpty(Purpose))
61 Purpose = "Validating Contract through web interface at " + Gateway.Domain;
62
63 if (!await Gateway.PetitionContract(ContractId, PetitionId, Purpose, Password, async (_, e) =>
64 {
65 await ClientEvents.PushEvent(new string[] { TabID }, "PetitionResponseReceived", JSON.Encode(new Dictionary<string, object>()
66 {
67 { "PetitionId", e.PetitionId },
68 { "PetitionResponse", e.Response },
69 { "Contract", await this.Encode(e.RequestedContract) },
70 { "Declined", e.RequestedContract is null && !(e.Message is null) },
71 { "Timeout", e.Message is null }
72 }, false), true);
73 }, TimeSpan.FromMinutes(5)))
74 {
75 throw new ForbiddenException("Unable to sign petition. Either password is incorrect, or no legal identity assigned to broker.");
76 }
77
78 ResponseObj = new Dictionary<string, object>()
79 {
80 { "Id", ContractId },
81 { "Petition", true },
82 { "PetitionId", PetitionId },
83 { "Message", "The information has been petitioned from the owner. If the owner accepts to share the information, it will be displayed here when it arrives." }
84 };
85 }
86
87 await Response.Return(ResponseObj);
88 }
89
90 private async Task<Dictionary<string, object>> Encode(Contract Contract)
91 {
92 if (Contract is null)
93 return null;
94
96 List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
97 Dictionary<string, object> ResponseObj = new Dictionary<string, object>()
98 {
99 { "ContractId", Contract.ContractId },
100 { "ContractIdUri", Contract.ContractIdUriString },
101 { "Petition", false },
102 { "Provider", Contract.Provider },
103 { "State", Contract.State.ToString() },
104 { "ValidationStatus", Status.ToString() },
105 { "Visibility", Contract.Visibility },
106 { "Created", Contract.Created },
107 { "Updated", Contract.Updated },
108 { "From", Contract.From },
109 { "To", Contract.To },
110 { "SignAfter", Contract.SignAfter },
111 { "SignBefore", Contract.SignBefore },
112 { "Duration", Contract.Duration.ToString() },
113 { "ArchiveOptional", Contract.ArchiveOptional.ToString() },
114 { "ArchiveRequired", Contract.ArchiveRequired.ToString() },
115 { "TemplateId", Contract.TemplateId },
116 { "TemplateIdUri", Contract.TemplateIdUriString },
117 { "CanActAsTemplate", Contract.CanActAsTemplate },
118 { "PartsMode", Contract.PartsMode.ToString() },
119 { "DefaultLanguage", Contract.DefaultLanguage },
120 { "ForHumans", await this.Encode(Contract.ForHumans, Contract) },
121 { "ContentSchemaDigest", Contract.ContentSchemaDigest is null ? null : Convert.ToBase64String(Contract.ContentSchemaDigest) },
122 { "ContentSchemaHashFunction", Contract.ContentSchemaHashFunction.ToString() },
123 { "ForMachinesLocalName", Contract.ForMachinesLocalName },
124 { "ForMachinesNamespace", Contract.ForMachinesNamespace },
125 { "ForMachines", XML.PrettyXml(Contract.ForMachines) }
126 };
127
128 if (!(Contract.Roles is null))
129 {
130 foreach (Role Role in Contract.Roles)
131 {
132 List.Add(new Dictionary<string, object>()
133 {
134 { "Name", Role.Name },
135 { "MinCount", Role.MinCount },
136 { "MaxCount", Role.MaxCount },
137 { "CanRevoke", Role.CanRevoke },
138 { "Descriptions", await this.Encode(Role.Descriptions, Contract) }
139 });
140 }
141
142 ResponseObj["Roles"] = List.ToArray();
143 List.Clear();
144 }
145
146 if (!(Contract.Parts is null))
147 {
148 foreach (Part Part in Contract.Parts)
149 {
150 List.Add(new Dictionary<string, object>()
151 {
152 { "LegalId", Part.LegalId },
153 { "LegalIdUri", Part.LegalIdUriString },
154 { "Role", Part.Role }
155 });
156 }
157
158 ResponseObj["Parts"] = List.ToArray();
159 List.Clear();
160 }
161
162 if (!(Contract.Parameters is null))
163 {
165 {
166 List.Add(new Dictionary<string, object>()
167 {
168 { "Name", Parameter.Name },
169 { "Value", Parameter.ObjectValue },
170 { "Descriptions", await this .Encode(Parameter.Descriptions, Contract) }
171 });
172 }
173
174 ResponseObj["Parameters"] = List.ToArray();
175 List.Clear();
176 }
177
178 if (!(Contract.ClientSignatures is null))
179 {
181 {
182 List.Add(new Dictionary<string, object>()
183 {
184 { "BareJid", ClientSignature.BareJid },
185 { "DigitalSignature", Convert.ToBase64String(ClientSignature.DigitalSignature) },
186 { "LegalId", ClientSignature.LegalId },
187 { "LegalIdUri", ClientSignature.LegalIdUriString },
188 { "Role", ClientSignature.Role },
189 { "Timestamp", ClientSignature.Timestamp },
190 { "Transferable", ClientSignature.Transferable }
191 });
192 }
193
194 ResponseObj["ClientSignatures"] = List.ToArray();
195 List.Clear();
196 }
197
198 if (!(Contract.Attachments is null))
199 {
201 {
202 List.Add(new Dictionary<string, object>()
203 {
204 { "BareJid", ClientSignature.BareJid },
205 { "DigitalSignature", Convert.ToBase64String(ClientSignature.DigitalSignature) },
206 { "LegalId", ClientSignature.LegalId },
207 { "LegalIdUri", ClientSignature.LegalIdUriString },
208 { "Role", ClientSignature.Role },
209 { "Timestamp", ClientSignature.Timestamp },
210 { "Transferable", ClientSignature.Transferable }
211 });
212 }
213
214 ResponseObj["ClientSignatures"] = List.ToArray();
215 List.Clear();
216 }
217
218 if (!(Contract.Attachments is null))
219 {
221 {
222 List.Add(new Dictionary<string, object>()
223 {
224 { "Id", Attachment.Id },
225 { "ContentType", Attachment.ContentType },
226 { "FileName", Attachment.FileName },
227 { "Url", Attachment.Url },
228 { "Signature", Convert.ToBase64String(Attachment.Signature) },
229 { "Timestamp", Attachment.Timestamp },
230 });
231 }
232
233 ResponseObj["Attachments"] = List.ToArray();
234 List.Clear();
235 }
236
237 ResponseObj["ServerSignature"] = new Dictionary<string, object>()
238 {
239 { "DigitalSignature", Convert.ToBase64String(Contract.ServerSignature.DigitalSignature) },
240 { "Timestamp", Contract.ServerSignature.Timestamp }
241 };
242
243 return ResponseObj;
244 }
245
246 private async Task<Dictionary<string, object>[]> Encode(HumanReadableText[] Text, Contract Contract)
247 {
248 List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
249
250 foreach (HumanReadableText Localization in Text)
251 {
252 List.Add(new Dictionary<string, object>()
253 {
254 { "Language", Localization.Language },
255 { "IsWellDefined", await Localization.IsWellDefined() },
256 { "Html", HtmlDocument.GetBody(await Localization.GenerateHTML(Contract)) }
257 });
258 }
259
260 return List.ToArray();
261 }
262
263 }
264}
static string GetBody(string Html)
Extracts the contents of the BODY element in a HTML string.
Helps with common JSON-related tasks.
Definition: JSON.cs:14
static string Encode(string s)
Encodes a string for inclusion in JSON.
Definition: JSON.cs:507
Helps with common XML-related tasks.
Definition: XML.cs:19
static string PrettyXml(string Xml)
Reformats XML to make it easier to read.
Definition: XML.cs:1548
The ClientEvents class allows applications to push information asynchronously to web clients connecte...
Definition: ClientEvents.cs:51
static Task< int > PushEvent(string[] TabIDs, string Type, object Data)
Puses an event to a set of Tabs, given their Tab IDs.
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:126
static CaseInsensitiveString Domain
Domain name.
Definition: Gateway.cs:2354
static IUser AssertUserAuthenticated(HttpRequest Request, string Privilege)
Makes sure a request is being made from a session with a successful user login.
Definition: Gateway.cs:3041
static Task< bool > PetitionContract(string ContractId, string PetitionId, string Purpose, EventHandlerAsync< ContractPetitionResponseEventArgs > Callback, TimeSpan Timeout)
Petitions information about a smart contract from its owner.
Definition: Gateway.cs:4567
static ContractsClient ContractsClient
XMPP Contracts Client, if such a compoent is available on the XMPP broker.
Definition: Gateway.cs:4375
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
The server understood the request, but is refusing to fulfill it. Authorization will not help and the...
Represents an HTTP request.
Definition: HttpRequest.cs:18
bool HasData
If the request has data.
Definition: HttpRequest.cs:74
async Task< object > DecodeDataAsync()
Decodes data sent in request.
Definition: HttpRequest.cs:95
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:21
async Task Return(object Object)
Returns an object to the client. This method can only be called once per response,...
Base class for all synchronous HTTP resources. A synchronous resource responds within the method hand...
The server is currently unable to handle the request due to a temporary overloading or maintenance of...
Contains a reference to an attachment assigned to a legal object.
Definition: Attachment.cs:9
byte[] Signature
Binary signature of the attachment, generated by an approved legal identity of the account-holder....
Definition: Attachment.cs:75
Represents a digital signature on a contract.
Contains the definition of a contract
Definition: Contract.cs:22
byte[] ContentSchemaDigest
The hash digest of the schema used to validate the machine-readable contents (ForMachines) of the sma...
Definition: Contract.cs:221
Security.HashFunction ContentSchemaHashFunction
Hash function of the schema used to validate the machine-readable contents (ForMachines) of the smart...
Definition: Contract.cs:231
Parameter[] Parameters
Defined parameters for the smart contract.
Definition: Contract.cs:267
Duration? ArchiveRequired
Requied time to archive a signed smart contract, after it becomes obsolete.
Definition: Contract.cs:202
ClientSignature[] ClientSignatures
Client signatures of the contract.
Definition: Contract.cs:309
HumanReadableText[] ForHumans
Human-readable contents of the contract.
Definition: Contract.cs:300
Attachment[] Attachments
Attachments assigned to the legal identity.
Definition: Contract.cs:318
Duration? ArchiveOptional
Optional time to archive a signed smart contract, after it becomes obsolete, and after its required a...
Definition: Contract.cs:211
XmlElement ForMachines
Machine-readable contents of the contract.
Definition: Contract.cs:276
Role[] Roles
Roles defined in the smart contract.
Definition: Contract.cs:240
ContractParts PartsMode
How parts are defined in the smart contract.
Definition: Contract.cs:249
ContractState State
Contract state
Definition: Contract.cs:121
Part[] Parts
Defined parts for the smart contract.
Definition: Contract.cs:258
Duration? Duration
Duration of the contract. Is counted from the time it is signed by the required parties.
Definition: Contract.cs:193
ServerSignature ServerSignature
Server signature attesting to the validity of the contents of the contract.
Definition: Contract.cs:327
Task< IdentityStatus > ValidateAsync(LegalIdentity Identity)
Validates a legal identity.
Task< Contract > GetContractAsync(string ContractId)
Gets a contract
override async Task< HumanReadableElement > IsWellDefined()
Checks if the element is well-defined.
Definition: Blocks.cs:25
async Task< string > GenerateHTML(Contract Contract)
Generates HTML for the human-readable text.
HumanReadableText[] Descriptions
Discriptions of the object, in different languages.
Abstract base class for contractual parameters
Definition: Parameter.cs:17
Class defining a part in a contract
Definition: Part.cs:30
Class defining a role
Definition: Role.cs:7
byte[] DigitalSignature
Digital Signature
Definition: Signature.cs:27
bool AllowsPOST
If the POST method is allowed.
async Task POST(HttpRequest Request, HttpResponse Response)
Executes the POST method on the resource.
POST Interface for HTTP resources.
ContractStatus
Validation Status of smart contract
override string ToString()
Definition: Duration.cs:471