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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
// This file is part of Substrate.

// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Module helpers for off-chain calls.
//!
//! ## Overview
//!
//! This module provides transaction related helpers to:
//! - Submit a raw unsigned transaction
//! - Submit an unsigned transaction with a signed payload
//! - Submit a signed transction.
//!
//! ## Usage
//!
//! Please refer to [`example-offchain-worker`](../../pallet_example_offchain_worker/index.html) for
//! a concrete example usage of this crate.
//!
//! ### Submit a raw unsigned transaction
//!
//! To submit a raw unsigned transaction, [`SubmitTransaction`](./struct.SubmitTransaction.html)
//! can be used.
//!
//! ### Signing transactions
//!
//! To be able to use signing, the following trait should be implemented:
//!
//! - [`AppCrypto`](./trait.AppCrypto.html): where an application-specific key
//!   is defined and can be used by this module's helpers for signing.
//! - [`CreateSignedTransaction`](./trait.CreateSignedTransaction.html): where
//!   the manner in which the transaction is constructed is defined.
//!
//! #### Submit an unsigned transaction with a signed payload
//!
//! Initially, a payload instance that implements the `SignedPayload` trait should be defined.
//! See [`PricePayload`](../../pallet_example_offchain_worker/struct.PricePayload.html)
//!
//! The payload type that is defined defined can then be signed and submitted onchain.
//!
//! #### Submit a signed transaction
//!
//! [`Signer`](./struct.Signer.html) can be used to sign/verify payloads
//!

#![warn(missing_docs)]

use codec::Encode;
use sp_std::collections::btree_set::BTreeSet;
use sp_std::convert::{TryInto, TryFrom};
use sp_std::prelude::{Box, Vec};
use sp_runtime::app_crypto::RuntimeAppPublic;
use sp_runtime::traits::{Extrinsic as ExtrinsicT, IdentifyAccount, One};
use frame_support::{debug, storage::StorageMap, RuntimeDebug};

/// Marker struct used to flag using all supported keys to sign a payload.
pub struct ForAll {}
/// Marker struct used to flag using any of the supported keys to sign a payload.
pub struct ForAny {}

/// Provides the ability to directly submit signed and unsigned
/// transaction onchain.
///
/// For submitting unsigned transactions, `submit_unsigned_transaction`
/// utility function can be used. However, this struct is used by `Signer`
/// to submit a signed transactions providing the signature along with the call.
pub struct SubmitTransaction<T: SendTransactionTypes<OverarchingCall>, OverarchingCall> {
	_phantom: sp_std::marker::PhantomData<(T, OverarchingCall)>
}

impl<T, LocalCall> SubmitTransaction<T, LocalCall>
where
	T: SendTransactionTypes<LocalCall>,
{
	/// Submit transaction onchain by providing the call and an optional signature
	pub fn submit_transaction(
		call: <T as SendTransactionTypes<LocalCall>>::OverarchingCall,
		signature: Option<<T::Extrinsic as ExtrinsicT>::SignaturePayload>,
	) -> Result<(), ()> {
		let xt = T::Extrinsic::new(call.into(), signature).ok_or(())?;
		sp_io::offchain::submit_transaction(xt.encode())
	}

	/// A convenience method to submit an unsigned transaction onchain.
	pub fn submit_unsigned_transaction(
		call: <T as SendTransactionTypes<LocalCall>>::OverarchingCall,
	) -> Result<(), ()> {
		SubmitTransaction::<T, LocalCall>::submit_transaction(call, None)
	}
}

/// Provides an implementation for signing transaction payloads.
///
/// Keys used for signing are defined when instantiating the signer object.
/// Signing can be done using:
///
/// - All supported keys in the keystore
/// - Any of the supported keys in the keystore
/// - An intersection of in-keystore keys and the list of provided keys
///
/// The signer is then able to:
/// - Submit a unsigned transaction with a signed payload
/// - Submit a signed transaction
#[derive(RuntimeDebug)]
pub struct Signer<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>, X = ForAny> {
	accounts: Option<Vec<T::Public>>,
	_phantom: sp_std::marker::PhantomData<(X, C)>,
}

impl<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>, X> Default for Signer<T, C, X> {
	fn default() -> Self {
		Self {
			accounts: Default::default(),
			_phantom: Default::default(),
		}
	}
}

impl<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>, X> Signer<T, C, X> {
	/// Use all available keys for signing.
	pub fn all_accounts() -> Signer<T, C, ForAll> {
		Default::default()
	}

	/// Use any of the available keys for signing.
	pub fn any_account() -> Signer<T, C, ForAny> {
		Default::default()
	}

	/// Use provided `accounts` for signing.
	///
	/// Note that not all keys will be necessarily used. The provided
	/// vector of accounts will be intersected with the supported keys
	/// in the keystore and the resulting list will be used for signing.
	pub fn with_filter(mut self, accounts: Vec<T::Public>) -> Self {
		self.accounts = Some(accounts);
		self
	}

	/// Check if there are any keys that could be used for signing.
	pub fn can_sign(&self) -> bool {
		self.accounts_from_keys().count() > 0
	}

	/// Return a vector of the intersection between
	/// all available accounts and the provided accounts
	/// in `with_filter`. If no accounts are provided,
	/// use all accounts by default.
	fn accounts_from_keys<'a>(&'a self) -> Box<dyn Iterator<Item = Account<T>> + 'a> {
		let keystore_accounts = self.keystore_accounts();
		match self.accounts {
			None => Box::new(keystore_accounts),
			Some(ref keys) =>  {
				let keystore_lookup: BTreeSet<<T as SigningTypes>::Public> = keystore_accounts
					.map(|account| account.public).collect();

				Box::new(keys.into_iter()
					.enumerate()
					.map(|(index, key)| {
						let account_id = key.clone().into_account();
						Account::new(index, account_id, key.clone())
					})
					.filter(move |account| keystore_lookup.contains(&account.public)))
			}
		}
	}

	fn keystore_accounts(&self) -> impl Iterator<Item = Account<T>> {
		C::RuntimeAppPublic::all()
			.into_iter()
			.enumerate()
			.map(|(index, key)| {
				let generic_public = C::GenericPublic::from(key);
				let public = generic_public.into();
				let account_id = public.clone().into_account();
				Account::new(index, account_id, public.clone())
			})
	}
}


impl<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>> Signer<T, C, ForAll> {
	fn for_all<F, R>(&self, f: F) -> Vec<(Account<T>, R)> where
		F: Fn(&Account<T>) -> Option<R>,
	{
		let accounts = self.accounts_from_keys();
		accounts
			.into_iter()
			.filter_map(|account| {
				f(&account).map(|res| (account, res))
			})
			.collect()
	}
}

impl<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>> Signer<T, C, ForAny> {
	fn for_any<F, R>(&self, f: F) -> Option<(Account<T>, R)> where
		F: Fn(&Account<T>) -> Option<R>,
	{
		let accounts = self.accounts_from_keys();
		for account in accounts.into_iter() {
			let res = f(&account);
			if let Some(res) = res {
				return Some((account, res));
			}
		}
		None
	}
}

impl<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>> SignMessage<T> for Signer<T, C, ForAll> {
	type SignatureData = Vec<(Account<T>, T::Signature)>;

	fn sign_message(&self, message: &[u8]) -> Self::SignatureData {
		self.for_all(|account| C::sign(message, account.public.clone()))
	}

	fn sign<TPayload, F>(&self, f: F) -> Self::SignatureData where
		F: Fn(&Account<T>) -> TPayload,
		TPayload: SignedPayload<T>,
	{
		self.for_all(|account| f(account).sign::<C>())
	}
}

impl<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>> SignMessage<T> for Signer<T, C, ForAny> {
	type SignatureData = Option<(Account<T>, T::Signature)>;

	fn sign_message(&self, message: &[u8]) -> Self::SignatureData {
		self.for_any(|account| C::sign(message, account.public.clone()))
	}

	fn sign<TPayload, F>(&self, f: F) -> Self::SignatureData where
		F: Fn(&Account<T>) -> TPayload,
		TPayload: SignedPayload<T>,
	{
		self.for_any(|account| f(account).sign::<C>())
	}
}

impl<
	T: CreateSignedTransaction<LocalCall> + SigningTypes,
	C: AppCrypto<T::Public, T::Signature>,
	LocalCall,
> SendSignedTransaction<T, C, LocalCall> for Signer<T, C, ForAny> {
	type Result = Option<(Account<T>, Result<(), ()>)>;

	fn send_signed_transaction(
		&self,
		f: impl Fn(&Account<T>) -> LocalCall,
	) -> Self::Result {
		self.for_any(|account| {
			let call = f(account);
			self.send_single_signed_transaction(account, call)
		})
	}
}

impl<
	T: SigningTypes + CreateSignedTransaction<LocalCall>,
	C: AppCrypto<T::Public, T::Signature>,
	LocalCall,
> SendSignedTransaction<T, C, LocalCall> for Signer<T, C, ForAll> {
	type Result = Vec<(Account<T>, Result<(), ()>)>;

	fn send_signed_transaction(
		&self,
		f: impl Fn(&Account<T>) -> LocalCall,
	) -> Self::Result {
		self.for_all(|account| {
			let call = f(account);
			self.send_single_signed_transaction(account, call)
		})
	}
}

impl<
	T: SigningTypes + SendTransactionTypes<LocalCall>,
	C: AppCrypto<T::Public, T::Signature>,
	LocalCall,
> SendUnsignedTransaction<T, LocalCall> for Signer<T, C, ForAny> {
	type Result = Option<(Account<T>, Result<(), ()>)>;

	fn send_unsigned_transaction<TPayload, F>(
		&self,
		f: F,
		f2: impl Fn(TPayload, T::Signature) -> LocalCall,
	) -> Self::Result
	where
		F: Fn(&Account<T>) -> TPayload,
		TPayload: SignedPayload<T>,
	{
		self.for_any(|account| {
			let payload = f(account);
			let signature= payload.sign::<C>()?;
			let call = f2(payload, signature);
			self.submit_unsigned_transaction(call)
		})
	}
}

impl<
	T: SigningTypes + SendTransactionTypes<LocalCall>,
	C: AppCrypto<T::Public, T::Signature>,
	LocalCall,
> SendUnsignedTransaction<T, LocalCall> for Signer<T, C, ForAll> {
	type Result = Vec<(Account<T>, Result<(), ()>)>;

	fn send_unsigned_transaction<TPayload, F>(
		&self,
		f: F,
		f2: impl Fn(TPayload, T::Signature) -> LocalCall,
	) -> Self::Result
	where
		F: Fn(&Account<T>) -> TPayload,
		TPayload: SignedPayload<T> {
		self.for_all(|account| {
			let payload = f(account);
			let signature = payload.sign::<C>()?;
			let call = f2(payload, signature);
			self.submit_unsigned_transaction(call)
		})
	}
}

/// Details of an account for which a private key is contained in the keystore.
#[derive(RuntimeDebug, PartialEq)]
pub struct Account<T: SigningTypes> {
	/// Index on the provided list of accounts or list of all accounts.
	pub index: usize,
	/// Runtime-specific `AccountId`.
	pub id: T::AccountId,
	/// A runtime-specific `Public` key for that key pair.
	pub public: T::Public,
}

impl<T: SigningTypes> Account<T> {
	/// Create a new Account instance
	pub fn new(index: usize, id: T::AccountId, public: T::Public) -> Self {
		Self { index, id, public }
	}
}

impl<T: SigningTypes> Clone for Account<T> where
	T::AccountId: Clone,
	T::Public: Clone,
{
	fn clone(&self) -> Self {
		Self {
			index: self.index,
			id: self.id.clone(),
			public: self.public.clone(),
		}
	}
}

/// A type binding runtime-level `Public/Signature` pair with crypto wrapped by `RuntimeAppPublic`.
///
/// Implementations of this trait should specify the app-specific public/signature types.
/// This is merely a wrapper around an existing `RuntimeAppPublic` type, but with
/// extra non-application-specific crypto type that is being wrapped (e.g. `sr25519`, `ed25519`).
/// This is needed to later on convert into runtime-specific `Public` key, which might support
/// multiple different crypto.
/// The point of this trait is to be able to easily convert between `RuntimeAppPublic`, the wrapped
/// (generic = non application-specific) crypto types and the `Public` type required by the runtime.
///
/// TODO [#5662] Potentially use `IsWrappedBy` types, or find some other way to make it easy to
/// obtain unwrapped crypto (and wrap it back).
///
///	Example (pseudo-)implementation:
/// ```ignore
///	// im-online specific crypto
/// type RuntimeAppPublic = ImOnline(sr25519::Public);
///
/// // wrapped "raw" crypto
/// type GenericPublic = sr25519::Public;
/// type GenericSignature = sr25519::Signature;
///
/// // runtime-specific public key
/// type Public = MultiSigner: From<sr25519::Public>;
/// type Signature = MulitSignature: From<sr25519::Signature>;
/// ```
pub trait AppCrypto<Public, Signature> {
	/// A application-specific crypto.
	type RuntimeAppPublic: RuntimeAppPublic;

	/// A raw crypto public key wrapped by `RuntimeAppPublic`.
	type GenericPublic:
		From<Self::RuntimeAppPublic>
		+ Into<Self::RuntimeAppPublic>
		+ TryFrom<Public>
		+ Into<Public>;

	/// A matching raw crypto `Signature` type.
	type GenericSignature:
		From<<Self::RuntimeAppPublic as RuntimeAppPublic>::Signature>
		+ Into<<Self::RuntimeAppPublic as RuntimeAppPublic>::Signature>
		+ TryFrom<Signature>
		+ Into<Signature>;

	/// Sign payload with the private key to maps to the provided public key.
	fn sign(payload: &[u8], public: Public) -> Option<Signature> {
		let p: Self::GenericPublic = public.try_into().ok()?;
		let x = Into::<Self::RuntimeAppPublic>::into(p);
		x.sign(&payload)
			.map(|x| {
				let sig: Self::GenericSignature = x.into();
				sig
			})
			.map(Into::into)
	}

	/// Verify signature against the provided public key.
	fn verify(payload: &[u8], public: Public, signature: Signature) -> bool {
		let p: Self::GenericPublic = match public.try_into() {
			Ok(a) => a,
			_ => return false
		};
		let x = Into::<Self::RuntimeAppPublic>::into(p);
		let signature: Self::GenericSignature = match signature.try_into() {
			Ok(a) => a,
			_ => return false
		};
		let signature = Into::<<
			Self::RuntimeAppPublic as RuntimeAppPublic
		>::Signature>::into(signature);

		x.verify(&payload, &signature)
	}
}

/// A wrapper around the types which are used for signing.
///
/// This trait adds extra bounds to `Public` and `Signature` types of the runtime
/// that are necessary to use these types for signing.
///
///	TODO [#5663] Could this be just `T::Signature as traits::Verify>::Signer`?
/// Seems that this may cause issues with bounds resolution.
pub trait SigningTypes: crate::Trait {
	/// A public key that is capable of identifing `AccountId`s.
	///
	/// Usually that's either a raw crypto public key (e.g. `sr25519::Public`) or
	/// an aggregate type for multiple crypto public keys, like `MulitSigner`.
	type Public: Clone
		+ PartialEq
		+ IdentifyAccount<AccountId = Self::AccountId>
		+ core::fmt::Debug
		+ codec::Codec
		+ Ord;

	/// A matching `Signature` type.
	type Signature: Clone
		+ PartialEq
		+ core::fmt::Debug
		+ codec::Codec;
}

/// A definition of types required to submit transactions from within the runtime.
pub trait SendTransactionTypes<LocalCall> {
	/// The extrinsic type expected by the runtime.
	type Extrinsic: ExtrinsicT<Call=Self::OverarchingCall> + codec::Encode;
	/// The runtime's call type.
	///
	/// This has additional bound to be able to be created from pallet-local `Call` types.
	type OverarchingCall: From<LocalCall>;
}

/// Create signed transaction.
///
/// This trait is meant to be implemented by the runtime and is responsible for constructing
/// a payload to be signed and contained within the extrinsic.
/// This will most likely include creation of `SignedExtra` (a set of `SignedExtensions`).
/// Note that the result can be altered by inspecting the `Call` (for instance adjusting
/// fees, or mortality depending on the `pallet` being called).
pub trait CreateSignedTransaction<LocalCall>: SendTransactionTypes<LocalCall> + SigningTypes {
	/// Attempt to create signed extrinsic data that encodes call from given account.
	///
	/// Runtime implementation is free to construct the payload to sign and the signature
	/// in any way it wants.
	/// Returns `None` if signed extrinsic could not be created (either because signing failed
	/// or because of any other runtime-specific reason).
	fn create_transaction<C: AppCrypto<Self::Public, Self::Signature>>(
		call: Self::OverarchingCall,
		public: Self::Public,
		account: Self::AccountId,
		nonce: Self::Index,
	) -> Option<(Self::OverarchingCall, <Self::Extrinsic as ExtrinsicT>::SignaturePayload)>;
}

/// A message signer.
pub trait SignMessage<T: SigningTypes> {
	/// A signature data.
	///
	/// May contain account used for signing and the `Signature` itself.
	type SignatureData;

	/// Sign a message.
	///
	/// Implementation of this method should return
	/// a result containing the signature.
	fn sign_message(&self, message: &[u8]) -> Self::SignatureData;

	/// Construct and sign given payload.
	///
	/// This method expects `f` to return a `SignedPayload`
	/// object which is then used for signing.
	fn sign<TPayload, F>(&self, f: F) -> Self::SignatureData where
		F: Fn(&Account<T>) -> TPayload,
		TPayload: SignedPayload<T>,
		;
}

/// Submit a signed transaction to the transaction pool.
pub trait SendSignedTransaction<
	T: SigningTypes + CreateSignedTransaction<LocalCall>,
	C: AppCrypto<T::Public, T::Signature>,
	LocalCall
> {
	/// A submission result.
	///
	/// This should contain an indication of success and the account that was used for signing.
	type Result;

	/// Submit a signed transaction to the local pool.
	///
	/// Given `f` closure will be called for every requested account and expects a `Call` object
	/// to be returned.
	/// The call is then wrapped into a transaction (see `#CreateSignedTransaction`), signed and
	/// submitted to the pool.
	fn send_signed_transaction(
		&self,
		f: impl Fn(&Account<T>) -> LocalCall,
	) -> Self::Result;

	/// Wraps the call into transaction, signs using given account and submits to the pool.
	fn send_single_signed_transaction(
		&self,
		account: &Account<T>,
		call: LocalCall,
	) -> Option<Result<(), ()>> {
		let mut account_data = crate::Account::<T>::get(&account.id);
		debug::native::debug!(
			target: "offchain",
			"Creating signed transaction from account: {:?} (nonce: {:?})",
			account.id,
			account_data.nonce,
		);
		let (call, signature) = T::create_transaction::<C>(
			call.into(),
			account.public.clone(),
			account.id.clone(),
			account_data.nonce
		)?;
		let res = SubmitTransaction::<T, LocalCall>
			::submit_transaction(call, Some(signature));

		if res.is_ok() {
			// increment the nonce. This is fine, since the code should always
			// be running in off-chain context, so we NEVER persists data.
			account_data.nonce += One::one();
			crate::Account::<T>::insert(&account.id, account_data);
		}

		Some(res)
	}
}

/// Submit an unsigned transaction onchain with a signed payload
pub trait SendUnsignedTransaction<
	T: SigningTypes + SendTransactionTypes<LocalCall>,
	LocalCall,
> {
	/// A submission result.
	///
	/// Should contain the submission result and the account(s) that signed the payload.
	type Result;

	/// Send an unsigned transaction with a signed payload.
	///
	/// This method takes `f` and `f2` where:
	/// - `f` is called for every account and is expected to return a `SignedPayload` object.
	/// - `f2` is then called with the `SignedPayload` returned by `f` and the signature and is
	/// expected to return a `Call` object to be embedded into transaction.
	fn send_unsigned_transaction<TPayload, F>(
		&self,
		f: F,
		f2: impl Fn(TPayload, T::Signature) -> LocalCall,
	) -> Self::Result
	where
		F: Fn(&Account<T>) -> TPayload,
		TPayload: SignedPayload<T>;

	/// Submits an unsigned call to the transaction pool.
	fn submit_unsigned_transaction(
		&self,
		call: LocalCall
	) -> Option<Result<(), ()>> {
		Some(SubmitTransaction::<T, LocalCall>
			::submit_unsigned_transaction(call.into()))
	}
}

/// Utility trait to be implemented on payloads that can be signed.
pub trait SignedPayload<T: SigningTypes>: Encode {
	/// Return a public key that is expected to have a matching key in the keystore,
	/// which should be used to sign the payload.
	fn public(&self) -> T::Public;

	/// Sign the payload using the implementor's provided public key.
	///
	/// Returns `Some(signature)` if public key is supported.
	fn sign<C: AppCrypto<T::Public, T::Signature>>(&self) -> Option<T::Signature> {
		self.using_encoded(|payload| C::sign(payload, self.public()))
	}

	/// Verify signature against payload.
	///
	/// Returns a bool indicating whether the signature is valid or not.
	fn verify<C: AppCrypto<T::Public, T::Signature>>(&self, signature: T::Signature) -> bool {
		self.using_encoded(|payload| C::verify(payload, self.public(), signature))
	}
}


#[cfg(test)]
mod tests {
	use super::*;
	use codec::Decode;
	use crate::mock::{Test as TestRuntime, Call};
	use sp_core::offchain::{testing, TransactionPoolExt};
	use sp_runtime::testing::{UintAuthorityId, TestSignature, TestXt};

	impl SigningTypes for TestRuntime {
		type Public = UintAuthorityId;
		type Signature = TestSignature;
	}

	type Extrinsic = TestXt<Call, ()>;

	impl SendTransactionTypes<Call> for TestRuntime {
		type Extrinsic = Extrinsic;
		type OverarchingCall = Call;
	}

	#[derive(codec::Encode, codec::Decode)]
	struct SimplePayload {
		pub public: UintAuthorityId,
		pub data: Vec<u8>,
	}

	impl SignedPayload<TestRuntime> for SimplePayload {
		fn public(&self) -> UintAuthorityId {
			self.public.clone()
		}
	}

	struct DummyAppCrypto;
	// Bind together the `SigningTypes` with app-crypto and the wrapper types.
	// here the implementation is pretty dummy, because we use the same type for
	// both application-specific crypto and the runtime crypto, but in real-life
	// runtimes it's going to use different types everywhere.
	impl AppCrypto<UintAuthorityId, TestSignature> for DummyAppCrypto {
		type RuntimeAppPublic = UintAuthorityId;
		type GenericPublic = UintAuthorityId;
		type GenericSignature = TestSignature;
	}

	fn assert_account(
		next: Option<(Account<TestRuntime>, Result<(), ()>)>,
		index: usize,
		id: u64,
	) {
		assert_eq!(next, Some((Account {
			index,
			id,
			public: id.into(),
		}, Ok(()))));
	}

	#[test]
	fn should_send_unsigned_with_signed_payload_with_all_accounts() {
		let (pool, pool_state) = testing::TestTransactionPoolExt::new();

		let mut t = sp_io::TestExternalities::default();
		t.register_extension(TransactionPoolExt::new(pool));

		// given
		UintAuthorityId::set_all_keys(vec![0xf0, 0xf1, 0xf2]);

		t.execute_with(|| {
			// when
			let result = Signer::<TestRuntime, DummyAppCrypto>
				::all_accounts()
				.send_unsigned_transaction(
					|account| SimplePayload {
						data: vec![1, 2, 3],
						public: account.public.clone()
					},
					|_payload, _signature| {
						Call
					}
				);

			// then
			let mut res = result.into_iter();
			assert_account(res.next(), 0, 0xf0);
			assert_account(res.next(), 1, 0xf1);
			assert_account(res.next(), 2, 0xf2);
			assert_eq!(res.next(), None);

			// check the transaction pool content:
			let tx1 = pool_state.write().transactions.pop().unwrap();
			let _tx2 = pool_state.write().transactions.pop().unwrap();
			let _tx3 = pool_state.write().transactions.pop().unwrap();
			assert!(pool_state.read().transactions.is_empty());
			let tx1 = Extrinsic::decode(&mut &*tx1).unwrap();
			assert_eq!(tx1.signature, None);
		});
	}

	#[test]
	fn should_send_unsigned_with_signed_payload_with_any_account() {
		let (pool, pool_state) = testing::TestTransactionPoolExt::new();

		let mut t = sp_io::TestExternalities::default();
		t.register_extension(TransactionPoolExt::new(pool));

		// given
		UintAuthorityId::set_all_keys(vec![0xf0, 0xf1, 0xf2]);

		t.execute_with(|| {
			// when
			let result = Signer::<TestRuntime, DummyAppCrypto>
				::any_account()
				.send_unsigned_transaction(
					|account| SimplePayload {
						data: vec![1, 2, 3],
						public: account.public.clone()
					},
					|_payload, _signature| {
						Call
					}
				);

			// then
			let mut res = result.into_iter();
			assert_account(res.next(), 0, 0xf0);
			assert_eq!(res.next(), None);

			// check the transaction pool content:
			let tx1 = pool_state.write().transactions.pop().unwrap();
			assert!(pool_state.read().transactions.is_empty());
			let tx1 = Extrinsic::decode(&mut &*tx1).unwrap();
			assert_eq!(tx1.signature, None);
		});
	}

	#[test]
	fn should_send_unsigned_with_signed_payload_with_all_account_and_filter() {
		let (pool, pool_state) = testing::TestTransactionPoolExt::new();

		let mut t = sp_io::TestExternalities::default();
		t.register_extension(TransactionPoolExt::new(pool));

		// given
		UintAuthorityId::set_all_keys(vec![0xf0, 0xf1, 0xf2]);

		t.execute_with(|| {
			// when
			let result = Signer::<TestRuntime, DummyAppCrypto>
				::all_accounts()
				.with_filter(vec![0xf2.into(), 0xf1.into()])
				.send_unsigned_transaction(
					|account| SimplePayload {
						data: vec![1, 2, 3],
						public: account.public.clone()
					},
					|_payload, _signature| {
						Call
					}
				);

			// then
			let mut res = result.into_iter();
			assert_account(res.next(), 0, 0xf2);
			assert_account(res.next(), 1, 0xf1);
			assert_eq!(res.next(), None);

			// check the transaction pool content:
			let tx1 = pool_state.write().transactions.pop().unwrap();
			let _tx2 = pool_state.write().transactions.pop().unwrap();
			assert!(pool_state.read().transactions.is_empty());
			let tx1 = Extrinsic::decode(&mut &*tx1).unwrap();
			assert_eq!(tx1.signature, None);
		});
	}

	#[test]
	fn should_send_unsigned_with_signed_payload_with_any_account_and_filter() {
		let (pool, pool_state) = testing::TestTransactionPoolExt::new();

		let mut t = sp_io::TestExternalities::default();
		t.register_extension(TransactionPoolExt::new(pool));

		// given
		UintAuthorityId::set_all_keys(vec![0xf0, 0xf1, 0xf2]);

		t.execute_with(|| {
			// when
			let result = Signer::<TestRuntime, DummyAppCrypto>
				::any_account()
				.with_filter(vec![0xf2.into(), 0xf1.into()])
				.send_unsigned_transaction(
					|account| SimplePayload {
						data: vec![1, 2, 3],
						public: account.public.clone()
					},
					|_payload, _signature| {
						Call
					}
				);

			// then
			let mut res = result.into_iter();
			assert_account(res.next(), 0, 0xf2);
			assert_eq!(res.next(), None);

			// check the transaction pool content:
			let tx1 = pool_state.write().transactions.pop().unwrap();
			assert!(pool_state.read().transactions.is_empty());
			let tx1 = Extrinsic::decode(&mut &*tx1).unwrap();
			assert_eq!(tx1.signature, None);
		});
	}

}