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
// This file is part of Substrate.

// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

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

//! The best way to understand how this iterator works is to imagine some 2D terrain that have some mountains
//! (digest changes tries) and valleys (changes tries for regular blocks). There are gems (blocks) beneath the
//! terrain. Given the request to find all gems in the range [X1; X2] this iterator will return **minimal set**
//! of points at the terrain (mountains and valleys) inside this range that have to be drilled down to
//! search for gems.

use crate::changes_trie::{BlockNumber, ConfigurationRange};
use num_traits::One;

/// Returns surface iterator for given range of blocks.
///
/// `max` is the number of best block, known to caller. We can't access any changes tries
/// that are built after this block, even though we may have them built already.
pub fn surface_iterator<'a, Number: BlockNumber>(
	config: ConfigurationRange<'a, Number>,
	max: Number,
	begin: Number,
	end: Number,
) -> Result<SurfaceIterator<'a, Number>, String> {
	let (current, current_begin, digest_step, digest_level) =
		lower_bound_max_digest(config.clone(), max.clone(), begin.clone(), end)?;
	Ok(SurfaceIterator {
		config,
		begin,
		max,
		current: Some(current),
		current_begin,
		digest_step,
		digest_level,
	})
}

/// Surface iterator - only traverses top-level digests from given range and tries to find
/// all valid digest changes.
///
/// Iterator item is the tuple of (last block of the current point + digest level of the current point).
/// Digest level is Some(0) when it is regular block, is Some(non-zero) when it is digest block and None
/// if it is skewed digest block.
pub struct SurfaceIterator<'a, Number: BlockNumber> {
	config: ConfigurationRange<'a, Number>,
	begin: Number,
	max: Number,
	current: Option<Number>,
	current_begin: Number,
	digest_step: u32,
	digest_level: Option<u32>,
}

impl<'a, Number: BlockNumber> Iterator for SurfaceIterator<'a, Number> {
	type Item = Result<(Number, Option<u32>), String>;

	fn next(&mut self) -> Option<Self::Item> {
		let current = self.current.clone()?;
		let digest_level = self.digest_level;

		if current < self.digest_step.into() {
			self.current = None;
		} else {
			let next = current.clone() - self.digest_step.into();
			if next.is_zero() || next < self.begin {
				self.current = None;
			} else if next > self.current_begin {
				self.current = Some(next);
			} else {
				let max_digest_interval = lower_bound_max_digest(
					self.config.clone(),
					self.max.clone(),
					self.begin.clone(),
					next,
				);
				let (current, current_begin, digest_step, digest_level) = match max_digest_interval
				{
					Err(err) => return Some(Err(err)),
					Ok(range) => range,
				};

				self.current = Some(current);
				self.current_begin = current_begin;
				self.digest_step = digest_step;
				self.digest_level = digest_level;
			}
		}

		Some(Ok((current, digest_level)))
	}
}

/// Returns parameters of highest level digest block that includes the end of given range
/// and tends to include the whole range.
fn lower_bound_max_digest<'a, Number: BlockNumber>(
	config: ConfigurationRange<'a, Number>,
	max: Number,
	begin: Number,
	end: Number,
) -> Result<(Number, Number, u32, Option<u32>), String> {
	if end > max || begin > end {
		return Err(format!("invalid changes range: {}..{}/{}", begin, end, max))
	}
	if begin <= config.zero ||
		config.end.as_ref().map(|config_end| end > *config_end).unwrap_or(false)
	{
		return Err(format!(
			"changes trie range is not covered by configuration: {}..{}/{}..{}",
			begin,
			end,
			config.zero,
			match config.end.as_ref() {
				Some(config_end) => format!("{}", config_end),
				None => "None".into(),
			}
		))
	}

	let mut digest_level = 0u32;
	let mut digest_step = 1u32;
	let mut digest_interval = 0u32;
	let mut current = end.clone();
	let mut current_begin = begin.clone();
	if current_begin != current {
		while digest_level != config.config.digest_levels {
			// try to use next level digest
			let new_digest_level = digest_level + 1;
			let new_digest_step = digest_step * config.config.digest_interval;
			let new_digest_interval = config.config.digest_interval * {
				if digest_interval == 0 {
					1
				} else {
					digest_interval
				}
			};
			let new_digest_begin = config.zero.clone() +
				((current.clone() - One::one() - config.zero.clone()) /
					new_digest_interval.into()) *
					new_digest_interval.into();
			let new_digest_end = new_digest_begin.clone() + new_digest_interval.into();
			let new_current = new_digest_begin.clone() + new_digest_interval.into();

			// check if we met skewed digest
			if let Some(skewed_digest_end) = config.end.as_ref() {
				if new_digest_end > *skewed_digest_end {
					let skewed_digest_start = config.config.prev_max_level_digest_block(
						config.zero.clone(),
						skewed_digest_end.clone(),
					);
					if let Some(skewed_digest_start) = skewed_digest_start {
						let skewed_digest_range = (skewed_digest_end.clone() -
							skewed_digest_start.clone())
						.try_into()
						.ok()
						.expect(
							"skewed digest range is always <= max level digest range;\
								max level digest range always fits u32; qed",
						);
						return Ok((
							skewed_digest_end.clone(),
							skewed_digest_start,
							skewed_digest_range,
							None,
						))
					}
				}
			}

			// we can't use next level digest if it touches any unknown (> max) blocks
			if new_digest_end > max {
				if begin < new_digest_begin {
					current_begin = new_digest_begin;
				}
				break
			}

			// we can (and will) use this digest
			digest_level = new_digest_level;
			digest_step = new_digest_step;
			digest_interval = new_digest_interval;
			current = new_current;
			current_begin = new_digest_begin;

			// if current digest covers the whole range => no need to use next level digest
			if current_begin <= begin && new_digest_end >= end {
				break
			}
		}
	}

	Ok((current, current_begin, digest_step, Some(digest_level)))
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::changes_trie::Configuration;

	fn configuration_range<'a>(
		config: &'a Configuration,
		zero: u64,
	) -> ConfigurationRange<'a, u64> {
		ConfigurationRange { config, zero, end: None }
	}

	#[test]
	fn lower_bound_max_digest_works() {
		let config = Configuration { digest_interval: 4, digest_levels: 2 };

		// when config activates at 0
		assert_eq!(
			lower_bound_max_digest(configuration_range(&config, 0u64), 100_000u64, 20u64, 180u64)
				.unwrap(),
			(192, 176, 16, Some(2)),
		);

		// when config activates at 30
		assert_eq!(
			lower_bound_max_digest(configuration_range(&config, 30u64), 100_000u64, 50u64, 210u64)
				.unwrap(),
			(222, 206, 16, Some(2)),
		);
	}

	#[test]
	fn surface_iterator_works() {
		let config = Configuration { digest_interval: 4, digest_levels: 2 };

		// when config activates at 0
		assert_eq!(
			surface_iterator(configuration_range(&config, 0u64), 100_000u64, 40u64, 180u64,)
				.unwrap()
				.collect::<Vec<_>>(),
			vec![
				Ok((192, Some(2))),
				Ok((176, Some(2))),
				Ok((160, Some(2))),
				Ok((144, Some(2))),
				Ok((128, Some(2))),
				Ok((112, Some(2))),
				Ok((96, Some(2))),
				Ok((80, Some(2))),
				Ok((64, Some(2))),
				Ok((48, Some(2))),
			],
		);

		// when config activates at 30
		assert_eq!(
			surface_iterator(configuration_range(&config, 30u64), 100_000u64, 40u64, 180u64,)
				.unwrap()
				.collect::<Vec<_>>(),
			vec![
				Ok((190, Some(2))),
				Ok((174, Some(2))),
				Ok((158, Some(2))),
				Ok((142, Some(2))),
				Ok((126, Some(2))),
				Ok((110, Some(2))),
				Ok((94, Some(2))),
				Ok((78, Some(2))),
				Ok((62, Some(2))),
				Ok((46, Some(2))),
			],
		);

		// when config activates at 0 AND max block is before next digest
		assert_eq!(
			surface_iterator(configuration_range(&config, 0u64), 183u64, 40u64, 183u64)
				.unwrap()
				.collect::<Vec<_>>(),
			vec![
				Ok((183, Some(0))),
				Ok((182, Some(0))),
				Ok((181, Some(0))),
				Ok((180, Some(1))),
				Ok((176, Some(2))),
				Ok((160, Some(2))),
				Ok((144, Some(2))),
				Ok((128, Some(2))),
				Ok((112, Some(2))),
				Ok((96, Some(2))),
				Ok((80, Some(2))),
				Ok((64, Some(2))),
				Ok((48, Some(2))),
			],
		);
	}

	#[test]
	fn surface_iterator_works_with_skewed_digest() {
		let config = Configuration { digest_interval: 4, digest_levels: 2 };
		let mut config_range = configuration_range(&config, 0u64);

		// when config activates at 0 AND ends at 170
		config_range.end = Some(170);
		assert_eq!(
			surface_iterator(config_range, 100_000u64, 40u64, 170u64)
				.unwrap()
				.collect::<Vec<_>>(),
			vec![
				Ok((170, None)),
				Ok((160, Some(2))),
				Ok((144, Some(2))),
				Ok((128, Some(2))),
				Ok((112, Some(2))),
				Ok((96, Some(2))),
				Ok((80, Some(2))),
				Ok((64, Some(2))),
				Ok((48, Some(2))),
			],
		);
	}
}