-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
377 lines (319 loc) · 14.4 KB
/
lib.rs
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
#![cfg_attr(not(feature = "std"), no_std)]
mod types;
mod builders;
/// Edit this file to define custom logic or remove it if it is not needed.
/// Learn more about FRAME and the core library of Substrate FRAME pallets:
/// <https://substrate.dev/docs/en/knowledgebase/runtime/frame>
pub use pallet::*;
use frame_support::{log::debug};
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[frame_support::pallet]
pub mod pallet {
use crate::builders::*;
use crate::types::*;
use codec::alloc::string::ToString;
use frame_support::dispatch::DispatchResultWithPostInfo;
use frame_support::pallet_prelude::EnsureOrigin;
use frame_support::pallet_prelude::IsType;
use frame_support::pallet_prelude::OptionQuery;
use frame_support::Blake2_128Concat;
use frame_support::{ pallet_prelude::*};
use frame_system::offchain::SendTransactionTypes;
use frame_system::pallet_prelude::OriginFor;
use frame_system::pallet_prelude::*;
use product_registry::ProductId;
use sp_runtime::offchain::storage::StorageValueRef;
use sp_std::vec;
use sp_std::vec::Vec;
pub const IDENTIFIER_MAX_LENGTH: usize = 36;
pub const SHIPMENT_MAX_PRODUCTS: usize = 10;
pub const LISTENER_ENDPOINT: &str = "http://localhost:3005";
pub const LOCK_TIMEOUT_EXPIRATION: u64 = 3000; // in milli-seconds
/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config:
frame_system::Config + pallet_timestamp::Config + SendTransactionTypes<Call<Self>>
{
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type CreateRoleOrigin: EnsureOrigin<Self::Origin>;
}
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::storage]
#[pallet::getter(fn shipment_by_id)]
pub type Shipments<T: Config> =
StorageMap<_, Blake2_128Concat, ShipmentId, Shipment<T::AccountId, T::Moment>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn shipments_of_org)]
pub type ShipmentsOfOrganization<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, Vec<ShipmentId>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn event_count)]
pub type EventCount<T> = StorageValue<_, u128, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn event_by_idx)]
pub type AllEvents<T: Config> =
StorageMap<_, Blake2_128Concat, ShippingEventIndex, ShippingEvent<T::Moment>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn events_of_shipment)]
pub type EventsOfShipment<T> =
StorageMap<_, Blake2_128Concat, ShipmentId, Vec<ShippingEventIndex>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn ocw_notifications)]
pub type OcwNotifications<T: Config> =
StorageMap<_, Identity, T::BlockNumber, Vec<ShippingEventIndex>, ValueQuery>;
// Pallets use events to inform users when important changes are made.
// https://substrate.dev/docs/en/knowledgebase/runtime/events
#[pallet::event]
#[pallet::metadata(T::AccountId = "AccountId")]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Event documentation should end with an array that provides descriptive names for event
/// parameters. [something, who]
ShipmentRegistered(T::AccountId, ShipmentId, T::AccountId),
ShipmentStatusUpdated(T::AccountId, ShipmentId, ShippingEventIndex, ShipmentStatus),
}
// Errors inform users that something went wrong.
#[pallet::error]
pub enum Error<T> {
InvalidOrMissingIdentifier,
ShipmentAlreadyExists,
ShipmentHasBeenDelivered,
ShipmentIsInTransit,
ShipmentIsUnknown,
ShipmentHasTooManyProducts,
ShippingEventAlreadyExists,
ShippingEventMaxExceeded,
OffchainWorkerAlreadyBusy,
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
// Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(10_000)]
pub fn register_shipment(
origin: OriginFor<T>,
id: ShipmentId,
owner: T::AccountId,
products: Vec<ProductId>,
) -> DispatchResultWithPostInfo {
T::CreateRoleOrigin::ensure_origin(origin.clone())?;
let who = ensure_signed(origin)?;
// Validate format of shipment ID
Self::validate_identifier(&id)?;
// Validate shipment products
Self::validate_shipment_products(&products)?;
// Check shipment doesn't exist yet (1 DB read)
Self::validate_new_shipment(&id)?;
// Create a shipment instance
let shipment = Self::new_shipment()
.identified_by(id.clone())
.owned_by(owner.clone())
.registered_at(<pallet_timestamp::Pallet<T>>::now())
.with_products(products)
.build();
let status = shipment.status.clone();
// Create shipping event
let event = Self::new_shipping_event()
.of_type(ShippingEventType::ShipmentRegistration)
.for_shipment(id.clone())
.at_location(None)
.with_readings(vec![])
.at_time(shipment.registered)
.build();
// Storage writes
// --------------
// Add shipment (2 DB write)
<Shipments<T>>::insert(&id, shipment);
<ShipmentsOfOrganization<T>>::append(&owner, &id);
// Store shipping event (1 DB read, 3 DB writes)
let event_idx = Self::store_event(event)?;
// Update offchain notifications (1 DB write)
<OcwNotifications<T>>::append(<frame_system::Pallet<T>>::block_number(), event_idx);
// Raise events
Self::deposit_event(Event::ShipmentRegistered(who.clone(), id.clone(), owner));
Self::deposit_event(Event::ShipmentStatusUpdated(who, id, event_idx, status));
Ok(().into())
}
#[pallet::weight(10_000)]
pub fn track_shipment(
origin: OriginFor<T>,
id: ShipmentId,
operation: ShippingOperation,
timestamp: T::Moment,
location: Option<ReadPoint>,
readings: Option<Vec<Reading<T::Moment>>>,
) -> DispatchResultWithPostInfo {
T::CreateRoleOrigin::ensure_origin(origin.clone())?;
let who = ensure_signed(origin)?;
// Validate format of shipment ID
Self::validate_identifier(&id)?;
// Check shipment is known (1 DB read) & do transition checks
let mut shipment = match <Shipments<T>>::get(&id) {
Some(shipment) => match shipment.status {
ShipmentStatus::Delivered => Err(<Error<T>>::ShipmentHasBeenDelivered),
ShipmentStatus::InTransit if operation == ShippingOperation::Pickup => {
Err(<Error<T>>::ShipmentIsInTransit)
}
_ => Ok(shipment),
},
None => Err(<Error<T>>::ShipmentIsUnknown),
}?;
// Update shipment status
shipment = match operation {
ShippingOperation::Pickup => shipment.pickup(),
ShippingOperation::Deliver => shipment.deliver(timestamp),
_ => shipment,
};
let status = shipment.status.clone();
// Create shipping event
let event = Self::new_shipping_event()
.of_type(operation.clone().into())
.for_shipment(id.clone())
.at_location(location)
.with_readings(readings.unwrap_or_default())
.at_time(timestamp)
.build();
// Storage writes
// --------------
// Store shipping event (1 DB read, 3 DB writes)
let event_idx = Self::store_event(event)?;
// Update offchain notifications (1 DB write)
<OcwNotifications<T>>::append(<frame_system::Pallet<T>>::block_number(), event_idx);
if operation != ShippingOperation::Scan {
// Update shipment (1 DB write)
<Shipments<T>>::insert(&id, shipment);
// Raise events
Self::deposit_event(Event::ShipmentStatusUpdated(who, id, event_idx, status));
}
Ok(().into())
}
// pub fn offchain_worker(block_number: T::BlockNumber) {
// // Acquiring the lock
// let mut lock = StorageLock::<Time>::with_deadline(
// b"product_tracking_ocw::lock",
// rt_offchain::Duration::from_millis(LOCK_TIMEOUT_EXPIRATION)
// );
// match lock.try_lock() {
// Ok(_guard) => { Self::process_ocw_notifications(block_number); }
// Err(_err) => { debug::info!("[product_tracking_ocw] lock is already acquired"); }
// };
// }
}
#[allow(dead_code)]
impl<T: Config> Pallet<T> {
fn new_shipment() -> ShipmentBuilder<T::AccountId, T::Moment> {
ShipmentBuilder::<T::AccountId, T::Moment>::default()
}
fn new_shipping_event() -> ShippingEventBuilder<T::Moment> {
ShippingEventBuilder::<T::Moment>::default()
}
fn store_event(event: ShippingEvent<T::Moment>) -> Result<ShippingEventIndex, Error<T>> {
let event_idx = EventCount::<T>::get()
.checked_add(1)
.ok_or(Error::<T>::ShippingEventMaxExceeded)?;
EventCount::<T>::put(event_idx);
EventsOfShipment::<T>::append(&event.shipment_id, event_idx);
<AllEvents<T>>::insert(event_idx, event);
Ok(event_idx)
}
// (Public) Validation methods
pub fn validate_identifier(id: &[u8]) -> Result<(), Error<T>> {
// Basic identifier validation
ensure!(!id.is_empty(), Error::<T>::InvalidOrMissingIdentifier);
ensure!(
id.len() <= IDENTIFIER_MAX_LENGTH,
Error::<T>::InvalidOrMissingIdentifier
);
Ok(())
}
pub fn validate_new_shipment(id: &[u8]) -> Result<(), Error<T>> {
// Shipment existence check
ensure!(
!<Shipments<T>>::contains_key(id),
Error::<T>::ShipmentAlreadyExists
);
Ok(())
}
pub fn validate_shipment_products(props: &[ProductId]) -> Result<(), Error<T>> {
ensure!(
props.len() <= SHIPMENT_MAX_PRODUCTS,
Error::<T>::ShipmentHasTooManyProducts,
);
Ok(())
}
// --- Offchain worker methods ---
fn process_ocw_notifications(block_number: T::BlockNumber) {
// Check last processed block
// let last_processed_block_ref =
// StorageValueRef::persistent(b"product_tracking_ocw::last_proccessed_block");
// let mut last_processed_block: u32 = match last_processed_block_ref.get::<T::BlockNumber>()
// {
// Some(Some(last_proccessed_block)) => {
// last_proccessed_block.try_into().ok().unwrap() as u32
// }
// None => 0u32, //TODO: define a OCW_MAX_BACKTRACK_PERIOD param
// _ => {
// debug::error!("[product_tracking_ocw] Error reading product_tracking_ocw::last_proccessed_block.");
// return;
// }
// };
// let start_block = last_processed_block + 1;
// let end_block = block_number.try_into().ok().unwrap() as u32;
// for current_block in start_block..end_block {
// debug::debug!(
// "[product_tracking_ocw] Processing notifications for block {}",
// current_block
// );
// let ev_indices = Self::ocw_notifications::<T::BlockNumber>(current_block.into());
// let listener_results: Result<Vec<_>, _> = ev_indices
// .iter()
// .map(|idx| match Self::event_by_idx(idx) {
// Some(ev) => Self::notify_listener(&ev),
// None => Ok(()),
// })
// .collect();
// if let Err(err) = listener_results {
// debug::warn!("[product_tracking_ocw] notify_listener error: {}", err);
// break;
// }
// last_processed_block = current_block;
// }
// // Save last processed block
// if last_processed_block >= start_block {
// last_processed_block_ref.set(&last_processed_block);
// debug::info!(
// "[product_tracking_ocw] Notifications successfully processed up to block {}",
// last_processed_block
// );
// }
}
fn notify_listener(ev: &ShippingEvent<T::Moment>) -> Result<(), &'static str> {
let request =
sp_runtime::offchain::http::Request::post(&LISTENER_ENDPOINT, vec![ev.to_string()]);
let timeout =
sp_io::offchain::timestamp().add(sp_runtime::offchain::Duration::from_millis(3000));
let pending = request
.add_header(&"Content-Type", &"text/plain")
.deadline(timeout) // Setting the timeout time
.send() // Sending the request out by the host
.map_err(|_| "http post request building error")?;
let response = pending
.try_wait(timeout)
.map_err(|_| "http post request sent error")?
.map_err(|_| "http post request sent error")?;
if response.code != 200 {
return Err("http response error");
}
Ok(())
}
}
}