mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-09 12:49:23 +00:00
Slash malevolent validators (#294)
* add slash tx * ignore unsigned tx replays * verify that provided evidence is valid * fix clippy + fmt * move application tx handling to another module * partially handle the tendermint txs * fix pr comments * support unsigned app txs * add slash target to the votes * enforce provided, unsigned, signed tx ordering within a block * bug fixes * add unit test for tendermint txs * bug fixes * update tests for tendermint txs * add tx ordering test * tidy up tx ordering test * cargo +nightly fmt * Misc fixes from rebasing * Finish resolving clippy * Remove sha3 from tendermint-machine * Resolve a DoS in SlashEvidence's read Also moves Evidence from Vec<Message> to (Message, Option<Message>). That should meet all requirements while being a bit safer. * Make lazy_static a dev-depend for tributary * Various small tweaks One use of sort was inefficient, sorting unsigned || signed when unsigned was already properly sorted. Given how the unsigned TXs were given a nonce of 0, an unstable sort may swap places with an unsigned TX and a signed TX with a nonce of 0 (leading to a faulty block). The extra protection added here sorts signed, then concats. * Fix Tributary tests I broke, start review on tendermint/tx.rs * Finish reviewing everything outside tests and empty_signature * Remove empty_signature empty_signature led to corrupted local state histories. Unfortunately, the API is only sane with a signature. We now use the actual signature, which risks creating a signature over a malicious message if we have ever have an invariant producing malicious messages. Prior, we only signed the message after the local machine confirmed it was okay per the local view of consensus. This is tolerated/preferred over a corrupt state history since production of such messages is already an invariant. TODOs are added to make handling of this theoretical invariant further robust. * Remove async_sequential for tokio::test There was no competition for resources forcing them to be run sequentially. * Modify block order test to be statistically significant without multiple runs * Clean tests --------- Co-authored-by: Luke Parker <lukeparker5132@gmail.com>
This commit is contained in:
@@ -1,14 +1,23 @@
|
||||
use std::{io, collections::HashMap};
|
||||
use std::{sync::Arc, io, collections::HashMap, fmt::Debug};
|
||||
|
||||
use blake2::{Digest, Blake2s256};
|
||||
|
||||
use ciphersuite::{
|
||||
group::{ff::Field, Group},
|
||||
Ciphersuite, Ristretto,
|
||||
};
|
||||
use schnorr::SchnorrSignature;
|
||||
|
||||
use crate::{ReadWrite, TransactionError, Signed, TransactionKind, Transaction, BlockError, Block};
|
||||
use serai_db::MemDb;
|
||||
use tendermint::ext::Commit;
|
||||
|
||||
use crate::{
|
||||
ReadWrite, BlockError, Block, Transaction,
|
||||
tests::p2p::DummyP2p,
|
||||
transaction::{TransactionError, Signed, TransactionKind, Transaction as TransactionTrait},
|
||||
tendermint::{TendermintNetwork, Validators},
|
||||
};
|
||||
|
||||
type N = TendermintNetwork<MemDb, NonceTransaction, DummyP2p>;
|
||||
|
||||
// A transaction solely defined by its nonce and a distinguisher (to allow creating distinct TXs
|
||||
// sharing a nonce).
|
||||
@@ -50,7 +59,7 @@ impl ReadWrite for NonceTransaction {
|
||||
}
|
||||
}
|
||||
|
||||
impl Transaction for NonceTransaction {
|
||||
impl TransactionTrait for NonceTransaction {
|
||||
fn kind(&self) -> TransactionKind<'_> {
|
||||
TransactionKind::Signed(&self.2)
|
||||
}
|
||||
@@ -68,8 +77,21 @@ impl Transaction for NonceTransaction {
|
||||
fn empty_block() {
|
||||
const GENESIS: [u8; 32] = [0xff; 32];
|
||||
const LAST: [u8; 32] = [0x01; 32];
|
||||
let validators = Arc::new(Validators::new(GENESIS, vec![]).unwrap());
|
||||
let commit = |_: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
let unsigned_in_chain = |_: [u8; 32]| false;
|
||||
Block::<NonceTransaction>::new(LAST, vec![], vec![])
|
||||
.verify(GENESIS, LAST, HashMap::new(), HashMap::new())
|
||||
.verify::<N>(
|
||||
GENESIS,
|
||||
LAST,
|
||||
HashMap::new(),
|
||||
HashMap::new(),
|
||||
validators,
|
||||
commit,
|
||||
unsigned_in_chain,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -78,19 +100,29 @@ fn duplicate_nonces() {
|
||||
const GENESIS: [u8; 32] = [0xff; 32];
|
||||
const LAST: [u8; 32] = [0x01; 32];
|
||||
|
||||
let validators = Arc::new(Validators::new(GENESIS, vec![]).unwrap());
|
||||
|
||||
// Run once without duplicating a nonce, and once with, so that's confirmed to be the faulty
|
||||
// component
|
||||
for i in [1, 0] {
|
||||
let mut mempool = vec![];
|
||||
let mut insert = |tx: NonceTransaction| mempool.push(tx);
|
||||
let mut insert = |tx: NonceTransaction| mempool.push(Transaction::Application(tx));
|
||||
insert(NonceTransaction::new(0, 0));
|
||||
insert(NonceTransaction::new(i, 1));
|
||||
|
||||
let res = Block::new(LAST, vec![], mempool).verify(
|
||||
let commit = |_: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
let unsigned_in_chain = |_: [u8; 32]| false;
|
||||
|
||||
let res = Block::new(LAST, vec![], mempool).verify::<N>(
|
||||
GENESIS,
|
||||
LAST,
|
||||
HashMap::new(),
|
||||
HashMap::from([(<Ristretto as Ciphersuite>::G::identity(), 0)]),
|
||||
validators.clone(),
|
||||
commit,
|
||||
unsigned_in_chain,
|
||||
);
|
||||
if i == 1 {
|
||||
res.unwrap();
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
use std::collections::{VecDeque, HashMap};
|
||||
use core::ops::Deref;
|
||||
use std::{
|
||||
collections::{VecDeque, HashMap},
|
||||
sync::Arc,
|
||||
io,
|
||||
};
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
use rand::{RngCore, rngs::OsRng};
|
||||
use rand::rngs::OsRng;
|
||||
|
||||
use blake2::{Digest, Blake2s256};
|
||||
|
||||
@@ -10,17 +15,20 @@ use ciphersuite::{group::ff::Field, Ciphersuite, Ristretto};
|
||||
use serai_db::{DbTxn, Db, MemDb};
|
||||
|
||||
use crate::{
|
||||
merkle, Transaction, ProvidedError, ProvidedTransactions, Block, Blockchain,
|
||||
tests::{ProvidedTransaction, SignedTransaction, random_provided_transaction},
|
||||
ReadWrite, TransactionKind,
|
||||
transaction::Transaction as TransactionTrait,
|
||||
TransactionError, Transaction, ProvidedError, ProvidedTransactions, merkle, BlockError, Block,
|
||||
Blockchain,
|
||||
tendermint::{TendermintNetwork, Validators, tx::TendermintTx, Signer, TendermintBlock},
|
||||
tests::{
|
||||
ProvidedTransaction, SignedTransaction, random_provided_transaction, p2p::DummyP2p,
|
||||
new_genesis, random_vote_tx, random_evidence_tx,
|
||||
},
|
||||
};
|
||||
|
||||
fn new_genesis() -> [u8; 32] {
|
||||
let mut genesis = [0; 32];
|
||||
OsRng.fill_bytes(&mut genesis);
|
||||
genesis
|
||||
}
|
||||
type N = TendermintNetwork<MemDb, SignedTransaction, DummyP2p>;
|
||||
|
||||
fn new_blockchain<T: Transaction>(
|
||||
fn new_blockchain<T: TransactionTrait>(
|
||||
genesis: [u8; 32],
|
||||
participants: &[<Ristretto as Ciphersuite>::G],
|
||||
) -> (MemDb, Blockchain<MemDb, T>) {
|
||||
@@ -34,12 +42,14 @@ fn new_blockchain<T: Transaction>(
|
||||
#[test]
|
||||
fn block_addition() {
|
||||
let genesis = new_genesis();
|
||||
let validators = Arc::new(Validators::new(genesis, vec![]).unwrap());
|
||||
let (db, mut blockchain) = new_blockchain::<SignedTransaction>(genesis, &[]);
|
||||
let block = blockchain.build_block();
|
||||
let block = blockchain.build_block::<N>(validators.clone());
|
||||
|
||||
assert_eq!(block.header.parent, genesis);
|
||||
assert_eq!(block.header.transactions, [0; 32]);
|
||||
blockchain.verify_block(&block).unwrap();
|
||||
assert!(blockchain.add_block(&block, vec![]).is_ok());
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
assert!(blockchain.add_block::<N>(&block, vec![], validators).is_ok());
|
||||
assert_eq!(blockchain.tip(), block.hash());
|
||||
assert_eq!(blockchain.block_number(), 1);
|
||||
assert_eq!(
|
||||
@@ -51,23 +61,24 @@ fn block_addition() {
|
||||
#[test]
|
||||
fn invalid_block() {
|
||||
let genesis = new_genesis();
|
||||
let validators = Arc::new(Validators::new(genesis, vec![]).unwrap());
|
||||
let (_, mut blockchain) = new_blockchain::<SignedTransaction>(genesis, &[]);
|
||||
|
||||
let block = blockchain.build_block();
|
||||
let block = blockchain.build_block::<N>(validators.clone());
|
||||
|
||||
// Mutate parent
|
||||
{
|
||||
#[allow(clippy::redundant_clone)] // False positive
|
||||
let mut block = block.clone();
|
||||
block.header.parent = Blake2s256::digest(block.header.parent).into();
|
||||
assert!(blockchain.verify_block(&block).is_err());
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
}
|
||||
|
||||
// Mutate tranactions merkle
|
||||
{
|
||||
let mut block = block;
|
||||
block.header.transactions = Blake2s256::digest(block.header.transactions).into();
|
||||
assert!(blockchain.verify_block(&block).is_err());
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
}
|
||||
|
||||
let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
|
||||
@@ -76,9 +87,9 @@ fn invalid_block() {
|
||||
// Not a participant
|
||||
{
|
||||
// Manually create the block to bypass build_block's checks
|
||||
let block = Block::new(blockchain.tip(), vec![], vec![tx.clone()]);
|
||||
let block = Block::new(blockchain.tip(), vec![], vec![Transaction::Application(tx.clone())]);
|
||||
assert_eq!(block.header.transactions, merkle(&[tx.hash()]));
|
||||
assert!(blockchain.verify_block(&block).is_err());
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
}
|
||||
|
||||
// Run the rest of the tests with them as a participant
|
||||
@@ -86,40 +97,81 @@ fn invalid_block() {
|
||||
|
||||
// Re-run the not a participant block to make sure it now works
|
||||
{
|
||||
let block = Block::new(blockchain.tip(), vec![], vec![tx.clone()]);
|
||||
let block = Block::new(blockchain.tip(), vec![], vec![Transaction::Application(tx.clone())]);
|
||||
assert_eq!(block.header.transactions, merkle(&[tx.hash()]));
|
||||
blockchain.verify_block(&block).unwrap();
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
}
|
||||
|
||||
{
|
||||
// Add a valid transaction
|
||||
let mut blockchain = blockchain.clone();
|
||||
assert!(blockchain.add_transaction(true, tx.clone()));
|
||||
let mut block = blockchain.build_block();
|
||||
assert!(blockchain.add_transaction::<N>(
|
||||
true,
|
||||
Transaction::Application(tx.clone()),
|
||||
validators.clone()
|
||||
));
|
||||
let mut block = blockchain.build_block::<N>(validators.clone());
|
||||
assert_eq!(block.header.transactions, merkle(&[tx.hash()]));
|
||||
blockchain.verify_block(&block).unwrap();
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
|
||||
// And verify mutating the transactions merkle now causes a failure
|
||||
block.header.transactions = merkle(&[]);
|
||||
assert!(blockchain.verify_block(&block).is_err());
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
}
|
||||
|
||||
{
|
||||
// Invalid nonce
|
||||
let tx = crate::tests::signed_transaction(&mut OsRng, genesis, &key, 5);
|
||||
// Manually create the block to bypass build_block's checks
|
||||
let block = Block::new(blockchain.tip(), vec![], vec![tx]);
|
||||
assert!(blockchain.verify_block(&block).is_err());
|
||||
let block = Block::new(blockchain.tip(), vec![], vec![Transaction::Application(tx)]);
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
}
|
||||
|
||||
{
|
||||
// Invalid signature
|
||||
let mut blockchain = blockchain;
|
||||
assert!(blockchain.add_transaction(true, tx));
|
||||
let mut block = blockchain.build_block();
|
||||
blockchain.verify_block(&block).unwrap();
|
||||
block.transactions[0].1.signature.s += <Ristretto as Ciphersuite>::F::ONE;
|
||||
assert!(blockchain.verify_block(&block).is_err());
|
||||
let mut blockchain = blockchain.clone();
|
||||
assert!(blockchain.add_transaction::<N>(
|
||||
true,
|
||||
Transaction::Application(tx),
|
||||
validators.clone()
|
||||
));
|
||||
let mut block = blockchain.build_block::<N>(validators.clone());
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
match &mut block.transactions[0] {
|
||||
Transaction::Application(tx) => {
|
||||
tx.1.signature.s += <Ristretto as Ciphersuite>::F::ONE;
|
||||
}
|
||||
_ => panic!("non-signed tx found"),
|
||||
}
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
|
||||
// Make sure this isn't because the merkle changed due to the transaction hash including the
|
||||
// signature (which it explicitly isn't allowed to anyways)
|
||||
assert_eq!(block.header.transactions, merkle(&[block.transactions[0].hash()]));
|
||||
}
|
||||
|
||||
{
|
||||
// Invalid vote signature
|
||||
let mut blockchain = blockchain.clone();
|
||||
let vote_tx = random_vote_tx(&mut OsRng, genesis);
|
||||
assert!(blockchain.add_transaction::<N>(
|
||||
true,
|
||||
Transaction::Tendermint(vote_tx),
|
||||
validators.clone()
|
||||
));
|
||||
let mut block = blockchain.build_block::<N>(validators.clone());
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
match &mut block.transactions[0] {
|
||||
Transaction::Tendermint(tx) => match tx {
|
||||
TendermintTx::SlashVote(vote) => {
|
||||
vote.sig.signature.s += <Ristretto as Ciphersuite>::F::ONE;
|
||||
}
|
||||
_ => panic!("non-vote tx found"),
|
||||
},
|
||||
_ => panic!("non-tendermint tx found"),
|
||||
}
|
||||
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
|
||||
// Make sure this isn't because the merkle changed due to the transaction hash including the
|
||||
// signature (which it explicitly isn't allowed to anyways)
|
||||
@@ -130,7 +182,7 @@ fn invalid_block() {
|
||||
#[test]
|
||||
fn signed_transaction() {
|
||||
let genesis = new_genesis();
|
||||
|
||||
let validators = Arc::new(Validators::new(genesis, vec![]).unwrap());
|
||||
let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
|
||||
let tx = crate::tests::signed_transaction(&mut OsRng, genesis, &key, 0);
|
||||
let signer = tx.1.signer;
|
||||
@@ -139,14 +191,21 @@ fn signed_transaction() {
|
||||
assert_eq!(blockchain.next_nonce(signer), Some(0));
|
||||
|
||||
let test = |blockchain: &mut Blockchain<MemDb, SignedTransaction>,
|
||||
mempool: Vec<SignedTransaction>| {
|
||||
mempool: Vec<Transaction<SignedTransaction>>| {
|
||||
let tip = blockchain.tip();
|
||||
for tx in mempool.clone() {
|
||||
let Transaction::Application(tx) = tx else {
|
||||
panic!("tendermint tx found");
|
||||
};
|
||||
let next_nonce = blockchain.next_nonce(signer).unwrap();
|
||||
assert!(blockchain.add_transaction(true, tx));
|
||||
assert!(blockchain.add_transaction::<N>(
|
||||
true,
|
||||
Transaction::Application(tx),
|
||||
validators.clone()
|
||||
));
|
||||
assert_eq!(next_nonce + 1, blockchain.next_nonce(signer).unwrap());
|
||||
}
|
||||
let block = blockchain.build_block();
|
||||
let block = blockchain.build_block::<N>(validators.clone());
|
||||
assert_eq!(block, Block::new(blockchain.tip(), vec![], mempool.clone()));
|
||||
assert_eq!(blockchain.tip(), tip);
|
||||
assert_eq!(block.header.parent, tip);
|
||||
@@ -160,19 +219,21 @@ fn signed_transaction() {
|
||||
);
|
||||
|
||||
// Verify and add the block
|
||||
blockchain.verify_block(&block).unwrap();
|
||||
assert!(blockchain.add_block(&block, vec![]).is_ok());
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
assert!(blockchain.add_block::<N>(&block, vec![], validators.clone()).is_ok());
|
||||
assert_eq!(blockchain.tip(), block.hash());
|
||||
};
|
||||
|
||||
// Test with a single nonce
|
||||
test(&mut blockchain, vec![tx]);
|
||||
test(&mut blockchain, vec![Transaction::Application(tx)]);
|
||||
assert_eq!(blockchain.next_nonce(signer), Some(1));
|
||||
|
||||
// Test with a flood of nonces
|
||||
let mut mempool = vec![];
|
||||
for nonce in 1 .. 64 {
|
||||
mempool.push(crate::tests::signed_transaction(&mut OsRng, genesis, &key, nonce));
|
||||
mempool.push(Transaction::Application(crate::tests::signed_transaction(
|
||||
&mut OsRng, genesis, &key, nonce,
|
||||
)));
|
||||
}
|
||||
test(&mut blockchain, mempool);
|
||||
assert_eq!(blockchain.next_nonce(signer), Some(64));
|
||||
@@ -181,6 +242,7 @@ fn signed_transaction() {
|
||||
#[test]
|
||||
fn provided_transaction() {
|
||||
let genesis = new_genesis();
|
||||
let validators = Arc::new(Validators::new(genesis, vec![]).unwrap());
|
||||
let (_, mut blockchain) = new_blockchain::<ProvidedTransaction>(genesis, &[]);
|
||||
|
||||
let tx = random_provided_transaction(&mut OsRng);
|
||||
@@ -203,18 +265,274 @@ fn provided_transaction() {
|
||||
|
||||
// Non-provided transactions should fail verification
|
||||
let block = Block::new(blockchain.tip(), vec![tx.clone()], vec![]);
|
||||
assert!(blockchain.verify_block(&block).is_err());
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
|
||||
// Provided transactions should pass verification
|
||||
blockchain.provide_transaction(tx.clone()).unwrap();
|
||||
blockchain.verify_block(&block).unwrap();
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
|
||||
// add_block should work for verified blocks
|
||||
assert!(blockchain.add_block(&block, vec![]).is_ok());
|
||||
assert!(blockchain.add_block::<N>(&block, vec![], validators.clone()).is_ok());
|
||||
|
||||
let block = Block::new(blockchain.tip(), vec![tx], vec![]);
|
||||
// The provided transaction should no longer considered provided, causing this error
|
||||
assert!(blockchain.verify_block(&block).is_err());
|
||||
assert!(blockchain.verify_block::<N>(&block, validators.clone()).is_err());
|
||||
// add_block should fail for unverified provided transactions if told to add them
|
||||
assert!(blockchain.add_block(&block, vec![]).is_err());
|
||||
assert!(blockchain.add_block::<N>(&block, vec![], validators.clone()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tendermint_vote_tx() {
|
||||
let genesis = new_genesis();
|
||||
let validators = Arc::new(Validators::new(genesis, vec![]).unwrap());
|
||||
|
||||
let (_, mut blockchain) = new_blockchain::<SignedTransaction>(genesis, &[]);
|
||||
|
||||
let test = |blockchain: &mut Blockchain<MemDb, SignedTransaction>,
|
||||
mempool: Vec<Transaction<SignedTransaction>>| {
|
||||
let tip = blockchain.tip();
|
||||
for tx in mempool.clone() {
|
||||
let Transaction::Tendermint(tx) = tx else {
|
||||
panic!("non-tendermint tx found");
|
||||
};
|
||||
assert!(blockchain.add_transaction::<N>(
|
||||
true,
|
||||
Transaction::Tendermint(tx),
|
||||
validators.clone()
|
||||
));
|
||||
}
|
||||
let block = blockchain.build_block::<N>(validators.clone());
|
||||
|
||||
assert_eq!(blockchain.tip(), tip);
|
||||
assert_eq!(block.header.parent, tip);
|
||||
|
||||
// Make sure all transactions were included
|
||||
for bt in &block.transactions {
|
||||
assert!(mempool.contains(bt));
|
||||
}
|
||||
|
||||
// Make sure the merkle was correct
|
||||
// Uses block.transactions instead of mempool as order may differ between the two
|
||||
assert_eq!(
|
||||
block.header.transactions,
|
||||
merkle(&block.transactions.iter().map(Transaction::hash).collect::<Vec<_>>()),
|
||||
);
|
||||
|
||||
// Verify and add the block
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
assert!(blockchain.add_block::<N>(&block, vec![], validators.clone()).is_ok());
|
||||
assert_eq!(blockchain.tip(), block.hash());
|
||||
};
|
||||
|
||||
// test with single tx
|
||||
let tx = random_vote_tx(&mut OsRng, genesis);
|
||||
test(&mut blockchain, vec![Transaction::Tendermint(tx)]);
|
||||
|
||||
// test with multiple txs
|
||||
let mut mempool: Vec<Transaction<SignedTransaction>> = vec![];
|
||||
for _ in 0 .. 5 {
|
||||
mempool.push(Transaction::Tendermint(random_vote_tx(&mut OsRng, genesis)));
|
||||
}
|
||||
test(&mut blockchain, mempool);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tendermint_evidence_tx() {
|
||||
let genesis = new_genesis();
|
||||
let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
|
||||
let signer = Signer::new(genesis, key.clone());
|
||||
let signer_id = Ristretto::generator() * key.deref();
|
||||
let validators = Arc::new(Validators::new(genesis, vec![(signer_id, 1)]).unwrap());
|
||||
|
||||
let (_, mut blockchain) = new_blockchain::<SignedTransaction>(genesis, &[]);
|
||||
|
||||
let test = |blockchain: &mut Blockchain<MemDb, SignedTransaction>,
|
||||
mempool: Vec<Transaction<SignedTransaction>>,
|
||||
validators: Arc<Validators>| {
|
||||
let tip = blockchain.tip();
|
||||
for tx in mempool.clone() {
|
||||
let Transaction::Tendermint(tx) = tx else {
|
||||
panic!("non-tendermint tx found");
|
||||
};
|
||||
assert!(blockchain.add_transaction::<N>(
|
||||
true,
|
||||
Transaction::Tendermint(tx),
|
||||
validators.clone()
|
||||
));
|
||||
}
|
||||
let block = blockchain.build_block::<N>(validators.clone());
|
||||
assert_eq!(blockchain.tip(), tip);
|
||||
assert_eq!(block.header.parent, tip);
|
||||
|
||||
// Make sure all transactions were included
|
||||
for bt in &block.transactions {
|
||||
assert!(mempool.contains(bt));
|
||||
}
|
||||
|
||||
// Verify and add the block
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
assert!(blockchain.add_block::<N>(&block, vec![], validators.clone()).is_ok());
|
||||
assert_eq!(blockchain.tip(), block.hash());
|
||||
};
|
||||
|
||||
// test with single tx
|
||||
let tx = random_evidence_tx::<N>(signer.into(), TendermintBlock(vec![0x12])).await;
|
||||
test(&mut blockchain, vec![Transaction::Tendermint(tx)], validators);
|
||||
|
||||
// test with multiple txs
|
||||
let mut mempool: Vec<Transaction<SignedTransaction>> = vec![];
|
||||
let mut signers = vec![];
|
||||
for _ in 0 .. 5 {
|
||||
let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
|
||||
let signer = Signer::new(genesis, key.clone());
|
||||
let signer_id = Ristretto::generator() * key.deref();
|
||||
signers.push((signer_id, 1));
|
||||
mempool.push(Transaction::Tendermint(
|
||||
random_evidence_tx::<N>(signer.into(), TendermintBlock(vec![0x12])).await,
|
||||
));
|
||||
}
|
||||
|
||||
// update validators
|
||||
let validators = Arc::new(Validators::new(genesis, signers).unwrap());
|
||||
test(&mut blockchain, mempool, validators);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_tx_ordering() {
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
enum SignedTx {
|
||||
Signed(Box<SignedTransaction>),
|
||||
Provided(Box<ProvidedTransaction>),
|
||||
}
|
||||
impl ReadWrite for SignedTx {
|
||||
fn read<R: io::Read>(reader: &mut R) -> io::Result<Self> {
|
||||
let mut kind = [0];
|
||||
reader.read_exact(&mut kind)?;
|
||||
match kind[0] {
|
||||
0 => Ok(SignedTx::Signed(Box::new(SignedTransaction::read(reader)?))),
|
||||
1 => Ok(SignedTx::Provided(Box::new(ProvidedTransaction::read(reader)?))),
|
||||
_ => Err(io::Error::new(io::ErrorKind::Other, "invalid transaction type")),
|
||||
}
|
||||
}
|
||||
|
||||
fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
|
||||
match self {
|
||||
SignedTx::Signed(signed) => {
|
||||
writer.write_all(&[0])?;
|
||||
signed.write(writer)
|
||||
}
|
||||
SignedTx::Provided(pro) => {
|
||||
writer.write_all(&[1])?;
|
||||
pro.write(writer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TransactionTrait for SignedTx {
|
||||
fn kind(&self) -> TransactionKind<'_> {
|
||||
match self {
|
||||
SignedTx::Signed(signed) => signed.kind(),
|
||||
SignedTx::Provided(pro) => pro.kind(),
|
||||
}
|
||||
}
|
||||
|
||||
fn hash(&self) -> [u8; 32] {
|
||||
match self {
|
||||
SignedTx::Signed(signed) => signed.hash(),
|
||||
SignedTx::Provided(pro) => pro.hash(),
|
||||
}
|
||||
}
|
||||
|
||||
fn verify(&self) -> Result<(), TransactionError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let genesis = new_genesis();
|
||||
let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
|
||||
let validators = Arc::new(Validators::new(genesis, vec![]).unwrap());
|
||||
|
||||
// signer
|
||||
let signer = crate::tests::signed_transaction(&mut OsRng, genesis, &key, 0).1.signer;
|
||||
|
||||
let (_, mut blockchain) = new_blockchain::<SignedTx>(genesis, &[signer]);
|
||||
let tip = blockchain.tip();
|
||||
|
||||
// add txs
|
||||
let mut mempool = vec![];
|
||||
let mut provided_txs = vec![];
|
||||
for i in 0 .. 128 {
|
||||
let signed_tx = Transaction::Application(SignedTx::Signed(Box::new(
|
||||
crate::tests::signed_transaction(&mut OsRng, genesis, &key, i),
|
||||
)));
|
||||
assert!(blockchain.add_transaction::<N>(true, signed_tx.clone(), validators.clone()));
|
||||
mempool.push(signed_tx);
|
||||
|
||||
let unsigned_tx = Transaction::Tendermint(random_vote_tx(&mut OsRng, genesis));
|
||||
assert!(blockchain.add_transaction::<N>(true, unsigned_tx.clone(), validators.clone()));
|
||||
mempool.push(unsigned_tx);
|
||||
|
||||
let provided_tx = SignedTx::Provided(Box::new(random_provided_transaction(&mut OsRng)));
|
||||
blockchain.provide_transaction(provided_tx.clone()).unwrap();
|
||||
provided_txs.push(provided_tx);
|
||||
}
|
||||
let block = blockchain.build_block::<N>(validators.clone());
|
||||
|
||||
assert_eq!(blockchain.tip(), tip);
|
||||
assert_eq!(block.header.parent, tip);
|
||||
|
||||
// Make sure all transactions were included
|
||||
assert_eq!(block.transactions.len(), 3 * 128);
|
||||
for bt in &block.transactions[128 ..] {
|
||||
assert!(mempool.contains(bt));
|
||||
}
|
||||
|
||||
// check the tx order
|
||||
let txs = &block.transactions;
|
||||
for tx in txs.iter().take(128) {
|
||||
assert!(matches!(tx.kind(), TransactionKind::Provided(..)));
|
||||
}
|
||||
for tx in txs.iter().take(128).skip(128) {
|
||||
assert!(matches!(tx.kind(), TransactionKind::Unsigned));
|
||||
}
|
||||
for tx in txs.iter().take(128).skip(256) {
|
||||
assert!(matches!(tx.kind(), TransactionKind::Signed(..)));
|
||||
}
|
||||
|
||||
// should be a valid block
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap();
|
||||
|
||||
// Unsigned before Provided
|
||||
{
|
||||
let mut block = block.clone();
|
||||
// Doesn't use swap to preserve the order of Provided, as that's checked before kind ordering
|
||||
let unsigned = block.transactions.remove(128);
|
||||
block.transactions.insert(0, unsigned);
|
||||
assert_eq!(
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap_err(),
|
||||
BlockError::WrongTransactionOrder
|
||||
);
|
||||
}
|
||||
|
||||
// Signed before Provided
|
||||
{
|
||||
let mut block = block.clone();
|
||||
let signed = block.transactions.remove(256);
|
||||
block.transactions.insert(0, signed);
|
||||
assert_eq!(
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap_err(),
|
||||
BlockError::WrongTransactionOrder
|
||||
);
|
||||
}
|
||||
|
||||
// Signed before Unsigned
|
||||
{
|
||||
let mut block = block;
|
||||
block.transactions.swap(128, 256);
|
||||
assert_eq!(
|
||||
blockchain.verify_block::<N>(&block, validators.clone()).unwrap_err(),
|
||||
BlockError::WrongTransactionOrder
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,50 +1,132 @@
|
||||
use std::collections::HashMap;
|
||||
use std::{sync::Arc, collections::HashMap};
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
use rand::{RngCore, rngs::OsRng};
|
||||
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite, Ristretto};
|
||||
|
||||
use tendermint::ext::Commit;
|
||||
|
||||
use serai_db::MemDb;
|
||||
|
||||
use crate::{
|
||||
transaction::Transaction as TransactionTrait,
|
||||
tendermint::{TendermintBlock, Validators, Signer, TendermintNetwork},
|
||||
ACCOUNT_MEMPOOL_LIMIT, Transaction, Mempool,
|
||||
tests::{SignedTransaction, signed_transaction},
|
||||
tests::{
|
||||
SignedTransaction, signed_transaction, p2p::DummyP2p, random_vote_tx, random_evidence_tx,
|
||||
},
|
||||
};
|
||||
|
||||
fn new_mempool<T: Transaction>() -> ([u8; 32], MemDb, Mempool<MemDb, T>) {
|
||||
type N = TendermintNetwork<MemDb, SignedTransaction, DummyP2p>;
|
||||
|
||||
fn new_mempool<T: TransactionTrait>() -> ([u8; 32], MemDb, Mempool<MemDb, T>) {
|
||||
let mut genesis = [0; 32];
|
||||
OsRng.fill_bytes(&mut genesis);
|
||||
let db = MemDb::new();
|
||||
(genesis, db.clone(), Mempool::new(db, genesis))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mempool_addition() {
|
||||
#[tokio::test]
|
||||
async fn mempool_addition() {
|
||||
let (genesis, db, mut mempool) = new_mempool::<SignedTransaction>();
|
||||
|
||||
let commit = |_: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
let unsigned_in_chain = |_: [u8; 32]| false;
|
||||
let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
|
||||
|
||||
let first_tx = signed_transaction(&mut OsRng, genesis, &key, 0);
|
||||
let signer = first_tx.1.signer;
|
||||
assert_eq!(mempool.next_nonce(&signer), None);
|
||||
|
||||
// validators
|
||||
let validators = Arc::new(Validators::new(genesis, vec![(signer, 1)]).unwrap());
|
||||
|
||||
// Add TX 0
|
||||
let mut blockchain_next_nonces = HashMap::from([(signer, 0)]);
|
||||
assert!(mempool.add(&blockchain_next_nonces, true, first_tx.clone()));
|
||||
assert!(mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Application(first_tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
assert_eq!(mempool.next_nonce(&signer), Some(1));
|
||||
|
||||
// add a tendermint vote tx
|
||||
let vote_tx = random_vote_tx(&mut OsRng, genesis);
|
||||
assert!(mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Tendermint(vote_tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
|
||||
// add a tendermint evidence tx
|
||||
let evidence_tx =
|
||||
random_evidence_tx::<N>(Signer::new(genesis, key.clone()).into(), TendermintBlock(vec![]))
|
||||
.await;
|
||||
assert!(mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Tendermint(evidence_tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
|
||||
// Test reloading works
|
||||
assert_eq!(mempool, Mempool::new(db, genesis));
|
||||
|
||||
// Adding it again should fail
|
||||
assert!(!mempool.add(&blockchain_next_nonces, true, first_tx.clone()));
|
||||
assert!(!mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Application(first_tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
assert!(!mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Tendermint(vote_tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
assert!(!mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Tendermint(evidence_tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
|
||||
// Do the same with the next nonce
|
||||
let second_tx = signed_transaction(&mut OsRng, genesis, &key, 1);
|
||||
assert!(mempool.add(&blockchain_next_nonces, true, second_tx.clone()));
|
||||
assert!(mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Application(second_tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
assert_eq!(mempool.next_nonce(&signer), Some(2));
|
||||
assert!(!mempool.add(&blockchain_next_nonces, true, second_tx.clone()));
|
||||
assert!(!mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Application(second_tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
|
||||
// If the mempool doesn't have a nonce for an account, it should successfully use the
|
||||
// blockchain's
|
||||
@@ -53,43 +135,68 @@ fn mempool_addition() {
|
||||
let second_signer = tx.1.signer;
|
||||
assert_eq!(mempool.next_nonce(&second_signer), None);
|
||||
blockchain_next_nonces.insert(second_signer, 2);
|
||||
assert!(mempool.add(&blockchain_next_nonces, true, tx.clone()));
|
||||
assert!(mempool.add::<N>(
|
||||
&blockchain_next_nonces,
|
||||
true,
|
||||
Transaction::Application(tx.clone()),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit
|
||||
));
|
||||
assert_eq!(mempool.next_nonce(&second_signer), Some(3));
|
||||
|
||||
// Getting a block should work
|
||||
assert_eq!(mempool.block(&blockchain_next_nonces).len(), 3);
|
||||
assert_eq!(mempool.block(&blockchain_next_nonces, unsigned_in_chain).len(), 5);
|
||||
|
||||
// If the blockchain says an account had its nonce updated, it should cause a prune
|
||||
blockchain_next_nonces.insert(signer, 1);
|
||||
let mut block = mempool.block(&blockchain_next_nonces);
|
||||
assert_eq!(block.len(), 2);
|
||||
let mut block = mempool.block(&blockchain_next_nonces, unsigned_in_chain);
|
||||
assert_eq!(block.len(), 4);
|
||||
assert!(!block.iter().any(|tx| tx.hash() == first_tx.hash()));
|
||||
assert_eq!(mempool.txs(), &block.drain(..).map(|tx| (tx.hash(), tx)).collect::<HashMap<_, _>>());
|
||||
|
||||
// Removing should also successfully prune
|
||||
mempool.remove(&tx.hash());
|
||||
assert_eq!(mempool.txs(), &HashMap::from([(second_tx.hash(), second_tx)]));
|
||||
mempool.remove(&vote_tx.hash());
|
||||
|
||||
assert_eq!(
|
||||
mempool.txs(),
|
||||
&HashMap::from([
|
||||
(second_tx.hash(), Transaction::Application(second_tx)),
|
||||
(evidence_tx.hash(), Transaction::Tendermint(evidence_tx))
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_mempool() {
|
||||
let (genesis, _, mut mempool) = new_mempool::<SignedTransaction>();
|
||||
|
||||
let validators = Arc::new(Validators::new(genesis, vec![]).unwrap());
|
||||
let commit = |_: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
let unsigned_in_chain = |_: [u8; 32]| false;
|
||||
let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
|
||||
let signer = signed_transaction(&mut OsRng, genesis, &key, 0).1.signer;
|
||||
|
||||
// We should be able to add transactions up to the limit
|
||||
for i in 0 .. ACCOUNT_MEMPOOL_LIMIT {
|
||||
assert!(mempool.add(
|
||||
assert!(mempool.add::<N>(
|
||||
&HashMap::from([(signer, 0)]),
|
||||
false,
|
||||
signed_transaction(&mut OsRng, genesis, &key, i)
|
||||
Transaction::Application(signed_transaction(&mut OsRng, genesis, &key, i)),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
}
|
||||
// Yet adding more should fail
|
||||
assert!(!mempool.add(
|
||||
assert!(!mempool.add::<N>(
|
||||
&HashMap::from([(signer, 0)]),
|
||||
false,
|
||||
signed_transaction(&mut OsRng, genesis, &key, ACCOUNT_MEMPOOL_LIMIT)
|
||||
Transaction::Application(signed_transaction(&mut OsRng, genesis, &key, ACCOUNT_MEMPOOL_LIMIT)),
|
||||
validators.clone(),
|
||||
unsigned_in_chain,
|
||||
commit,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -10,3 +10,5 @@ mod block;
|
||||
mod blockchain;
|
||||
#[cfg(test)]
|
||||
mod mempool;
|
||||
#[cfg(test)]
|
||||
mod p2p;
|
||||
|
||||
11
coordinator/tributary/src/tests/p2p.rs
Normal file
11
coordinator/tributary/src/tests/p2p.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
pub use crate::P2p;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DummyP2p;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl P2p for DummyP2p {
|
||||
async fn broadcast(&self, _: [u8; 32], _: Vec<u8>) {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use core::ops::Deref;
|
||||
use std::{io, collections::HashMap};
|
||||
use std::{sync::Arc, io, collections::HashMap};
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
use rand::{RngCore, CryptoRng};
|
||||
use rand::{RngCore, CryptoRng, rngs::OsRng};
|
||||
|
||||
use blake2::{Digest, Blake2s256};
|
||||
|
||||
@@ -12,11 +12,28 @@ use ciphersuite::{
|
||||
};
|
||||
use schnorr::SchnorrSignature;
|
||||
|
||||
use crate::{ReadWrite, Signed, TransactionError, TransactionKind, Transaction, verify_transaction};
|
||||
use scale::Encode;
|
||||
|
||||
use ::tendermint::{
|
||||
ext::{Network, Signer as SignerTrait, SignatureScheme, BlockNumber, RoundNumber},
|
||||
SignedMessageFor, DataFor, Message, SignedMessage, Data,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
transaction::{Signed, TransactionError, TransactionKind, Transaction, verify_transaction},
|
||||
ReadWrite,
|
||||
tendermint::{
|
||||
tx::{SlashVote, VoteSignature, TendermintTx},
|
||||
Validators, Signer,
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod signed;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tendermint;
|
||||
|
||||
pub fn random_signed<R: RngCore + CryptoRng>(rng: &mut R) -> Signed {
|
||||
Signed {
|
||||
signer: <Ristretto as Ciphersuite>::G::random(&mut *rng),
|
||||
@@ -138,3 +155,69 @@ pub fn random_signed_transaction<R: RngCore + CryptoRng>(
|
||||
|
||||
(genesis, signed_transaction(rng, genesis, &key, nonce))
|
||||
}
|
||||
|
||||
pub fn new_genesis() -> [u8; 32] {
|
||||
let mut genesis = [0; 32];
|
||||
OsRng.fill_bytes(&mut genesis);
|
||||
genesis
|
||||
}
|
||||
|
||||
pub async fn tendermint_meta() -> ([u8; 32], Signer, [u8; 32], Arc<Validators>) {
|
||||
// signer
|
||||
let genesis = new_genesis();
|
||||
let signer =
|
||||
Signer::new(genesis, Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng)));
|
||||
let validator_id = signer.validator_id().await.unwrap();
|
||||
|
||||
// schema
|
||||
let signer_pub =
|
||||
<Ristretto as Ciphersuite>::read_G::<&[u8]>(&mut validator_id.as_slice()).unwrap();
|
||||
let validators = Arc::new(Validators::new(genesis, vec![(signer_pub, 1)]).unwrap());
|
||||
|
||||
(genesis, signer, validator_id, validators)
|
||||
}
|
||||
|
||||
pub async fn signed_from_data<N: Network>(
|
||||
signer: <N::SignatureScheme as SignatureScheme>::Signer,
|
||||
signer_id: N::ValidatorId,
|
||||
block_number: u64,
|
||||
round_number: u32,
|
||||
data: DataFor<N>,
|
||||
) -> SignedMessageFor<N> {
|
||||
let msg = Message {
|
||||
sender: signer_id,
|
||||
block: BlockNumber(block_number),
|
||||
round: RoundNumber(round_number),
|
||||
data,
|
||||
};
|
||||
let sig = signer.sign(&msg.encode()).await;
|
||||
SignedMessage { msg, sig }
|
||||
}
|
||||
|
||||
pub async fn random_evidence_tx<N: Network>(
|
||||
signer: <N::SignatureScheme as SignatureScheme>::Signer,
|
||||
b: N::Block,
|
||||
) -> TendermintTx {
|
||||
// Creates a TX with an invalid valid round number
|
||||
// TODO: Use a random failure reason
|
||||
let data = Data::Proposal(Some(RoundNumber(0)), b);
|
||||
let signer_id = signer.validator_id().await.unwrap();
|
||||
let signed = signed_from_data::<N>(signer, signer_id, 0, 0, data).await;
|
||||
TendermintTx::SlashEvidence((signed, None::<SignedMessageFor<N>>).encode())
|
||||
}
|
||||
|
||||
pub fn random_vote_tx<R: RngCore + CryptoRng>(rng: &mut R, genesis: [u8; 32]) -> TendermintTx {
|
||||
// private key
|
||||
let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut *rng));
|
||||
|
||||
// vote data
|
||||
let mut id = [0u8; 13];
|
||||
let mut target = [0u8; 32];
|
||||
rng.fill_bytes(&mut id);
|
||||
rng.fill_bytes(&mut target);
|
||||
|
||||
let mut tx = TendermintTx::SlashVote(SlashVote { id, target, sig: VoteSignature::default() });
|
||||
tx.sign(rng, genesis, &key);
|
||||
|
||||
tx
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ use blake2::{Digest, Blake2s256};
|
||||
use ciphersuite::{group::ff::Field, Ciphersuite, Ristretto};
|
||||
|
||||
use crate::{
|
||||
ReadWrite, Signed, Transaction, verify_transaction,
|
||||
ReadWrite,
|
||||
transaction::{Signed, Transaction, verify_transaction},
|
||||
tests::{random_signed, random_signed_transaction},
|
||||
};
|
||||
|
||||
|
||||
303
coordinator/tributary/src/tests/transaction/tendermint.rs
Normal file
303
coordinator/tributary/src/tests/transaction/tendermint.rs
Normal file
@@ -0,0 +1,303 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
use rand::{RngCore, rngs::OsRng};
|
||||
|
||||
use ciphersuite::{Ristretto, Ciphersuite, group::ff::Field};
|
||||
use schnorr::SchnorrSignature;
|
||||
|
||||
use scale::Encode;
|
||||
|
||||
use tendermint::{
|
||||
time::CanonicalInstant,
|
||||
round::RoundData,
|
||||
Data, SignedMessageFor, commit_msg,
|
||||
ext::{RoundNumber, Commit, Signer as SignerTrait},
|
||||
};
|
||||
|
||||
use serai_db::MemDb;
|
||||
|
||||
use crate::{
|
||||
ReadWrite,
|
||||
tendermint::{
|
||||
tx::{TendermintTx, verify_tendermint_tx},
|
||||
TendermintBlock, Signer, Validators, TendermintNetwork,
|
||||
},
|
||||
tests::{
|
||||
p2p::DummyP2p, SignedTransaction, new_genesis, random_evidence_tx, random_vote_tx,
|
||||
tendermint_meta, signed_from_data,
|
||||
},
|
||||
};
|
||||
|
||||
type N = TendermintNetwork<MemDb, SignedTransaction, DummyP2p>;
|
||||
|
||||
#[test]
|
||||
fn vote_tx() {
|
||||
let genesis = new_genesis();
|
||||
let mut tx = random_vote_tx(&mut OsRng, genesis);
|
||||
|
||||
let commit = |_: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
let validators = Arc::new(Validators::new(genesis, vec![]).unwrap());
|
||||
|
||||
// should pass
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap();
|
||||
|
||||
if let TendermintTx::SlashVote(vote) = &mut tx {
|
||||
vote.sig.signature = SchnorrSignature::read(&mut [0; 64].as_slice()).unwrap();
|
||||
} else {
|
||||
panic!("SlashVote TX wasn't SlashVote");
|
||||
}
|
||||
|
||||
// should fail
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators, commit).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn serialize_tendermint() {
|
||||
// make a tendermint tx with random evidence
|
||||
let (genesis, signer, _, _) = tendermint_meta().await;
|
||||
let tx = random_evidence_tx::<N>(signer.into(), TendermintBlock(vec![])).await;
|
||||
let res = TendermintTx::read::<&[u8]>(&mut tx.serialize().as_ref()).unwrap();
|
||||
assert_eq!(res, tx);
|
||||
|
||||
// with vote tx
|
||||
let vote_tx = random_vote_tx(&mut OsRng, genesis);
|
||||
let vote_res = TendermintTx::read::<&[u8]>(&mut vote_tx.serialize().as_ref()).unwrap();
|
||||
assert_eq!(vote_res, vote_tx);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_valid_round() {
|
||||
// signer
|
||||
let (genesis, signer, signer_id, validators) = tendermint_meta().await;
|
||||
let commit = |_: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
|
||||
let valid_round_tx = |valid_round| {
|
||||
let signer = signer.clone();
|
||||
async move {
|
||||
let data = Data::Proposal(valid_round, TendermintBlock(vec![]));
|
||||
let signed = signed_from_data::<N>(signer.clone().into(), signer_id, 0, 0, data).await;
|
||||
(signed.clone(), TendermintTx::SlashEvidence((signed, None::<SignedMessageFor<N>>).encode()))
|
||||
}
|
||||
};
|
||||
|
||||
// This should be invalid evidence if a valid valid round is specified
|
||||
let (_, tx) = valid_round_tx(None).await;
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).is_err());
|
||||
|
||||
// If an invalid valid round is specified (>= current), this should be invalid evidence
|
||||
let (mut signed, tx) = valid_round_tx(Some(RoundNumber(0))).await;
|
||||
|
||||
// should pass
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap();
|
||||
|
||||
// change the signature
|
||||
let mut random_sig = [0u8; 64];
|
||||
OsRng.fill_bytes(&mut random_sig);
|
||||
signed.sig = random_sig;
|
||||
let tx = TendermintTx::SlashEvidence((signed.clone(), None::<SignedMessageFor<N>>).encode());
|
||||
|
||||
// should fail
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators, commit).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_precommit_signature() {
|
||||
let (genesis, signer, signer_id, validators) = tendermint_meta().await;
|
||||
let commit = |i: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
assert_eq!(i, 0);
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
|
||||
let precommit = |precommit| {
|
||||
let signer = signer.clone();
|
||||
async move {
|
||||
let signed =
|
||||
signed_from_data::<N>(signer.clone().into(), signer_id, 1, 0, Data::Precommit(precommit))
|
||||
.await;
|
||||
(signed.clone(), TendermintTx::SlashEvidence((signed, None::<SignedMessageFor<N>>).encode()))
|
||||
}
|
||||
};
|
||||
|
||||
// Empty Precommit should fail.
|
||||
assert!(verify_tendermint_tx::<N>(&precommit(None).await.1, genesis, validators.clone(), commit)
|
||||
.is_err());
|
||||
|
||||
// valid precommit signature should fail.
|
||||
let block_id = [0x22u8; 32];
|
||||
let last_end_time =
|
||||
RoundData::<N>::new(RoundNumber(0), CanonicalInstant::new(commit(0).unwrap().end_time))
|
||||
.end_time();
|
||||
let commit_msg = commit_msg(last_end_time.canonical(), block_id.as_ref());
|
||||
|
||||
assert!(verify_tendermint_tx::<N>(
|
||||
&precommit(Some((block_id, signer.clone().sign(&commit_msg).await))).await.1,
|
||||
genesis,
|
||||
validators.clone(),
|
||||
commit
|
||||
)
|
||||
.is_err());
|
||||
|
||||
// any other signature can be used as evidence.
|
||||
{
|
||||
let (mut signed, tx) = precommit(Some((block_id, signer.sign(&[]).await))).await;
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap();
|
||||
|
||||
// So long as we can authenticate where it came from
|
||||
let mut random_sig = [0u8; 64];
|
||||
OsRng.fill_bytes(&mut random_sig);
|
||||
signed.sig = random_sig;
|
||||
let tx = TendermintTx::SlashEvidence((signed.clone(), None::<SignedMessageFor<N>>).encode());
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators, commit).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn evidence_with_prevote() {
|
||||
let (genesis, signer, signer_id, validators) = tendermint_meta().await;
|
||||
let commit = |_: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
|
||||
let prevote = |block_id| {
|
||||
let signer = signer.clone();
|
||||
async move {
|
||||
TendermintTx::SlashEvidence(
|
||||
(
|
||||
signed_from_data::<N>(signer.clone().into(), signer_id, 0, 0, Data::Prevote(block_id))
|
||||
.await,
|
||||
None::<SignedMessageFor<N>>,
|
||||
)
|
||||
.encode(),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
// No prevote message should be valid as slash evidence at this time
|
||||
for prevote in [prevote(None).await, prevote(Some([0x22u8; 32])).await] {
|
||||
assert!(verify_tendermint_tx::<N>(&prevote, genesis, validators.clone(), commit).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn conflicting_msgs_evidence_tx() {
|
||||
let (genesis, signer, signer_id, validators) = tendermint_meta().await;
|
||||
let commit = |i: u32| -> Option<Commit<Arc<Validators>>> {
|
||||
assert_eq!(i, 0);
|
||||
Some(Commit::<Arc<Validators>> { end_time: 0, validators: vec![], signature: vec![] })
|
||||
};
|
||||
|
||||
// Block b, round n
|
||||
let signed_for_b_r = |block, round, data| {
|
||||
let signer = signer.clone();
|
||||
async move { signed_from_data::<N>(signer.clone().into(), signer_id, block, round, data).await }
|
||||
};
|
||||
|
||||
// Proposal
|
||||
{
|
||||
// non-conflicting data should fail
|
||||
let signed_1 = signed_for_b_r(0, 0, Data::Proposal(None, TendermintBlock(vec![0x11]))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(&signed_1)).encode());
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).is_err());
|
||||
|
||||
// conflicting data should pass
|
||||
let signed_2 = signed_for_b_r(0, 0, Data::Proposal(None, TendermintBlock(vec![0x22]))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(signed_2)).encode());
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap();
|
||||
|
||||
// Except if it has a distinct round number, as we don't check cross-round conflicts
|
||||
// (except for Precommit)
|
||||
let signed_2 = signed_for_b_r(0, 1, Data::Proposal(None, TendermintBlock(vec![0x22]))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(signed_2)).encode());
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap_err();
|
||||
|
||||
// Proposals for different block numbers should also fail as evidence
|
||||
let signed_2 = signed_for_b_r(1, 0, Data::Proposal(None, TendermintBlock(vec![0x22]))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(signed_2)).encode());
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap_err();
|
||||
}
|
||||
|
||||
// Prevote
|
||||
{
|
||||
// non-conflicting data should fail
|
||||
let signed_1 = signed_for_b_r(0, 0, Data::Prevote(Some([0x11; 32]))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(&signed_1)).encode());
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).is_err());
|
||||
|
||||
// conflicting data should pass
|
||||
let signed_2 = signed_for_b_r(0, 0, Data::Prevote(Some([0x22; 32]))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(signed_2)).encode());
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap();
|
||||
|
||||
// Except if it has a distinct round number, as we don't check cross-round conflicts
|
||||
// (except for Precommit)
|
||||
let signed_2 = signed_for_b_r(0, 1, Data::Prevote(Some([0x22; 32]))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(signed_2)).encode());
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap_err();
|
||||
|
||||
// Proposals for different block numbers should also fail as evidence
|
||||
let signed_2 = signed_for_b_r(1, 0, Data::Prevote(Some([0x22; 32]))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(signed_2)).encode());
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap_err();
|
||||
}
|
||||
|
||||
// Precommit
|
||||
{
|
||||
let sig = signer.sign(&[]).await; // the inner signature doesn't matter
|
||||
|
||||
let signed_1 = signed_for_b_r(0, 0, Data::Precommit(Some(([0x11; 32], sig)))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(&signed_1)).encode());
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).is_err());
|
||||
|
||||
// For precommit, the round number is ignored
|
||||
let signed_2 = signed_for_b_r(0, 1, Data::Precommit(Some(([0x22; 32], sig)))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(signed_2)).encode());
|
||||
verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).unwrap();
|
||||
|
||||
// Yet the block number isn't
|
||||
let signed_2 = signed_for_b_r(1, 0, Data::Precommit(Some(([0x22; 32], sig)))).await;
|
||||
let tx = TendermintTx::SlashEvidence((&signed_1, Some(signed_2)).encode());
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).is_err());
|
||||
}
|
||||
|
||||
// msgs from different senders should fail
|
||||
{
|
||||
let signed_1 = signed_for_b_r(0, 0, Data::Proposal(None, TendermintBlock(vec![0x11]))).await;
|
||||
|
||||
let signer_2 =
|
||||
Signer::new(genesis, Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng)));
|
||||
let signed_id_2 = signer_2.validator_id().await.unwrap();
|
||||
let signed_2 = signed_from_data::<N>(
|
||||
signer_2.into(),
|
||||
signed_id_2,
|
||||
0,
|
||||
0,
|
||||
Data::Proposal(None, TendermintBlock(vec![0x22])),
|
||||
)
|
||||
.await;
|
||||
|
||||
let tx = TendermintTx::SlashEvidence((signed_1, Some(signed_2)).encode());
|
||||
|
||||
// update schema so that we don't fail due to invalid signature
|
||||
let signer_pub =
|
||||
<Ristretto as Ciphersuite>::read_G::<&[u8]>(&mut signer_id.as_slice()).unwrap();
|
||||
let signer_pub_2 =
|
||||
<Ristretto as Ciphersuite>::read_G::<&[u8]>(&mut signed_id_2.as_slice()).unwrap();
|
||||
let validators =
|
||||
Arc::new(Validators::new(genesis, vec![(signer_pub, 1), (signer_pub_2, 1)]).unwrap());
|
||||
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators, commit).is_err());
|
||||
}
|
||||
|
||||
// msgs with different steps should fail
|
||||
{
|
||||
let signed_1 = signed_for_b_r(0, 0, Data::Proposal(None, TendermintBlock(vec![]))).await;
|
||||
let signed_2 = signed_for_b_r(0, 0, Data::Prevote(None)).await;
|
||||
let tx = TendermintTx::SlashEvidence((signed_1, Some(signed_2)).encode());
|
||||
assert!(verify_tendermint_tx::<N>(&tx, genesis, validators.clone(), commit).is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user