1use serde::{Serialize, Serializer, Deserialize, de::Error as DeError, Deserializer};
21use std::{fmt::{self, Debug}, ops::Deref, cell::RefCell};
22use crate::codec::{Codec, Encode, Decode};
23use crate::traits::{
24 self, Checkable, Applyable, BlakeTwo256, OpaqueKeys,
25 SignedExtension, Dispatchable, DispatchInfoOf, PostDispatchInfoOf,
26};
27use crate::traits::ValidateUnsigned;
28use crate::{generic, KeyTypeId, CryptoTypeId, ApplyExtrinsicResultWithInfo};
29pub use tet_core::{H256, sr25519};
30use tet_core::{crypto::{CryptoType, Dummy, key_types, Public}, U256};
31use crate::transaction_validity::{TransactionValidity, TransactionValidityError, TransactionSource};
32
33#[derive(Default, PartialEq, Eq, Clone, Encode, Decode, Debug, Hash, Serialize, Deserialize, PartialOrd, Ord)]
40pub struct UintAuthorityId(pub u64);
41
42impl From<u64> for UintAuthorityId {
43 fn from(id: u64) -> Self {
44 UintAuthorityId(id)
45 }
46}
47
48impl From<UintAuthorityId> for u64 {
49 fn from(id: UintAuthorityId) -> u64 {
50 id.0
51 }
52}
53
54impl UintAuthorityId {
55 pub fn to_public_key<T: Public>(&self) -> T {
57 let bytes: [u8; 32] = U256::from(self.0).into();
58 T::from_slice(&bytes)
59 }
60}
61
62impl CryptoType for UintAuthorityId {
63 type Pair = Dummy;
64}
65
66impl AsRef<[u8]> for UintAuthorityId {
67 fn as_ref(&self) -> &[u8] {
68 unsafe {
71 std::slice::from_raw_parts(&self.0 as *const u64 as *const _, std::mem::size_of::<u64>())
72 }
73 }
74}
75
76thread_local! {
77 static ALL_KEYS: RefCell<Vec<UintAuthorityId>> = RefCell::new(vec![]);
79}
80
81impl UintAuthorityId {
82 pub fn set_all_keys<T: Into<UintAuthorityId>>(keys: impl IntoIterator<Item=T>) {
84 ALL_KEYS.with(|l| *l.borrow_mut() = keys.into_iter().map(Into::into).collect())
85 }
86}
87
88impl tet_application_crypto::RuntimeAppPublic for UintAuthorityId {
89 const ID: KeyTypeId = key_types::DUMMY;
90 const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"dumm");
91
92 type Signature = TestSignature;
93
94 fn all() -> Vec<Self> {
95 ALL_KEYS.with(|l| l.borrow().clone())
96 }
97
98 fn generate_pair(_: Option<Vec<u8>>) -> Self {
99 use rand::RngCore;
100 UintAuthorityId(rand::thread_rng().next_u64())
101 }
102
103 fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature> {
104 Some(TestSignature(self.0, msg.as_ref().to_vec()))
105 }
106
107 fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
108 traits::Verify::verify(signature, msg.as_ref(), &self.0)
109 }
110
111 fn to_raw_vec(&self) -> Vec<u8> {
112 AsRef::<[u8]>::as_ref(self).to_vec()
113 }
114}
115
116impl OpaqueKeys for UintAuthorityId {
117 type KeyTypeIdProviders = ();
118
119 fn key_ids() -> &'static [KeyTypeId] {
120 &[key_types::DUMMY]
121 }
122
123 fn get_raw(&self, _: KeyTypeId) -> &[u8] {
124 self.as_ref()
125 }
126
127 fn get<T: Decode>(&self, _: KeyTypeId) -> Option<T> {
128 self.using_encoded(|mut x| T::decode(&mut x)).ok()
129 }
130}
131
132impl crate::BoundToRuntimeAppPublic for UintAuthorityId {
133 type Public = Self;
134}
135
136impl traits::IdentifyAccount for UintAuthorityId {
137 type AccountId = u64;
138
139 fn into_account(self) -> Self::AccountId {
140 self.0
141 }
142}
143
144#[derive(Eq, PartialEq, Clone, Debug, Hash, Serialize, Deserialize, Encode, Decode)]
146pub struct TestSignature(pub u64, pub Vec<u8>);
147
148impl traits::Verify for TestSignature {
149 type Signer = UintAuthorityId;
150
151 fn verify<L: traits::Lazy<[u8]>>(&self, mut msg: L, signer: &u64) -> bool {
152 signer == &self.0 && msg.get() == &self.1[..]
153 }
154}
155
156pub type DigestItem = generic::DigestItem<H256>;
158
159pub type Digest = generic::Digest<H256>;
161
162pub type Header = generic::Header<u64, BlakeTwo256>;
164
165impl Header {
166 pub fn new_from_number(number: <Self as traits::Header>::Number) -> Self {
168 Self {
169 number,
170 extrinsics_root: Default::default(),
171 state_root: Default::default(),
172 parent_hash: Default::default(),
173 digest: Default::default(),
174 }
175 }
176}
177
178#[derive(PartialEq, Eq, Clone, Debug, Encode, Decode, tetsy_util_mem::MallocSizeOf)]
180pub struct ExtrinsicWrapper<Xt>(Xt);
181
182impl<Xt> traits::Extrinsic for ExtrinsicWrapper<Xt>
183where Xt: tetsy_util_mem::MallocSizeOf
184{
185 type Call = ();
186 type SignaturePayload = ();
187
188 fn is_signed(&self) -> Option<bool> {
189 None
190 }
191}
192
193impl<Xt: Encode> serde::Serialize for ExtrinsicWrapper<Xt> {
194 fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer {
195 self.using_encoded(|bytes| seq.serialize_bytes(bytes))
196 }
197}
198
199impl<Xt> From<Xt> for ExtrinsicWrapper<Xt> {
200 fn from(xt: Xt) -> Self {
201 ExtrinsicWrapper(xt)
202 }
203}
204
205impl<Xt> Deref for ExtrinsicWrapper<Xt> {
206 type Target = Xt;
207
208 fn deref(&self) -> &Self::Target {
209 &self.0
210 }
211}
212
213#[derive(PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode, tetsy_util_mem::MallocSizeOf)]
215pub struct Block<Xt> {
216 pub header: Header,
218 pub extrinsics: Vec<Xt>,
220}
221
222impl<Xt: 'static + Codec + Sized + Send + Sync + Serialize + Clone + Eq + Debug + traits::Extrinsic> traits::Block
223 for Block<Xt>
224{
225 type Extrinsic = Xt;
226 type Header = Header;
227 type Hash = <Header as traits::Header>::Hash;
228
229 fn header(&self) -> &Self::Header {
230 &self.header
231 }
232 fn extrinsics(&self) -> &[Self::Extrinsic] {
233 &self.extrinsics[..]
234 }
235 fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>) {
236 (self.header, self.extrinsics)
237 }
238 fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self {
239 Block { header, extrinsics }
240 }
241 fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8> {
242 (header, extrinsics).encode()
243 }
244}
245
246impl<'a, Xt> Deserialize<'a> for Block<Xt> where Block<Xt>: Decode {
247 fn deserialize<D: Deserializer<'a>>(de: D) -> Result<Self, D::Error> {
248 let r = <Vec<u8>>::deserialize(de)?;
249 Decode::decode(&mut &r[..])
250 .map_err(|e| DeError::custom(format!("Invalid value passed into decode: {}", e)))
251 }
252}
253
254#[derive(PartialEq, Eq, Clone, Encode, Decode)]
259pub struct TestXt<Call, Extra> {
260 pub signature: Option<(u64, Extra)>,
262 pub call: Call,
264}
265
266impl<Call, Extra> TestXt<Call, Extra> {
267 pub fn new(call: Call, signature: Option<(u64, Extra)>) -> Self {
269 Self { call, signature }
270 }
271}
272
273tetsy_util_mem::malloc_size_of_is_0!(any: TestXt<Call, Extra>);
275
276impl<Call, Extra> Serialize for TestXt<Call, Extra> where TestXt<Call, Extra>: Encode {
277 fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> where S: Serializer {
278 self.using_encoded(|bytes| seq.serialize_bytes(bytes))
279 }
280}
281
282impl<Call, Extra> Debug for TestXt<Call, Extra> {
283 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
284 write!(f, "TestXt({:?}, ...)", self.signature.as_ref().map(|x| &x.0))
285 }
286}
287
288impl<Call: Codec + Sync + Send, Context, Extra> Checkable<Context> for TestXt<Call, Extra> {
289 type Checked = Self;
290 fn check(self, _: &Context) -> Result<Self::Checked, TransactionValidityError> { Ok(self) }
291}
292
293impl<Call: Codec + Sync + Send, Extra> traits::Extrinsic for TestXt<Call, Extra> {
294 type Call = Call;
295 type SignaturePayload = (u64, Extra);
296
297 fn is_signed(&self) -> Option<bool> {
298 Some(self.signature.is_some())
299 }
300
301 fn new(c: Call, sig: Option<Self::SignaturePayload>) -> Option<Self> {
302 Some(TestXt { signature: sig, call: c })
303 }
304}
305
306impl<Origin, Call, Extra> Applyable for TestXt<Call, Extra> where
307 Call: 'static + Sized + Send + Sync + Clone + Eq + Codec + Debug + Dispatchable<Origin=Origin>,
308 Extra: SignedExtension<AccountId=u64, Call=Call>,
309 Origin: From<Option<u64>>,
310{
311 type Call = Call;
312
313 fn validate<U: ValidateUnsigned<Call=Self::Call>>(
315 &self,
316 source: TransactionSource,
317 info: &DispatchInfoOf<Self::Call>,
318 len: usize,
319 ) -> TransactionValidity {
320 if let Some((ref id, ref extra)) = self.signature {
321 Extra::validate(extra, id, &self.call, info, len)
322 } else {
323 let valid = Extra::validate_unsigned(&self.call, info, len)?;
324 let unsigned_validation = U::validate_unsigned(source, &self.call)?;
325 Ok(valid.combine_with(unsigned_validation))
326 }
327 }
328
329 fn apply<U: ValidateUnsigned<Call=Self::Call>>(
332 self,
333 info: &DispatchInfoOf<Self::Call>,
334 len: usize,
335 ) -> ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>> {
336 let maybe_who = if let Some((who, extra)) = self.signature {
337 Extra::pre_dispatch(extra, &who, &self.call, info, len)?;
338 Some(who)
339 } else {
340 Extra::pre_dispatch_unsigned(&self.call, info, len)?;
341 U::pre_dispatch(&self.call)?;
342 None
343 };
344
345 Ok(self.call.dispatch(maybe_who.into()))
346 }
347}