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 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
// Copyright 2022 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
#![cfg_attr(not(feature = "std"), no_std)]
mod median;
pub mod traits;
mod types;
mod weights;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub use pallet::*;
pub use traits::*;
pub use types::*;
pub use weights::WeightInfo;
use frame_support::traits::StorageVersion;
use sp_distance::{InherentError, INHERENT_IDENTIFIER};
use sp_inherents::{InherentData, InherentIdentifier};
use sp_runtime::traits::One;
use sp_runtime::traits::Zero;
use sp_runtime::Saturating;
use sp_std::convert::TryInto;
use sp_std::prelude::*;
type IdtyIndex = u32;
/// Maximum number of identities to be evaluated in an evaluation period.
pub const MAX_EVALUATIONS_PER_SESSION: u32 = 1_300; // See https://git.duniter.org/nodes/rust/duniter-v2s/-/merge_requests/252
/// Maximum number of evaluators in an evaluation period.
pub const MAX_EVALUATORS_PER_SESSION: u32 = 100;
#[frame_support::pallet()]
pub mod pallet {
use super::*;
use frame_support::{pallet_prelude::*, traits::ReservableCurrency};
use frame_system::pallet_prelude::*;
use sp_runtime::Perbill;
/// The current storage version.
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::config]
pub trait Config:
frame_system::Config
+ pallet_authorship::Config
+ pallet_identity::Config<IdtyIndex = IdtyIndex>
{
/// Currency type used in this pallet (used for reserve/slash)
type Currency: ReservableCurrency<Self::AccountId>;
/// Amount reserved during evaluation
#[pallet::constant]
type EvaluationPrice: Get<
<Self::Currency as frame_support::traits::Currency<Self::AccountId>>::Balance,
>;
/// Evaluation period number of blocks.
/// As the evaluation is done using 3 pools,
/// the evaluation will take 3 * EvaluationPeriod.
#[pallet::constant]
type EvaluationPeriod: Get<u32>;
/// Maximum distance used to define referee's accessibility
/// Unused by runtime but needed by client distance oracle
#[pallet::constant]
type MaxRefereeDistance: Get<u32>;
/// Minimum ratio of accessible referees
#[pallet::constant]
type MinAccessibleReferees: Get<Perbill>;
/// The overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Type representing the weight of this pallet
type WeightInfo: WeightInfo;
/// Handler for successful distance evaluation
type OnValidDistanceStatus: OnValidDistanceStatus<Self>;
/// Trait to check that distance evaluation request is allowed
type CheckRequestDistanceEvaluation: CheckRequestDistanceEvaluation<Self>;
}
// STORAGE //
/// Identities queued for distance evaluation
#[pallet::storage]
#[pallet::getter(fn evaluation_pool_0)]
pub type EvaluationPool0<T: Config> = StorageValue<
_,
EvaluationPool<
<T as frame_system::Config>::AccountId,
<T as pallet_identity::Config>::IdtyIndex,
>,
ValueQuery,
>;
/// Identities queued for distance evaluation
#[pallet::storage]
#[pallet::getter(fn evaluation_pool_1)]
pub type EvaluationPool1<T: Config> = StorageValue<
_,
EvaluationPool<
<T as frame_system::Config>::AccountId,
<T as pallet_identity::Config>::IdtyIndex,
>,
ValueQuery,
>;
/// Identities queued for distance evaluation
#[pallet::storage]
#[pallet::getter(fn evaluation_pool_2)]
pub type EvaluationPool2<T: Config> = StorageValue<
_,
EvaluationPool<
<T as frame_system::Config>::AccountId,
<T as pallet_identity::Config>::IdtyIndex,
>,
ValueQuery,
>;
/// Block for which the distance rule must be checked
#[pallet::storage]
pub type EvaluationBlock<T: Config> =
StorageValue<_, <T as frame_system::Config>::Hash, ValueQuery>;
/// Pending evaluation requesters
///
/// account who requested an evaluation and reserved the price,
/// for whom the price will be unreserved or slashed when the evaluation completes.
#[pallet::storage]
#[pallet::getter(fn pending_evaluation_request)]
pub type PendingEvaluationRequest<T: Config> = StorageMap<
_,
Twox64Concat,
<T as pallet_identity::Config>::IdtyIndex,
<T as frame_system::Config>::AccountId,
OptionQuery,
>;
/// Did evaluation get updated in this block?
#[pallet::storage]
pub(super) type DidUpdate<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Current evaluation pool.
#[pallet::storage]
#[pallet::getter(fn current_pool_index)]
pub(super) type CurrentPoolIndex<T: Config> = StorageValue<_, u32, ValueQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A distance evaluation was requested.
EvaluationRequested {
idty_index: T::IdtyIndex,
who: T::AccountId,
},
/// Distance rule was found valid.
EvaluatedValid {
idty_index: T::IdtyIndex,
distance: Perbill,
},
/// Distance rule was found invalid.
EvaluatedInvalid {
idty_index: T::IdtyIndex,
distance: Perbill,
},
}
// ERRORS //
#[pallet::error]
pub enum Error<T> {
/// Distance is already under evaluation.
AlreadyInEvaluation,
/// Too many evaluations requested by author.
TooManyEvaluationsByAuthor,
/// Too many evaluations for this block.
TooManyEvaluationsInBlock,
/// No author for this block.
NoAuthor,
/// Caller has no identity.
CallerHasNoIdentity,
/// Caller identity not found.
CallerIdentityNotFound,
/// Caller not member.
CallerNotMember,
// Caller status can only be Unvalidated, Member or NotMember.
CallerStatusInvalid,
/// Target identity not found.
TargetIdentityNotFound,
/// Evaluation queue is full.
QueueFull,
/// Too many evaluators in the current evaluation pool.
TooManyEvaluators,
/// Evaluation result has a wrong length.
WrongResultLength,
/// Targeted distance evaluation request is only possible for an unvalidated identity.
TargetMustBeUnvalidated,
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(block: BlockNumberFor<T>) -> Weight
where
BlockNumberFor<T>: From<u32>,
{
let mut weight = <T as pallet::Config>::WeightInfo::on_initialize_overhead();
if block % BlockNumberFor::<T>::one().saturating_mul(T::EvaluationPeriod::get().into())
== BlockNumberFor::<T>::zero()
{
let index = (CurrentPoolIndex::<T>::get() + 1) % 3;
CurrentPoolIndex::<T>::put(index);
weight = weight
.saturating_add(Self::do_evaluation(index))
.saturating_add(T::DbWeight::get().reads_writes(1, 1));
}
weight.saturating_add(<T as pallet::Config>::WeightInfo::on_finalize())
}
fn on_finalize(_n: BlockNumberFor<T>) {
DidUpdate::<T>::take();
}
}
// CALLS //
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Request caller identity to be evaluated
/// positive evaluation will result in claim/renew membership
/// negative evaluation will result in slash for caller
#[pallet::call_index(0)]
#[pallet::weight(<T as pallet::Config>::WeightInfo::request_distance_evaluation())]
pub fn request_distance_evaluation(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
let idty = Self::check_request_distance_evaluation_self(&who)?;
Pallet::<T>::do_request_distance_evaluation(&who, idty)?;
Ok(().into())
}
/// Request target identity to be evaluated
/// only possible for unvalidated identity
#[pallet::call_index(4)]
#[pallet::weight(<T as pallet::Config>::WeightInfo::request_distance_evaluation_for())]
pub fn request_distance_evaluation_for(
origin: OriginFor<T>,
target: T::IdtyIndex,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
Self::check_request_distance_evaluation_for(&who, target)?;
Pallet::<T>::do_request_distance_evaluation(&who, target)?;
Ok(().into())
}
/// (Inherent) Push an evaluation result to the pool
/// this is called internally by validators (= inherent)
#[pallet::call_index(1)]
#[pallet::weight(<T as pallet::Config>::WeightInfo::update_evaluation(MAX_EVALUATIONS_PER_SESSION))]
pub fn update_evaluation(
origin: OriginFor<T>,
computation_result: ComputationResult,
) -> DispatchResult {
// no origin = inherent
ensure_none(origin)?;
ensure!(
!DidUpdate::<T>::exists(),
Error::<T>::TooManyEvaluationsInBlock,
);
let author = pallet_authorship::Pallet::<T>::author().ok_or(Error::<T>::NoAuthor)?;
Pallet::<T>::do_update_evaluation(author, computation_result)?;
DidUpdate::<T>::set(true);
Ok(())
}
/// Force push an evaluation result to the pool
// (it is convenient to have this call in end2end tests)
#[pallet::call_index(2)]
#[pallet::weight(<T as pallet::Config>::WeightInfo::force_update_evaluation(MAX_EVALUATIONS_PER_SESSION))]
pub fn force_update_evaluation(
origin: OriginFor<T>,
evaluator: <T as frame_system::Config>::AccountId,
computation_result: ComputationResult,
) -> DispatchResult {
ensure_root(origin)?;
Pallet::<T>::do_update_evaluation(evaluator, computation_result)
}
/// Force set the distance evaluation status of an identity
// (it is convenient to have this in test network)
#[pallet::call_index(3)]
#[pallet::weight(<T as pallet::Config>::WeightInfo::force_valid_distance_status())]
pub fn force_valid_distance_status(
origin: OriginFor<T>,
identity: <T as pallet_identity::Config>::IdtyIndex,
) -> DispatchResult {
ensure_root(origin)?;
Self::do_valid_distance_status(identity, Perbill::one());
Ok(())
}
}
// INTERNAL FUNCTIONS //
impl<T: Config> Pallet<T> {
/// Mutate the evaluation pool containing:
/// * when this period begins: the evaluation results to be applied.
/// * when this period ends: the evaluation requests.
fn mutate_current_pool<
R,
F: FnOnce(
&mut EvaluationPool<
<T as frame_system::Config>::AccountId,
<T as pallet_identity::Config>::IdtyIndex,
>,
) -> R,
>(
index: u32,
f: F,
) -> R {
match index {
0 => EvaluationPool2::<T>::mutate(f),
1 => EvaluationPool0::<T>::mutate(f),
2 => EvaluationPool1::<T>::mutate(f),
_ => unreachable!("index < 3"),
}
}
/// Mutate the evaluation pool containing the results sent by evaluators on this period.
fn mutate_next_pool<
R,
F: FnOnce(
&mut EvaluationPool<
<T as frame_system::Config>::AccountId,
<T as pallet_identity::Config>::IdtyIndex,
>,
) -> R,
>(
index: u32,
f: F,
) -> R {
match index {
0 => EvaluationPool0::<T>::mutate(f),
1 => EvaluationPool1::<T>::mutate(f),
2 => EvaluationPool2::<T>::mutate(f),
_ => unreachable!("index < 3"),
}
}
/// Take (and leave empty) the evaluation pool containing:
/// * when this period begins: the evaluation results to be applied.
/// * when this period ends: the evaluation requests.
#[allow(clippy::type_complexity)]
fn take_current_pool(
index: u32,
) -> EvaluationPool<
<T as frame_system::Config>::AccountId,
<T as pallet_identity::Config>::IdtyIndex,
> {
match index {
0 => EvaluationPool2::<T>::take(),
1 => EvaluationPool0::<T>::take(),
2 => EvaluationPool1::<T>::take(),
_ => unreachable!("index % 3 < 3"),
}
}
/// check that request distance evaluation is allowed
fn check_request_distance_evaluation_self(
who: &T::AccountId,
) -> Result<<T as pallet_identity::Config>::IdtyIndex, DispatchError> {
// caller has an identity
let idty_index = pallet_identity::IdentityIndexOf::<T>::get(who)
.ok_or(Error::<T>::CallerHasNoIdentity)?;
let idty = pallet_identity::Identities::<T>::get(idty_index)
.ok_or(Error::<T>::CallerIdentityNotFound)?;
// caller is (Unvalidated, Member, NotMember)
ensure!(
idty.status == pallet_identity::IdtyStatus::Unvalidated
|| idty.status == pallet_identity::IdtyStatus::Member
|| idty.status == pallet_identity::IdtyStatus::NotMember,
Error::<T>::CallerStatusInvalid
);
Self::check_request_distance_evaluation_common(idty_index)?;
Ok(idty_index)
}
/// check that targeted request distance evaluation is allowed
fn check_request_distance_evaluation_for(
who: &T::AccountId,
target: <T as pallet_identity::Config>::IdtyIndex,
) -> Result<(), DispatchError> {
// caller has an identity
let caller_idty_index = pallet_identity::IdentityIndexOf::<T>::get(who)
.ok_or(Error::<T>::CallerHasNoIdentity)?;
let caller_idty = pallet_identity::Identities::<T>::get(caller_idty_index)
.ok_or(Error::<T>::CallerIdentityNotFound)?;
// caller is member
ensure!(
caller_idty.status == pallet_identity::IdtyStatus::Member,
Error::<T>::CallerNotMember
);
// target has an identity
let target_idty = pallet_identity::Identities::<T>::get(target)
.ok_or(Error::<T>::TargetIdentityNotFound)?;
// target is unvalidated
ensure!(
target_idty.status == pallet_identity::IdtyStatus::Unvalidated,
Error::<T>::TargetMustBeUnvalidated
);
Self::check_request_distance_evaluation_common(target)?;
Ok(())
}
// common checks between check_request_distance_evaluation _self and _for
fn check_request_distance_evaluation_common(
target: <T as pallet_identity::Config>::IdtyIndex,
) -> Result<(), DispatchError> {
// no pending evaluation request
ensure!(
PendingEvaluationRequest::<T>::get(target).is_none(),
Error::<T>::AlreadyInEvaluation
);
// external validation (wot)
// - membership renewal antispam
// - target has received enough certifications
T::CheckRequestDistanceEvaluation::check_request_distance_evaluation(target)
}
/// request distance evaluation in current pool
fn do_request_distance_evaluation(
who: &T::AccountId,
idty_index: <T as pallet_identity::Config>::IdtyIndex,
) -> Result<(), DispatchError> {
Pallet::<T>::mutate_current_pool(CurrentPoolIndex::<T>::get(), |current_pool| {
// extrinsics are transactional by default, this check might not be needed
ensure!(
current_pool.evaluations.len() < (MAX_EVALUATIONS_PER_SESSION as usize),
Error::<T>::QueueFull
);
T::Currency::reserve(who, <T as Config>::EvaluationPrice::get())?;
current_pool
.evaluations
.try_push((idty_index, median::MedianAcc::new()))
.map_err(|_| Error::<T>::QueueFull)?;
PendingEvaluationRequest::<T>::insert(idty_index, who);
Self::deposit_event(Event::EvaluationRequested {
idty_index,
who: who.clone(),
});
Ok(())
})
}
/// update distance evaluation in next pool
fn do_update_evaluation(
evaluator: <T as frame_system::Config>::AccountId,
computation_result: ComputationResult,
) -> DispatchResult {
Pallet::<T>::mutate_next_pool(CurrentPoolIndex::<T>::get(), |result_pool| {
// evaluation must be provided for all identities (no more, no less)
ensure!(
computation_result.distances.len() == result_pool.evaluations.len(),
Error::<T>::WrongResultLength
);
// insert the evaluator if not already there
if result_pool
.evaluators
.try_insert(evaluator.clone())
.map_err(|_| Error::<T>::TooManyEvaluators)?
{
// update the median accumulator with the new result
for (distance_value, (_identity, median_acc)) in computation_result
.distances
.into_iter()
.zip(result_pool.evaluations.iter_mut())
{
median_acc.push(distance_value);
}
Ok(())
} else {
// one author can only submit one evaluation
Err(Error::<T>::TooManyEvaluationsByAuthor.into())
}
})
}
/// Set the distance status using IdtyIndex and AccountId
pub fn do_valid_distance_status(
idty: <T as pallet_identity::Config>::IdtyIndex,
distance: Perbill,
) {
// callback
T::OnValidDistanceStatus::on_valid_distance_status(idty);
// deposit event
Self::deposit_event(Event::EvaluatedValid {
idty_index: idty,
distance,
});
}
pub fn do_evaluation(index: u32) -> Weight {
let mut weight = <T as pallet::Config>::WeightInfo::do_evaluation_overhead();
// set evaluation block
EvaluationBlock::<T>::set(frame_system::Pallet::<T>::parent_hash());
// Apply the results from the current pool (which was previous period's result pool)
// We take the results so the pool is left empty for the new period.
#[allow(clippy::type_complexity)]
let current_pool: EvaluationPool<
<T as frame_system::Config>::AccountId,
<T as pallet_identity::Config>::IdtyIndex,
> = Pallet::<T>::take_current_pool(index);
for (idty, median_acc) in current_pool.evaluations.into_iter() {
let mut distance_result: Option<Perbill> = None;
// Retrieve the result of the computation from the median accumulator
if let Some(median_result) = median_acc.get_median() {
let distance = match median_result {
MedianResult::One(m) => m,
MedianResult::Two(m1, m2) => m1 + (m2 - m1) / 2, // Avoid overflow (since max is 1)
};
// Update distance result
distance_result = Some(distance);
}
// If there's a pending evaluation request with the provided identity
if let Some(requester) = PendingEvaluationRequest::<T>::take(idty) {
// If distance_result is available
if let Some(distance) = distance_result {
if distance >= T::MinAccessibleReferees::get() {
// Positive result, unreserve and apply
T::Currency::unreserve(
&requester,
<T as Config>::EvaluationPrice::get(),
);
Self::do_valid_distance_status(idty, distance);
weight = weight.saturating_add(
<T as pallet::Config>::WeightInfo::do_evaluation_success()
.saturating_sub(
<T as pallet::Config>::WeightInfo::do_evaluation_overhead(),
),
);
} else {
// Negative result, slash and deposit event
let _ = T::Currency::slash_reserved(
&requester,
<T as Config>::EvaluationPrice::get(),
);
Self::deposit_event(Event::EvaluatedInvalid {
idty_index: idty,
distance,
});
weight = weight.saturating_add(
<T as pallet::Config>::WeightInfo::do_evaluation_failure()
.saturating_sub(
<T as pallet::Config>::WeightInfo::do_evaluation_overhead(),
),
);
}
} else {
// No result, unreserve
T::Currency::unreserve(&requester, <T as Config>::EvaluationPrice::get());
weight = weight.saturating_add(
<T as pallet::Config>::WeightInfo::do_evaluation_failure()
.saturating_sub(
<T as pallet::Config>::WeightInfo::do_evaluation_overhead(),
),
);
}
}
// If evaluation happened without request, it's ok to do nothing
}
weight
}
}
#[pallet::inherent]
impl<T: Config> ProvideInherent for Pallet<T> {
type Call = Call<T>;
type Error = InherentError;
const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
fn create_inherent(data: &InherentData) -> Option<Self::Call> {
data.get_data::<ComputationResult>(&INHERENT_IDENTIFIER)
.expect("Distance inherent data not correctly encoded")
.map(|inherent_data| Call::update_evaluation {
computation_result: inherent_data,
})
}
fn is_inherent(call: &Self::Call) -> bool {
matches!(call, Self::Call::update_evaluation { .. })
}
}
}