-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathout.rs
465 lines (465 loc) · 16.2 KB
/
out.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
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#![feature(prelude_import)]
#[prelude_import]
use std::prelude::rust_2021::*;
#[macro_use]
extern crate std;
mod balances {
use num::traits::{CheckedAdd, CheckedSub, Zero};
use std::collections::BTreeMap;
/// The configuration trait for the Balances Module.
/// Contains the basic types needed for handling balances.
pub trait Config: crate::system::Config {
/// A type which can represent the balance of an account.
/// Usually this is a large unsigned integer.
type Balance: Zero + CheckedSub + CheckedAdd + Copy;
}
/// This is the Balances Module.
/// It is a simple module which keeps track of how much balance each account has in this state
/// machine.
pub struct Pallet<T: Config> {
balances: BTreeMap<T::AccountId, T::Balance>,
}
#[automatically_derived]
impl<T: ::core::fmt::Debug + Config> ::core::fmt::Debug for Pallet<T>
where
T::AccountId: ::core::fmt::Debug,
T::Balance: ::core::fmt::Debug,
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(
f,
"Pallet",
"balances",
&&self.balances,
)
}
}
impl<T: Config> Pallet<T> {
pub fn new() -> Self {
Self { balances: BTreeMap::new() }
}
/// Set the balance of an account `who` to some `amount`.
pub fn set_balance(&mut self, who: &T::AccountId, amount: T::Balance) {
self.balances.insert(who.clone(), amount);
}
/// Get the balance of an account `who`.
/// If the account has no stored balance, we return zero.
pub fn balance(&self, who: &T::AccountId) -> T::Balance {
*self.balances.get(who).unwrap_or(&T::Balance::zero())
}
}
impl<T: Config> Pallet<T> {
/// Transfer `amount` from one account to another.
/// This function verifies that `from` has at least `amount` balance to transfer,
/// and that no mathematical overflows occur.
pub fn transfer(
&mut self,
caller: T::AccountId,
to: T::AccountId,
amount: T::Balance,
) -> crate::support::DispatchResult {
let caller_balance = self.balance(&caller);
let to_balance = self.balance(&to);
let new_caller_balance = caller_balance
.checked_sub(&amount)
.ok_or("Not enough funds.")?;
let new_to_balance = to_balance.checked_add(&amount).ok_or("Overflow")?;
self.balances.insert(caller, new_caller_balance);
self.balances.insert(to, new_to_balance);
Ok(())
}
}
#[allow(non_camel_case_types)]
pub enum Call<T: Config> {
transfer { to: T::AccountId, amount: T::Balance },
}
impl<T: Config> crate::support::Dispatch for Pallet<T> {
type Caller = T::AccountId;
type Call = Call<T>;
fn dispatch(
&mut self,
caller: Self::Caller,
call: Self::Call,
) -> crate::support::DispatchResult {
match call {
Call::transfer { to, amount } => {
self.transfer(caller, to, amount)?;
}
}
Ok(())
}
}
}
mod proof_of_existence {
use crate::support::DispatchResult;
use core::fmt::Debug;
use std::collections::BTreeMap;
pub trait Config: crate::system::Config {
/// The type which represents the content that can be claimed using this pallet.
/// Could be the content directly as bytes, or better yet the hash of that content.
/// We leave that decision to the runtime developer.
type Content: Debug + Ord;
}
/// This is the Proof of Existence Module.
/// It is a simple module that allows accounts to claim existence of some data.
pub struct Pallet<T: Config> {
/// A simple storage map from content to the owner of that content.
/// Accounts can make multiple different claims, but each claim can only have one owner.
claims: BTreeMap<T::Content, T::AccountId>,
}
#[automatically_derived]
impl<T: ::core::fmt::Debug + Config> ::core::fmt::Debug for Pallet<T>
where
T::Content: ::core::fmt::Debug,
T::AccountId: ::core::fmt::Debug,
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(
f,
"Pallet",
"claims",
&&self.claims,
)
}
}
impl<T: Config> Pallet<T> {
/// Create a new instance of the Proof of Existence Module.
pub fn new() -> Self {
Self { claims: BTreeMap::new() }
}
/// Get the owner (if any) of a claim.
pub fn get_claim(&self, claim: &T::Content) -> Option<&T::AccountId> {
self.claims.get(claim)
}
}
impl<T: Config> Pallet<T> {
/// Create a new claim on behalf of the `caller`.
/// This function will return an error if someone already has claimed that content.
pub fn create_claim(
&mut self,
caller: T::AccountId,
claim: T::Content,
) -> DispatchResult {
if self.claims.contains_key(&claim) {
return Err(&"This content is already claimed");
}
self.claims.insert(claim, caller);
Ok(())
}
/// Revoke an existing claim on some content.
/// This function should only succeed if the caller is the owner of an existing claim.
/// It will return an error if the claim does not exist, or if the caller is not the owner.
pub fn revoke_claim(
&mut self,
caller: T::AccountId,
claim: T::Content,
) -> DispatchResult {
let owner = match self.get_claim(&claim) {
None => return Err("Claim does not exist"),
Some(o) => o,
};
if *owner != caller {
return Err("The caller does not own this claim");
}
self.claims.remove(&claim);
Ok(())
}
}
#[allow(non_camel_case_types)]
pub enum Call<T: Config> {
create_claim { claim: T::Content },
revoke_claim { claim: T::Content },
}
impl<T: Config> crate::support::Dispatch for Pallet<T> {
type Caller = T::AccountId;
type Call = Call<T>;
fn dispatch(
&mut self,
caller: Self::Caller,
call: Self::Call,
) -> crate::support::DispatchResult {
match call {
Call::create_claim { claim } => {
self.create_claim(caller, claim)?;
}
Call::revoke_claim { claim } => {
self.revoke_claim(caller, claim)?;
}
}
Ok(())
}
}
}
mod support {
/// The most primitive representation of a Blockchain block.
pub struct Block<Header, Extrinsic> {
/// The block header contains metadata about the block.
pub header: Header,
/// The extrinsics represent the state transitions to be executed in this block.
pub extrinsics: Vec<Extrinsic>,
}
/// We are using an extremely simplified header which only contains the current block number.
/// On a real blockchain, you would expect to also find:
/// - parent block hash
/// - state root
/// - extrinsics root
/// - etc...
pub struct Header<BlockNumber> {
pub block_number: BlockNumber,
}
/// This is an "extrinsic": literally an external message from outside of the blockchain.
/// This simplified version of an extrinsic tells us who is making the call, and which call they are
/// making.
pub struct Extrinsic<Caller, Call> {
pub caller: Caller,
pub call: Call,
}
/// The Result type for our runtime. When everything completes successfully, we return `Ok(())`,
/// otherwise return a static error message.
pub type DispatchResult = Result<(), &'static str>;
/// A trait which allows us to dispatch an incoming extrinsic to the appropriate state transition
/// function call.
pub trait Dispatch {
/// The type used to identify the caller of the function.
type Caller;
/// The state transition function call the caller is trying to access.
type Call;
/// This function takes a `caller` and the `call` they want to make, and returns a `Result`
/// based on the outcome of that function call.
fn dispatch(&mut self, caller: Self::Caller, call: Self::Call) -> DispatchResult;
}
}
mod system {
use num::traits::{One, Zero};
use std::collections::BTreeMap;
pub trait Config {
type AccountId: Ord + Clone;
type BlockNumber: Zero + One + Copy;
type Nonce: Zero + One + Copy;
}
pub struct Pallet<T: Config> {
block_number: T::BlockNumber,
nonce: BTreeMap<T::AccountId, T::Nonce>,
}
#[automatically_derived]
impl<T: ::core::fmt::Debug + Config> ::core::fmt::Debug for Pallet<T>
where
T::BlockNumber: ::core::fmt::Debug,
T::AccountId: ::core::fmt::Debug,
T::Nonce: ::core::fmt::Debug,
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(
f,
"Pallet",
"block_number",
&self.block_number,
"nonce",
&&self.nonce,
)
}
}
impl<T: Config> Pallet<T> {
pub fn new() -> Self {
Pallet {
block_number: Zero::zero(),
nonce: BTreeMap::new(),
}
}
pub fn block_number(&self) -> T::BlockNumber {
self.block_number
}
pub fn inc_block_number(&mut self) {
self.block_number = self.block_number + One::one();
}
pub fn inc_nonce(&mut self, who: &T::AccountId) {
let prev = *self.nonce.get(who).unwrap_or(&Zero::zero());
self.nonce.insert(who.clone(), prev + One::one());
}
}
}
use crate::support::Dispatch;
mod types {
pub type AccountId = String;
pub type Balance = u128;
pub type Block = crate::support::Block<Header, Extrinsic>;
pub type BlockNumber = u32;
pub type Content = &'static str;
pub type Extrinsic = crate::support::Extrinsic<AccountId, crate::RuntimeCall>;
pub type Header = crate::support::Header<BlockNumber>;
pub type Nonce = u32;
}
pub enum RuntimeCall {
Balances(balances::Call<Runtime>),
ProofOfExistence(proof_of_existence::Call<Runtime>),
}
pub struct Runtime {
system: system::Pallet<Self>,
balances: balances::Pallet<Self>,
proof_of_existence: proof_of_existence::Pallet<Self>,
}
#[automatically_derived]
impl ::core::fmt::Debug for Runtime {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(
f,
"Runtime",
"system",
&self.system,
"balances",
&self.balances,
"proof_of_existence",
&&self.proof_of_existence,
)
}
}
impl system::Config for Runtime {
type AccountId = types::AccountId;
type BlockNumber = types::BlockNumber;
type Nonce = types::Nonce;
}
impl balances::Config for Runtime {
type Balance = types::Balance;
}
impl proof_of_existence::Config for Runtime {
type Content = types::Content;
}
impl Runtime {
fn new() -> Self {
Runtime {
system: system::Pallet::new(),
balances: balances::Pallet::new(),
proof_of_existence: proof_of_existence::Pallet::new(),
}
}
fn execute_block(&mut self, block: types::Block) -> support::DispatchResult {
self.system.inc_block_number();
if block.header.block_number != self.system.block_number() {
return Err("Invalid block number");
}
for (i, support::Extrinsic { caller, call }) in block
.extrinsics
.into_iter()
.enumerate()
{
self.system.inc_nonce(&caller);
let _res = self
.dispatch(caller, call)
.map_err(|e| {
{
::std::io::_eprint(
format_args!(
"Extrinsic Error\n\tBlock Number: {0}\n\tExtrinsic Number: {1}\n\tError: {2}\n",
block.header.block_number,
i,
e,
),
);
}
});
}
Ok(())
}
}
impl crate::support::Dispatch for Runtime {
type Caller = <Runtime as system::Config>::AccountId;
type Call = RuntimeCall;
fn dispatch(
&mut self,
caller: Self::Caller,
runtime_call: Self::Call,
) -> support::DispatchResult {
match runtime_call {
RuntimeCall::Balances(call) => self.balances.dispatch(caller, call)?,
RuntimeCall::ProofOfExistence(call) => {
self.proof_of_existence.dispatch(caller, call)?
}
}
Ok(())
}
}
fn main() {
let mut runtime = Runtime::new();
let alice = "alice".to_string();
let bob = "bob".to_string();
let charlie = "charlie".to_string();
runtime.balances.set_balance(&alice, 100);
let block_1 = crate::types::Block {
header: crate::types::Header {
block_number: 1,
},
extrinsics: <[_]>::into_vec(
#[rustc_box]
::alloc::boxed::Box::new([
crate::types::Extrinsic {
caller: alice.clone(),
call: RuntimeCall::Balances(balances::Call::transfer {
to: bob.clone(),
amount: 30,
}),
},
crate::types::Extrinsic {
caller: alice.clone(),
call: RuntimeCall::Balances(balances::Call::transfer {
to: charlie.clone(),
amount: 20,
}),
},
]),
),
};
runtime.execute_block(block_1).expect("Invalid block");
let block_2 = crate::types::Block {
header: crate::types::Header {
block_number: 2,
},
extrinsics: <[_]>::into_vec(
#[rustc_box]
::alloc::boxed::Box::new([
crate::types::Extrinsic {
caller: alice.clone(),
call: RuntimeCall::ProofOfExistence(proof_of_existence::Call::create_claim {
claim: "Alice's claim",
}),
},
crate::types::Extrinsic {
caller: bob.clone(),
call: RuntimeCall::ProofOfExistence(proof_of_existence::Call::create_claim {
claim: "Bob's claim",
}),
},
crate::types::Extrinsic {
caller: alice.clone(),
call: RuntimeCall::ProofOfExistence(proof_of_existence::Call::revoke_claim {
claim: "Alice's claim",
}),
},
]),
),
};
runtime.execute_block(block_2).expect("Invalid block");
let block_3 = crate::types::Block {
header: crate::types::Header {
block_number: 3,
},
extrinsics: <[_]>::into_vec(
#[rustc_box]
::alloc::boxed::Box::new([
crate::types::Extrinsic {
caller: bob.clone(),
call: RuntimeCall::ProofOfExistence(proof_of_existence::Call::revoke_claim {
claim: "Bob's claim",
}),
},
]),
),
};
runtime.execute_block(block_3).expect("Invalid block");
{
::std::io::_print(format_args!("{0:?}\n", runtime));
};
}