-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathgenesis.rs
178 lines (159 loc) · 6.46 KB
/
genesis.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
//! Custom GenesisBlockBuilder for Tuxedo, to allow extrinsics to be added to the genesis block.
use crate::{
ensure,
types::{Output, OutputRef, Transaction},
ConstraintChecker, Verifier, EXTRINSIC_KEY,
};
use parity_scale_codec::{Decode, Encode};
use sc_chain_spec::BuildGenesisBlock;
use sc_client_api::backend::{Backend, BlockImportOperation};
use sc_executor::RuntimeVersionOf;
use serde::{Deserialize, Serialize};
use sp_core::{storage::Storage, traits::CodeExecutor};
use sp_runtime::{
traits::{BlakeTwo256, Block as BlockT, Hash as HashT, Header as HeaderT, Zero},
BuildStorage,
};
use std::sync::Arc;
pub struct TuxedoGenesisBlockBuilder<
'a,
Block: BlockT,
B: Backend<Block>,
E: RuntimeVersionOf + CodeExecutor,
> {
build_genesis_storage: &'a dyn BuildStorage,
commit_genesis_state: bool,
backend: Arc<B>,
executor: E,
_phantom: std::marker::PhantomData<Block>,
}
impl<'a, Block: BlockT, B: Backend<Block>, E: RuntimeVersionOf + CodeExecutor>
TuxedoGenesisBlockBuilder<'a, Block, B, E>
{
pub fn new(
build_genesis_storage: &'a dyn BuildStorage,
commit_genesis_state: bool,
backend: Arc<B>,
executor: E,
) -> sp_blockchain::Result<Self> {
Ok(Self {
build_genesis_storage,
commit_genesis_state,
backend,
executor,
_phantom: Default::default(),
})
}
}
impl<'a, Block: BlockT, B: Backend<Block>, E: RuntimeVersionOf + CodeExecutor>
BuildGenesisBlock<Block> for TuxedoGenesisBlockBuilder<'a, Block, B, E>
{
type BlockImportOperation = <B as Backend<Block>>::BlockImportOperation;
/// Build the genesis block, including the extrinsics found in storage at EXTRINSIC_KEY.
/// The extrinsics are not checked for validity, nor executed, so the values in storage must be placed manually.
/// This can be done by using the `assimilate_storage` function.
fn build_genesis_block(self) -> sp_blockchain::Result<(Block, Self::BlockImportOperation)> {
// We build it here to gain mutable access to the storage.
let mut genesis_storage = self
.build_genesis_storage
.build_storage()
.map_err(sp_blockchain::Error::Storage)?;
let state_version =
sc_chain_spec::resolve_state_version_from_wasm(&genesis_storage, &self.executor)?;
let extrinsics = match genesis_storage.top.remove(crate::EXTRINSIC_KEY) {
Some(v) => <Vec<<Block as BlockT>::Extrinsic>>::decode(&mut &v[..]).unwrap_or_default(),
None => Vec::new(),
};
let extrinsics_root =
<<<Block as BlockT>::Header as HeaderT>::Hashing as HashT>::ordered_trie_root(
extrinsics.iter().map(Encode::encode).collect(),
state_version,
);
let mut op = self.backend.begin_operation()?;
let state_root =
op.set_genesis_state(genesis_storage, self.commit_genesis_state, state_version)?;
let block = Block::new(
HeaderT::new(
Zero::zero(),
extrinsics_root,
state_root,
Default::default(),
Default::default(),
),
extrinsics,
);
Ok((block, op))
}
}
#[derive(Serialize, Deserialize)]
/// The `TuxedoGenesisConfig` struct is used to configure the genesis state of the runtime.
/// It expects the wasm binary and 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.
/// Make sure to pass the inherents before the extrinsics.
pub struct TuxedoGenesisConfig<V, C> {
wasm_binary: Vec<u8>,
genesis_transactions: Vec<Transaction<V, C>>,
}
impl<V, C> TuxedoGenesisConfig<V, C> {
/// Create a new `TuxedoGenesisConfig` from a WASM binary and a list of transactions.
/// Make sure to pass the transactions in order: the inherents should be first, then the extrinsics.
pub fn new(wasm_binary: Vec<u8>, genesis_transactions: Vec<Transaction<V, C>>) -> Self {
Self {
wasm_binary,
genesis_transactions,
}
}
pub fn get_transaction(&self, i: usize) -> Option<&Transaction<V, C>> {
self.genesis_transactions.get(i)
}
}
impl<V, C> BuildStorage for TuxedoGenesisConfig<V, C>
where
V: Verifier,
C: ConstraintChecker<V>,
Transaction<V, C>: Encode,
Output<V>: Encode,
{
/// Assimilate the storage into the genesis block.
/// This is done by inserting the genesis extrinsics into the genesis block, along with their outputs.
fn assimilate_storage(&self, storage: &mut Storage) -> Result<(), String> {
// The wasm binary is stored under a special key.
storage.top.insert(
sp_storage::well_known_keys::CODE.into(),
self.wasm_binary.clone(),
);
// The transactions are stored under a special key.
storage
.top
.insert(EXTRINSIC_KEY.to_vec(), self.genesis_transactions.encode());
let mut finished_with_opening_inherents = false;
for tx in self.genesis_transactions.iter() {
// Enforce that inherents are in the right place
let current_tx_is_inherent = tx.checker.is_inherent();
if current_tx_is_inherent && finished_with_opening_inherents {
return Err(
"Tried to execute opening inherent after switching to non-inherents.".into(),
);
}
if !current_tx_is_inherent && !finished_with_opening_inherents {
// This is the first non-inherent, so we update our flag and continue.
finished_with_opening_inherents = true;
}
// Enforce that transactions do not have any inputs or peeks.
ensure!(
tx.inputs.is_empty() && tx.peeks.is_empty(),
"Genesis transactions must not have any inputs or peeks."
);
// Insert the outputs into the storage.
let tx_hash = BlakeTwo256::hash_of(&tx.encode());
for (index, utxo) in tx.outputs.iter().enumerate() {
let output_ref = OutputRef {
tx_hash,
index: index as u32,
};
storage.top.insert(output_ref.encode(), utxo.encode());
}
}
Ok(())
}
}