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
use super::*;
use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade, BoundedVec};
use sp_core::H256;
const TARGET: &'static str = "runtime::democracy::migration::v1";
mod v0 {
use super::*;
#[storage_alias]
pub type PublicProps<T: Config> = StorageValue<
Pallet<T>,
Vec<(
PropIndex,
<T as frame_system::Config>::Hash,
<T as frame_system::Config>::AccountId,
)>,
ValueQuery,
>;
#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
pub enum PreimageStatus<AccountId, Balance, BlockNumber> {
Missing(BlockNumber),
Available {
data: Vec<u8>,
provider: AccountId,
deposit: Balance,
since: BlockNumber,
expiry: Option<BlockNumber>,
},
}
#[storage_alias]
pub type Preimages<T: Config> = StorageMap<
Pallet<T>,
Identity,
<T as frame_system::Config>::Hash,
PreimageStatus<<T as frame_system::Config>::AccountId, BalanceOf<T>, BlockNumberFor<T>>,
>;
#[cfg(feature = "try-runtime")]
#[storage_alias]
pub type ReferendumInfoOf<T: Config> = StorageMap<
Pallet<T>,
frame_support::Twox64Concat,
ReferendumIndex,
ReferendumInfo<BlockNumberFor<T>, <T as frame_system::Config>::Hash, BalanceOf<T>>,
>;
}
pub mod v1 {
use super::*;
use frame_system::pallet_prelude::BlockNumberFor;
#[cfg(feature = "try-runtime")]
use sp_runtime::TryRuntimeError;
pub struct Migration<T>(sp_std::marker::PhantomData<T>);
impl<T: Config + frame_system::Config<Hash = H256>> OnRuntimeUpgrade for Migration<T> {
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
assert_eq!(StorageVersion::get::<Pallet<T>>(), 0, "can only upgrade from version 0");
let props_count = v0::PublicProps::<T>::get().len();
log::info!(target: TARGET, "{} public proposals will be migrated.", props_count,);
ensure!(props_count <= T::MaxProposals::get() as usize, "too many proposals");
let referenda_count = v0::ReferendumInfoOf::<T>::iter().count();
log::info!(target: TARGET, "{} referenda will be migrated.", referenda_count);
Ok((props_count as u32, referenda_count as u32).encode())
}
#[allow(deprecated)]
fn on_runtime_upgrade() -> Weight {
let mut weight = T::DbWeight::get().reads(1);
if StorageVersion::get::<Pallet<T>>() != 0 {
log::warn!(
target: TARGET,
"skipping on_runtime_upgrade: executed on wrong storage version.\
Expected version 0"
);
return weight;
}
ReferendumInfoOf::<T>::translate(|index, old: ReferendumInfo<BlockNumberFor<T>, T::Hash, BalanceOf<T>>| {
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
log::info!(target: TARGET, "migrating referendum #{:?}", &index);
Some(match old {
ReferendumInfo::Ongoing(status) => ReferendumInfo::Ongoing(ReferendumStatus {
end: status.end,
proposal: Bounded::from_legacy_hash(status.proposal),
threshold: status.threshold,
delay: status.delay,
tally: status.tally,
}),
ReferendumInfo::Finished { approved, end } => ReferendumInfo::Finished { approved, end },
})
});
let props = v0::PublicProps::<T>::take()
.into_iter()
.map(|(i, hash, a)| (i, Bounded::from_legacy_hash(hash), a))
.collect::<Vec<_>>();
let bounded = BoundedVec::<_, T::MaxProposals>::truncate_from(props.clone());
PublicProps::<T>::put(bounded);
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
if props.len() as u32 > T::MaxProposals::get() {
log::error!(
target: TARGET,
"truncated {} public proposals to {}; continuing",
props.len(),
T::MaxProposals::get()
);
}
let res = frame_support::migration::clear_storage_prefix(
<Pallet<T>>::name().as_bytes(),
b"Preimages",
b"",
None,
None,
);
log::info!(
target: TARGET,
"Cleared '{}' entries from 'Preimages' storage prefix",
res.unique
);
if res.maybe_cursor.is_some() {
log::error!(target: TARGET, "Storage prefix 'Preimages' is not completely cleared.");
}
weight.saturating_add(T::DbWeight::get().writes(res.unique.into()));
let _ = frame_support::migration::clear_storage_prefix(
<Pallet<T>>::name().as_bytes(),
b"StorageVersion",
b"",
None,
None,
);
weight.saturating_add(T::DbWeight::get().writes(1));
StorageVersion::new(1).put::<Pallet<T>>();
weight.saturating_add(T::DbWeight::get().reads_writes(1, 2))
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(state: Vec<u8>) -> Result<(), TryRuntimeError> {
assert_eq!(StorageVersion::get::<Pallet<T>>(), 1, "must upgrade");
let (old_props_count, old_ref_count): (u32, u32) =
Decode::decode(&mut &state[..]).expect("pre_upgrade provides a valid state; qed");
let new_props_count = crate::PublicProps::<T>::get().len() as u32;
assert_eq!(new_props_count, old_props_count, "must migrate all public proposals");
let new_ref_count = crate::ReferendumInfoOf::<T>::iter().count() as u32;
assert_eq!(new_ref_count, old_ref_count, "must migrate all referenda");
log::info!(
target: TARGET,
"{} public proposals migrated, {} referenda migrated",
new_props_count,
new_ref_count,
);
Ok(())
}
}
}
#[cfg(test)]
#[cfg(feature = "try-runtime")]
mod test {
use super::*;
use crate::{
tests::{Test as T, *},
types::*,
};
use frame_support::bounded_vec;
#[allow(deprecated)]
#[test]
fn migration_works() {
new_test_ext().execute_with(|| {
assert_eq!(StorageVersion::get::<Pallet<T>>(), 0);
let hash = H256::repeat_byte(1);
let status = ReferendumStatus {
end: 1u32.into(),
proposal: hash.clone(),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 1u32.into(),
tally: Tally {
ayes: 1u32.into(),
nays: 1u32.into(),
turnout: 1u32.into(),
},
};
v0::ReferendumInfoOf::<T>::insert(1u32, ReferendumInfo::Ongoing(status));
v0::ReferendumInfoOf::<T>::insert(
2u32,
ReferendumInfo::Finished {
approved: true,
end: 123u32.into(),
},
);
let hash2 = H256::repeat_byte(2);
v0::PublicProps::<T>::put(vec![(3u32, hash.clone(), 123u64), (4u32, hash2.clone(), 123u64)]);
v0::Preimages::<T>::insert(
hash2,
v0::PreimageStatus::Available {
data: vec![],
provider: 0,
deposit: 0,
since: 0,
expiry: None,
},
);
let state = v1::Migration::<T>::pre_upgrade().unwrap();
let _weight = v1::Migration::<T>::on_runtime_upgrade();
v1::Migration::<T>::post_upgrade(state).unwrap();
assert_eq!(
ReferendumInfoOf::<T>::get(1u32),
Some(ReferendumInfo::Ongoing(ReferendumStatus {
end: 1u32.into(),
proposal: Bounded::from_legacy_hash(hash),
threshold: VoteThreshold::SuperMajorityApprove,
delay: 1u32.into(),
tally: Tally {
ayes: 1u32.into(),
nays: 1u32.into(),
turnout: 1u32.into()
},
}))
);
assert_eq!(
ReferendumInfoOf::<T>::get(2u32),
Some(ReferendumInfo::Finished {
approved: true,
end: 123u32.into()
})
);
let props: BoundedVec<_, <Test as Config>::MaxProposals> = bounded_vec![
(3u32, Bounded::from_legacy_hash(hash), 123u64),
(4u32, Bounded::from_legacy_hash(hash2), 123u64)
];
assert_eq!(PublicProps::<T>::get(), props);
assert_eq!(v0::Preimages::<T>::iter().collect::<Vec<_>>().len(), 0);
});
}
}