-
Notifications
You must be signed in to change notification settings - Fork 18
/
lib.rs
510 lines (435 loc) · 18.2 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
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! The Tuxedo Template Runtime is an example runtime that uses
//! most of the pieces provided in the wardrobe.
//!
//! Runtime developers wishing to get started with Tuxedo should
//! consider copying this template.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_consensus_grandpa::AuthorityId as GrandpaId;
use sp_api::impl_runtime_apis;
use sp_inherents::InherentData;
use sp_runtime::{
create_runtime_str, impl_opaque_keys,
traits::{BlakeTwo256, Block as BlockT},
transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
ApplyExtrinsicResult, BoundToRuntimeAppPublic,
};
use sp_std::prelude::*;
use sp_core::OpaqueMetadata;
#[cfg(any(feature = "std", test))]
use sp_runtime::{BuildStorage, Storage};
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
use serde::{Deserialize, Serialize};
use tuxedo_core::{
tuxedo_constraint_checker, tuxedo_verifier,
types::Transaction as TuxedoTransaction,
verifier::{SigCheck, ThresholdMultiSignature, UpForGrabs},
};
pub use amoeba;
pub use kitties;
pub use money;
pub use poe;
pub use runtime_upgrade;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
/// to even the core data structures.
pub mod opaque {
use super::*;
/// Opaque block type.
pub type Block = sp_runtime::generic::Block<Header, sp_runtime::OpaqueExtrinsic>;
// This part is necessary for generating session keys in the runtime
impl_opaque_keys! {
pub struct SessionKeys {
pub aura: AuraAppPublic,
pub grandpa: GrandpaAppPublic,
}
}
// Typically these are not implemented manually, but rather for the pallet associated with the
// keys. Here we are not using the pallets, and these implementations are trivial, so we just
// re-write them.
pub struct AuraAppPublic;
impl BoundToRuntimeAppPublic for AuraAppPublic {
type Public = AuraId;
}
pub struct GrandpaAppPublic;
impl BoundToRuntimeAppPublic for GrandpaAppPublic {
type Public = sp_consensus_grandpa::AuthorityId;
}
}
/// This runtime version.
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("tuxedo-template-runtime"),
impl_name: create_runtime_str!("tuxedo-template-runtime"),
authoring_version: 1,
spec_version: 1,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
state_version: 1,
};
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
}
#[derive(Serialize, Deserialize)]
/// The `TuxedoGenesisConfig` struct is used to configure the genesis state of the runtime.
/// The only parameter is a list of transactions to be included in the genesis block, and stored along with their outputs.
/// They must not contain any inputs or peeks. These transactions will not be validated by the corresponding ConstraintChecker or Verifier.
pub struct TuxedoGenesisConfig(pub Vec<Transaction>);
impl Default for TuxedoGenesisConfig {
fn default() -> Self {
use hex_literal::hex;
use kitties::{KittyData, Parent};
use money::Coin;
const SHAWN_PUB_KEY_BYTES: [u8; 32] =
hex!("d2bf4b844dfefd6772a8843e669f943408966a977e3ae2af1dd78e0f55f4df67");
const ANDREW_PUB_KEY_BYTES: [u8; 32] =
hex!("baa81e58b1b4d053c2e86d93045765036f9d265c7dfe8b9693bbc2c0f048d93a");
let signatories = vec![SHAWN_PUB_KEY_BYTES.into(), ANDREW_PUB_KEY_BYTES.into()];
let genesis_transactions = vec![
// Money Transactions
Coin::<0>::mint(100, SigCheck::new(SHAWN_PUB_KEY_BYTES)),
Coin::<0>::mint(100, ThresholdMultiSignature::new(1, signatories)),
// Kitty Transactions
KittyData::mint(Parent::mom(), b"mother", UpForGrabs),
KittyData::mint(Parent::dad(), b"father", UpForGrabs),
];
// TODO: Initial Transactions for Existence
TuxedoGenesisConfig(genesis_transactions)
}
}
#[cfg(feature = "std")]
impl BuildStorage for TuxedoGenesisConfig {
fn assimilate_storage(&self, storage: &mut Storage) -> Result<(), String> {
use tuxedo_core::inherents::InherentInternal;
// The wasm binary is stored under a special key.
storage.top.insert(
sp_storage::well_known_keys::CODE.into(),
WASM_BINARY.unwrap().to_vec(),
);
// The inherents transactions are computed using the appropriate method,
// and placed in the block before the normal transactions.
let mut genesis_transactions = OuterConstraintCheckerInherentHooks::genesis_transactions();
genesis_transactions.extend(self.0.clone());
tuxedo_core::genesis::assimilate_storage(storage, genesis_transactions)
}
}
pub type Transaction = TuxedoTransaction<OuterVerifier, OuterConstraintChecker>;
pub type BlockNumber = u32;
pub type Header = sp_runtime::generic::Header<BlockNumber, BlakeTwo256>;
pub type Block = sp_runtime::generic::Block<Header, Transaction>;
pub type Executive = tuxedo_core::Executive<Block, OuterVerifier, OuterConstraintChecker>;
pub type Output = tuxedo_core::types::Output<OuterVerifier>;
impl sp_runtime::traits::GetNodeBlockType for Runtime {
type NodeBlock = opaque::Block;
}
impl sp_runtime::traits::GetRuntimeBlockType for Runtime {
type RuntimeBlock = Block;
}
/// The Aura slot duration. When things are working well, this will also be the block time.
const BLOCK_TIME: u64 = 3000;
/// A verifier checks that an individual input can be consumed. For example that it is signed properly
/// To begin playing, we will have two kinds. A simple signature check, and an anyone-can-consume check.
#[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
#[tuxedo_verifier]
pub enum OuterVerifier {
SigCheck(SigCheck),
UpForGrabs(UpForGrabs),
ThresholdMultiSignature(ThresholdMultiSignature),
}
impl poe::PoeConfig for Runtime {
fn block_height() -> u32 {
Executive::block_height()
}
}
impl timestamp::TimestampConfig for Runtime {
fn block_height() -> u32 {
Executive::block_height()
}
}
// Observation: For some applications, it will be invalid to simply delete
// a UTXO without any further processing. Therefore, we explicitly include
// AmoebaDeath and PoeRevoke on an application-specific basis
/// A constraint checker is a piece of logic that can be used to check a transaction.
/// For any given Tuxedo runtime there is a finite set of such constraint checkers.
/// For example, this may check that input token values exceed output token values.
#[derive(Serialize, Deserialize, Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
#[tuxedo_constraint_checker(OuterVerifier)]
pub enum OuterConstraintChecker {
/// Checks monetary transactions in a basic fungible cryptocurrency
Money(money::MoneyConstraintChecker<0>),
/// Checks Free Kitty transactions
FreeKittyConstraintChecker(kitties::FreeKittyConstraintChecker),
/// Checks that an amoeba can split into two new amoebas
AmoebaMitosis(amoeba::AmoebaMitosis),
/// Checks that a single amoeba is simply removed from the state
AmoebaDeath(amoeba::AmoebaDeath),
/// Checks that a single amoeba is simply created from the void... and it is good
AmoebaCreation(amoeba::AmoebaCreation),
/// Checks that new valid proofs of existence are claimed
PoeClaim(poe::PoeClaim<Runtime>),
/// Checks that proofs of existence are revoked.
PoeRevoke(poe::PoeRevoke),
/// Checks that one winning claim came earlier than all the other claims, and thus
/// the losing claims can be removed from storage.
PoeDispute(poe::PoeDispute),
/// Set the block's timestamp via an inherent extrinsic.
SetTimestamp(timestamp::SetTimestamp<Runtime>),
/// Upgrade the Wasm Runtime
RuntimeUpgrade(runtime_upgrade::RuntimeUpgrade),
}
/// The main struct in this module.
#[derive(Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
pub struct Runtime;
// Here we hard-code consensus authority IDs for the well-known identities that work with the CLI flags
// Such as `--alice`, `--bob`, etc. Only Alice is enabled by default which makes things work nicely
// in a `--dev` node. You may enable more authorities to test more interesting networks, or replace
// these IDs entirely.
impl Runtime {
/// Aura authority IDs
fn aura_authorities() -> Vec<AuraId> {
use hex_literal::hex;
use sp_application_crypto::ByteArray;
[
// Alice
hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"),
// Bob
// hex!("8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"),
// Charlie
// hex!("90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22"),
// Dave
// hex!("306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20"),
// Eve
// hex!("e659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e"),
// Ferdie
// hex!("1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c"),
]
.iter()
.map(|hex| AuraId::from_slice(hex.as_ref()).expect("Valid Aura authority hex was provided"))
.collect()
}
///Grandpa Authority IDs - All equally weighted
fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
use hex_literal::hex;
use sp_application_crypto::ByteArray;
[
// Alice
hex!("88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee"),
// Bob
// hex!("d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69"),
// Charlie
// hex!("439660b36c6c03afafca027b910b4fecf99801834c62a5e6006f27d978de234f"),
// Dave
// hex!("5e639b43e0052c47447dac87d6fd2b6ec50bdd4d0f614e4299c665249bbd09d9"),
// Eve
// hex!("1dfe3e22cc0d45c70779c1095f7489a8ef3cf52d62fbd8c2fa38c9f1723502b5"),
// Ferdie
// hex!("568cb4a574c6d178feb39c27dfc8b3f789e5f5423e19c71633c748b9acf086b5"),
]
.iter()
.map(|hex| {
(
GrandpaId::from_slice(hex.as_ref())
.expect("Valid Grandpa authority hex was provided"),
1,
)
})
.collect()
}
}
impl_runtime_apis! {
// https://substrate.dev/rustdocs/master/sp_api/trait.Core.html
impl sp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) {
Executive::open_block(header)
}
}
// https://substrate.dev/rustdocs/master/sc_block_builder/trait.BlockBuilderApi.html
impl sp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::close_block()
}
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
Executive::inherent_extrinsics(data)
}
fn check_inherents(
block: Block,
data: InherentData
) -> sp_inherents::CheckInherentsResult {
Executive::check_inherents(block, data)
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
// Tuxedo does not yet support metadata
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Default::default())
}
fn metadata_at_version(_version: u32) -> Option<OpaqueMetadata> {
None
}
fn metadata_versions() -> sp_std::vec::Vec<u32> {
Default::default()
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
opaque::SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(BLOCK_TIME)
}
fn authorities() -> Vec<AuraId> {
Self::aura_authorities()
}
}
impl sp_consensus_grandpa::GrandpaApi<Block> for Runtime {
fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
Self::grandpa_authorities()
}
fn current_set_id() -> sp_consensus_grandpa::SetId {
0u64
}
fn submit_report_equivocation_unsigned_extrinsic(
_equivocation_proof: sp_consensus_grandpa::EquivocationProof<
<Block as BlockT>::Hash,
sp_runtime::traits::NumberFor<Block>,
>,
_key_owner_proof: sp_consensus_grandpa::OpaqueKeyOwnershipProof,
) -> Option<()> {
None
}
fn generate_key_ownership_proof(
_set_id: sp_consensus_grandpa::SetId,
_authority_id: sp_consensus_grandpa::AuthorityId,
) -> Option<sp_consensus_grandpa::OpaqueKeyOwnershipProof> {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use parity_scale_codec::Encode;
use sp_api::HashT;
use sp_core::testing::SR25519;
use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt};
use std::sync::Arc;
use tuxedo_core::{
dynamic_typing::{DynamicallyTypedData, UtxoData},
types::OutputRef,
};
// other random account generated with subkey
const SHAWN_PHRASE: &str =
"news slush supreme milk chapter athlete soap sausage put clutch what kitten";
const ANDREW_PHRASE: &str =
"monkey happy total rib lumber scrap guide photo country online rose diet";
fn new_test_ext() -> sp_io::TestExternalities {
let keystore = MemoryKeystore::new();
let t = TuxedoGenesisConfig::default()
.build_storage()
.expect("System builds valid default genesis config");
let mut ext = sp_io::TestExternalities::from(t);
ext.register_extension(KeystoreExt(Arc::new(keystore)));
ext
}
#[test]
fn utxo_money_test_genesis() {
new_test_ext().execute_with(|| {
let keystore = MemoryKeystore::new();
let shawn_pub_key = keystore
.sr25519_generate_new(SR25519, Some(SHAWN_PHRASE))
.unwrap();
// Grab genesis value from storage and assert it is correct
let genesis_utxo = Output {
verifier: OuterVerifier::SigCheck(SigCheck {
owner_pubkey: shawn_pub_key.into(),
}),
payload: DynamicallyTypedData {
data: 100u128.encode(),
type_id: <money::Coin<0> as UtxoData>::TYPE_ID,
},
};
let tx = TuxedoGenesisConfig::default().0.get(0).unwrap().clone();
assert_eq!(tx.outputs.get(0), Some(&genesis_utxo));
let tx_hash = BlakeTwo256::hash_of(&tx.encode());
let output_ref = OutputRef {
tx_hash,
index: 0_u32,
};
let encoded_utxo =
sp_io::storage::get(&output_ref.encode()).expect("Retrieve Genesis UTXO");
let utxo = Output::decode(&mut &encoded_utxo[..]).expect("Can Decode UTXO correctly");
assert_eq!(utxo, genesis_utxo);
})
}
#[test]
fn utxo_money_multi_sig_genesis_test() {
new_test_ext().execute_with(|| {
let keystore = MemoryKeystore::new();
let shawn_pub_key = keystore
.sr25519_generate_new(SR25519, Some(SHAWN_PHRASE))
.unwrap();
let andrew_pub_key = keystore
.sr25519_generate_new(SR25519, Some(ANDREW_PHRASE))
.unwrap();
let genesis_multi_sig_utxo = Output {
verifier: OuterVerifier::ThresholdMultiSignature(ThresholdMultiSignature {
threshold: 1,
signatories: vec![shawn_pub_key.into(), andrew_pub_key.into()],
}),
payload: DynamicallyTypedData {
data: 100u128.encode(),
type_id: <money::Coin<0> as UtxoData>::TYPE_ID,
},
};
let tx = TuxedoGenesisConfig::default().0.get(1).unwrap().clone();
assert_eq!(tx.outputs.get(0), Some(&genesis_multi_sig_utxo));
let tx_hash = BlakeTwo256::hash_of(&tx.encode());
let output_ref = OutputRef {
tx_hash,
index: 0_u32,
};
let encoded_utxo =
sp_io::storage::get(&output_ref.encode()).expect("Retrieve Genesis MultiSig UTXO");
let utxo = Output::decode(&mut &encoded_utxo[..]).expect("Can Decode UTXO correctly");
assert_eq!(utxo, genesis_multi_sig_utxo);
})
}
}