Skip to content

Commit

Permalink
fix(sdk): small sdk improvements and fixes for v1.4 (#2200)
Browse files Browse the repository at this point in the history
  • Loading branch information
QuantumExplorer authored Oct 3, 2024
1 parent 5eacc13 commit 09d89f8
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 13 deletions.
3 changes: 2 additions & 1 deletion packages/rs-dpp/src/core_types/validator/v0/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use dashcore::{ProTxHash, PubkeyHash};
use std::fmt::{Debug, Formatter};
use std::fmt;

Check warning on line 2 in packages/rs-dpp/src/core_types/validator/v0/mod.rs

View workflow job for this annotation

GitHub Actions / Rust packages (dpp) / Linting

unused import: `std::fmt`

warning: unused import: `std::fmt` --> packages/rs-dpp/src/core_types/validator/v0/mod.rs:2:5 | 2 | use std::fmt; | ^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default

Check warning on line 2 in packages/rs-dpp/src/core_types/validator/v0/mod.rs

View workflow job for this annotation

GitHub Actions / Rust packages (dash-sdk) / Linting

unused import: `std::fmt`

warning: unused import: `std::fmt` --> packages/rs-dpp/src/core_types/validator/v0/mod.rs:2:5 | 2 | use std::fmt; | ^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default

Check warning on line 2 in packages/rs-dpp/src/core_types/validator/v0/mod.rs

View workflow job for this annotation

GitHub Actions / Rust packages (drive-abci) / Linting

unused import: `std::fmt`

warning: unused import: `std::fmt` --> packages/rs-dpp/src/core_types/validator/v0/mod.rs:2:5 | 2 | use std::fmt; | ^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default
use std::fmt::{Debug, Display, Formatter};

Check warning on line 3 in packages/rs-dpp/src/core_types/validator/v0/mod.rs

View workflow job for this annotation

GitHub Actions / Rust packages (dpp) / Linting

unused import: `Display`

warning: unused import: `Display` --> packages/rs-dpp/src/core_types/validator/v0/mod.rs:3:23 | 3 | use std::fmt::{Debug, Display, Formatter}; | ^^^^^^^

Check warning on line 3 in packages/rs-dpp/src/core_types/validator/v0/mod.rs

View workflow job for this annotation

GitHub Actions / Rust packages (dash-sdk) / Linting

unused import: `Display`

warning: unused import: `Display` --> packages/rs-dpp/src/core_types/validator/v0/mod.rs:3:23 | 3 | use std::fmt::{Debug, Display, Formatter}; | ^^^^^^^

Check warning on line 3 in packages/rs-dpp/src/core_types/validator/v0/mod.rs

View workflow job for this annotation

GitHub Actions / Rust packages (drive-abci) / Linting

unused import: `Display`

warning: unused import: `Display` --> packages/rs-dpp/src/core_types/validator/v0/mod.rs:3:23 | 3 | use std::fmt::{Debug, Display, Formatter}; | ^^^^^^^

use crate::bls_signatures::PublicKey as BlsPublicKey;
#[cfg(feature = "core-types-serde-conversion")]
Expand Down
9 changes: 9 additions & 0 deletions packages/rs-dpp/src/core_types/validator_set/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use platform_serialization_derive::{PlatformDeserialize, PlatformSerialize};
#[cfg(feature = "core-types-serde-conversion")]
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt::{Display, Formatter};

/// Version 0
pub mod v0;
Expand All @@ -34,6 +35,14 @@ pub enum ValidatorSet {
V0(ValidatorSetV0),
}

impl Display for ValidatorSet {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ValidatorSet::V0(v0) => write!(f, "{}", v0),
}
}
}

impl ValidatorSetV0Getters for ValidatorSet {
fn quorum_hash(&self) -> &QuorumHash {
match self {
Expand Down
33 changes: 32 additions & 1 deletion packages/rs-dpp/src/core_types/validator_set/v0/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ use bincode::error::EncodeError;
use bincode::{BorrowDecode, Decode, Encode};
use dashcore::hashes::Hash;
use dashcore::{ProTxHash, QuorumHash};
use itertools::Itertools;
#[cfg(feature = "core-types-serde-conversion")]
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt::{Debug, Formatter};
use std::fmt;
use std::fmt::{Debug, Display, Formatter};

/// The validator set is only slightly different from a quorum as it does not contain non valid
/// members
Expand All @@ -35,6 +37,35 @@ pub struct ValidatorSetV0 {
pub threshold_public_key: BlsPublicKey,
}

impl Display for ValidatorSetV0 {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"ValidatorSet {{
quorum_hash: {},
quorum_index: {},
core_height: {},
members: [{}],
threshold_public_key: {}
}}",
hex::encode(self.quorum_hash), // Assuming QuorumHash is a byte array and should be in hex format
match self.quorum_index {
Some(index) => index.to_string(),
None => "None".to_string(),
},
self.core_height,
self.members
.iter()
.map(|(pro_tx_hash, validator)| format!(
"{{{}: {}}}",
pro_tx_hash, validator.node_ip
))
.join(", "),
hex::encode(self.threshold_public_key.to_bytes().as_slice()) // Assuming BlsPublicKey is a byte array
)
}
}

#[cfg(feature = "core-types-serialization")]
impl Encode for ValidatorSetV0 {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
Expand Down
2 changes: 1 addition & 1 deletion packages/rs-drive-proof-verifier/src/unproved.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ impl FromUnproved<platform::GetCurrentQuorumsInfoRequest> for CurrentQuorumsInfo
pro_tx_hash,
public_key: None, // Assuming it's not provided here
node_ip: member.node_ip,
node_id: PubkeyHash::from_slice(&[0; 32]).unwrap(), // Placeholder, since not provided
node_id: PubkeyHash::from_slice(&[0; 20]).expect("expected to make pub key hash from 20 byte empty array"), // Placeholder, since not provided
core_port: 0, // Placeholder, since not provided
platform_http_port: 0, // Placeholder, since not provided
platform_p2p_port: 0, // Placeholder, since not provided
Expand Down
25 changes: 25 additions & 0 deletions packages/rs-sdk/src/mock/requests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::MockDashPlatformSdk;
use dpp::bincode::config::standard;
use dpp::{
bincode,
block::extended_epoch_info::ExtendedEpochInfo,
Expand All @@ -14,6 +15,7 @@ use dpp::{
},
voting::votes::{resource_vote::ResourceVote, Vote},
};
use drive::grovedb::Element;
use drive_proof_verifier::types::{
Contenders, ContestedResources, CurrentQuorumsInfo, ElementFetchRequestItem, EvoNodeStatus,
IdentityBalanceAndRevision, MasternodeProtocolVote, PrefundedSpecializedBalance,
Expand Down Expand Up @@ -165,6 +167,29 @@ impl MockResponse for Document {
}
}

impl MockResponse for Element {
fn mock_serialize(&self, _sdk: &MockDashPlatformSdk) -> Vec<u8> {
// Create a bincode configuration
let config = standard();

// Serialize using the specified configuration
bincode::encode_to_vec(self, config).expect("Failed to serialize Element")
}

fn mock_deserialize(_sdk: &MockDashPlatformSdk, buf: &[u8]) -> Self
where
Self: Sized,
{
// Create a bincode configuration
let config = standard();

// Deserialize using the specified configuration
bincode::decode_from_slice(buf, config)
.expect("Failed to deserialize Element")
.0
}
}

impl MockResponse for drive_proof_verifier::types::IdentityNonceFetcher {
fn mock_serialize(&self, _sdk: &MockDashPlatformSdk) -> Vec<u8> {
(self.0).to_be_bytes().to_vec()
Expand Down
26 changes: 20 additions & 6 deletions packages/rs-sdk/src/platform/fetch_many.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ use dapi_grpc::platform::v0::{
GetContestedResourceVotersForIdentityRequest, GetContestedResourcesRequest,
GetDataContractsRequest, GetDocumentsResponse, GetEpochsInfoRequest,
GetEvonodesProposedEpochBlocksByIdsRequest, GetEvonodesProposedEpochBlocksByRangeRequest,
GetIdentitiesBalancesRequest, GetIdentityKeysRequest, GetProtocolVersionUpgradeStateRequest,
GetProtocolVersionUpgradeVoteStatusRequest, GetVotePollsByEndDateRequest,
GetIdentitiesBalancesRequest, GetIdentityKeysRequest, GetPathElementsRequest,
GetProtocolVersionUpgradeStateRequest, GetProtocolVersionUpgradeVoteStatusRequest,
GetVotePollsByEndDateRequest,
};
use dashcore_rpc::dashcore::ProTxHash;
use dpp::data_contract::DataContract;
Expand All @@ -30,11 +31,14 @@ use dpp::{
block::extended_epoch_info::ExtendedEpochInfo, voting::votes::resource_vote::ResourceVote,
};
use dpp::{document::Document, voting::contender_structs::ContenderWithSerializedDocument};
use drive::grovedb::query_result_type::{Key, Path};
use drive::grovedb::Element;
use drive_proof_verifier::types::{
Contenders, ContestedResource, ContestedResources, DataContracts, ExtendedEpochInfos,
IdentityBalances, IdentityPublicKeys, MasternodeProtocolVote, MasternodeProtocolVotes,
ProposerBlockCountById, ProposerBlockCountByRange, ProposerBlockCounts,
ProtocolVersionUpgrades, ResourceVotesByIdentity, VotePollsGroupedByTimestamp, Voter, Voters,
Contenders, ContestedResource, ContestedResources, DataContracts, Elements, ExtendedEpochInfos,
IdentityBalances, IdentityPublicKeys, KeysInPath, MasternodeProtocolVote,
MasternodeProtocolVotes, ProposerBlockCountById, ProposerBlockCountByRange,
ProposerBlockCounts, ProtocolVersionUpgrades, ResourceVotesByIdentity,
VotePollsGroupedByTimestamp, Voter, Voters,
};
use drive_proof_verifier::{types::Documents, FromProof};
use rs_dapi_client::{transport::TransportRequest, DapiRequest, RequestSettings};
Expand Down Expand Up @@ -415,3 +419,13 @@ impl FetchMany<TimestampMillis, VotePollsGroupedByTimestamp> for VotePoll {
impl FetchMany<Identifier, IdentityBalances> for drive_proof_verifier::types::IdentityBalance {
type Request = GetIdentitiesBalancesRequest;
}

//
/// Fetch multiple elements.
///
/// ## Supported query types
///
/// * [KeysInPath]
impl FetchMany<Key, Elements> for Element {
type Request = GetPathElementsRequest;
}
28 changes: 24 additions & 4 deletions packages/rs-sdk/src/platform/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ 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::get_current_quorums_info_request::GetCurrentQuorumsInfoRequestV0;
use dapi_grpc::platform::v0::get_evonodes_proposed_epoch_blocks_by_range_request::GetEvonodesProposedEpochBlocksByRangeRequestV0;
use dapi_grpc::platform::v0::get_path_elements_request::GetPathElementsRequestV0;
use dapi_grpc::platform::v0::get_status_request::GetStatusRequestV0;
use dapi_grpc::platform::v0::get_total_credits_in_platform_request::GetTotalCreditsInPlatformRequestV0;
use dapi_grpc::platform::v0::{
self as proto, get_identity_keys_request, get_identity_keys_request::GetIdentityKeysRequestV0,
get_path_elements_request, get_total_credits_in_platform_request, AllKeys,
GetContestedResourceVoteStateRequest, GetContestedResourceVotersForIdentityRequest,
GetContestedResourcesRequest, GetEpochsInfoRequest,
self as proto, get_current_quorums_info_request, get_identity_keys_request,
get_identity_keys_request::GetIdentityKeysRequestV0, get_path_elements_request,
get_total_credits_in_platform_request, AllKeys, GetContestedResourceVoteStateRequest,
GetContestedResourceVotersForIdentityRequest, GetContestedResourcesRequest,
GetCurrentQuorumsInfoRequest, GetEpochsInfoRequest,
GetEvonodesProposedEpochBlocksByRangeRequest, GetIdentityKeysRequest, GetPathElementsRequest,
GetProtocolVersionUpgradeStateRequest, GetProtocolVersionUpgradeVoteStatusRequest,
GetTotalCreditsInPlatformRequest, KeyRequestType,
Expand Down Expand Up @@ -621,6 +623,24 @@ impl Query<GetTotalCreditsInPlatformRequest> for NoParamQuery {
}
}

impl Query<GetCurrentQuorumsInfoRequest> for NoParamQuery {
fn query(self, prove: bool) -> Result<GetCurrentQuorumsInfoRequest, Error> {
if prove {
unimplemented!(
"query with proof are not supported yet for GetCurrentQuorumsInfoRequest"
);
}

let request: GetCurrentQuorumsInfoRequest = GetCurrentQuorumsInfoRequest {
version: Some(get_current_quorums_info_request::Version::V0(
GetCurrentQuorumsInfoRequestV0 {},
)),
};

Ok(request)
}
}

impl Query<GetEvonodesProposedEpochBlocksByRangeRequest> for LimitQuery<Option<EpochIndex>> {
fn query(self, prove: bool) -> Result<GetEvonodesProposedEpochBlocksByRangeRequest, Error> {
if !prove {
Expand Down
14 changes: 14 additions & 0 deletions packages/withdrawals-contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use platform_value::{Identifier, IdentifierBytes32};
use platform_version::version::PlatformVersion;
use serde_json::Value;
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::fmt;

mod error;
pub mod v1;
Expand Down Expand Up @@ -44,6 +45,19 @@ pub enum WithdrawalStatus {
EXPIRED = 4,
}

impl fmt::Display for WithdrawalStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let status_str = match self {
WithdrawalStatus::QUEUED => "Queued",
WithdrawalStatus::POOLED => "Pooled",
WithdrawalStatus::BROADCASTED => "Broadcasted",
WithdrawalStatus::COMPLETE => "Complete",
WithdrawalStatus::EXPIRED => "Expired",
};
write!(f, "{}", status_str)
}
}

pub fn load_definitions(platform_version: &PlatformVersion) -> Result<Option<Value>, Error> {
match platform_version.system_data_contracts.withdrawals {
1 => Ok(None),
Expand Down

0 comments on commit 09d89f8

Please sign in to comment.