SyntiFi played a leading role in the development of the Casper Java SDK. In this blog post, we would like to share with the broader community the rationale behind some of our decisions when implementing the SDK.
The Casper network, most specifically their RPC methods, are well designed and structured, making it a much easier task to wrap them around a fully compatible and secure SDK.
The most challenging part in implementing the Casper Java SDK was the correct handling of the serialization of the object for:
- The RPC-JSON calls
- Signatures
JSON parsing
For handling the JSON-RPC calls, we chose to use a readily available and open-source JSON-RPC library in Java, Json RPC4J. In a nutshell, it uses the proxy pattern (more of this in another post) to facilitate the implementation and handling of JSON/POJO parsing.
In fact, for the parsing, the library also uses Jackson. It is a neat JSON parser for Java with many features besides being the de-facto JSON serializer used by many projects. We also love Jackson, so this would perfectly fit our serialization needs.
With Jackson, it is a very straightforward process to parse POJOs to JSON and vice-versa. This was further simplified by using Lombok, which made the object mapping and parsing from basic to complex, hierarchical objects straightforward, readable and maintainable. For instance, take a look at the implementation of one RPC call:
/**
* Sends a deploy to be received by the network
*
* @param deploy the deploy object to send to the network
* @return Object holding the api version and the deploy hash
*/
@JsonRpcMethod(value = "account_put_deploy", paramsPassMode = JsonRpcParamsPassMode.ARRAY)
DeployResult putDeploy(Deploy deploy);The proxy pattern allows the usage of a simple @JsonRpcMethod annotation on an interface method to provide access to any node RPC method readable and maintainable. Also, it just handles responses, errors, and resulting serializations and deserializations transparently, allowing us to focus on core functionality.
Get SyntiFi’s stories in your inbox
Join Medium for free to get updates from this writer.
That being said, it turns out that one has to account for several subtypes in many objects returned by the RPC services. Note that this is perfectly fine and easily handled in JavaScript which is a dynamic typing language, but in Java, if we want to convert these JSONs to POJOs, we need to specify these Java types properly. Take, for instance, the Deploy class:
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Deploy implements CasperSerializableObject {
/**
* Hex-encoded deploy hash
*/
private Digest hash;
/**
* @see DeployHeader
*/
private DeployHeader header;
/**
* @see Approval
*/
private List<Approval> approvals;
/**
* @see ExecutableDeployItem
*/
private ExecutableDeployItem payment;
/**
* @see ExecutableDeployItem
*/
private ExecutableDeployItem session;
/**
* Implements Deploy encoder
*/
@Override
public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException {
header.serialize(ser, Target.BYTE);
hash.serialize(ser, Target.BYTE);
payment.serialize(ser, Target.BYTE);
session.serialize(ser, Target.BYTE);
ser.writeI32(approvals.size());
for (Approval approval : approvals) {
approval.serialize(ser, Target.BYTE);
}
}
}It expects an ExecutableDeployItem, which could be StoredContractByHash, StoredContractByName, and many more. For our help, Jackson already had a solution for these situations. It is great because we can specify these subtypes given the wrapper object name:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({@JsonSubTypes.Type(value = ModuleBytes.class, name = "ModuleBytes"),
@JsonSubTypes.Type(value = StoredContractByHash.class, name = "StoredContractByHash"),
@JsonSubTypes.Type(value = StoredContractByName.class, name = "StoredContractByName"),
@JsonSubTypes.Type(value = StoredVersionedContractByHash.class, name = "StoredVersionedContractByHash"),
@JsonSubTypes.Type(value = StoredVersionedContractByName.class, name = "StoredVersionedContractByName"),
@JsonSubTypes.Type(value = Transfer.class, name = "Transfer")})
public interface ExecutableDeployItem extends CasperSerializableObject {
@JsonIgnore
byte getOrder();
}We were not as lucky for the CLTypes and CLValues. The @JsonSubTypes approach does not help us much there, and, in this particular case, we ended up creating our custom deserializers/resolvers:
public abstract class AbstractAnyOfDeserializer extends AsPropertyTypeDeserializer {
protected AbstractAnyOfDeserializer(final JavaType bt, final TypeIdResolver idRes, final String typePropertyName,
final boolean typeIdVisible, JavaType defaultImpl) {
super(bt, idRes, typePropertyName, typeIdVisible, defaultImpl);
}With this simple approach, we could handle any specific processing we needed to account for fields with serialized byte arrays that follow specific serialization standards and must be converted to actual values in our java objects to eliminate the need for the SDK user to know the inner workings of said byte array serializations.
Serialization for Signatures
Instances of the ExecutableDeployItem class need the extra capability to serialize themselves, following specific predefined rules. With this byte stream, the end user can hash and sign the transaction to send a request to the Chain.
This capability is crucial for a successful working SDK. Our approach here was to modularize as much as possible and let those objects that need this method implement it, following a Separation of Concerns (SoC) pattern. All these objects implement the CasperSerializableObject interface:
/**
* Defines an object as being capable of encoding with {@link SerializerBuffer}
*
* @author Alexandre Carvalho
* @author Andre Bertolace
* @since 0.2.2
*/
public interface CasperSerializableObject extends SerializableObject {
/**
* Called when the object's values must be serialized
*
* @param ser the serializer to be used
* @param target target serialization standard
* @throws ValueSerializationException exception holding information of failure to serialize a value
*/
void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException;
/**
* Called when the object's values must be serialized
* <p>
* Allows to use the default serialize with the custom casper serialize signature, defaulting encodeType to false
*
* @param ser the serializer to be used
* @throws ValueSerializationException exception holding information of failure to serialize a value
*/
@Override
default void serialize(SerializerBuffer ser) throws ValueSerializationException {
try {
serialize(ser, Target.JSON);
} catch (NoSuchTypeException e) {
throw new ValueSerializationException(String.format("Error serializing %s", this.getClass().getSimpleName()), e);
}
}
}In particular, implement the serialize method as the one of the Deploy class:
public class Deploy implements CasperSerializableObject {
...
@Override
public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException {
header.serialize(ser, Target.BYTE);
hash.serialize(ser, Target.BYTE);
payment.serialize(ser, Target.BYTE);
session.serialize(ser, Target.BYTE);
ser.writeI32(approvals.size());
for (Approval approval : approvals) {
approval.serialize(ser, Target.BYTE);
}
}
}This way, each Java object can take care of its serialization and deserialization needs (following a proper Domain Model approach) and forward the SerializerBuffer through the serialization chain, asking its children objects or collections to do the same, consistently and sequentially, like the Approval collection in this case:
public class Approval implements CasperSerializableObject {
...
@Override
public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException {
signer.serialize(ser, target);
signature.serialize(ser, target);
}
}This article was written by André Bertolace and Alexandre Carvalho, members of the SyntiFi team.
SyntiFi next generation risk intelligence offers privacy enabled collaborative data analysis, visualization and actionable agent-centric intelligence to unlock compliance relevant insights about digital asset transactions. SyntiFi features a number of innovations not seen before in risk intelligence. For more information, visit SyntiFi.com, follow us on Twitter and connect on LinkedIn.










