From 48a3d0a2a7dfac4dd567c89386ea5555411e4b64 Mon Sep 17 00:00:00 2001 From: gui1117 Date: Mon, 23 Nov 2026 15:34:03 -0800 Subject: [PATCH 1/4] impl --- pallets/game/src/benchmarking.rs | 2 +- pallets/game/src/lib.rs | 48 +++++---- pallets/game/src/tests.rs | 155 +++++++++++++++++++++++++++--- pallets/game/src/types.rs | 4 +- pallets/nft-credits/src/tests.rs | 4 +- pallets/score/src/benchmarking.rs | 5 +- pallets/score/src/lib.rs | 17 ++-- pallets/score/src/tests.rs | 87 +++++++++++------ pallets/score/src/types.rs | 12 ++- 9 files changed, 258 insertions(+), 76 deletions(-) diff --git a/pallets/game/src/benchmarking.rs b/pallets/game/src/benchmarking.rs index 81e8f118..100a4a16 100644 --- a/pallets/game/src/benchmarking.rs +++ b/pallets/game/src/benchmarking.rs @@ -112,7 +112,7 @@ pub mod benches { PeopleOf::::recognize_personhood(id, Some(key))?; indiv_pallet_score::Participants::::mutate(who, |p| { p.as_mut().expect("participant entry exists").recognition = - indiv_pallet_score::Recognition::Recognized(id); + indiv_pallet_score::Recognition::Recognized { id, newly_recognized: false }; }); Ok(id) } diff --git a/pallets/game/src/lib.rs b/pallets/game/src/lib.rs index f1aa2c30..3fe04868 100644 --- a/pallets/game/src/lib.rs +++ b/pallets/game/src/lib.rs @@ -186,6 +186,14 @@ //! invited player is a new, non-recognized account, so the remaining work in dispatch cannot fail //! and the invite buys a sign-up. //! +//! ## Airdrop entries of a newly recognized player +//! +//! A player that is not recognized enters the airdrop draws with [`AirdropVrfs::Account`]. A +//! player enters them with either variant from its `register` call in indiv-pallet-score until +//! the game next sets its attendance, and with [`AirdropVrfs::Alias`] in the games after that. +//! The reason is that `register` only queues the member key for a ring, so the player cannot build +//! the ring proof of the alias variant right after it. +//! //! # Statement store usage //! //! All players in the game are given some statement store usage allowance. The player's allowance @@ -334,7 +342,7 @@ use indiv_pallet_airdrop::types::{ Airdrop, EventId as AirdropEventId, EventInfo as AirdropEventInfo, ProductName as AirdropProductName, RegistrationEntry as AirdropRegistrationEntry, }; -use indiv_pallet_score::AccountOrPerson; +use indiv_pallet_score::{AccountOrPerson, Recognition}; use indiv_support::{ credit_trees::AwardCredits, offchain::{submit_authorized, TX_LONGEVITY}, @@ -2290,25 +2298,32 @@ pub mod pallet { } /// Check the count and the variant of the airdrop VRF entries against the player's - /// `recognized` state. + /// `recognition` in indiv-pallet-score. /// - /// The caller computes `recognized` itself: dispatch after onboarding, the extension - /// before it. Registration for the events is a separate step. + /// The caller reads `recognition` itself: dispatch after onboarding, the extension before + /// it. Registration for the events is a separate step. pub(crate) fn check_airdrop_shape( airdrops: &AirdropVrfs>, who: &AccountOrPerson, - recognized: bool, + recognition: Option<&Recognition>, airdrops_scheduled: u8, ) -> Result<(), AirdropShapeError> { ensure!( airdrops.count() == usize::from(airdrops_scheduled), AirdropShapeError::CountMismatch ); + let recognized = recognition.is_some_and(Recognition::is_recognized); + // A newly recognized player may supply either variant. See the module documentation. + let newly_recognized = + matches!(recognition, Some(Recognition::Recognized { newly_recognized: true, .. })); match airdrops { AirdropVrfs::Alias { .. } => ensure!(recognized, AirdropShapeError::RecognitionMismatch), AirdropVrfs::Account(_) => { - ensure!(!recognized, AirdropShapeError::RecognitionMismatch); + ensure!( + !recognized || newly_recognized, + AirdropShapeError::RecognitionMismatch + ); ensure!( matches!(who, AccountOrPerson::Account(_)), AirdropShapeError::AccountVariantForPerson @@ -2947,10 +2962,10 @@ pub mod pallet { return Ok(()); }; - let recognized = indiv_pallet_score::Participants::::get(who) + let recognition = indiv_pallet_score::Participants::::get(who) .defensive_proof("pallet-game: registering account must be a participant") - .is_some_and(|p| p.recognition.is_recognized()); - Self::check_airdrop_shape(&airdrops, who, recognized, airdrops_scheduled) + .map(|p| p.recognition); + Self::check_airdrop_shape(&airdrops, who, recognition.as_ref(), airdrops_scheduled) .map_err(Error::::from)?; match airdrops { AirdropVrfs::Account(vrfs) => { @@ -2984,8 +2999,8 @@ pub mod pallet { /// Validation-only counterpart of [`Self::register_for_airdrop`] for the `GameAsInvited` /// extension: it dry-runs the per-event registration and rolls the storage back. /// - /// The invite path is the only caller, where the player is a new account. `recognized` is - /// `false` both here, where the participant is not onboarded yet, and in + /// The invite path is the only caller, where the player is a new account. Only the account + /// variant is accepted both here, where the participant is not onboarded yet, and in /// [`Self::register_for_airdrop`], where a freshly onboarded account is `NotRecognized`. pub(crate) fn validate_register_for_airdrop( airdrops: &Option>>, @@ -3000,17 +3015,16 @@ pub mod pallet { return Ok(()); }; - let recognized = indiv_pallet_score::Participants::::get(who) + let recognition = indiv_pallet_score::Participants::::get(who) // When None, it will be onboarded as NotRecognized. - .is_some_and(|p| p.recognition.is_recognized()); + .map(|p| p.recognition); - Self::check_airdrop_shape(airdrops, who, recognized, airdrops_scheduled).map_err( - |e| match e { + Self::check_airdrop_shape(airdrops, who, recognition.as_ref(), airdrops_scheduled) + .map_err(|e| match e { AirdropShapeError::CountMismatch => InvalidAirdropVrfCount, AirdropShapeError::RecognitionMismatch | AirdropShapeError::AccountVariantForPerson => InvalidAirdropVrfVariant, - }, - )?; + })?; let res = match airdrops { AirdropVrfs::Account(vrfs) => { diff --git a/pallets/game/src/tests.rs b/pallets/game/src/tests.rs index d51809f1..6b74dfdf 100644 --- a/pallets/game/src/tests.rs +++ b/pallets/game/src/tests.rs @@ -3642,7 +3642,8 @@ fn kickout_suspends_recognized_player() { let (key, _sk) = mock_key(1234); assert_ok!(People::recognize_personhood(id, Some(key))); indiv_pallet_score::Participants::::mutate(&player, |p| { - p.as_mut().unwrap().recognition = indiv_pallet_score::Recognition::Recognized(id); + p.as_mut().unwrap().recognition = + indiv_pallet_score::Recognition::Recognized { id, newly_recognized: false }; }); ArchivedPlayers::::insert( &player, @@ -3686,7 +3687,8 @@ fn offboard_fails_when_suspension_fails() { // Make ALICE `Recognized` with a personal id that does not belong to any person, so // the suspension on offboard fails. indiv_pallet_score::Participants::::mutate(&alice, |p| { - p.as_mut().unwrap().recognition = indiv_pallet_score::Recognition::Recognized(404); + p.as_mut().unwrap().recognition = + indiv_pallet_score::Recognition::Recognized { id: 404, newly_recognized: false }; }); let err = Game::offboard(RuntimeOrigin::signed(ALICE)).unwrap_err(); @@ -3703,7 +3705,8 @@ fn kickout_fails_when_suspension_fails() { // belong to any person, so the suspension on kickout fails. assert_ok!(indiv_pallet_score::Pallet::::onboard_for_recognition(&ALICE)); indiv_pallet_score::Participants::::mutate(&player, |p| { - p.as_mut().unwrap().recognition = indiv_pallet_score::Recognition::Recognized(404); + p.as_mut().unwrap().recognition = + indiv_pallet_score::Recognition::Recognized { id: 404, newly_recognized: false }; }); ArchivedPlayers::::insert( &player, @@ -5792,8 +5795,10 @@ mod airdrop { recognition: Recognition, last_attended_game: Option, ) { - let reached = - matches!(recognition, Recognition::Recognized(_) | Recognition::ExternallyRecognized,); + let reached = matches!( + recognition, + Recognition::Recognized { .. } | Recognition::ExternallyRecognized + ); indiv_pallet_score::Participants::::insert( player, Participant { @@ -5811,6 +5816,49 @@ mod airdrop { ); } + /// The account variant for the single event `event_id`, with a VRF signature that verifies. + /// Registers a fresh sr25519 key as the public key of `account`. + fn valid_account_proofs( + account: AccountId32, + event_id: indiv_pallet_airdrop::types::EventId, + ) -> crate::AirdropVrfs<::Proof> { + let pair = sr25519::Pair::from_seed(b"valid_account_proofs_seed_______"); + register_account_pubkey(account, pair.public()); + let signature = pair.vrf_sign( + &indiv_pallet_airdrop::vrf::transcript_for_event(&event_id, &pair.public()) + .into_sign_data(), + ); + crate::AirdropVrfs::Account(vec![signature].try_into().expect("one entry fits the bound")) + } + + /// Make `account` a newly recognized player. The player is archived so that the sign-up skips + /// the onboarding. + fn force_newly_recognized(account: AccountId32) { + force_recognition( + AccountOrPerson::Account(account.clone()), + Recognition::Recognized { id: 0, newly_recognized: true }, + ); + ArchivedPlayers::::insert( + AccountOrPerson::Account(account), + ArchivedPlayer::Unkickable { first_game: 0 }, + ); + } + + /// Start a game with one airdrop event open for registration. Returns the event id. + fn new_game_with_open_airdrop() -> indiv_pallet_airdrop::types::EventId { + let schedule = GameSchedule:: { + game_play_time: 10, + rounds: 2, + max_group_size: 3, + airdrops: test_airdrops(1), + tenure_claim_window: 0, + }; + assert_ok!(Game::new_game(&schedule)); + let event_id = Game::airdrop_event_id(GameIndex::::get(), 0); + set_event_status(event_id, Status::Registering { total_participants: 0 }); + event_id + } + /// Disable the airdrop's prize asset so the next `T::Airdrop::schedule` call /// returns an error. The game pallet should swallow this error and still /// create the game. @@ -6175,6 +6223,32 @@ mod airdrop { }); } + #[test] + fn sign_up_accepts_both_variants_for_newly_recognized_player() { + new_test_ext().execute_with(|| { + let event_id = new_game_with_open_airdrop(); + force_newly_recognized(ALICE); + force_newly_recognized(BOB); + + assert_ok!(Game::sign_up_with_account( + RuntimeOrigin::signed(ALICE), + DEFAULT_IDENTIFIER_KEY, + Some(valid_account_proofs(ALICE, event_id)), + )); + assert_ok!(Game::sign_up_with_account( + RuntimeOrigin::signed(BOB), + DEFAULT_IDENTIFIER_KEY, + Some(alias_proofs(1)), + )); + let entries = + AirdropRegistrations::::iter_prefix_values(event_id).collect::>(); + assert_eq!(entries.len(), 2); + for account_id in [ALICE, BOB] { + assert!(entries.contains(&RegistrationEntry::Account { account_id })); + } + }); + } + #[test] fn sign_up_rejects_account_variant_for_recognized_player() { new_test_ext().execute_with(|| { @@ -6188,7 +6262,10 @@ mod airdrop { assert_ok!(Game::new_game(&schedule)); // Pre-recognized account player: in `Participants` as `Recognized(_)` and in // `ArchivedPlayers` so the sign-up's onboard step is skipped. - force_recognition(AccountOrPerson::Account(ALICE), Recognition::Recognized(0)); + force_recognition( + AccountOrPerson::Account(ALICE), + Recognition::Recognized { id: 0, newly_recognized: false }, + ); ArchivedPlayers::::insert( AccountOrPerson::Account(ALICE), ArchivedPlayer::Unkickable { first_game: 0 }, @@ -6204,6 +6281,33 @@ mod airdrop { }); } + #[test] + fn validate_register_for_airdrop_follows_the_recognition() { + new_test_ext().execute_with(|| { + let event_id = new_game_with_open_airdrop(); + let game_index = GameIndex::::get(); + let who = AccountOrPerson::Account(ALICE); + let account_proofs = Some(valid_account_proofs(ALICE, event_id)); + let alias_proofs = Some(alias_proofs(1)); + + force_newly_recognized(ALICE); + for proofs in [&account_proofs, &alias_proofs] { + assert!(Game::validate_register_for_airdrop(proofs, &who, game_index, 1).is_ok()); + } + // The dry runs registered nothing. + assert_eq!(AirdropRegistrations::::iter_prefix(event_id).count(), 0); + + force_recognition( + who.clone(), + Recognition::Recognized { id: 0, newly_recognized: false }, + ); + assert!(matches!( + Game::validate_register_for_airdrop(&account_proofs, &who, game_index, 1), + Err(CustomError::InvalidAirdropVrfVariant) + )); + }); + } + #[test] fn sign_up_participate_failure_rolls_back() { // If the airdrop pallet rejects the participation, the whole sign-up must roll @@ -6400,7 +6504,11 @@ mod airdrop { #[test] fn claim_rejects_when_never_attended() { new_test_ext().execute_with(|| { - force_participant(AccountOrPerson::Account(ALICE), Recognition::Recognized(0), None); + force_participant( + AccountOrPerson::Account(ALICE), + Recognition::Recognized { id: 0, newly_recognized: false }, + None, + ); assert_noop!( Game::claim_airdrop(RuntimeOrigin::signed(ALICE), 1, 0, id_to_account(99)), Error::::NotEligibleForAirdrop, @@ -6413,7 +6521,11 @@ mod airdrop { // Eligibility is `last_attended_game == Some(game_index)`. ALICE attended game 5; // claims for the previous (game 4) and the next (game 6) must both be rejected. new_test_ext().execute_with(|| { - force_participant(AccountOrPerson::Account(ALICE), Recognition::Recognized(0), Some(5)); + force_participant( + AccountOrPerson::Account(ALICE), + Recognition::Recognized { id: 0, newly_recognized: false }, + Some(5), + ); // Previous game. stage_claim_for(4, RegistrationEntry::Account { account_id: ALICE }); @@ -6487,7 +6599,8 @@ mod airdrop { let who = AccountOrPerson::Account(ALICE); assert_ok!(indiv_pallet_score::Pallet::::set_attendance(&who, true, game_index)); indiv_pallet_score::Participants::::mutate(&who, |maybe| { - maybe.as_mut().unwrap().recognition = Recognition::Recognized(0); + maybe.as_mut().unwrap().recognition = + Recognition::Recognized { id: 0, newly_recognized: false }; }); // Stage the event as `Claiming` with ALICE as the sole winner, then claim. @@ -6525,7 +6638,11 @@ mod airdrop { // Pre-recognized account player: in `Participants` as `Recognized(_)` and in // `ArchivedPlayers` so the sign-up's onboard step is skipped. - force_participant(AccountOrPerson::Account(ALICE), Recognition::Recognized(0), None); + force_participant( + AccountOrPerson::Account(ALICE), + Recognition::Recognized { id: 0, newly_recognized: false }, + None, + ); ArchivedPlayers::::insert( AccountOrPerson::Account(ALICE), ArchivedPlayer::Unkickable { first_game: 0 }, @@ -6579,7 +6696,11 @@ mod airdrop { #[test] fn claim_forwards_account_registrant() { new_test_ext().execute_with(|| { - force_participant(AccountOrPerson::Account(ALICE), Recognition::Recognized(0), Some(7)); + force_participant( + AccountOrPerson::Account(ALICE), + Recognition::Recognized { id: 0, newly_recognized: false }, + Some(7), + ); stage_claim_for(7, RegistrationEntry::Account { account_id: ALICE }); let beneficiary = id_to_account(123); let prize_amount = test_airdrop_prize().asset_amount; @@ -7223,7 +7344,11 @@ mod airdrop { fn claim_airdrop_selects_event_by_index() { new_test_ext().execute_with(|| { let alice_entry = RegistrationEntry::::Account { account_id: ALICE }; - force_participant(AccountOrPerson::Account(ALICE), Recognition::Recognized(0), Some(5)); + force_participant( + AccountOrPerson::Account(ALICE), + Recognition::Recognized { id: 0, newly_recognized: false }, + Some(5), + ); // Index 0: claimable with a winning entry for ALICE. stage_claim_for_index(5, 0, alice_entry.clone()); @@ -7261,7 +7386,11 @@ mod airdrop { fn claim_each_won_airdrop_separately() { new_test_ext().execute_with(|| { let alice_entry = RegistrationEntry::::Account { account_id: ALICE }; - force_participant(AccountOrPerson::Account(ALICE), Recognition::Recognized(0), Some(5)); + force_participant( + AccountOrPerson::Account(ALICE), + Recognition::Recognized { id: 0, newly_recognized: false }, + Some(5), + ); stage_claim_for_index(5, 0, alice_entry.clone()); stage_claim_for_index(5, 1, alice_entry.clone()); diff --git a/pallets/game/src/types.rs b/pallets/game/src/types.rs index 1021b3a9..cf54f491 100644 --- a/pallets/game/src/types.rs +++ b/pallets/game/src/types.rs @@ -183,7 +183,9 @@ pub enum AttendanceStatus { /// /// The variant picks the identity path: if the player is recognized (pallet-score `Recognition` /// is `Recognized` or `ExternallyRecognized`) then they must provide the alias variant, -/// otherwise they must provide the account variant. The variant holds exactly one entry per +/// otherwise they must provide the account variant. A newly recognized player (pallet-score +/// `Recognized` with `newly_recognized`) may provide either variant (in case the key is not +/// included in a ring yet). The variant holds exactly one entry per /// scheduled airdrop event of the game, in airdrop-index order: the entry at position `i` is /// bound to the event id of airdrop index `i` (see `Pallet::airdrop_event_id`). #[derive(Encode, Decode, TypeInfo, Debug, Clone, PartialEq, Eq)] diff --git a/pallets/nft-credits/src/tests.rs b/pallets/nft-credits/src/tests.rs index 63f3031a..4eb60e45 100644 --- a/pallets/nft-credits/src/tests.rs +++ b/pallets/nft-credits/src/tests.rs @@ -3577,7 +3577,7 @@ mod claim_tenure_credits { let id = People::reserve_new_id(); let (key, _) = mock_key(id); assert_ok!(People::recognize_personhood(id, Some(key))); - set_recognition(who, Recognition::Recognized(id)); + set_recognition(who, Recognition::Recognized { id, newly_recognized: false }); id } @@ -3593,7 +3593,7 @@ mod claim_tenure_credits { .expect("sign-up onboards the account") .recognition { - Recognition::Recognized(id) => id, + Recognition::Recognized { id, .. } => id, _ => recognise(who), }; set_recognition(who, Recognition::Suspended(id)); diff --git a/pallets/score/src/benchmarking.rs b/pallets/score/src/benchmarking.rs index 2adc6c23..9ee7670f 100644 --- a/pallets/score/src/benchmarking.rs +++ b/pallets/score/src/benchmarking.rs @@ -412,7 +412,7 @@ mod benches { let after = Participants::::get(&participant_key).expect("entry must exist"); assert!( - matches!(after.recognition, Recognition::Recognized(_)), + matches!(after.recognition, Recognition::Recognized { .. }), "participant must now be Recognized" ); @@ -498,7 +498,8 @@ mod benches { SystemOrigin::Signed(caller.clone()).into(), Some((pk, proof_of_ownership)), )?; - let Recognition::Recognized(id) = Participants::::get(&who).expect("exists").recognition + let Recognition::Recognized { id, .. } = + Participants::::get(&who).expect("exists").recognition else { return Err(BenchmarkError::Stop("participant must be Recognized")); }; diff --git a/pallets/score/src/lib.rs b/pallets/score/src/lib.rs index 71bb37b9..9dd7ae7c 100644 --- a/pallets/score/src/lib.rs +++ b/pallets/score/src/lib.rs @@ -987,10 +987,11 @@ pub mod pallet { T::People::recognize_personhood(id, Some(member_key))?; (id, false) }, - ExternallyRecognized | Recognized(_) => return Err(Error::::Recognized.into()), + ExternallyRecognized | Recognized { .. } => + return Err(Error::::Recognized.into()), }; - score.recognition = Recognized(id); + score.recognition = Recognized { id, newly_recognized: true }; score.reached_personhood = true; score.has_ever_reached_personhood = true; Participants::::insert(&who, score); @@ -1157,7 +1158,7 @@ pub mod pallet { /// entry. pub fn offboard(who: &AccountOrPerson) -> DispatchResult { let maybe_recognition = Participants::::get(who).map(|p| p.recognition); - if let Some(Recognized(id)) = maybe_recognition { + if let Some(Recognized { id, .. }) = maybe_recognition { with_storage_layer::<_, DispatchError, _>(|| { T::People::start_people_set_mutation_session()?; T::People::suspend_personhood(&[id])?; @@ -1243,6 +1244,10 @@ pub mod pallet { ) -> Result>, DispatchError> { let mut score = Participants::::get(who).ok_or(Error::::NoScore)?; + if let Recognized { newly_recognized, .. } = &mut score.recognition { + *newly_recognized = false; + } + let personhood_threshold = PersonhoodThreshold::::get(); // If they are externally recognized, their score is always set to the threshold. @@ -1256,7 +1261,7 @@ pub mod pallet { } // Counting games attended while recognized through games - if attended && matches!(score.recognition, Recognized(_)) { + if attended && matches!(score.recognition, Recognized { .. }) { score.attended_games_while_recognized = score.attended_games_while_recognized.saturating_add(1); } @@ -1296,7 +1301,7 @@ pub mod pallet { // exceeding the allowed misses within the window triggers suspension. // A window of 0 (with allowed_misses 0) means no grace: any absence // immediately suspends. - Recognized(_) => window == 0 || misses > allowed_misses, + Recognized { .. } => window == 0 || misses > allowed_misses, // NotRecognized participants additionally lose personhood when their // score drops below threshold, otherwise a stale flag would let them @@ -1311,7 +1316,7 @@ pub mod pallet { // and keeps their personhood until the next attendance where, if they are absent, the // suspension is retried. if suspend_personhood { - if let Recognized(id) = score.recognition { + if let Recognized { id, .. } = score.recognition { if T::People::suspend_personhood(&[id]).is_ok() { score.recognition = Suspended(id); } else { diff --git a/pallets/score/src/tests.rs b/pallets/score/src/tests.rs index a46ccf5c..51d1a0f4 100644 --- a/pallets/score/src/tests.rs +++ b/pallets/score/src/tests.rs @@ -1299,7 +1299,7 @@ fn recognition_flow() { )); let participant = Participants::::get(&user_key).unwrap(); let personal_id = match participant.recognition { - Recognition::Recognized(id) => id, + Recognition::Recognized { id, .. } => id, _ => panic!("Expected participant to be Recognized now"), }; @@ -1353,7 +1353,7 @@ fn recognition_flow() { assert_ok!(PalletScore::register(RuntimeOrigin::signed(user), None)); let participant = Participants::::get(&user_key).unwrap(); match participant.recognition { - Recognition::Recognized(same_id) => assert_eq!(same_id, personal_id), + Recognition::Recognized { id: same_id, .. } => assert_eq!(same_id, personal_id), _ => panic!("Expected participant recognized again"), } // Confirm People pallet => recognized again @@ -1677,7 +1677,7 @@ fn register_works_for_suspended_participant() { assert_ok!(PalletScore::register(RuntimeOrigin::signed(user), Some((key, proof)))); let participant = Participants::::get(&who).unwrap(); let id = match participant.recognition { - Recognized(id) => id, + Recognized { id, .. } => id, _ => panic!("expected participant to be Recognized after registration"), }; @@ -1706,7 +1706,7 @@ fn register_works_for_suspended_participant() { // Should succeed now. assert_ok!(PalletScore::register(RuntimeOrigin::signed(user), None)); let participant = Participants::::get(&who).unwrap(); - assert_eq!(participant.recognition, Recognized(id)); + assert_eq!(participant.recognition, Recognized { id, newly_recognized: true }); assert!(participant.reached_personhood); assert!(participant.has_ever_reached_personhood); System::assert_last_event( @@ -1777,7 +1777,7 @@ fn offboard_fails_when_suspension_fails() { // suspension on offboard fails. PalletScore::onboard_for_recognition(&user).unwrap(); Participants::::mutate(&who, |p| { - p.as_mut().unwrap().recognition = Recognized(404); + p.as_mut().unwrap().recognition = Recognized { id: 404, newly_recognized: false }; }); assert_noop!(PalletScore::offboard(&who), indiv_pallet_people::Error::::NotPerson); @@ -1807,7 +1807,7 @@ fn set_attendance_retries_suspension_after_failure() { assert_ok!(PalletScore::onboard_for_recognition(&user)); Participants::::mutate(&who, |p| { let p = p.as_mut().unwrap(); - p.recognition = Recognized(0); + p.recognition = Recognized { id: 0, newly_recognized: false }; p.reached_personhood = true; p.score = 21; }); @@ -1825,7 +1825,7 @@ fn set_attendance_retries_suspension_after_failure() { // their personhood. attend(&who, false); let p = Participants::::get(&who).unwrap(); - assert_eq!(p.recognition, Recognized(0)); + assert_eq!(p.recognition, Recognized { id: 0, newly_recognized: false }); assert!(p.reached_personhood); // The person with that id now exists. @@ -1900,7 +1900,7 @@ fn register_works_for_not_recognized_participant() { // Should succeed now. assert_ok!(PalletScore::register(RuntimeOrigin::signed(user), Some((key, proof)))); let participant = Participants::::get(&who).unwrap(); - assert!(matches!(participant.recognition, Recognized(_))); + assert!(matches!(participant.recognition, Recognized { newly_recognized: true, .. })); assert!(participant.reached_personhood); assert!(participant.has_ever_reached_personhood); System::assert_last_event( @@ -1950,7 +1950,7 @@ fn setup_recognised_person(user: u64) -> (AccountOrPerson, u64) { let participant = Participants::::get(&who).unwrap(); let personal_id = match participant.recognition { - Recognized(id) => id, + Recognized { id, .. } => id, _ => panic!("Expected Recognized"), }; @@ -1989,7 +1989,7 @@ fn grace_ratio_suspension() { attend(&who, false); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(_)), + matches!(p.recognition, Recognized { .. }), "should remain Recognized after {i} misses (allowed_misses=5)" ); assert!(p.reached_personhood); @@ -2007,6 +2007,26 @@ fn grace_ratio_suspension() { } /// Attending pushes misses out of the rolling window, preventing suspension. +#[test] +fn set_attendance_ends_the_newly_recognized_state() { + new_test_ext().execute_with(|| { + set_active_members(100); // grace ratio = (5, 6): one absence does not suspend + let (who, id) = setup_recognised_person(99); + assert_eq!( + Participants::::get(&who).unwrap().recognition, + Recognized { id, newly_recognized: true } + ); + + // An absence ends the state as an attendance does. + attend(&who, false); + + assert_eq!( + Participants::::get(&who).unwrap().recognition, + Recognized { id, newly_recognized: false } + ); + }); +} + #[test] fn attendance_within_window_prevents_suspension() { new_test_ext().execute_with(|| { @@ -2019,19 +2039,19 @@ fn attendance_within_window_prevents_suspension() { attend(&who, false); } let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(_)), "still Recognized after 5 misses"); + assert!(matches!(p.recognition, Recognized { .. }), "still Recognized after 5 misses"); // Attend once — window still has 5 misses out of 6, but within allowance. attend(&who, true); let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(_)), "still Recognized after recovery"); + assert!(matches!(p.recognition, Recognized { .. }), "still Recognized after recovery"); // Keep missing — the single attendance stays in the window, capping misses at 5. for _ in 0..5 { attend(&who, false); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(_)), + matches!(p.recognition, Recognized { .. }), "still Recognized — attendance keeps misses within allowance" ); } @@ -2121,7 +2141,7 @@ fn large_network_second_miss_in_window_suspends() { // First miss: 1 miss in 6, within allowance. attend(&who, false); let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(_)), "1 miss in 6 is tolerated"); + assert!(matches!(p.recognition, Recognized { .. }), "1 miss in 6 is tolerated"); // Attend a few then miss again: 2 misses in window of 6. attend(&who, true); @@ -2151,10 +2171,10 @@ fn grace_ratio_window_three_full_cycle() { // First two misses: 2 misses in 3, within allowance. attend(&who, false); let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(_))); + assert!(matches!(p.recognition, Recognized { .. })); attend(&who, false); let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(_))); + assert!(matches!(p.recognition, Recognized { .. })); assert!(p.reached_personhood); // Third miss: 3 misses in window of 3, exceeds allowance → suspended. @@ -2184,7 +2204,7 @@ fn grace_ratio_window_three_full_cycle() { assert_ok!(PalletScore::register(RuntimeOrigin::signed(99), None)); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(id) if id == personal_id), + matches!(p.recognition, Recognized { id, .. } if id == personal_id), "register(None) should resume personhood with same id" ); assert!(p.reached_personhood); @@ -2207,7 +2227,7 @@ fn grace_ratio_window_two_full_cycle() { // First miss: 1/2, tolerated. attend(&who, false); let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(_))); + assert!(matches!(p.recognition, Recognized { .. })); assert!(p.reached_personhood); // Score: started at 15, lost 1 => 14. assert_eq!(p.score, 14); @@ -2240,7 +2260,7 @@ fn grace_ratio_window_two_full_cycle() { assert_ok!(PalletScore::register(RuntimeOrigin::signed(99), None)); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(id) if id == personal_id), + matches!(p.recognition, Recognized { id, .. } if id == personal_id), "register(None) should resume personhood with same ID" ); assert!(p.reached_personhood); @@ -2264,7 +2284,7 @@ fn grace_ratio_large_network_full_cycle() { // First miss: 1/6, tolerated. attend(&who, false); let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(_))); + assert!(matches!(p.recognition, Recognized { .. })); // Score: started at 21 (capped), lost 1 => 20. assert_eq!(p.score, 20); @@ -2296,7 +2316,7 @@ fn grace_ratio_large_network_full_cycle() { assert_ok!(PalletScore::register(RuntimeOrigin::signed(99), None)); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(id) if id == personal_id), + matches!(p.recognition, Recognized { id, .. } if id == personal_id), "register(None) should resume personhood with same ID" ); @@ -2306,7 +2326,7 @@ fn grace_ratio_large_network_full_cycle() { attend(&who, true); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(_)), + matches!(p.recognition, Recognized { .. }), "should remain Recognized after attendance {i}" ); assert!(p.reached_personhood); @@ -2327,7 +2347,7 @@ fn attending_does_not_suspend() { for _ in 0..8 { attend(&who, true); let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(_))); + assert!(matches!(p.recognition, Recognized { .. })); assert!(p.reached_personhood); } }); @@ -2607,7 +2627,10 @@ fn force_set_attendance_absence_suspends_recognised_person() { new_test_ext().execute_with(|| { advance_to(1); let (who, personal_id) = setup_recognised_person(7); - assert_eq!(Participants::::get(&who).unwrap().recognition, Recognized(personal_id)); + assert_eq!( + Participants::::get(&who).unwrap().recognition, + Recognized { id: personal_id, newly_recognized: true } + ); // No grace: any absence suspends. let schedule: AbsenceGraceTiers = BoundedVec::try_from(vec![AbsenceGraceTier { @@ -2834,7 +2857,7 @@ fn mid_session_schedule_tightening_does_not_affect_current_session() { } let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(_)), + matches!(p.recognition, Recognized { .. }), "still recognized after 5 misses under (5,6)" ); // Start a new session (caches ratio), then tighten the schedule mid-session. @@ -2857,7 +2880,7 @@ fn mid_session_schedule_tightening_does_not_affect_current_session() { People::on_poll(System::block_number(), &mut WeightMeter::new()); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(_)), + matches!(p.recognition, Recognized { .. }), "still recognized: mid-session change did not affect current session" ); // Next session picks up the strict (0, 0) ratio. Any absence now suspends. @@ -2892,7 +2915,7 @@ fn schedule_relaxation_saves_participant_next_session() { attend(&who, false); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(_)), + matches!(p.recognition, Recognized { .. }), "still recognized after 1 miss under (1,2)" ); // Governance relaxes the schedule to (5, 6) before the next session. @@ -2911,7 +2934,7 @@ fn schedule_relaxation_saves_participant_next_session() { attend(&who, false); let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(_)), + matches!(p.recognition, Recognized { .. }), "still recognized: relaxed (5,6) ratio saved the participant" ); }); @@ -3355,7 +3378,7 @@ fn personhood_schedule_raise_does_not_retroactively_suspend() { assert_eq!(PersonhoodThreshold::::get(), 1); let (who, personal_id) = setup_recognised_person(99); let p = Participants::::get(&who).unwrap(); - assert!(matches!(p.recognition, Recognized(id) if id == personal_id)); + assert!(matches!(p.recognition, Recognized { id, .. } if id == personal_id)); let original_score = p.score; assert!(original_score < 21, "score should be modest under default curve at N=100"); @@ -3372,7 +3395,7 @@ fn personhood_schedule_raise_does_not_retroactively_suspend() { // Recognition retained — non-retroactivity guarantee. let p = Participants::::get(&who).unwrap(); assert!( - matches!(p.recognition, Recognized(_)), + matches!(p.recognition, Recognized { .. }), "raising the bar must not retroactively suspend already-recognized participants" ); assert!(p.reached_personhood, "reached_personhood must remain true"); @@ -3487,7 +3510,7 @@ mod migration { true, true, true, - Recognized(42), + Recognized { id: 42, newly_recognized: false }, Some(5u32), ); unhashed::put_raw(&Participants::::hashed_key_for(key), &old.encode()); @@ -3523,7 +3546,7 @@ mod migration { cashed_out: true, reached_personhood: true, has_ever_reached_personhood: true, - recognition: Recognized(42), + recognition: Recognized { id: 42, newly_recognized: false }, last_attended_game: Some(5), attended_games_while_recognized: 0, }) diff --git a/pallets/score/src/types.rs b/pallets/score/src/types.rs index 7ce776a6..3ce30cd4 100644 --- a/pallets/score/src/types.rs +++ b/pallets/score/src/types.rs @@ -233,12 +233,20 @@ pub enum Recognition { /// /// A participant may have reached personhood score, it is not recognized until he submit his /// key and calls `register`. - Recognized(PersonalId), + Recognized { + /// The personal id of the participant. + id: PersonalId, + /// Whether the participant is newly recognized until the next attendance. + /// + /// Set to true after calling `register` until the next attendance set with + /// `set_attendance`. + newly_recognized: bool, + }, } impl Recognition { pub fn is_recognized(&self) -> bool { - matches!(self, Recognition::Recognized(_) | Recognition::ExternallyRecognized) + matches!(self, Recognition::Recognized { .. } | Recognition::ExternallyRecognized) } pub fn is_externally_recognized(&self) -> bool { From 1d11586257729ad636a5b0788ee1f1aaa27b685e Mon Sep 17 00:00:00 2001 From: gui1117 Date: Tue, 24 Nov 2026 11:58:21 -0800 Subject: [PATCH 2/4] migration --- pallets/score/src/lib.rs | 2 +- pallets/score/src/migration.rs | 139 +++++++++++++- pallets/score/src/tests.rs | 254 ++++++++++++++++++++++++-- runtimes/next-people-paseo/src/lib.rs | 2 + 4 files changed, 372 insertions(+), 25 deletions(-) diff --git a/pallets/score/src/lib.rs b/pallets/score/src/lib.rs index 9dd7ae7c..13091e18 100644 --- a/pallets/score/src/lib.rs +++ b/pallets/score/src/lib.rs @@ -95,7 +95,7 @@ pub mod pallet { /// far in the future. const CUSTOM_ERROR_FAR_FUTURE: u8 = 87; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] diff --git a/pallets/score/src/migration.rs b/pallets/score/src/migration.rs index 06a6362a..b46f53de 100644 --- a/pallets/score/src/migration.rs +++ b/pallets/score/src/migration.rs @@ -16,10 +16,15 @@ //! Storage migrations for the Score pallet. -use crate::{BalanceOf, Config, Pallet, Participant, Participants}; +use crate::{ + AccountOrPerson, AttendanceHistory, BalanceOf, Config, Pallet, Participant, Participants, + Recognition, Streak, +}; use frame_support::{ - migrations::VersionedMigration, pallet_prelude::*, traits::UncheckedOnRuntimeUpgrade, + migrations::VersionedMigration, pallet_prelude::*, storage_alias, + traits::UncheckedOnRuntimeUpgrade, }; +use indiv_support::traits::PersonalId; use sp_runtime::Saturating; const LOG_TARGET: &str = "runtime::indiv-pallet-score::migration"; @@ -33,9 +38,29 @@ pub type MigrateV0ToV1 = VersionedMigration< ::DbWeight, >; +/// Adds `newly_recognized` to every stored participant that is `Recognized`, as `false`. +/// +/// Use it on a testnet only. It translates every participant in one block and its weight does not +/// include the proof size. +pub type MigrateV1ToV2TestnetOnly = VersionedMigration< + 1, + 2, + v2::MigrateToNewlyRecognizedTestnetOnly, + Pallet, + ::DbWeight, +>; + pub mod v1 { use super::*; - use crate::{AttendanceHistory, Recognition, Streak}; + + /// The recognition status as stored at versions 0 and 1. + #[derive(Encode, Decode, Eq, PartialEq, Debug)] + pub enum Recognition { + ExternallyRecognized, + NotRecognized, + Suspended(PersonalId), + Recognized(PersonalId), + } /// A participant as stored before the attended games counter existed. #[derive(Decode)] @@ -51,6 +76,30 @@ pub mod v1 { pub last_attended_game: Option, } + /// A participant as stored at version 1. + #[derive(Encode, Decode, Eq, PartialEq, Debug)] + pub struct Participant { + pub score: u8, + pub streak: Streak, + pub attendance_history: AttendanceHistory, + pub credit: Balance, + pub cashed_out: bool, + pub reached_personhood: bool, + pub has_ever_reached_personhood: bool, + pub recognition: Recognition, + pub last_attended_game: Option, + pub attended_games_while_recognized: u32, + } + + /// The [`crate::Participants`] map under the version 1 participant layout. + #[storage_alias] + pub type Participants = StorageMap< + Pallet, + Blake2_128Concat, + AccountOrPerson<::AccountId>, + Participant>, + >; + /// Use [`MigrateV0ToV1`] rather than this directly. /// /// Running this twice would reset every counter to zero: the new encoding is the old one plus @@ -85,7 +134,7 @@ pub mod v1 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { - // Keys, not entries: the values do not decode under the current type yet, and + // Keys, not entries: the values do not decode under the version 1 type yet, and // `iter` would skip every one of them and report an empty map. Ok((Participants::::iter_keys().count() as u32).encode()) } @@ -103,3 +152,85 @@ pub mod v1 { } } } + +pub mod v2 { + use super::*; + + /// Use [`MigrateV1ToV2TestnetOnly`] rather than this directly. + /// + /// A second run decodes a migrated `Recognized` participant with the version 1 layout. It then + /// reads `newly_recognized` as part of `last_attended_game` and corrupts the entry. The + /// version gate prevents a second run. + pub struct MigrateToNewlyRecognizedTestnetOnly(PhantomData); + + impl UncheckedOnRuntimeUpgrade for MigrateToNewlyRecognizedTestnetOnly { + fn on_runtime_upgrade() -> Weight { + let mut translated = 0u64; + Participants::::translate_values(|old: v1::Participant>| { + translated.saturating_inc(); + Some(Participant { + score: old.score, + streak: old.streak, + attendance_history: old.attendance_history, + credit: old.credit, + cashed_out: old.cashed_out, + reached_personhood: old.reached_personhood, + has_ever_reached_personhood: old.has_ever_reached_personhood, + recognition: match old.recognition { + v1::Recognition::ExternallyRecognized => Recognition::ExternallyRecognized, + v1::Recognition::NotRecognized => Recognition::NotRecognized, + v1::Recognition::Suspended(id) => Recognition::Suspended(id), + // The game accepted only the alias variant from a recognized player + // before the flag existed. `false` keeps that rule. + v1::Recognition::Recognized(id) => + Recognition::Recognized { id, newly_recognized: false }, + }, + last_attended_game: old.last_attended_game, + attended_games_while_recognized: old.attended_games_while_recognized, + }) + }); + log::info!(target: LOG_TARGET, "translated {translated} participants"); + // `DbWeight` gives the `ref_time` of the reads and writes only. The weight has no + // `proof_size` for the participants that the translation pulls into the PoV. A testnet + // accepts that, hence the `TestnetOnly` suffix. + T::DbWeight::get().reads_writes(translated.saturating_add(1), translated) + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + // The version 1 map, because a `Recognized` participant does not decode under the + // current type yet. + let recognized = v1::Participants::::iter_values() + .filter(|p| matches!(p.recognition, v1::Recognition::Recognized(_))) + .count() as u32; + let total = Participants::::iter_keys().count() as u32; + Ok((total, recognized).encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(state: alloc::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { + let (total_before, recognized_before) = + <(u32, u32)>::decode(&mut &state[..]).map_err(|_| { + sp_runtime::TryRuntimeError::Other("pre_upgrade state is not a (u32, u32)") + })?; + let mut total = 0u32; + let mut recognized = 0u32; + for participant in Participants::::iter_values() { + total.saturating_inc(); + match participant.recognition { + Recognition::Recognized { newly_recognized: false, .. } => + recognized.saturating_inc(), + Recognition::Recognized { newly_recognized: true, .. } => + return Err("the migration marked a participant as newly recognized".into()), + _ => {}, + } + } + ensure!(total_before == total, "a participant did not survive the migration"); + ensure!( + recognized_before == recognized, + "a recognized participant did not survive the migration" + ); + Ok(()) + } + } +} diff --git a/pallets/score/src/tests.rs b/pallets/score/src/tests.rs index 51d1a0f4..07535b91 100644 --- a/pallets/score/src/tests.rs +++ b/pallets/score/src/tests.rs @@ -3494,7 +3494,10 @@ fn integrity_test_passes() { mod migration { use super::*; - use crate::migration::{v1::MigrateToAttendedGamesCounter, MigrateV0ToV1}; + use crate::migration::{ + v1, v1::MigrateToAttendedGamesCounter, v2::MigrateToNewlyRecognizedTestnetOnly, + MigrateV0ToV1, MigrateV1ToV2TestnetOnly, + }; use frame_support::{ storage::unhashed, traits::{GetStorageVersion, OnRuntimeUpgrade, StorageVersion, UncheckedOnRuntimeUpgrade}, @@ -3510,12 +3513,44 @@ mod migration { true, true, true, - Recognized { id: 42, newly_recognized: false }, + v1::Recognition::Recognized(42), Some(5u32), ); unhashed::put_raw(&Participants::::hashed_key_for(key), &old.encode()); } + /// Returns a participant in the version 1 shape with the given recognition. + fn v1_participant(credit: u64, recognition: v1::Recognition) -> v1::Participant { + v1::Participant { + score: 7, + streak: Streak::Attended(3), + attendance_history: AttendanceHistory::default(), + credit, + cashed_out: true, + reached_personhood: true, + has_ever_reached_personhood: true, + recognition, + last_attended_game: Some(5), + attended_games_while_recognized: 4, + } + } + + /// Returns the current-shape counterpart of [`v1_participant`]. + fn participant(credit: u64, recognition: Recognition) -> Participant { + Participant { + score: 7, + streak: Streak::Attended(3), + attendance_history: AttendanceHistory::default(), + credit, + cashed_out: true, + reached_personhood: true, + has_ever_reached_personhood: true, + recognition, + last_attended_game: Some(5), + attended_games_while_recognized: 4, + } + } + fn old_keys() -> [AccountOrPerson; 3] { [ AccountOrPerson::Account(1), @@ -3537,8 +3572,8 @@ mod migration { // Every stored field survives and the counter starts at zero. assert_eq!( - Participants::::get(&key), - Some(Participant { + v1::Participants::::get(&key), + Some(v1::Participant { score: 7, streak: Streak::Attended(3), attendance_history: AttendanceHistory::default(), @@ -3546,7 +3581,7 @@ mod migration { cashed_out: true, reached_personhood: true, has_ever_reached_personhood: true, - recognition: Recognized { id: 42, newly_recognized: false }, + recognition: v1::Recognition::Recognized(42), last_attended_game: Some(5), attended_games_while_recognized: 0, }) @@ -3565,13 +3600,18 @@ mod migration { // An old-shaped participant is stored. let key = AccountOrPerson::Account(1); put_old_participant(&key, 77); - assert_eq!(Participants::::get(&key), None, "the old encoding must not decode"); + assert_eq!( + v1::Participants::::get(&key), + None, + "the old encoding must not decode" + ); // The inner migration runs. MigrateToAttendedGamesCounter::::on_runtime_upgrade(); // The participant decodes again. - let participant = Participants::::get(&key).expect("the migration restored it"); + let participant = + v1::Participants::::get(&key).expect("the migration restored it"); assert_eq!(participant.credit, 77); assert_eq!(participant.attended_games_while_recognized, 0); }); @@ -3589,7 +3629,7 @@ mod migration { MigrateToAttendedGamesCounter::::on_runtime_upgrade(); // All three decode. - assert_eq!(Participants::::iter().count(), 3); + assert_eq!(v1::Participants::::iter().count(), 3); }); } @@ -3601,23 +3641,120 @@ mod migration { PalletScore::in_code_storage_version(), "genesis must stamp the in-code version" ); - // A participant registered by the current code has a non-zero counter. - PalletScore::onboard_for_recognition(&1).unwrap(); + // A participant registered by the current code has a non-zero counter and is newly + // recognized. let key = AccountOrPerson::Account(1); - Participants::::mutate(&key, |p| { - p.as_mut().unwrap().attended_games_while_recognized = 9 - }); + let current = participant(9, Recognized { id: 42, newly_recognized: true }); + Participants::::insert(&key, ¤t); - // The wired migration runs. + // The wired migrations run. + let db = ::DbWeight::get(); let weight = as OnRuntimeUpgrade>::on_runtime_upgrade(); + assert_eq!(weight, db.reads(1)); + let weight = as OnRuntimeUpgrade>::on_runtime_upgrade(); + assert_eq!(weight, db.reads(1)); + + // The participant is untouched and only the version reads are charged. + assert_eq!( + Participants::::get(&key), + Some(current), + "the gates must leave a current participant alone" + ); + }); + } + + #[test] + fn versioned_migration_adds_newly_recognized_and_bumps_the_version() { + new_test_ext().execute_with(|| { + // Chain at version 1 holds one recognized participant in the version 1 shape. + StorageVersion::new(1).put::(); + let key = AccountOrPerson::Account(1); + v1::Participants::::insert( + &key, + v1_participant(77, v1::Recognition::Recognized(42)), + ); + assert_eq!(Participants::::get(&key), None, "the old encoding must not decode"); + + // The wired migration runs. + let weight = as OnRuntimeUpgrade>::on_runtime_upgrade(); + + // Every stored field survives and the participant is not newly recognized. + assert_eq!( + Participants::::get(&key), + Some(participant(77, Recognized { id: 42, newly_recognized: false })) + ); + assert_eq!(PalletScore::on_chain_storage_version(), 2, "the gate must close behind it"); + // One read and write for the one participant, one more read for the end of the + // prefix iteration, and a read and write for the version the gate checks and stamps. + let db = ::DbWeight::get(); + assert_eq!(weight, db.reads_writes(3, 2), "the translation must charge what it did"); + }); + } + + #[test] + fn newly_recognized_migration_keeps_every_recognition_variant() { + new_test_ext().execute_with(|| { + // One participant per version 1 recognition variant is stored. + let cases = [ + (1, v1::Recognition::ExternallyRecognized, ExternallyRecognized), + (2, v1::Recognition::NotRecognized, NotRecognized), + (3, v1::Recognition::Suspended(11), Suspended(11)), + ( + 4, + v1::Recognition::Recognized(12), + Recognized { id: 12, newly_recognized: false }, + ), + ]; + let expected = cases + .into_iter() + .map(|(who, old, new)| { + let key = AccountOrPerson::Account(who); + v1::Participants::::insert(&key, v1_participant(who, old)); + (key, participant(who, new)) + }) + .collect::>(); + let person = AccountOrPerson::Person([3u8; 32]); + v1::Participants::::insert( + &person, + v1_participant(5, v1::Recognition::Recognized(13)), + ); + + // The inner migration runs. + MigrateToNewlyRecognizedTestnetOnly::::on_runtime_upgrade(); + + // Each participant keeps its fields and its recognition. + for (key, participant) in expected { + assert_eq!(Participants::::get(&key), Some(participant)); + } + assert_eq!( + Participants::::get(&person), + Some(participant(5, Recognized { id: 13, newly_recognized: false })) + ); + assert_eq!(Participants::::iter().count(), 5); + }); + } - // The counter is untouched and only the version read is charged. + #[test] + fn both_migrations_chain_from_version_zero() { + new_test_ext().execute_with(|| { + // Chain at version 0 holds one participant in the oldest shape. + StorageVersion::new(0).put::(); + let key = AccountOrPerson::Account(1); + put_old_participant(&key, 77); + + // Both wired migrations run in the runtime order. + as OnRuntimeUpgrade>::on_runtime_upgrade(); + as OnRuntimeUpgrade>::on_runtime_upgrade(); + + // The participant decodes under the current type. assert_eq!( - Participants::::get(&key).expect("exists").attended_games_while_recognized, - 9, - "the gate must leave a current participant alone" + Participants::::get(&key), + Some(Participant { + attended_games_while_recognized: 0, + ..participant(77, Recognized { id: 42, newly_recognized: false }) + }) ); - assert_eq!(weight, ::DbWeight::get().reads(1)); + assert_eq!(PalletScore::on_chain_storage_version(), 2); }); } @@ -3629,7 +3766,7 @@ mod migration { for key in &old_keys() { put_old_participant(key, 5); } - assert_eq!(Participants::::iter().count(), 0, "nothing decodes before"); + assert_eq!(v1::Participants::::iter().count(), 0, "nothing decodes before"); // Pre-upgrade state is captured and the migration runs. let state = MigrateToAttendedGamesCounter::::pre_upgrade().expect("counts keys"); @@ -3658,4 +3795,81 @@ mod migration { assert!(MigrateToAttendedGamesCounter::::post_upgrade(state).is_err()); }); } + + #[cfg(feature = "try-runtime")] + #[test] + fn newly_recognized_try_runtime_checks_span_the_translation() { + new_test_ext().execute_with(|| { + // Two recognized participants and one that is not are stored in the version 1 shape. + let [first, second, third] = old_keys(); + v1::Participants::::insert( + &first, + v1_participant(5, v1::Recognition::Recognized(1)), + ); + v1::Participants::::insert( + &second, + v1_participant(5, v1::Recognition::NotRecognized), + ); + v1::Participants::::insert( + &third, + v1_participant(5, v1::Recognition::Recognized(2)), + ); + + // Pre-upgrade state is captured and the migration runs. + let state = + MigrateToNewlyRecognizedTestnetOnly::::pre_upgrade().expect("counts keys"); + assert_eq!(<(u32, u32)>::decode(&mut &state[..]).unwrap(), (3, 2)); + MigrateToNewlyRecognizedTestnetOnly::::on_runtime_upgrade(); + + // Post-upgrade check passes. + assert_ok!(MigrateToNewlyRecognizedTestnetOnly::::post_upgrade(state)); + }); + } + + #[cfg(feature = "try-runtime")] + #[test] + fn newly_recognized_post_upgrade_check_catches_a_lost_participant() { + new_test_ext().execute_with(|| { + // Pre-upgrade state counted one recognized participant. + let key = AccountOrPerson::Account(1); + v1::Participants::::insert( + &key, + v1_participant(5, v1::Recognition::Recognized(1)), + ); + let state = + MigrateToNewlyRecognizedTestnetOnly::::pre_upgrade().expect("counts keys"); + + // A value that decodes as neither shape is dropped by `translate_values`. + unhashed::put_raw(&Participants::::hashed_key_for(&key), &[0xffu8]); + MigrateToNewlyRecognizedTestnetOnly::::on_runtime_upgrade(); + + // Post-upgrade check reports the loss. + assert!(MigrateToNewlyRecognizedTestnetOnly::::post_upgrade(state).is_err()); + }); + } + + #[cfg(feature = "try-runtime")] + #[test] + fn newly_recognized_post_upgrade_check_rejects_a_newly_recognized_participant() { + new_test_ext().execute_with(|| { + // Pre-upgrade state counted one recognized participant. + let key = AccountOrPerson::Account(1); + v1::Participants::::insert( + &key, + v1_participant(5, v1::Recognition::Recognized(1)), + ); + let state = + MigrateToNewlyRecognizedTestnetOnly::::pre_upgrade().expect("counts keys"); + MigrateToNewlyRecognizedTestnetOnly::::on_runtime_upgrade(); + + // The participant is marked as newly recognized after the migration. + Participants::::insert( + &key, + participant(5, Recognized { id: 1, newly_recognized: true }), + ); + + // Post-upgrade check reports it. + assert!(MigrateToNewlyRecognizedTestnetOnly::::post_upgrade(state).is_err()); + }); + } } diff --git a/runtimes/next-people-paseo/src/lib.rs b/runtimes/next-people-paseo/src/lib.rs index f32370f5..d2955c5f 100644 --- a/runtimes/next-people-paseo/src/lib.rs +++ b/runtimes/next-people-paseo/src/lib.rs @@ -277,6 +277,8 @@ pub type Migrations = ( // Single use! - remove once the upgrade carrying it is live. indiv_pallet_score::migration::MigrateV0ToV1, // Single use! - remove once the upgrade carrying it is live. + indiv_pallet_score::migration::MigrateV1ToV2TestnetOnly, + // Single use! - remove once the upgrade carrying it is live. indiv_pallet_airdrop::migration::MigrateV0ToV1, // Single use! - remove once the upgrade carrying it is live. indiv_pallet_game::migration::MigrateV0ToV1, From be344abd8a7b38df9e03b2aa4ae04c2f568b2325 Mon Sep 17 00:00:00 2001 From: gui1117 Date: Tue, 24 Nov 2026 12:06:18 -0800 Subject: [PATCH 3/4] apply Theo suggestion --- pallets/score/src/types.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pallets/score/src/types.rs b/pallets/score/src/types.rs index 3ce30cd4..234f6827 100644 --- a/pallets/score/src/types.rs +++ b/pallets/score/src/types.rs @@ -238,8 +238,7 @@ pub enum Recognition { id: PersonalId, /// Whether the participant is newly recognized until the next attendance. /// - /// Set to true after calling `register` until the next attendance set with - /// `set_attendance`. + /// `register` sets this and the next `set_attendance` clears it. newly_recognized: bool, }, } From 0a2964ccf0ae1331463f7451cd5d4588f127862f Mon Sep 17 00:00:00 2001 From: gui1117 Date: Wed, 25 Nov 2026 09:47:14 -0800 Subject: [PATCH 4/4] apply Theo's suggestions --- pallets/game/src/types.rs | 8 ++++---- pallets/score/src/tests.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pallets/game/src/types.rs b/pallets/game/src/types.rs index cf54f491..52cbea8c 100644 --- a/pallets/game/src/types.rs +++ b/pallets/game/src/types.rs @@ -184,10 +184,10 @@ pub enum AttendanceStatus { /// The variant picks the identity path: if the player is recognized (pallet-score `Recognition` /// is `Recognized` or `ExternallyRecognized`) then they must provide the alias variant, /// otherwise they must provide the account variant. A newly recognized player (pallet-score -/// `Recognized` with `newly_recognized`) may provide either variant (in case the key is not -/// included in a ring yet). The variant holds exactly one entry per -/// scheduled airdrop event of the game, in airdrop-index order: the entry at position `i` is -/// bound to the event id of airdrop index `i` (see `Pallet::airdrop_event_id`). +/// `Recognized` with `newly_recognized`) may provide either variant, because their member key may +/// not be in a ring yet. The variant holds exactly one entry per scheduled airdrop event of the +/// game, in airdrop-index order: the entry at position `i` is bound to the event id of airdrop +/// index `i` (see `Pallet::airdrop_event_id`). #[derive(Encode, Decode, TypeInfo, Debug, Clone, PartialEq, Eq)] #[scale_info(skip_type_params(P))] pub enum AirdropVrfs

{ diff --git a/pallets/score/src/tests.rs b/pallets/score/src/tests.rs index 07535b91..70a7fc95 100644 --- a/pallets/score/src/tests.rs +++ b/pallets/score/src/tests.rs @@ -2006,7 +2006,6 @@ fn grace_ratio_suspension() { }); } -/// Attending pushes misses out of the rolling window, preventing suspension. #[test] fn set_attendance_ends_the_newly_recognized_state() { new_test_ext().execute_with(|| { @@ -2027,6 +2026,7 @@ fn set_attendance_ends_the_newly_recognized_state() { }); } +/// Attending pushes misses out of the rolling window, preventing suspension. #[test] fn attendance_within_window_prevents_suspension() { new_test_ext().execute_with(|| {