Skip to content
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

fix: identifier deserialization doesn't work for bincode #885

Merged
merged 1 commit into from
Apr 4, 2023
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
8 changes: 3 additions & 5 deletions packages/rs-dpp/src/errors/consensus/consensus_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,8 @@ impl ConsensusError {
.reject_trailing_bytes()
.with_big_endian()
.serialize(self)
.map_err(|_| {
ProtocolError::EncodingError(String::from(
"unable to serialize identity public key",
))
.map_err(|e| {
ProtocolError::EncodingError(format!("unable to serialize consensus error: {e}"))
})
}

Expand All @@ -67,7 +65,7 @@ impl ConsensusError {
.with_big_endian()
.deserialize(bytes)
.map_err(|e| {
ProtocolError::EncodingError(format!("unable to deserialize consensus error {}", e))
ProtocolError::EncodingError(format!("unable to deserialize consensus error: {e}"))
})
}
}
6 changes: 0 additions & 6 deletions packages/rs-dpp/src/identity/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,12 +334,6 @@ impl Identity {
raw_object.try_into()
}

/// Creates an identity from a json object
pub fn from_json_object(raw_object: JsonValue) -> Result<Identity, ProtocolError> {
let value: Value = raw_object.into();
value.try_into()
}

/// Computes the hash of an identity
pub fn hash(&self) -> Result<Vec<u8>, ProtocolError> {
Ok(hash::hash(self.to_buffer()?))
Expand Down
29 changes: 23 additions & 6 deletions packages/rs-platform-value/src/types/identifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,30 @@ impl<'de> Deserialize<'de> for IdentifierBytes32 {

deserializer.deserialize_string(StringVisitor)
} else {
let value = Value::deserialize(deserializer)?;
struct BytesVisitor;

Ok(IdentifierBytes32(
value
.into_hash256()
.map_err(|_| D::Error::custom("hello"))?,
))
impl<'de> Visitor<'de> for BytesVisitor {
type Value = IdentifierBytes32;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a byte array with length 32")
}

fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if v.len() != 32 {
return Err(E::invalid_length(v.len(), &self));
}
let mut array = [0u8; 32];
array.copy_from_slice(&v);

Ok(IdentifierBytes32(array))
}
}

deserializer.deserialize_bytes(BytesVisitor)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ impl From<&ProtocolVersionParsingError> for ProtocolVersionParsingErrorWasm {

#[wasm_bindgen(js_class=ProtocolVersionParsingError)]
impl ProtocolVersionParsingErrorWasm {
#[wasm_bindgen(constructor)]
pub fn new(parsing_error: String) -> Self {
Self {
inner: ProtocolVersionParsingError::new(parsing_error),
}
}

#[wasm_bindgen(js_name = getParsingError)]
pub fn get_parsing_error(&self) -> String {
self.inner.parsing_error().to_string()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ impl From<&BalanceIsNotEnoughError> for BalanceIsNotEnoughErrorWasm {

#[wasm_bindgen(js_class=BalanceIsNotEnoughError)]
impl BalanceIsNotEnoughErrorWasm {
#[wasm_bindgen(constructor)]
pub fn new(balance: Credits, fee: Credits) -> Self {
Self {
inner: BalanceIsNotEnoughError::new(balance, fee),
}
}

#[wasm_bindgen(js_name=getBalance)]
pub fn get_balance(&self) -> Credits {
self.inner.balance()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use dpp::consensus::ConsensusError;
use wasm_bindgen::prelude::*;

use crate::buffer::Buffer;
use crate::identifier::IdentifierWrapper;

#[wasm_bindgen(js_name=IdentityNotFoundError)]
pub struct IdentityNotFoundErrorWasm {
Expand All @@ -18,9 +19,16 @@ impl From<&IdentityNotFoundError> for IdentityNotFoundErrorWasm {

#[wasm_bindgen(js_class=IdentityNotFoundError)]
impl IdentityNotFoundErrorWasm {
#[wasm_bindgen(constructor)]
pub fn new(identity_id: IdentifierWrapper) -> Self {
Self {
inner: IdentityNotFoundError::new(identity_id.into()),
}
}

#[wasm_bindgen(js_name=getIdentityId)]
pub fn get_identity_id(&self) -> Buffer {
Buffer::from_bytes(self.inner.identity_id().as_bytes())
pub fn get_identity_id(&self) -> IdentifierWrapper {
self.inner.identity_id().into()
}

#[wasm_bindgen(js_name=getCode)]
Expand All @@ -37,7 +45,7 @@ impl IdentityNotFoundErrorWasm {
pub fn serialize(&self) -> Result<Buffer, JsError> {
let bytes = ConsensusError::from(self.inner.clone())
.serialize()
.map_err(|e| JsError::from(e))?;
.map_err(JsError::from)?;

Ok(Buffer::from_bytes(bytes.as_slice()))
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::buffer::Buffer;
use crate::identifier::IdentifierWrapper;
use dpp::consensus::codes::ErrorWithCode;
use dpp::consensus::state::data_contract::data_contract_already_present_error::DataContractAlreadyPresentError;
use dpp::consensus::ConsensusError;
use dpp::identifier::Identifier;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(js_name=DataContractAlreadyPresentError)]
Expand All @@ -17,9 +19,16 @@ impl From<&DataContractAlreadyPresentError> for DataContractAlreadyPresentErrorW

#[wasm_bindgen(js_class=DataContractAlreadyPresentError)]
impl DataContractAlreadyPresentErrorWasm {
#[wasm_bindgen(constructor)]
pub fn new(data_contract_id: IdentifierWrapper) -> Self {
Self {
inner: DataContractAlreadyPresentError::new(data_contract_id.into()),
}
}

#[wasm_bindgen(js_name=getDataContractId)]
pub fn data_contract_id(&self) -> Buffer {
Buffer::from_bytes(self.inner.data_contract_id().as_bytes())
pub fn data_contract_id(&self) -> IdentifierWrapper {
self.inner.data_contract_id().to_owned().into()
}

#[wasm_bindgen(js_name=getCode)]
Expand Down
2 changes: 1 addition & 1 deletion packages/wasm-dpp/src/identity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl IdentityWasm {
let raw_identity: Value =
serde_json::from_str(&identity_json).map_err(|e| e.to_string())?;

let identity = Identity::from_json_object(raw_identity).unwrap();
let identity = Identity::from_json(raw_identity).unwrap();
Ok(IdentityWasm(identity))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,30 @@ const { default: loadWasmDpp } = require('../../../..');

let {
deserializeConsensusError,
decodeProtocolEntity,
ProtocolVersionParsingError,
} = require('../../../..');

describe('deserializeConsensusError', () => {
before(async () => {
({
deserializeConsensusError,
decodeProtocolEntity,
ProtocolVersionParsingError,
} = await loadWasmDpp());
});

it('should deserialize consensus error', async () => {
try {
await decodeProtocolEntity(Buffer.alloc(0));
} catch (consensusError) {
expect(consensusError).to.be.instanceOf(ProtocolVersionParsingError);
expect(consensusError.getCode()).to.equals(1000);
expect(consensusError.message).to.equals('Can\'t read protocol version from serialized object: protocol version could not be decoded as a varint');
const consensusError = new ProtocolVersionParsingError('test');
const message = 'Can\'t read protocol version from serialized object: test';

const bytes = consensusError.serialize();
expect(consensusError).to.be.instanceOf(ProtocolVersionParsingError);
expect(consensusError.getCode()).to.equals(1000);
expect(consensusError.message).to.equals(message);

const recoveredError = deserializeConsensusError(bytes);
expect(recoveredError).to.be.instanceOf(ProtocolVersionParsingError);
expect(recoveredError.getCode()).to.equals(1000);
expect(recoveredError.message).to.equals('Can\'t read protocol version from serialized object: protocol version could not be decoded as a varint');
}
const serializedConsensusError = consensusError.serialize();

const recoveredError = deserializeConsensusError(serializedConsensusError);
expect(recoveredError).to.be.instanceOf(ProtocolVersionParsingError);
expect(recoveredError.getCode()).to.equals(1000);
expect(recoveredError.message).to.equals(message);
});
});