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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#![cfg_attr(not(feature = "std"), no_std)]
mod benchmarking;
pub mod weights;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
use codec::{Decode, Encode};
use frame_support::{
dispatch::{Dispatchable, GetDispatchInfo},
traits::{Currency, OnUnbalanced, ReservableCurrency},
};
use sp_runtime::traits::{BlakeTwo256, Hash, One, Saturating, Zero};
use sp_std::{prelude::*, result};
use sp_transaction_storage_proof::{
encode_index, random_chunk, InherentError, TransactionStorageProof, CHUNK_SIZE,
DEFAULT_STORAGE_PERIOD, INHERENT_IDENTIFIER,
};
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
pub use pallet::*;
pub use weights::WeightInfo;
pub const DEFAULT_MAX_TRANSACTION_SIZE: u32 = 8 * 1024 * 1024;
pub const DEFAULT_MAX_BLOCK_TRANSACTIONS: u32 = 512;
#[derive(Encode, Decode, Clone, sp_runtime::RuntimeDebug, PartialEq, Eq)]
pub struct TransactionInfo {
chunk_root: <BlakeTwo256 as Hash>::Output,
content_hash: <BlakeTwo256 as Hash>::Output,
size: u32,
block_chunks: u32,
}
fn num_chunks(bytes: u32) -> u32 {
((bytes as u64 + CHUNK_SIZE as u64 - 1) / CHUNK_SIZE as u64) as u32
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config {
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type Call: Parameter
+ Dispatchable<Origin = Self::Origin>
+ GetDispatchInfo
+ From<frame_system::Call<Self>>;
type Currency: ReservableCurrency<Self::AccountId>;
type FeeDestination: OnUnbalanced<NegativeImbalanceOf<Self>>;
type WeightInfo: WeightInfo;
}
#[pallet::error]
pub enum Error<T> {
InsufficientFunds,
NotConfigured,
RenewedNotFound,
EmptyTransaction,
UnexpectedProof,
InvalidProof,
MissingProof,
MissingStateData,
DoubleCheck,
ProofNotChecked,
TransactionTooLarge,
TooManyTransactions,
BadContext,
}
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(n: T::BlockNumber) -> Weight {
let period = <StoragePeriod<T>>::get();
let obsolete = n.saturating_sub(period.saturating_add(One::one()));
if obsolete > Zero::zero() {
<Transactions<T>>::remove(obsolete);
<ChunkCount<T>>::remove(obsolete);
}
T::DbWeight::get().reads_writes(2, 4)
}
fn on_finalize(n: T::BlockNumber) {
assert!(
<ProofChecked<T>>::take() || {
let number = <frame_system::Pallet<T>>::block_number();
let period = <StoragePeriod<T>>::get();
let target_number = number.saturating_sub(period);
target_number.is_zero() || <ChunkCount<T>>::get(target_number) == 0
},
"Storage proof must be checked once in the block"
);
let transactions = <BlockTransactions<T>>::take();
let total_chunks = transactions.last().map_or(0, |t| t.block_chunks);
if total_chunks != 0 {
<ChunkCount<T>>::insert(n, total_chunks);
<Transactions<T>>::insert(n, transactions);
}
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(T::WeightInfo::store(data.len() as u32))]
pub fn store(origin: OriginFor<T>, data: Vec<u8>) -> DispatchResult {
ensure!(data.len() > 0, Error::<T>::EmptyTransaction);
ensure!(
data.len() <= MaxTransactionSize::<T>::get() as usize,
Error::<T>::TransactionTooLarge
);
let sender = ensure_signed(origin)?;
Self::apply_fee(sender, data.len() as u32)?;
let chunk_count = num_chunks(data.len() as u32);
let chunks = data.chunks(CHUNK_SIZE).map(|c| c.to_vec()).collect();
let root = sp_io::trie::blake2_256_ordered_root(chunks);
let content_hash = sp_io::hashing::blake2_256(&data);
let extrinsic_index = <frame_system::Pallet<T>>::extrinsic_index()
.ok_or_else(|| Error::<T>::BadContext)?;
sp_io::transaction_index::index(extrinsic_index, data.len() as u32, content_hash);
let mut index = 0;
<BlockTransactions<T>>::mutate(|transactions| {
if transactions.len() + 1 > MaxBlockTransactions::<T>::get() as usize {
return Err(Error::<T>::TooManyTransactions)
}
let total_chunks = transactions.last().map_or(0, |t| t.block_chunks) + chunk_count;
index = transactions.len() as u32;
transactions.push(TransactionInfo {
chunk_root: root,
size: data.len() as u32,
content_hash: content_hash.into(),
block_chunks: total_chunks,
});
Ok(())
})?;
Self::deposit_event(Event::Stored(index));
Ok(())
}
#[pallet::weight(T::WeightInfo::renew())]
pub fn renew(
origin: OriginFor<T>,
block: T::BlockNumber,
index: u32,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
let transactions = <Transactions<T>>::get(block).ok_or(Error::<T>::RenewedNotFound)?;
let info = transactions.get(index as usize).ok_or(Error::<T>::RenewedNotFound)?;
Self::apply_fee(sender, info.size)?;
let extrinsic_index = <frame_system::Pallet<T>>::extrinsic_index().unwrap();
sp_io::transaction_index::renew(extrinsic_index, info.content_hash.into());
let mut index = 0;
<BlockTransactions<T>>::mutate(|transactions| {
if transactions.len() + 1 > MaxBlockTransactions::<T>::get() as usize {
return Err(Error::<T>::TooManyTransactions)
}
let chunks = num_chunks(info.size);
let total_chunks = transactions.last().map_or(0, |t| t.block_chunks) + chunks;
index = transactions.len() as u32;
transactions.push(TransactionInfo {
chunk_root: info.chunk_root,
size: info.size,
content_hash: info.content_hash,
block_chunks: total_chunks,
});
Ok(())
})?;
Self::deposit_event(Event::Renewed(index));
Ok(().into())
}
#[pallet::weight((T::WeightInfo::check_proof_max(), DispatchClass::Mandatory))]
pub fn check_proof(
origin: OriginFor<T>,
proof: TransactionStorageProof,
) -> DispatchResultWithPostInfo {
ensure_none(origin)?;
ensure!(!ProofChecked::<T>::get(), Error::<T>::DoubleCheck);
let number = <frame_system::Pallet<T>>::block_number();
let period = <StoragePeriod<T>>::get();
let target_number = number.saturating_sub(period);
ensure!(!target_number.is_zero(), Error::<T>::UnexpectedProof);
let total_chunks = <ChunkCount<T>>::get(target_number);
ensure!(total_chunks != 0, Error::<T>::UnexpectedProof);
let parent_hash = <frame_system::Pallet<T>>::parent_hash();
let selected_chunk_index = random_chunk(parent_hash.as_ref(), total_chunks);
let (info, chunk_index) = match <Transactions<T>>::get(target_number) {
Some(infos) => {
let index = match infos
.binary_search_by_key(&selected_chunk_index, |info| info.block_chunks)
{
Ok(index) => index,
Err(index) => index,
};
let info =
infos.get(index).ok_or_else(|| Error::<T>::MissingStateData)?.clone();
let chunks = num_chunks(info.size);
let prev_chunks = info.block_chunks - chunks;
(info, selected_chunk_index - prev_chunks)
},
None => Err(Error::<T>::MissingStateData)?,
};
ensure!(
sp_io::trie::blake2_256_verify_proof(
info.chunk_root,
&proof.proof,
&encode_index(chunk_index),
&proof.chunk,
),
Error::<T>::InvalidProof
);
ProofChecked::<T>::put(true);
Self::deposit_event(Event::ProofChecked);
Ok(().into())
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
Stored(u32),
Renewed(u32),
ProofChecked,
}
#[pallet::storage]
#[pallet::getter(fn transaction_roots)]
pub(super) type Transactions<T: Config> =
StorageMap<_, Blake2_128Concat, T::BlockNumber, Vec<TransactionInfo>, OptionQuery>;
#[pallet::storage]
pub(super) type ChunkCount<T: Config> =
StorageMap<_, Blake2_128Concat, T::BlockNumber, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn byte_fee)]
pub(super) type ByteFee<T: Config> = StorageValue<_, BalanceOf<T>>;
#[pallet::storage]
#[pallet::getter(fn entry_fee)]
pub(super) type EntryFee<T: Config> = StorageValue<_, BalanceOf<T>>;
#[pallet::storage]
#[pallet::getter(fn max_transaction_size)]
pub(super) type MaxTransactionSize<T: Config> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn max_block_transactions)]
pub(super) type MaxBlockTransactions<T: Config> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
pub(super) type StoragePeriod<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>;
#[pallet::storage]
pub(super) type BlockTransactions<T: Config> =
StorageValue<_, Vec<TransactionInfo>, ValueQuery>;
#[pallet::storage]
pub(super) type ProofChecked<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub byte_fee: BalanceOf<T>,
pub entry_fee: BalanceOf<T>,
pub storage_period: T::BlockNumber,
pub max_block_transactions: u32,
pub max_transaction_size: u32,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
byte_fee: 10u32.into(),
entry_fee: 1000u32.into(),
storage_period: DEFAULT_STORAGE_PERIOD.into(),
max_block_transactions: DEFAULT_MAX_BLOCK_TRANSACTIONS,
max_transaction_size: DEFAULT_MAX_TRANSACTION_SIZE,
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
<ByteFee<T>>::put(&self.byte_fee);
<EntryFee<T>>::put(&self.entry_fee);
<MaxTransactionSize<T>>::put(&self.max_transaction_size);
<MaxBlockTransactions<T>>::put(&self.max_block_transactions);
<StoragePeriod<T>>::put(&self.storage_period);
}
}
#[pallet::inherent]
impl<T: Config> ProvideInherent for Pallet<T> {
type Call = Call<T>;
type Error = InherentError;
const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
fn create_inherent(data: &InherentData) -> Option<Self::Call> {
let proof = data
.get_data::<TransactionStorageProof>(&Self::INHERENT_IDENTIFIER)
.unwrap_or(None);
proof.map(Call::check_proof)
}
fn check_inherent(
_call: &Self::Call,
_data: &InherentData,
) -> result::Result<(), Self::Error> {
Ok(())
}
fn is_inherent(call: &Self::Call) -> bool {
matches!(call, Call::check_proof(_))
}
}
impl<T: Config> Pallet<T> {
fn apply_fee(sender: T::AccountId, size: u32) -> DispatchResult {
let byte_fee = ByteFee::<T>::get().ok_or(Error::<T>::NotConfigured)?;
let entry_fee = EntryFee::<T>::get().ok_or(Error::<T>::NotConfigured)?;
let fee = byte_fee.saturating_mul(size.into()).saturating_add(entry_fee);
ensure!(T::Currency::can_slash(&sender, fee), Error::<T>::InsufficientFunds);
let (credit, _) = T::Currency::slash(&sender, fee);
T::FeeDestination::on_unbalanced(credit);
Ok(())
}
}
}