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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// KILT Blockchain – https://botlabs.org
// Copyright (C) 2019-2024 BOTLabs GmbH

// The KILT Blockchain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The KILT Blockchain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

// If you feel like getting in touch with us, you can do so at info@botlabs.org

//! # Pallet storing unique nickname <-> DID links for user-friendly DID
//! nicknames.

#![cfg_attr(not(feature = "std"), no_std)]

mod default_weights;

pub mod migrations;
pub mod web3_name;

#[cfg(any(test, feature = "runtime-benchmarks"))]
mod mock;
#[cfg(any(test, feature = "try-runtime"))]
mod try_state;

#[cfg(test)]
mod tests;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;

pub use crate::{default_weights::WeightInfo, pallet::*};

#[frame_support::pallet]
pub mod pallet {
	use frame_support::{
		pallet_prelude::*,
		sp_runtime::SaturatedConversion,
		traits::{
			fungible::{Inspect, InspectHold, MutateHold},
			StorageVersion,
		},
		Blake2_128Concat,
	};
	use frame_system::pallet_prelude::*;
	use parity_scale_codec::FullCodec;
	use sp_runtime::DispatchError;
	use sp_std::{fmt::Debug, vec::Vec};

	use kilt_support::{
		traits::{BalanceMigrationManager, CallSources, StorageDepositCollector},
		Deposit,
	};

	use super::WeightInfo;
	use crate::web3_name::Web3NameOwnership;

	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);

	pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
	pub type Web3NameOwnerOf<T> = <T as Config>::Web3NameOwner;
	pub type Web3NameInput<T> = BoundedVec<u8, <T as Config>::MaxNameLength>;
	pub type Web3NameOf<T> = <T as Config>::Web3Name;
	pub type Web3OwnershipOf<T> =
		Web3NameOwnership<Web3NameOwnerOf<T>, Deposit<AccountIdOf<T>, BalanceOf<T>>, BlockNumberFor<T>>;

	pub(crate) type BalanceMigrationManagerOf<T> = <T as Config>::BalanceMigrationManager;
	pub(crate) type CurrencyOf<T> = <T as Config>::Currency;
	pub type BalanceOf<T> = <CurrencyOf<T> as Inspect<AccountIdOf<T>>>::Balance;

	#[pallet::pallet]
	#[pallet::storage_version(STORAGE_VERSION)]
	pub struct Pallet<T>(_);

	/// Map of name -> ownership details.
	#[pallet::storage]
	#[pallet::getter(fn owner)]
	pub type Owner<T> = StorageMap<_, Blake2_128Concat, Web3NameOf<T>, Web3OwnershipOf<T>>;

	/// Map of owner -> name.
	#[pallet::storage]
	#[pallet::getter(fn names)]
	pub type Names<T> = StorageMap<_, Blake2_128Concat, Web3NameOwnerOf<T>, Web3NameOf<T>>;

	/// Map of name -> ().
	///
	/// If a name key is present, the name is currently banned.
	#[pallet::storage]
	#[pallet::getter(fn is_banned)]
	pub type Banned<T> = StorageMap<_, Blake2_128Concat, Web3NameOf<T>, ()>;

	#[pallet::composite_enum]
	pub enum HoldReason {
		Deposit,
	}

	#[pallet::config]
	pub trait Config: frame_system::Config {
		/// The origin allowed to ban names.
		type BanOrigin: EnsureOrigin<Self::RuntimeOrigin>;
		/// The origin allowed to perform regular operations.
		type OwnerOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin, Success = Self::OriginSuccess>;
		/// The type of origin after a successful origin check.
		type OriginSuccess: CallSources<AccountIdOf<Self>, Web3NameOwnerOf<Self>>;
		/// Aggregated hold reason.
		type RuntimeHoldReason: From<HoldReason>;
		/// The currency type to reserve and release deposits.
		type Currency: MutateHold<AccountIdOf<Self>, Reason = Self::RuntimeHoldReason>;
		/// The amount of KILT to deposit to claim a name.
		#[pallet::constant]
		type Deposit: Get<BalanceOf<Self>>;
		/// The overarching event type.
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
		/// The min encoded length of a name.
		#[pallet::constant]
		type MinNameLength: Get<u32>;
		/// The max encoded length of a name.
		#[pallet::constant]
		type MaxNameLength: Get<u32>;
		// FIXME: Refactor the definition of AsciiWeb3Name so that we don't need to
		// require `Ord` here
		/// The type of a name.
		type Web3Name: FullCodec
			+ Debug
			+ PartialEq
			+ Clone
			+ TypeInfo
			+ TryFrom<Vec<u8>, Error = Error<Self>>
			+ MaxEncodedLen
			+ Ord;
		/// The type of a name owner.
		type Web3NameOwner: Parameter + MaxEncodedLen;
		/// Weight information for extrinsics in this pallet.
		type WeightInfo: WeightInfo;

		/// Migration manager to handle new created entries
		type BalanceMigrationManager: BalanceMigrationManager<AccountIdOf<Self>, BalanceOf<Self>>;
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	pub enum Event<T: Config> {
		/// A new name has been claimed.
		Web3NameClaimed {
			owner: Web3NameOwnerOf<T>,
			name: Web3NameOf<T>,
		},
		/// A name has been released.
		Web3NameReleased {
			owner: Web3NameOwnerOf<T>,
			name: Web3NameOf<T>,
		},
		/// A name has been banned.
		Web3NameBanned { name: Web3NameOf<T> },
		/// A name has been unbanned.
		Web3NameUnbanned { name: Web3NameOf<T> },
	}

	#[pallet::error]
	pub enum Error<T> {
		/// The tx submitter does not have enough funds to pay for the deposit.
		InsufficientFunds,
		/// The specified name has already been previously claimed.
		AlreadyExists,
		/// The specified name does not exist.
		NotFound,
		/// The specified owner already owns a name.
		OwnerAlreadyExists,
		/// The specified owner does not own any names.
		OwnerNotFound,
		/// The specified name has been banned and cannot be interacted
		/// with.
		Banned,
		/// The specified name is not currently banned.
		NotBanned,
		/// The specified name has already been previously banned.
		AlreadyBanned,
		/// The actor cannot performed the specified operation.
		NotAuthorized,
		/// A name that is too short is being claimed.
		TooShort,
		/// A name that is too long is being claimed.
		TooLong,
		/// A name that contains not allowed characters is being claimed.
		InvalidCharacter,
	}

	#[pallet::hooks]
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
		#[cfg(feature = "try-runtime")]
		fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
			crate::try_state::do_try_state::<T>()
		}
	}

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Assign the specified name to the owner as specified in the
		/// origin.
		///
		/// The name must not have already been claimed by someone else and the
		/// owner must not already own another name.
		///
		/// Emits `Web3NameClaimed` if the operation is carried out
		/// successfully.
		///
		/// # <weight>
		/// Weight: O(1)
		/// - Reads: Names, Owner, Banned storage entries + available currency
		///   check + origin check
		/// - Writes: Names, Owner storage entries + currency deposit reserve
		/// # </weight>
		#[pallet::call_index(0)]
		#[pallet::weight(<T as Config>::WeightInfo::claim(name.len().saturated_into()))]
		pub fn claim(origin: OriginFor<T>, name: Web3NameInput<T>) -> DispatchResult {
			let origin = T::OwnerOrigin::ensure_origin(origin)?;
			let payer = origin.sender();
			let owner = origin.subject();

			let decoded_name = Self::check_claiming_preconditions(name, &owner, &payer)?;

			Self::register_name(decoded_name, owner, payer)?;

			Ok(())
		}

		/// Release the provided name from its owner.
		///
		/// The origin must be the owner of the specified name.
		///
		/// Emits `Web3NameReleased` if the operation is carried out
		/// successfully.
		///
		/// # <weight>
		/// Weight: O(1)
		/// - Reads: Names storage entry + origin check
		/// - Writes: Names, Owner storage entries + currency deposit release
		/// # </weight>
		#[pallet::call_index(1)]
		#[pallet::weight(<T as Config>::WeightInfo::release_by_owner())]
		pub fn release_by_owner(origin: OriginFor<T>) -> DispatchResult {
			let origin = T::OwnerOrigin::ensure_origin(origin)?;
			let owner = origin.subject();

			let owned_name = Self::check_releasing_preconditions(&owner)?;

			Self::unregister_name(&owned_name)?;

			Ok(())
		}

		/// Release the provided name from its owner.
		///
		/// The origin must be the account that paid for the name's deposit.
		///
		/// Emits `Web3NameReleased` if the operation is carried out
		/// successfully.
		///
		/// # <weight>
		/// Weight: O(1)
		/// - Reads: Owner storage entry + origin check
		/// - Writes: Names, Owner storage entries + currency deposit release
		/// # </weight>
		#[pallet::call_index(2)]
		#[pallet::weight(<T as Config>::WeightInfo::reclaim_deposit(name.len().saturated_into()))]
		pub fn reclaim_deposit(origin: OriginFor<T>, name: Web3NameInput<T>) -> DispatchResult {
			let caller = ensure_signed(origin)?;

			let decoded_name = Self::check_reclaim_deposit_preconditions(name, &caller)?;

			Self::unregister_name(&decoded_name)?;

			Ok(())
		}

		/// Ban a name.
		///
		/// A banned name cannot be claimed by anyone. The name's deposit
		/// is returned to the original payer.
		///
		/// The origin must be the ban origin.
		///
		/// Emits `Web3NameBanned` if the operation is carried out
		/// successfully.
		///
		/// # <weight>
		/// Weight: O(1)
		/// - Reads: Banned, Owner, Names storage entries + origin check
		/// - Writes: Names, Owner, Banned storage entries + currency deposit
		///   release
		/// # </weight>
		#[pallet::call_index(3)]
		#[pallet::weight(<T as Config>::WeightInfo::ban(name.len().saturated_into()))]
		pub fn ban(origin: OriginFor<T>, name: Web3NameInput<T>) -> DispatchResult {
			T::BanOrigin::ensure_origin(origin)?;

			let (decoded_name, is_claimed) = Self::check_banning_preconditions(name)?;

			if is_claimed {
				Self::unregister_name(&decoded_name)?;
			}

			Self::ban_name(&decoded_name);
			Self::deposit_event(Event::<T>::Web3NameBanned { name: decoded_name });

			Ok(())
		}

		/// Unban a name.
		///
		/// Make a name claimable again.
		///
		/// The origin must be the ban origin.
		///
		/// Emits `Web3NameUnbanned` if the operation is carried out
		/// successfully.
		///
		/// # <weight>
		/// Weight: O(1)
		/// - Reads: Banned storage entry + origin check
		/// - Writes: Banned storage entry deposit release
		/// # </weight>
		#[pallet::call_index(4)]
		#[pallet::weight(<T as Config>::WeightInfo::unban(name.len().saturated_into()))]
		pub fn unban(origin: OriginFor<T>, name: Web3NameInput<T>) -> DispatchResult {
			T::BanOrigin::ensure_origin(origin)?;

			let decoded_name = Self::check_unbanning_preconditions(name)?;

			Self::unban_name(&decoded_name);
			Self::deposit_event(Event::<T>::Web3NameUnbanned { name: decoded_name });

			Ok(())
		}

		/// Changes the deposit owner.
		///
		/// The balance that is reserved by the current deposit owner will be
		/// freed and balance of the new deposit owner will get reserved.
		///
		/// The subject of the call must be the owner of the web3name.
		/// The sender of the call will be the new deposit owner.
		#[pallet::call_index(5)]
		#[pallet::weight(<T as Config>::WeightInfo::change_deposit_owner())]
		pub fn change_deposit_owner(origin: OriginFor<T>) -> DispatchResult {
			let source = <T as Config>::OwnerOrigin::ensure_origin(origin)?;
			let w3n_owner = source.subject();
			let name = Names::<T>::get(&w3n_owner).ok_or(Error::<T>::NotFound)?;
			Web3NameStorageDepositCollector::<T>::change_deposit_owner::<BalanceMigrationManagerOf<T>>(
				&name,
				source.sender(),
			)?;

			Ok(())
		}

		/// Updates the deposit amount to the current deposit rate.
		///
		/// The sender must be the deposit owner.
		#[pallet::call_index(6)]
		#[pallet::weight(<T as Config>::WeightInfo::update_deposit())]
		pub fn update_deposit(origin: OriginFor<T>, name_input: Web3NameInput<T>) -> DispatchResult {
			let source = ensure_signed(origin)?;
			let name = Web3NameOf::<T>::try_from(name_input.into_inner()).map_err(DispatchError::from)?;
			let w3n_entry = Owner::<T>::get(&name).ok_or(Error::<T>::NotFound)?;
			ensure!(w3n_entry.deposit.owner == source, Error::<T>::NotAuthorized);

			Web3NameStorageDepositCollector::<T>::update_deposit::<BalanceMigrationManagerOf<T>>(&name)?;

			Ok(())
		}
	}

	impl<T: Config> Pallet<T> {
		/// Verify that the claiming preconditions are verified. Specifically:
		/// - The name input data can be decoded as a valid name
		/// - The name does not already exist
		/// - The owner does not already own a name
		/// - The name has not been banned
		/// - The tx submitter has enough funds to pay the deposit
		fn check_claiming_preconditions(
			name_input: Web3NameInput<T>,
			owner: &Web3NameOwnerOf<T>,
			deposit_payer: &AccountIdOf<T>,
		) -> Result<Web3NameOf<T>, DispatchError> {
			let name = Web3NameOf::<T>::try_from(name_input.into_inner()).map_err(DispatchError::from)?;

			ensure!(!Names::<T>::contains_key(owner), Error::<T>::OwnerAlreadyExists);
			ensure!(!Owner::<T>::contains_key(&name), Error::<T>::AlreadyExists);
			ensure!(!Banned::<T>::contains_key(&name), Error::<T>::Banned);

			ensure!(
				<T::Currency as InspectHold<AccountIdOf<T>>>::can_hold(
					&HoldReason::Deposit.into(),
					deposit_payer,
					T::Deposit::get()
				),
				Error::<T>::InsufficientFunds
			);

			Ok(name)
		}

		/// Assign a name to the provided owner reserving the deposit from
		/// the provided account. This function must be called after
		/// `check_claiming_preconditions` as it does not verify all the
		/// preconditions again.
		pub fn register_name(
			name: Web3NameOf<T>,
			owner: Web3NameOwnerOf<T>,
			deposit_payer: AccountIdOf<T>,
		) -> DispatchResult {
			let block_number = frame_system::Pallet::<T>::block_number();

			let deposit = Web3NameStorageDepositCollector::<T>::create_deposit(deposit_payer, T::Deposit::get())?;
			<T as Config>::BalanceMigrationManager::exclude_key_from_migration(&Owner::<T>::hashed_key_for(&name));

			Names::<T>::insert(&owner, name.clone());
			Owner::<T>::insert(
				&name,
				Web3OwnershipOf::<T> {
					owner: owner.clone(),
					claimed_at: block_number,
					deposit,
				},
			);

			Self::deposit_event(Event::<T>::Web3NameClaimed { owner, name });
			Ok(())
		}

		/// Verify that the releasing preconditions for an owner are verified.
		/// Specifically:
		/// - The owner has a previously claimed name
		fn check_releasing_preconditions(owner: &Web3NameOwnerOf<T>) -> Result<Web3NameOf<T>, DispatchError> {
			let name = Names::<T>::get(owner).ok_or(Error::<T>::OwnerNotFound)?;

			Ok(name)
		}

		/// Verify that the releasing preconditions for a deposit payer are
		/// verified. Specifically:
		/// - The name input data can be decoded as a valid name
		/// - The name exists (i.e., it has been previous claimed)
		/// - The caller owns the name's deposit
		fn check_reclaim_deposit_preconditions(
			name_input: Web3NameInput<T>,
			caller: &AccountIdOf<T>,
		) -> Result<Web3NameOf<T>, DispatchError> {
			let name = Web3NameOf::<T>::try_from(name_input.into_inner()).map_err(DispatchError::from)?;
			let Web3NameOwnership { deposit, .. } = Owner::<T>::get(&name).ok_or(Error::<T>::NotFound)?;

			ensure!(caller == &deposit.owner, Error::<T>::NotAuthorized);

			Ok(name)
		}

		/// Release the provided name and returns the deposit to the
		/// original payer. This function must be called after
		/// `check_releasing_preconditions` as it does not verify all the
		/// preconditions again.
		fn unregister_name(name: &Web3NameOf<T>) -> Result<Web3OwnershipOf<T>, DispatchError> {
			let name_ownership = Owner::<T>::take(name).unwrap();
			Names::<T>::remove(&name_ownership.owner);

			let is_key_migrated =
				<T as Config>::BalanceMigrationManager::is_key_migrated(&Owner::<T>::hashed_key_for(name));

			if is_key_migrated {
				Web3NameStorageDepositCollector::<T>::free_deposit(name_ownership.clone().deposit)?;
			} else {
				<T as Config>::BalanceMigrationManager::release_reserved_deposit(
					&name_ownership.deposit.owner,
					&name_ownership.deposit.amount,
				)
			}

			Self::deposit_event(Event::<T>::Web3NameReleased {
				owner: name_ownership.owner.clone(),
				name: name.clone(),
			});

			Ok(name_ownership)
		}

		/// Verify that the banning preconditions are verified.
		/// Specifically:
		/// - The name input data can be decoded as a valid name
		/// - The name must not be already banned
		///
		/// If the preconditions are verified, return
		/// a tuple containing the parsed name value and whether the name
		/// being banned is currently assigned to someone or not.
		fn check_banning_preconditions(name_input: Web3NameInput<T>) -> Result<(Web3NameOf<T>, bool), DispatchError> {
			let name = Web3NameOf::<T>::try_from(name_input.into_inner()).map_err(DispatchError::from)?;

			ensure!(!Banned::<T>::contains_key(&name), Error::<T>::AlreadyBanned);

			let is_claimed = Owner::<T>::contains_key(&name);

			Ok((name, is_claimed))
		}

		/// Ban the provided name. This function must be called after
		/// `check_banning_preconditions` as it does not verify all the
		/// preconditions again.
		pub(crate) fn ban_name(name: &Web3NameOf<T>) {
			Banned::<T>::insert(name, ());
		}

		/// Verify that the unbanning preconditions are verified.
		/// Specifically:
		/// - The name input data can be decoded as a valid name
		/// - The name must have already been banned
		fn check_unbanning_preconditions(name_input: Web3NameInput<T>) -> Result<Web3NameOf<T>, DispatchError> {
			let name = Web3NameOf::<T>::try_from(name_input.into_inner()).map_err(DispatchError::from)?;

			ensure!(Banned::<T>::contains_key(&name), Error::<T>::NotBanned);

			Ok(name)
		}

		/// Unban the provided name. This function must be called after
		/// `check_unbanning_preconditions` as it does not verify all the
		/// preconditions again.
		fn unban_name(name: &Web3NameOf<T>) {
			Banned::<T>::remove(name);
		}
	}

	pub(crate) struct Web3NameStorageDepositCollector<T: Config>(PhantomData<T>);
	impl<T: Config> StorageDepositCollector<AccountIdOf<T>, T::Web3Name, T::RuntimeHoldReason>
		for Web3NameStorageDepositCollector<T>
	{
		type Currency = T::Currency;
		type Reason = HoldReason;

		fn get_hashed_key(key: &T::Web3Name) -> Result<sp_std::vec::Vec<u8>, DispatchError> {
			Ok(Owner::<T>::hashed_key_for(key))
		}

		fn reason() -> Self::Reason {
			HoldReason::Deposit
		}
		fn deposit(
			key: &T::Web3Name,
		) -> Result<Deposit<AccountIdOf<T>, <Self::Currency as Inspect<AccountIdOf<T>>>::Balance>, DispatchError> {
			let w3n_entry = Owner::<T>::get(key).ok_or(Error::<T>::NotFound)?;

			Ok(w3n_entry.deposit)
		}

		fn deposit_amount(_key: &T::Web3Name) -> <Self::Currency as Inspect<AccountIdOf<T>>>::Balance {
			T::Deposit::get()
		}

		fn store_deposit(
			key: &T::Web3Name,
			deposit: Deposit<AccountIdOf<T>, <Self::Currency as Inspect<AccountIdOf<T>>>::Balance>,
		) -> Result<(), DispatchError> {
			let w3n_entry = Owner::<T>::get(key).ok_or(Error::<T>::NotFound)?;
			Owner::<T>::insert(key, Web3OwnershipOf::<T> { deposit, ..w3n_entry });

			Ok(())
		}
	}
}