Skip to content

Commit b155e53

Browse files
drcpu-githubaesedepece
authored andcommitted
feat(node): always solve data requests included in a pre-wit/2 block using pre-wit/2 logic
1 parent ecce698 commit b155e53

File tree

6 files changed

+156
-161
lines changed

6 files changed

+156
-161
lines changed

data_structures/src/chain/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4836,6 +4836,7 @@ pub enum SignaturesToVerify {
48364836
dr_hash: Hash,
48374837
target_hash: Hash,
48384838
withdrawer: Option<PublicKeyHash>,
4839+
inclusion_epoch: Option<Epoch>,
48394840
},
48404841
VrfBlock {
48414842
proof: BlockEligibilityClaim,

node/src/actors/chain_manager/mining.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,6 @@ impl ChainManager {
320320
.unwrap_or_default();
321321
// Retrieve the withdrawer address of the first stake entry in which we are the validator
322322
let first_withdrawer_address = stake_entries.first().map(|stake| stake.key.withdrawer);
323-
let protocol_version = get_protocol_version(self.current_epoch);
324323
let mut available_stake = totalize_stakes(stake_entries).unwrap_or_default();
325324

326325
// Data Request mining
@@ -358,14 +357,18 @@ impl ChainManager {
358357
.data_request_state(&dr_pointer)
359358
.map(|dr_state| (dr_pointer, dr_state.clone()))
360359
}) {
360+
// The protocol version under which a data request needs to be resolved is decided
361+
// based on the epoch of the block in which the data request was included.
362+
let protocol_version = get_protocol_version(Some(dr_state.epoch));
363+
361364
// It's possible a data request requesting too many witnesses are in our local data
362365
// request pool (e.g., when we failed to validate a proposed block). Do not attempt
363366
// to solve this data request.
364367
let validator_count = self.chain_state.stakes.validator_count();
365368
if data_request_has_too_many_witnesses(
366369
&dr_state.data_request,
367370
validator_count,
368-
Some(current_epoch),
371+
Some(dr_state.epoch),
369372
) {
370373
continue;
371374
}
@@ -846,7 +849,7 @@ impl ChainManager {
846849
let too_many_witnesses = data_request_has_too_many_witnesses(
847850
&dr_state.data_request,
848851
validator_count,
849-
Some(block_epoch),
852+
Some(dr_state.epoch),
850853
);
851854

852855
// The result of `RunTally` will be published as tally
@@ -883,7 +886,7 @@ impl ChainManager {
883886
collateral_minimum,
884887
tally_bytes_on_encode_error(),
885888
&active_wips_inside_move,
886-
get_protocol_version(Some(block_epoch)),
889+
get_protocol_version(Some(dr_state.epoch)),
887890
);
888891

889892
log::info!(
@@ -1381,7 +1384,7 @@ mod tests {
13811384
PublicKey as Secp256k1_PublicKey, SecretKey as Secp256k1_SecretKey,
13821385
};
13831386
use witnet_crypto::signature::{sign, verify};
1384-
use witnet_data_structures::{chain::*, strum::IntoEnumIterator, transaction::*, vrf::VrfCtx};
1387+
use witnet_data_structures::{chain::*, transaction::*, vrf::VrfCtx};
13851388
use witnet_protected::Protected;
13861389
use witnet_validations::validations::validate_block_signature;
13871390

@@ -1555,9 +1558,7 @@ mod tests {
15551558
let mut signatures_to_verify = vec![];
15561559
assert!(validate_block_signature(&block, &mut signatures_to_verify).is_ok());
15571560

1558-
for protocol in ProtocolVersion::iter() {
1559-
assert!(verify_signatures(signatures_to_verify.clone(), vrf, protocol).is_ok());
1560-
}
1561+
assert!(verify_signatures(signatures_to_verify.clone(), vrf).is_ok());
15611562
}
15621563

15631564
static MILLION_TX_OUTPUT: &str =

node/src/actors/chain_manager/mod.rs

Lines changed: 86 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1348,7 +1348,6 @@ impl ChainManager {
13481348

13491349
fn add_temp_superblock_votes(&mut self, ctx: &mut Context<Self>) {
13501350
let consensus_constants = self.consensus_constants();
1351-
let protocol = ProtocolVersion::from_epoch_opt(self.current_epoch);
13521351

13531352
let superblock_period = u32::from(consensus_constants.superblock_period);
13541353

@@ -1360,12 +1359,9 @@ impl ChainManager {
13601359
}
13611360

13621361
// Validate secp256k1 signature
1363-
signature_mngr::verify_signatures(
1364-
vec![SignaturesToVerify::SuperBlockVote {
1365-
superblock_vote: superblock_vote.clone(),
1366-
}],
1367-
protocol,
1368-
)
1362+
signature_mngr::verify_signatures(vec![SignaturesToVerify::SuperBlockVote {
1363+
superblock_vote: superblock_vote.clone(),
1364+
}])
13691365
.map(|res| {
13701366
res.map_err(|e| {
13711367
log::error!("Verify superblock vote signature: {}", e);
@@ -1396,7 +1392,6 @@ impl ChainManager {
13961392
self.sm_state
13971393
);
13981394
let consensus_constants = self.consensus_constants();
1399-
let protocol = ProtocolVersion::from_epoch_opt(self.current_epoch);
14001395

14011396
let superblock_period = u32::from(consensus_constants.superblock_period);
14021397

@@ -1410,12 +1405,9 @@ impl ChainManager {
14101405
}
14111406

14121407
// Validate secp256k1 signature
1413-
signature_mngr::verify_signatures(
1414-
vec![SignaturesToVerify::SuperBlockVote {
1415-
superblock_vote: superblock_vote.clone(),
1416-
}],
1417-
protocol,
1418-
)
1408+
signature_mngr::verify_signatures(vec![SignaturesToVerify::SuperBlockVote {
1409+
superblock_vote: superblock_vote.clone(),
1410+
}])
14191411
.into_actor(self)
14201412
.map_err(|e, _act, _ctx| {
14211413
log::error!("Verify superblock vote signature: {}", e);
@@ -1578,7 +1570,24 @@ impl ChainManager {
15781570
// than or equal to the current epoch
15791571
block_epoch: current_epoch,
15801572
};
1581-
let protocol_version = ProtocolVersion::from_epoch(current_epoch);
1573+
// For commit transactions, we want to verify their validity using the protocol version at
1574+
// the time of the data request inclusion. For simplicity's sake when validating signatures,
1575+
// we use the protocol version of the block epoch.
1576+
// For all other transactions which can pass through the add_transaction function and which
1577+
// need the protocol version, we can always use the protocol version of the block epoch.
1578+
let protocol_version = if let Transaction::Commit(co_tx) = &msg.transaction {
1579+
if let Some(dr_state) = self
1580+
.chain_state
1581+
.data_request_pool
1582+
.data_request_state(&co_tx.body.dr_pointer)
1583+
{
1584+
ProtocolVersion::from_epoch(dr_state.epoch)
1585+
} else {
1586+
ProtocolVersion::from_epoch(current_epoch)
1587+
}
1588+
} else {
1589+
ProtocolVersion::from_epoch(current_epoch)
1590+
};
15821591
let collateral_age = self
15831592
.consensus_constants_wit2
15841593
.get_collateral_age(&active_wips);
@@ -1612,7 +1621,7 @@ impl ChainManager {
16121621
))
16131622
.into_actor(self)
16141623
.and_then(move |fee, act, _ctx| {
1615-
signature_mngr::verify_signatures(signatures_to_verify, protocol_version)
1624+
signature_mngr::verify_signatures(signatures_to_verify)
16161625
.map(move |res| res.map(|()| fee))
16171626
.into_actor(act)
16181627
})
@@ -2147,7 +2156,7 @@ impl ChainManager {
21472156
// Short-circuit if validation failed
21482157
res?;
21492158

2150-
signature_mngr::verify_signatures(signatures_to_verify, protocol_version).await
2159+
signature_mngr::verify_signatures(signatures_to_verify).await
21512160
}
21522161
.into_actor(self)
21532162
.and_then(move |(), act, _ctx| {
@@ -2166,13 +2175,12 @@ impl ChainManager {
21662175
&active_wips,
21672176
None,
21682177
&act.chain_state.stakes,
2169-
protocol_version,
21702178
);
21712179
async move {
21722180
// Short-circuit if validation failed
21732181
let diff = res?;
21742182

2175-
signature_mngr::verify_signatures(signatures_to_verify, protocol_version)
2183+
signature_mngr::verify_signatures(signatures_to_verify)
21762184
.await
21772185
.map(|()| diff)
21782186
}
@@ -2935,7 +2943,7 @@ pub fn process_validations(
29352943
replication_factor,
29362944
)?;
29372945
log::trace!("Verifying {} block signatures", signatures_to_verify.len());
2938-
verify_signatures(signatures_to_verify, vrf_ctx, protocol_version)?;
2946+
verify_signatures(signatures_to_verify, vrf_ctx)?;
29392947
}
29402948

29412949
let mut signatures_to_verify = vec![];
@@ -2953,15 +2961,14 @@ pub fn process_validations(
29532961
active_wips,
29542962
transaction_visitor,
29552963
stakes,
2956-
protocol_version,
29572964
)?;
29582965

29592966
if !resynchronizing {
29602967
log::trace!(
29612968
"Verifying {} transaction signatures",
29622969
signatures_to_verify.len()
29632970
);
2964-
verify_signatures(signatures_to_verify, vrf_ctx, protocol_version)?;
2971+
verify_signatures(signatures_to_verify, vrf_ctx)?;
29652972
}
29662973

29672974
Ok(utxo_dif)
@@ -3044,6 +3051,10 @@ fn process_wit2_stakes_changes(
30443051

30453052
let mut total_commit_reward = 0;
30463053
for co_tx in &block.txns.commit_txns {
3054+
if data_request_is_pre_wit2(data_request_pool, &Transaction::Commit(co_tx.clone())) {
3055+
continue;
3056+
}
3057+
30473058
let commit_pkh = co_tx.body.proof.proof.pkh();
30483059
total_commit_reward +=
30493060
if let Some(dr_output) = data_request_pool.get_dr_output(&co_tx.body.dr_pointer) {
@@ -3081,6 +3092,10 @@ fn process_wit2_stakes_changes(
30813092
// Add reveal rewards
30823093
let mut total_reveal_reward = 0;
30833094
for re_tx in &block.txns.reveal_txns {
3095+
if data_request_is_pre_wit2(data_request_pool, &Transaction::Reveal(re_tx.clone())) {
3096+
continue;
3097+
}
3098+
30843099
total_reveal_reward +=
30853100
if let Some(dr_output) = data_request_pool.get_dr_output(&re_tx.body.dr_pointer) {
30863101
dr_output.commit_and_reveal_fee
@@ -3101,6 +3116,10 @@ fn process_wit2_stakes_changes(
31013116
}
31023117

31033118
for ta_tx in &block.txns.tally_txns {
3119+
if data_request_is_pre_wit2(data_request_pool, &Transaction::Tally(ta_tx.clone())) {
3120+
continue;
3121+
}
3122+
31043123
let (collateral, reward) =
31053124
if let Some(dr_output) = data_request_pool.get_dr_output(&ta_tx.dr_pointer) {
31063125
(dr_output.collateral, dr_output.witness_reward)
@@ -3194,6 +3213,10 @@ fn process_wit2_stakes_changes(
31943213

31953214
// Reset witnessing power
31963215
for co_tx in &block.txns.commit_txns {
3216+
if data_request_is_pre_wit2(data_request_pool, &Transaction::Commit(co_tx.clone())) {
3217+
continue;
3218+
}
3219+
31973220
let commit_pkh = co_tx.body.proof.proof.pkh();
31983221
log::debug!(
31993222
"Resetting witnessing age for {} to {}",
@@ -3209,6 +3232,10 @@ fn process_wit2_stakes_changes(
32093232
// Collateral was already reserved, so not returning it results in losing it
32103233
// Reset the age for witnessing power to 10 epochs in the future
32113234
for ta_tx in &block.txns.tally_txns {
3235+
if data_request_is_pre_wit2(data_request_pool, &Transaction::Tally(ta_tx.clone())) {
3236+
continue;
3237+
}
3238+
32123239
let liar_pkhs: Vec<PublicKeyHash> = ta_tx
32133240
.out_of_consensus
32143241
.iter()
@@ -3353,6 +3380,40 @@ fn update_pools(
33533380
rep_info
33543381
}
33553382

3383+
fn data_request_is_pre_wit2(
3384+
data_request_pool: &DataRequestPool,
3385+
transaction: &Transaction,
3386+
) -> bool {
3387+
// Data requests which were included in a block prior to the activation of wit/2 do
3388+
// not need to be processed using the wit/2 business logic.
3389+
match transaction {
3390+
Transaction::Commit(co_tx) => {
3391+
if let Some(dr_state) = data_request_pool.data_request_state(&co_tx.body.dr_pointer) {
3392+
if get_protocol_version(Some(dr_state.epoch)) < ProtocolVersion::V2_0 {
3393+
return true;
3394+
}
3395+
}
3396+
}
3397+
Transaction::Reveal(re_tx) => {
3398+
if let Some(dr_state) = data_request_pool.data_request_state(&re_tx.body.dr_pointer) {
3399+
if get_protocol_version(Some(dr_state.epoch)) < ProtocolVersion::V2_0 {
3400+
return true;
3401+
}
3402+
}
3403+
}
3404+
Transaction::Tally(ta_tx) => {
3405+
if let Some(dr_state) = data_request_pool.data_request_state(&ta_tx.dr_pointer) {
3406+
if get_protocol_version(Some(dr_state.epoch)) < ProtocolVersion::V2_0 {
3407+
return true;
3408+
}
3409+
}
3410+
}
3411+
_ => (),
3412+
}
3413+
3414+
false
3415+
}
3416+
33563417
fn separate_honest_errors_and_liars<K, I>(rep_info: I) -> (Vec<K>, Vec<K>, Vec<(K, u32)>)
33573418
where
33583419
I: IntoIterator<Item = (K, RequestResult)>,
@@ -4793,6 +4854,7 @@ mod tests {
47934854
}
47944855

47954856
// Build pools
4857+
let epoch = 200;
47964858
let mut data_request_pool = DataRequestPool::default();
47974859
let data_request_state = DataRequestState {
47984860
data_request: DataRequestOutput {
@@ -4810,6 +4872,7 @@ mod tests {
48104872
..Default::default()
48114873
},
48124874
stage: DataRequestStage::TALLY,
4875+
epoch,
48134876
..Default::default()
48144877
};
48154878
data_request_pool.data_request_pool =
@@ -4818,7 +4881,6 @@ mod tests {
48184881
let unspent_outputs_pool = UnspentOutputsPool::default();
48194882

48204883
// Test stake changes with a block with a tally with four honests
4821-
let epoch = 200;
48224884
let tally_transactions = vec![TallyTransaction::new(
48234885
Hash::from(vec![1; 32]), // dr_pointer
48244886
vec![], // tally
@@ -4827,7 +4889,7 @@ mod tests {
48274889
vec![], // error_committers
48284890
)];
48294891
let block_one_succesful_tally = build_block_with_tally_transactions(
4830-
epoch,
4892+
epoch + 3,
48314893
&mut data_request_pool,
48324894
tally_transactions,
48334895
&stakes,

node/src/signature_mngr.rs

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ use witnet_data_structures::{
2121
Bn256KeyedSignature, Bn256PublicKey, Bn256SecretKey, ExtendedSecretKey, Hash, Hashable,
2222
KeyedSignature, PublicKey, PublicKeyHash, SecretKey, Signature, SignaturesToVerify,
2323
},
24-
proto::versioning::ProtocolVersion,
2524
transaction::MemoizedHashable,
2625
vrf::{VrfCtx, VrfMessage, VrfProof},
2726
};
@@ -145,14 +144,9 @@ pub async fn vrf_prove(message: VrfMessage) -> Result<(VrfProof, Hash), failure:
145144
}
146145

147146
/// Verify signatures async
148-
pub async fn verify_signatures(
149-
message: Vec<SignaturesToVerify>,
150-
protocol: ProtocolVersion,
151-
) -> Result<(), failure::Error> {
147+
pub async fn verify_signatures(message: Vec<SignaturesToVerify>) -> Result<(), failure::Error> {
152148
let addr = SignatureManagerAdapter::from_registry();
153-
addr.send(VerifySignatures(message, protocol))
154-
.flatten_err()
155-
.await
149+
addr.send(VerifySignatures(message)).flatten_err().await
156150
}
157151

158152
#[derive(Debug, Default)]
@@ -194,7 +188,7 @@ struct GetBn256KeyPair;
194188

195189
struct VrfProve(VrfMessage);
196190

197-
struct VerifySignatures(Vec<SignaturesToVerify>, ProtocolVersion);
191+
struct VerifySignatures(Vec<SignaturesToVerify>);
198192

199193
async fn persist_master_key(master_key: ExtendedSK) -> Result<(), failure::Error> {
200194
let master_key = ExtendedSecretKey::from(master_key);
@@ -468,13 +462,8 @@ impl Handler<VrfProve> for SignatureManager {
468462
impl Handler<VerifySignatures> for SignatureManager {
469463
type Result = <VerifySignatures as Message>::Result;
470464

471-
fn handle(
472-
&mut self,
473-
VerifySignatures(signatures, protocol): VerifySignatures,
474-
_ctx: &mut Self::Context,
475-
) -> Self::Result {
476-
validations::verify_signatures(signatures, self.vrf_ctx.as_mut().unwrap(), protocol)
477-
.map(|_| ())
465+
fn handle(&mut self, msg: VerifySignatures, _ctx: &mut Self::Context) -> Self::Result {
466+
validations::verify_signatures(msg.0, self.vrf_ctx.as_mut().unwrap()).map(|_| ())
478467
}
479468
}
480469

0 commit comments

Comments
 (0)