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
// Copyright (C) 2021 Subspace Labs, Inc.
// 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.

//! Pallet feeds, used for storing arbitrary user-provided data combined into feeds.

#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]
#![warn(rust_2018_idioms, missing_debug_implementations)]

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
use alloc::vec;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::mem;
pub use pallet::*;
use subspace_core_primitives::{crypto, Blake3Hash};

pub mod feed_processor;
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;

#[frame_support::pallet]
mod pallet {
    use crate::feed_processor::{FeedMetadata, FeedProcessor as FeedProcessorT};
    use frame_support::pallet_prelude::*;
    use frame_system::pallet_prelude::*;
    use sp_runtime::traits::{CheckedAdd, Hash, One, StaticLookup};
    use sp_runtime::ArithmeticError;

    #[pallet::config]
    pub trait Config: frame_system::Config {
        /// `pallet-feeds` events
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

        // Feed ID uniquely identifies a Feed
        type FeedId: Parameter + Member + Default + Copy + PartialOrd + CheckedAdd + One;

        // Type that references to a particular impl of feed processor
        type FeedProcessorKind: Parameter + Member + Default + Copy;

        #[pallet::constant]
        type MaxFeeds: Get<u32>;

        fn feed_processor(
            feed_processor_kind: Self::FeedProcessorKind,
        ) -> Box<dyn FeedProcessorT<Self::FeedId>>;
    }

    /// Pallet feeds, used for storing arbitrary user-provided data combined into feeds.
    #[pallet::pallet]
    #[pallet::without_storage_info]
    pub struct Pallet<T>(_);

    /// User-provided object to store
    pub(super) type Object = Vec<u8>;
    /// User provided initial data for validation
    pub(super) type InitData = Vec<u8>;

    /// Total amount of data and number of objects stored in a feed
    #[derive(Debug, Decode, Encode, TypeInfo, Default, PartialEq, Eq)]
    pub struct TotalObjectsAndSize {
        /// Total size of objects in bytes
        pub size: u64,
        /// Total number of objects
        pub count: u64,
    }

    #[derive(Debug, Decode, Encode, TypeInfo, Default)]
    pub struct FeedConfig<FeedProcessorId, AccountId> {
        pub active: bool,
        pub feed_processor_id: FeedProcessorId,
        pub owner: AccountId,
    }

    #[pallet::storage]
    #[pallet::getter(fn metadata)]
    pub(super) type Metadata<T: Config> =
        StorageMap<_, Identity, T::FeedId, FeedMetadata, OptionQuery>;

    #[pallet::storage]
    #[pallet::getter(fn feed_configs)]
    pub(super) type FeedConfigs<T: Config> = StorageMap<
        _,
        Identity,
        T::FeedId,
        FeedConfig<T::FeedProcessorKind, T::AccountId>,
        OptionQuery,
    >;

    #[pallet::storage]
    #[pallet::getter(fn feeds)]
    pub(super) type Feeds<T: Config> =
        StorageMap<_, Identity, T::AccountId, BoundedVec<T::FeedId, T::MaxFeeds>, OptionQuery>;

    #[pallet::storage]
    #[pallet::getter(fn totals)]
    pub(super) type Totals<T: Config> =
        StorageMap<_, Identity, T::FeedId, TotalObjectsAndSize, ValueQuery>;

    #[pallet::storage]
    #[pallet::getter(fn next_feed_id)]
    pub(super) type NextFeedId<T: Config> = StorageValue<_, T::FeedId, ValueQuery>;

    #[pallet::storage]
    pub(super) type SuccessfulPuts<T: Config> = StorageValue<_, Vec<T::Hash>, ValueQuery>;

    /// `pallet-feeds` events
    #[pallet::event]
    #[pallet::generate_deposit(pub (super) fn deposit_event)]
    pub enum Event<T: Config> {
        /// New object was added.
        ObjectSubmitted {
            feed_id: T::FeedId,
            who: T::AccountId,
            metadata: FeedMetadata,
            object_size: u64,
        },
        /// New feed was created.
        FeedCreated {
            feed_id: T::FeedId,
            who: T::AccountId,
        },

        /// An existing feed was updated.
        FeedUpdated {
            feed_id: T::FeedId,
            who: T::AccountId,
        },

        /// Feed was closed.
        FeedClosed {
            feed_id: T::FeedId,
            who: T::AccountId,
        },

        /// Feed was deleted.
        FeedDeleted {
            feed_id: T::FeedId,
            who: T::AccountId,
        },

        /// feed ownership transferred
        OwnershipTransferred {
            feed_id: T::FeedId,
            old_owner: T::AccountId,
            new_owner: T::AccountId,
        },
    }

    /// `pallet-feeds` errors
    #[pallet::error]
    pub enum Error<T> {
        /// `FeedId` doesn't exist
        UnknownFeedId,

        /// Feed was closed
        FeedClosed,

        /// Not a feed owner
        NotFeedOwner,

        /// Maximum feeds created by the caller
        MaxFeedsReached,
    }

    macro_rules! ensure_owner {
        ( $origin:expr, $feed_id:expr ) => {{
            let sender = ensure_signed($origin)?;
            let feed_config = FeedConfigs::<T>::get($feed_id).ok_or(Error::<T>::UnknownFeedId)?;
            ensure!(feed_config.owner == sender, Error::<T>::NotFeedOwner);
            (sender, feed_config)
        }};
    }

    #[pallet::hooks]
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
        fn on_initialize(_now: BlockNumberFor<T>) -> Weight {
            SuccessfulPuts::<T>::kill();
            T::DbWeight::get().writes(1)
        }
    }

    #[pallet::call]
    impl<T: Config> Pallet<T> {
        // TODO: add proper weights
        /// Create a new feed
        #[pallet::call_index(0)]
        #[pallet::weight((10_000, Pays::No))]
        pub fn create(
            origin: OriginFor<T>,
            feed_processor_id: T::FeedProcessorKind,
            init_data: Option<InitData>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;
            let feed_id = NextFeedId::<T>::get();
            let next_feed_id = feed_id
                .checked_add(&One::one())
                .ok_or(ArithmeticError::Overflow)?;
            let feed_processor = T::feed_processor(feed_processor_id);
            if let Some(init_data) = init_data {
                feed_processor.init(feed_id, init_data.as_slice())?;
            }

            // check if max feeds are reached
            let mut owned_feeds = Feeds::<T>::get(who.clone()).unwrap_or_default();
            owned_feeds
                .try_push(feed_id)
                .map_err(|_| Error::<T>::MaxFeedsReached)?;

            NextFeedId::<T>::set(next_feed_id);
            FeedConfigs::<T>::insert(
                feed_id,
                FeedConfig {
                    active: true,
                    feed_processor_id,
                    owner: who.clone(),
                },
            );
            Feeds::<T>::insert(who.clone(), owned_feeds);
            Totals::<T>::insert(feed_id, TotalObjectsAndSize::default());

            Self::deposit_event(Event::FeedCreated { feed_id, who });

            Ok(())
        }

        /// Updates the feed with init data provided.
        #[pallet::call_index(1)]
        #[pallet::weight((10_000, Pays::No))]
        pub fn update(
            origin: OriginFor<T>,
            feed_id: T::FeedId,
            feed_processor_id: T::FeedProcessorKind,
            init_data: Option<InitData>,
        ) -> DispatchResult {
            let (owner, feed_config) = ensure_owner!(origin, feed_id);
            let feed_processor = T::feed_processor(feed_processor_id);
            if let Some(init_data) = init_data {
                feed_processor.init(feed_id, init_data.as_slice())?;
            }

            FeedConfigs::<T>::insert(
                feed_id,
                FeedConfig {
                    active: feed_config.active,
                    feed_processor_id,
                    owner: owner.clone(),
                },
            );

            Self::deposit_event(Event::FeedUpdated {
                feed_id,
                who: owner,
            });

            Ok(())
        }

        // TODO: add proper weights
        // TODO: For now we don't have fees, but we will have them in the future
        /// Put a new object into a feed
        #[pallet::call_index(2)]
        #[pallet::weight((10_000, Pays::No))]
        pub fn put(origin: OriginFor<T>, feed_id: T::FeedId, object: Object) -> DispatchResult {
            let (owner, feed_config) = ensure_owner!(origin, feed_id);
            // ensure feed is active
            ensure!(feed_config.active, Error::<T>::FeedClosed);

            let object_size = object.len() as u64;
            let feed_processor = T::feed_processor(feed_config.feed_processor_id);

            let metadata = feed_processor
                .put(feed_id, object.as_slice())?
                .unwrap_or_default();
            Metadata::<T>::insert(feed_id, metadata.clone());

            Totals::<T>::mutate(feed_id, |feed_totals| {
                feed_totals.size += object_size;
                feed_totals.count += 1;
            });

            Self::deposit_event(Event::ObjectSubmitted {
                feed_id,
                who: owner,
                metadata,
                object_size,
            });

            // store the call
            // there could be multiple calls with same hash and that is fine
            // since we assume the same order
            let uniq = T::Hashing::hash(Call::<T>::put { feed_id, object }.encode().as_slice());
            SuccessfulPuts::<T>::append(uniq);
            Ok(())
        }

        /// Closes the feed and stops accepting new feed.
        #[pallet::call_index(3)]
        #[pallet::weight((T::DbWeight::get().reads_writes(1, 1), Pays::No))]
        pub fn close(origin: OriginFor<T>, feed_id: T::FeedId) -> DispatchResult {
            let (owner, mut feed_config) = ensure_owner!(origin, feed_id);
            feed_config.active = false;
            FeedConfigs::<T>::insert(feed_id, feed_config);
            Self::deposit_event(Event::FeedClosed {
                feed_id,
                who: owner,
            });
            Ok(())
        }

        /// Transfers feed from current owner to new owner
        #[pallet::call_index(4)]
        #[pallet::weight((T::DbWeight::get().reads_writes(3, 3), Pays::No))]
        pub fn transfer(
            origin: OriginFor<T>,
            feed_id: T::FeedId,
            new_owner: <T::Lookup as StaticLookup>::Source,
        ) -> DispatchResult {
            let (owner, mut feed_config) = ensure_owner!(origin, feed_id);
            let new_owner = T::Lookup::lookup(new_owner)?;

            // remove current owner details
            let mut current_owner_feeds = Feeds::<T>::get(owner.clone()).unwrap_or_default();
            current_owner_feeds.retain(|x| *x != feed_id);

            // update new owner details
            feed_config.owner = new_owner.clone();
            let mut new_owner_feeds = Feeds::<T>::get(new_owner.clone()).unwrap_or_default();
            new_owner_feeds
                .try_push(feed_id)
                .map_err(|_| Error::<T>::MaxFeedsReached)?;

            // if the owner doesn't own any feed, then reclaim empty storage
            if current_owner_feeds.is_empty() {
                Feeds::<T>::remove(owner.clone());
            } else {
                Feeds::<T>::insert(owner.clone(), current_owner_feeds);
            }

            Feeds::<T>::insert(new_owner.clone(), new_owner_feeds);
            FeedConfigs::<T>::insert(feed_id, feed_config);
            Self::deposit_event(Event::OwnershipTransferred {
                feed_id,
                old_owner: owner,
                new_owner,
            });
            Ok(())
        }
    }
}

/// Mapping to the object offset within an extrinsic associated with given key
#[derive(Debug)]
pub struct CallObject {
    /// Key to the object located at the offset.
    pub key: Blake3Hash,
    /// Offset of object in the encoded call.
    pub offset: u32,
}

impl<T: Config> Pallet<T> {
    pub fn successful_puts() -> Vec<T::Hash> {
        SuccessfulPuts::<T>::get()
    }
}

impl<T: Config> Call<T> {
    /// Extract the call objects if an extrinsic corresponds to `put` call
    pub fn extract_call_objects(&self) -> Vec<CallObject> {
        match self {
            Self::put { feed_id, object } => {
                let feed_processor_id = match FeedConfigs::<T>::get(feed_id) {
                    Some(config) => config.feed_processor_id,
                    // return if this was a invalid extrinsic
                    None => return vec![],
                };
                let feed_processor = T::feed_processor(feed_processor_id);
                let objects_mappings = feed_processor.object_mappings(*feed_id, object);
                // +1 for the Call::put enum variant
                // Since first arg is feed_id, we bump the offset by its encoded size
                let base_offset = 1 + mem::size_of::<T::FeedId>() as u32;
                objects_mappings
                    .into_iter()
                    .filter_map(|object_mapping| {
                        let mut co = object_mapping.try_into_call_object(
                            feed_id,
                            object.as_slice(),
                            crypto::blake3_hash,
                        )?;
                        co.offset += base_offset;
                        Some(co)
                    })
                    .collect()
            }
            _ => Default::default(),
        }
    }
}