Skip to content

Implement ChangeParams #1535

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 77 additions & 4 deletions core/src/consensus/stake/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use ckey::Address;
use ckey::{Address, Signature};
use ctypes::CommonParams;
use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};

const ACTION_TAG_TRANSFER_CCS: u8 = 1;
const ACTION_TAG_DELEGATE_CCS: u8 = 2;
const ACTION_TAG_CHANGE_PARAMS: u8 = 0xFF;

#[derive(Debug)]
#[derive(Debug, PartialEq)]
pub enum Action {
TransferCCS {
address: Address,
Expand All @@ -30,6 +32,11 @@ pub enum Action {
address: Address,
quantity: u64,
},
ChangeParams {
metadata_seq: u64,
params: Box<CommonParams>,
signatures: Vec<Signature>,
},
}

impl Encodable for Action {
Expand All @@ -38,11 +45,28 @@ impl Encodable for Action {
Action::TransferCCS {
address,
quantity,
} => s.begin_list(3).append(&ACTION_TAG_TRANSFER_CCS).append(address).append(quantity),
} => {
s.begin_list(3).append(&ACTION_TAG_TRANSFER_CCS).append(address).append(quantity);
}
Action::DelegateCCS {
address,
quantity,
} => s.begin_list(3).append(&ACTION_TAG_DELEGATE_CCS).append(address).append(quantity),
} => {
s.begin_list(3).append(&ACTION_TAG_DELEGATE_CCS).append(address).append(quantity);
}
Action::ChangeParams {
metadata_seq,
params,
signatures,
} => {
s.begin_list(3 + signatures.len())
.append(&ACTION_TAG_CHANGE_PARAMS)
.append(metadata_seq)
.append(&**params);
for signature in signatures {
s.append(signature);
}
}
};
}
}
Expand Down Expand Up @@ -77,7 +101,56 @@ impl Decodable for Action {
quantity: rlp.val_at(2)?,
})
}
ACTION_TAG_CHANGE_PARAMS => {
let item_count = rlp.item_count()?;
if item_count < 4 {
return Err(DecoderError::RlpIncorrectListLen {
expected: 4,
got: item_count,
})
}
let metadata_seq = rlp.val_at(1)?;
let params = Box::new(rlp.val_at(2)?);
let signatures = (3..item_count).map(|i| rlp.val_at(i)).collect::<Result<_, _>>()?;
Ok(Action::ChangeParams {
metadata_seq,
params,
signatures,
})
}
_ => Err(DecoderError::Custom("Unexpected Tendermint Stake Action Type")),
}
}
}

#[cfg(test)]
mod tests {
use rlp::rlp_encode_and_decode_test;

use super::*;

#[test]
fn decode_fail_if_change_params_have_no_signatures() {
let action = Action::ChangeParams {
metadata_seq: 3,
params: CommonParams::default_for_test().into(),
signatures: vec![],
};
assert_eq!(
Err(DecoderError::RlpIncorrectListLen {
expected: 4,
got: 3,
}),
UntrustedRlp::new(&rlp::encode(&action)).as_val::<Action>()
);
}

#[test]
fn rlp_of_change_params() {
rlp_encode_and_decode_test!(Action::ChangeParams {
metadata_seq: 3,
params: CommonParams::default_for_test().into(),
signatures: vec![Signature::random(), Signature::random()],
});
}
}
77 changes: 73 additions & 4 deletions core/src/consensus/stake/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@ use std::collections::HashMap;
use std::ops::Deref;
use std::sync::Arc;

use ckey::Address;
use cstate::{ActionHandler, StateResult, TopLevelState};
use ccrypto::Blake;
use ckey::{public_to_address, recover, Address, Signature};
use cstate::{ActionHandler, StateResult, TopLevelState, TopState};
use ctypes::errors::{RuntimeError, SyntaxError};
use ctypes::util::unexpected::Mismatch;
use ctypes::{CommonParams, Header};
use primitives::H256;
use rlp::{Decodable, UntrustedRlp};

use self::action_data::{Delegation, StakeAccount, Stakeholders};
Expand Down Expand Up @@ -111,12 +114,44 @@ impl ActionHandler for Stake {
Err(RuntimeError::FailedToHandleCustomAction("DelegateCCS is disabled".to_string()).into())
}
}
Action::ChangeParams {
metadata_seq,
params,
signatures,
} => change_params(state, metadata_seq, *params, &signatures),
}
}

fn verify(&self, bytes: &[u8]) -> Result<(), SyntaxError> {
Action::decode(&UntrustedRlp::new(bytes)).map_err(|err| SyntaxError::InvalidCustomAction(err.to_string()))?;
Ok(())
let action = Action::decode(&UntrustedRlp::new(bytes))
.map_err(|err| SyntaxError::InvalidCustomAction(err.to_string()))?;
match action {
Action::TransferCCS {
..
} => Ok(()),
Action::DelegateCCS {
..
} => Ok(()),
Action::ChangeParams {
metadata_seq,
params,
signatures,
} => {
let action = Action::ChangeParams {
metadata_seq,
params,
signatures: vec![],
};
let encoded_action = H256::blake(rlp::encode(&action));
for signature in signatures {
// XXX: Signature recovery is an expensive job. Should we do it twice?
recover(&signature, &encoded_action).map_err(|err| {
SyntaxError::InvalidCustomAction(format!("Cannot decode the signature: {}", err))
})?;
}
Ok(())
}
}
}

fn on_close_block(
Expand Down Expand Up @@ -183,6 +218,40 @@ pub fn get_stakes(state: &TopLevelState) -> StateResult<HashMap<Address, u64>> {
Ok(result)
}

fn change_params(
state: &mut TopLevelState,
metadata_seq: u64,
params: CommonParams,
signatures: &[Signature],
) -> StateResult<()> {
// Update state first because the signature validation is more expensive.
state.update_params(metadata_seq, params)?;

let action = Action::ChangeParams {
metadata_seq,
params: params.into(),
signatures: vec![],
};
let encoded_action = H256::blake(rlp::encode(&action));
let stakes = get_stakes(state)?;
let signed_stakes = signatures.iter().try_fold(0, |sum, signature| {
let public = recover(signature, &encoded_action).unwrap_or_else(|err| {
unreachable!("The transaction with an invalid signature cannot pass the verification: {}", err);
});
let address = public_to_address(&public);
stakes.get(&address).map(|stake| sum + stake).ok_or_else(|| RuntimeError::SignatureOfInvalidAccount(address))
})?;
let total_stakes: u64 = stakes.values().sum();
if total_stakes / 2 >= signed_stakes {
return Err(RuntimeError::InsufficientStakes(Mismatch {
expected: total_stakes,
found: signed_stakes,
})
.into())
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::action_data::get_account_key;
Expand Down
1 change: 1 addition & 0 deletions spec/Staking.md
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ It also does not provide a voting feature.
The vote initiator should collect the signatures through the off-chain.

This transaction increases the `seq` of `Metadata` and changes the `params` of `Metadata`.
The changed parameters are applied from the next block that the changing transaction is included.

### Action
`[ 0xFF, metadata_seq, new_parameters, ...signatures ]`
Expand Down
17 changes: 16 additions & 1 deletion state/src/impls/top_level.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ use ctypes::transaction::{
Action, AssetOutPoint, AssetTransferInput, AssetWrapCCCOutput, ShardTransaction, Transaction,
};
use ctypes::util::unexpected::Mismatch;
use ctypes::{BlockNumber, ShardId};
use ctypes::{BlockNumber, CommonParams, ShardId};
use cvm::ChainTimeInfo;
use hashdb::AsHashDB;
use kvdb::DBTransaction;
Expand Down Expand Up @@ -989,6 +989,21 @@ impl TopState for TopLevelState {
fn remove_action_data(&mut self, key: &H256) {
self.top_cache.remove_action_data(key)
}

fn update_params(&mut self, metadata_seq: u64, params: CommonParams) -> StateResult<()> {
let mut metadata = self.get_metadata_mut()?;
if metadata.seq() != metadata_seq {
return Err(RuntimeError::InvalidSeq(Mismatch {
found: metadata_seq,
expected: metadata.seq(),
})
.into())
}

metadata.set_params(params);
metadata.increase_seq();
Ok(())
}
}

fn is_active_account(state: &TopStateView, address: &Address) -> TrieResult<bool> {
Expand Down
17 changes: 14 additions & 3 deletions state/src/item/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use ctypes::{CommonParams, ShardId};
use primitives::H256;
use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};

use ctypes::{CommonParams, ShardId};

use crate::CacheableItem;

#[derive(Clone, Debug, Default, PartialEq)]
Expand All @@ -33,7 +32,7 @@ pub struct Metadata {
number_of_initial_shards: ShardId,
hashes: Vec<H256>,
term: TermMetadata,
seq: usize,
seq: u64,
params: Option<CommonParams>,
}

Expand Down Expand Up @@ -78,10 +77,22 @@ impl Metadata {
})
}

pub fn seq(&self) -> u64 {
self.seq
}

pub fn increase_seq(&mut self) {
self.seq += 1;
}

pub fn params(&self) -> Option<&CommonParams> {
self.params.as_ref()
}

pub fn set_params(&mut self, params: CommonParams) {
self.params = Some(params);
}

pub fn change_term(&mut self, last_term_finished_block_num: u64, current_term_id: u64) {
assert!(self.term.last_term_finished_block_num < last_term_finished_block_num);
assert!(self.term.current_term_id < current_term_id);
Expand Down
4 changes: 3 additions & 1 deletion state/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use ckey::{public_to_address, Address, Public, Signature};
use cmerkle::Result as TrieResult;
use ctypes::transaction::ShardTransaction;
use ctypes::{BlockNumber, ShardId};
use ctypes::{BlockNumber, CommonParams, ShardId};
use cvm::ChainTimeInfo;
use primitives::{Bytes, H160, H256};

Expand Down Expand Up @@ -181,6 +181,8 @@ pub trait TopState {

fn update_action_data(&mut self, key: &H256, data: Bytes) -> StateResult<()>;
fn remove_action_data(&mut self, key: &H256);

fn update_params(&mut self, metadata_seq: u64, params: CommonParams) -> StateResult<()>;
}

pub trait StateWithCache {
Expand Down
Loading