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

// Copyright (C) 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.

//! All benchmarks in this file are just for debugging the PoV calculation logic, they are unused.

#![cfg(feature = "runtime-benchmarks")]

use super::*;

use frame_support::traits::UnfilteredDispatchable;
use frame_system::{Pallet as System, RawOrigin};
use sp_runtime::traits::Hash;

frame_benchmarking::benchmarks! {
	storage_single_value_read {
		Value::<T>::put(123);
	}: {
		assert_eq!(Value::<T>::get(), Some(123));
	}

	#[pov_mode = Ignored]
	storage_single_value_ignored_read {
		Value::<T>::put(123);
	}: {
		assert_eq!(Value::<T>::get(), Some(123));
	}

	#[pov_mode = MaxEncodedLen {
		Pov::Value2: Ignored
	}]
	storage_single_value_ignored_some_read {
		Value::<T>::put(123);
		Value2::<T>::put(123);
	}: {
		assert_eq!(Value::<T>::get(), Some(123));
		assert_eq!(Value2::<T>::get(), Some(123));
	}

	storage_single_value_read_twice {
		Value::<T>::put(123);
	}: {
		assert_eq!(Value::<T>::get(), Some(123));
		assert_eq!(Value::<T>::get(), Some(123));
	}

	storage_single_value_write {
	}: {
		Value::<T>::put(123);
	} verify {
		assert_eq!(Value::<T>::get(), Some(123));
	}

	storage_single_value_kill {
		Value::<T>::put(123);
	}: {
		Value::<T>::kill();
	} verify {
		assert!(!Value::<T>::exists());
	}

	// This benchmark and the following are testing a storage map with adjacent storage items.
	//
	// First a storage map is filled and a specific number of other storage items is
	// created. Then the one value is read from the map. This demonstrates that the number of other
	// nodes in the Trie influences the proof size. The number of inserted nodes can be interpreted
	// as the number of `StorageMap`/`StorageValue` in the whole runtime.
	#[pov_mode = Measured]
	storage_1m_map_read_one_value_two_additional_layers {
		(0..(1<<10)).for_each(|i| Map1M::<T>::insert(i, i));
		// Assume there are 16-256 other storage items.
		(0..(1u32<<4)).for_each(|i| {
			let k = T::Hashing::hash(&i.to_be_bytes());
			frame_support::storage::unhashed::put(k.as_ref(), &i);
		});
	}: {
		assert_eq!(Map1M::<T>::get(1<<9), Some(1<<9));
	}

	#[pov_mode = Measured]
	storage_1m_map_read_one_value_three_additional_layers {
		(0..(1<<10)).for_each(|i| Map1M::<T>::insert(i, i));
		// Assume there are 256-4096 other storage items.
		(0..(1u32<<8)).for_each(|i| {
			let k = T::Hashing::hash(&i.to_be_bytes());
			frame_support::storage::unhashed::put(k.as_ref(), &i);
		});
	}: {
		assert_eq!(Map1M::<T>::get(1<<9), Some(1<<9));
	}

	#[pov_mode = Measured]
	storage_1m_map_read_one_value_four_additional_layers {
		(0..(1<<10)).for_each(|i| Map1M::<T>::insert(i, i));
		// Assume there are 4096-65536 other storage items.
		(0..(1u32<<12)).for_each(|i| {
			let k = T::Hashing::hash(&i.to_be_bytes());
			frame_support::storage::unhashed::put(k.as_ref(), &i);
		});
	}: {
		assert_eq!(Map1M::<T>::get(1<<9), Some(1<<9));
	}

	// Reads from both storage maps each `n` and `m` times. Should result in two linear components.
	storage_map_read_per_component {
		let n in 0 .. 100;
		let m in 0 .. 100;

		(0..m*10).for_each(|i| Map1M::<T>::insert(i, i));
		(0..n*10).for_each(|i| Map16M::<T>::insert(i, i));
	}: {
		(0..m).for_each(|i|
			assert_eq!(Map1M::<T>::get(i*10), Some(i*10)));
		(0..n).for_each(|i|
			assert_eq!(Map16M::<T>::get(i*10), Some(i*10)));
	}

	#[pov_mode = MaxEncodedLen {
		Pov::Map1M: Ignored
	}]
	storage_map_read_per_component_one_ignored {
		let n in 0 .. 100;
		let m in 0 .. 100;

		(0..m*10).for_each(|i| Map1M::<T>::insert(i, i));
		(0..n*10).for_each(|i| Map16M::<T>::insert(i, i));
	}: {
		(0..m).for_each(|i|
			assert_eq!(Map1M::<T>::get(i*10), Some(i*10)));
		(0..n).for_each(|i|
			assert_eq!(Map16M::<T>::get(i*10), Some(i*10)));
	}

	// Reads the same value from a storage map. Should not result in a component.
	storage_1m_map_one_entry_repeated_read {
		let n in 0 .. 100;
		Map1M::<T>::insert(0, 0);
	}: {
		(0..n).for_each(|i|
			assert_eq!(Map1M::<T>::get(0), Some(0)));
	}

	// Reads the same values from a storage map. Should result in a `1x` linear component.
	storage_1m_map_multiple_entry_repeated_read {
		let n in 0 .. 100;
		(0..n).for_each(|i| Map1M::<T>::insert(i, i));
	}: {
		(0..n).for_each(|i| {
			// Reading the same value 10 times does nothing.
			(0..10).for_each(|j|
				assert_eq!(Map1M::<T>::get(i), Some(i)));
		});
	}

	storage_1m_double_map_read_per_component {
		let n in 0 .. 1024;
		(0..(1<<10)).for_each(|i| DoubleMap1M::<T>::insert(i, i, i));
	}: {
		(0..n).for_each(|i|
			assert_eq!(DoubleMap1M::<T>::get(i, i), Some(i)));
	}

	storage_value_bounded_read {
	}: {
		assert!(BoundedValue::<T>::get().is_none());
	}

	// Reading unbounded values will produce no mathematical worst case PoV size for this component.
	storage_value_unbounded_read {
	}: {
		assert!(UnboundedValue::<T>::get().is_none());
	}

	#[pov_mode = Ignored]
	storage_value_unbounded_ignored_read {
	}: {
		assert!(UnboundedValue::<T>::get().is_none());
	}

	// Same as above, but we still expect a mathematical worst case PoV size for the bounded one.
	storage_value_bounded_and_unbounded_read {
		(0..1024).for_each(|i| Map1M::<T>::insert(i, i));
	}: {
		assert!(UnboundedValue::<T>::get().is_none());
		assert!(BoundedValue::<T>::get().is_none());
	}

	#[pov_mode = Measured]
	measured_storage_value_read_linear_size {
		let l in 0 .. 1<<22;
		let v: sp_runtime::BoundedVec<u8, _> = sp_std::vec![0u8; l as usize].try_into().unwrap();
		LargeValue::<T>::put(&v);
	}: {
		assert!(LargeValue::<T>::get().is_some());
	}

	#[pov_mode = MaxEncodedLen]
	mel_storage_value_read_linear_size {
		let l in 0 .. 1<<22;
		let v: sp_runtime::BoundedVec<u8, _> = sp_std::vec![0u8; l as usize].try_into().unwrap();
		LargeValue::<T>::put(&v);
	}: {
		assert!(LargeValue::<T>::get().is_some());
	}

	#[pov_mode = Measured]
	measured_storage_double_value_read_linear_size {
		let l in 0 .. 1<<22;
		let v: sp_runtime::BoundedVec<u8, _> = sp_std::vec![0u8; l as usize].try_into().unwrap();
		LargeValue::<T>::put(&v);
		LargeValue2::<T>::put(&v);
	}: {
		assert!(LargeValue::<T>::get().is_some());
		assert!(LargeValue2::<T>::get().is_some());
	}

	#[pov_mode = MaxEncodedLen]
	mel_storage_double_value_read_linear_size {
		let l in 0 .. 1<<22;
		let v: sp_runtime::BoundedVec<u8, _> = sp_std::vec![0u8; l as usize].try_into().unwrap();
		LargeValue::<T>::put(&v);
		LargeValue2::<T>::put(&v);
	}: {
		assert!(LargeValue::<T>::get().is_some());
		assert!(LargeValue2::<T>::get().is_some());
	}

	#[pov_mode = MaxEncodedLen {
		Pov::LargeValue2: Measured
	}]
	mel_mixed_storage_double_value_read_linear_size {
		let l in 0 .. 1<<22;
		let v: sp_runtime::BoundedVec<u8, _> = sp_std::vec![0u8; l as usize].try_into().unwrap();
		LargeValue::<T>::put(&v);
		LargeValue2::<T>::put(&v);
	}: {
		assert!(LargeValue::<T>::get().is_some());
		assert!(LargeValue2::<T>::get().is_some());
	}

	#[pov_mode = Measured {
		Pov::LargeValue2: MaxEncodedLen
	}]
	measured_mixed_storage_double_value_read_linear_size {
		let l in 0 .. 1<<22;
		let v: sp_runtime::BoundedVec<u8, _> = sp_std::vec![0u8; l as usize].try_into().unwrap();
		LargeValue::<T>::put(&v);
		LargeValue2::<T>::put(&v);
	}: {
		assert!(LargeValue::<T>::get().is_some());
		assert!(LargeValue2::<T>::get().is_some());
	}

	#[pov_mode = Measured]
	storage_map_unbounded_both_measured_read {
		let i in 0 .. 1000;

		UnboundedMap::<T>::insert(i, sp_std::vec![0; i as usize]);
		UnboundedMap2::<T>::insert(i, sp_std::vec![0; i as usize]);
	}: {
		assert!(UnboundedMap::<T>::get(i).is_some());
		assert!(UnboundedMap2::<T>::get(i).is_some());
	}

	#[pov_mode = MaxEncodedLen {
		Pov::UnboundedMap: Measured
	}]
	storage_map_partial_unbounded_read {
		let i in 0 .. 1000;

		Map1M::<T>::insert(i, 0);
		UnboundedMap::<T>::insert(i, sp_std::vec![0; i as usize]);
	}: {
		assert!(Map1M::<T>::get(i).is_some());
		assert!(UnboundedMap::<T>::get(i).is_some());
	}

	#[pov_mode = MaxEncodedLen {
		Pov::UnboundedMap: Ignored
	}]
	storage_map_partial_unbounded_ignored_read {
		let i in 0 .. 1000;

		Map1M::<T>::insert(i, 0);
		UnboundedMap::<T>::insert(i, sp_std::vec![0; i as usize]);
	}: {
		assert!(Map1M::<T>::get(i).is_some());
		assert!(UnboundedMap::<T>::get(i).is_some());
	}

	// Emitting an event will not incur any PoV.
	emit_event {
		// Emit a single event.
		let call = Call::<T>::emit_event {  };
	}: { call.dispatch_bypass_filter(RawOrigin::Root.into()).unwrap(); }
	verify {
		assert_eq!(System::<T>::events().len(), 1);
	}

	// A No-OP will not incur any PoV.
	noop {
		let call = Call::<T>::noop { };
	}: {
		call.dispatch_bypass_filter(RawOrigin::Root.into()).unwrap();
	}

	storage_iteration {
		for i in 0..65000 {
			UnboundedMapTwox::<T>::insert(i, sp_std::vec![0; 64]);
		}
	}: {
		for (key, value) in UnboundedMapTwox::<T>::iter() {
			unsafe {
				core::ptr::read_volatile(&key);
				core::ptr::read_volatile(value.as_ptr());
			}
		}
	}

	impl_benchmark_test_suite!(
		Pallet,
		mock::new_test_ext(),
		mock::Test,
	);
}

#[cfg(test)]
mod mock {
	use sp_runtime::{testing::H256, BuildStorage};

	type AccountId = u64;
	type Nonce = u32;

	type Block = frame_system::mocking::MockBlock<Test>;

	frame_support::construct_runtime!(
		pub enum Test
		{
			System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
			Baseline: crate::{Pallet, Call, Storage, Event<T>},
		}
	);

	impl frame_system::Config for Test {
		type BaseCallFilter = frame_support::traits::Everything;
		type BlockWeights = ();
		type BlockLength = ();
		type DbWeight = ();
		type RuntimeOrigin = RuntimeOrigin;
		type Nonce = Nonce;
		type RuntimeCall = RuntimeCall;
		type Hash = H256;
		type Hashing = ::sp_runtime::traits::BlakeTwo256;
		type AccountId = AccountId;
		type Lookup = sp_runtime::traits::IdentityLookup<Self::AccountId>;
		type Block = Block;
		type RuntimeEvent = RuntimeEvent;
		type BlockHashCount = ();
		type Version = ();
		type PalletInfo = PalletInfo;
		type AccountData = ();
		type OnNewAccount = ();
		type OnKilledAccount = ();
		type SystemWeightInfo = ();
		type SS58Prefix = ();
		type OnSetCode = ();
		type MaxConsumers = frame_support::traits::ConstU32<16>;
	}

	impl crate::Config for Test {
		type RuntimeEvent = RuntimeEvent;
	}

	pub fn new_test_ext() -> sp_io::TestExternalities {
		frame_system::GenesisConfig::<Test>::default().build_storage().unwrap().into()
	}
}