1
// This file is part of Substrate.
2

            
3
// Copyright (C) Parity Technologies (UK) Ltd.
4
// SPDX-License-Identifier: Apache-2.0
5

            
6
// Licensed under the Apache License, Version 2.0 (the "License");
7
// you may not use this file except in compliance with the License.
8
// You may obtain a copy of the License at
9
//
10
// 	http://www.apache.org/licenses/LICENSE-2.0
11
//
12
// Unless required by applicable law or agreed to in writing, software
13
// distributed under the License is distributed on an "AS IS" BASIS,
14
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
// See the License for the specific language governing permissions and
16
// limitations under the License.
17

            
18
//! Storage migrations for the referenda pallet.
19

            
20
use super::*;
21
use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
22
use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade};
23
use log;
24

            
25
#[cfg(feature = "try-runtime")]
26
use sp_runtime::TryRuntimeError;
27

            
28
/// Initial version of storage types.
29
pub mod v0 {
30
	use super::*;
31
	// ReferendumStatus and its dependency types referenced from the latest version while staying
32
	// unchanged. [`super::test::referendum_status_v0()`] checks its immutability between v0 and
33
	// latest version.
34
	#[cfg(test)]
35
	pub(super) use super::{ReferendumStatus, ReferendumStatusOf};
36

            
37
	pub type ReferendumInfoOf<T, I> = ReferendumInfo<
38
		TrackIdOf<T, I>,
39
		PalletsOriginOf<T>,
40
		frame_system::pallet_prelude::BlockNumberFor<T>,
41
		BoundedCallOf<T, I>,
42
		BalanceOf<T, I>,
43
		TallyOf<T, I>,
44
		<T as frame_system::Config>::AccountId,
45
		ScheduleAddressOf<T, I>,
46
	>;
47

            
48
	/// Info regarding a referendum, present or past.
49
	#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
50
	pub enum ReferendumInfo<
51
		TrackId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone,
52
		RuntimeOrigin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone,
53
		Moment: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone + EncodeLike,
54
		Call: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone,
55
		Balance: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone,
56
		Tally: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone,
57
		AccountId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone,
58
		ScheduleAddress: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone,
59
	> {
60
		/// Referendum has been submitted and is being voted on.
61
		Ongoing(
62
			ReferendumStatus<
63
				TrackId,
64
				RuntimeOrigin,
65
				Moment,
66
				Call,
67
				Balance,
68
				Tally,
69
				AccountId,
70
				ScheduleAddress,
71
			>,
72
		),
73
		/// Referendum finished with approval. Submission deposit is held.
74
		Approved(Moment, Deposit<AccountId, Balance>, Option<Deposit<AccountId, Balance>>),
75
		/// Referendum finished with rejection. Submission deposit is held.
76
		Rejected(Moment, Deposit<AccountId, Balance>, Option<Deposit<AccountId, Balance>>),
77
		/// Referendum finished with cancellation. Submission deposit is held.
78
		Cancelled(Moment, Deposit<AccountId, Balance>, Option<Deposit<AccountId, Balance>>),
79
		/// Referendum finished and was never decided. Submission deposit is held.
80
		TimedOut(Moment, Deposit<AccountId, Balance>, Option<Deposit<AccountId, Balance>>),
81
		/// Referendum finished with a kill.
82
		Killed(Moment),
83
	}
84

            
85
	#[storage_alias]
86
	pub type ReferendumInfoFor<T: Config<I>, I: 'static> =
87
		StorageMap<Pallet<T, I>, Blake2_128Concat, ReferendumIndex, ReferendumInfoOf<T, I>>;
88
}
89

            
90
pub mod v1 {
91
	use super::*;
92

            
93
	/// The log target.
94
	const TARGET: &'static str = "runtime::referenda::migration::v1";
95

            
96
	/// Transforms a submission deposit of ReferendumInfo(Approved|Rejected|Cancelled|TimedOut) to
97
	/// optional value, making it refundable.
98
	pub struct MigrateV0ToV1<T, I = ()>(PhantomData<(T, I)>);
99
	impl<T: Config<I>, I: 'static> OnRuntimeUpgrade for MigrateV0ToV1<T, I> {
100
		#[cfg(feature = "try-runtime")]
101
		fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
102
			let referendum_count = v0::ReferendumInfoFor::<T, I>::iter().count();
103
			log::info!(
104
				target: TARGET,
105
				"pre-upgrade state contains '{}' referendums.",
106
				referendum_count
107
			);
108
			Ok((referendum_count as u32).encode())
109
		}
110

            
111
		fn on_runtime_upgrade() -> Weight {
112
			let in_code_version = Pallet::<T, I>::in_code_storage_version();
113
			let on_chain_version = Pallet::<T, I>::on_chain_storage_version();
114
			let mut weight = T::DbWeight::get().reads(1);
115
			log::info!(
116
				target: TARGET,
117
				"running migration with in-code storage version {:?} / onchain {:?}.",
118
				in_code_version,
119
				on_chain_version
120
			);
121
			if on_chain_version != 0 {
122
				log::warn!(target: TARGET, "skipping migration from v0 to v1.");
123
				return weight
124
			}
125
			v0::ReferendumInfoFor::<T, I>::iter().for_each(|(key, value)| {
126
				let maybe_new_value = match value {
127
					v0::ReferendumInfo::Ongoing(_) | v0::ReferendumInfo::Killed(_) => None,
128
					v0::ReferendumInfo::Approved(e, s, d) =>
129
						Some(ReferendumInfo::Approved(e, Some(s), d)),
130
					v0::ReferendumInfo::Rejected(e, s, d) =>
131
						Some(ReferendumInfo::Rejected(e, Some(s), d)),
132
					v0::ReferendumInfo::Cancelled(e, s, d) =>
133
						Some(ReferendumInfo::Cancelled(e, Some(s), d)),
134
					v0::ReferendumInfo::TimedOut(e, s, d) =>
135
						Some(ReferendumInfo::TimedOut(e, Some(s), d)),
136
				};
137
				if let Some(new_value) = maybe_new_value {
138
					weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
139
					log::info!(target: TARGET, "migrating referendum #{:?}", &key);
140
					ReferendumInfoFor::<T, I>::insert(key, new_value);
141
				} else {
142
					weight.saturating_accrue(T::DbWeight::get().reads(1));
143
				}
144
			});
145
			StorageVersion::new(1).put::<Pallet<T, I>>();
146
			weight.saturating_accrue(T::DbWeight::get().writes(1));
147
			weight
148
		}
149

            
150
		#[cfg(feature = "try-runtime")]
151
		fn post_upgrade(state: Vec<u8>) -> Result<(), TryRuntimeError> {
152
			let on_chain_version = Pallet::<T, I>::on_chain_storage_version();
153
			ensure!(on_chain_version == 1, "must upgrade from version 0 to 1.");
154
			let pre_referendum_count: u32 = Decode::decode(&mut &state[..])
155
				.expect("failed to decode the state from pre-upgrade.");
156
			let post_referendum_count = ReferendumInfoFor::<T, I>::iter().count() as u32;
157
			ensure!(post_referendum_count == pre_referendum_count, "must migrate all referendums.");
158
			log::info!(target: TARGET, "migrated all referendums.");
159
			Ok(())
160
		}
161
	}
162
}
163

            
164
#[cfg(test)]
165
pub mod test {
166
	use super::*;
167
	use crate::mock::{Test as T, *};
168
	use core::str::FromStr;
169

            
170
	// create referendum status v0.
171
	fn create_status_v0() -> v0::ReferendumStatusOf<T, ()> {
172
		let origin: OriginCaller = frame_system::RawOrigin::Root.into();
173
		let track = <T as Config<()>>::Tracks::track_for(&origin).unwrap();
174
		v0::ReferendumStatusOf::<T, ()> {
175
			track,
176
			in_queue: true,
177
			origin,
178
			proposal: set_balance_proposal_bounded(1),
179
			enactment: DispatchTime::At(1),
180
			tally: TallyOf::<T, ()>::new(track),
181
			submission_deposit: Deposit { who: 1, amount: 10 },
182
			submitted: 1,
183
			decision_deposit: None,
184
			alarm: None,
185
			deciding: None,
186
		}
187
	}
188

            
189
	#[test]
190
	pub fn referendum_status_v0() {
191
		// make sure the bytes of the encoded referendum v0 is decodable.
192
		let ongoing_encoded = sp_core::Bytes::from_str("0x00000000012c01082a0000000000000004000100000000000000010000000000000001000000000000000a00000000000000000000000000000000000100").unwrap();
193
		let ongoing_dec = v0::ReferendumInfoOf::<T, ()>::decode(&mut &*ongoing_encoded).unwrap();
194
		let ongoing = v0::ReferendumInfoOf::<T, ()>::Ongoing(create_status_v0());
195
		assert_eq!(ongoing, ongoing_dec);
196
	}
197

            
198
	#[test]
199
	fn migration_v0_to_v1_works() {
200
		ExtBuilder::default().build_and_execute(|| {
201
			// create and insert into the storage an ongoing referendum v0.
202
			let status_v0 = create_status_v0();
203
			let ongoing_v0 = v0::ReferendumInfoOf::<T, ()>::Ongoing(status_v0.clone());
204
			ReferendumCount::<T, ()>::mutate(|x| x.saturating_inc());
205
			v0::ReferendumInfoFor::<T, ()>::insert(2, ongoing_v0);
206
			// create and insert into the storage an approved referendum v0.
207
			let approved_v0 = v0::ReferendumInfoOf::<T, ()>::Approved(
208
				123,
209
				Deposit { who: 1, amount: 10 },
210
				Some(Deposit { who: 2, amount: 20 }),
211
			);
212
			ReferendumCount::<T, ()>::mutate(|x| x.saturating_inc());
213
			v0::ReferendumInfoFor::<T, ()>::insert(5, approved_v0);
214
			// run migration from v0 to v1.
215
			v1::MigrateV0ToV1::<T, ()>::on_runtime_upgrade();
216
			// fetch and assert migrated into v1 the ongoing referendum.
217
			let ongoing_v1 = ReferendumInfoFor::<T, ()>::get(2).unwrap();
218
			// referendum status schema is the same for v0 and v1.
219
			assert_eq!(ReferendumInfoOf::<T, ()>::Ongoing(status_v0), ongoing_v1);
220
			// fetch and assert migrated into v1 the approved referendum.
221
			let approved_v1 = ReferendumInfoFor::<T, ()>::get(5).unwrap();
222
			assert_eq!(
223
				approved_v1,
224
				ReferendumInfoOf::<T, ()>::Approved(
225
					123,
226
					Some(Deposit { who: 1, amount: 10 }),
227
					Some(Deposit { who: 2, amount: 20 })
228
				)
229
			);
230
		});
231
	}
232
}