Skip to content

Commit

Permalink
test(sdk): masternode voting SDK tests (#1893)
Browse files Browse the repository at this point in the history
  • Loading branch information
lklimek authored Jun 23, 2024
1 parent 966f29f commit 69134e4
Show file tree
Hide file tree
Showing 22 changed files with 1,446 additions and 92 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 23 additions & 8 deletions packages/rs-drive-proof-verifier/src/from_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,16 @@ impl TryFromRequest<GetContestedResourcesRequest> for VotePollsByDocumentTypeQue
index_name: req.index_name.clone(),
start_at_value: req
.start_at_value_info
.map(|i| (i.start_value, i.start_value_included)),
.map(|i| {
let (value, _): (Value, _) =
bincode::decode_from_slice(&i.start_value, BINCODE_CONFIG).map_err(
|e| Error::RequestError {
error: format!("cannot decode start value: {}", e),
},
)?;
Ok::<_, Error>((value, i.start_value_included))
})
.transpose()?,
start_index_values: bincode_decode_values(req.start_index_values.iter())?,
end_index_values: bincode_decode_values(req.end_index_values.iter())?,
limit: req.count.map(|v| v as u16),
Expand All @@ -320,14 +329,20 @@ impl TryFromRequest<GetContestedResourcesRequest> for VotePollsByDocumentTypeQue
start_index_values: bincode_encode_values(&self.start_index_values)?,
index_name: self.index_name.clone(),
order_ascending: self.order_ascending,
start_at_value_info: self.start_at_value.as_ref().map(
|(start_value, start_value_included)| {
get_contested_resources_request_v0::StartAtValueInfo {
start_value: start_value.clone(),
start_at_value_info: self
.start_at_value
.as_ref()
.map(|(start_value, start_value_included)| {
Ok::<_, Error>(get_contested_resources_request_v0::StartAtValueInfo {
start_value: bincode::encode_to_vec(start_value, BINCODE_CONFIG).map_err(
|e| Error::RequestError {
error: format!("cannot encode start value: {}", e),
},
)?,
start_value_included: *start_value_included,
}
},
),
})
})
.transpose()?,
}
.into())
}
Expand Down
2 changes: 1 addition & 1 deletion packages/rs-drive-proof-verifier/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ mod provider;
pub mod types;
mod verify;
pub use error::Error;
pub use proof::FromProof;
pub use proof::{FromProof, Length};
pub use provider::ContextProvider;
#[cfg(feature = "mocks")]
pub use provider::MockContextProvider;
Expand Down
32 changes: 28 additions & 4 deletions packages/rs-drive-proof-verifier/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub type DataContracts = RetrievedObjects<Identifier, DataContract>;
///
/// Mapping between the contenders identity IDs and their info.
/// If a contender is not found, it is represented as `None`.
#[derive(Default)]
#[derive(Default, Debug, Clone)]
#[cfg_attr(
feature = "mocks",
derive(Encode, Decode, PlatformSerialize, PlatformDeserialize,),
Expand Down Expand Up @@ -159,12 +159,36 @@ pub type IdentityBalance = u64;
pub type IdentityBalanceAndRevision = (u64, Revision);

/// Contested resource values.
#[derive(Debug, derive_more::From, Clone)]
#[derive(Debug, derive_more::From, Clone, PartialEq)]
pub enum ContestedResource {
/// Generic [Value]
Value(Value),
}

impl ContestedResource {
/// Get the value.
pub fn encode_to_vec(
&self,
platform_version: &PlatformVersion,
) -> Result<Vec<u8>, bincode::error::EncodeError> {
platform_serialization::platform_encode_to_vec(
self,
bincode::config::standard(),
platform_version,
)
}
}

impl TryInto<Value> for ContestedResource {
type Error = crate::Error;

fn try_into(self) -> Result<Value, Self::Error> {
match self {
ContestedResource::Value(value) => Ok(value),
}
}
}

#[cfg(feature = "mocks")]
impl PlatformVersionEncode for ContestedResource {
fn platform_encode<E: bincode::enc::Encoder>(
Expand All @@ -173,7 +197,7 @@ impl PlatformVersionEncode for ContestedResource {
_platform_version: &platform_version::PlatformVersion,
) -> Result<(), bincode::error::EncodeError> {
match self {
ContestedResource::Value(document) => document.encode(encoder),
ContestedResource::Value(value) => value.encode(encoder),
}
}
}
Expand Down Expand Up @@ -248,7 +272,7 @@ pub type ResourceVotesByIdentity = RetrievedObjects<Identifier, ResourceVote>;
derive(Encode, Decode, PlatformSerialize, PlatformDeserialize),
platform_serialize(unversioned)
)]
pub struct PrefundedSpecializedBalance(Credits);
pub struct PrefundedSpecializedBalance(pub Credits);
impl PrefundedSpecializedBalance {
/// Get the balance.
pub fn to_credits(&self) -> Credits {
Expand Down
1 change: 1 addition & 0 deletions packages/rs-sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ data-contracts = { path = "../data-contracts" }
tokio-test = { version = "0.4.4" }
clap = { version = "4.5.4", features = ["derive"] }
sanitize-filename = { version = "0.5.0" }
chrono = { version = "0.4.38" }

[features]
default = ["mocks", "offline-testing"]
Expand Down
26 changes: 25 additions & 1 deletion packages/rs-sdk/src/core_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@

use dashcore_rpc::{
dashcore::{hashes::Hash, Amount, QuorumHash},
dashcore_rpc_json as json, Auth, Client, RpcApi,
dashcore_rpc_json as json,
json::{ProTxList, ProTxListType},
Auth, Client, RpcApi,
};
use dpp::dashcore::ProTxHash;
use drive_proof_verifier::error::ContextProviderError;
use std::{fmt::Debug, sync::Mutex};

Expand Down Expand Up @@ -126,4 +129,25 @@ impl CoreClient {
})?;
Ok(pubkey)
}

/// Require list of validators from Core.
///
/// See also [Dash Core documentation](https://docs.dash.org/projects/core/en/stable/docs/api/remote-procedure-calls-evo.html#protx-list)
#[allow(unused)]
pub fn protx_list(
&self,
height: Option<u32>,
protx_type: Option<ProTxListType>,
) -> Result<Vec<ProTxHash>, Error> {
let core = self.core.lock().expect("Core lock poisoned");

let pro_tx_hashes =
core.get_protx_list(protx_type, Some(false), height)
.map(|x| match x {
ProTxList::Hex(hex) => hex,
ProTxList::Info(info) => info.into_iter().map(|v| v.pro_tx_hash).collect(),
})?;

Ok(pro_tx_hashes)
}
}
2 changes: 1 addition & 1 deletion packages/rs-sdk/src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ pub use {
document_query::DocumentQuery,
fetch::Fetch,
fetch_many::FetchMany,
query::{LimitQuery, Query, DEFAULT_EPOCH_QUERY_LIMIT},
query::{LimitQuery, Query, QueryStartInfo, DEFAULT_EPOCH_QUERY_LIMIT},
};
105 changes: 105 additions & 0 deletions packages/rs-sdk/src/platform/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
//! [Query] trait is used to specify individual objects as well as search criteria for fetching multiple objects from the platform.
use dapi_grpc::mock::Mockable;
use dapi_grpc::platform::v0::get_contested_resource_identity_votes_request::GetContestedResourceIdentityVotesRequestV0;
use dapi_grpc::platform::v0::get_contested_resource_voters_for_identity_request::GetContestedResourceVotersForIdentityRequestV0;
use dapi_grpc::platform::v0::get_contested_resources_request::GetContestedResourcesRequestV0;
use dapi_grpc::platform::v0::{
self as proto, get_identity_keys_request, get_identity_keys_request::GetIdentityKeysRequestV0,
AllKeys, GetContestedResourceVoteStateRequest, GetContestedResourceVotersForIdentityRequest,
Expand All @@ -15,6 +17,7 @@ use dapi_grpc::platform::v0::{
GetVotePollsByEndDateRequest,
};
use dashcore_rpc::dashcore::{hashes::Hash, ProTxHash};
use dpp::version::PlatformVersionError;
use dpp::{block::epoch::EpochIndex, prelude::Identifier};
use drive::query::contested_resource_votes_given_by_identity_query::ContestedResourceVotesGivenByIdentityQuery;
use drive::query::vote_poll_contestant_votes_query::ContestedDocumentVotePollVotesDriveQuery;
Expand Down Expand Up @@ -317,6 +320,34 @@ impl Query<GetContestedResourcesRequest> for VotePollsByDocumentTypeQuery {
}
}

impl Query<GetContestedResourcesRequest> for LimitQuery<GetContestedResourcesRequest> {
fn query(self, prove: bool) -> Result<GetContestedResourcesRequest, Error> {
use proto::get_contested_resources_request::{
get_contested_resources_request_v0::StartAtValueInfo, Version,
};
let query = match self.query.query(prove)?.version {
Some(Version::V0(v0)) => GetContestedResourcesRequestV0 {
start_at_value_info: self.start_info.map(|v| StartAtValueInfo {
start_value: v.start_key,
start_value_included: v.start_included,
}),
..v0
}
.into(),
None => {
return Err(Error::Protocol(
PlatformVersionError::UnknownVersionError(
"version not present in request".into(),
)
.into(),
))
}
};

Ok(query)
}
}

impl Query<GetContestedResourceVoteStateRequest> for ContestedDocumentVotePollDriveQuery {
fn query(self, prove: bool) -> Result<GetContestedResourceVoteStateRequest, Error> {
if !prove {
Expand All @@ -330,6 +361,33 @@ impl Query<GetContestedResourceVoteStateRequest> for ContestedDocumentVotePollDr
}
}

impl Query<GetContestedResourceVoteStateRequest>
for LimitQuery<ContestedDocumentVotePollDriveQuery>
{
fn query(self, prove: bool) -> Result<GetContestedResourceVoteStateRequest, Error> {
use proto::get_contested_resource_vote_state_request::get_contested_resource_vote_state_request_v0::StartAtIdentifierInfo;
if !prove {
unimplemented!("queries without proofs are not supported yet");
}
let result = match self.query.query(prove)?.version {
Some(proto::get_contested_resource_vote_state_request::Version::V0(v0)) =>
proto::get_contested_resource_vote_state_request::GetContestedResourceVoteStateRequestV0 {
start_at_identifier_info: self.start_info.map(|v| StartAtIdentifierInfo {
start_identifier: v.start_key,
start_identifier_included: v.start_included,
}),
..v0
}.into(),

None =>return Err(Error::Protocol(
PlatformVersionError::UnknownVersionError("version not present in request".into()).into(),
)),
};

Ok(result)
}
}

impl Query<GetContestedResourceVotersForIdentityRequest>
for ContestedDocumentVotePollVotesDriveQuery
{
Expand All @@ -345,6 +403,36 @@ impl Query<GetContestedResourceVotersForIdentityRequest>
}
}

impl Query<GetContestedResourceVotersForIdentityRequest>
for LimitQuery<GetContestedResourceVotersForIdentityRequest>
{
fn query(self, prove: bool) -> Result<GetContestedResourceVotersForIdentityRequest, Error> {
use proto::get_contested_resource_voters_for_identity_request::{
get_contested_resource_voters_for_identity_request_v0::StartAtIdentifierInfo, Version,
};
let query = match self.query.query(prove)?.version {
Some(Version::V0(v0)) => GetContestedResourceVotersForIdentityRequestV0 {
start_at_identifier_info: self.start_info.map(|v| StartAtIdentifierInfo {
start_identifier: v.start_key,
start_identifier_included: v.start_included,
}),
..v0
}
.into(),
None => {
return Err(Error::Protocol(
PlatformVersionError::UnknownVersionError(
"version not present in request".into(),
)
.into(),
))
}
};

Ok(query)
}
}

impl Query<GetContestedResourceIdentityVotesRequest>
for ContestedResourceVotesGivenByIdentityQuery
{
Expand All @@ -360,6 +448,23 @@ impl Query<GetContestedResourceIdentityVotesRequest>
}
}

impl Query<GetContestedResourceIdentityVotesRequest> for ProTxHash {
fn query(self, prove: bool) -> Result<GetContestedResourceIdentityVotesRequest, Error> {
if !prove {
unimplemented!("queries without proofs are not supported yet");
}
Ok(GetContestedResourceIdentityVotesRequestV0 {
identity_id: self.to_byte_array().to_vec(),
prove,
limit: None,
offset: None,
order_ascending: true,
start_at_vote_poll_id_info: None,
}
.into())
}
}

impl Query<GetVotePollsByEndDateRequest> for VotePollsByEndDateDriveQuery {
fn query(self, prove: bool) -> Result<GetVotePollsByEndDateRequest, Error> {
if !prove {
Expand Down
2 changes: 1 addition & 1 deletion packages/rs-sdk/tests/fetch/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub fn mock_data_contract(
pub fn setup_logs() {
tracing_subscriber::fmt::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::new(
"info,dash_sdk=trace,drive_proof_verifier=trace,main=debug,h2=info",
"info,dash_sdk=trace,dash_sdk::platform::fetch=debug,drive_proof_verifier=debug,main=debug,h2=info",
))
.pretty()
.with_ansi(true)
Expand Down
Loading

0 comments on commit 69134e4

Please sign in to comment.