1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#![allow(dead_code)]
#![allow(unused_imports)]
//! SPDX-License-Identifier: APACHE 2.0 
//!
//! # OpenRoles crate for NEAR blockchain 
//! 
//! <br/> @author : Block Star Logic 
//! <br/> @coder : T Ushewokunze 
//! <br/> @license :  Apache 2.0 
//!
//! <br/> The **obei_or_near_core** crate contains the functionality to enable remote governance of function level access for smart contracts built on the NEAR blockchain.
//! <br/>
//! <br/> The **OpenRolesContract** is the core functional struct of this crate. It enables the independent creation of **'ParticipantList's** the registration of **'DependentContract's** to be 
//! placed under management and the assignment of **'ParticipantLists'** to **'DependentContracts'**.
//! <br/>
//! <br/> **'ParticipantList's** hold the participants to be either **'allowed'** or **'barred'** access to a given function on a given smart contract.
//! <br/>
//! <br/> **'DependentContact's** are the contracts for the dApp under governance of the **'OpenRolesContract'** 
//! <br/>
//! <br/> As the **OpenRolesContract** is deployed separately from the main **'functional contract'** the access scheme can be shared and retained across deployments and migrations, without altering the governance model
//! 
//! # Integration 
//! To integrate Open Roles into a dApp contract you need to 'use' **[\\or_traits::TOpenRoles]** and implement this where ever needed in your dApp contract as follows:
//! <br/> **[ext_open_roles::is_allowed ( near_account_id, registered_contract_name, contract_operation, signer_account_id, no_deposit, base_gas_fee );]**  
//! <br/> A Promise will be returned from the **OpenRolesContract** containing a **'bool'** as per the function definition
//!
mod tests;
mod or_structs;

use std::collections::{HashMap, HashSet};
use chrono::{Utc};
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{env, near_bindgen};
use or_structs::{AssignmentAddress, DependentContract, ParticipantList};

near_sdk::setup_alloc!();

#[near_bindgen]
#[derive( serde::Serialize, BorshDeserialize, BorshSerialize, Default)]
struct OpenRoles{
	
	role_administrator : String, //administers all the accounts 
	
	id : String, // name of this 

	contract_by_contract_name_by_contract_account_id : HashMap<String, HashMap<String, or_structs::DependentContract>>, // main data store
	
	lists :HashMap<String, or_structs::ParticipantList>, // participant lists 
	
	operation_assignment_address_by_list : HashMap<String, HashSet<or_structs::AssignmentAddress>>, // view of list operation assignments 

	list_names : HashSet<String>, // participant list names 

	affirmative : i32, // affirmative value

	negative : i32, // negative value 

}

#[near_bindgen]
impl OpenRoles{
	
	/// Returns the code version of this OpenRoles instance 
	/// # Return Value 
	/// This function returns:
	/// **String** with code version 
	pub fn get_version(&self) -> String {
		"0.1.0".to_string()
	}


	/// Returns the id of this instance which was set on creation 
	/// # Return Value 
	/// This function returns :
	/// **String** with id as set by the administrator 
	pub fn get_id(&self) -> String {
		self.id.to_string()
	}

	/// Checks whether the given on chain **'user_account_id'**  is allowed to access the stated operation (function)
	/// <br/> This operation provides the implementation for **[\or_structs::TOpenRoles]**
	/// # Return Value 
	/// This function returns: 
	///  **'i32'** : value equal to **self.affirmative**  if and only if the user is listed as allowed to access the operation (default = 1)	
	pub fn is_allowed(&self, contract_account_id : String, contract_name : String, operation : String, user_account_id : String) -> i32 {
		if self.is_registered(contract_account_id.clone(), contract_name.clone()){
			let  list_name = self.contract_by_contract_name_by_contract_account_id.get(&contract_account_id).unwrap().get(&contract_name).unwrap().list_name_by_operation.get(&operation).unwrap();
			let plist = self.lists.get(list_name).unwrap();
	
			if plist.status.as_bytes() != "DELETED".to_string().as_bytes() && plist.account_ids.contains(&user_account_id){
				return self.affirmative
			}
			return self.negative
		}
		else {
			panic!(" CONTRACT : {} NOT REGISTERED FOR ACCOUNT : {} ", contract_account_id, contract_name)
		}
	}

	/// Checks whether the given on chain **'user_account_id'**  is barred from access the stated operation (function)
	/// <br/> This operation provides the implementation for **[\or_structs::TOpenRoles]**
	/// # Return Value 
	/// This function returns: 
	///  **'i32'** : value equal to **self.affirmative** if and only if the user is listed as barred to access the operation (default = 1)	 
	pub fn is_barred(&self, contract_account_id : String, contract_name :String, operation : String, user_account_id : String) -> i32 {
		if self.is_registered(contract_account_id.clone(), contract_name.clone()){
			let  list_name = self.contract_by_contract_name_by_contract_account_id.get(&contract_account_id).unwrap().get(&contract_name).unwrap().list_name_by_operation.get(&operation).unwrap();		
			let plist = self.lists.get(list_name).unwrap();

			if plist.status.as_bytes() != "DELETED".to_string().as_bytes() && plist.account_ids.contains(&user_account_id){
				 return self.affirmative
			} 		
			return self.negative
		}
		else {
			panic!(" CONTRACT : {} NOT REGISTERED FOR ACCOUNT : {} ", contract_account_id, contract_name)
		}
	}
	
	/// Checks whether the given **DependentContract** is registered under the given **concract_account_id** 
	/// <br/> This operation provides the implementation for **[\or_structs::TOpenRoles]**
	/// # Return Value 
	/// This function returns: 
	///  **'bool'** : **true** if and only if the contract is registered according to the given details  
	pub fn is_registered(&self, contract_account_id : String, contract_name : String) -> bool {
		self.contract_by_contract_name_by_contract_account_id.get(&contract_account_id).unwrap().contains_key(&contract_name)
	}
	
	pub fn view_list_assignments(&self, list_name : String) -> &HashSet<AssignmentAddress> {
		self.operation_assignment_address_by_list.get(&list_name).unwrap()
	}

	/// Assigns the given **list** to the given operation on the given contract deployed at the given NEAR account id
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns: *String* otherwise panics  
	pub fn assign_list_to_operation(&mut self, contract_account_id : String, contract_name : String, operation : String, list_name : String) -> String {
		self.administrator_only ();
		
		let assignment_address = AssignmentAddress {
								deployment_account_id: contract_account_id.clone(), 
								contract_name : contract_name.clone(), 
								operation : operation.clone(),
							};

		let contract = self.contract_by_contract_name_by_contract_account_id.get_mut(&contract_account_id).unwrap().get_mut(&contract_name).unwrap();
				
		contract.assign_list_name_to_operation(operation.clone(), list_name.clone());
		
		if self.operation_assignment_address_by_list.contains_key(&list_name) {

		}
		else {
			let mut ops = HashSet::<AssignmentAddress>::new(); 
			ops.insert(assignment_address);			
			self.operation_assignment_address_by_list.insert(list_name.clone(), ops);
		}

		format!("LIST {} ASSIGNED", list_name).to_string()
	}
		
	/// Removes the given **list** from the given operation on the given contract deployed on the given NEAR account id 
	/// <br/> *Administrator Only function*
	/// # Return Value 
	// This function returns *String* otherwise panics 
	pub fn remove_list_from_operation(&mut self, contract_account_id : String, contract_name : String, operation : String) -> String {
		self.administrator_only ();
		
		let assignment_address = or_structs::AssignmentAddress {
			deployment_account_id: contract_account_id.clone(), 
			contract_name :contract_name.clone(), 
			operation : operation.clone(),
		};

		let contract = self.contract_by_contract_name_by_contract_account_id.get_mut(&contract_account_id).unwrap().get_mut(&contract_name).unwrap();
		
		let list_name = contract.de_assign_list_name_from_operation(operation);
		
		self.operation_assignment_address_by_list.get_mut(&list_name).unwrap().remove(&assignment_address);

		format!("LIST {} REMOVED", &list_name).to_string()						
	}

	
	/// Creates the given **list** with **ACTIVE** status 
	/// <br/> *Administrator Only function* 
	/// # Return Value 
	/// This function returns *String* otherwise panics 
	pub fn create_list(&mut self, list_name : String, list_type : String) -> String {
		self.administrator_only ();
		let list = ParticipantList {
							name : list_name.clone(), 
							list_type, 
							account_ids : HashSet::<String>::new(),
							status : "ACTIVE".to_string(),
						};
		self.lists.insert(list_name.clone(), list);
		self.list_names.insert(list_name.clone());
		format!("LIST {} CREATED", list_name).to_string()
	}

	/// Deletes the given **list** from those available by setting the list status to **DELETED**
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns *String* otherwise panics  
	pub fn delete_list(&mut self, list_name : String) -> String {
		self.administrator_only ();
		
		let plist = self.lists.get_mut(&list_name).unwrap(); 
		plist.status = "DELETED".to_string();

		self.list_names.remove(&plist.name);

		format!("LIST {} DELETED.",plist.name).to_string()
	}
    
	/// Adds a NEAR blockchain user_account_id to the given **list_name** from those available 
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns *String* otherwise panics  
	pub fn add_account_id_to_list(&mut self, user_account_id : String, list_name : String) -> String {
		self.administrator_only ();
		let plist = self.lists.get_mut(&list_name).unwrap();
		
		OpenRoles::check_status( plist.status.to_string(), "ACTIVE".to_string());
		
		plist.account_ids.insert(user_account_id.clone());
		
		format!("ACCOUNT {} ADDED.",user_account_id).to_string()
	}    
	
	/// Removes the given NEAR blockchain user_account_id from the given **list** 
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns *String* otherwise panics  	
	pub fn remove_account_from_list(&mut self, user_account_id : String, list_name : String) -> String {
		self.administrator_only ();
		let plist = self.lists.get_mut(&list_name).unwrap(); 

		OpenRoles::check_status( plist.status.to_string(), "ACTIVE".to_string());

		plist.account_ids.remove(&user_account_id);
		
		format!("ACCOUNT {} REMOVED.",user_account_id).to_string()
	}	
	
	/// Registers the given contract as deployed on the given **contract_account_id** with the given operations 
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns *String* otherwise panics  
	pub fn register_contract(&mut self, contract_account_id : String, contract_name : String, ops : Vec<String>) -> String {
		self.administrator_only ();
		let mut u_ops = HashSet::<String>::new();
		for o in ops { 
			u_ops.insert(o);
		}
		let contract = DependentContract{
								name : contract_name, 
								account_id : contract_account_id, 
								operations : u_ops, 
								list_name_by_operation : HashMap::<String, String>::new(),
							 };
		let msg = format!("CONTRACT {} REGISTERED", &contract.view_name());
		
		if self.contract_by_contract_name_by_contract_account_id.contains_key(&contract.view_account_id()) {
			
			let contracts  = self.contract_by_contract_name_by_contract_account_id.get_mut(&contract.view_account_id()).unwrap();
			
			if contracts.contains_key(&contract.view_name()) {
				panic!("Contract {} already registered. De-register and re-register to change.", &contract.view_name())
			}
			else {
				let c_name = contract.view_name().clone(); 
				contracts.insert(c_name, contract);
			}			
		}
		else {
			
			let mut cs = HashMap::<String, DependentContract>::new();
			
			let c_n = contract.view_name();
			let c_a_id = contract.view_account_id();
			
			cs.insert(c_n, contract);
			self.contract_by_contract_name_by_contract_account_id.insert(c_a_id, cs);
		}
		msg
	}	
	
	/// Deregisters the given NEAR **contract** deployed at the given NEAR blockchain **contract_account_id**
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns *String* otherwise panics  
	pub fn deregister_contract(&mut self, contract_account_id : String, contract_name : String) -> String {
		self.administrator_only ();
		let contracts = self.contract_by_contract_name_by_contract_account_id.get_mut(&contract_account_id).unwrap();
		contracts.remove(&contract_name); 
		let msg = format!("CONTRACT {} DE-REGISTERED", contract_name);
		msg
	}		
	
	/// Provides a list of list_names currently held by this instance. This will include names of **DELETED** lists 
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns *String* otherwise panics  
	pub fn view_list_names(&self) -> HashSet<String>{
		self.administrator_only();
		self.list_names.clone()
	}

		
	/// Provides a view of the list consisting of the name, type, NEAR account ids held and status of the list 
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns a tuple otherwise panics 
	pub fn view_list(&self, list_name : String) -> (/*name*/ String,  /*type*/ String, /*ids*/ HashSet<String>, /*status*/ String) { 
		self.administrator_only();
		let plist = self.lists.get(&list_name).unwrap();
		plist.get_tuple()
	}
   	

	/// Provides a view of the currently assigned role administrator for this instance 
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns a *String* otherwise panics
	pub fn view_role_administrator(&self)-> String{
		self.role_administrator.clone()
	}

	
	/// Sets the role administrator for this instance MUST be set after deployment
	/// <br/> *Administrator Only function*
	/// # Return Value 
	/// This function returns a *String* otherwise panics
	pub fn set_role_administrator(&mut self, account_id : String) -> bool { 
		if self.role_administrator.clone().as_bytes() == "".as_bytes() { // if unset
			self.role_administrator = account_id;
			true
		}
		else {
			self.administrator_only();
			self.role_administrator = account_id; 
			true
		}
	}	

	/// Sets the id for this instance MUST be set after deployment
	/// <br/> *Administrator Only function* 
	/// # Return Value 
	/// *true* if the instance 'id' is set
	pub fn set_instance_id(&mut self, instance_id : String) -> bool { 
		self.administrator_only();
		self.id = instance_id; 
		true 
	}

	/// Sets the affirmative code for this instance MUST be set after deployment
	/// <br/> *Administrator Only function* 
	/// # Return Value 
	/// This function rturns a *String* message
	pub fn set_affirmative_code(&mut self, affirmative : i32) -> String {
		self.administrator_only();
		self.affirmative = affirmative; 
		format!(" AFFIRMATIVE CODE : {} ", affirmative).to_string()
	}

	/// Sets the negative code for this instance MUST be set after deployment
	/// <br/> *Administrator Only function* 
	/// # Return Value 
	/// This function rturns a *String* message
	pub fn set_negative_code(&mut self, negative : i32) -> String {
		self.administrator_only();
		self.negative = negative;
		format!(" NEGATIVE CODE : {} ", negative).to_string()
	}

	/// Creates a default instance of the OpenRoles contract
	pub fn new() -> Self {
		Self {
			role_administrator : env::current_account_id().to_string(),
			id : format!("OBEI OPEN ROLES: {}-{}", env::current_account_id().to_string(), Utc::now().timestamp_millis()).to_string(),
			contract_by_contract_name_by_contract_account_id : HashMap::<String, HashMap<String, DependentContract>>::new(),
			lists : HashMap::<String, or_structs::ParticipantList>::new(),
			list_names : HashSet::<String>::new(),
			operation_assignment_address_by_list : HashMap::<String, HashSet<AssignmentAddress>>::new(),
			affirmative : 1, 
			negative : 0,
		}
	}	

	/// Creates a new instance of the OpenRoles contract 
	pub fn default() -> Self {
		OpenRoles::new()
	}

	fn check_status( base : String, required : String) {
		if base.as_bytes() == required.as_bytes() {
			return; 
		}
		panic!("INVALID STATUS REQUIRED : {}, PRESENTED : {} " ,required, base );
	}
	 
	fn administrator_only(&self) -> bool {
		if self.role_administrator == "" {
			panic!( "ADMINISTRATOR NOT SET");
		}

		let caller = env::signer_account_id().to_string();
		if caller.as_bytes() == self.role_administrator.to_string().as_bytes() {
			return true; 	
		}	
		panic!( "ROLE ADMINISTRATOR ONLY");
	
	}

}