From 630ded38ceb7dedde8c27212a5e449d7157bc07a Mon Sep 17 00:00:00 2001 From: meywood Date: Tue, 2 Aug 2022 12:13:24 +0100 Subject: [PATCH 01/35] issues/120 - Initial commit of EventService against merged codebase --- build.gradle | 4 +- .../sdk/exception/CasperClientException.java | 5 + .../com/casper/sdk/model/common/Digest.java | 12 +- .../com/casper/sdk/model/event/Event.java | 33 +++ .../com/casper/sdk/model/event/EventData.java | 10 + .../casper/sdk/model/event/EventTarget.java | 14 ++ .../com/casper/sdk/model/event/EventType.java | 16 ++ .../model/event/blockadded/BlockAdded.java | 30 +++ .../event/deployaccepted/DeployAccepted.java | 27 ++ .../event/deployexpired/DeployExpired.java | 28 +++ .../deployprocessed/DeployProcessed.java | 44 ++++ .../deployprocessed/ExecutionEffect.java | 22 ++ .../casper/sdk/model/event/fault/Fault.java | 30 +++ .../finalitysignature/FinalitySignature.java | 33 +++ .../sdk/model/event/shutdown/Shutdown.java | 22 ++ .../com/casper/sdk/model/event/step/Step.java | 28 +++ .../sdk/model/event/version/ApiVersion.java | 25 ++ .../com/casper/sdk/service/EventService.java | 70 ++++++ .../sdk/service/EventServiceFactory.java | 110 ++++++++ .../sdk/service/EventServiceFactoryTest.java | 37 +++ .../service/EventServiceIntegrationTest.java | 156 ++++++++++++ .../sdk/service/impl/event/AbstractEvent.java | 68 +++++ .../sdk/service/impl/event/EventBuilder.java | 127 ++++++++++ .../service/impl/event/EventBuilderTest.java | 236 ++++++++++++++++++ .../sdk/service/impl/event/EventRoot.java | 153 ++++++++++++ .../service/impl/event/EventServiceImpl.java | 97 +++++++ .../service/impl/event/EventUrlBuilder.java | 50 ++++ .../impl/event/EventUrlBuilderTest.java | 44 ++++ .../sdk/service/impl/event/PojoEvent.java | 19 ++ .../sdk/service/impl/event/RawEvent.java | 17 ++ .../java/com/casper/sdk/test/MockNode.java | 30 +++ .../test/PathMatchingResourceDispatcher.java | 46 ++++ .../event-samples/api-version-event.txt | 1 + .../event-samples/block-added-event.txt | 2 + .../event-samples/deploy-accepted-event.txt | 2 + .../event-samples/deploy-expired-event.txt | 2 + .../event-samples/deploy-processed-event.txt | 2 + .../event-samples/deploys-events.txt | 4 + .../resources/event-samples/fault-event.txt | 3 + .../finality-signature-event.txt | 2 + .../resources/event-samples/main-events.txt | 10 + .../event-samples/shutdown-event.txt | 2 + .../resources/event-samples/sigs-events.txt | 13 + .../resources/event-samples/step-event.txt | 2 + 44 files changed, 1682 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/casper/sdk/model/event/Event.java create mode 100644 src/main/java/com/casper/sdk/model/event/EventData.java create mode 100644 src/main/java/com/casper/sdk/model/event/EventTarget.java create mode 100644 src/main/java/com/casper/sdk/model/event/EventType.java create mode 100644 src/main/java/com/casper/sdk/model/event/blockadded/BlockAdded.java create mode 100644 src/main/java/com/casper/sdk/model/event/deployaccepted/DeployAccepted.java create mode 100644 src/main/java/com/casper/sdk/model/event/deployexpired/DeployExpired.java create mode 100644 src/main/java/com/casper/sdk/model/event/deployprocessed/DeployProcessed.java create mode 100644 src/main/java/com/casper/sdk/model/event/deployprocessed/ExecutionEffect.java create mode 100644 src/main/java/com/casper/sdk/model/event/fault/Fault.java create mode 100644 src/main/java/com/casper/sdk/model/event/finalitysignature/FinalitySignature.java create mode 100644 src/main/java/com/casper/sdk/model/event/shutdown/Shutdown.java create mode 100644 src/main/java/com/casper/sdk/model/event/step/Step.java create mode 100644 src/main/java/com/casper/sdk/model/event/version/ApiVersion.java create mode 100644 src/main/java/com/casper/sdk/service/EventService.java create mode 100644 src/main/java/com/casper/sdk/service/EventServiceFactory.java create mode 100644 src/test/java/com/casper/sdk/service/EventServiceFactoryTest.java create mode 100644 src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/EventRoot.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilderTest.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/RawEvent.java create mode 100644 src/test/java/com/casper/sdk/test/MockNode.java create mode 100644 src/test/java/com/casper/sdk/test/PathMatchingResourceDispatcher.java create mode 100644 src/test/resources/event-samples/api-version-event.txt create mode 100644 src/test/resources/event-samples/block-added-event.txt create mode 100644 src/test/resources/event-samples/deploy-accepted-event.txt create mode 100644 src/test/resources/event-samples/deploy-expired-event.txt create mode 100644 src/test/resources/event-samples/deploy-processed-event.txt create mode 100644 src/test/resources/event-samples/deploys-events.txt create mode 100644 src/test/resources/event-samples/fault-event.txt create mode 100644 src/test/resources/event-samples/finality-signature-event.txt create mode 100644 src/test/resources/event-samples/main-events.txt create mode 100644 src/test/resources/event-samples/shutdown-event.txt create mode 100644 src/test/resources/event-samples/sigs-events.txt create mode 100644 src/test/resources/event-samples/step-event.txt diff --git a/build.gradle b/build.gradle index 522192e8d..90b549d81 100644 --- a/build.gradle +++ b/build.gradle @@ -34,6 +34,8 @@ dependencies { testImplementation "org.apache.logging.log4j:log4j-api:${log4jVersion}" testImplementation "org.apache.logging.log4j:log4j-core:${log4jVersion}" testImplementation "org.apache.logging.log4j:log4j-slf4j-impl:${log4jVersion}" + testImplementation "com.jayway.jsonpath:json-path-assert:${jsonPathAssertVersion}" + testImplementation "com.squareup.okhttp3:mockwebserver:${mockwebserverVersion}" // Use JUnit Jupiter for testing. testImplementation "org.junit.jupiter:junit-jupiter:${jupiterVersion}" @@ -153,7 +155,7 @@ publishing { licenses { license { name = 'The Apache License, Version 2.0' - url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' + url = 'https://www.apache.org/licenses/LICENSE-2.0.txt' } } diff --git a/src/main/java/com/casper/sdk/exception/CasperClientException.java b/src/main/java/com/casper/sdk/exception/CasperClientException.java index ac9803467..d3bfaf8f7 100644 --- a/src/main/java/com/casper/sdk/exception/CasperClientException.java +++ b/src/main/java/com/casper/sdk/exception/CasperClientException.java @@ -16,4 +16,9 @@ public CasperClientException(CasperClientErrorData error) { public CasperClientException(String message, Throwable cause) { super(message, cause); } + + public CasperClientException(String message) { + super(message); + + } } diff --git a/src/main/java/com/casper/sdk/model/common/Digest.java b/src/main/java/com/casper/sdk/model/common/Digest.java index 8f4cfa64f..f548917f7 100644 --- a/src/main/java/com/casper/sdk/model/common/Digest.java +++ b/src/main/java/com/casper/sdk/model/common/Digest.java @@ -6,11 +6,7 @@ import com.casper.sdk.model.clvalue.encdec.CLValueEncoder; import com.casper.sdk.model.clvalue.encdec.interfaces.EncodableValue; import com.fasterxml.jackson.annotation.JsonValue; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import lombok.*; import org.bouncycastle.util.encoders.Hex; import java.io.IOException; @@ -26,6 +22,7 @@ @Setter @NoArgsConstructor @AllArgsConstructor +@EqualsAndHashCode(of = "digest") @Builder public class Digest implements EncodableValue { @JsonValue @@ -53,4 +50,9 @@ public void encode(CLValueEncoder clve, boolean encodeType) throws IOException, CLValueEncodeException, DynamicInstanceException, NoSuchTypeException { clve.write(getDigest()); } + + @Override + public String toString() { + return digest; + } } \ No newline at end of file diff --git a/src/main/java/com/casper/sdk/model/event/Event.java b/src/main/java/com/casper/sdk/model/event/Event.java new file mode 100644 index 000000000..464b51608 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/Event.java @@ -0,0 +1,33 @@ +package com.casper.sdk.model.event; + +import java.util.Optional; + +/** + * The interface implemented by all events that are read from a nodes event stream + * + * @author ian@meywood.com + */ +public interface Event { + + /** + * The type of the event + * + * @return the type of the event + */ + + EventType getEventType(); + + /** + * The event payload a JSON string or Pojo + * + * @return the event payload + */ + T getData(); + + /** + * The optional ID of the event + * + * @return the optional ID + */ + Optional getId(); +} diff --git a/src/main/java/com/casper/sdk/model/event/EventData.java b/src/main/java/com/casper/sdk/model/event/EventData.java new file mode 100644 index 000000000..6bc0e3df6 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/EventData.java @@ -0,0 +1,10 @@ +package com.casper.sdk.model.event; + +/** + * Interface implemented by all Pojo event data JSON nodes + * + * @author ian@meywood.com + */ +public interface EventData { + +} diff --git a/src/main/java/com/casper/sdk/model/event/EventTarget.java b/src/main/java/com/casper/sdk/model/event/EventTarget.java new file mode 100644 index 000000000..391a32953 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/EventTarget.java @@ -0,0 +1,14 @@ +package com.casper.sdk.model.event; + +/** + * The target type, that states how an event is to be + * + * @author ian@meywood.com + */ +public enum EventTarget { + + /** The event data is obtained as a raw JSON string */ + RAW, + /** The event data in parsed from JSON to a Pojo */ + POJO +} diff --git a/src/main/java/com/casper/sdk/model/event/EventType.java b/src/main/java/com/casper/sdk/model/event/EventType.java new file mode 100644 index 000000000..cbdeb7921 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/EventType.java @@ -0,0 +1,16 @@ +package com.casper.sdk.model.event; + +/** + * The type of event to obtain from a nodes event stream + * + * @author ian@meywood.com + */ +public enum EventType { + + /** Request deploy events from a stream */ + DEPLOYS, + /** Request main events from a stream */ + MAIN, + /** Request for signature events from a stream */ + SIGS +} diff --git a/src/main/java/com/casper/sdk/model/event/blockadded/BlockAdded.java b/src/main/java/com/casper/sdk/model/event/blockadded/BlockAdded.java new file mode 100644 index 000000000..276d75e74 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/blockadded/BlockAdded.java @@ -0,0 +1,30 @@ +package com.casper.sdk.model.event.blockadded; + +import com.casper.sdk.model.block.JsonBlock; +import com.casper.sdk.model.common.Digest; +import com.casper.sdk.model.event.EventData; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import lombok.*; + +/** + * The BlockAdded event is emitted whenever a new block is added to the blockchain and stored locally in the node. + * + * @author ian@meywood.com + */ +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +@JsonTypeName("BlockAdded") +public class BlockAdded implements EventData { + + /** A cryptographic hash identifying a `Block` */ + @JsonProperty("block_hash") + private Digest blockHash; + + /** A JSON-friendly representation of `Block`. */ + @JsonProperty("block") + private JsonBlock block; +} diff --git a/src/main/java/com/casper/sdk/model/event/deployaccepted/DeployAccepted.java b/src/main/java/com/casper/sdk/model/event/deployaccepted/DeployAccepted.java new file mode 100644 index 000000000..168ce6336 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/deployaccepted/DeployAccepted.java @@ -0,0 +1,27 @@ +package com.casper.sdk.model.event.deployaccepted; + +import com.casper.sdk.model.deploy.Deploy; +import com.casper.sdk.model.event.EventData; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonUnwrapped; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * The event stream server of the node emits a DeployAccepted event when a Deploy has been received by the node. + * + * @author ian@meywood.com + */ +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@JsonTypeName("DeployAccepted") +public class DeployAccepted implements EventData { + + /** The wrapped deploy */ + @JsonUnwrapped + private Deploy deploy; +} diff --git a/src/main/java/com/casper/sdk/model/event/deployexpired/DeployExpired.java b/src/main/java/com/casper/sdk/model/event/deployexpired/DeployExpired.java new file mode 100644 index 000000000..364dc1f90 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/deployexpired/DeployExpired.java @@ -0,0 +1,28 @@ +package com.casper.sdk.model.event.deployexpired; + +import com.casper.sdk.model.common.Digest; +import com.casper.sdk.model.event.EventData; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * The DeployExpired event is emitted when a Deploy becomes no longer valid to be executed or added to a block due to + * their times to live (TTLs) expiring. + * + * @author ian@meywood.com + */ +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@JsonTypeName("DeployExpired") +public class DeployExpired implements EventData { + + /** The hash of the expired deploy */ + @JsonProperty("deploy_hash") + private Digest deployHash; +} diff --git a/src/main/java/com/casper/sdk/model/event/deployprocessed/DeployProcessed.java b/src/main/java/com/casper/sdk/model/event/deployprocessed/DeployProcessed.java new file mode 100644 index 000000000..dbfafe818 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/deployprocessed/DeployProcessed.java @@ -0,0 +1,44 @@ +package com.casper.sdk.model.event.deployprocessed; + +import com.casper.sdk.model.deploy.executionresult.ExecutionResult; +import com.casper.sdk.model.event.EventData; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import lombok.*; + +import java.util.List; + +/** + * The DeployProcessed event is emitted when a given Deploy has been executed. + * + * @author ian@meywood.com + */ +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +@JsonTypeName("DeployProcessed") +public class DeployProcessed implements EventData { + + @JsonProperty("deploy_hash") + private String deployHash; + + @JsonProperty("account") + private String account; + + @JsonProperty("timestamp") + private String timestamp; // TODO convert to data + + @JsonProperty("ttl") + private String ttl; + + @JsonProperty("dependencies") + private List dependencies; + + @JsonProperty("block_hash") + private String blockHash; + + @JsonProperty("execution_result") + private ExecutionResult executionResult; +} diff --git a/src/main/java/com/casper/sdk/model/event/deployprocessed/ExecutionEffect.java b/src/main/java/com/casper/sdk/model/event/deployprocessed/ExecutionEffect.java new file mode 100644 index 000000000..349f9e174 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/deployprocessed/ExecutionEffect.java @@ -0,0 +1,22 @@ +package com.casper.sdk.model.event.deployprocessed; + +import com.casper.sdk.model.deploy.Operation; +import com.casper.sdk.model.deploy.transform.Transform; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + +import java.util.List; + +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class ExecutionEffect { + + @JsonProperty("operations") + private List operations; + + @JsonProperty("transforms") + private List transforms; +} diff --git a/src/main/java/com/casper/sdk/model/event/fault/Fault.java b/src/main/java/com/casper/sdk/model/event/fault/Fault.java new file mode 100644 index 000000000..2e2f6ff49 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/fault/Fault.java @@ -0,0 +1,30 @@ +package com.casper.sdk.model.event.fault; + +import com.casper.sdk.model.event.EventData; +import com.casper.sdk.model.key.PublicKey; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@JsonTypeName("Fault") +public class Fault implements EventData { + + /** The period of time used to specify when specific events in a blockchain network occur. */ + @JsonProperty("era_id") + private Long eraId; + + /** A unique personal address that is shared in the network. */ + @JsonProperty("public_key") + private PublicKey publicKey; + + /** A timestamp type, representing a concrete moment in time of the fault. */ + @JsonProperty("timestamp") + private String timestamp; // TODO convert to data +} diff --git a/src/main/java/com/casper/sdk/model/event/finalitysignature/FinalitySignature.java b/src/main/java/com/casper/sdk/model/event/finalitysignature/FinalitySignature.java new file mode 100644 index 000000000..1e0a6f94d --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/finalitysignature/FinalitySignature.java @@ -0,0 +1,33 @@ +package com.casper.sdk.model.event.finalitysignature; + +import com.casper.sdk.model.common.Digest; +import com.casper.sdk.model.event.EventData; +import com.casper.sdk.model.key.PublicKey; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import lombok.*; + +/** + * A validator's signature of a block, to confirm it is finalized. Clients and joining nodes should wait until the + * signers' combined weight exceeds their fault tolerance threshold before accepting the block as finalized. + */ +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +@JsonTypeName("FinalitySignature") +public class FinalitySignature implements EventData { + + @JsonProperty("block_hash") + private Digest blockHash; + + @JsonProperty("era_id") + private long eraId; + + @JsonProperty("public_key") + private PublicKey publicKey; + + @JsonProperty("signature") + private String signature; +} diff --git a/src/main/java/com/casper/sdk/model/event/shutdown/Shutdown.java b/src/main/java/com/casper/sdk/model/event/shutdown/Shutdown.java new file mode 100644 index 000000000..7f0f5e58d --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/shutdown/Shutdown.java @@ -0,0 +1,22 @@ +package com.casper.sdk.model.event.shutdown; + +import com.casper.sdk.model.event.EventData; +import com.fasterxml.jackson.annotation.JsonTypeName; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +/** + * Event sent when a node shuts down + * + * @author ian@meywood.com + */ +@Getter +@Setter +@Builder +@AllArgsConstructor +@JsonTypeName("Shutdown") +public class Shutdown implements EventData { + +} diff --git a/src/main/java/com/casper/sdk/model/event/step/Step.java b/src/main/java/com/casper/sdk/model/event/step/Step.java new file mode 100644 index 000000000..bcd2d5858 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/step/Step.java @@ -0,0 +1,28 @@ +package com.casper.sdk.model.event.step; + +import com.casper.sdk.model.deploy.ExecutionEffect; +import com.casper.sdk.model.event.EventData; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import lombok.*; + +/** + * The execution effects produced by a `StepRequest + * + * @author ian@meywood.com + */ +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +@JsonTypeName("Step") +public class Step implements EventData { + + @JsonProperty("era_id") + private long eraId; + + /** The journal of execution transforms from a single deploy. */ + @JsonProperty("execution_effect") + private ExecutionEffect executionEffect; +} diff --git a/src/main/java/com/casper/sdk/model/event/version/ApiVersion.java b/src/main/java/com/casper/sdk/model/event/version/ApiVersion.java new file mode 100644 index 000000000..84bbc9e8a --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/version/ApiVersion.java @@ -0,0 +1,25 @@ +package com.casper.sdk.model.event.version; + + +import com.casper.sdk.model.event.EventData; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import lombok.*; + +/** + * ApiVersion is always the first event emitted when a new client connects to the SSE server. It specifies the API + * version of the server. The ApiVersion is the protocol version of a node on the Casper platform. + * + * @author ian@meywood.com + */ +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +@JsonTypeName("ApiVersion") +public class ApiVersion implements EventData { + + @JsonValue + private String apiVersion; +} diff --git a/src/main/java/com/casper/sdk/service/EventService.java b/src/main/java/com/casper/sdk/service/EventService.java new file mode 100644 index 000000000..d36e64b0d --- /dev/null +++ b/src/main/java/com/casper/sdk/service/EventService.java @@ -0,0 +1,70 @@ +package com.casper.sdk.service; + +import com.casper.sdk.model.event.Event; +import com.casper.sdk.model.event.EventTarget; +import com.casper.sdk.model.event.EventType; + +import java.io.Reader; +import java.net.URI; +import java.util.stream.Stream; + +/** + * The EventService interface. + *

+ * Is instantiated using the static create methods within the interface eg: + *

final EventService eventService = EventService.create("http://localhost:18101");
+ * + * @author ian@meywood.com + */ +public interface EventService { + + /** + * Reads a single event from a reader + * + * @param eventType the type of event to read + * @param eventTarget the target of the event JSON string or POJO + * @param reader the reader to read the event from + * @param the type of the event + * @param the type of the events content + * @return the read event + */ + > Stream readEvent(final EventType eventType, + final EventTarget eventTarget, + final Reader reader); + + + /** + * Reads a stream of events from a node + * * + * + * @param eventType the type of event to read + * @param eventTarget the target of the event JSON string or POJO + * @param the type of the event + * @param the type of the events content + * @return the read event + */ + > Stream readEventStream(final EventType eventType, + final EventTarget eventTarget, + final Long startFrom); + + + /** + * Creates a new EventService for the specified host including protocol and port + * + * @param host the host including protocol and port eg: http:/localhost:18101 + * @return the event service for the specified host + */ + static EventService usingPeer(final String host) { + return EventServiceFactory.create(host); + } + + /** + * Creates a new EventService for the specified host including protocol and port + * + * @param uri the uri of the host to connect to + * @return the event service for the specified host + */ + static EventService usingPeer(final URI uri) { + return EventServiceFactory.create(uri); + } +} diff --git a/src/main/java/com/casper/sdk/service/EventServiceFactory.java b/src/main/java/com/casper/sdk/service/EventServiceFactory.java new file mode 100644 index 000000000..79ff82070 --- /dev/null +++ b/src/main/java/com/casper/sdk/service/EventServiceFactory.java @@ -0,0 +1,110 @@ +package com.casper.sdk.service; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.lang.reflect.Proxy; +import java.net.URI; +import java.util.*; + +/** + * The factory class for creating the {@link EventService} + * + * @author ian@meywood.com + */ +final class EventServiceFactory { + + /** The name of the class that implements the {@link com.casper.sdk.service.EventService} */ + private static final String IMPLEMENTATION_CLASS = "com.casper.sdk.service.impl.event.EventServiceImpl"; + /** The map of service method names to log */ + private static final Map> methodParamMap = new HashMap<>(); + + /** + * Creates a new EventService for the specified host + * + * @param host the host to connect to including protocol and port eg:
http://localhost:18101
+ * @return a newly created event service + */ + static EventService create(final String host) { + return proxy(createEventService(host)); + } + + /** + * Creates a new EventService for the specified host + * + * @param uri to URO of the host to connect to + * @return a newly created event service + */ + static EventService create(final URI uri) { + return proxy(createEventService(uri)); + } + + private static EventService proxy(final EventService eventService) { + + final Logger logger = LoggerFactory.getLogger(EventService.class); + + return (EventService) Proxy.newProxyInstance( + EventServiceFactory.class.getClassLoader(), + new Class[]{EventService.class}, + (proxy, method, args) -> { + if (logger.isDebugEnabled() && isServiceMethod(method)) { + logger.debug("{}({})", method.getName(), argsToString(method, args)); + } + return method.invoke(eventService, args); + } + ); + } + + private static boolean isServiceMethod(final Method method) { + return Arrays.asList(EventService.class.getDeclaredMethods()).contains(method); + } + + private static EventService createEventService(final Object param) { + + try { + final Constructor constructor = Class.forName(IMPLEMENTATION_CLASS) + .getDeclaredConstructor(param.getClass()); + constructor.setAccessible(true); + return (EventService) constructor.newInstance(param); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static String argsToString(final Method method, final Object[] args) { + + final Iterator parameterNames = getParameterNames(method).iterator(); + + final StringBuilder builder = new StringBuilder(); + + if (args != null && args.length > 0) { + for (Object arg : args) { + + if (builder.length() > 0) { + builder.append(", "); + } + builder.append(parameterNames.next()); + builder.append('='); + builder.append(arg); + + } + } + return builder.toString(); + } + + private static List getParameterNames(final Method method) { + + return methodParamMap.computeIfAbsent(method, method1 -> { + final Parameter[] parameters = method1.getParameters(); + final List parameterNames = new ArrayList<>(); + for (Parameter parameter : parameters) { + parameterNames.add(parameter.getName()); + } + return parameterNames; + }); + } +} diff --git a/src/test/java/com/casper/sdk/service/EventServiceFactoryTest.java b/src/test/java/com/casper/sdk/service/EventServiceFactoryTest.java new file mode 100644 index 000000000..322608f1d --- /dev/null +++ b/src/test/java/com/casper/sdk/service/EventServiceFactoryTest.java @@ -0,0 +1,37 @@ +package com.casper.sdk.service; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNull.notNullValue; + +/** + * Unit tests for the EventServiceFactory + * + * @author ian@meywood.com + */ +class EventServiceFactoryTest { + + @Test + void createUsingHostString() { + final EventService eventService = EventServiceFactory.create("http://localhost:18101"); + assertEventServiceProxied(eventService); + + } + + @Test + void createUsingURI() throws URISyntaxException { + final EventService eventService = EventServiceFactory.create(new URI("http://localhost:18101")); + assertEventServiceProxied(eventService); + } + + private void assertEventServiceProxied(final EventService eventService) { + assertThat(eventService, is(notNullValue())); + assertThat(Proxy.isProxyClass(eventService.getClass()), is(true)); + } +} \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java new file mode 100644 index 000000000..4b72c00f2 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java @@ -0,0 +1,156 @@ +package com.casper.sdk.service; + + +import com.casper.sdk.model.event.Event; +import com.casper.sdk.model.event.EventData; +import com.casper.sdk.model.event.EventTarget; +import com.casper.sdk.model.event.EventType; +import com.casper.sdk.model.event.step.Step; +import com.casper.sdk.model.event.version.ApiVersion; +import com.casper.sdk.test.MockNode; +import com.casper.sdk.test.PathMatchingResourceDispatcher; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.core.Is.is; + +class EventServiceIntegrationTest { + + private static final String MAIN_EVENTS = "/event-samples/main-events.txt"; + private static final String SIGS_EVENTS = "/event-samples/sigs-events.txt"; + private final MockNode mockNode = new MockNode(); + private final EventService eventService = EventService.usingPeer("http://localhost:28101"); + + @BeforeEach + void setUp() throws URISyntaxException, IOException { + mockNode.start(new URI("http://localhost:28101")); + } + + @AfterEach + void tearDown() throws IOException { + mockNode.shutdown(); + } + + @Test + void mainRawEvents() { + + mockNode.setDispatcher( + new PathMatchingResourceDispatcher(MAIN_EVENTS, is("/events/main?start_from=0")) + ); + + + int[] count = {0}; + eventService.readEventStream(EventType.MAIN, EventTarget.RAW, 0L).forEach(e -> { + + assertThat(e, instanceOf(Event.class)); + + //noinspection unchecked,rawtypes + final Event event = (Event) e; + assertThat(event.getEventType(), is(EventType.MAIN)); + + if (count[0] == 0) { + assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); + assertThat(event.getId().isPresent(), is(false)); + } else if (count[0] == 1) { + assertThat(event.getData(), startsWith("data:{\"Step\":{\"era_id\":0,\"execution_effect\":{\"operations\":[],")); + assertThat(event.getData(), endsWith("\"bytes\":\"03f5d62682010000\",\"parsed\":1658508997891}}}]}}}")); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(0L)); + } else if (count[0] == 3) { + assertThat( + event.getData(), + is("data:{\"BlockAdded\":{\"block_hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\"," + + "\"block\":{\"hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\",\"header\":" + + "{\"parent_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\"," + + "\"state_root_hash\":\"fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc\"," + + "\"body_hash\":\"980531392fb02fd03d632abaa17f0a59bc788ea5b86ff9ce4630851cf9c2b4cf\"," + + "\"random_bit\":true,\"accumulated_seed\":\"ab5d756563bf09545590bd95f9a8e7978d51760be95ea8e5c9bab58ba1129186\"," + + "\"era_end\":null,\"timestamp\":\"2022-07-22T16:56:40.704Z\",\"era_id\":1,\"height\":1," + + "\"protocol_version\":\"1.0.0\"},\"body\":{\"proposer\":\"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5\"," + + "\"deploy_hashes\":[],\"transfer_hashes\":[]},\"proofs\":[]}}}") + ); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(7L)); + + } + count[0]++; + }); + + assertThat(count[0], is(4)); + } + + @Test + void sigsRawEvents() { + + mockNode.setDispatcher( + new PathMatchingResourceDispatcher(SIGS_EVENTS, is("/events/sigs?start_from=0")) + ); + + int[] count = {0}; + + eventService.readEventStream(EventType.SIGS, EventTarget.RAW, 0L).forEach(e -> { + + //noinspection unchecked,rawtypes + final Event event = (Event) e; + assertThat(event.getEventType(), is(EventType.SIGS)); + + if (count[0] == 0) { + assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); + assertThat(event.getId().isPresent(), is(false)); + } else if (count[0] == 1) { + assertThat( + event.getData(), + is("data:{\"FinalitySignature\":{\"block_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\"," + + "\"era_id\":0,\"signature\":\"0141eba160bb11448c663aa574de7a87554adb01531b1c6e93f31d4e998d5e5b4bdd71aa67442e3e5ffd8c75f709ad68ecbec9f116f4c50c49198098d30486dc02\"," + + "\"public_key\":\"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565\"}}") + ); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(1L)); + } + count[0]++; + }); + + assertThat(count[0], is(5)); + } + + + @Test + void mainPojoEvents() { + + mockNode.setDispatcher( + new PathMatchingResourceDispatcher(MAIN_EVENTS, is("/events/main?start_from=0")) + ); + + int[] count = {0}; + eventService.readEventStream(EventType.MAIN, EventTarget.POJO, 0L).forEach(e -> { + + //noinspection unchecked,rawtypes + final Event event = (Event) e; + assertThat(event.getEventType(), is(EventType.MAIN)); + + EventData data = event.getData(); + + if (count[0] == 0) { + assertThat(data, instanceOf(ApiVersion.class)); + assertThat(((ApiVersion) data).getApiVersion(), is("1.0.0")); + assertThat(event.getId().isPresent(), is(false)); + } else if (count[0] == 1) { + assertThat(data, instanceOf(Step.class)); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(0L)); + } + + count[0]++; + }); + + assertThat(count[0], is(greaterThan(2))); + + } +} \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java b/src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java new file mode 100644 index 000000000..8c31cf206 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java @@ -0,0 +1,68 @@ +package com.casper.sdk.service.impl.event; + +import com.casper.sdk.model.event.Event; +import com.casper.sdk.model.event.EventType; + +import java.util.Objects; +import java.util.Optional; + +/** + * The abstract base class implementation for all events + * + * @param the type of the event data + * + * @author ian@meywood.com + */ +abstract class AbstractEvent implements Event { + + /** + * The ID of the event + */ + private final Long id; + private final EventType eventType; + /** + * The event data + */ + private final T data; + + protected AbstractEvent(final EventType eventType, final T data, final Long id) { + this.eventType = eventType; + this.data = data; + this.id = id; + } + + + public EventType getEventType() { + return eventType; + } + + public T getData() { + return data; + } + + public Optional getId() { + return Optional.ofNullable(id); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "{" + + ", eventType='" + eventType + '\'' + + ", id=" + id + + ", data=" + data + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + final AbstractEvent that = (AbstractEvent) o; + return Objects.equals(id, that.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } +} diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java new file mode 100644 index 000000000..b760c5212 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java @@ -0,0 +1,127 @@ +package com.casper.sdk.service.impl.event; + + +import com.casper.sdk.model.event.Event; +import com.casper.sdk.model.event.EventTarget; +import com.casper.sdk.model.event.EventType; +import com.casper.sdk.exception.CasperClientException; +import com.casper.sdk.model.event.EventData; +import com.casper.sdk.model.event.shutdown.Shutdown; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.jetbrains.annotations.NotNull; + +/** + * Builds events from the lines read from a node + * + * @author ian@meywood.com + */ +final class EventBuilder { + + public static final String DATA = "data:"; + public static final String ID = "id:"; + public static final String API_VERSION = "ApiVersion"; + public static final String SHUTDOWN = "\"Shutdown\""; + /** The most recent ID read from an event stream */ + private Long id; + /** The line of data read from an event stream */ + private String data; + /** The type of data being read */ + private final EventType eventType; + /** The target type of the event to build */ + private final EventTarget eventTarget; + /** Indicates if an ID line is expected for the current data line */ + private boolean idExpected = true; + /** Used to build the pojo model objects from the JSON in the data line */ + private final ObjectMapper mapper; + + EventBuilder(final EventType eventType, final EventTarget eventTarget) { + this.eventType = eventType; + this.eventTarget = eventTarget; + mapper = new ObjectMapper(); + } + + boolean isComplete() { + return (id != null || !idExpected) && data != null; + } + + boolean processLine(final String line) { + try { + + if (line.startsWith(DATA)) { + this.data = line; + idExpected = isIdExpected(line); + } + + if (isId(line)) { + this.id = getId(line); + } + + return isComplete(); + } catch (Exception e) { + throw new CasperClientException(e.getMessage(), e); + } + } + + private boolean isIdExpected(String line) { + return !isApiVersion(line); + } + + private boolean isId(final String line) { + return line.startsWith(ID); + } + + private Long getId(final String line) { + return Long.valueOf(line.substring(ID.length())); + } + + private boolean isApiVersion(final String line) { + return line.contains(API_VERSION); + } + + @SuppressWarnings("rawtypes") + T buildEvent() { + + final T event; + if (this.eventTarget == EventTarget.RAW) { + //noinspection unchecked + event = (T) new RawEvent(eventType, data, id); + } else if (eventTarget == EventTarget.POJO) { + //noinspection unchecked + event = (T) buildPojoEvent(); + } else { + throw new IllegalArgumentException("Unsupported eventTarget: " + eventTarget); + } + reset(); + return event; + } + + @NotNull + private PojoEvent buildPojoEvent() { + final PojoEvent event; + try { + // Remove the "data:" prefix from the line + final String value = data.substring(DATA.length()).trim(); + + final EventRoot root; + if (SHUTDOWN.equals(value)) { + // Shutdown is text value, so we need to manually convert + //noinspection unchecked + root = new EventRoot<>((T) new Shutdown()); + } else { + //noinspection unchecked + root = mapper.readValue(value, EventRoot.class); + } + event = new PojoEvent<>(eventType, EventRoot.getData(root), id); + } catch (JsonProcessingException e) { + throw new CasperClientException("Error building POJO event for: " + data, e); + } + return event; + } + + private void reset() { + this.data = null; + this.id = null; + this.idExpected = true; + } +} diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java new file mode 100644 index 000000000..466d846a5 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -0,0 +1,236 @@ +package com.casper.sdk.service.impl.event; + + +import com.casper.sdk.exception.InvalidByteStringException; +import com.casper.sdk.model.common.Digest; +import com.casper.sdk.model.event.Event; +import com.casper.sdk.model.event.EventTarget; +import com.casper.sdk.model.event.EventType; +import com.casper.sdk.model.event.blockadded.BlockAdded; +import com.casper.sdk.model.event.deployaccepted.DeployAccepted; +import com.casper.sdk.model.event.deployexpired.DeployExpired; +import com.casper.sdk.model.event.deployprocessed.DeployProcessed; +import com.casper.sdk.model.event.fault.Fault; +import com.casper.sdk.model.event.finalitysignature.FinalitySignature; +import com.casper.sdk.model.event.shutdown.Shutdown; +import com.casper.sdk.model.event.step.Step; +import com.casper.sdk.model.event.version.ApiVersion; +import com.casper.sdk.model.key.PublicKey; +import org.joda.time.DateTime; +import org.junit.jupiter.api.Test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.math.BigInteger; +import java.security.NoSuchAlgorithmException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; +import static org.hamcrest.core.StringEndsWith.endsWith; +import static org.hamcrest.core.StringStartsWith.startsWith; + +class EventBuilderTest { + + private static final String BLOCK_ADDED_EVENT = "event-samples/block-added-event.txt"; + + private static final String DEPLOY_ACCEPTED_EVENT = "event-samples/deploy-accepted-event.txt"; + private static final String DEPLOY_EXPIRED_EVENT = "event-samples/deploy-expired-event.txt"; + + private static final String FINALITY_SIGNATURE_EVENT = "event-samples/finality-signature-event.txt"; + + private static final String STEP_EVENT = "event-samples/step-event.txt"; + + private static final String DEPLOY_PROCESSED_EVENT = "event-samples/deploy-processed-event.txt"; + + private static final String API_VERSION_EVENT = "event-samples/api-version-event.txt"; + + private static final String FAULT_EVENT = "event-samples/fault-event.txt"; + + private static final String SHUTDOWN_EVENT = "event-samples/shutdown-event.txt"; + + + @Test + void buildRawMainEvent() throws IOException { + + final AbstractEvent abstractEvent = getEvent(EventType.MAIN, EventTarget.RAW, BLOCK_ADDED_EVENT); + + assertThat(abstractEvent, instanceOf(RawEvent.class)); + assertThat(abstractEvent.getEventType(), is(EventType.MAIN)); + assertThat(abstractEvent.getId().isPresent(), is(true)); + assertThat(abstractEvent.getId().get(), is(2L)); + assertThat(abstractEvent.getData().toString(), startsWith("data:{\"BlockAdded\":{\"block_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\",\"block\":")); + assertThat(abstractEvent.getData().toString(), endsWith("\"transfer_hashes\":[]},\"proofs\":[]}}}")); + } + + @Test + void buildApiVersionEvent() throws IOException { + + final InputStream in = EventBuilderTest.class.getClassLoader().getResourceAsStream(API_VERSION_EVENT); + final EventBuilder builder = new EventBuilder(EventType.MAIN, EventTarget.POJO); + final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + builder.processLine(reader.readLine()); + + assertThat(builder.isComplete(), is(true)); + final AbstractEvent abstractEvent = builder.buildEvent(); + assertThat(builder.isComplete(), is(false)); + + assertThat(abstractEvent, instanceOf(PojoEvent.class)); + assertThat(abstractEvent.getData(), instanceOf(ApiVersion.class)); + + final ApiVersion apiVersion = abstractEvent.getData(); + assertThat(apiVersion.getApiVersion(), is("1.0.0")); + } + + @Test + void buildPojoBlockAddedMainEvent() throws IOException, InvalidByteStringException, NoSuchAlgorithmException { + + final AbstractEvent abstractEvent = getEvent(EventType.MAIN, EventTarget.POJO, BLOCK_ADDED_EVENT); + + assertThat(abstractEvent, instanceOf(PojoEvent.class)); + assertThat(abstractEvent.getData(), instanceOf(BlockAdded.class)); + + final BlockAdded blockAdded = abstractEvent.getData(); + assertThat(blockAdded.getBlockHash(), is(new Digest("bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c"))); + + assertThat(blockAdded.getBlock().getHash(), is(new Digest("bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c"))); + + assertThat(blockAdded.getBlock().getHeader().getParentHash(), is(new Digest("0000000000000000000000000000000000000000000000000000000000000000"))); + assertThat(blockAdded.getBlock().getHeader().getStateRootHash(), is(new Digest("fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc"))); + assertThat(blockAdded.getBlock().getHeader().getBodyHash(), is(new Digest("5187b7a8021bf4f2c004ea3a54cfece1754f11c7624d2363c7f4cf4fddd1441e"))); + assertThat(blockAdded.getBlock().getHeader().isRandomBit(), is(false)); + assertThat(blockAdded.getBlock().getHeader().getAccumulatedSeed(), is(new Digest("d8908c165dee785924e7421a0fd0418a19d5daeec395fd505a92a0fd3117e428"))); + assertThat(blockAdded.getBlock().getHeader().getEraEnd().getEraReport().getEquivocators().isEmpty(), is(true)); + assertThat(blockAdded.getBlock().getHeader().getEraEnd().getEraReport().getRewards().isEmpty(), is(true)); + assertThat(blockAdded.getBlock().getHeader().getEraEnd().getEraReport().getInactiveValidators().isEmpty(), is(true)); + assertThat(blockAdded.getBlock().getHeader().getEraEnd().getNextEraValidatorWeights().isEmpty(), is(false)); + assertThat(blockAdded.getBlock().getHeader().getEraEnd().getNextEraValidatorWeights(), hasSize(5)); + assertThat(blockAdded.getBlock().getHeader().getEraEnd().getNextEraValidatorWeights().get(4).getValidator(), is (PublicKey.fromTaggedHexString("01fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25"))); + assertThat(blockAdded.getBlock().getHeader().getEraEnd().getNextEraValidatorWeights().get(4).getWeight(), is(new BigInteger("2000000000000008"))); + assertThat(blockAdded.getBlock().getHeader().getTimeStamp(), is(new DateTime("2022-07-22T16:56:37.891Z").toDate())); + assertThat(blockAdded.getBlock().getHeader().getEraId(), is(0L)); + assertThat(blockAdded.getBlock().getHeader().getHeight(), is(0L)); + assertThat(blockAdded.getBlock().getHeader().getProtocolVersion(), is("1.0.0")); + assertThat(blockAdded.getBlock().getBody().getProposer(), is(nullValue())); + assertThat(blockAdded.getBlock().getBody().getDeployHashes().isEmpty(), is(true)); + assertThat(blockAdded.getBlock().getBody().getTransferHashes().isEmpty(), is(true)); + assertThat(blockAdded.getBlock().getProofs().isEmpty(), is(true)); + } + + @Test + void buildFinalitySignatureSigEvent() throws IOException, InvalidByteStringException, NoSuchAlgorithmException { + + final PojoEvent abstractEvent = getEvent(EventType.SIGS, EventTarget.POJO, FINALITY_SIGNATURE_EVENT); + assertThat(abstractEvent.getData(), instanceOf(FinalitySignature.class)); + + final FinalitySignature finalitySignature = abstractEvent.getData(); + assertThat(finalitySignature.getBlockHash(), is(new Digest("bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c"))); + assertThat(finalitySignature.getEraId(), is(0L)); + assertThat(finalitySignature.getSignature(), is("0141eba160bb11448c663aa574de7a87554adb01531b1c6e93f31d4e998d5e5b4bdd71aa67442e3e5ffd8c75f709ad68ecbec9f116f4c50c49198098d30486dc02")); + assertThat(finalitySignature.getPublicKey(), is(PublicKey.fromTaggedHexString("01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565"))); + } + + + @Test + void buildDeployAcceptedEvent() throws IOException { + + final PojoEvent deployAcceptedEvent = getEvent(EventType.MAIN, EventTarget.POJO, DEPLOY_ACCEPTED_EVENT); + assertThat(deployAcceptedEvent, is(notNullValue())); + assertThat(deployAcceptedEvent.getData(), is(instanceOf(DeployAccepted.class))); + + final DeployAccepted deployAccepted = deployAcceptedEvent.getData(); + assertThat(deployAccepted.getDeploy(), is(notNullValue())); + assertThat(deployAccepted.getDeploy().getHash(), is(new Digest("fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087"))); + + // TODO rest of fields + } + + @Test + void buildDeployProcessedEvent() throws IOException { + + final PojoEvent deployProcessedEvent = getEvent(EventType.MAIN, EventTarget.POJO, DEPLOY_PROCESSED_EVENT); + assertThat(deployProcessedEvent, is(notNullValue())); + assertThat(deployProcessedEvent.getData(), is(instanceOf(DeployAccepted.class))); + + final DeployProcessed deployProcessed = deployProcessedEvent.getData(); + assertThat(deployProcessed.getBlockHash(), is(new Digest("fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087"))); + assertThat(deployProcessed.getAccount(), is(new Digest("01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565"))); + + // TODO rest of fields + } + + @Test + void buildDeployExpiredEvent() throws IOException { + + final PojoEvent deployProcessedEvent = getEvent(EventType.MAIN, EventTarget.POJO, DEPLOY_EXPIRED_EVENT); + assertThat(deployProcessedEvent, is(notNullValue())); + assertThat(deployProcessedEvent.getData(), is(instanceOf(DeployExpired.class))); + + final DeployExpired deployProcessed = deployProcessedEvent.getData(); + assertThat(deployProcessed.getDeployHash(), is(new Digest("7ecf22fc284526c6db16fb6455f489e0a9cbf782834131c010cf3078fb9be353"))); + } + + @Test + void buildFaultEvent() throws IOException, InvalidByteStringException, NoSuchAlgorithmException { + + final PojoEvent faultPojoEvent = getEvent(EventType.MAIN, EventTarget.POJO, FAULT_EVENT); + assertThat(faultPojoEvent, is(notNullValue())); + assertThat(faultPojoEvent.getData(), instanceOf(Fault.class)); + + final Fault fault = faultPojoEvent.getData(); + assertThat(fault.getEraId(), is(4591448806312642506L)); + assertThat(fault.getPublicKey(), is(PublicKey.fromTaggedHexString("012fa85eb06279da42e68530e1116be04bfd2aaa5ed8d63401ebff4d9153a609a9"))); + assertThat(fault.getTimestamp(), is("2020-08-07T01:26:58.364Z")); + } + + @Test + void buildStepEvent() throws IOException { + + final PojoEvent stepEvent = getEvent(EventType.MAIN, EventTarget.POJO, STEP_EVENT); + assertThat(stepEvent, is(notNullValue())); + } + + + @Test + void buildRawShutDownEvent() throws IOException { + + final RawEvent shutdownEvent = getEvent(EventType.MAIN, EventTarget.RAW, SHUTDOWN_EVENT); + assertThat(shutdownEvent, is(notNullValue())); + assertThat(shutdownEvent.getData(), is("data:\"Shutdown\"")); + } + + @Test + void buildPojoShutDownEvent() throws IOException { + + final PojoEvent shutdownEvent = getEvent(EventType.MAIN, EventTarget.POJO, SHUTDOWN_EVENT); + assertThat(shutdownEvent, is(notNullValue())); + } + + private > T getEvent(final EventType eventType, + final EventTarget eventTarget, + final String eventPath) throws IOException { + + final InputStream in = EventBuilderTest.class.getClassLoader().getResourceAsStream(eventPath); + final EventBuilder builder = new EventBuilder(eventType, eventTarget); + final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + + builder.processLine(reader.readLine()); + assertThat(builder.isComplete(), is(false)); + builder.processLine(reader.readLine()); + assertThat(builder.isComplete(), is(true)); + + final T e = builder.buildEvent(); + + // Assert builder has reset + assertThat(builder.isComplete(), is(false)); + + return e; + } + + +} \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventRoot.java b/src/test/java/com/casper/sdk/service/impl/event/EventRoot.java new file mode 100644 index 000000000..6db030bde --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/EventRoot.java @@ -0,0 +1,153 @@ +package com.casper.sdk.service.impl.event; + + +import com.casper.sdk.model.event.EventData; +import com.casper.sdk.model.event.blockadded.BlockAdded; +import com.casper.sdk.model.event.deployaccepted.DeployAccepted; +import com.casper.sdk.model.event.deployexpired.DeployExpired; +import com.casper.sdk.model.event.deployprocessed.DeployProcessed; +import com.casper.sdk.model.event.fault.Fault; +import com.casper.sdk.model.event.finalitysignature.FinalitySignature; +import com.casper.sdk.model.event.shutdown.Shutdown; +import com.casper.sdk.model.event.step.Step; +import com.casper.sdk.model.event.version.ApiVersion; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A root holder to allow parsing of the Pojo data as the top level element contains the actual data as a named element eg: + * + *
{ BlockAdded: { block_hash: "6fa8d0ad18289e9a0f45993b9201560820b70d92521c5670b02dc2cf7d512ab8"}}
+ * + * @param the type of the data + * + * @author ian@meywood.com + */ +final class EventRoot { + + public T data; + + @SuppressWarnings("unused") + public EventRoot() { + // Default constructor needed for Jackson deserialization + } + + public EventRoot(final T data) { + this.data = data; + } + + /** + * Setter for ApiVersion due to @JsonAlias not working as expected + * + * @param apiVersion the apiVersion to set as data + */ + @JsonProperty("ApiVersion") + public void setApiVersion(final ApiVersion apiVersion) { + //noinspection unchecked + this.data = (T) apiVersion; + } + + /** + * Setter for BlockAdded due to @JsonAlias not working as expected + * + * @param blockAdded the blockAdded to set as data + */ + @JsonProperty("BlockAdded") + public void setBlockAdded(final BlockAdded blockAdded) { + //noinspection unchecked + this.data = (T) blockAdded; + } + + /** + * Setter for FinalitySignature due to @JsonAlias not working as expected + * + * @param finalitySignature the blockAdded to set as data + */ + @JsonProperty("FinalitySignature") + public void setFinalitySignature(final FinalitySignature finalitySignature) { + //noinspection unchecked + this.data = (T) finalitySignature; + } + + /** + * Setter for DeployAccepted due to @JsonAlias not working as expected + * + * @param deployAccepted the deployAccepted to set as data + */ + @JsonProperty("DeployAccepted") + public void setDeployAccepted(final DeployAccepted deployAccepted) { + //noinspection unchecked + this.data = (T) deployAccepted; + } + + /** + * Setter for DeployProcessed due to @JsonAlias not working as expected + * + * @param deployProcessed the deployProcessed to set as data + */ + @JsonProperty("DeployProcessed") + public void setDeployProcessed(final DeployProcessed deployProcessed) { + //noinspection unchecked + this.data = (T) deployProcessed; + } + + /** + * Setter for DeployExpired due to @JsonAlias not working as expected + * + * @param deployExpired the deployExpired to set as data + */ + @JsonProperty("DeployExpired") + public void setDeployExpired(final DeployExpired deployExpired) { + //noinspection unchecked + this.data = (T) deployExpired; + } + + /** + * Setter for Fault due to @JsonAlias not working as expected + * + * @param fault the fault to set as data + */ + @JsonProperty("Fault") + public void setFault(final Fault fault) { + //noinspection unchecked + this.data = (T) fault; + } + + /** + * Setter for Shutdown due to @JsonAlias not working as expected + * + * @param shutdown the shutdown to set as data + */ + @JsonProperty("Shutdown") + public void setShutdown(final Shutdown shutdown) { + //noinspection unchecked + this.data = (T) shutdown; + } + + /** + * Setter for Step due to @JsonAlias not working as expected + * + * @param step the step to set as data + */ + @JsonProperty("Step") + public void setStep(final Step step) { + //noinspection unchecked + this.data = (T) step; + } + + + public static E getData(@SuppressWarnings("rawtypes") final EventRoot pojoData) { + //noinspection unchecked + return pojoData != null ? (E) pojoData.data : null; + } + + public T getData() { + return data; + } + + @Override + public String toString() { + return "{" + + "data=" + data + + '}'; + } +} diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java b/src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java new file mode 100644 index 000000000..da72d8ec0 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java @@ -0,0 +1,97 @@ +package com.casper.sdk.service.impl.event; + +import com.casper.sdk.model.event.Event; +import com.casper.sdk.model.event.EventTarget; +import com.casper.sdk.model.event.EventType; +import com.casper.sdk.exception.CasperClientException; +import com.casper.sdk.service.EventService; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.URI; +import java.time.Duration; +import java.util.stream.Stream; + +/** + * Package local to prevent construction. + * + * @author ian@meywood.com + */ +@SuppressWarnings("unused") +final class EventServiceImpl implements EventService { + + /** The mime type for JSON */ + private static final String APPLICATION_JSON = "application/json"; + public static final String ACCEPT = "Accept"; + public static final String CONTENT_TYPE = "Content-Type"; + + /** Build the URLs for event get requests */ + private final EventUrlBuilder urlBuilder = new EventUrlBuilder(); + + /** The URI of the node to request events from */ + private final URI uri; + + /** The HTTP Client to connect to the node with */ + final OkHttpClient client; + + @SuppressWarnings("unused") + private EventServiceImpl(final String host) { + this(URI.create(host)); + } + + private EventServiceImpl(final URI uri) { + this.uri = uri; + + this.client = new OkHttpClient.Builder() + .connectTimeout(Duration.ofDays(1)) + .readTimeout(Duration.ofDays(1)) + .build(); + } + + /** {@inheritDoc} */ + @Override + public > Stream readEventStream(final EventType eventType, + final EventTarget eventTarget, + final Long startFrom) { + try { + //noinspection resource + final Response response = this.client.newCall( + new Request.Builder() + .url(urlBuilder.buildUrl(uri, eventType, startFrom)) + .header(ACCEPT, APPLICATION_JSON) + .header(CONTENT_TYPE, APPLICATION_JSON) + .get() + .build() + ).execute(); + + if (response.isSuccessful() && response.body() != null) { + //noinspection ConstantConditions + return readEvent(eventType, eventTarget, new InputStreamReader(response.body().byteStream())); + } else { + throw new CasperClientException("No response from node " + this.uri); + } + } catch (IOException e) { + throw new CasperClientException("Error executing request against node" + this.uri, e); + } + } + + /** {@inheritDoc} */ + @Override + public > Stream readEvent(final EventType eventType, + final EventTarget eventTarget, + final Reader reader) { + + final EventBuilder eventBuilder = new EventBuilder(eventType, eventTarget); + + //noinspection unchecked + return new BufferedReader(reader) + .lines() + .filter(eventBuilder::processLine) + .map(line -> eventBuilder.buildEvent()); + } +} diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java b/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java new file mode 100644 index 000000000..2468b6e79 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java @@ -0,0 +1,50 @@ +package com.casper.sdk.service.impl.event; + +import com.casper.sdk.model.event.EventType; +import com.casper.sdk.exception.CasperClientException; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; + +/** + * Class for building event URLs + */ +final class EventUrlBuilder { + + /** + * The root path to the events stream + */ + private static final String EVENTS = "/events/"; + /** + * The start_from parameter that allow the specification of which ID to start from + */ + public static final String START_FROM = "start_from"; + + /** + * Builds an event URL + * + * @param uri the URI to the host + * @param eventType the type of event to build a URL for + * @param startFrom the optional 'start_from' URL query parameter will be omitted if null + * @return the URL for the requested parameters + */ + URL buildUrl(final URI uri, final EventType eventType, final Long startFrom) { + + try { + return new URL(uri.toString() + EVENTS + eventType.toString().toLowerCase() + buildParams(startFrom)); + } catch (MalformedURLException e) { + throw new CasperClientException("Error building URL for " + uri, e); + } + } + + private String buildParams(final Long startFrom) { + if (startFrom != null) { + return '?' + START_FROM + '=' + startFrom; + } else { + return ""; + } + } + + +} diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilderTest.java new file mode 100644 index 000000000..b918ded78 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilderTest.java @@ -0,0 +1,44 @@ +package com.casper.sdk.service.impl.event; + +import com.casper.sdk.model.event.EventType; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.net.URISyntaxException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +/** + * Unit tests for the EventUrlBuilder + * + * @author ian@meywood.com + */ +class EventUrlBuilderTest { + + private final EventUrlBuilder eventUrlBuilder = new EventUrlBuilder(); + + @Test + void buildMainEventUrl() throws URISyntaxException { + + URI uri = new URI("https://localhost:18101"); + assertThat(eventUrlBuilder.buildUrl(uri, EventType.MAIN, null).toString(), is("https://localhost:18101/events/main")); + assertThat(eventUrlBuilder.buildUrl(uri, EventType.MAIN, 1L).toString(), is("https://localhost:18101/events/main?start_from=1")); + } + + @Test + void buildDeploysEventUrl() throws URISyntaxException { + + URI uri = new URI("https://localhost:18101"); + assertThat(eventUrlBuilder.buildUrl(uri, EventType.DEPLOYS, null).toString(), is("https://localhost:18101/events/deploys")); + assertThat(eventUrlBuilder.buildUrl(uri, EventType.DEPLOYS, 99L).toString(), is("https://localhost:18101/events/deploys?start_from=99")); + } + + @Test + void buildSigsEventUrl() throws URISyntaxException { + + URI uri = new URI("https://localhost:18101"); + assertThat(eventUrlBuilder.buildUrl(uri, EventType.SIGS, null).toString(), is("https://localhost:18101/events/sigs")); + assertThat(eventUrlBuilder.buildUrl(uri, EventType.SIGS, 3L).toString(), is("https://localhost:18101/events/sigs?start_from=3")); + } +} \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java b/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java new file mode 100644 index 000000000..bfd5e00db --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java @@ -0,0 +1,19 @@ +package com.casper.sdk.service.impl.event; + +import com.casper.sdk.model.event.EventType; +import com.casper.sdk.model.event.EventData; +import com.casper.sdk.model.event.EventTarget; + +/** + * An event that contains the event data as Pojo model returned from the event service when + * {@link EventTarget#POJO} is requested. + * + * @param the types of the expected EventData + * @author ian@meywood.com + */ +final class PojoEvent extends AbstractEvent { + + PojoEvent(final EventType eventType, T data, final Long id) { + super(eventType, data, id); + } +} diff --git a/src/test/java/com/casper/sdk/service/impl/event/RawEvent.java b/src/test/java/com/casper/sdk/service/impl/event/RawEvent.java new file mode 100644 index 000000000..ebb78358d --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/RawEvent.java @@ -0,0 +1,17 @@ +package com.casper.sdk.service.impl.event; + +import com.casper.sdk.model.event.EventType; +import com.casper.sdk.model.event.EventTarget; + +/** + * An event that contains the event data as raw JSON without the 'data:' prefix is returned from the event service when + * a {@link EventTarget#RAW} is requested. + * + * @author ian@meywood.com + */ +final class RawEvent extends AbstractEvent { + + RawEvent(final EventType eventType, final String data, final Long id) { + super(eventType, data, id); + } +} diff --git a/src/test/java/com/casper/sdk/test/MockNode.java b/src/test/java/com/casper/sdk/test/MockNode.java new file mode 100644 index 000000000..b507c041f --- /dev/null +++ b/src/test/java/com/casper/sdk/test/MockNode.java @@ -0,0 +1,30 @@ +package com.casper.sdk.test; + +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockWebServer; + +import java.io.IOException; +import java.net.URI; + +/** + * Provides a mock node that can be used for integration testing with having to spin up a real CSPR Node. + * + * @author ian@meywood.com + */ +public class MockNode { + + private final MockWebServer mockWebServer = new MockWebServer(); + + public void start(final URI url) throws IOException { + mockWebServer.start(url.getPort()); + } + + public void shutdown() throws IOException { + mockWebServer.shutdown(); + } + + public void setDispatcher(final Dispatcher dispatcher) { + mockWebServer.setDispatcher(dispatcher); + } + +} \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/test/PathMatchingResourceDispatcher.java b/src/test/java/com/casper/sdk/test/PathMatchingResourceDispatcher.java new file mode 100644 index 000000000..c28dfae04 --- /dev/null +++ b/src/test/java/com/casper/sdk/test/PathMatchingResourceDispatcher.java @@ -0,0 +1,46 @@ +package com.casper.sdk.test; + +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.RecordedRequest; +import okio.Buffer; +import org.hamcrest.Matcher; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.io.InputStream; + +public class PathMatchingResourceDispatcher extends Dispatcher { + + /** The path to the resource to use */ + private final String resourcePath; + /** The matcher for the URL request path */ + private final Matcher pathMatcher; + + public PathMatchingResourceDispatcher(final String resourcePath, final Matcher pathMatcher) { + this.resourcePath = resourcePath; + this.pathMatcher = pathMatcher; + } + + @NotNull + @Override + public MockResponse dispatch(@NotNull final RecordedRequest recordedRequest) { + + if (pathMatcher.matches(recordedRequest.getPath())) { + + //noinspection ConstantConditions + try (final InputStream in = PathMatchingResourceDispatcher.class.getResourceAsStream(resourcePath); + final Buffer buffer = new Buffer().readFrom(in)) { + + return new MockResponse().setResponseCode(200) + .addHeader("Content-Type", "application/json") + .setBody(buffer); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else { + // return not found if no match + return new MockResponse().setResponseCode(404); + } + } +} diff --git a/src/test/resources/event-samples/api-version-event.txt b/src/test/resources/event-samples/api-version-event.txt new file mode 100644 index 000000000..e19ef4456 --- /dev/null +++ b/src/test/resources/event-samples/api-version-event.txt @@ -0,0 +1 @@ +data:{"ApiVersion":"1.0.0"} diff --git a/src/test/resources/event-samples/block-added-event.txt b/src/test/resources/event-samples/block-added-event.txt new file mode 100644 index 000000000..b98c4a5e9 --- /dev/null +++ b/src/test/resources/event-samples/block-added-event.txt @@ -0,0 +1,2 @@ +data:{"BlockAdded":{"block_hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","block":{"hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","header":{"parent_hash":"0000000000000000000000000000000000000000000000000000000000000000","state_root_hash":"fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc","body_hash":"5187b7a8021bf4f2c004ea3a54cfece1754f11c7624d2363c7f4cf4fddd1441e","random_bit":false,"accumulated_seed":"d8908c165dee785924e7421a0fd0418a19d5daeec395fd505a92a0fd3117e428","era_end":{"era_report":{"equivocators":[],"rewards":[],"inactive_validators":[]},"next_era_validator_weights":[{"validator":"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5","weight":"2000000000000004"},{"validator":"011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852","weight":"2000000000000006"},{"validator":"0180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b","weight":"2000000000000010"},{"validator":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565","weight":"2000000000000002"},{"validator":"01fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25","weight":"2000000000000008"}]},"timestamp":"2022-07-22T16:56:37.891Z","era_id":0,"height":0,"protocol_version":"1.0.0"},"body":{"proposer":"00","deploy_hashes":[],"transfer_hashes":[]},"proofs":[]}}} +id:2 \ No newline at end of file diff --git a/src/test/resources/event-samples/deploy-accepted-event.txt b/src/test/resources/event-samples/deploy-accepted-event.txt new file mode 100644 index 000000000..b5e6859ac --- /dev/null +++ b/src/test/resources/event-samples/deploy-accepted-event.txt @@ -0,0 +1,2 @@ +data:{"DeployAccepted":{"hash":"fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087","header":{"account":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565","timestamp":"2022-07-26T14:37:15.150Z","ttl":"30m","gas_price":10,"body_hash":"c2930c761cdc90241e7bfd2c5bbc5805ec9511845cb4820f997fa57334a33723","dependencies":[],"chain_name":"casper-net-1"},"payment":{"ModuleBytes":{"module_bytes":"","args":[["amount",{"cl_type":"U512","bytes":"0500e40b5402","parsed":"10000000000"}]]}},"session":{"Transfer":{"args":[["amount",{"cl_type":"U512","bytes":"0400f90295","parsed":"2500000000"}],["target",{"cl_type":{"ByteArray":32},"bytes":"a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67","parsed":"a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67"}],["id",{"cl_type":{"Option":"U64"},"bytes":"010100000000000000","parsed":1}]]}},"approvals":[{"signer":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565","signature":"01e57c01fc538fe057eac09d55360c70b6b7830548582c9931832af78149c66a698a41f33ca06904898138bda6767cfc5f60f26a11980ad5f95f489dcccc2fa80d"}]}} +id:2951 \ No newline at end of file diff --git a/src/test/resources/event-samples/deploy-expired-event.txt b/src/test/resources/event-samples/deploy-expired-event.txt new file mode 100644 index 000000000..e946eb980 --- /dev/null +++ b/src/test/resources/event-samples/deploy-expired-event.txt @@ -0,0 +1,2 @@ +data:{ "DeployExpired":{ "deploy_hash":"7ecf22fc284526c6db16fb6455f489e0a9cbf782834131c010cf3078fb9be353"}} +id:887 diff --git a/src/test/resources/event-samples/deploy-processed-event.txt b/src/test/resources/event-samples/deploy-processed-event.txt new file mode 100644 index 000000000..1fa0c718c --- /dev/null +++ b/src/test/resources/event-samples/deploy-processed-event.txt @@ -0,0 +1,2 @@ +data:{"DeployProcessed":{"deploy_hash":"fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087","account":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565","timestamp":"2022-07-26T14:37:15.150Z","ttl":"30m","dependencies":[],"block_hash":"5ae463abe56ebd37044600b90236d91fa93e3ff88d47f12a9c616d8b16ae9100","execution_result":{"Success":{"effect":{"operations":[],"transforms":[{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"account-hash-a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67","transform":"Identity"},{"key":"account-hash-a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-5ba9ce15ffc7429476de4e278d23362759e37cbdcafd1a8efb2f8bb475e8574e","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-090f97f668d33884974255ba853c74fdd5fb187ba6e48c0ac652f00e81b2b67f","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"balance-0eeb2bd99ae07173be21a5fc86db7a2ea7fae0abdfb5e81350bf52f22a66ea80","transform":"Identity"},{"key":"balance-3fc748c8cad37d3c5b65d3cd53b189ec4f3da23475ce4d3dae02bc08e63b8329","transform":"Identity"},{"key":"balance-0eeb2bd99ae07173be21a5fc86db7a2ea7fae0abdfb5e81350bf52f22a66ea80","transform":{"WriteCLValue":{"cl_type":"U512","bytes":"0e001f0afa095bc138938d44c64d31","parsed":"999999999999999999999999900000000"}}},{"key":"balance-3fc748c8cad37d3c5b65d3cd53b189ec4f3da23475ce4d3dae02bc08e63b8329","transform":{"AddUInt512":"100000000"}},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"account-hash-a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67","transform":"Identity"},{"key":"account-hash-a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-5ba9ce15ffc7429476de4e278d23362759e37cbdcafd1a8efb2f8bb475e8574e","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-090f97f668d33884974255ba853c74fdd5fb187ba6e48c0ac652f00e81b2b67f","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"balance-0eeb2bd99ae07173be21a5fc86db7a2ea7fae0abdfb5e81350bf52f22a66ea80","transform":"Identity"},{"key":"balance-3fc748c8cad37d3c5b65d3cd53b189ec4f3da23475ce4d3dae02bc08e63b8329","transform":"Identity"},{"key":"balance-0eeb2bd99ae07173be21a5fc86db7a2ea7fae0abdfb5e81350bf52f22a66ea80","transform":{"WriteCLValue":{"cl_type":"U512","bytes":"0e001f0afa095bc138938d44c64d31","parsed":"999999999999999999999999900000000"}}},{"key":"balance-3fc748c8cad37d3c5b65d3cd53b189ec4f3da23475ce4d3dae02bc08e63b8329","transform":{"AddUInt512":"100000000"}},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-090f97f668d33884974255ba853c74fdd5fb187ba6e48c0ac652f00e81b2b67f","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"balance-0eeb2bd99ae07173be21a5fc86db7a2ea7fae0abdfb5e81350bf52f22a66ea80","transform":"Identity"},{"key":"balance-05f54a84872c75f7f05c8e8aaf9338ec848fa1a5b4f07202e371955c982f7f60","transform":"Identity"},{"key":"balance-0eeb2bd99ae07173be21a5fc86db7a2ea7fae0abdfb5e81350bf52f22a66ea80","transform":{"WriteCLValue":{"cl_type":"U512","bytes":"0e00260765095bc138938d44c64d31","parsed":"999999999999999999999997400000000"}}},{"key":"balance-05f54a84872c75f7f05c8e8aaf9338ec848fa1a5b4f07202e371955c982f7f60","transform":{"AddUInt512":"2500000000"}},{"key":"transfer-bae0cec10eb82aa81af18a31393ff5d5023e25ea7ed820e978b8407ccc22160d","transform":{"WriteTransfer":{"deploy_hash":"fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087","from":"account-hash-59cbc880e6d1f7407f18c36393c33d47ae51d5a54258f94a837ff996bf25a34d","to":"account-hash-a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67","source":"uref-0eeb2bd99ae07173be21a5fc86db7a2ea7fae0abdfb5e81350bf52f22a66ea80-007","target":"uref-05f54a84872c75f7f05c8e8aaf9338ec848fa1a5b4f07202e371955c982f7f60-004","amount":"2500000000","gas":"0","id":1}}},{"key":"deploy-fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087","transform":{"WriteDeployInfo":{"deploy_hash":"fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087","transfers":["transfer-bae0cec10eb82aa81af18a31393ff5d5023e25ea7ed820e978b8407ccc22160d"],"from":"account-hash-59cbc880e6d1f7407f18c36393c33d47ae51d5a54258f94a837ff996bf25a34d","source":"uref-0eeb2bd99ae07173be21a5fc86db7a2ea7fae0abdfb5e81350bf52f22a66ea80-007","gas":"100000000"}}},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-5ba9ce15ffc7429476de4e278d23362759e37cbdcafd1a8efb2f8bb475e8574e","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"balance-3fc748c8cad37d3c5b65d3cd53b189ec4f3da23475ce4d3dae02bc08e63b8329","transform":"Identity"},{"key":"hash-c5cbbfd90319b74de3e147e33c17d480ea782bafa37e2a08b7dda37d3713e036","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-090f97f668d33884974255ba853c74fdd5fb187ba6e48c0ac652f00e81b2b67f","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"balance-3fc748c8cad37d3c5b65d3cd53b189ec4f3da23475ce4d3dae02bc08e63b8329","transform":"Identity"},{"key":"balance-8bd1ab925b4c91ea54b4aa6edadfd11d2be294cb64c59745258cb67e32aea67a","transform":"Identity"},{"key":"balance-3fc748c8cad37d3c5b65d3cd53b189ec4f3da23475ce4d3dae02bc08e63b8329","transform":{"WriteCLValue":{"cl_type":"U512","bytes":"00","parsed":"0"}}},{"key":"balance-8bd1ab925b4c91ea54b4aa6edadfd11d2be294cb64c59745258cb67e32aea67a","transform":{"AddUInt512":"100000000"}}]},"transfers":["transfer-bae0cec10eb82aa81af18a31393ff5d5023e25ea7ed820e978b8407ccc22160d"],"cost":"100000000"}}}} +id:2958 \ No newline at end of file diff --git a/src/test/resources/event-samples/deploys-events.txt b/src/test/resources/event-samples/deploys-events.txt new file mode 100644 index 000000000..11e5a6d95 --- /dev/null +++ b/src/test/resources/event-samples/deploys-events.txt @@ -0,0 +1,4 @@ +data:{"ApiVersion":"1.0.0"} + +data:{"DeployAccepted":{"hash":"fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087","header":{"account":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565","timestamp":"2022-07-26T14:37:15.150Z","ttl":"30m","gas_price":10,"body_hash":"c2930c761cdc90241e7bfd2c5bbc5805ec9511845cb4820f997fa57334a33723","dependencies":[],"chain_name":"casper-net-1"},"payment":{"ModuleBytes":{"module_bytes":"","args":[["amount",{"cl_type":"U512","bytes":"0500e40b5402","parsed":"10000000000"}]]}},"session":{"Transfer":{"args":[["amount",{"cl_type":"U512","bytes":"0400f90295","parsed":"2500000000"}],["target",{"cl_type":{"ByteArray":32},"bytes":"a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67","parsed":"a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67"}],["id",{"cl_type":{"Option":"U64"},"bytes":"010100000000000000","parsed":1}]]}},"approvals":[{"signer":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565","signature":"01e57c01fc538fe057eac09d55360c70b6b7830548582c9931832af78149c66a698a41f33ca06904898138bda6767cfc5f60f26a11980ad5f95f489dcccc2fa80d"}]}} +id:2951 \ No newline at end of file diff --git a/src/test/resources/event-samples/fault-event.txt b/src/test/resources/event-samples/fault-event.txt new file mode 100644 index 000000000..01d175b1f --- /dev/null +++ b/src/test/resources/event-samples/fault-event.txt @@ -0,0 +1,3 @@ +data:{"Fault":{ "era_id":4591448806312642506,"public_key":"012fa85eb06279da42e68530e1116be04bfd2aaa5ed8d63401ebff4d9153a609a9","timestamp":"2020-08-07T01:26:58.364Z"}} +id:1224 + diff --git a/src/test/resources/event-samples/finality-signature-event.txt b/src/test/resources/event-samples/finality-signature-event.txt new file mode 100644 index 000000000..f98ad0137 --- /dev/null +++ b/src/test/resources/event-samples/finality-signature-event.txt @@ -0,0 +1,2 @@ +data:{"FinalitySignature":{"block_hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","era_id":0,"signature":"0141eba160bb11448c663aa574de7a87554adb01531b1c6e93f31d4e998d5e5b4bdd71aa67442e3e5ffd8c75f709ad68ecbec9f116f4c50c49198098d30486dc02","public_key":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565"}} +id:1 \ No newline at end of file diff --git a/src/test/resources/event-samples/main-events.txt b/src/test/resources/event-samples/main-events.txt new file mode 100644 index 000000000..b76dfc344 --- /dev/null +++ b/src/test/resources/event-samples/main-events.txt @@ -0,0 +1,10 @@ +data:{"ApiVersion":"1.0.0"} + +data:{"Step":{"era_id":0,"execution_effect":{"operations":[],"transforms":[{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"hash-ddf9693d82abe59403f3862253286746444ae2c59e16065b61be9d39bcd1c021","transform":"Identity"},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":"Identity"},{"key":"uref-dd83e7fe133d4b08943547528c25d1219e6817520c5ba48ffcf8c2b4f6f16812-000","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-090f97f668d33884974255ba853c74fdd5fb187ba6e48c0ac652f00e81b2b67f","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"uref-69d5f69b9472d134060d2bdf76d5f8b7e612a3182f6653650b1077d1de1e0f3d-000","transform":"Identity"},{"key":"uref-5b51fc3660bb6d9fdf9facd1ba645f3aeb0fbb2ee152e24501f2a44a44714a11-000","transform":"Identity"},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":"Identity"},{"key":"era-0","transform":{"WriteEraInfo":{"seigniorage_allocations":[]}}},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"hash-ddf9693d82abe59403f3862253286746444ae2c59e16065b61be9d39bcd1c021","transform":"Identity"},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"uref-8a3276d1c526097993c38de881234cef522171ac9f92af2b056017d0bc9eea25-000","transform":"Identity"},{"key":"uref-76b110b04a0513a7ad237568c1845fefb38339e8e5883ae26ec5551079b0ca05-000","transform":"Identity"},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":"Identity"},{"key":"bid-3c64ec57707a0685c00b0068c687ee6d82c2fa36f63fc4503d48253c93ba3d10","transform":"Identity"},{"key":"bid-59cbc880e6d1f7407f18c36393c33d47ae51d5a54258f94a837ff996bf25a34d","transform":"Identity"},{"key":"bid-8d5998e9f6d5da25e76889d47841ba79bd8cca8c348a939cd1c459393105544e","transform":"Identity"},{"key":"bid-b5a727d071bc0a4920682bde11c62a94afafba1eb2be71aef306fdc4c4d2749f","transform":"Identity"},{"key":"bid-eb89ed102f0a5933a8ba4c9b093b8d37491a22020128ba0f087fde4aab90ca31","transform":"Identity"},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":"Identity"},{"key":"uref-02653fde6ec969034539d75048bfef571284bd488dc53c8be7197f3bb0dc9bb4-000","transform":"Identity"},{"key":"uref-dd83e7fe133d4b08943547528c25d1219e6817520c5ba48ffcf8c2b4f6f16812-000","transform":"Identity"},{"key":"uref-dd83e7fe133d4b08943547528c25d1219e6817520c5ba48ffcf8c2b4f6f16812-000","transform":{"WriteCLValue":{"cl_type":{"Map":{"key":"U64","value":{"Map":{"key":"PublicKey","value":"Any"}}}},"bytes":"04000000010000000000000005000000010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5070280c6a47e8d030201000000013372bd275423a2191f3fc11e1bee0419fcb4890319873f455bb462e02b199457070280c6a47e8d03011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852070380c6a47e8d03030100000001e45436d1609bd5c5ce13e8320a140421cf40a21089df1a08f7c58bcd06b6c9e4070380c6a47e8d030180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b070580c6a47e8d030501000000018973a4ffc17abab43f90bd229ef8a310236dd364ba0416d31612091d8cc17933070580c6a47e8d0301959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565070180c6a47e8d03010100000001a1cce6ea8db0d11d95b83671cc69f726b36aafb46dbf808c608dbcd5d237b11c070180c6a47e8d0301fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25070480c6a47e8d030401000000016997c57f973cd02df90941b7ace79d2b49e173f5f14a343cbf69a7a7ff8be3b5070480c6a47e8d03020000000000000005000000010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5070280c6a47e8d030201000000013372bd275423a2191f3fc11e1bee0419fcb4890319873f455bb462e02b199457070280c6a47e8d03011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852070380c6a47e8d03030100000001e45436d1609bd5c5ce13e8320a140421cf40a21089df1a08f7c58bcd06b6c9e4070380c6a47e8d030180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b070580c6a47e8d030501000000018973a4ffc17abab43f90bd229ef8a310236dd364ba0416d31612091d8cc17933070580c6a47e8d0301959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565070180c6a47e8d03010100000001a1cce6ea8db0d11d95b83671cc69f726b36aafb46dbf808c608dbcd5d237b11c070180c6a47e8d0301fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25070480c6a47e8d030401000000016997c57f973cd02df90941b7ace79d2b49e173f5f14a343cbf69a7a7ff8be3b5070480c6a47e8d03030000000000000005000000010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5070280c6a47e8d030201000000013372bd275423a2191f3fc11e1bee0419fcb4890319873f455bb462e02b199457070280c6a47e8d03011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852070380c6a47e8d03030100000001e45436d1609bd5c5ce13e8320a140421cf40a21089df1a08f7c58bcd06b6c9e4070380c6a47e8d030180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b070580c6a47e8d030501000000018973a4ffc17abab43f90bd229ef8a310236dd364ba0416d31612091d8cc17933070580c6a47e8d0301959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565070180c6a47e8d03010100000001a1cce6ea8db0d11d95b83671cc69f726b36aafb46dbf808c608dbcd5d237b11c070180c6a47e8d0301fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25070480c6a47e8d030401000000016997c57f973cd02df90941b7ace79d2b49e173f5f14a343cbf69a7a7ff8be3b5070480c6a47e8d03040000000000000005000000010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5070280c6a47e8d030201000000013372bd275423a2191f3fc11e1bee0419fcb4890319873f455bb462e02b199457070280c6a47e8d03011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852070380c6a47e8d03030100000001e45436d1609bd5c5ce13e8320a140421cf40a21089df1a08f7c58bcd06b6c9e4070380c6a47e8d030180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b070580c6a47e8d030501000000018973a4ffc17abab43f90bd229ef8a310236dd364ba0416d31612091d8cc17933070580c6a47e8d0301959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565070180c6a47e8d03010100000001a1cce6ea8db0d11d95b83671cc69f726b36aafb46dbf808c608dbcd5d237b11c070180c6a47e8d0301fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25070480c6a47e8d030401000000016997c57f973cd02df90941b7ace79d2b49e173f5f14a343cbf69a7a7ff8be3b5070480c6a47e8d03","parsed":null}}},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":{"WriteCLValue":{"cl_type":"U64","bytes":"0100000000000000","parsed":1}}},{"key":"uref-9b9e5674c62c6d6ea7e57ff6341f0e7ae99cb49c9588668fcf5ba1e7c2cf5110-000","transform":{"WriteCLValue":{"cl_type":"U64","bytes":"03f5d62682010000","parsed":1658508997891}}}]}}} +id:0 + +data:{"BlockAdded":{"block_hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","block":{"hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","header":{"parent_hash":"0000000000000000000000000000000000000000000000000000000000000000","state_root_hash":"fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc","body_hash":"5187b7a8021bf4f2c004ea3a54cfece1754f11c7624d2363c7f4cf4fddd1441e","random_bit":false,"accumulated_seed":"d8908c165dee785924e7421a0fd0418a19d5daeec395fd505a92a0fd3117e428","era_end":{"era_report":{"equivocators":[],"rewards":[],"inactive_validators":[]},"next_era_validator_weights":[{"validator":"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5","weight":"2000000000000004"},{"validator":"011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852","weight":"2000000000000006"},{"validator":"0180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b","weight":"2000000000000010"},{"validator":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565","weight":"2000000000000002"},{"validator":"01fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25","weight":"2000000000000008"}]},"timestamp":"2022-07-22T16:56:37.891Z","era_id":0,"height":0,"protocol_version":"1.0.0"},"body":{"proposer":"00","deploy_hashes":[],"transfer_hashes":[]},"proofs":[]}}} +id:2 + +data:{"BlockAdded":{"block_hash":"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534","block":{"hash":"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534","header":{"parent_hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","state_root_hash":"fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc","body_hash":"980531392fb02fd03d632abaa17f0a59bc788ea5b86ff9ce4630851cf9c2b4cf","random_bit":true,"accumulated_seed":"ab5d756563bf09545590bd95f9a8e7978d51760be95ea8e5c9bab58ba1129186","era_end":null,"timestamp":"2022-07-22T16:56:40.704Z","era_id":1,"height":1,"protocol_version":"1.0.0"},"body":{"proposer":"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5","deploy_hashes":[],"transfer_hashes":[]},"proofs":[]}}} +id:7 diff --git a/src/test/resources/event-samples/shutdown-event.txt b/src/test/resources/event-samples/shutdown-event.txt new file mode 100644 index 000000000..98910f6f9 --- /dev/null +++ b/src/test/resources/event-samples/shutdown-event.txt @@ -0,0 +1,2 @@ +data:"Shutdown" +id:13 diff --git a/src/test/resources/event-samples/sigs-events.txt b/src/test/resources/event-samples/sigs-events.txt new file mode 100644 index 000000000..85b2e2d5d --- /dev/null +++ b/src/test/resources/event-samples/sigs-events.txt @@ -0,0 +1,13 @@ +data:{"ApiVersion":"1.0.0"} + +data:{"FinalitySignature":{"block_hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","era_id":0,"signature":"0141eba160bb11448c663aa574de7a87554adb01531b1c6e93f31d4e998d5e5b4bdd71aa67442e3e5ffd8c75f709ad68ecbec9f116f4c50c49198098d30486dc02","public_key":"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565"}} +id:1 + +data:{"FinalitySignature":{"block_hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","era_id":0,"signature":"0184bad4379f9799546e534d47177f2ad7e34c56c9f85ff68737212cf67571406bb4eac4ec2f4755635957f454115de0f9de04bf03784cc2cac1c4ca079e38500e","public_key":"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5"}} +id:3 + +data:{"FinalitySignature":{"block_hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","era_id":0,"signature":"0166a5274d5960e626d2c9857d91944b62ac9ed707f66f3ad66ca7318c6adc996c23415080e726c40371b2b5c1967a15f27bc6dc652a185637c59c331781451b06","public_key":"011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852"}} +id:4 + +data:{"FinalitySignature":{"block_hash":"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c","era_id":0,"signature":"01d26e504a87525eb711064539257f06b7daaea1589e60be3dc31556ff0fe3a79a9dd964ff2ba283540272251a36d7ece0b1e40a9d044caf6b848361208daf840d","public_key":"01fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25"}} +id:5 diff --git a/src/test/resources/event-samples/step-event.txt b/src/test/resources/event-samples/step-event.txt new file mode 100644 index 000000000..e014e2955 --- /dev/null +++ b/src/test/resources/event-samples/step-event.txt @@ -0,0 +1,2 @@ +data:{"Step":{"era_id":0,"execution_effect":{"operations":[],"transforms":[{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"hash-ddf9693d82abe59403f3862253286746444ae2c59e16065b61be9d39bcd1c021","transform":"Identity"},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":"Identity"},{"key":"uref-dd83e7fe133d4b08943547528c25d1219e6817520c5ba48ffcf8c2b4f6f16812-000","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"hash-090f97f668d33884974255ba853c74fdd5fb187ba6e48c0ac652f00e81b2b67f","transform":"Identity"},{"key":"hash-b8527fd6de4c547f7afef1427094846b68a8762e61cf118bb69ea7e78b9e82d4","transform":"Identity"},{"key":"uref-69d5f69b9472d134060d2bdf76d5f8b7e612a3182f6653650b1077d1de1e0f3d-000","transform":"Identity"},{"key":"uref-5b51fc3660bb6d9fdf9facd1ba645f3aeb0fbb2ee152e24501f2a44a44714a11-000","transform":"Identity"},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":"Identity"},{"key":"era-0","transform":{"WriteEraInfo":{"seigniorage_allocations":[]}}},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"hash-ddf9693d82abe59403f3862253286746444ae2c59e16065b61be9d39bcd1c021","transform":"Identity"},{"key":"hash-0304486f396669cc1c40de707bbdc3884a9cdfaf21aa2557c814ed594566d771","transform":"Identity"},{"key":"uref-8a3276d1c526097993c38de881234cef522171ac9f92af2b056017d0bc9eea25-000","transform":"Identity"},{"key":"uref-76b110b04a0513a7ad237568c1845fefb38339e8e5883ae26ec5551079b0ca05-000","transform":"Identity"},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":"Identity"},{"key":"bid-3c64ec57707a0685c00b0068c687ee6d82c2fa36f63fc4503d48253c93ba3d10","transform":"Identity"},{"key":"bid-59cbc880e6d1f7407f18c36393c33d47ae51d5a54258f94a837ff996bf25a34d","transform":"Identity"},{"key":"bid-8d5998e9f6d5da25e76889d47841ba79bd8cca8c348a939cd1c459393105544e","transform":"Identity"},{"key":"bid-b5a727d071bc0a4920682bde11c62a94afafba1eb2be71aef306fdc4c4d2749f","transform":"Identity"},{"key":"bid-eb89ed102f0a5933a8ba4c9b093b8d37491a22020128ba0f087fde4aab90ca31","transform":"Identity"},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":"Identity"},{"key":"uref-02653fde6ec969034539d75048bfef571284bd488dc53c8be7197f3bb0dc9bb4-000","transform":"Identity"},{"key":"uref-dd83e7fe133d4b08943547528c25d1219e6817520c5ba48ffcf8c2b4f6f16812-000","transform":"Identity"},{"key":"uref-dd83e7fe133d4b08943547528c25d1219e6817520c5ba48ffcf8c2b4f6f16812-000","transform":{"WriteCLValue":{"cl_type":{"Map":{"key":"U64","value":{"Map":{"key":"PublicKey","value":"Any"}}}},"bytes":"04000000010000000000000005000000010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5070280c6a47e8d030201000000013372bd275423a2191f3fc11e1bee0419fcb4890319873f455bb462e02b199457070280c6a47e8d03011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852070380c6a47e8d03030100000001e45436d1609bd5c5ce13e8320a140421cf40a21089df1a08f7c58bcd06b6c9e4070380c6a47e8d030180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b070580c6a47e8d030501000000018973a4ffc17abab43f90bd229ef8a310236dd364ba0416d31612091d8cc17933070580c6a47e8d0301959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565070180c6a47e8d03010100000001a1cce6ea8db0d11d95b83671cc69f726b36aafb46dbf808c608dbcd5d237b11c070180c6a47e8d0301fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25070480c6a47e8d030401000000016997c57f973cd02df90941b7ace79d2b49e173f5f14a343cbf69a7a7ff8be3b5070480c6a47e8d03020000000000000005000000010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5070280c6a47e8d030201000000013372bd275423a2191f3fc11e1bee0419fcb4890319873f455bb462e02b199457070280c6a47e8d03011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852070380c6a47e8d03030100000001e45436d1609bd5c5ce13e8320a140421cf40a21089df1a08f7c58bcd06b6c9e4070380c6a47e8d030180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b070580c6a47e8d030501000000018973a4ffc17abab43f90bd229ef8a310236dd364ba0416d31612091d8cc17933070580c6a47e8d0301959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565070180c6a47e8d03010100000001a1cce6ea8db0d11d95b83671cc69f726b36aafb46dbf808c608dbcd5d237b11c070180c6a47e8d0301fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25070480c6a47e8d030401000000016997c57f973cd02df90941b7ace79d2b49e173f5f14a343cbf69a7a7ff8be3b5070480c6a47e8d03030000000000000005000000010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5070280c6a47e8d030201000000013372bd275423a2191f3fc11e1bee0419fcb4890319873f455bb462e02b199457070280c6a47e8d03011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852070380c6a47e8d03030100000001e45436d1609bd5c5ce13e8320a140421cf40a21089df1a08f7c58bcd06b6c9e4070380c6a47e8d030180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b070580c6a47e8d030501000000018973a4ffc17abab43f90bd229ef8a310236dd364ba0416d31612091d8cc17933070580c6a47e8d0301959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565070180c6a47e8d03010100000001a1cce6ea8db0d11d95b83671cc69f726b36aafb46dbf808c608dbcd5d237b11c070180c6a47e8d0301fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25070480c6a47e8d030401000000016997c57f973cd02df90941b7ace79d2b49e173f5f14a343cbf69a7a7ff8be3b5070480c6a47e8d03040000000000000005000000010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5070280c6a47e8d030201000000013372bd275423a2191f3fc11e1bee0419fcb4890319873f455bb462e02b199457070280c6a47e8d03011213e00a3bd748278b38a00a4787a7143f28a9d564126566716a53daa9499852070380c6a47e8d03030100000001e45436d1609bd5c5ce13e8320a140421cf40a21089df1a08f7c58bcd06b6c9e4070380c6a47e8d030180b99ded1d271c61a26d1b18c289ab33fc64355fa90cda4ae18f91786aa6ba4b070580c6a47e8d030501000000018973a4ffc17abab43f90bd229ef8a310236dd364ba0416d31612091d8cc17933070580c6a47e8d0301959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565070180c6a47e8d03010100000001a1cce6ea8db0d11d95b83671cc69f726b36aafb46dbf808c608dbcd5d237b11c070180c6a47e8d0301fcf1392c59c7d89190bfcd1b00902cc0801700eab98034aa4e56816d338f6c25070480c6a47e8d030401000000016997c57f973cd02df90941b7ace79d2b49e173f5f14a343cbf69a7a7ff8be3b5070480c6a47e8d03","parsed":null}}},{"key":"uref-14b309cf110abed5a8d5f0ccd6328a88ab8f929fa6a470f57ed08e4207bc769b-000","transform":{"WriteCLValue":{"cl_type":"U64","bytes":"0100000000000000","parsed":1}}},{"key":"uref-9b9e5674c62c6d6ea7e57ff6341f0e7ae99cb49c9588668fcf5ba1e7c2cf5110-000","transform":{"WriteCLValue":{"cl_type":"U64","bytes":"03f5d62682010000","parsed":1658508997891}}}]}}} +id:0 \ No newline at end of file From bf840c8e46d6355aefe3f636faa382f158859da2 Mon Sep 17 00:00:00 2001 From: meywood Date: Tue, 2 Aug 2022 12:13:34 +0100 Subject: [PATCH 02/35] issues/120 - Initial commit of EventService against merged codebase --- gradle.properties | 6 ++++-- .../casper/sdk/model/deploy/executionresult/Success.java | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/gradle.properties b/gradle.properties index 280aec2bf..9e88254e1 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,9 +1,11 @@ cryptokeyVersion=0.2.0 lombokPluginVersion=6.2.0 jupiterVersion=5.8.2 +jsonPathAssertVersion=2.7.0 jsonrpc4jVersion=1.6 -jacksonVersion=2.13.2 -log4jVersion=2.17.1 +jacksonVersion=2.13.3 +log4jVersion=2.17.2 +mockwebserverVersion=4.10.0 slf4jApiVersion=1.7.36 javaTuplesVersion=1.2 jsonassertVersion=1.5.0 diff --git a/src/main/java/com/casper/sdk/model/deploy/executionresult/Success.java b/src/main/java/com/casper/sdk/model/deploy/executionresult/Success.java index d9b1caaec..297356f27 100644 --- a/src/main/java/com/casper/sdk/model/deploy/executionresult/Success.java +++ b/src/main/java/com/casper/sdk/model/deploy/executionresult/Success.java @@ -16,7 +16,7 @@ /** * Abstract Executable Result of type Success containing the details of the - * contract execution. It shows the result of a successs execution + * contract execution. It shows the result of a successful execution * * @author Alexandre Carvalho * @author Andre Bertolace From 2e8d2a532579f5e954a28d62164e6861d3f15bd2 Mon Sep 17 00:00:00 2001 From: meywood Date: Wed, 3 Aug 2022 10:05:04 +0100 Subject: [PATCH 03/35] issues/120 - Tidy up of JavaDoc --- .../com/casper/sdk/model/event/Event.java | 8 ++- .../com/casper/sdk/service/EventService.java | 20 +++---- .../sdk/service/impl/event/AbstractEvent.java | 56 ++++--------------- .../sdk/service/impl/event/EventBuilder.java | 12 ++-- .../service/impl/event/EventBuilderTest.java | 4 +- .../service/impl/event/EventServiceImpl.java | 2 +- .../sdk/service/impl/event/PojoEvent.java | 6 +- .../sdk/service/impl/event/RawEvent.java | 4 +- 8 files changed, 44 insertions(+), 68 deletions(-) diff --git a/src/main/java/com/casper/sdk/model/event/Event.java b/src/main/java/com/casper/sdk/model/event/Event.java index 464b51608..d5235b2b2 100644 --- a/src/main/java/com/casper/sdk/model/event/Event.java +++ b/src/main/java/com/casper/sdk/model/event/Event.java @@ -9,12 +9,18 @@ */ public interface Event { + /** + * The node URL that is the source of the event + * + * @return the URL of the source node + */ + String getSource(); + /** * The type of the event * * @return the type of the event */ - EventType getEventType(); /** diff --git a/src/main/java/com/casper/sdk/service/EventService.java b/src/main/java/com/casper/sdk/service/EventService.java index d36e64b0d..c6cc113b5 100644 --- a/src/main/java/com/casper/sdk/service/EventService.java +++ b/src/main/java/com/casper/sdk/service/EventService.java @@ -24,13 +24,13 @@ public interface EventService { * @param eventType the type of event to read * @param eventTarget the target of the event JSON string or POJO * @param reader the reader to read the event from - * @param the type of the event - * @param the type of the events content + * @param the type of the event + * @param the type of the events data content * @return the read event */ - > Stream readEvent(final EventType eventType, - final EventTarget eventTarget, - final Reader reader); + > Stream readEvent(final EventType eventType, + final EventTarget eventTarget, + final Reader reader); /** @@ -39,13 +39,13 @@ > Stream readEvent(final EventType eventType, * * @param eventType the type of event to read * @param eventTarget the target of the event JSON string or POJO - * @param the type of the event - * @param the type of the events content + * @param the type of the event + * @param the type of the events data content * @return the read event */ - > Stream readEventStream(final EventType eventType, - final EventTarget eventTarget, - final Long startFrom); + > Stream readEventStream(final EventType eventType, + final EventTarget eventTarget, + final Long startFrom); /** diff --git a/src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java b/src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java index 8c31cf206..6a7451250 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java +++ b/src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java @@ -2,6 +2,7 @@ import com.casper.sdk.model.event.Event; import com.casper.sdk.model.event.EventType; +import lombok.*; import java.util.Objects; import java.util.Optional; @@ -10,59 +11,24 @@ * The abstract base class implementation for all events * * @param the type of the event data - * * @author ian@meywood.com */ +@Getter +@AllArgsConstructor(access = AccessLevel.PACKAGE) +@ToString(doNotUseGetters = true) +@EqualsAndHashCode(of = {"source", "id"}) abstract class AbstractEvent implements Event { - /** - * The ID of the event - */ - private final Long id; + /** The type of event RAW or POJO */ private final EventType eventType; - /** - * The event data - */ + /** The source node of the event */ + private final String source; + /** The ID of the event */ + private final Long id; + /** The event data */ private final T data; - protected AbstractEvent(final EventType eventType, final T data, final Long id) { - this.eventType = eventType; - this.data = data; - this.id = id; - } - - - public EventType getEventType() { - return eventType; - } - - public T getData() { - return data; - } - public Optional getId() { return Optional.ofNullable(id); } - - @Override - public String toString() { - return getClass().getSimpleName() + "{" + - ", eventType='" + eventType + '\'' + - ", id=" + id + - ", data=" + data + - '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final AbstractEvent that = (AbstractEvent) o; - return Objects.equals(id, that.id); - } - - @Override - public int hashCode() { - return Objects.hash(id); - } } diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java index b760c5212..6113fcb6a 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java @@ -1,11 +1,11 @@ package com.casper.sdk.service.impl.event; +import com.casper.sdk.exception.CasperClientException; import com.casper.sdk.model.event.Event; +import com.casper.sdk.model.event.EventData; import com.casper.sdk.model.event.EventTarget; import com.casper.sdk.model.event.EventType; -import com.casper.sdk.exception.CasperClientException; -import com.casper.sdk.model.event.EventData; import com.casper.sdk.model.event.shutdown.Shutdown; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -30,14 +30,16 @@ final class EventBuilder { private final EventType eventType; /** The target type of the event to build */ private final EventTarget eventTarget; + private final String source; /** Indicates if an ID line is expected for the current data line */ private boolean idExpected = true; /** Used to build the pojo model objects from the JSON in the data line */ private final ObjectMapper mapper; - EventBuilder(final EventType eventType, final EventTarget eventTarget) { + EventBuilder(final EventType eventType, final EventTarget eventTarget, final String source) { this.eventType = eventType; this.eventTarget = eventTarget; + this.source = source; mapper = new ObjectMapper(); } @@ -85,7 +87,7 @@ T buildEvent() { final T event; if (this.eventTarget == EventTarget.RAW) { //noinspection unchecked - event = (T) new RawEvent(eventType, data, id); + event = (T) new RawEvent(eventType, source, data, id); } else if (eventTarget == EventTarget.POJO) { //noinspection unchecked event = (T) buildPojoEvent(); @@ -112,7 +114,7 @@ private PojoEvent buildPojoEvent() { //noinspection unchecked root = mapper.readValue(value, EventRoot.class); } - event = new PojoEvent<>(eventType, EventRoot.getData(root), id); + event = new PojoEvent<>(eventType, source, id, EventRoot.getData(root)); } catch (JsonProcessingException e) { throw new CasperClientException("Error building POJO event for: " + data, e); } diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java index 466d846a5..c8329e449 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -72,7 +72,7 @@ void buildRawMainEvent() throws IOException { void buildApiVersionEvent() throws IOException { final InputStream in = EventBuilderTest.class.getClassLoader().getResourceAsStream(API_VERSION_EVENT); - final EventBuilder builder = new EventBuilder(EventType.MAIN, EventTarget.POJO); + final EventBuilder builder = new EventBuilder(EventType.MAIN, EventTarget.POJO, "http://localhost:81012"); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); builder.processLine(reader.readLine()); @@ -216,7 +216,7 @@ private > T getEvent(final EventType eventType, final String eventPath) throws IOException { final InputStream in = EventBuilderTest.class.getClassLoader().getResourceAsStream(eventPath); - final EventBuilder builder = new EventBuilder(eventType, eventTarget); + final EventBuilder builder = new EventBuilder(eventType, eventTarget, "http://localhost:81012"); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); builder.processLine(reader.readLine()); diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java b/src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java index da72d8ec0..9f889710e 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java @@ -86,7 +86,7 @@ public > Stream readEvent(final EventType eventType, final EventTarget eventTarget, final Reader reader) { - final EventBuilder eventBuilder = new EventBuilder(eventType, eventTarget); + final EventBuilder eventBuilder = new EventBuilder(eventType, eventTarget, uri.toString()); //noinspection unchecked return new BufferedReader(reader) diff --git a/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java b/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java index bfd5e00db..e234c32ad 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java +++ b/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java @@ -3,6 +3,7 @@ import com.casper.sdk.model.event.EventType; import com.casper.sdk.model.event.EventData; import com.casper.sdk.model.event.EventTarget; +import lombok.AllArgsConstructor; /** * An event that contains the event data as Pojo model returned from the event service when @@ -11,9 +12,10 @@ * @param the types of the expected EventData * @author ian@meywood.com */ + final class PojoEvent extends AbstractEvent { - PojoEvent(final EventType eventType, T data, final Long id) { - super(eventType, data, id); + PojoEvent(final EventType eventType, final String source, final Long id, T data) { + super(eventType, source, id, data); } } diff --git a/src/test/java/com/casper/sdk/service/impl/event/RawEvent.java b/src/test/java/com/casper/sdk/service/impl/event/RawEvent.java index ebb78358d..737e2e8cc 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/RawEvent.java +++ b/src/test/java/com/casper/sdk/service/impl/event/RawEvent.java @@ -11,7 +11,7 @@ */ final class RawEvent extends AbstractEvent { - RawEvent(final EventType eventType, final String data, final Long id) { - super(eventType, data, id); + RawEvent(final EventType eventType, final String source, final String data, final Long id) { + super(eventType, source, id, data); } } From 0a84db9ffc36eb22e6c46c4b39bc5b24faef54f0 Mon Sep 17 00:00:00 2001 From: meywood Date: Wed, 3 Aug 2022 12:16:13 +0100 Subject: [PATCH 04/35] issues/120 - Added missing patch code for Digest fields and AbstractSerializedKeyTaggedHexDeserializer to handle "00" from the event stream for empty/null keys --- .../AbstractSerializedKeyTaggedHexDeserializer.java | 7 +++++++ src/main/java/com/casper/sdk/model/block/JsonBlock.java | 3 ++- .../java/com/casper/sdk/model/block/JsonBlockHeader.java | 9 +++++---- .../java/com/casper/sdk/service/CasperServiceTests.java | 4 ++-- .../casper/sdk/service/impl/event/CLTypeErrorsTest.java | 8 ++++++++ .../casper/sdk/test/PathMatchingResourceDispatcher.java | 2 +- 6 files changed, 25 insertions(+), 8 deletions(-) create mode 100644 src/test/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java diff --git a/src/main/java/com/casper/sdk/jackson/deserializer/AbstractSerializedKeyTaggedHexDeserializer.java b/src/main/java/com/casper/sdk/jackson/deserializer/AbstractSerializedKeyTaggedHexDeserializer.java index a82c68218..6e1faec28 100644 --- a/src/main/java/com/casper/sdk/jackson/deserializer/AbstractSerializedKeyTaggedHexDeserializer.java +++ b/src/main/java/com/casper/sdk/jackson/deserializer/AbstractSerializedKeyTaggedHexDeserializer.java @@ -25,10 +25,17 @@ public abstract class AbstractSerializedKeyTaggedHexDeserializer, S extends Tag> extends JsonDeserializer { + /** Missing PublicKey in Events is shown as "00" */ + private static final String NULL_PUBLIC_KEY = "00"; + @Override public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { JsonNode node = p.getCodec().readTree(p); + if (NULL_PUBLIC_KEY.equals(node.textValue())) { + return null; + } + T object = this.getInstanceOf(); try { diff --git a/src/main/java/com/casper/sdk/model/block/JsonBlock.java b/src/main/java/com/casper/sdk/model/block/JsonBlock.java index 965490c89..d521def63 100644 --- a/src/main/java/com/casper/sdk/model/block/JsonBlock.java +++ b/src/main/java/com/casper/sdk/model/block/JsonBlock.java @@ -1,5 +1,6 @@ package com.casper.sdk.model.block; +import com.casper.sdk.model.common.Digest; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Builder; @@ -28,7 +29,7 @@ public class JsonBlock { * The block's hash. */ @JsonProperty("hash") - private String hash; + private Digest hash; /** * {@link JsonBlockHeader} diff --git a/src/main/java/com/casper/sdk/model/block/JsonBlockHeader.java b/src/main/java/com/casper/sdk/model/block/JsonBlockHeader.java index df3842667..df6d44875 100644 --- a/src/main/java/com/casper/sdk/model/block/JsonBlockHeader.java +++ b/src/main/java/com/casper/sdk/model/block/JsonBlockHeader.java @@ -1,5 +1,6 @@ package com.casper.sdk.model.block; +import com.casper.sdk.model.common.Digest; import com.casper.sdk.model.era.JsonEraEnd; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; @@ -35,7 +36,7 @@ public class JsonBlockHeader { * Hex-encoded hash digest */ @JsonProperty("state_root_hash") - private String stateRootHash; + private Digest stateRootHash; /** * boolean @@ -53,19 +54,19 @@ public class JsonBlockHeader { * Hex-encoded hash digest */ @JsonProperty("body_hash") - private String bodyHash; + private Digest bodyHash; /** * Hex-encoded hash digest. */ @JsonProperty("parent_hash") - private String parentHash; + private Digest parentHash; /** * Hex-encoded hash digest */ @JsonProperty("accumulated_seed") - private String accumulatedSeed; + private Digest accumulatedSeed; /** * Timestamp formatted as per RFC 3339 diff --git a/src/test/java/com/casper/sdk/service/CasperServiceTests.java b/src/test/java/com/casper/sdk/service/CasperServiceTests.java index da8c6fd72..84278bed5 100644 --- a/src/test/java/com/casper/sdk/service/CasperServiceTests.java +++ b/src/test/java/com/casper/sdk/service/CasperServiceTests.java @@ -74,10 +74,10 @@ void testIfBlockReturnedMatchesRequestedByHash() { for (int i = 0; i < blocks_to_check; i++) { LOGGER.debug(String.format("Testing with block height %d", i)); JsonBlockData resultByHeight = casperServiceMainnet.getBlock(new HeightBlockIdentifier(i)); - String hash = resultByHeight.getBlock().getHash(); + String hash = resultByHeight.getBlock().getHash().toString(); JsonBlockData resultByHash = casperServiceMainnet.getBlock(new HashBlockIdentifier(hash)); - assertEquals(resultByHash.getBlock().getHash(), hash); + assertEquals(resultByHash.getBlock().getHash().toString(), hash); } } diff --git a/src/test/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java b/src/test/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java new file mode 100644 index 000000000..c1e333b9e --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java @@ -0,0 +1,8 @@ +package com.casper.sdk.service.impl.event; + +/** + * + * @author ian@meywood.com + */ +public class CLTypeErrorsTest { +} diff --git a/src/test/java/com/casper/sdk/test/PathMatchingResourceDispatcher.java b/src/test/java/com/casper/sdk/test/PathMatchingResourceDispatcher.java index c28dfae04..463907f6c 100644 --- a/src/test/java/com/casper/sdk/test/PathMatchingResourceDispatcher.java +++ b/src/test/java/com/casper/sdk/test/PathMatchingResourceDispatcher.java @@ -12,7 +12,7 @@ public class PathMatchingResourceDispatcher extends Dispatcher { - /** The path to the resource to use */ + /** The path to the resource to serve for the path that matches the pathMatcher */ private final String resourcePath; /** The matcher for the URL request path */ private final Matcher pathMatcher; From 9500fda395bb69c8fdd4eb4cba57e0b3eb98d57e Mon Sep 17 00:00:00 2001 From: meywood Date: Wed, 10 Aug 2022 15:36:29 +0100 Subject: [PATCH 05/35] issues/120 - Fixed issues with production classes being added to test folder --- .../java/com/casper/sdk/service/impl/event/AbstractEvent.java | 0 .../com/casper/sdk/service/impl/event/CLTypeErrorsTest.java | 0 .../java/com/casper/sdk/service/impl/event/EventBuilder.java | 0 .../java/com/casper/sdk/service/impl/event/EventRoot.java | 0 .../com/casper/sdk/service/impl/event/EventServiceImpl.java | 0 .../com/casper/sdk/service/impl/event/EventUrlBuilder.java | 2 -- .../java/com/casper/sdk/service/impl/event/PojoEvent.java | 1 - .../java/com/casper/sdk/service/impl/event/RawEvent.java | 0 .../com/casper/sdk/service/impl/event/EventBuilderTest.java | 1 + .../casper/sdk/service/impl/event/EventUrlBuilderTest.java | 4 ++-- 10 files changed, 3 insertions(+), 5 deletions(-) rename src/{test => main}/java/com/casper/sdk/service/impl/event/AbstractEvent.java (100%) rename src/{test => main}/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java (100%) rename src/{test => main}/java/com/casper/sdk/service/impl/event/EventBuilder.java (100%) rename src/{test => main}/java/com/casper/sdk/service/impl/event/EventRoot.java (100%) rename src/{test => main}/java/com/casper/sdk/service/impl/event/EventServiceImpl.java (100%) rename src/{test => main}/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java (99%) rename src/{test => main}/java/com/casper/sdk/service/impl/event/PojoEvent.java (94%) rename src/{test => main}/java/com/casper/sdk/service/impl/event/RawEvent.java (100%) diff --git a/src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java b/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java similarity index 100% rename from src/test/java/com/casper/sdk/service/impl/event/AbstractEvent.java rename to src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java diff --git a/src/test/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java b/src/main/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java similarity index 100% rename from src/test/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java rename to src/main/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java b/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java similarity index 100% rename from src/test/java/com/casper/sdk/service/impl/event/EventBuilder.java rename to src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventRoot.java b/src/main/java/com/casper/sdk/service/impl/event/EventRoot.java similarity index 100% rename from src/test/java/com/casper/sdk/service/impl/event/EventRoot.java rename to src/main/java/com/casper/sdk/service/impl/event/EventRoot.java diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java similarity index 100% rename from src/test/java/com/casper/sdk/service/impl/event/EventServiceImpl.java rename to src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java b/src/main/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java similarity index 99% rename from src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java rename to src/main/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java index 2468b6e79..693981b27 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java +++ b/src/main/java/com/casper/sdk/service/impl/event/EventUrlBuilder.java @@ -45,6 +45,4 @@ private String buildParams(final Long startFrom) { return ""; } } - - } diff --git a/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java b/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java similarity index 94% rename from src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java rename to src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java index e234c32ad..44692dece 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/PojoEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java @@ -3,7 +3,6 @@ import com.casper.sdk.model.event.EventType; import com.casper.sdk.model.event.EventData; import com.casper.sdk.model.event.EventTarget; -import lombok.AllArgsConstructor; /** * An event that contains the event data as Pojo model returned from the event service when diff --git a/src/test/java/com/casper/sdk/service/impl/event/RawEvent.java b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java similarity index 100% rename from src/test/java/com/casper/sdk/service/impl/event/RawEvent.java rename to src/main/java/com/casper/sdk/service/impl/event/RawEvent.java diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java index c8329e449..a9d6eef75 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -16,6 +16,7 @@ import com.casper.sdk.model.event.step.Step; import com.casper.sdk.model.event.version.ApiVersion; import com.casper.sdk.model.key.PublicKey; + import org.joda.time.DateTime; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilderTest.java index b918ded78..4b28490f5 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventUrlBuilderTest.java @@ -11,8 +11,8 @@ /** * Unit tests for the EventUrlBuilder - * - * @author ian@meywood.com + * + * @author ian@meywood.com */ class EventUrlBuilderTest { From 4a3c00219f2df60cb965364cb3ae68f460f36873 Mon Sep 17 00:00:00 2001 From: meywood Date: Thu, 11 Aug 2022 12:22:43 +0100 Subject: [PATCH 06/35] issues/120 - Data field DataType to Events to allow for easy identification of data payload for both raw and pojo events --- .../com/casper/sdk/model/event/DataType.java | 58 +++++++++++++++++++ .../com/casper/sdk/model/event/Event.java | 7 +++ .../sdk/service/impl/event/AbstractEvent.java | 4 +- .../sdk/service/impl/event/EventBuilder.java | 2 +- .../sdk/service/impl/event/PojoEvent.java | 8 ++- .../sdk/service/impl/event/RawEvent.java | 15 ++++- .../sdk/service/impl/event/PojoEventTest.java | 33 +++++++++++ .../sdk/service/impl/event/RawEventTest.java | 30 ++++++++++ 8 files changed, 150 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/casper/sdk/model/event/DataType.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/PojoEventTest.java create mode 100644 src/test/java/com/casper/sdk/service/impl/event/RawEventTest.java diff --git a/src/main/java/com/casper/sdk/model/event/DataType.java b/src/main/java/com/casper/sdk/model/event/DataType.java new file mode 100644 index 000000000..0dde7effa --- /dev/null +++ b/src/main/java/com/casper/sdk/model/event/DataType.java @@ -0,0 +1,58 @@ +package com.casper.sdk.model.event; + +import com.casper.sdk.model.event.blockadded.BlockAdded; +import com.casper.sdk.model.event.deployaccepted.DeployAccepted; +import com.casper.sdk.model.event.deployexpired.DeployExpired; +import com.casper.sdk.model.event.deployprocessed.DeployProcessed; +import com.casper.sdk.model.event.fault.Fault; +import com.casper.sdk.model.event.finalitysignature.FinalitySignature; +import com.casper.sdk.model.event.shutdown.Shutdown; +import com.casper.sdk.model.event.step.Step; +import com.casper.sdk.model.event.version.ApiVersion; + +/** + * The enums of the allowable data type key names + * + * @author ian@meywood.com + */ +public enum DataType { + + API_VERSION(ApiVersion.class), + BLOCK_ADDED(BlockAdded.class), + DEPLOY_ACCEPTED(DeployAccepted.class), + DEPLOY_EXPIRED(DeployExpired.class), + DEPLOY_PROCESSED(DeployProcessed.class), + FAULT(Fault.class), + FINALITY_SIGNATURE(FinalitySignature.class), + SHUTDOWN(Shutdown.class), + STEP(Step.class); + + + private Class dataType; + + DataType(Class dataType) { + this.dataType = dataType; + } + + public static DataType of(final Class dataTypeClass) { + for (DataType dataType : DataType.values()) { + if (dataType.dataType.equals(dataTypeClass)) { + return dataType; + } + } + return null; + } + + public static DataType of(final String dataTypeSimpleClassName) { + for (DataType dataType : DataType.values()) { + if (dataType.dataType.getSimpleName().equals(dataTypeSimpleClassName)) { + return dataType; + } + } + return null; + } + + public String getDataTypeName() { + return this.dataType.getSimpleName(); + } +} diff --git a/src/main/java/com/casper/sdk/model/event/Event.java b/src/main/java/com/casper/sdk/model/event/Event.java index d5235b2b2..9cfc54590 100644 --- a/src/main/java/com/casper/sdk/model/event/Event.java +++ b/src/main/java/com/casper/sdk/model/event/Event.java @@ -23,6 +23,13 @@ public interface Event { */ EventType getEventType(); + /** + * The key name of the data field. + * + * @return the key name of the data field + */ + DataType getDataType(); + /** * The event payload a JSON string or Pojo * diff --git a/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java b/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java index 6a7451250..7a96b55f1 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java @@ -1,10 +1,10 @@ package com.casper.sdk.service.impl.event; +import com.casper.sdk.model.event.DataType; import com.casper.sdk.model.event.Event; import com.casper.sdk.model.event.EventType; import lombok.*; -import java.util.Objects; import java.util.Optional; /** @@ -21,6 +21,8 @@ abstract class AbstractEvent implements Event { /** The type of event RAW or POJO */ private final EventType eventType; + /** The type of the data field */ + private final DataType dataType; /** The source node of the event */ private final String source; /** The ID of the event */ diff --git a/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java b/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java index 6113fcb6a..3469a4ee2 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java +++ b/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java @@ -87,7 +87,7 @@ T buildEvent() { final T event; if (this.eventTarget == EventTarget.RAW) { //noinspection unchecked - event = (T) new RawEvent(eventType, source, data, id); + event = (T) new RawEvent(eventType, source, id, data); } else if (eventTarget == EventTarget.POJO) { //noinspection unchecked event = (T) buildPojoEvent(); diff --git a/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java b/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java index 44692dece..61f0f40de 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java @@ -1,5 +1,6 @@ package com.casper.sdk.service.impl.event; +import com.casper.sdk.model.event.DataType; import com.casper.sdk.model.event.EventType; import com.casper.sdk.model.event.EventData; import com.casper.sdk.model.event.EventTarget; @@ -11,10 +12,13 @@ * @param the types of the expected EventData * @author ian@meywood.com */ - final class PojoEvent extends AbstractEvent { PojoEvent(final EventType eventType, final String source, final Long id, T data) { - super(eventType, source, id, data); + super(eventType, getDataType(data), source, id, data); + } + + private static DataType getDataType(final Object data) { + return DataType.of(data.getClass()); } } diff --git a/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java index 737e2e8cc..4f883a922 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java @@ -1,7 +1,8 @@ package com.casper.sdk.service.impl.event; -import com.casper.sdk.model.event.EventType; +import com.casper.sdk.model.event.DataType; import com.casper.sdk.model.event.EventTarget; +import com.casper.sdk.model.event.EventType; /** * An event that contains the event data as raw JSON without the 'data:' prefix is returned from the event service when @@ -11,7 +12,15 @@ */ final class RawEvent extends AbstractEvent { - RawEvent(final EventType eventType, final String source, final String data, final Long id) { - super(eventType, source, id, data); + RawEvent(final EventType eventType, final String source, final Long id, final String data) { + super(eventType, getDataType(data), source, id, data); + } + + private static DataType getDataType(final String data) { + final int start = data.indexOf(':'); + final int end = data.indexOf(':', start + 1); + final String dataTypeName = data.substring(start + 3, end - 1); + return DataType.of(dataTypeName); } } + diff --git a/src/test/java/com/casper/sdk/service/impl/event/PojoEventTest.java b/src/test/java/com/casper/sdk/service/impl/event/PojoEventTest.java new file mode 100644 index 000000000..09b1ee897 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/PojoEventTest.java @@ -0,0 +1,33 @@ +package com.casper.sdk.service.impl.event; + +import com.casper.sdk.model.common.Digest; +import com.casper.sdk.model.event.DataType; +import com.casper.sdk.model.event.EventType; +import com.casper.sdk.model.event.deployexpired.DeployExpired; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +/** + * @author ian@meywood.com + */ +class PojoEventTest { + + @Test + void pojoEvent() { + + final String source = "http://localhost:9999"; + final DeployExpired data = new DeployExpired(new Digest("bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c")); + + final PojoEvent rawEvent = new PojoEvent<>(EventType.MAIN, source, 2L, data); + + assertThat(rawEvent.getEventType(), is(EventType.MAIN)); + assertThat(rawEvent.getSource(), is(source)); + assertThat(rawEvent.getId().isPresent(), is(true)); + assertThat(rawEvent.getId().get(), is(2L)); + assertThat(rawEvent.getData(), is(data)); + assertThat(rawEvent.getDataType(), is(DataType.DEPLOY_EXPIRED)); + + } +} \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/service/impl/event/RawEventTest.java b/src/test/java/com/casper/sdk/service/impl/event/RawEventTest.java new file mode 100644 index 000000000..c50e052f1 --- /dev/null +++ b/src/test/java/com/casper/sdk/service/impl/event/RawEventTest.java @@ -0,0 +1,30 @@ +package com.casper.sdk.service.impl.event; + +import com.casper.sdk.model.event.DataType; +import com.casper.sdk.model.event.EventType; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +/** + * @author ian@meywood.com + */ +class RawEventTest { + + @Test + void rawEvent() { + + final String source = "http://localhost:9999"; + final String data = "data:{\"ApiVersion\":\"1.0.0\"}"; + + final RawEvent rawEvent = new RawEvent(EventType.MAIN, source, 1L, data); + + assertThat(rawEvent.getEventType(), is(EventType.MAIN)); + assertThat(rawEvent.getSource(), is(source)); + assertThat(rawEvent.getId().isPresent(), is(true)); + assertThat(rawEvent.getId().get(), is(1L)); + assertThat(rawEvent.getData(), is(data)); + assertThat(rawEvent.getDataType(), is(DataType.API_VERSION)); + } +} \ No newline at end of file From 70ccee2c9dcefef564e7d28031dbcc943c601f13 Mon Sep 17 00:00:00 2001 From: meywood Date: Mon, 5 Sep 2022 10:46:16 +0100 Subject: [PATCH 07/35] issues/120 - Added gradle setting for publishing to network.casper MVN repo --- .github/workflows/gradle.yml | 95 +++---------------- .github/workflows/publish.yml | 19 ++-- build.gradle | 84 ++++++++++------ .../com/casper/sdk/model/event/DataType.java | 2 +- .../com/casper/sdk/service/CasperService.java | 1 - .../sdk/service/CasperServiceTests.java | 28 +++--- .../service/EventServiceIntegrationTest.java | 2 + .../service/impl/event/EventBuilderTest.java | 4 + 8 files changed, 95 insertions(+), 140 deletions(-) diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 89847b470..67ecb0674 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -1,13 +1,13 @@ -# This workflow will build a Java project with Gradle -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle - name: Java CI with Gradle on: push: - branches: [ main ] + branches: [ "issues/120" ] pull_request: - branches: [ main ] + branches: [ "issues/120" ] + +permissions: + contents: read jobs: build: @@ -15,84 +15,13 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Set up JDK 8 - uses: actions/setup-java@v2 - with: - java-version: '8' - distribution: 'adopt' - - - name: Grant execute permission for gradlew - run: chmod +x gradlew - - - name: Build with Gradle - run: ./gradlew build - - publish-docs-reports: - needs: build - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - - name: Set up JDK 11 - uses: actions/setup-java@v2 + - uses: actions/checkout@v3 + - name: Set up JDK 8 + uses: actions/setup-java@v3 with: - java-version: '11' - distribution: 'adopt' - + java-version: '8' + distribution: 'temurin' - name: Grant execute permission for gradlew run: chmod +x gradlew - - - name: Export project version - run: echo "PROJECT_VERSION=$(./gradlew properties -q | grep "version:" | awk '{print $2}')" >> $GITHUB_ENV - - - name: Generate Javadoc - run: ./gradlew javadoc - - - name: Run tests and generate reports - run: ./gradlew test - - - name: Deploy tests results to GitHub Pages - uses: JamesIves/github-pages-deploy-action@v4.2.2 - with: - branch: gh-pages - clean: true - folder: build/reports/tests - target-folder: docs/latest/junit - - name: Deploy jacoco report to GitHub Pages - uses: JamesIves/github-pages-deploy-action@v4.2.2 - with: - branch: gh-pages - clean: true - folder: build/reports/jacoco - target-folder: docs/latest/jacoco - - name: Deploy to GitHub Pages - uses: JamesIves/github-pages-deploy-action@v4.2.2 - with: - branch: gh-pages - clean: true - folder: build/docs/javadoc - target-folder: docs/latest/javadoc - - - name: Deploy tests results to GitHub Pages - uses: JamesIves/github-pages-deploy-action@v4.2.2 - with: - branch: gh-pages - clean: true - folder: build/reports/tests - target-folder: docs/${{ env.PROJECT_VERSION }}/junit - - name: Deploy jacoco report to GitHub Pages - uses: JamesIves/github-pages-deploy-action@v4.2.2 - with: - branch: gh-pages - clean: true - folder: build/reports/jacoco - target-folder: docs/${{ env.PROJECT_VERSION }}/jacoco - - name: Deploy to GitHub Pages - uses: JamesIves/github-pages-deploy-action@v4.2.2 - with: - branch: gh-pages - clean: true - folder: build/docs/javadoc - target-folder: docs/${{ env.PROJECT_VERSION }}/javadoc \ No newline at end of file + - name: Build with Gradle + run: ./gradlew clean build \ No newline at end of file diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 46675f9ad..b849e0426 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,18 +1,13 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - name: Publish package to GitHub Packages and Maven Central on: release: types: [created] jobs: publish: - runs-on: ubuntu-latest - permissions: + runs-on: ubuntu-latest + permissions: contents: read - packages: write + packages: write steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v2 @@ -26,10 +21,10 @@ jobs: - name: Publish package uses: gradle/gradle-build-action@v2 with: - arguments: publish + arguments: publish closeAndReleaseStagingRepository env: GPG_SIGNING_KEY: ${{ secrets.GPG_SIGNING_KEY }} GPG_SIGNING_KEY_PASSWORD: ${{ secrets.GPG_SIGNING_KEY_PASSWORD }} - MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} - MAVEN_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 90b549d81..c54495212 100644 --- a/build.gradle +++ b/build.gradle @@ -7,10 +7,11 @@ plugins { id 'jacoco' id 'signing' id 'maven-publish' + id('io.github.gradle-nexus.publish-plugin') version '1.1.0' } -group = 'com.syntifi.casper' -version = '0.2.1' +group = 'network.casper' +version = '0.5.0-SNAPSHOT' sourceCompatibility = '8' repositories { @@ -48,12 +49,30 @@ java { withSourcesJar() } +task casperJar(type: Jar) { + archiveBaseName = 'casper-java-sdk' + archiveVersion = "$version" + from { configurations.compileClasspath.findAll { it.isDirectory() ? it : zipTree(it) } } + with jar +} + javadoc { if (JavaVersion.current().isJava9Compatible()) { options.addBooleanOption('html5', true) } } +nexusPublishing { + repositories { + sonatype { //only for users registered in Sonatype after 24 Feb 2021 + nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) + snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) + username.set(System.getenv('MAVEN_USERNAME')) + password.set(System.getenv('MAVEN_PASSWORD')) + } + } +} + test { finalizedBy jacocoTestReport @@ -106,19 +125,9 @@ jacocoTestReport { publishing { repositories { - maven { - name = 'OSSRH' - def releasesRepoUrl = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/' - def snapshotsRepoUrl = 'https://s01.oss.sonatype.org/content/repositories/snapshots/' - url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl - credentials { - username = System.getenv('MAVEN_USERNAME') - password = System.getenv('MAVEN_PASSWORD') - } - } maven { name = "GitHubPackages" - url = "https://maven.pkg.github.com/syntifi/casper-sdk" + url = "https://maven.pkg.github.com/casper-network/casper-java-sdk" credentials { username = System.getenv("GITHUB_ACTOR") password = System.getenv("GITHUB_TOKEN") @@ -128,34 +137,34 @@ publishing { publications { mavenJava(MavenPublication) { - artifactId = 'casper-sdk' + artifactId = 'casper-java-sdk' from components.java pom { - name = 'Java 8+ Casper RPC Client SDK' + name = 'Casper Java SDK' packaging = 'jar' - description = 'This project implements the SDK to interact with a Casper Node. It wraps the Json-RPC requests and maps the results to Java objects.' - url = 'https://github.com/syntifi/casper-sdk' + description = 'SDK to streamline the 3rd party Java client integration processes. Such 3rd parties include exchanges & app developers.' + url = 'https://github.com/casper-network/casper-java-sdk' scm { - connection = 'scm:git:https://github.com/syntifi/casper-sdk.git' - developerConnection = 'git@github.com:syntifi/casper-sdk.git' - url = 'https://github.com/syntifi/casper-sdk' + connection = 'scm:git:https://github.com/casper-network/casper-java-sdk.git' + developerConnection = 'git@github.com:casper-network/casper-java-sdk.git' + url = 'https://github.com/casper-network/casper-java-sdk' } issueManagement { system = 'GitHub' - url = 'https://github.com/syntifi/casper-sdk/issues' + url = 'https://github.com/casper-network/casper-java-sdk/issues' } ciManagement { system = 'Github Actions' - url = 'https://github.com/syntifi/casper-sdk/actions' + url = 'https://github.com/casper-network/casper-java-sdk/actions' } licenses { license { name = 'The Apache License, Version 2.0' - url = 'https://www.apache.org/licenses/LICENSE-2.0.txt' + url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' } } @@ -170,16 +179,31 @@ publishing { name = 'Andre Bertolace' email = 'andre@syntifi.com' } + developer { + id = 'meywood' + name = 'Ian Mills' + email = 'ian@meywood.com' + } + developer { + id = 'stormeye' + name = 'Carl Norburn' + email = 'carl@stormeye.co.uk' + } } } } } -} -// Reference at https://docs.gradle.org/current/userguide/signing_plugin.html#sec:in-memory-keys -signing { - def signingKey = System.getenv('GPG_SIGNING_KEY') ?: findProperty('GPG_SIGNING_KEY') - def signingKeyPassword = System.getenv('GPG_SIGNING_KEY_PASSWORD') ?: findProperty('GPG_SIGNING_KEY_PASSWORD') - useInMemoryPgpKeys(signingKey, signingKeyPassword) - sign publishing.publications.mavenJava + jar { + archiveClassifier = '' + } + + // Reference at https://docs.gradle.org/current/userguide/signing_plugin.html#sec:in-memory-keys + signing { + def signingKey = System.getenv('GPG_SIGNING_KEY') ?: findProperty('GPG_SIGNING_KEY') + def signingKeyPassword = System.getenv('GPG_SIGNING_KEY_PASSWORD') ?: findProperty('GPG_SIGNING_KEY_PASSWORD') + + useInMemoryPgpKeys(signingKey, signingKeyPassword) + sign publishing.publications.mavenJava + } } diff --git a/src/main/java/com/casper/sdk/model/event/DataType.java b/src/main/java/com/casper/sdk/model/event/DataType.java index 0dde7effa..273224f58 100644 --- a/src/main/java/com/casper/sdk/model/event/DataType.java +++ b/src/main/java/com/casper/sdk/model/event/DataType.java @@ -27,7 +27,7 @@ public enum DataType { SHUTDOWN(Shutdown.class), STEP(Step.class); - + /** The EventData class for the data type */ private Class dataType; DataType(Class dataType) { diff --git a/src/main/java/com/casper/sdk/service/CasperService.java b/src/main/java/com/casper/sdk/service/CasperService.java index 55ccea2c7..e94ddb472 100644 --- a/src/main/java/com/casper/sdk/service/CasperService.java +++ b/src/main/java/com/casper/sdk/service/CasperService.java @@ -247,5 +247,4 @@ DictionaryData getStateDictionaryItem(@JsonRpcParam("state_root_hash") String st StoredValueData getStateItem(@JsonRpcParam("state_root_hash") String stateRootHash, @JsonRpcParam("key") String key, @JsonRpcParam("path") List path); - } diff --git a/src/test/java/com/casper/sdk/service/CasperServiceTests.java b/src/test/java/com/casper/sdk/service/CasperServiceTests.java index 84278bed5..fa192297d 100644 --- a/src/test/java/com/casper/sdk/service/CasperServiceTests.java +++ b/src/test/java/com/casper/sdk/service/CasperServiceTests.java @@ -1,25 +1,24 @@ package com.casper.sdk.service; -import java.io.IOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import com.casper.sdk.exception.CasperClientException; import com.casper.sdk.identifier.block.BlockIdentifier; import com.casper.sdk.identifier.block.HashBlockIdentifier; import com.casper.sdk.identifier.block.HeightBlockIdentifier; import com.casper.sdk.model.account.AccountData; import com.casper.sdk.model.auction.AuctionData; +import com.casper.sdk.model.block.JsonBlock; +import com.casper.sdk.model.block.JsonBlockData; import com.casper.sdk.model.clvalue.CLValueString; import com.casper.sdk.model.clvalue.encdec.StringByteHelper; +import com.casper.sdk.model.deploy.DeployData; import com.casper.sdk.model.deploy.executabledeploy.ModuleBytes; import com.casper.sdk.model.deploy.executabledeploy.StoredContractByHash; import com.casper.sdk.model.deploy.executionresult.Success; import com.casper.sdk.model.deploy.transform.WriteCLValue; import com.casper.sdk.model.era.EraInfoData; +import com.casper.sdk.model.key.AlgorithmTag; import com.casper.sdk.model.key.PublicKey; +import com.casper.sdk.model.peer.PeerData; import com.casper.sdk.model.stateroothash.StateRootHashData; import com.casper.sdk.model.status.StatusData; import com.casper.sdk.model.storedvalue.StoredValueAccount; @@ -27,20 +26,21 @@ import com.casper.sdk.model.storedvalue.StoredValueData; import com.casper.sdk.model.transfer.Transfer; import com.casper.sdk.model.transfer.TransferData; -import com.casper.sdk.model.block.JsonBlock; -import com.casper.sdk.model.block.JsonBlockData; -import com.casper.sdk.model.deploy.DeployData; -import com.casper.sdk.model.key.AlgorithmTag; -import com.casper.sdk.model.peer.PeerData; - import com.casper.sdk.model.validator.ValidatorChangeData; -import com.fasterxml.jackson.databind.JsonNode; import org.json.JSONException; +import org.junit.Ignore; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import static org.junit.jupiter.api.Assertions.*; /** @@ -112,6 +112,7 @@ void retrieveLastBlock() { } @Test + @Disabled void getBlockByHash() { JsonBlockData blockData = casperServiceMainnet.getBlock(new HashBlockIdentifier("2fe9630b7790852e4409d815b04ca98f37effcdf9097d317b9b9b8ad658f47c8")); @@ -122,6 +123,7 @@ void getBlockByHash() { } @Test + @Disabled void getBlockByHeight() { JsonBlockData blockData = casperServiceMainnet.getBlock(new HeightBlockIdentifier(0)); JsonBlock block = blockData.getBlock(); diff --git a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java index 4b72c00f2..0d86efe2e 100644 --- a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java +++ b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java @@ -11,6 +11,7 @@ import com.casper.sdk.test.PathMatchingResourceDispatcher; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -21,6 +22,7 @@ import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; +@Disabled class EventServiceIntegrationTest { private static final String MAIN_EVENTS = "/event-samples/main-events.txt"; diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java index a9d6eef75..f9a3f5383 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -18,6 +18,7 @@ import com.casper.sdk.model.key.PublicKey; import org.joda.time.DateTime; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.BufferedReader; @@ -152,6 +153,7 @@ void buildDeployAcceptedEvent() throws IOException { } @Test + @Disabled void buildDeployProcessedEvent() throws IOException { final PojoEvent deployProcessedEvent = getEvent(EventType.MAIN, EventTarget.POJO, DEPLOY_PROCESSED_EVENT); @@ -190,6 +192,7 @@ void buildFaultEvent() throws IOException, InvalidByteStringException, NoSuchAlg } @Test + @Disabled void buildStepEvent() throws IOException { final PojoEvent stepEvent = getEvent(EventType.MAIN, EventTarget.POJO, STEP_EVENT); @@ -198,6 +201,7 @@ void buildStepEvent() throws IOException { @Test + @Disabled void buildRawShutDownEvent() throws IOException { final RawEvent shutdownEvent = getEvent(EventType.MAIN, EventTarget.RAW, SHUTDOWN_EVENT); From f896438597ca8779fdde708a4f55fbdd13d6c821 Mon Sep 17 00:00:00 2001 From: Carl Norburn Date: Mon, 5 Sep 2022 13:16:21 +0100 Subject: [PATCH 08/35] added OSSRH repo --- build.gradle | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/build.gradle b/build.gradle index c54495212..9aa9e0c23 100644 --- a/build.gradle +++ b/build.gradle @@ -125,6 +125,16 @@ jacocoTestReport { publishing { repositories { + maven { + name = 'OSSRH' + def releasesRepoUrl = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/' + def snapshotsRepoUrl = 'https://s01.oss.sonatype.org/content/repositories/snapshots/' + url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl + credentials { + username = System.getenv('MAVEN_USERNAME') + password = System.getenv('MAVEN_PASSWORD') + } + } maven { name = "GitHubPackages" url = "https://maven.pkg.github.com/casper-network/casper-java-sdk" From 33ac0c2f181d70252da140ed97916180b0d5afc0 Mon Sep 17 00:00:00 2001 From: Carl Norburn Date: Mon, 5 Sep 2022 15:08:59 +0100 Subject: [PATCH 09/35] add and increment version --- build.gradle | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index 9aa9e0c23..e7eb29b8f 100644 --- a/build.gradle +++ b/build.gradle @@ -11,8 +11,9 @@ plugins { } group = 'network.casper' -version = '0.5.0-SNAPSHOT' -sourceCompatibility = '8' +version='0.5.2-SNAPSHOT' +sourceCompatibility = 1.8 +targetCompatibility = 1.8 repositories { mavenCentral() @@ -51,7 +52,7 @@ java { task casperJar(type: Jar) { archiveBaseName = 'casper-java-sdk' - archiveVersion = "$version" + archiveVersion = "0.5.2-SNAPSHOT" from { configurations.compileClasspath.findAll { it.isDirectory() ? it : zipTree(it) } } with jar } From 5674963fff64adc0acd32519372abc8d2d282cc6 Mon Sep 17 00:00:00 2001 From: Carl Norburn Date: Mon, 5 Sep 2022 15:10:21 +0100 Subject: [PATCH 10/35] remove gradle-nexus plugin --- build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/build.gradle b/build.gradle index e7eb29b8f..258b3a5fd 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,6 @@ plugins { id 'jacoco' id 'signing' id 'maven-publish' - id('io.github.gradle-nexus.publish-plugin') version '1.1.0' } group = 'network.casper' From 17153b7ec9b648a1fbbff6d211fc5c894f4bf45a Mon Sep 17 00:00:00 2001 From: Carl Norburn Date: Mon, 5 Sep 2022 15:17:45 +0100 Subject: [PATCH 11/35] make same as main branch --- build.gradle | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/build.gradle b/build.gradle index 258b3a5fd..83967fbb6 100644 --- a/build.gradle +++ b/build.gradle @@ -7,8 +7,11 @@ plugins { id 'jacoco' id 'signing' id 'maven-publish' + id('io.github.gradle-nexus.publish-plugin') version '1.1.0' } +apply plugin: 'java' + group = 'network.casper' version='0.5.2-SNAPSHOT' sourceCompatibility = 1.8 @@ -125,16 +128,6 @@ jacocoTestReport { publishing { repositories { - maven { - name = 'OSSRH' - def releasesRepoUrl = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/' - def snapshotsRepoUrl = 'https://s01.oss.sonatype.org/content/repositories/snapshots/' - url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl - credentials { - username = System.getenv('MAVEN_USERNAME') - password = System.getenv('MAVEN_PASSWORD') - } - } maven { name = "GitHubPackages" url = "https://maven.pkg.github.com/casper-network/casper-java-sdk" From f4350a3faf6fb4810fc8b5954dcb129f4fdce537 Mon Sep 17 00:00:00 2001 From: Carl Norburn Date: Tue, 6 Sep 2022 10:43:54 +0100 Subject: [PATCH 12/35] add OSSRH repo back --- build.gradle | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/build.gradle b/build.gradle index 83967fbb6..6c00adc17 100644 --- a/build.gradle +++ b/build.gradle @@ -67,6 +67,16 @@ javadoc { nexusPublishing { repositories { + maven { + name = 'OSSRH' + def releasesRepoUrl = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/' + def snapshotsRepoUrl = 'https://s01.oss.sonatype.org/content/repositories/snapshots/' + url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl + credentials { + username = System.getenv('MAVEN_USERNAME') + password = System.getenv('MAVEN_PASSWORD') + } + } sonatype { //only for users registered in Sonatype after 24 Feb 2021 nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) From 0be77843a2d2cac818c5a4f6405f66baa0cb3d54 Mon Sep 17 00:00:00 2001 From: Carl Norburn Date: Tue, 6 Sep 2022 10:58:47 +0100 Subject: [PATCH 13/35] fixed OSSRH repo typo --- build.gradle | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/build.gradle b/build.gradle index 6c00adc17..a05e4547d 100644 --- a/build.gradle +++ b/build.gradle @@ -67,16 +67,6 @@ javadoc { nexusPublishing { repositories { - maven { - name = 'OSSRH' - def releasesRepoUrl = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/' - def snapshotsRepoUrl = 'https://s01.oss.sonatype.org/content/repositories/snapshots/' - url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl - credentials { - username = System.getenv('MAVEN_USERNAME') - password = System.getenv('MAVEN_PASSWORD') - } - } sonatype { //only for users registered in Sonatype after 24 Feb 2021 nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) @@ -138,6 +128,16 @@ jacocoTestReport { publishing { repositories { + maven { + name = 'OSSRH' + def releasesRepoUrl = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/' + def snapshotsRepoUrl = 'https://s01.oss.sonatype.org/content/repositories/snapshots/' + url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl + credentials { + username = System.getenv('MAVEN_USERNAME') + password = System.getenv('MAVEN_PASSWORD') + } + } maven { name = "GitHubPackages" url = "https://maven.pkg.github.com/casper-network/casper-java-sdk" From addfd78d3a3a65955bf3b05b36a52dd389a1a804 Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Wed, 7 Sep 2022 19:34:43 -0300 Subject: [PATCH 14/35] adjusting to new de/serialization --- gradle.properties | 6 +++--- .../com/casper/sdk/service/CasperServiceTests.java | 12 ++++++++---- .../sdk/service/impl/event/EventBuilderTest.java | 7 +++---- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/gradle.properties b/gradle.properties index 2e7dfc2c6..9eef867e5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,11 +3,11 @@ cryptokeyVersion=0.3.1 lombokPluginVersion=6.2.0 jupiterVersion=5.9.0 jsonrpc4jVersion=1.6 -jacksonVersion=2.13.3 +jacksonVersion=2.13.4 jsonassertVersion=1.5.1 jsonPathAssertVersion=2.7.0 mockwebserverVersion=4.10.0 log4jVersion=2.18.0 -slf4jApiVersion=1.7.36 +slf4jApiVersion=2.0.0 javaTuplesVersion=1.2 -jodaTimeVersion=2.10.14 \ No newline at end of file +jodaTimeVersion=2.11.1 \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/service/CasperServiceTests.java b/src/test/java/com/casper/sdk/service/CasperServiceTests.java index 9b80c67c5..1b747ecf4 100644 --- a/src/test/java/com/casper/sdk/service/CasperServiceTests.java +++ b/src/test/java/com/casper/sdk/service/CasperServiceTests.java @@ -44,7 +44,11 @@ import java.util.Collections; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link CasperService} @@ -120,7 +124,7 @@ void getBlockByHash() { assertNotNull(blockData); JsonBlock block = blockData.getBlock(); - assertEquals("0000000000000000000000000000000000000000000000000000000000000000", block.getHeader().getParentHash()); + assertEquals("0000000000000000000000000000000000000000000000000000000000000000", block.getHeader().getParentHash().toString()); assertEquals(0, block.getHeader().getHeight()); } @@ -128,8 +132,8 @@ void getBlockByHash() { void getBlockByHeight() { JsonBlockData blockData = casperServiceMainnet.getBlock(new HeightBlockIdentifier(0)); JsonBlock block = blockData.getBlock(); - assertEquals("0000000000000000000000000000000000000000000000000000000000000000", block.getHeader().getParentHash()); - assertEquals("2fe9630b7790852e4409d815b04ca98f37effcdf9097d317b9b9b8ad658f47c8", block.getHash()); + assertEquals("0000000000000000000000000000000000000000000000000000000000000000", block.getHeader().getParentHash().toString()); + assertEquals("2fe9630b7790852e4409d815b04ca98f37effcdf9097d317b9b9b8ad658f47c8", block.getHash().toString()); assertNotNull(blockData); } diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java index c8329e449..6a91746d9 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -1,7 +1,6 @@ package com.casper.sdk.service.impl.event; -import com.casper.sdk.exception.InvalidByteStringException; import com.casper.sdk.model.common.Digest; import com.casper.sdk.model.event.Event; import com.casper.sdk.model.event.EventTarget; @@ -88,7 +87,7 @@ void buildApiVersionEvent() throws IOException { } @Test - void buildPojoBlockAddedMainEvent() throws IOException, InvalidByteStringException, NoSuchAlgorithmException { + void buildPojoBlockAddedMainEvent() throws IOException, NoSuchAlgorithmException { final AbstractEvent abstractEvent = getEvent(EventType.MAIN, EventTarget.POJO, BLOCK_ADDED_EVENT); @@ -123,7 +122,7 @@ void buildPojoBlockAddedMainEvent() throws IOException, InvalidByteStringExcepti } @Test - void buildFinalitySignatureSigEvent() throws IOException, InvalidByteStringException, NoSuchAlgorithmException { + void buildFinalitySignatureSigEvent() throws IOException, NoSuchAlgorithmException { final PojoEvent abstractEvent = getEvent(EventType.SIGS, EventTarget.POJO, FINALITY_SIGNATURE_EVENT); assertThat(abstractEvent.getData(), instanceOf(FinalitySignature.class)); @@ -176,7 +175,7 @@ void buildDeployExpiredEvent() throws IOException { } @Test - void buildFaultEvent() throws IOException, InvalidByteStringException, NoSuchAlgorithmException { + void buildFaultEvent() throws IOException, NoSuchAlgorithmException { final PojoEvent faultPojoEvent = getEvent(EventType.MAIN, EventTarget.POJO, FAULT_EVENT); assertThat(faultPojoEvent, is(notNullValue())); From 1799f2fb69cdb6fd3b9f687c6736709e8d7d0ae1 Mon Sep 17 00:00:00 2001 From: meywood Date: Fri, 16 Sep 2022 16:04:42 +0200 Subject: [PATCH 15/35] issues/120 - Refactor of SSE APIs to use Consumer in place of returning a Stream --- .../com/casper/sdk/service/EventConsumer.java | 31 +++ .../com/casper/sdk/service/EventService.java | 26 +- .../service/impl/event/EventServiceImpl.java | 67 +++-- .../sdk/service/impl/event/PojoEvent.java | 2 + .../sdk/service/impl/event/RawEvent.java | 2 + .../sdk/service/impl/event/StopException.java | 8 + .../service/EventServiceIntegrationTest.java | 241 ++++++++++++------ 7 files changed, 278 insertions(+), 99 deletions(-) create mode 100644 src/main/java/com/casper/sdk/service/EventConsumer.java create mode 100644 src/main/java/com/casper/sdk/service/impl/event/StopException.java diff --git a/src/main/java/com/casper/sdk/service/EventConsumer.java b/src/main/java/com/casper/sdk/service/EventConsumer.java new file mode 100644 index 000000000..da0a1dc1f --- /dev/null +++ b/src/main/java/com/casper/sdk/service/EventConsumer.java @@ -0,0 +1,31 @@ +package com.casper.sdk.service; + +import com.casper.sdk.model.event.Event; + +import java.util.function.Consumer; + +/** + * The class that is used to consume events from an SSE stream + * + * @author ian@meywood.com + */ +public abstract class EventConsumer implements Consumer> { + + private boolean stop; + + /** + * Tells the consumer to stop accepting events + */ + void stop() { + this.stop = true; + } + + /** + * Indicates if the consumer has requested to stop processing events + * + * @return true if event processing should stop otherwise false + */ + public boolean isStop() { + return stop; + } +} diff --git a/src/main/java/com/casper/sdk/service/EventService.java b/src/main/java/com/casper/sdk/service/EventService.java index c6cc113b5..30e6ad05a 100644 --- a/src/main/java/com/casper/sdk/service/EventService.java +++ b/src/main/java/com/casper/sdk/service/EventService.java @@ -6,13 +6,14 @@ import java.io.Reader; import java.net.URI; +import java.util.function.Consumer; import java.util.stream.Stream; /** * The EventService interface. *

* Is instantiated using the static create methods within the interface eg: - *

final EventService eventService = EventService.create("http://localhost:18101");
+ *
final EventService eventService = EventService.create("...");
* * @author ian@meywood.com */ @@ -24,8 +25,8 @@ public interface EventService { * @param eventType the type of event to read * @param eventTarget the target of the event JSON string or POJO * @param reader the reader to read the event from - * @param the type of the event - * @param the type of the events data content + * @param the type of the event + * @param the type of the events data content * @return the read event */ > Stream readEvent(final EventType eventType, @@ -37,15 +38,17 @@ > Stream readEvent(final EventType ev * Reads a stream of events from a node * * * - * @param eventType the type of event to read - * @param eventTarget the target of the event JSON string or POJO - * @param the type of the event - * @param the type of the events data content - * @return the read event + * @param eventType the type of event to read + * @param eventTarget the target of the event JSON string or POJO + * @param startFrom the optional event to start streaming from, if not present only obtains new events + * @param eventConsumer the consumer of the events + * @param the type of the event + * @param the type of the events data content */ - > Stream readEventStream(final EventType eventType, - final EventTarget eventTarget, - final Long startFrom); + > void consumeEvents(final EventType eventType, + final EventTarget eventTarget, + final Long startFrom, + final Consumer eventConsumer); /** @@ -67,4 +70,5 @@ static EventService usingPeer(final String host) { static EventService usingPeer(final URI uri) { return EventServiceFactory.create(uri); } + } diff --git a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java index 9f889710e..35a3ec7b0 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java +++ b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java @@ -1,9 +1,10 @@ package com.casper.sdk.service.impl.event; +import com.casper.sdk.exception.CasperClientException; import com.casper.sdk.model.event.Event; import com.casper.sdk.model.event.EventTarget; import com.casper.sdk.model.event.EventType; -import com.casper.sdk.exception.CasperClientException; +import com.casper.sdk.service.EventConsumer; import com.casper.sdk.service.EventService; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -15,12 +16,13 @@ import java.io.Reader; import java.net.URI; import java.time.Duration; +import java.util.function.Consumer; import java.util.stream.Stream; /** * Package local to prevent construction. - * - * @author ian@meywood.com + * + * @author ian@meywood.com */ @SuppressWarnings("unused") final class EventServiceImpl implements EventService { @@ -55,9 +57,25 @@ private EventServiceImpl(final URI uri) { /** {@inheritDoc} */ @Override - public > Stream readEventStream(final EventType eventType, - final EventTarget eventTarget, - final Long startFrom) { + public > Stream readEvent(final EventType eventType, + final EventTarget eventTarget, + final Reader reader) { + + final EventBuilder eventBuilder = new EventBuilder(eventType, eventTarget, uri.toString()); + + //noinspection unchecked + return new BufferedReader(reader) + .lines() + .filter(eventBuilder::processLine) + .map(line -> eventBuilder.buildEvent()); + } + + + @Override + public > void consumeEvents(final EventType eventType, + final EventTarget eventTarget, + final Long startFrom, + final Consumer eventTConsumer) { try { //noinspection resource final Response response = this.client.newCall( @@ -71,7 +89,7 @@ public > Stream readEventStream(final EventType eventTy if (response.isSuccessful() && response.body() != null) { //noinspection ConstantConditions - return readEvent(eventType, eventTarget, new InputStreamReader(response.body().byteStream())); + consumeEvent(eventType, eventTarget, new InputStreamReader(response.body().byteStream()), eventTConsumer); } else { throw new CasperClientException("No response from node " + this.uri); } @@ -80,18 +98,33 @@ public > Stream readEventStream(final EventType eventTy } } - /** {@inheritDoc} */ - @Override - public > Stream readEvent(final EventType eventType, - final EventTarget eventTarget, - final Reader reader) { + private > void consumeEvent(final EventType eventType, + final EventTarget eventTarget, + final Reader reader, + final Consumer consumer) { + final EventBuilder eventBuilder = new EventBuilder(eventType, eventTarget, uri.toString()); - //noinspection unchecked - return new BufferedReader(reader) - .lines() - .filter(eventBuilder::processLine) - .map(line -> eventBuilder.buildEvent()); + try { + //noinspection unchecked + new BufferedReader(reader) + .lines() + .filter(line -> throwOnStop(consumer)) + .filter(eventBuilder::processLine) + .forEach(line -> consumer.accept(eventBuilder.buildEvent())); + + } catch (StopException e) { + // The consumer asked to stop reading events + } + } + + private + boolean throwOnStop(final Consumer consumer) { + if (consumer instanceof EventConsumer && ((EventConsumer) consumer).isStop()) { + throw new StopException(); + } + return true; + } } diff --git a/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java b/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java index 61f0f40de..39874e9df 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java @@ -4,6 +4,7 @@ import com.casper.sdk.model.event.EventType; import com.casper.sdk.model.event.EventData; import com.casper.sdk.model.event.EventTarget; +import lombok.ToString; /** * An event that contains the event data as Pojo model returned from the event service when @@ -12,6 +13,7 @@ * @param the types of the expected EventData * @author ian@meywood.com */ +@ToString(doNotUseGetters = true, callSuper = true) final class PojoEvent extends AbstractEvent { PojoEvent(final EventType eventType, final String source, final Long id, T data) { diff --git a/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java index 4f883a922..651b60b54 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java @@ -3,6 +3,7 @@ import com.casper.sdk.model.event.DataType; import com.casper.sdk.model.event.EventTarget; import com.casper.sdk.model.event.EventType; +import lombok.ToString; /** * An event that contains the event data as raw JSON without the 'data:' prefix is returned from the event service when @@ -10,6 +11,7 @@ * * @author ian@meywood.com */ +@ToString(doNotUseGetters = true, callSuper = true) final class RawEvent extends AbstractEvent { RawEvent(final EventType eventType, final String source, final Long id, final String data) { diff --git a/src/main/java/com/casper/sdk/service/impl/event/StopException.java b/src/main/java/com/casper/sdk/service/impl/event/StopException.java new file mode 100644 index 000000000..e35ad7c69 --- /dev/null +++ b/src/main/java/com/casper/sdk/service/impl/event/StopException.java @@ -0,0 +1,8 @@ +package com.casper.sdk.service.impl.event; + +/** + * An exception that is thrown to stop reading another line from the SSE service + * @author ian@meywood.com + */ +public class StopException extends RuntimeException { +} diff --git a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java index 0d86efe2e..6ffa50811 100644 --- a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java +++ b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java @@ -22,7 +22,7 @@ import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; -@Disabled +//@Disabled class EventServiceIntegrationTest { private static final String MAIN_EVENTS = "/event-samples/main-events.txt"; @@ -40,6 +40,95 @@ void tearDown() throws IOException { mockNode.shutdown(); } + + @Test + void consumeMainRawEvents() { + + mockNode.setDispatcher( + new PathMatchingResourceDispatcher(MAIN_EVENTS, is("/events/main?start_from=0")) + ); + + int[] count = {0}; + + eventService.consumeEvents(EventType.MAIN, EventTarget.RAW, 0L, new EventConsumer() { + @Override + public void accept(final Event event) { + + assertThat(event, instanceOf(Event.class)); + assertThat(event.getClass().getSimpleName(), is("RawEvent")); + + assertThat(event.getEventType(), is(EventType.MAIN)); + + if (count[0] == 0) { + assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); + assertThat(event.getId().isPresent(), is(false)); + } else if (count[0] == 1) { + assertThat(event.getData(), startsWith("data:{\"Step\":{\"era_id\":0,\"execution_effect\":{\"operations\":[],")); + assertThat(event.getData(), endsWith("\"bytes\":\"03f5d62682010000\",\"parsed\":1658508997891}}}]}}}")); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(0L)); + } else if (count[0] == 3) { + assertThat( + event.getData(), + is("data:{\"BlockAdded\":{\"block_hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\"," + + "\"block\":{\"hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\",\"header\":" + + "{\"parent_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\"," + + "\"state_root_hash\":\"fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc\"," + + "\"body_hash\":\"980531392fb02fd03d632abaa17f0a59bc788ea5b86ff9ce4630851cf9c2b4cf\"," + + "\"random_bit\":true,\"accumulated_seed\":\"ab5d756563bf09545590bd95f9a8e7978d51760be95ea8e5c9bab58ba1129186\"," + + "\"era_end\":null,\"timestamp\":\"2022-07-22T16:56:40.704Z\",\"era_id\":1,\"height\":1," + + "\"protocol_version\":\"1.0.0\"},\"body\":{\"proposer\":\"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5\"," + + "\"deploy_hashes\":[],\"transfer_hashes\":[]},\"proofs\":[]}}}") + ); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(7L)); + + } + count[0]++; + + } + }); + } + + @Test + void consumeMainRawEventsWithStop() { + + mockNode.setDispatcher( + new PathMatchingResourceDispatcher(MAIN_EVENTS, is("/events/main?start_from=0")) + ); + + int[] count = {0}; + + eventService.consumeEvents(EventType.MAIN, EventTarget.RAW, 0L, new EventConsumer() { + @Override + public void accept(final Event event) { + + assertThat(event, instanceOf(Event.class)); + assertThat(event.getClass().getSimpleName(), is("RawEvent")); + + assertThat(event.getEventType(), is(EventType.MAIN)); + + if (count[0] == 0) { + assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); + assertThat(event.getId().isPresent(), is(false)); + } else if (count[0] == 1) { + assertThat(event.getData(), startsWith("data:{\"Step\":{\"era_id\":0,\"execution_effect\":{\"operations\":[],")); + assertThat(event.getData(), endsWith("\"bytes\":\"03f5d62682010000\",\"parsed\":1658508997891}}}]}}}")); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(0L)); + // STOP ANY FURTHER EVENTS!!! + this.stop(); + } else if (count[0] > 1) { + throw new IllegalArgumentException("Should have stopped at 1"); + + } + count[0]++; + } + }); + + assertThat(count[0], is(2)); + } + @Test void mainRawEvents() { @@ -49,42 +138,44 @@ void mainRawEvents() { int[] count = {0}; - eventService.readEventStream(EventType.MAIN, EventTarget.RAW, 0L).forEach(e -> { - - assertThat(e, instanceOf(Event.class)); - - //noinspection unchecked,rawtypes - final Event event = (Event) e; - assertThat(event.getEventType(), is(EventType.MAIN)); - - if (count[0] == 0) { - assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); - assertThat(event.getId().isPresent(), is(false)); - } else if (count[0] == 1) { - assertThat(event.getData(), startsWith("data:{\"Step\":{\"era_id\":0,\"execution_effect\":{\"operations\":[],")); - assertThat(event.getData(), endsWith("\"bytes\":\"03f5d62682010000\",\"parsed\":1658508997891}}}]}}}")); - assertThat(event.getId().isPresent(), is(true)); - assertThat(event.getId().get(), is(0L)); - } else if (count[0] == 3) { - assertThat( - event.getData(), - is("data:{\"BlockAdded\":{\"block_hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\"," + - "\"block\":{\"hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\",\"header\":" + - "{\"parent_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\"," + - "\"state_root_hash\":\"fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc\"," + - "\"body_hash\":\"980531392fb02fd03d632abaa17f0a59bc788ea5b86ff9ce4630851cf9c2b4cf\"," + - "\"random_bit\":true,\"accumulated_seed\":\"ab5d756563bf09545590bd95f9a8e7978d51760be95ea8e5c9bab58ba1129186\"," + - "\"era_end\":null,\"timestamp\":\"2022-07-22T16:56:40.704Z\",\"era_id\":1,\"height\":1," + - "\"protocol_version\":\"1.0.0\"},\"body\":{\"proposer\":\"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5\"," + - "\"deploy_hashes\":[],\"transfer_hashes\":[]},\"proofs\":[]}}}") - ); - assertThat(event.getId().isPresent(), is(true)); - assertThat(event.getId().get(), is(7L)); + eventService.consumeEvents(EventType.MAIN, EventTarget.RAW, 0L, new EventConsumer() { + @Override + public void accept(Event event) { + assertThat(event, instanceOf(Event.class)); + + assertThat(event.getEventType(), is(EventType.MAIN)); + + if (count[0] == 0) { + assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); + assertThat(event.getId().isPresent(), is(false)); + } else if (count[0] == 1) { + assertThat(event.getData(), startsWith("data:{\"Step\":{\"era_id\":0,\"execution_effect\":{\"operations\":[],")); + assertThat(event.getData(), endsWith("\"bytes\":\"03f5d62682010000\",\"parsed\":1658508997891}}}]}}}")); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(0L)); + } else if (count[0] == 3) { + assertThat( + event.getData(), + is("data:{\"BlockAdded\":{\"block_hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\"," + + "\"block\":{\"hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\",\"header\":" + + "{\"parent_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\"," + + "\"state_root_hash\":\"fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc\"," + + "\"body_hash\":\"980531392fb02fd03d632abaa17f0a59bc788ea5b86ff9ce4630851cf9c2b4cf\"," + + "\"random_bit\":true,\"accumulated_seed\":\"ab5d756563bf09545590bd95f9a8e7978d51760be95ea8e5c9bab58ba1129186\"," + + "\"era_end\":null,\"timestamp\":\"2022-07-22T16:56:40.704Z\",\"era_id\":1,\"height\":1," + + "\"protocol_version\":\"1.0.0\"},\"body\":{\"proposer\":\"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5\"," + + "\"deploy_hashes\":[],\"transfer_hashes\":[]},\"proofs\":[]}}}") + ); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(7L)); + + } + count[0]++; } - count[0]++; }); + assertThat(count[0], is(4)); } @@ -97,33 +188,38 @@ void sigsRawEvents() { int[] count = {0}; - eventService.readEventStream(EventType.SIGS, EventTarget.RAW, 0L).forEach(e -> { - - //noinspection unchecked,rawtypes - final Event event = (Event) e; - assertThat(event.getEventType(), is(EventType.SIGS)); - - if (count[0] == 0) { - assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); - assertThat(event.getId().isPresent(), is(false)); - } else if (count[0] == 1) { - assertThat( - event.getData(), - is("data:{\"FinalitySignature\":{\"block_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\"," + - "\"era_id\":0,\"signature\":\"0141eba160bb11448c663aa574de7a87554adb01531b1c6e93f31d4e998d5e5b4bdd71aa67442e3e5ffd8c75f709ad68ecbec9f116f4c50c49198098d30486dc02\"," + - "\"public_key\":\"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565\"}}") - ); - assertThat(event.getId().isPresent(), is(true)); - assertThat(event.getId().get(), is(1L)); + eventService.consumeEvents(EventType.SIGS, EventTarget.RAW, 0L, new EventConsumer() { + + @Override + public void accept(Event event) { + + assertThat(event.getEventType(), is(EventType.SIGS)); + + if (count[0] == 0) { + assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); + assertThat(event.getId().isPresent(), is(false)); + } else if (count[0] == 1) { + assertThat( + event.getData(), + is("data:{\"FinalitySignature\":{\"block_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\"," + + "\"era_id\":0,\"signature\":\"0141eba160bb11448c663aa574de7a87554adb01531b1c6e93f31d4e998d5e5b4bdd71aa67442e3e5ffd8c75f709ad68ecbec9f116f4c50c49198098d30486dc02\"," + + "\"public_key\":\"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565\"}}") + ); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(1L)); + } + count[0]++; } - count[0]++; }); + assertThat(count[0], is(5)); } @Test + @Disabled + // Re-enable once SDK correctly deserializes CLValueMap toy ANY type void mainPojoEvents() { mockNode.setDispatcher( @@ -131,28 +227,31 @@ void mainPojoEvents() { ); int[] count = {0}; - eventService.readEventStream(EventType.MAIN, EventTarget.POJO, 0L).forEach(e -> { - - //noinspection unchecked,rawtypes - final Event event = (Event) e; - assertThat(event.getEventType(), is(EventType.MAIN)); - - EventData data = event.getData(); - - if (count[0] == 0) { - assertThat(data, instanceOf(ApiVersion.class)); - assertThat(((ApiVersion) data).getApiVersion(), is("1.0.0")); - assertThat(event.getId().isPresent(), is(false)); - } else if (count[0] == 1) { - assertThat(data, instanceOf(Step.class)); - assertThat(event.getId().isPresent(), is(true)); - assertThat(event.getId().get(), is(0L)); - } - count[0]++; + eventService.consumeEvents(EventType.MAIN, EventTarget.RAW, 0L, new EventConsumer() { + + @Override + public void accept(Event event) { + + assertThat(event.getEventType(), is(EventType.MAIN)); + + final EventData data = event.getData(); + + if (count[0] == 0) { + assertThat(data, instanceOf(ApiVersion.class)); + assertThat(((ApiVersion) data).getApiVersion(), is("1.0.0")); + assertThat(event.getId().isPresent(), is(false)); + } else if (count[0] == 1) { + assertThat(data, instanceOf(Step.class)); + assertThat(event.getId().isPresent(), is(true)); + assertThat(event.getId().get(), is(0L)); + } + + count[0]++; + } }); - assertThat(count[0], is(greaterThan(2))); + assertThat(count[0], is(greaterThan(2))); } } \ No newline at end of file From 0a87ffe665a1cd738836f08cda650ecd7d4df63b Mon Sep 17 00:00:00 2001 From: meywood Date: Fri, 16 Sep 2022 16:12:04 +0200 Subject: [PATCH 16/35] issues/120 - Refactor of SSE APIs to use Consumer in place of returning a Stream --- .../com/casper/sdk/service/EventService.java | 26 +++------------- .../service/impl/event/EventServiceImpl.java | 30 ++++--------------- 2 files changed, 10 insertions(+), 46 deletions(-) diff --git a/src/main/java/com/casper/sdk/service/EventService.java b/src/main/java/com/casper/sdk/service/EventService.java index 30e6ad05a..328ea2e20 100644 --- a/src/main/java/com/casper/sdk/service/EventService.java +++ b/src/main/java/com/casper/sdk/service/EventService.java @@ -4,10 +4,8 @@ import com.casper.sdk.model.event.EventTarget; import com.casper.sdk.model.event.EventType; -import java.io.Reader; import java.net.URI; import java.util.function.Consumer; -import java.util.stream.Stream; /** * The EventService interface. @@ -19,20 +17,6 @@ */ public interface EventService { - /** - * Reads a single event from a reader - * - * @param eventType the type of event to read - * @param eventTarget the target of the event JSON string or POJO - * @param reader the reader to read the event from - * @param the type of the event - * @param the type of the events data content - * @return the read event - */ - > Stream readEvent(final EventType eventType, - final EventTarget eventTarget, - final Reader reader); - /** * Reads a stream of events from a node @@ -43,12 +27,11 @@ > Stream readEvent(final EventType ev * @param startFrom the optional event to start streaming from, if not present only obtains new events * @param eventConsumer the consumer of the events * @param the type of the event - * @param the type of the events data content */ - > void consumeEvents(final EventType eventType, - final EventTarget eventTarget, - final Long startFrom, - final Consumer eventConsumer); + > void consumeEvents(final EventType eventType, + final EventTarget eventTarget, + final Long startFrom, + final Consumer eventConsumer); /** @@ -70,5 +53,4 @@ static EventService usingPeer(final String host) { static EventService usingPeer(final URI uri) { return EventServiceFactory.create(uri); } - } diff --git a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java index 35a3ec7b0..6817e495b 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java +++ b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java @@ -17,7 +17,6 @@ import java.net.URI; import java.time.Duration; import java.util.function.Consumer; -import java.util.stream.Stream; /** * Package local to prevent construction. @@ -55,27 +54,11 @@ private EventServiceImpl(final URI uri) { .build(); } - /** {@inheritDoc} */ @Override - public > Stream readEvent(final EventType eventType, - final EventTarget eventTarget, - final Reader reader) { - - final EventBuilder eventBuilder = new EventBuilder(eventType, eventTarget, uri.toString()); - - //noinspection unchecked - return new BufferedReader(reader) - .lines() - .filter(eventBuilder::processLine) - .map(line -> eventBuilder.buildEvent()); - } - - - @Override - public > void consumeEvents(final EventType eventType, - final EventTarget eventTarget, - final Long startFrom, - final Consumer eventTConsumer) { + public > void consumeEvents(final EventType eventType, + final EventTarget eventTarget, + final Long startFrom, + final Consumer eventTConsumer) { try { //noinspection resource final Response response = this.client.newCall( @@ -119,9 +102,8 @@ private > void consumeEvent(final EventType e } } - private - boolean throwOnStop(final Consumer consumer) { - if (consumer instanceof EventConsumer && ((EventConsumer) consumer).isStop()) { + private boolean throwOnStop(final Consumer consumer) { + if (consumer instanceof EventConsumer && ((EventConsumer) consumer).isStop()) { throw new StopException(); } return true; From 628c8f3d6c73a995a1095adf50b72a30ca78be75 Mon Sep 17 00:00:00 2001 From: meywood Date: Tue, 20 Sep 2022 10:04:50 +0100 Subject: [PATCH 17/35] issues/120 - Refactor of SSE APIs to use Consumer in place of returning a Stream --- .../com/casper/sdk/service/EventService.java | 16 +----- .../sdk/service/EventServiceFactory.java | 15 +---- .../service/impl/event/CLTypeErrorsTest.java | 8 --- .../service/impl/event/EventServiceImpl.java | 12 ++-- .../sdk/service/impl/event/RawEvent.java | 2 +- .../sdk/service/EventServiceFactoryTest.java | 4 +- .../service/EventServiceIntegrationTest.java | 55 ++++++++++--------- 7 files changed, 43 insertions(+), 69 deletions(-) delete mode 100644 src/main/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java diff --git a/src/main/java/com/casper/sdk/service/EventService.java b/src/main/java/com/casper/sdk/service/EventService.java index 328ea2e20..75b5efae5 100644 --- a/src/main/java/com/casper/sdk/service/EventService.java +++ b/src/main/java/com/casper/sdk/service/EventService.java @@ -11,13 +11,12 @@ * The EventService interface. *

* Is instantiated using the static create methods within the interface eg: - *

final EventService eventService = EventService.create("...");
+ *
final EventService eventService = EventService.usingPeer("...");
* * @author ian@meywood.com */ public interface EventService { - /** * Reads a stream of events from a node * * @@ -33,21 +32,10 @@ > void consumeEvents(final EventType eventType, final Long startFrom, final Consumer eventConsumer); - - /** - * Creates a new EventService for the specified host including protocol and port - * - * @param host the host including protocol and port eg: http:/localhost:18101 - * @return the event service for the specified host - */ - static EventService usingPeer(final String host) { - return EventServiceFactory.create(host); - } - /** * Creates a new EventService for the specified host including protocol and port * - * @param uri the uri of the host to connect to + * @param uri the uri of the host to connect to must include protocol, hostname, and port number * @return the event service for the specified host */ static EventService usingPeer(final URI uri) { diff --git a/src/main/java/com/casper/sdk/service/EventServiceFactory.java b/src/main/java/com/casper/sdk/service/EventServiceFactory.java index 79ff82070..d44e82830 100644 --- a/src/main/java/com/casper/sdk/service/EventServiceFactory.java +++ b/src/main/java/com/casper/sdk/service/EventServiceFactory.java @@ -22,16 +22,8 @@ final class EventServiceFactory { private static final String IMPLEMENTATION_CLASS = "com.casper.sdk.service.impl.event.EventServiceImpl"; /** The map of service method names to log */ private static final Map> methodParamMap = new HashMap<>(); - - /** - * Creates a new EventService for the specified host - * - * @param host the host to connect to including protocol and port eg:
http://localhost:18101
- * @return a newly created event service - */ - static EventService create(final String host) { - return proxy(createEventService(host)); - } + /** The logger that logs all event service calls at debug level */ + private static final Logger logger = LoggerFactory.getLogger(EventService.class); /** * Creates a new EventService for the specified host @@ -45,8 +37,6 @@ static EventService create(final URI uri) { private static EventService proxy(final EventService eventService) { - final Logger logger = LoggerFactory.getLogger(EventService.class); - return (EventService) Proxy.newProxyInstance( EventServiceFactory.class.getClassLoader(), new Class[]{EventService.class}, @@ -66,6 +56,7 @@ private static boolean isServiceMethod(final Method method) { private static EventService createEventService(final Object param) { try { + //noinspection JavaReflectionMemberAccess final Constructor constructor = Class.forName(IMPLEMENTATION_CLASS) .getDeclaredConstructor(param.getClass()); constructor.setAccessible(true); diff --git a/src/main/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java b/src/main/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java deleted file mode 100644 index c1e333b9e..000000000 --- a/src/main/java/com/casper/sdk/service/impl/event/CLTypeErrorsTest.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.casper.sdk.service.impl.event; - -/** - * - * @author ian@meywood.com - */ -public class CLTypeErrorsTest { -} diff --git a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java index 6817e495b..fe9a9cd60 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java +++ b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java @@ -40,11 +40,12 @@ final class EventServiceImpl implements EventService { /** The HTTP Client to connect to the node with */ final OkHttpClient client; - @SuppressWarnings("unused") - private EventServiceImpl(final String host) { - this(URI.create(host)); - } - + /** + * Constructs a new {@link EventServiceImpl}, is private to prevent API users construction manually. To create the + * service user the interface method {@link EventService#usingPeer(URI)}. + * + * @param uri the URL if the node to connect to must contain protocol, host and port number + */ private EventServiceImpl(final URI uri) { this.uri = uri; @@ -107,6 +108,5 @@ private boolean throwOnStop(final Consumer consumer) { throw new StopException(); } return true; - } } diff --git a/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java index 651b60b54..fbf440483 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java @@ -22,7 +22,7 @@ private static DataType getDataType(final String data) { final int start = data.indexOf(':'); final int end = data.indexOf(':', start + 1); final String dataTypeName = data.substring(start + 3, end - 1); - return DataType.of(dataTypeName); + return DataType.of(dataTypeName.trim()); } } diff --git a/src/test/java/com/casper/sdk/service/EventServiceFactoryTest.java b/src/test/java/com/casper/sdk/service/EventServiceFactoryTest.java index 322608f1d..fed0ba807 100644 --- a/src/test/java/com/casper/sdk/service/EventServiceFactoryTest.java +++ b/src/test/java/com/casper/sdk/service/EventServiceFactoryTest.java @@ -18,8 +18,8 @@ class EventServiceFactoryTest { @Test - void createUsingHostString() { - final EventService eventService = EventServiceFactory.create("http://localhost:18101"); + void createUsingHostString() throws URISyntaxException { + final EventService eventService = EventServiceFactory.create(new URI("http://localhost:18101")); assertEventServiceProxied(eventService); } diff --git a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java index 6ffa50811..9e4dde393 100644 --- a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java +++ b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java @@ -27,8 +27,14 @@ class EventServiceIntegrationTest { private static final String MAIN_EVENTS = "/event-samples/main-events.txt"; private static final String SIGS_EVENTS = "/event-samples/sigs-events.txt"; + + private static final String DEPLOYS_EVENTS = "/event-samples/deploys-events.txt"; private final MockNode mockNode = new MockNode(); - private final EventService eventService = EventService.usingPeer("http://localhost:28101"); + private final EventService eventService; + + EventServiceIntegrationTest() throws URISyntaxException { + eventService = EventService.usingPeer(new URI("http://localhost:28101")); + } @BeforeEach void setUp() throws URISyntaxException, IOException { @@ -130,53 +136,51 @@ public void accept(final Event event) { } @Test - void mainRawEvents() { + void deployRawEvents() { mockNode.setDispatcher( - new PathMatchingResourceDispatcher(MAIN_EVENTS, is("/events/main?start_from=0")) + new PathMatchingResourceDispatcher(DEPLOYS_EVENTS, is("/events/deploys?start_from=0")) ); - int[] count = {0}; - eventService.consumeEvents(EventType.MAIN, EventTarget.RAW, 0L, new EventConsumer() { + eventService.consumeEvents(EventType.DEPLOYS, EventTarget.RAW, 0L, new EventConsumer() { + @Override public void accept(Event event) { - assertThat(event, instanceOf(Event.class)); - assertThat(event.getEventType(), is(EventType.MAIN)); + assertThat(event.getEventType(), is(EventType.DEPLOYS)); if (count[0] == 0) { assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); assertThat(event.getId().isPresent(), is(false)); } else if (count[0] == 1) { - assertThat(event.getData(), startsWith("data:{\"Step\":{\"era_id\":0,\"execution_effect\":{\"operations\":[],")); - assertThat(event.getData(), endsWith("\"bytes\":\"03f5d62682010000\",\"parsed\":1658508997891}}}]}}}")); - assertThat(event.getId().isPresent(), is(true)); - assertThat(event.getId().get(), is(0L)); - } else if (count[0] == 3) { assertThat( event.getData(), - is("data:{\"BlockAdded\":{\"block_hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\"," + - "\"block\":{\"hash\":\"c77080456598933f9b0a68827314f8da3a0b10d1a7532d1737352d9f3a36a534\",\"header\":" + - "{\"parent_hash\":\"bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c\"," + - "\"state_root_hash\":\"fbd89036ca934a53b14ebc99abcf64351008ac073848c0b384771036121a25cc\"," + - "\"body_hash\":\"980531392fb02fd03d632abaa17f0a59bc788ea5b86ff9ce4630851cf9c2b4cf\"," + - "\"random_bit\":true,\"accumulated_seed\":\"ab5d756563bf09545590bd95f9a8e7978d51760be95ea8e5c9bab58ba1129186\"," + - "\"era_end\":null,\"timestamp\":\"2022-07-22T16:56:40.704Z\",\"era_id\":1,\"height\":1," + - "\"protocol_version\":\"1.0.0\"},\"body\":{\"proposer\":\"010d23984fefcce099679a24496f1d3072a540b95d321f8ba951df0cfe2c0691e5\"," + - "\"deploy_hashes\":[],\"transfer_hashes\":[]},\"proofs\":[]}}}") + is("data:{\"DeployAccepted\":{\"hash\":\"fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087\"," + + "\"header\":{\"account\":\"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565\"," + + "\"timestamp\":\"2022-07-26T14:37:15.150Z\",\"ttl\":\"30m\",\"gas_price\":10," + + "\"body_hash\":\"c2930c761cdc90241e7bfd2c5bbc5805ec9511845cb4820f997fa57334a33723\"," + + "\"dependencies\":[],\"chain_name\":\"casper-net-1\"},\"payment\":{\"ModuleBytes\":" + + "{\"module_bytes\":\"\",\"args\":[[\"amount\",{\"cl_type\":\"U512\"," + + "\"bytes\":\"0500e40b5402\",\"parsed\":\"10000000000\"}]]}},\"session\":" + + "{\"Transfer\":{\"args\":[[\"amount\",{\"cl_type\":\"U512\",\"bytes\":\"0400f90295\"," + + "\"parsed\":\"2500000000\"}],[\"target\",{\"cl_type\":{\"ByteArray\":32},\"bytes\":" + + "\"a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67\",\"parsed\":" + + "\"a6cdb6f049363f6ab119be0c961c36e4a3c09319589341dd861f405d9836fc67\"}]," + + "[\"id\",{\"cl_type\":{\"Option\":\"U64\"},\"bytes\":\"010100000000000000\",\"parsed\":1}]]}}," + + "\"approvals\":[{\"signer\":\"01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565\"," + + "\"signature\":\"01e57c01fc538fe057eac09d55360c70b6b7830548582c9931832af78149c66a698a41f33ca06904898138bda6767cfc5f60f26a11980ad5f95f489dcccc2fa80d\"}]}}") ); assertThat(event.getId().isPresent(), is(true)); - assertThat(event.getId().get(), is(7L)); - + assertThat(event.getId().get(), is(2951L)); } count[0]++; } }); - assertThat(count[0], is(4)); + assertThat(count[0], is(2)); } @Test @@ -218,8 +222,7 @@ public void accept(Event event) { @Test - @Disabled - // Re-enable once SDK correctly deserializes CLValueMap toy ANY type + @Disabled // Re-enable once SDK correctly deserializes CLValueMap toy ANY type void mainPojoEvents() { mockNode.setDispatcher( From d7847b0d0060b87f7db9c314cb7cba850c333b76 Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Wed, 28 Sep 2022 11:42:32 +0200 Subject: [PATCH 18/35] Generalizing serialization to support both byte and json --- .../casper/sdk/helper/CasperDeployHelper.java | 25 +++++++++++------ .../sdk/model/clvalue/AbstractCLValue.java | 3 +- .../casper/sdk/model/clvalue/CLValueAny.java | 11 +++----- .../casper/sdk/model/clvalue/CLValueBool.java | 5 ++-- .../sdk/model/clvalue/CLValueByteArray.java | 5 ++-- .../sdk/model/clvalue/CLValueFixedList.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueI32.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueI64.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueKey.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueList.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueMap.java | 5 ++-- .../sdk/model/clvalue/CLValueOption.java | 7 +++-- .../sdk/model/clvalue/CLValuePublicKey.java | 5 ++-- .../sdk/model/clvalue/CLValueResult.java | 5 ++-- .../sdk/model/clvalue/CLValueString.java | 5 ++-- .../sdk/model/clvalue/CLValueTuple1.java | 5 ++-- .../sdk/model/clvalue/CLValueTuple2.java | 5 ++-- .../sdk/model/clvalue/CLValueTuple3.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueU128.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueU256.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueU32.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueU512.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueU64.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueU8.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueURef.java | 5 ++-- .../casper/sdk/model/clvalue/CLValueUnit.java | 5 ++-- .../sdk/model/clvalue/cltype/CLTypeData.java | 28 ++----------------- .../model/clvalue/cltype/CLTypeFixedList.java | 2 +- .../sdk/model/clvalue/cltype/CLTypeList.java | 2 +- .../sdk/model/clvalue/cltype/CLTypeMap.java | 6 +--- .../model/clvalue/cltype/CLTypeOption.java | 2 +- .../model/clvalue/cltype/CLTypeResult.java | 8 ++---- .../serde/CasperSerializableObject.java | 8 +++--- .../sdk/model/clvalue/serde/Target.java | 6 ++++ .../com/casper/sdk/model/common/Digest.java | 3 +- .../java/com/casper/sdk/model/common/Ttl.java | 3 +- .../com/casper/sdk/model/deploy/Approval.java | 9 ++++-- .../com/casper/sdk/model/deploy/Deploy.java | 13 +++++---- .../casper/sdk/model/deploy/DeployHeader.java | 11 +++++--- .../com/casper/sdk/model/deploy/NamedArg.java | 5 ++-- .../deploy/executabledeploy/ModuleBytes.java | 5 ++-- .../StoredContractByHash.java | 5 ++-- .../StoredContractByName.java | 5 ++-- .../StoredVersionedContractByHash.java | 5 ++-- .../StoredVersionedContractByName.java | 5 ++-- .../deploy/executabledeploy/Transfer.java | 5 ++-- .../key/AbstractSerializedKeyTaggedHex.java | 3 +- .../model/deploy/DeploySerializationTest.java | 3 +- 48 files changed, 159 insertions(+), 139 deletions(-) create mode 100644 src/main/java/com/casper/sdk/model/clvalue/serde/Target.java diff --git a/src/main/java/com/casper/sdk/helper/CasperDeployHelper.java b/src/main/java/com/casper/sdk/helper/CasperDeployHelper.java index 231107b15..76e7be172 100644 --- a/src/main/java/com/casper/sdk/helper/CasperDeployHelper.java +++ b/src/main/java/com/casper/sdk/helper/CasperDeployHelper.java @@ -1,13 +1,15 @@ package com.casper.sdk.helper; import com.casper.sdk.exception.NoSuchTypeException; - -import com.casper.sdk.model.clvalue.CLValueByteArray; import com.casper.sdk.model.clvalue.CLValueU512; import com.casper.sdk.model.clvalue.cltype.CLTypeU512; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.common.Digest; import com.casper.sdk.model.common.Ttl; -import com.casper.sdk.model.deploy.*; +import com.casper.sdk.model.deploy.Approval; +import com.casper.sdk.model.deploy.Deploy; +import com.casper.sdk.model.deploy.DeployHeader; +import com.casper.sdk.model.deploy.NamedArg; import com.casper.sdk.model.deploy.executabledeploy.ExecutableDeployItem; import com.casper.sdk.model.deploy.executabledeploy.ModuleBytes; import com.casper.sdk.model.key.PublicKey; @@ -16,11 +18,16 @@ import com.syntifi.crypto.key.hash.Blake2b; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.*; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; import java.math.BigInteger; import java.security.GeneralSecurityException; -import java.util.*; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; /** * Deploy Service class implementing the process to generate deploys @@ -48,10 +55,10 @@ public static DeployHeader buildDeployHeader(PublicKey fromPublicKey, String cha } public static HashAndSignature signDeployHeader(AbstractPrivateKey privateKey, DeployHeader deployHeader) - throws GeneralSecurityException { + throws GeneralSecurityException, NoSuchTypeException, ValueSerializationException { SerializerBuffer serializerBuffer = new SerializerBuffer(); - deployHeader.serialize(serializerBuffer, true); + deployHeader.serialize(serializerBuffer, Target.BYTE); byte[] headerHash = Blake2b.digest(serializerBuffer.toByteArray(), 32); Signature signature = Signature.sign(privateKey, headerHash); return new HashAndSignature(headerHash, signature); @@ -60,8 +67,8 @@ public static HashAndSignature signDeployHeader(AbstractPrivateKey privateKey, D public static byte[] getDeployItemAndModuleBytesHash(ExecutableDeployItem deployItem, ModuleBytes moduleBytes) throws NoSuchTypeException, ValueSerializationException { SerializerBuffer ser = new SerializerBuffer(); - moduleBytes.serialize(ser, true); - deployItem.serialize(ser, true); + moduleBytes.serialize(ser, Target.BYTE); + deployItem.serialize(ser, Target.BYTE); return Blake2b.digest(ser.toByteArray(), 32); } diff --git a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java index 048245e51..63a50a8dc 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java +++ b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java @@ -6,6 +6,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLType; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.annotation.JsonTypeResolver; @@ -70,7 +71,7 @@ protected void setJsonBytes(String bytes) { public abstract void setClType(P value); - public abstract void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException; + public abstract void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException; public abstract void deserialize(DeserializerBuffer deserializerBuffer) throws ValueDeserializationException; diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java index 90672e855..a13932691 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeAny; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -14,11 +15,7 @@ import lombok.NoArgsConstructor; import lombok.Setter; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; +import java.io.*; /** * Casper Object CLValue implementation @@ -52,7 +49,7 @@ public CLValueAny(Object value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -62,7 +59,7 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSeri ser.writeI32(objectByteArray.length); ser.writeByteArray(objectByteArray); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } catch (IOException e) { diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java index aff7be060..ef68483b6 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeBool; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -46,12 +47,12 @@ public CLValueBool(Boolean value) { } @Override - public void serialize(@NotNull SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(@NotNull SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeBool(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java index 74d23e400..c7cc469fa 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeByteArray; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -35,12 +36,12 @@ public CLValueByteArray(byte[] value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeByteArray(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java index adfebc3e5..060cb8e0c 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java @@ -5,6 +5,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeFixedList; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -40,7 +41,7 @@ public CLValueFixedList(List> value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; setListType(); @@ -49,7 +50,7 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSeri child.serialize(ser); } - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java index 710b1fd32..2bc59ce5d 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeI32; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -43,12 +44,12 @@ public CLValueI32(Integer value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeI32(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java index a9d8086aa..1cc96c0e5 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeI64; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -45,12 +46,12 @@ public CLValueI64(Long value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeI64(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java index def070b94..d4fc9a4be 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java @@ -4,6 +4,7 @@ import com.casper.sdk.exception.NoSuchKeyTagException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeKey; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.key.Key; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; @@ -48,13 +49,13 @@ public CLValueKey(Key value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeU8(this.getValue().getTag().getByteTag()); ser.writeByteArray(this.getValue().getKey()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java index 38b80d6f5..eb4f75f87 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java @@ -5,6 +5,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeList; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -40,7 +41,7 @@ public CLValueList(List> value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; setListType(); @@ -53,7 +54,7 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSeri child.serialize(ser); } - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java index 8a46399e0..809dd0849 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java @@ -5,6 +5,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeMap; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -42,7 +43,7 @@ public CLValueMap(Map, ? extends AbstractCLValue } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; setChildTypes(); @@ -55,7 +56,7 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSeri entry.getValue().serialize(ser); } - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java index ae088b36c..5568c9064 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java @@ -5,6 +5,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeOption; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -43,8 +44,8 @@ public CLValueOption(Optional> value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { - if (this.getValue() == null) return; + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { + if (!this.getValue().isPresent()) return; Optional> value = getValue(); @@ -61,7 +62,7 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSeri child.get().serialize(ser); } - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); if (child.isPresent() && isPresent.getValue().equals(Boolean.TRUE)) { child.get().encodeType(ser); diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java b/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java index 4c1498605..37972cd98 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypePublicKey; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.key.PublicKey; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; @@ -49,13 +50,13 @@ public CLValuePublicKey(PublicKey value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeU8(this.getValue().getTag().getByteTag()); ser.writeByteArray(this.getValue().getKey()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java index 3437bd69a..613d53607 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java @@ -5,6 +5,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeResult; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -53,7 +54,7 @@ public CLValueResult(AbstractCLValue ok, AbstractCLValue err) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; setChildTypes(); @@ -68,7 +69,7 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSeri getValue().getErr().serialize(ser); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java index d38c1c8c6..f88fec04f 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeString; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -45,12 +46,12 @@ public CLValueString(String value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeString(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java index 3b0dbf99e..9647ba4cd 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java @@ -5,6 +5,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeTuple1; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -40,13 +41,13 @@ public CLValueTuple1(Unit> value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException, ValueSerializationException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; setChildTypes(); getValue().getValue0().serialize(ser); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java index b1db16c12..e07e1d8d3 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java @@ -5,6 +5,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeTuple2; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -41,14 +42,14 @@ public CLValueTuple2(Pair, ? extends AbstractCLV } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException, ValueSerializationException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; setChildTypes(); getValue().getValue0().serialize(ser); getValue().getValue1().serialize(ser); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java index 5a1c828de..1ca78bd1f 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java @@ -5,6 +5,7 @@ import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeTuple3; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -41,7 +42,7 @@ public CLValueTuple3(Triplet, ? extends Abstract } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException, ValueSerializationException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; setChildTypes(); @@ -50,7 +51,7 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTyp getValue().getValue1().serialize(ser); getValue().getValue2().serialize(ser); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java index 8e71cad34..cc8e7c2dd 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeU128; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -48,12 +49,12 @@ public CLValueU128(BigInteger value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; ser.writeU128(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java index 4009190b4..81a8e09e7 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeU256; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -48,12 +49,12 @@ public CLValueU256(BigInteger value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; ser.writeU256(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java index 8bffaf4b5..988ef445f 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeU32; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -45,12 +46,12 @@ public CLValueU32(Long value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeU32(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java index 8974f1b04..e59a11792 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeU512; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -46,12 +47,12 @@ public CLValueU512(BigInteger value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; ser.writeU512(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java index c695ee229..b79caeeeb 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeU64; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -46,12 +47,12 @@ public CLValueU64(BigInteger value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; ser.writeU64(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java index 49f04106f..78bc56214 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeU8; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -45,12 +46,12 @@ public CLValueU8(Byte value) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; ser.writeU8(this.getValue()); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java index 541243af8..702203c99 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java @@ -4,6 +4,7 @@ import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeURef; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.uref.URef; import com.casper.sdk.model.uref.URefAccessRight; import com.fasterxml.jackson.annotation.JsonGetter; @@ -53,7 +54,7 @@ protected void setJsonClType(CLTypeURef clType) { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; URef uref = this.getValue(); @@ -62,7 +63,7 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTyp urefByte[32] = uref.getAccessRight().serializationTag; ser.writeByteArray(urefByte); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java index 7e95f875b..328e48a12 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java @@ -3,6 +3,7 @@ import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeUnit; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; @@ -47,12 +48,12 @@ public CLValueUnit() { } @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { if (this.getValue() == null) return; setBytes(UNITY_EMPTY_VALUE); - if (encodeType) { + if (target.equals(Target.BYTE)) { this.encodeType(ser); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeData.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeData.java index f8eb9dd7b..ac8b0113f 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeData.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeData.java @@ -1,33 +1,9 @@ package com.casper.sdk.model.clvalue.cltype; +import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; +import com.casper.sdk.model.clvalue.*; import com.casper.sdk.model.storedvalue.StoredValue; -import com.casper.sdk.exception.DynamicInstanceException; -import com.casper.sdk.model.clvalue.AbstractCLValue; -import com.casper.sdk.model.clvalue.CLValueAny; -import com.casper.sdk.model.clvalue.CLValueBool; -import com.casper.sdk.model.clvalue.CLValueByteArray; -import com.casper.sdk.model.clvalue.CLValueFixedList; -import com.casper.sdk.model.clvalue.CLValueI32; -import com.casper.sdk.model.clvalue.CLValueI64; -import com.casper.sdk.model.clvalue.CLValueKey; -import com.casper.sdk.model.clvalue.CLValueList; -import com.casper.sdk.model.clvalue.CLValueMap; -import com.casper.sdk.model.clvalue.CLValueOption; -import com.casper.sdk.model.clvalue.CLValuePublicKey; -import com.casper.sdk.model.clvalue.CLValueResult; -import com.casper.sdk.model.clvalue.CLValueString; -import com.casper.sdk.model.clvalue.CLValueTuple1; -import com.casper.sdk.model.clvalue.CLValueTuple2; -import com.casper.sdk.model.clvalue.CLValueTuple3; -import com.casper.sdk.model.clvalue.CLValueU128; -import com.casper.sdk.model.clvalue.CLValueU256; -import com.casper.sdk.model.clvalue.CLValueU32; -import com.casper.sdk.model.clvalue.CLValueU512; -import com.casper.sdk.model.clvalue.CLValueU64; -import com.casper.sdk.model.clvalue.CLValueU8; -import com.casper.sdk.model.clvalue.CLValueURef; -import com.casper.sdk.model.clvalue.CLValueUnit; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeFixedList.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeFixedList.java index d3ee35b79..286c8d96e 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeFixedList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeFixedList.java @@ -1,9 +1,9 @@ package com.casper.sdk.model.clvalue.cltype; +import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; -import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeList.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeList.java index 842ec13f1..31bd51bc0 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeList.java @@ -1,9 +1,9 @@ package com.casper.sdk.model.clvalue.cltype; +import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; -import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeMap.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeMap.java index 6a7229c0b..d5fd02f6b 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeMap.java @@ -5,11 +5,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import lombok.*; /** * CLType for {@link AbstractCLType#MAP} diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeOption.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeOption.java index 521af3332..ec2089421 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeOption.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeOption.java @@ -1,9 +1,9 @@ package com.casper.sdk.model.clvalue.cltype; +import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; -import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeResult.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeResult.java index d7b42e4a6..de00d4239 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeResult.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeResult.java @@ -1,15 +1,11 @@ package com.casper.sdk.model.clvalue.cltype; +import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; -import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import lombok.*; /** * CLType for {@link AbstractCLType#RESULT} diff --git a/src/main/java/com/casper/sdk/model/clvalue/serde/CasperSerializableObject.java b/src/main/java/com/casper/sdk/model/clvalue/serde/CasperSerializableObject.java index 834a981fa..afda6538c 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/serde/CasperSerializableObject.java +++ b/src/main/java/com/casper/sdk/model/clvalue/serde/CasperSerializableObject.java @@ -16,11 +16,11 @@ public interface CasperSerializableObject extends SerializableObject { /** * Called when the object's values must be serialized * - * @param ser the encoder to be used - * @param encodeType append encoded type? + * @param ser the encoder to be used + * @param target target serialization standard * @throws ValueSerializationException exception holding information of failure to serialize a value */ - void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException; + void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException; /** * Called when the object's values must be serialized @@ -33,7 +33,7 @@ public interface CasperSerializableObject extends SerializableObject { @Override default void serialize(SerializerBuffer ser) throws ValueSerializationException { try { - serialize(ser, false); + serialize(ser, Target.JSON); } catch (NoSuchTypeException e) { throw new ValueSerializationException(String.format("Error serializing %s", this.getClass().getSimpleName()), e); } diff --git a/src/main/java/com/casper/sdk/model/clvalue/serde/Target.java b/src/main/java/com/casper/sdk/model/clvalue/serde/Target.java new file mode 100644 index 000000000..0d04838a5 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/clvalue/serde/Target.java @@ -0,0 +1,6 @@ +package com.casper.sdk.model.clvalue.serde; + +public enum Target { + BYTE, + JSON, +} diff --git a/src/main/java/com/casper/sdk/model/common/Digest.java b/src/main/java/com/casper/sdk/model/common/Digest.java index 55ad2dec9..d9a909c07 100644 --- a/src/main/java/com/casper/sdk/model/common/Digest.java +++ b/src/main/java/com/casper/sdk/model/common/Digest.java @@ -1,6 +1,7 @@ package com.casper.sdk.model.common; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonValue; import dev.oak3.sbs4j.SerializerBuffer; import lombok.*; @@ -40,7 +41,7 @@ public static Digest digestFromBytes(byte[] bytes) { * Implements Digest encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) { + public void serialize(SerializerBuffer ser, Target target) { ser.writeByteArray(getDigest()); } } \ No newline at end of file diff --git a/src/main/java/com/casper/sdk/model/common/Ttl.java b/src/main/java/com/casper/sdk/model/common/Ttl.java index dce7061b8..f0e9c3959 100644 --- a/src/main/java/com/casper/sdk/model/common/Ttl.java +++ b/src/main/java/com/casper/sdk/model/common/Ttl.java @@ -2,6 +2,7 @@ import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonValue; import dev.oak3.sbs4j.SerializerBuffer; import lombok.*; @@ -40,7 +41,7 @@ public Long getTtl() { * implements SerializableObject */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) { + public void serialize(SerializerBuffer ser, Target target) { ser.writeI64(getTtl()); } } diff --git a/src/main/java/com/casper/sdk/model/deploy/Approval.java b/src/main/java/com/casper/sdk/model/deploy/Approval.java index eceb1d001..57342b1a0 100644 --- a/src/main/java/com/casper/sdk/model/deploy/Approval.java +++ b/src/main/java/com/casper/sdk/model/deploy/Approval.java @@ -1,9 +1,12 @@ package com.casper.sdk.model.deploy; +import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.key.PublicKey; import com.casper.sdk.model.key.Signature; import dev.oak3.sbs4j.SerializerBuffer; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.*; /** @@ -34,8 +37,8 @@ public class Approval implements CasperSerializableObject { * Implements Approval encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) { - signer.serialize(ser, encodeType); - signature.serialize(ser, encodeType); + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { + signer.serialize(ser, target); + signature.serialize(ser, target); } } diff --git a/src/main/java/com/casper/sdk/model/deploy/Deploy.java b/src/main/java/com/casper/sdk/model/deploy/Deploy.java index fbe2e5398..1e8a93cc0 100644 --- a/src/main/java/com/casper/sdk/model/deploy/Deploy.java +++ b/src/main/java/com/casper/sdk/model/deploy/Deploy.java @@ -2,6 +2,7 @@ import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.common.Digest; import com.casper.sdk.model.deploy.executabledeploy.ExecutableDeployItem; import dev.oak3.sbs4j.SerializerBuffer; @@ -54,14 +55,14 @@ public class Deploy implements CasperSerializableObject { * Implements Deploy encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException, ValueSerializationException { - header.serialize(ser, true); - hash.serialize(ser, true); - payment.serialize(ser, true); - session.serialize(ser, true); + 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, true); + approval.serialize(ser, Target.BYTE); } } } diff --git a/src/main/java/com/casper/sdk/model/deploy/DeployHeader.java b/src/main/java/com/casper/sdk/model/deploy/DeployHeader.java index 640f4f0ae..24e954279 100644 --- a/src/main/java/com/casper/sdk/model/deploy/DeployHeader.java +++ b/src/main/java/com/casper/sdk/model/deploy/DeployHeader.java @@ -1,12 +1,15 @@ package com.casper.sdk.model.deploy; +import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.common.Digest; import com.casper.sdk.model.common.Ttl; import com.casper.sdk.model.key.PublicKey; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.SerializerBuffer; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.*; import java.util.Date; @@ -70,12 +73,12 @@ public class DeployHeader implements CasperSerializableObject { * Implements DeployHearder encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) { - account.serialize(ser, encodeType); + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { + account.serialize(ser, target); ser.writeI64(timeStamp.getTime()); - ttl.serialize(ser, encodeType); + ttl.serialize(ser, target); ser.writeI64(gasPrice); - bodyHash.serialize(ser, encodeType); + bodyHash.serialize(ser, target); if (dependencies != null) { ser.writeI32(dependencies.size()); for (Digest dependency : dependencies) { diff --git a/src/main/java/com/casper/sdk/model/deploy/NamedArg.java b/src/main/java/com/casper/sdk/model/deploy/NamedArg.java index cbf1f0038..d83aea33b 100644 --- a/src/main/java/com/casper/sdk/model/deploy/NamedArg.java +++ b/src/main/java/com/casper/sdk/model/deploy/NamedArg.java @@ -4,6 +4,7 @@ import com.casper.sdk.model.clvalue.*; import com.casper.sdk.model.clvalue.cltype.AbstractCLType; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonFormat; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueSerializationException; @@ -35,7 +36,7 @@ public class NamedArg

implements CasperSerializableObj private AbstractCLValue clValue; @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { ser.writeString(type); if (clValue instanceof CLValueI32 || clValue instanceof CLValueU32) { ser.writeI32(32 / 8); @@ -56,6 +57,6 @@ public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSeri int size = localEncoder.toByteArray().length; ser.writeI32(size); //removing the CLValue type byte at the end } - clValue.serialize(ser, encodeType); + clValue.serialize(ser, target); } } diff --git a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/ModuleBytes.java b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/ModuleBytes.java index 6a83d5876..7bcd79401 100644 --- a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/ModuleBytes.java +++ b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/ModuleBytes.java @@ -1,6 +1,7 @@ package com.casper.sdk.model.deploy.executabledeploy; import com.casper.sdk.exception.NoSuchTypeException; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.deploy.NamedArg; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -50,13 +51,13 @@ public byte getOrder() { * Implements the ModuleBytes encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { ser.writeU8(getOrder()); ser.writeI32(getBytes().length); ser.writeByteArray(getBytes()); ser.writeI32(args.size()); for (NamedArg namedArg : args) { - namedArg.serialize(ser, encodeType); + namedArg.serialize(ser, target); } } } diff --git a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredContractByHash.java b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredContractByHash.java index 38bb2b6ee..d2235d621 100644 --- a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredContractByHash.java +++ b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredContractByHash.java @@ -1,6 +1,7 @@ package com.casper.sdk.model.deploy.executabledeploy; import com.casper.sdk.exception.NoSuchTypeException; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.deploy.NamedArg; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -54,13 +55,13 @@ public byte getOrder() { * Implements the StoredContractByHAsh encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException, ValueSerializationException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { ser.writeU8(getOrder()); ser.writeString(getHash()); ser.writeString(getEntryPoint()); ser.writeI32(args.size()); for (NamedArg namedArg : args) { - namedArg.serialize(ser, true); + namedArg.serialize(ser, Target.BYTE); } } diff --git a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredContractByName.java b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredContractByName.java index ed9a1d0ed..3bb4fdf15 100644 --- a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredContractByName.java +++ b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredContractByName.java @@ -1,6 +1,7 @@ package com.casper.sdk.model.deploy.executabledeploy; import com.casper.sdk.exception.NoSuchTypeException; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.deploy.NamedArg; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -54,13 +55,13 @@ public byte getOrder() { * Implements the StoredContractByHash encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException, ValueSerializationException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { ser.writeU8(getOrder()); ser.writeString(getName()); ser.writeString(getEntryPoint()); ser.writeI32(args.size()); for (NamedArg namedArg : args) { - namedArg.serialize(ser, true); + namedArg.serialize(ser, Target.BYTE); } } } \ No newline at end of file diff --git a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredVersionedContractByHash.java b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredVersionedContractByHash.java index c24100d89..98084226f 100644 --- a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredVersionedContractByHash.java +++ b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredVersionedContractByHash.java @@ -1,6 +1,7 @@ package com.casper.sdk.model.deploy.executabledeploy; import com.casper.sdk.exception.NoSuchTypeException; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.deploy.NamedArg; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -59,14 +60,14 @@ public byte getOrder() { * Implements the StoredVersionedContractByHash encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws NoSuchTypeException, ValueSerializationException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { ser.writeU8(getOrder()); ser.writeString(getHash()); ser.writeI64(getVersion()); ser.writeString(getEntryPoint()); ser.writeI32(args.size()); for (NamedArg namedArg : args) { - namedArg.serialize(ser, true); + namedArg.serialize(ser, Target.BYTE); } } } \ No newline at end of file diff --git a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredVersionedContractByName.java b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredVersionedContractByName.java index 85271f952..52b5f00aa 100644 --- a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredVersionedContractByName.java +++ b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/StoredVersionedContractByName.java @@ -1,6 +1,7 @@ package com.casper.sdk.model.deploy.executabledeploy; import com.casper.sdk.exception.NoSuchTypeException; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.deploy.NamedArg; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -59,14 +60,14 @@ public byte getOrder() { * Implements the StoredVersionedContractName encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { ser.writeU8(getOrder()); ser.writeString(getName()); ser.writeI64(getVersion()); ser.writeString(getEntryPoint()); ser.writeI32(args.size()); for (NamedArg namedArg : args) { - namedArg.serialize(ser, true); + namedArg.serialize(ser, Target.BYTE); } } diff --git a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/Transfer.java b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/Transfer.java index 0a544aa57..44f14c5c8 100644 --- a/src/main/java/com/casper/sdk/model/deploy/executabledeploy/Transfer.java +++ b/src/main/java/com/casper/sdk/model/deploy/executabledeploy/Transfer.java @@ -1,6 +1,7 @@ package com.casper.sdk.model.deploy.executabledeploy; import com.casper.sdk.exception.NoSuchTypeException; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.deploy.NamedArg; import com.fasterxml.jackson.annotation.JsonTypeName; import dev.oak3.sbs4j.SerializerBuffer; @@ -42,11 +43,11 @@ public byte getOrder() { * Implements the Transfer encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) throws ValueSerializationException, NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { ser.writeU8(getOrder()); ser.writeI32(args.size()); for (NamedArg namedArg : args) { - namedArg.serialize(ser, true); + namedArg.serialize(ser, Target.BYTE); } } } \ No newline at end of file diff --git a/src/main/java/com/casper/sdk/model/key/AbstractSerializedKeyTaggedHex.java b/src/main/java/com/casper/sdk/model/key/AbstractSerializedKeyTaggedHex.java index 3eb74227d..1b7e2c958 100644 --- a/src/main/java/com/casper/sdk/model/key/AbstractSerializedKeyTaggedHex.java +++ b/src/main/java/com/casper/sdk/model/key/AbstractSerializedKeyTaggedHex.java @@ -1,6 +1,7 @@ package com.casper.sdk.model.key; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; +import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonValue; import dev.oak3.sbs4j.SerializerBuffer; @@ -43,7 +44,7 @@ public String getAlgoTaggedHex() { * Implements TaggedHEx encoder */ @Override - public void serialize(SerializerBuffer ser, boolean encodeType) { + public void serialize(SerializerBuffer ser, Target target) { ser.writeU8(getTag().getByteTag()); ser.writeByteArray(getKey()); } diff --git a/src/test/java/com/casper/sdk/model/deploy/DeploySerializationTest.java b/src/test/java/com/casper/sdk/model/deploy/DeploySerializationTest.java index b0d3f8c9d..8bc25d0a7 100644 --- a/src/test/java/com/casper/sdk/model/deploy/DeploySerializationTest.java +++ b/src/test/java/com/casper/sdk/model/deploy/DeploySerializationTest.java @@ -2,6 +2,7 @@ import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.AbstractJsonTests; +import com.casper.sdk.model.clvalue.serde.Target; import com.casper.sdk.model.common.Digest; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueSerializationException; @@ -39,7 +40,7 @@ void deploySerialization() throws IOException, NoSuchTypeException, ValueSeriali assertNotNull(deploy); SerializerBuffer ser = new SerializerBuffer(); - deploy.serialize(ser, true); + deploy.serialize(ser, Target.BYTE); byte[] deployBytes = ser.toByteArray(); String val = Hex.toHexString(deployBytes); assertEquals(Hex.toHexString(digest.getDigest()), val); From 0036836bbb49dd197891caac9b26c0e9b10c1605 Mon Sep 17 00:00:00 2001 From: meywood Date: Wed, 28 Sep 2022 10:50:53 +0100 Subject: [PATCH 19/35] issues/120 - Added version number to all events --- gradle.properties | 4 +-- gradle/wrapper/gradle-wrapper.properties | 2 +- .../com/casper/sdk/model/event/Event.java | 6 +++++ .../sdk/service/impl/event/AbstractEvent.java | 2 ++ .../sdk/service/impl/event/EventBuilder.java | 25 ++++++++++++++----- .../service/impl/event/EventServiceImpl.java | 1 - .../sdk/service/impl/event/PojoEvent.java | 4 +-- .../sdk/service/impl/event/RawEvent.java | 4 +-- .../service/EventServiceIntegrationTest.java | 5 +++- .../service/impl/event/EventBuilderTest.java | 1 + .../sdk/service/impl/event/PojoEventTest.java | 4 ++- .../sdk/service/impl/event/RawEventTest.java | 4 ++- 12 files changed, 45 insertions(+), 17 deletions(-) diff --git a/gradle.properties b/gradle.properties index 9e88254e1..c21b241ed 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ cryptokeyVersion=0.2.0 lombokPluginVersion=6.2.0 -jupiterVersion=5.8.2 +jupiterVersion=5.9.0 jsonPathAssertVersion=2.7.0 jsonrpc4jVersion=1.6 jacksonVersion=2.13.3 @@ -8,5 +8,5 @@ log4jVersion=2.17.2 mockwebserverVersion=4.10.0 slf4jApiVersion=1.7.36 javaTuplesVersion=1.2 -jsonassertVersion=1.5.0 +jsonassertVersion=1.5.1 jodaTimeVersion=2.10.14 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 2e6e5897b..ae04661ee 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/java/com/casper/sdk/model/event/Event.java b/src/main/java/com/casper/sdk/model/event/Event.java index 9cfc54590..9811aafba 100644 --- a/src/main/java/com/casper/sdk/model/event/Event.java +++ b/src/main/java/com/casper/sdk/model/event/Event.java @@ -43,4 +43,10 @@ public interface Event { * @return the optional ID */ Optional getId(); + + /** + * Obtains the API version of the event + * @return the API version + */ + String getVersion(); } diff --git a/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java b/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java index 7a96b55f1..8d8dfffbd 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/AbstractEvent.java @@ -29,6 +29,8 @@ abstract class AbstractEvent implements Event { private final Long id; /** The event data */ private final T data; + /** The version of the casper API that generate the event */ + private final String version; public Optional getId() { return Optional.ofNullable(id); diff --git a/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java b/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java index 3469a4ee2..dfaf5b3f4 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java +++ b/src/main/java/com/casper/sdk/service/impl/event/EventBuilder.java @@ -35,6 +35,8 @@ final class EventBuilder { private boolean idExpected = true; /** Used to build the pojo model objects from the JSON in the data line */ private final ObjectMapper mapper; + /** The version of the node the event was generated with */ + private String version; EventBuilder(final EventType eventType, final EventTarget eventTarget, final String source) { this.eventType = eventType; @@ -50,13 +52,18 @@ boolean isComplete() { boolean processLine(final String line) { try { + // Remove any leading or trailing whitespace + final String trimmed = line.trim(); + if (line.startsWith(DATA)) { - this.data = line; - idExpected = isIdExpected(line); + this.data = trimmed; + idExpected = isIdExpected(trimmed); } - if (isId(line)) { - this.id = getId(line); + if (isId(trimmed)) { + this.id = getId(trimmed); + } else if (isApiVersion(trimmed)) { + this.version = getVersion(trimmed); } return isComplete(); @@ -65,6 +72,12 @@ boolean processLine(final String line) { } } + private String getVersion(final String line) { + // remove all but version number from: data:{"ApiVersion":"1.0.0"} + return line.replace("data:{\"ApiVersion\":\"", "") + .replace("\"}",""); + } + private boolean isIdExpected(String line) { return !isApiVersion(line); } @@ -87,7 +100,7 @@ T buildEvent() { final T event; if (this.eventTarget == EventTarget.RAW) { //noinspection unchecked - event = (T) new RawEvent(eventType, source, id, data); + event = (T) new RawEvent(eventType, source, id, data, version); } else if (eventTarget == EventTarget.POJO) { //noinspection unchecked event = (T) buildPojoEvent(); @@ -114,7 +127,7 @@ private PojoEvent buildPojoEvent() { //noinspection unchecked root = mapper.readValue(value, EventRoot.class); } - event = new PojoEvent<>(eventType, source, id, EventRoot.getData(root)); + event = new PojoEvent<>(eventType, source, id, EventRoot.getData(root), version); } catch (JsonProcessingException e) { throw new CasperClientException("Error building POJO event for: " + data, e); } diff --git a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java index fe9a9cd60..806c703fa 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java +++ b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java @@ -87,7 +87,6 @@ private > void consumeEvent(final EventType e final Reader reader, final Consumer consumer) { - final EventBuilder eventBuilder = new EventBuilder(eventType, eventTarget, uri.toString()); try { diff --git a/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java b/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java index 39874e9df..142533de9 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/PojoEvent.java @@ -16,8 +16,8 @@ @ToString(doNotUseGetters = true, callSuper = true) final class PojoEvent extends AbstractEvent { - PojoEvent(final EventType eventType, final String source, final Long id, T data) { - super(eventType, getDataType(data), source, id, data); + PojoEvent(final EventType eventType, final String source, final Long id, T data, final String version) { + super(eventType, getDataType(data), source, id, data, version); } private static DataType getDataType(final Object data) { diff --git a/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java index fbf440483..e156ac034 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java +++ b/src/main/java/com/casper/sdk/service/impl/event/RawEvent.java @@ -14,8 +14,8 @@ @ToString(doNotUseGetters = true, callSuper = true) final class RawEvent extends AbstractEvent { - RawEvent(final EventType eventType, final String source, final Long id, final String data) { - super(eventType, getDataType(data), source, id, data); + RawEvent(final EventType eventType, final String source, final Long id, final String data, final String version) { + super(eventType, getDataType(data), source, id, data, version); } private static DataType getDataType(final String data) { diff --git a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java index 9e4dde393..40c1c3a7c 100644 --- a/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java +++ b/src/test/java/com/casper/sdk/service/EventServiceIntegrationTest.java @@ -64,6 +64,7 @@ public void accept(final Event event) { assertThat(event.getClass().getSimpleName(), is("RawEvent")); assertThat(event.getEventType(), is(EventType.MAIN)); + assertThat(event.getVersion(), is("1.0.0")); if (count[0] == 0) { assertThat(event.getData(), is("data:{\"ApiVersion\":\"1.0.0\"}")); @@ -73,6 +74,7 @@ public void accept(final Event event) { assertThat(event.getData(), endsWith("\"bytes\":\"03f5d62682010000\",\"parsed\":1658508997891}}}]}}}")); assertThat(event.getId().isPresent(), is(true)); assertThat(event.getId().get(), is(0L)); + } else if (count[0] == 3) { assertThat( event.getData(), @@ -91,9 +93,10 @@ public void accept(final Event event) { } count[0]++; - } }); + + assertThat(count[0], is(greaterThan(3))); } @Test diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java index f9a3f5383..e9093bb41 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -84,6 +84,7 @@ void buildApiVersionEvent() throws IOException { assertThat(abstractEvent, instanceOf(PojoEvent.class)); assertThat(abstractEvent.getData(), instanceOf(ApiVersion.class)); + assertThat(abstractEvent.getVersion(), is("1.0.0")); final ApiVersion apiVersion = abstractEvent.getData(); assertThat(apiVersion.getApiVersion(), is("1.0.0")); diff --git a/src/test/java/com/casper/sdk/service/impl/event/PojoEventTest.java b/src/test/java/com/casper/sdk/service/impl/event/PojoEventTest.java index 09b1ee897..7ef06e266 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/PojoEventTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/PojoEventTest.java @@ -18,9 +18,10 @@ class PojoEventTest { void pojoEvent() { final String source = "http://localhost:9999"; + final String version = "1.0.0"; final DeployExpired data = new DeployExpired(new Digest("bb878bcf8827649f070c487800a95c35be3eb2e83b5447921675040cea38af1c")); - final PojoEvent rawEvent = new PojoEvent<>(EventType.MAIN, source, 2L, data); + final PojoEvent rawEvent = new PojoEvent<>(EventType.MAIN, source, 2L, data, version); assertThat(rawEvent.getEventType(), is(EventType.MAIN)); assertThat(rawEvent.getSource(), is(source)); @@ -28,6 +29,7 @@ void pojoEvent() { assertThat(rawEvent.getId().get(), is(2L)); assertThat(rawEvent.getData(), is(data)); assertThat(rawEvent.getDataType(), is(DataType.DEPLOY_EXPIRED)); + assertThat(rawEvent.getVersion(), is(version)); } } \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/service/impl/event/RawEventTest.java b/src/test/java/com/casper/sdk/service/impl/event/RawEventTest.java index c50e052f1..b98fcacd6 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/RawEventTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/RawEventTest.java @@ -17,8 +17,9 @@ void rawEvent() { final String source = "http://localhost:9999"; final String data = "data:{\"ApiVersion\":\"1.0.0\"}"; + final String version = "1.2.3"; - final RawEvent rawEvent = new RawEvent(EventType.MAIN, source, 1L, data); + final RawEvent rawEvent = new RawEvent(EventType.MAIN, source, 1L, data, version); assertThat(rawEvent.getEventType(), is(EventType.MAIN)); assertThat(rawEvent.getSource(), is(source)); @@ -26,5 +27,6 @@ void rawEvent() { assertThat(rawEvent.getId().get(), is(1L)); assertThat(rawEvent.getData(), is(data)); assertThat(rawEvent.getDataType(), is(DataType.API_VERSION)); + assertThat(rawEvent.getVersion(), is(version)); } } \ No newline at end of file From f8245d2636fac9632a988aea2e3a68e381dbe178 Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Wed, 28 Sep 2022 14:24:32 +0200 Subject: [PATCH 20/35] Byte serializing and deserializing first draft working --- .../sdk/model/clvalue/AbstractCLValue.java | 65 +++++++-- .../casper/sdk/model/clvalue/CLValueAny.java | 9 +- .../casper/sdk/model/clvalue/CLValueBool.java | 10 +- .../sdk/model/clvalue/CLValueByteArray.java | 10 +- .../sdk/model/clvalue/CLValueFixedList.java | 7 + .../casper/sdk/model/clvalue/CLValueI32.java | 10 +- .../casper/sdk/model/clvalue/CLValueI64.java | 10 +- .../casper/sdk/model/clvalue/CLValueKey.java | 10 +- .../casper/sdk/model/clvalue/CLValueList.java | 7 + .../casper/sdk/model/clvalue/CLValueMap.java | 7 + .../sdk/model/clvalue/CLValueOption.java | 7 + .../sdk/model/clvalue/CLValuePublicKey.java | 10 +- .../sdk/model/clvalue/CLValueResult.java | 7 + .../sdk/model/clvalue/CLValueString.java | 10 +- .../sdk/model/clvalue/CLValueTuple1.java | 7 + .../sdk/model/clvalue/CLValueTuple2.java | 7 + .../sdk/model/clvalue/CLValueTuple3.java | 7 + .../casper/sdk/model/clvalue/CLValueU128.java | 7 + .../casper/sdk/model/clvalue/CLValueU256.java | 7 + .../casper/sdk/model/clvalue/CLValueU32.java | 10 +- .../casper/sdk/model/clvalue/CLValueU512.java | 7 + .../casper/sdk/model/clvalue/CLValueU64.java | 7 + .../casper/sdk/model/clvalue/CLValueU8.java | 10 +- .../casper/sdk/model/clvalue/CLValueURef.java | 10 +- .../casper/sdk/model/clvalue/CLValueUnit.java | 10 +- .../serde/CasperDeserializableObject.java | 42 ++++++ .../serde/CasperSerializableObject.java | 4 +- .../com/casper/sdk/model/deploy/NamedArg.java | 21 +-- .../serde/SerializerDeserializerTests.java | 128 +++++++++--------- 29 files changed, 347 insertions(+), 116 deletions(-) create mode 100644 src/main/java/com/casper/sdk/model/clvalue/serde/CasperDeserializableObject.java diff --git a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java index 63a50a8dc..a5fdf13ea 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java +++ b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java @@ -5,16 +5,17 @@ import com.casper.sdk.jackson.resolver.CLValueResolver; import com.casper.sdk.model.clvalue.cltype.AbstractCLType; import com.casper.sdk.model.clvalue.cltype.CLTypeData; +import com.casper.sdk.model.clvalue.serde.CasperDeserializableObject; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; import com.casper.sdk.model.clvalue.serde.Target; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.annotation.JsonTypeResolver; +import com.syntifi.crypto.key.encdec.Hex; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import dev.oak3.sbs4j.interfaces.DeserializableObject; import dev.oak3.sbs4j.util.ByteUtils; import lombok.*; @@ -30,9 +31,11 @@ @EqualsAndHashCode(of = {"bytes", "value"}) @JsonTypeInfo(use = JsonTypeInfo.Id.NONE) @JsonTypeResolver(CLValueResolver.class) -public abstract class AbstractCLValue implements CasperSerializableObject, DeserializableObject { +public abstract class AbstractCLValue + implements CasperSerializableObject, CasperDeserializableObject { @Setter(AccessLevel.PROTECTED) + @Getter private String bytes = ""; @Setter @@ -44,18 +47,6 @@ public abstract class AbstractCLValue implements Ca @JsonIgnore private T value; - @SneakyThrows({ValueSerializationException.class}) - @JsonGetter(value = "bytes") - @ExcludeFromJacocoGeneratedReport - public String getBytes() { - SerializerBuffer ser = new SerializerBuffer(); - this.serialize(ser); - - this.bytes = ByteUtils.encodeHexString(ser.toByteArray()); - - return this.bytes; - } - @SneakyThrows({ValueDeserializationException.class}) @JsonSetter(value = "bytes") @ExcludeFromJacocoGeneratedReport @@ -66,16 +57,60 @@ protected void setJsonBytes(String bytes) { this.deserialize(deser); } + @SneakyThrows({ValueSerializationException.class, NoSuchTypeException.class}) + @JsonGetter(value = "bytes") + @ExcludeFromJacocoGeneratedReport + protected String getJsonBytes() { + SerializerBuffer ser = new SerializerBuffer(); + this.serialize(ser, Target.JSON); + + this.bytes = ByteUtils.encodeHexString(ser.toByteArray()); + + return this.bytes; + } + @JsonIgnore public abstract P getClType(); public abstract void setClType(P value); + protected void serializePrefixWithLength(SerializerBuffer ser) throws ValueSerializationException { + SerializerBuffer localSer = new SerializerBuffer(); + serialize(localSer); + int size = localSer.toByteArray().length; + ser.writeI32(size); + } + + @Override + public AbstractCLValue deserialize(DeserializerBuffer deser, Target target) throws ValueDeserializationException, NoSuchTypeException { + if (target.equals(Target.BYTE)) { + return AbstractCLValue.createInstanceFromBytes(deser); + } else { + deserialize(deser); + return this; + } + } + + public static AbstractCLValue createInstanceFromBytes(DeserializerBuffer deser) throws ValueDeserializationException, NoSuchTypeException { + int length = deser.readI32(); + byte[] bytes = deser.readByteArray(length); + byte clType = deser.readU8(); + try { + AbstractCLValue clValue = CLTypeData.getTypeBySerializationTag(clType).getClazz().newInstance(); + clValue.deserialize(new DeserializerBuffer(Hex.encode(bytes))); + return clValue; + } catch (InstantiationException | IllegalAccessException e) { + throw new ValueDeserializationException("Error while instantiating CLValue", e); + } + } + + @Override public abstract void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException; + @Override public abstract void deserialize(DeserializerBuffer deserializerBuffer) throws ValueDeserializationException; - public void encodeType(SerializerBuffer ser) throws NoSuchTypeException { + protected void encodeType(SerializerBuffer ser) throws NoSuchTypeException { byte val = (getClType().getClTypeData().getSerializationTag()); ser.writeU8(val); } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java index a13932691..dfa840d38 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java @@ -14,6 +14,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.io.*; @@ -51,9 +52,13 @@ public CLValueAny(Object value) { @Override public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; - try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) { + + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + oos.writeObject(this.getValue()); byte[] objectByteArray = bos.toByteArray(); ser.writeI32(objectByteArray.length); @@ -65,6 +70,8 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } catch (IOException e) { throw new ValueSerializationException(String.format("Error serializing %s", this.getClass().getSimpleName()), e); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java index ef68483b6..7e88522ae 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java @@ -9,10 +9,12 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import org.jetbrains.annotations.NotNull; /** @@ -47,14 +49,20 @@ public CLValueBool(Boolean value) { } @Override - public void serialize(@NotNull SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(@NotNull SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeBool(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java index c7cc469fa..137d057e3 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java @@ -8,9 +8,11 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.util.Arrays; import java.util.Objects; @@ -36,14 +38,20 @@ public CLValueByteArray(byte[] value) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeByteArray(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java index 060cb8e0c..54a8168a3 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java @@ -15,6 +15,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.util.LinkedList; import java.util.List; @@ -44,6 +45,10 @@ public CLValueFixedList(List> value) { public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + setListType(); for (AbstractCLValue child : getValue()) { @@ -53,6 +58,8 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java index 2bc59ce5d..9f86a8de6 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java @@ -9,7 +9,9 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.*; +import org.bouncycastle.util.encoders.Hex; /** * Casper I32 CLValue implementation @@ -44,14 +46,20 @@ public CLValueI32(Integer value) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeI32(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java index 1cc96c0e5..1a6fc3d64 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java @@ -9,10 +9,12 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; /** * Casper I64 CLValue implementation @@ -46,14 +48,20 @@ public CLValueI64(Long value) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeI64(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java index d4fc9a4be..85fb5b3f5 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java @@ -11,11 +11,13 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import dev.oak3.sbs4j.util.ByteUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; /** * Casper Key CLValue implementation @@ -49,15 +51,21 @@ public CLValueKey(Key value) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeU8(this.getValue().getTag().getByteTag()); ser.writeByteArray(this.getValue().getKey()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java index eb4f75f87..82d4a5777 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java @@ -15,6 +15,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.util.LinkedList; import java.util.List; @@ -44,6 +45,10 @@ public CLValueList(List> value) { public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + setListType(); // List length is written first @@ -57,6 +62,8 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java index 809dd0849..3c89b24e7 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java @@ -15,6 +15,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.util.LinkedHashMap; import java.util.Map; @@ -46,6 +47,10 @@ public CLValueMap(Map, ? extends AbstractCLValue public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + setChildTypes(); CLValueI32 mapLength = new CLValueI32(getValue().size()); @@ -59,6 +64,8 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java index 5568c9064..dc378cbba 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java @@ -15,6 +15,7 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.util.Optional; @@ -47,6 +48,10 @@ public CLValueOption(Optional> value) { public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (!this.getValue().isPresent()) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + Optional> value = getValue(); CLValueBool isPresent = new CLValueBool(value.isPresent() && value.get().getValue() != null); @@ -68,6 +73,8 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa child.get().encodeType(ser); } } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java b/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java index 37972cd98..4f9a3a3c4 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java @@ -10,11 +10,13 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import dev.oak3.sbs4j.util.ByteUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.security.NoSuchAlgorithmException; @@ -50,15 +52,21 @@ public CLValuePublicKey(PublicKey value) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeU8(this.getValue().getTag().getByteTag()); ser.writeByteArray(this.getValue().getKey()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java index 613d53607..7662065e7 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java @@ -12,6 +12,7 @@ import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.*; +import org.bouncycastle.util.encoders.Hex; /** * Casper Result CLValue implementation @@ -57,6 +58,10 @@ public CLValueResult(AbstractCLValue ok, AbstractCLValue err) { public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + setChildTypes(); CLValueBool clValueTrue = new CLValueBool(true); @@ -72,6 +77,8 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java index f88fec04f..3a60cbbb2 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java @@ -9,10 +9,12 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; /** * Casper String CLValue implementation @@ -46,14 +48,20 @@ public CLValueString(String value) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeString(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java index 9647ba4cd..97f704e24 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java @@ -15,6 +15,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import org.javatuples.Unit; import java.util.Arrays; @@ -44,12 +45,18 @@ public CLValueTuple1(Unit> value) { public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + setChildTypes(); getValue().getValue0().serialize(ser); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java index e07e1d8d3..159170680 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java @@ -15,6 +15,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import org.javatuples.Pair; import java.util.Arrays; @@ -45,6 +46,10 @@ public CLValueTuple2(Pair, ? extends AbstractCLV public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + setChildTypes(); getValue().getValue0().serialize(ser); getValue().getValue1().serialize(ser); @@ -52,6 +57,8 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java index 1ca78bd1f..cadbab2e5 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java @@ -15,6 +15,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import org.javatuples.Triplet; import java.util.Arrays; @@ -45,6 +46,10 @@ public CLValueTuple3(Triplet, ? extends Abstract public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + setChildTypes(); getValue().getValue0().serialize(ser); @@ -54,6 +59,8 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java index cc8e7c2dd..f87d18eb7 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java @@ -14,6 +14,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.math.BigInteger; @@ -52,11 +53,17 @@ public CLValueU128(BigInteger value) { public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeU128(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java index 81a8e09e7..047bad19c 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java @@ -14,6 +14,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.math.BigInteger; @@ -52,11 +53,17 @@ public CLValueU256(BigInteger value) { public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeU256(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java index 988ef445f..7a004b596 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java @@ -9,10 +9,12 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; /** * Casper U32 CLValue implementation @@ -46,14 +48,20 @@ public CLValueU32(Long value) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeU32(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java index e59a11792..b93e0fe83 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java @@ -11,6 +11,7 @@ import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.*; +import org.bouncycastle.util.encoders.Hex; import java.math.BigInteger; @@ -50,11 +51,17 @@ public CLValueU512(BigInteger value) { public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeU512(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java index b79caeeeb..e2160e7d1 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java @@ -11,6 +11,7 @@ import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.*; +import org.bouncycastle.util.encoders.Hex; import java.math.BigInteger; @@ -50,11 +51,17 @@ public CLValueU64(BigInteger value) { public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeU64(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java index 78bc56214..0e32a2293 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java @@ -9,10 +9,12 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; /** * Casper U8 CLValue implementation @@ -46,14 +48,20 @@ public CLValueU8(Byte value) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + ser.writeU8(this.getValue()); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java index 702203c99..9956382b1 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java @@ -12,9 +12,11 @@ import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; import java.util.Objects; @@ -54,9 +56,13 @@ protected void setJsonClType(CLTypeURef clType) { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + URef uref = this.getValue(); byte[] urefByte = new byte[uref.getAddress().length + 1]; System.arraycopy(uref.getAddress(), 0, urefByte, 0, uref.getAddress().length); @@ -66,6 +72,8 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java index 328e48a12..fe9bf400f 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java @@ -8,9 +8,11 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; +import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; +import org.bouncycastle.util.encoders.Hex; /** * Casper Unit CLValue implementation @@ -48,14 +50,20 @@ public CLValueUnit() { } @Override - public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException { + public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeException, ValueSerializationException { if (this.getValue() == null) return; + if (target.equals(Target.BYTE)) { + super.serializePrefixWithLength(ser); + } + setBytes(UNITY_EMPTY_VALUE); if (target.equals(Target.BYTE)) { this.encodeType(ser); } + + this.setBytes(Hex.toHexString(ser.toByteArray())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/serde/CasperDeserializableObject.java b/src/main/java/com/casper/sdk/model/clvalue/serde/CasperDeserializableObject.java new file mode 100644 index 000000000..44ce460f0 --- /dev/null +++ b/src/main/java/com/casper/sdk/model/clvalue/serde/CasperDeserializableObject.java @@ -0,0 +1,42 @@ +package com.casper.sdk.model.clvalue.serde; + +import com.casper.sdk.exception.NoSuchTypeException; +import com.casper.sdk.model.clvalue.AbstractCLValue; +import dev.oak3.sbs4j.DeserializerBuffer; +import dev.oak3.sbs4j.exception.ValueDeserializationException; +import dev.oak3.sbs4j.interfaces.DeserializableObject; + +/** + * Defines an object as being capable of encoding with {@link DeserializerBuffer} + * + * @author Alexandre Carvalho + * @author Andre Bertolace + * @since 0.2.2 + */ +public interface CasperDeserializableObject extends DeserializableObject { + /** + * Called when the object's values must be deserialized + * + * @param deser the deserializer to be used + * @param target target deserialization standard + * @throws ValueDeserializationException exception holding information of failure to deserialize a value + */ + AbstractCLValue deserialize(DeserializerBuffer deser, Target target) throws ValueDeserializationException, NoSuchTypeException; + + /** + * Called when the object's values must be deserialized + *

+ * Allows to use the default deserialize with the custom casper deserialize signature, defaulting encodeType to false + * + * @param deser the deserializer to be used + * @throws ValueDeserializationException exception holding information of failure to deserialize a value + */ + @Override + default void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { + try { + deserialize(deser, Target.JSON); + } catch (NoSuchTypeException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } + } +} diff --git a/src/main/java/com/casper/sdk/model/clvalue/serde/CasperSerializableObject.java b/src/main/java/com/casper/sdk/model/clvalue/serde/CasperSerializableObject.java index afda6538c..f9c739823 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/serde/CasperSerializableObject.java +++ b/src/main/java/com/casper/sdk/model/clvalue/serde/CasperSerializableObject.java @@ -16,7 +16,7 @@ public interface CasperSerializableObject extends SerializableObject { /** * Called when the object's values must be serialized * - * @param ser the encoder to be used + * @param ser the serializer to be used * @param target target serialization standard * @throws ValueSerializationException exception holding information of failure to serialize a value */ @@ -27,7 +27,7 @@ public interface CasperSerializableObject extends SerializableObject { *

* Allows to use the default serialize with the custom casper serialize signature, defaulting encodeType to false * - * @param ser the encoder to be used + * @param ser the serializer to be used * @throws ValueSerializationException exception holding information of failure to serialize a value */ @Override diff --git a/src/main/java/com/casper/sdk/model/deploy/NamedArg.java b/src/main/java/com/casper/sdk/model/deploy/NamedArg.java index d83aea33b..beda32b03 100644 --- a/src/main/java/com/casper/sdk/model/deploy/NamedArg.java +++ b/src/main/java/com/casper/sdk/model/deploy/NamedArg.java @@ -1,7 +1,7 @@ package com.casper.sdk.model.deploy; import com.casper.sdk.exception.NoSuchTypeException; -import com.casper.sdk.model.clvalue.*; +import com.casper.sdk.model.clvalue.AbstractCLValue; import com.casper.sdk.model.clvalue.cltype.AbstractCLType; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; import com.casper.sdk.model.clvalue.serde.Target; @@ -38,25 +38,6 @@ public class NamedArg

implements CasperSerializableObj @Override public void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException { ser.writeString(type); - if (clValue instanceof CLValueI32 || clValue instanceof CLValueU32) { - ser.writeI32(32 / 8); - } - if (clValue instanceof CLValueI64 || clValue instanceof CLValueU64) { - ser.writeI32(64 / 8); - } - if (clValue instanceof CLValueU128 || clValue instanceof CLValueU256 || - clValue instanceof CLValueU512 || clValue instanceof CLValuePublicKey) { - SerializerBuffer localEncoder = new SerializerBuffer(); - clValue.serialize(localEncoder); - int size = localEncoder.toByteArray().length; - ser.writeI32(size); //removing the CLValue type byte at the end - } - if (clValue instanceof CLValueOption) { - SerializerBuffer localEncoder = new SerializerBuffer(); - clValue.serialize(localEncoder); - int size = localEncoder.toByteArray().length; - ser.writeI32(size); //removing the CLValue type byte at the end - } clValue.serialize(ser, target); } } diff --git a/src/test/java/com/casper/sdk/model/clvalue/serde/SerializerDeserializerTests.java b/src/test/java/com/casper/sdk/model/clvalue/serde/SerializerDeserializerTests.java index 1b4d39769..949296b47 100644 --- a/src/test/java/com/casper/sdk/model/clvalue/serde/SerializerDeserializerTests.java +++ b/src/test/java/com/casper/sdk/model/clvalue/serde/SerializerDeserializerTests.java @@ -1,11 +1,13 @@ package com.casper.sdk.model.clvalue.serde; +import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.*; import com.casper.sdk.model.clvalue.cltype.AbstractCLType; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; +import lombok.AllArgsConstructor; import lombok.Getter; import org.junit.jupiter.api.Test; import org.slf4j.Logger; @@ -29,118 +31,110 @@ public class SerializerDeserializerTests { private static final Logger LOGGER = LoggerFactory.getLogger(SerializerDeserializerTests.class); /** - * A container for test data to test CLValue Encoder/Decoder + * A container for test data to test CLValue Encoder/Deserializer */ + @AllArgsConstructor + @Getter private static class TestData { - @Getter private final String name; - @Getter private final T value; - @Getter private final String hexEncodedValue; - - @Getter private final Class[] supportTypes; - - TestData(String name, T value, String hexEncodedValue, Class[] supportTypes) { - this.name = name; - this.value = value; - this.hexEncodedValue = hexEncodedValue; - this.supportTypes = supportTypes; - } + private final Target target; } private final List> successTestDataList = Arrays.asList( - new TestData<>(AbstractCLType.BOOL, true, "01", null), - new TestData<>(AbstractCLType.U8, Byte.valueOf("7"), "07", null), - new TestData<>(AbstractCLType.U32, 7L, "07000000", null), - new TestData<>(AbstractCLType.I32, 7, "07000000", null), - new TestData<>(AbstractCLType.I64, 7L, "0700000000000000", null), - new TestData<>(AbstractCLType.U64, new BigInteger("1024", 10), "0004000000000000", null), + new TestData<>(AbstractCLType.BOOL, true, "01", null, Target.JSON), + new TestData<>(AbstractCLType.U8, Byte.valueOf("7"), "07", null, Target.JSON), + new TestData<>(AbstractCLType.U32, 7L, "07000000", null, Target.JSON), + new TestData<>(AbstractCLType.I32, 7, "07000000", null, Target.JSON), + new TestData<>(AbstractCLType.I64, 7L, "0700000000000000", null, Target.JSON), + new TestData<>(AbstractCLType.U64, new BigInteger("1024", 10), "0004000000000000", null, Target.JSON), new TestData<>(AbstractCLType.U64, new BigInteger("18446744073709551615", 10), "ffffffffffffffff", - null), - new TestData<>(AbstractCLType.U512, new BigInteger("7", 10), "0107", null), - new TestData<>(AbstractCLType.U512, new BigInteger("1024", 10), "020004", null), + null, Target.JSON), + new TestData<>(AbstractCLType.U512, new BigInteger("7", 10), "0107", null, Target.JSON), + new TestData<>(AbstractCLType.U512, new BigInteger("1024", 10), "020004", null, Target.JSON), new TestData<>(AbstractCLType.U512, new BigInteger("123456789101112131415", 10), - "0957ff1ada959f4eb106", null), - new TestData<>(AbstractCLType.U512, new BigInteger("2500010000", 10), "0410200395", null), - new TestData<>(AbstractCLType.STRING, "the string", "0a00000074686520737472696e67", null), - new TestData<>(AbstractCLType.STRING, "Hello, World!", "0d00000048656c6c6f2c20576f726c6421", null)); + "0957ff1ada959f4eb106", null, Target.JSON), + new TestData<>(AbstractCLType.U512, new BigInteger("2500010000", 10), "0410200395", null, Target.JSON), + new TestData<>(AbstractCLType.STRING, "the string", "0a00000074686520737472696e67", null, Target.JSON), + new TestData<>(AbstractCLType.STRING, "Hello, World!", "0d00000048656c6c6f2c20576f726c6421", null, Target.JSON), + new TestData<>(AbstractCLType.STRING, "nested", "0a000000060000006e65737465640a", null, Target.BYTE)); private final List> lastValidNumberTestDataList = Arrays.asList( - new TestData<>(AbstractCLType.U64, SerializerBuffer.MAX_U64, null, null), - new TestData<>(AbstractCLType.U128, SerializerBuffer.MAX_U128, null, null), - new TestData<>(AbstractCLType.U256, SerializerBuffer.MAX_U256, null, null), - new TestData<>(AbstractCLType.U512, SerializerBuffer.MAX_U512, null, null)); + new TestData<>(AbstractCLType.U64, SerializerBuffer.MAX_U64, null, null, Target.JSON), + new TestData<>(AbstractCLType.U128, SerializerBuffer.MAX_U128, null, null, Target.JSON), + new TestData<>(AbstractCLType.U256, SerializerBuffer.MAX_U256, null, null, Target.JSON), + new TestData<>(AbstractCLType.U512, SerializerBuffer.MAX_U512, null, null, Target.JSON)); private final List> outOfBoundsTestDataList = Arrays.asList( - new TestData<>(AbstractCLType.U64, SerializerBuffer.MAX_U64.add(SerializerBuffer.ONE), null, null), - new TestData<>(AbstractCLType.U128, SerializerBuffer.MAX_U128.add(SerializerBuffer.ONE), null, null), - new TestData<>(AbstractCLType.U256, SerializerBuffer.MAX_U256.add(SerializerBuffer.ONE), null, null), - new TestData<>(AbstractCLType.U512, SerializerBuffer.MAX_U512.add(SerializerBuffer.ONE), null, null)); + new TestData<>(AbstractCLType.U64, SerializerBuffer.MAX_U64.add(SerializerBuffer.ONE), null, null, Target.JSON), + new TestData<>(AbstractCLType.U128, SerializerBuffer.MAX_U128.add(SerializerBuffer.ONE), null, null, Target.JSON), + new TestData<>(AbstractCLType.U256, SerializerBuffer.MAX_U256.add(SerializerBuffer.ONE), null, null, Target.JSON), + new TestData<>(AbstractCLType.U512, SerializerBuffer.MAX_U512.add(SerializerBuffer.ONE), null, null, Target.JSON)); @Test - void validateDecode_with_SampleData() throws ValueDeserializationException { + void validateDeserialize_with_SampleData() throws ValueDeserializationException, NoSuchTypeException { for (TestData testData : successTestDataList) { DeserializerBuffer deser = new DeserializerBuffer(testData.getHexEncodedValue()); switch (testData.getName()) { case AbstractCLType.BOOL: CLValueBool clValueBool = new CLValueBool(); - clValueBool.deserialize(deser); + clValueBool = (CLValueBool) clValueBool.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueBool.getValue()); assertEquals(testData.getValue(), clValueBool.getValue()); break; case AbstractCLType.U8: CLValueU8 clValueU8 = new CLValueU8(); - clValueU8.deserialize(deser); + clValueU8 = (CLValueU8) clValueU8.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueU8.getValue()); assertEquals(testData.getValue(), clValueU8.getValue()); break; case AbstractCLType.U32: CLValueU32 clValueU32 = new CLValueU32(); - clValueU32.deserialize(deser); + clValueU32 = (CLValueU32) clValueU32.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueU32.getValue()); assertEquals(testData.getValue(), clValueU32.getValue()); break; case AbstractCLType.U64: CLValueU64 clValueU64 = new CLValueU64(); - clValueU64.deserialize(deser); + clValueU64 = (CLValueU64) clValueU64.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueU64.getValue()); assertEquals(testData.getValue(), clValueU64.getValue()); break; case AbstractCLType.I32: CLValueI32 clValueI32 = new CLValueI32(); - clValueI32.deserialize(deser); + clValueI32 = (CLValueI32) clValueI32.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueI32.getValue()); assertEquals(testData.getValue(), clValueI32.getValue()); break; case AbstractCLType.I64: CLValueI64 clValueI64 = new CLValueI64(); - clValueI64.deserialize(deser); + clValueI64 = (CLValueI64) clValueI64.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueI64.getValue()); assertEquals(testData.getValue(), clValueI64.getValue()); break; case AbstractCLType.U128: CLValueU128 clValueU128 = new CLValueU128(); - clValueU128.deserialize(deser); + clValueU128 = (CLValueU128) clValueU128.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueU128.getValue()); assertEquals(testData.getValue(), clValueU128.getValue()); break; case AbstractCLType.U256: CLValueU256 clValueU256 = new CLValueU256(); - clValueU256.deserialize(deser); + clValueU256 = (CLValueU256) clValueU256.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueU256.getValue()); assertEquals(testData.getValue(), clValueU256.getValue()); break; case AbstractCLType.U512: CLValueU512 clValueU512 = new CLValueU512(); - clValueU512.deserialize(deser); + clValueU512 = (CLValueU512) clValueU512.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueU512.getValue()); assertEquals(testData.getValue(), clValueU512.getValue()); break; case AbstractCLType.STRING: CLValueString clValueString = new CLValueString(); - clValueString.deserialize(deser); + clValueString = (CLValueString) clValueString.deserialize(deser, testData.getTarget()); LOGGER.debug("Expected: {}, Actual: {}", testData.getValue(), clValueString.getValue()); assertEquals(testData.getValue(), clValueString.getValue()); break; @@ -149,58 +143,58 @@ void validateDecode_with_SampleData() throws ValueDeserializationException { } @Test - void validateEncode_with_SampleData() throws ValueSerializationException { + void validateEncode_with_SampleData() throws ValueSerializationException, NoSuchTypeException { for (TestData testData : successTestDataList) { SerializerBuffer ser = new SerializerBuffer(); switch (testData.getName()) { case AbstractCLType.BOOL: CLValueBool clValueBool = new CLValueBool((Boolean) testData.getValue()); - clValueBool.serialize(ser); + clValueBool.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueBool.getBytes()); break; case AbstractCLType.U8: CLValueU8 clValueU8 = new CLValueU8((Byte) testData.getValue()); - clValueU8.serialize(ser); + clValueU8.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueU8.getBytes()); break; case AbstractCLType.U32: CLValueU32 clValueU32 = new CLValueU32((Long) testData.getValue()); - clValueU32.serialize(ser); + clValueU32.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueU32.getBytes()); break; case AbstractCLType.U64: CLValueU64 clValueU64 = new CLValueU64((BigInteger) testData.getValue()); - clValueU64.serialize(ser); + clValueU64.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueU64.getBytes()); break; case AbstractCLType.I32: CLValueI32 clValueI32 = new CLValueI32((Integer) testData.getValue()); - clValueI32.serialize(ser); + clValueI32.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueI32.getBytes()); break; case AbstractCLType.I64: CLValueI64 clValueI64 = new CLValueI64((Long) testData.getValue()); - clValueI64.serialize(ser); + clValueI64.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueI64.getBytes()); break; case AbstractCLType.U128: CLValueU128 clValueU128 = new CLValueU128((BigInteger) testData.getValue()); - clValueU128.serialize(ser); + clValueU128.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueU128.getBytes()); break; case AbstractCLType.U256: CLValueU256 clValueU256 = new CLValueU256((BigInteger) testData.getValue()); - clValueU256.serialize(ser); + clValueU256.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueU256.getBytes()); break; case AbstractCLType.U512: CLValueU512 clValueU512 = new CLValueU512((BigInteger) testData.getValue()); - clValueU512.serialize(ser); + clValueU512.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueU512.getBytes()); break; case AbstractCLType.STRING: CLValueString clValueString = new CLValueString((String) testData.getValue()); - clValueString.serialize(ser); + clValueString.serialize(ser, testData.getTarget()); assertEquals(testData.getHexEncodedValue(), clValueString.getBytes()); break; } @@ -208,7 +202,7 @@ void validateEncode_with_SampleData() throws ValueSerializationException { } @Test - void numbersShouldBeInsideTheirTypeBounds() throws ValueSerializationException { + void numbersShouldBeInsideTheirTypeBounds() throws ValueSerializationException, NoSuchTypeException { for (TestData testData : lastValidNumberTestDataList) { SerializerBuffer ser = new SerializerBuffer(); switch (testData.getName()) { @@ -216,28 +210,28 @@ void numbersShouldBeInsideTheirTypeBounds() throws ValueSerializationException { LOGGER.debug("Testing last valid number (value: {}) for {}", testData.getValue(), AbstractCLType.U64); CLValueU64 clValueU64 = new CLValueU64((BigInteger) testData.getValue()); - clValueU64.serialize(ser); + clValueU64.serialize(ser, testData.getTarget()); assertNotNull(clValueU64.getBytes()); break; case AbstractCLType.U128: LOGGER.debug("Testing last valid number (value: {}) for {}", testData.getValue(), AbstractCLType.U128); CLValueU128 clValueU128 = new CLValueU128((BigInteger) testData.getValue()); - clValueU128.serialize(ser); + clValueU128.serialize(ser, testData.getTarget()); assertNotNull(clValueU128.getBytes()); break; case AbstractCLType.U256: LOGGER.debug("Testing last valid number (value: {}) for {}", testData.getValue(), AbstractCLType.U256); CLValueU256 clValueU256 = new CLValueU256((BigInteger) testData.getValue()); - clValueU256.serialize(ser); + clValueU256.serialize(ser, testData.getTarget()); assertNotNull(clValueU256.getBytes()); break; case AbstractCLType.U512: LOGGER.debug("Testing last valid number (value: {}) for {}", testData.getValue(), AbstractCLType.U512); CLValueU512 clValueU512 = new CLValueU512((BigInteger) testData.getValue()); - clValueU512.serialize(ser); + clValueU512.serialize(ser, testData.getTarget()); assertNotNull(clValueU512.getBytes()); break; } @@ -252,25 +246,25 @@ void dataOutOfBounds_should_throw_ValueSerializationException() { case AbstractCLType.U64: assertThrows(ValueSerializationException.class, () -> { CLValueU64 clValueU64 = new CLValueU64((BigInteger) testData.getValue()); - clValueU64.serialize(ser); + clValueU64.serialize(ser, testData.getTarget()); }); break; case AbstractCLType.U128: assertThrows(ValueSerializationException.class, () -> { CLValueU128 clValueU128 = new CLValueU128((BigInteger) testData.getValue()); - clValueU128.serialize(ser); + clValueU128.serialize(ser, testData.getTarget()); }); break; case AbstractCLType.U256: assertThrows(ValueSerializationException.class, () -> { CLValueU256 clValueU256 = new CLValueU256((BigInteger) testData.getValue()); - clValueU256.serialize(ser); + clValueU256.serialize(ser, testData.getTarget()); }); break; case AbstractCLType.U512: assertThrows(ValueSerializationException.class, () -> { CLValueU512 clValueU512 = new CLValueU512((BigInteger) testData.getValue()); - clValueU512.serialize(ser); + clValueU512.serialize(ser, testData.getTarget()); }); break; } @@ -283,9 +277,9 @@ void dataWithWrongInputLength_should_throw_IllegalArgumentException_or_ValueDese assertThrows(IllegalArgumentException.class, () -> new DeserializerBuffer("0")); final DeserializerBuffer deser2 = new DeserializerBuffer("01"); - assertThrows(ValueDeserializationException.class, () -> new CLValueU512().deserialize(deser2)); + assertThrows(ValueDeserializationException.class, () -> new CLValueU512().deserialize(deser2, Target.JSON)); final DeserializerBuffer deser3 = new DeserializerBuffer("01"); - assertThrows(ValueDeserializationException.class, () -> new CLValueString().deserialize(deser3)); + assertThrows(ValueDeserializationException.class, () -> new CLValueString().deserialize(deser3, Target.JSON)); } } From ecf0f8773c826b623d8f212e62dfc18ec560effd Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Thu, 29 Sep 2022 08:09:58 +0200 Subject: [PATCH 21/35] WIP: Map json deser not finding deserializer (StoredValueTests => validate_CLValueMap_Mapping_with_string_tuple1_i32 (line 594) --- build.gradle | 2 +- gradle.properties | 2 +- .../casper/sdk/helper/CasperDeployHelper.java | 2 +- .../sdk/model/clvalue/AbstractCLValue.java | 14 +++++++--- .../clvalue/AbstractCLValueWithChildren.java | 2 +- .../casper/sdk/model/clvalue/CLValueAny.java | 4 +-- .../casper/sdk/model/clvalue/CLValueBool.java | 13 +++++---- .../sdk/model/clvalue/CLValueByteArray.java | 8 ++++-- .../sdk/model/clvalue/CLValueFixedList.java | 12 ++++---- .../casper/sdk/model/clvalue/CLValueI32.java | 8 ++++-- .../casper/sdk/model/clvalue/CLValueI64.java | 8 ++++-- .../casper/sdk/model/clvalue/CLValueKey.java | 4 +-- .../casper/sdk/model/clvalue/CLValueList.java | 15 +++++----- .../casper/sdk/model/clvalue/CLValueMap.java | 12 ++++---- .../sdk/model/clvalue/CLValueOption.java | 28 +++++++++---------- .../sdk/model/clvalue/CLValuePublicKey.java | 4 +-- .../sdk/model/clvalue/CLValueResult.java | 12 ++++---- .../sdk/model/clvalue/CLValueString.java | 8 ++++-- .../sdk/model/clvalue/CLValueTuple1.java | 12 ++++---- .../sdk/model/clvalue/CLValueTuple2.java | 12 ++++---- .../sdk/model/clvalue/CLValueTuple3.java | 14 +++++----- .../casper/sdk/model/clvalue/CLValueU128.java | 8 ++++-- .../casper/sdk/model/clvalue/CLValueU256.java | 8 ++++-- .../casper/sdk/model/clvalue/CLValueU32.java | 8 ++++-- .../casper/sdk/model/clvalue/CLValueU512.java | 8 ++++-- .../casper/sdk/model/clvalue/CLValueU64.java | 8 ++++-- .../casper/sdk/model/clvalue/CLValueU8.java | 8 ++++-- .../casper/sdk/model/clvalue/CLValueURef.java | 4 +-- .../casper/sdk/model/clvalue/CLValueUnit.java | 2 +- 29 files changed, 148 insertions(+), 102 deletions(-) diff --git a/build.gradle b/build.gradle index 515341270..a6fc1252a 100644 --- a/build.gradle +++ b/build.gradle @@ -20,7 +20,7 @@ repositories { dependencies { implementation "dev.oak3:sbs4j:${sbs4jVersion}" - implementation "com.github.briandilley.jsonrpc4j:jsonrpc4j:${jsonrpc4jVersion}" + implementation "io.github.oak:jsonrpc4j:${jsonrpc4jVersion}" implementation "com.syntifi.crypto:crypto-key-common:${cryptokeyVersion}" implementation "com.syntifi.crypto:crypto-key-ed25519:${cryptokeyVersion}" implementation "com.syntifi.crypto:crypto-key-secp256k1:${cryptokeyVersion}" diff --git a/gradle.properties b/gradle.properties index e4768e0a0..56872c183 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,7 +2,7 @@ sbs4jVersion=0.1.5 cryptokeyVersion=0.4.0 lombokPluginVersion=6.2.0 jupiterVersion=5.9.0 -jsonrpc4jVersion=1.6 +jsonrpc4jVersion=1.6.1-oak jacksonVersion=2.13.3 log4jVersion=2.18.0 slf4jApiVersion=1.7.36 diff --git a/src/main/java/com/casper/sdk/helper/CasperDeployHelper.java b/src/main/java/com/casper/sdk/helper/CasperDeployHelper.java index 76e7be172..e75a59e3c 100644 --- a/src/main/java/com/casper/sdk/helper/CasperDeployHelper.java +++ b/src/main/java/com/casper/sdk/helper/CasperDeployHelper.java @@ -72,7 +72,7 @@ public static byte[] getDeployItemAndModuleBytesHash(ExecutableDeployItem deploy return Blake2b.digest(ser.toByteArray(), 32); } - public static ModuleBytes getPaymentModuleBytes(BigInteger paymentAmount) { + public static ModuleBytes getPaymentModuleBytes(BigInteger paymentAmount) throws ValueSerializationException { List> paymentArgs = new LinkedList<>(); NamedArg paymentArg = new NamedArg<>("amount", new CLValueU512(paymentAmount)); diff --git a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java index a5fdf13ea..8dd9c3aad 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java +++ b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java @@ -19,6 +19,8 @@ import dev.oak3.sbs4j.util.ByteUtils; import lombok.*; +import java.lang.reflect.InvocationTargetException; + /** * Base class for CLValues * @@ -35,7 +37,6 @@ public abstract class AbstractCLValue implements CasperSerializableObject, CasperDeserializableObject { @Setter(AccessLevel.PROTECTED) - @Getter private String bytes = ""; @Setter @@ -43,10 +44,14 @@ public abstract class AbstractCLValue @JsonInclude(Include.NON_NULL) private String parsed; - @Setter @JsonIgnore private T value; + public void setValue(T value) throws ValueSerializationException { + this.value = value; + this.serialize(new SerializerBuffer()); + } + @SneakyThrows({ValueDeserializationException.class}) @JsonSetter(value = "bytes") @ExcludeFromJacocoGeneratedReport @@ -96,10 +101,11 @@ protected void serializePrefixWithLength(SerializerBuffer ser) throws ValueSeria byte[] bytes = deser.readByteArray(length); byte clType = deser.readU8(); try { - AbstractCLValue clValue = CLTypeData.getTypeBySerializationTag(clType).getClazz().newInstance(); + AbstractCLValue clValue = CLTypeData.getTypeBySerializationTag(clType).getClazz().getDeclaredConstructor().newInstance(); clValue.deserialize(new DeserializerBuffer(Hex.encode(bytes))); return clValue; - } catch (InstantiationException | IllegalAccessException e) { + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | + InvocationTargetException e) { throw new ValueDeserializationException("Error while instantiating CLValue", e); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValueWithChildren.java b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValueWithChildren.java index 3e9baae58..6e9ad04a9 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValueWithChildren.java +++ b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValueWithChildren.java @@ -13,5 +13,5 @@ */ @EqualsAndHashCode(callSuper = true) public abstract class AbstractCLValueWithChildren extends AbstractCLValue { - protected abstract void setChildTypes(); + protected abstract void setChildTypes(T value); } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java index dfa840d38..a094da83b 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java @@ -45,7 +45,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueAny(Object value) { + public CLValueAny(Object value) throws ValueSerializationException { this.setValue(value); } @@ -80,7 +80,7 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc try (ByteArrayInputStream bis = new ByteArrayInputStream(deser.readByteArray(objectByteArrayLength)); ObjectInputStream ois = new ObjectInputStream(bis)) { this.setValue(ois.readObject()); - } catch (IOException | ClassNotFoundException e) { + } catch (IOException | ClassNotFoundException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java index 7e88522ae..a32566aa1 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java @@ -10,10 +10,7 @@ import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import lombok.*; import org.bouncycastle.util.encoders.Hex; import org.jetbrains.annotations.NotNull; @@ -44,7 +41,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueBool(Boolean value) { + public CLValueBool(Boolean value) throws ValueSerializationException { this.setValue(value); } @@ -67,6 +64,10 @@ public void serialize(@NotNull SerializerBuffer ser, Target target) throws NoSuc @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readBool()); + try { + this.setValue(deser.readBool()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException("Error serializing value", e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java index 137d057e3..a27627b99 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java @@ -32,7 +32,7 @@ public class CLValueByteArray extends AbstractCLValue { @JsonProperty("cl_type") private CLTypeByteArray clType = new CLTypeByteArray(); - public CLValueByteArray(byte[] value) { + public CLValueByteArray(byte[] value) throws ValueSerializationException { this.setValue(value); this.clType.setLength(value.length); } @@ -56,7 +56,11 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readByteArray(this.getClType().getLength())); + try { + this.setValue(deser.readByteArray(this.getClType().getLength())); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java index 54a8168a3..693ac2bc9 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java @@ -36,9 +36,9 @@ public class CLValueFixedList extends AbstractCLValue> value) { + public CLValueFixedList(List> value) throws ValueSerializationException { + setListType(value); this.setValue(value); - setListType(); } @Override @@ -49,7 +49,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa super.serializePrefixWithLength(ser); } - setListType(); + setListType(this.getValue()); for (AbstractCLValue child : getValue()) { child.serialize(ser); @@ -88,12 +88,12 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc } while (hasMoreItems); setValue(list); - } catch (NoSuchTypeException | DynamicInstanceException e) { + } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } - protected void setListType() { - clType.setListType(getValue().get(0).getClType()); + protected void setListType(List> value) { + clType.setListType(value.get(0).getClType()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java index 9f86a8de6..0cc64939e 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java @@ -41,7 +41,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueI32(Integer value) { + public CLValueI32(Integer value) throws ValueSerializationException { this.setValue(value); } @@ -64,6 +64,10 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readI32()); + try { + this.setValue(deser.readI32()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java index 1a6fc3d64..a850d3e9f 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java @@ -43,7 +43,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueI64(Long value) { + public CLValueI64(Long value) throws ValueSerializationException { this.setValue(value); } @@ -66,6 +66,10 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readI64()); + try { + this.setValue(deser.readI64()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java index 85fb5b3f5..a956feee1 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java @@ -46,7 +46,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueKey(Key value) { + public CLValueKey(Key value) throws ValueSerializationException { this.setValue(value); } @@ -72,7 +72,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { try { this.setValue(Key.fromTaggedHexString(ByteUtils.encodeHexString(deser.readByteArray(33)))); - } catch (IllegalArgumentException | NoSuchKeyTagException e) { + } catch (IllegalArgumentException | NoSuchKeyTagException | ValueSerializationException e) { throw new ValueDeserializationException("Error decoding CLValuePublicKey", e); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java index 82d4a5777..79cdfd160 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java @@ -32,13 +32,13 @@ @Setter @EqualsAndHashCode(callSuper = true) @NoArgsConstructor -public class CLValueList extends AbstractCLValue>, CLTypeList> { +public class CLValueList extends AbstractCLValueWithChildren>, CLTypeList> { @JsonProperty("cl_type") private CLTypeList clType = new CLTypeList(); - public CLValueList(List> value) { + public CLValueList(List> value) throws ValueSerializationException { this.setValue(value); - setListType(); + setChildTypes(value); } @Override @@ -49,7 +49,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa super.serializePrefixWithLength(ser); } - setListType(); + setChildTypes(this.getValue()); // List length is written first CLValueI32 length = new CLValueI32(getValue().size()); @@ -87,12 +87,13 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc } setValue(list); - } catch (NoSuchTypeException | DynamicInstanceException e) { + } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } - protected void setListType() { - clType.setListType(getValue().get(0).getClType()); + @Override + protected void setChildTypes(List> value) { + clType.setListType(value.get(0).getClType()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java index 3c89b24e7..790b784e4 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java @@ -38,9 +38,9 @@ public class CLValueMap extends @JsonProperty("cl_type") private CLTypeMap clType = new CLTypeMap(); - public CLValueMap(Map, ? extends AbstractCLValue> value) { + public CLValueMap(Map, ? extends AbstractCLValue> value) throws ValueSerializationException { + setChildTypes(value); this.setValue(value); - setChildTypes(); } @Override @@ -51,7 +51,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa super.serializePrefixWithLength(ser); } - setChildTypes(); + setChildTypes(this.getValue()); CLValueI32 mapLength = new CLValueI32(getValue().size()); mapLength.serialize(ser); @@ -103,14 +103,14 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc } setValue(map); - } catch (NoSuchTypeException | DynamicInstanceException e) { + } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } @Override - protected void setChildTypes() { - Entry, ? extends AbstractCLValue> entry = getValue().entrySet().iterator() + protected void setChildTypes(Map, ? extends AbstractCLValue> value) { + Entry, ? extends AbstractCLValue> entry = value.entrySet().iterator() .next(); clType.setKeyValueTypes( diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java index dc378cbba..9bdcdb546 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java @@ -11,10 +11,7 @@ import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; +import lombok.*; import org.bouncycastle.util.encoders.Hex; import java.util.Optional; @@ -30,18 +27,14 @@ @Getter @Setter @EqualsAndHashCode(callSuper = true) -@AllArgsConstructor -public class CLValueOption extends AbstractCLValue>, CLTypeOption> { +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class CLValueOption extends AbstractCLValueWithChildren>, CLTypeOption> { @JsonProperty("cl_type") private CLTypeOption clType = new CLTypeOption(); - public CLValueOption() { - this(Optional.of(new CLValueAny(null))); - } - - public CLValueOption(Optional> value) { + public CLValueOption(Optional> value) throws ValueSerializationException { + setChildTypes(value); this.setValue(value); - this.clType.setChildType(value.isPresent() ? value.get().getClType() : null); } @Override @@ -92,13 +85,18 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildType()).getChildTypes()); } - setValue(Optional.of(child)); - if (isPresent.getValue().equals(Boolean.TRUE)) { child.deserialize(deser); } - } catch (NoSuchTypeException | DynamicInstanceException e) { + + setValue(Optional.of(child)); + } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } + + @Override + protected void setChildTypes(Optional> value) { + clType.setChildType(value.isPresent() ? value.get().getClType() : null); + } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java b/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java index 4f9a3a3c4..b62612681 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java @@ -47,7 +47,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValuePublicKey(PublicKey value) { + public CLValuePublicKey(PublicKey value) throws ValueSerializationException { this.setValue(value); } @@ -73,7 +73,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { try { this.setValue(PublicKey.fromTaggedHexString(ByteUtils.encodeHexString(deser.readByteArray(33)))); - } catch (NoSuchAlgorithmException | IllegalArgumentException e) { + } catch (NoSuchAlgorithmException | IllegalArgumentException | ValueSerializationException e) { throw new ValueDeserializationException("Error decoding CLValuePublicKey", e); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java index 7662065e7..0690b0930 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java @@ -49,9 +49,9 @@ protected static class Result { @JsonProperty("cl_type") private CLTypeResult clType = new CLTypeResult(); - public CLValueResult(AbstractCLValue ok, AbstractCLValue err) { + public CLValueResult(AbstractCLValue ok, AbstractCLValue err) throws ValueSerializationException { + setChildTypes(ok, err); this.setValue(new Result(ok, err)); - setChildTypes(); } @Override @@ -62,7 +62,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa super.serializePrefixWithLength(ser); } - setChildTypes(); + setChildTypes(this.getValue().getOk(), this.getValue().getErr()); CLValueBool clValueTrue = new CLValueBool(true); clValueTrue.serialize(ser); @@ -108,13 +108,13 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc result.setErr(clValueErr); setValue(result); - } catch (NoSuchTypeException | DynamicInstanceException e) { + } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } - protected void setChildTypes() { + protected void setChildTypes(AbstractCLValue ok, AbstractCLValue err) { clType.setOkErrTypes( - new CLTypeResult.CLTypeResultOkErrTypes(getValue().getOk().getClType(), getValue().getErr().getClType())); + new CLTypeResult.CLTypeResultOkErrTypes(ok.getClType(), err.getClType())); } } \ No newline at end of file diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java index 3a60cbbb2..1e5f50af8 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java @@ -43,7 +43,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueString(String value) { + public CLValueString(String value) throws ValueSerializationException { this.setValue(value); } @@ -66,6 +66,10 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readString()); + try { + this.setValue(deser.readString()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java index 97f704e24..6e84d5bb1 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java @@ -36,9 +36,9 @@ public class CLValueTuple1 extends AbstractCLValueWithChildren> value) { + public CLValueTuple1(Unit> value) throws ValueSerializationException { + setChildTypes(value); this.setValue(value); - setChildTypes(); } @Override @@ -49,7 +49,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce super.serializePrefixWithLength(ser); } - setChildTypes(); + setChildTypes(this.getValue()); getValue().getValue0().serialize(ser); if (target.equals(Target.BYTE)) { @@ -72,13 +72,13 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc child1.deserialize(deser); setValue(new Unit<>(child1)); - } catch (NoSuchTypeException | DynamicInstanceException e) { + } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } @Override - protected void setChildTypes() { - clType.setChildTypes(Arrays.asList(getValue().getValue0().getClType())); + protected void setChildTypes(Unit> value) { + clType.setChildTypes(Arrays.asList(value.getValue0().getClType())); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java index 159170680..fd155ca76 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java @@ -37,9 +37,9 @@ public class CLValueTuple2 @JsonProperty("cl_type") private CLTypeTuple2 clType = new CLTypeTuple2(); - public CLValueTuple2(Pair, ? extends AbstractCLValue> value) { + public CLValueTuple2(Pair, ? extends AbstractCLValue> value) throws ValueSerializationException { + setChildTypes(value); this.setValue(value); - setChildTypes(); } @Override @@ -50,7 +50,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce super.serializePrefixWithLength(ser); } - setChildTypes(); + setChildTypes(this.getValue()); getValue().getValue0().serialize(ser); getValue().getValue1().serialize(ser); @@ -82,13 +82,13 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc child2.deserialize(deser); setValue(new Pair<>(child1, child2)); - } catch (NoSuchTypeException | DynamicInstanceException e) { + } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } @Override - protected void setChildTypes() { - clType.setChildTypes(Arrays.asList(getValue().getValue0().getClType(), getValue().getValue1().getClType())); + protected void setChildTypes(Pair, ? extends AbstractCLValue> value) { + clType.setChildTypes(Arrays.asList(value.getValue0().getClType(), value.getValue1().getClType())); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java index cadbab2e5..42ab49f88 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java @@ -37,9 +37,9 @@ public class CLValueTuple3 extends @JsonProperty("cl_type") private CLTypeTuple3 clType = new CLTypeTuple3(); - public CLValueTuple3(Triplet, ? extends AbstractCLValue, ? extends AbstractCLValue> value) { + public CLValueTuple3(Triplet, ? extends AbstractCLValue, ? extends AbstractCLValue> value) throws ValueSerializationException { + setChildTypes(value); this.setValue(value); - setChildTypes(); } @Override @@ -50,7 +50,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce super.serializePrefixWithLength(ser); } - setChildTypes(); + setChildTypes(this.getValue()); getValue().getValue0().serialize(ser); getValue().getValue1().serialize(ser); @@ -92,15 +92,15 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc child3.deserialize(deser); setValue(new Triplet<>(child1, child2, child3)); - } catch (NoSuchTypeException | DynamicInstanceException e) { + } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } @Override - protected void setChildTypes() { - clType.setChildTypes(Arrays.asList(getValue().getValue0().getClType(), getValue().getValue1().getClType(), - getValue().getValue2().getClType())); + protected void setChildTypes(Triplet, ? extends AbstractCLValue, ? extends AbstractCLValue> value) { + clType.setChildTypes(Arrays.asList(value.getValue0().getClType(), value.getValue1().getClType(), + value.getValue2().getClType())); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java index f87d18eb7..96d38bf82 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java @@ -45,7 +45,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueU128(BigInteger value) { + public CLValueU128(BigInteger value) throws ValueSerializationException { this.setValue(value); } @@ -68,6 +68,10 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readU128()); + try { + this.setValue(deser.readU128()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java index 047bad19c..af158a303 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java @@ -45,7 +45,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueU256(BigInteger value) { + public CLValueU256(BigInteger value) throws ValueSerializationException { this.setValue(value); } @@ -68,6 +68,10 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readU256()); + try { + this.setValue(deser.readU256()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java index 7a004b596..8f231dfaa 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java @@ -43,7 +43,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueU32(Long value) { + public CLValueU32(Long value) throws ValueSerializationException { this.setValue(value); } @@ -66,6 +66,10 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readU32()); + try { + this.setValue(deser.readU32()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java index b93e0fe83..99a100706 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java @@ -43,7 +43,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueU512(BigInteger value) { + public CLValueU512(BigInteger value) throws ValueSerializationException { this.setValue(value); } @@ -66,6 +66,10 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readU512()); + try { + this.setValue(deser.readU512()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java index e2160e7d1..747185418 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java @@ -43,7 +43,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueU64(BigInteger value) { + public CLValueU64(BigInteger value) throws ValueSerializationException { this.setValue(value); } @@ -66,6 +66,10 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readU64()); + try { + this.setValue(deser.readU64()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java index 0e32a2293..d161bc9e0 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java @@ -43,7 +43,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueU8(Byte value) { + public CLValueU8(Byte value) throws ValueSerializationException { this.setValue(value); } @@ -66,6 +66,10 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce @Override public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - this.setValue(deser.readU8()); + try { + this.setValue(deser.readU8()); + } catch (ValueSerializationException e) { + throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java index 9956382b1..88f425072 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java @@ -39,7 +39,7 @@ public class CLValueURef extends AbstractCLValue { private CLTypeURef clType = new CLTypeURef(); - public CLValueURef(URef value) { + public CLValueURef(URef value) throws ValueSerializationException { this.setValue(value); } @@ -87,7 +87,7 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc serializationTag.deserialize(deser); uref.setAccessRight(URefAccessRight.getTypeBySerializationTag(serializationTag.getValue())); setValue(uref); - } catch (DynamicInstanceException e) { + } catch (DynamicInstanceException | ValueSerializationException e) { throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java index fe9bf400f..299cca2a3 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java @@ -45,7 +45,7 @@ protected String getJsonClType() { return this.getClType().getTypeName(); } - public CLValueUnit() { + public CLValueUnit() throws ValueSerializationException { this.setValue(UNITY_EMPTY_VALUE); } From 938fec7cb6d9253726da3057767b2d8f2318c0a7 Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Thu, 29 Sep 2022 16:36:43 +0200 Subject: [PATCH 22/35] Fixed CLValueMap json deserialization, missing object equals --- .../java/com/casper/sdk/model/clvalue/CLValueList.java | 3 ++- src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java | 2 ++ .../java/com/casper/sdk/model/clvalue/CLValueOption.java | 7 +++++-- .../com/casper/sdk/model/storedvalue/StoredValueTests.java | 6 +++--- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java index 79cdfd160..dcb4ec8fb 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java @@ -6,6 +6,7 @@ import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeList; import com.casper.sdk.model.clvalue.serde.Target; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -37,8 +38,8 @@ public class CLValueList extends AbstractCLValueWithChildren> value) throws ValueSerializationException { - this.setValue(value); setChildTypes(value); + this.setValue(value); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java index 790b784e4..85a2e757c 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java @@ -6,6 +6,7 @@ import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeMap; import com.casper.sdk.model.clvalue.serde.Target; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -109,6 +110,7 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc } @Override + @JsonIgnore protected void setChildTypes(Map, ? extends AbstractCLValue> value) { Entry, ? extends AbstractCLValue> entry = value.entrySet().iterator() .next(); diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java index 9bdcdb546..2a97bcbdb 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java @@ -11,7 +11,10 @@ import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.*; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.bouncycastle.util.encoders.Hex; import java.util.Optional; @@ -27,7 +30,7 @@ @Getter @Setter @EqualsAndHashCode(callSuper = true) -@NoArgsConstructor(access = AccessLevel.PROTECTED) +@NoArgsConstructor public class CLValueOption extends AbstractCLValueWithChildren>, CLTypeOption> { @JsonProperty("cl_type") private CLTypeOption clType = new CLTypeOption(); diff --git a/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java b/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java index 1ae9e4a48..f550367e2 100644 --- a/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java +++ b/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java @@ -581,13 +581,13 @@ void validate_CLValueMap_Mapping_with_string_i32() throws IOException, StoredValueData expected = createAndInitExpectedStoredValueData(expectedClValue); - assertEquals(expected, sv); - String expectedJson = getPrettyJson(expected); + JSONAssert.assertEquals(inputJson, expectedJson, false); + LOGGER.debug("Serialized JSON: {}", expectedJson); - JSONAssert.assertEquals(inputJson, expectedJson, false); + assertEquals(expected, sv); } @Test From c810b5ce0e3a73b4073d232b91b6b1a80ba0e65e Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Thu, 29 Sep 2022 17:51:10 +0200 Subject: [PATCH 23/35] Fix AbstractClValue equals for CLValueMap --- .../java/com/casper/sdk/model/bid/Bid.java | 6 +-- .../sdk/model/clvalue/AbstractCLValue.java | 26 +++++++++- .../casper/sdk/model/clvalue/CLValueMap.java | 6 +-- .../cltype/AbstractCLTypeWithChildren.java | 4 +- .../sdk/model/clvalue/cltype/CLTypeMap.java | 2 +- .../model/storedvalue/StoredValueTests.java | 47 ++++--------------- 6 files changed, 43 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/casper/sdk/model/bid/Bid.java b/src/main/java/com/casper/sdk/model/bid/Bid.java index 932555d58..ea6b62e7a 100644 --- a/src/main/java/com/casper/sdk/model/bid/Bid.java +++ b/src/main/java/com/casper/sdk/model/bid/Bid.java @@ -11,7 +11,7 @@ import java.math.BigInteger; import java.security.NoSuchAlgorithmException; -import java.util.LinkedHashMap; +import java.util.HashMap; import java.util.Map; /** @@ -45,7 +45,7 @@ public class Bid { */ @JsonIgnore @Builder.Default - private Map delegators = new LinkedHashMap<>(); + private Map delegators = new HashMap<>(); /** * `true` if validator has been \"evicted\" @@ -84,7 +84,7 @@ protected void setJsonDelegators(Map node) @JsonGetter("delegators") @ExcludeFromJacocoGeneratedReport protected Map getJsonDelegators() { - Map out = new LinkedHashMap<>(); + Map out = new HashMap<>(); for (Map.Entry entry : this.delegators.entrySet()) { out.put(entry.getKey().getAlgoTaggedHex(), entry.getValue()); } diff --git a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java index 8dd9c3aad..c9d2328c2 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java +++ b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java @@ -20,6 +20,9 @@ import lombok.*; import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; /** * Base class for CLValues @@ -30,7 +33,6 @@ * @since 0.0.1 */ @Getter -@EqualsAndHashCode(of = {"bytes", "value"}) @JsonTypeInfo(use = JsonTypeInfo.Id.NONE) @JsonTypeResolver(CLValueResolver.class) public abstract class AbstractCLValue @@ -120,4 +122,26 @@ protected void encodeType(SerializerBuffer ser) throws NoSuchTypeException { byte val = (getClType().getClTypeData().getSerializationTag()); ser.writeU8(val); } + + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof AbstractCLValue)) return false; + final AbstractCLValue other = (AbstractCLValue) o; + if (!other.canEqual(this)) return false; + final Object this$bytes = this.getBytes(); + final Object other$bytes = other.getBytes(); + if (!Objects.equals(this$bytes, other$bytes)) return false; + final Object this$value = this.getValue(); + final Object other$value = other.getValue(); + if (this$value instanceof Map) { + return other$value.equals(other$value); + } else { + return Objects.equals(this$value, other$value); + } + } + + protected boolean canEqual(final Object other) { + return other instanceof AbstractCLValue; + } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java index 85a2e757c..00a2d07c9 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java @@ -18,7 +18,7 @@ import lombok.Setter; import org.bouncycastle.util.encoders.Hex; -import java.util.LinkedHashMap; +import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -32,7 +32,7 @@ */ @Getter @Setter -@EqualsAndHashCode(callSuper = true) +@EqualsAndHashCode(callSuper = true, of = {"clType"}) @NoArgsConstructor public class CLValueMap extends AbstractCLValueWithChildren, ? extends AbstractCLValue>, CLTypeMap> { @@ -75,7 +75,7 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc CLTypeData keyType = clType.getKeyValueTypes().getKeyType().getClTypeData(); CLTypeData valType = clType.getKeyValueTypes().getValueType().getClTypeData(); - Map, AbstractCLValue> map = new LinkedHashMap<>(); + Map, AbstractCLValue> map = new HashMap<>(); CLValueI32 mapLength = new CLValueI32(0); mapLength.deserialize(deser); diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/AbstractCLTypeWithChildren.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/AbstractCLTypeWithChildren.java index a301b0834..27e972d90 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/AbstractCLTypeWithChildren.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/AbstractCLTypeWithChildren.java @@ -8,7 +8,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; -import java.util.LinkedHashMap; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -82,7 +82,7 @@ private void addChildType(Object childTypeObject, List parent) addChildType(child, parent); } } else if (childTypeObject instanceof Map) { - Map subChildTypes = (LinkedHashMap) childTypeObject; + Map subChildTypes = (HashMap) childTypeObject; for (Entry entry : subChildTypes.entrySet()) { AbstractCLType nextParent = CLTypeData.getTypeByName(entry.getKey().toString()).getClTypeClass() diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeMap.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeMap.java index d5fd02f6b..768e1e0c4 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/CLTypeMap.java @@ -30,7 +30,7 @@ public class CLTypeMap extends AbstractCLTypeWithChildren { */ @Getter @Setter - @EqualsAndHashCode + @EqualsAndHashCode(of = {"keyType", "valueType"}) @NoArgsConstructor @AllArgsConstructor public static class CLTypeMapEntryType { diff --git a/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java b/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java index f550367e2..ea5dea4b7 100644 --- a/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java +++ b/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java @@ -2,31 +2,7 @@ import com.casper.sdk.model.AbstractJsonTests; import com.casper.sdk.model.account.Account; -import com.casper.sdk.model.clvalue.AbstractCLValue; -import com.casper.sdk.model.clvalue.CLValueAny; -import com.casper.sdk.model.clvalue.CLValueBool; -import com.casper.sdk.model.clvalue.CLValueByteArray; -import com.casper.sdk.model.clvalue.CLValueFixedList; -import com.casper.sdk.model.clvalue.CLValueI32; -import com.casper.sdk.model.clvalue.CLValueI64; -import com.casper.sdk.model.clvalue.CLValueKey; -import com.casper.sdk.model.clvalue.CLValueList; -import com.casper.sdk.model.clvalue.CLValueMap; -import com.casper.sdk.model.clvalue.CLValueOption; -import com.casper.sdk.model.clvalue.CLValuePublicKey; -import com.casper.sdk.model.clvalue.CLValueResult; -import com.casper.sdk.model.clvalue.CLValueString; -import com.casper.sdk.model.clvalue.CLValueTuple1; -import com.casper.sdk.model.clvalue.CLValueTuple2; -import com.casper.sdk.model.clvalue.CLValueTuple3; -import com.casper.sdk.model.clvalue.CLValueU128; -import com.casper.sdk.model.clvalue.CLValueU256; -import com.casper.sdk.model.clvalue.CLValueU32; -import com.casper.sdk.model.clvalue.CLValueU512; -import com.casper.sdk.model.clvalue.CLValueU64; -import com.casper.sdk.model.clvalue.CLValueU8; -import com.casper.sdk.model.clvalue.CLValueURef; -import com.casper.sdk.model.clvalue.CLValueUnit; +import com.casper.sdk.model.clvalue.*; import com.casper.sdk.model.contract.Contract; import com.casper.sdk.model.key.AlgorithmTag; import com.casper.sdk.model.key.Key; @@ -52,14 +28,9 @@ import java.io.IOException; import java.math.BigInteger; import java.nio.BufferUnderflowException; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; +import java.util.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Unit tests for {@link StoredValueData} @@ -581,13 +552,13 @@ void validate_CLValueMap_Mapping_with_string_i32() throws IOException, StoredValueData expected = createAndInitExpectedStoredValueData(expectedClValue); - String expectedJson = getPrettyJson(expected); + assertEquals(expected, sv); - JSONAssert.assertEquals(inputJson, expectedJson, false); + String expectedJson = getPrettyJson(expected); LOGGER.debug("Serialized JSON: {}", expectedJson); - assertEquals(expected, sv); + JSONAssert.assertEquals(inputJson, expectedJson, false); } @Test @@ -601,7 +572,7 @@ void validate_CLValueMap_Mapping_with_string_tuple1_i32() throws IOException, StoredValueData sv = OBJECT_MAPPER.readValue(inputJson, StoredValueData.class); // Should be CLValueMap assertTrue(sv.getStoredValue().getValue() instanceof CLValueMap); - Map map = new LinkedHashMap<>(); + Map map = new HashMap<>(); map.put(new CLValueString("ABC"), new CLValueTuple1(new Unit<>(new CLValueI32(10)))); CLValueMap expectedClValue = new CLValueMap(map); @@ -629,8 +600,8 @@ void validate_CLValueMap_Mapping_with_Map_i32_Any() throws IOException, // Should be CLValueMap assertTrue(sv.getStoredValue().getValue() instanceof CLValueMap); - Map map = new LinkedHashMap<>(); - Map childMap = new LinkedHashMap<>(); + Map map = new HashMap<>(); + Map childMap = new HashMap<>(); childMap.put(new CLValueI32(1), new CLValueAny(DummyClass.builder().name("One").value(1).build())); childMap.put(new CLValueI32(2), new CLValueAny(DummyClass.builder().name("Two").value(2).build())); map.put(new CLValueU64(BigInteger.ONE), new CLValueMap(childMap)); From 00ff34f3c6bd570dbae868c4c09b7a6de36315ff Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Thu, 6 Oct 2022 17:02:20 -0300 Subject: [PATCH 24/35] Changes for serializing ClValueMap Fixing some implementation mistakes and generalizing the equality check --- .../java/com/casper/sdk/model/bid/Bid.java | 12 ++-- .../sdk/model/clvalue/AbstractCLValue.java | 39 ++++------- .../casper/sdk/model/clvalue/CLValueList.java | 1 - .../casper/sdk/model/clvalue/CLValueMap.java | 64 ++++++++++++++++--- .../cltype/AbstractCLTypeWithChildren.java | 4 +- .../model/storedvalue/StoredValueTests.java | 41 ++++++++++-- 6 files changed, 113 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/casper/sdk/model/bid/Bid.java b/src/main/java/com/casper/sdk/model/bid/Bid.java index ea6b62e7a..53b6207ac 100644 --- a/src/main/java/com/casper/sdk/model/bid/Bid.java +++ b/src/main/java/com/casper/sdk/model/bid/Bid.java @@ -7,11 +7,15 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -45,7 +49,7 @@ public class Bid { */ @JsonIgnore @Builder.Default - private Map delegators = new HashMap<>(); + private Map delegators = new LinkedHashMap<>(); /** * `true` if validator has been \"evicted\" @@ -84,7 +88,7 @@ protected void setJsonDelegators(Map node) @JsonGetter("delegators") @ExcludeFromJacocoGeneratedReport protected Map getJsonDelegators() { - Map out = new HashMap<>(); + Map out = new LinkedHashMap<>(); for (Map.Entry entry : this.delegators.entrySet()) { out.put(entry.getKey().getAlgoTaggedHex(), entry.getValue()); } diff --git a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java index c9d2328c2..6817486a7 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java +++ b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java @@ -8,8 +8,13 @@ import com.casper.sdk.model.clvalue.serde.CasperDeserializableObject; import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; import com.casper.sdk.model.clvalue.serde.Target; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonTypeResolver; import com.syntifi.crypto.key.encdec.Hex; import dev.oak3.sbs4j.DeserializerBuffer; @@ -17,12 +22,13 @@ import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import dev.oak3.sbs4j.util.ByteUtils; -import lombok.*; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.SneakyThrows; import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; /** * Base class for CLValues @@ -35,6 +41,7 @@ @Getter @JsonTypeInfo(use = JsonTypeInfo.Id.NONE) @JsonTypeResolver(CLValueResolver.class) +@EqualsAndHashCode(of = {"bytes", "value"}) public abstract class AbstractCLValue implements CasperSerializableObject, CasperDeserializableObject { @@ -122,26 +129,4 @@ protected void encodeType(SerializerBuffer ser) throws NoSuchTypeException { byte val = (getClType().getClTypeData().getSerializationTag()); ser.writeU8(val); } - - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof AbstractCLValue)) return false; - final AbstractCLValue other = (AbstractCLValue) o; - if (!other.canEqual(this)) return false; - final Object this$bytes = this.getBytes(); - final Object other$bytes = other.getBytes(); - if (!Objects.equals(this$bytes, other$bytes)) return false; - final Object this$value = this.getValue(); - final Object other$value = other.getValue(); - if (this$value instanceof Map) { - return other$value.equals(other$value); - } else { - return Objects.equals(this$value, other$value); - } - } - - protected boolean canEqual(final Object other) { - return other instanceof AbstractCLValue; - } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java index dcb4ec8fb..be1df69fd 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java @@ -6,7 +6,6 @@ import com.casper.sdk.model.clvalue.cltype.CLTypeData; import com.casper.sdk.model.clvalue.cltype.CLTypeList; import com.casper.sdk.model.clvalue.serde.Target; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java index 00a2d07c9..2525d90df 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java @@ -12,15 +12,15 @@ import dev.oak3.sbs4j.SerializerBuffer; import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.bouncycastle.util.encoders.Hex; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; /** * Casper Map CLValue implementation @@ -32,7 +32,6 @@ */ @Getter @Setter -@EqualsAndHashCode(callSuper = true, of = {"clType"}) @NoArgsConstructor public class CLValueMap extends AbstractCLValueWithChildren, ? extends AbstractCLValue>, CLTypeMap> { @@ -75,7 +74,7 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc CLTypeData keyType = clType.getKeyValueTypes().getKeyType().getClTypeData(); CLTypeData valType = clType.getKeyValueTypes().getValueType().getClTypeData(); - Map, AbstractCLValue> map = new HashMap<>(); + Map, AbstractCLValue> map = new LinkedHashMap<>(); CLValueI32 mapLength = new CLValueI32(0); mapLength.deserialize(deser); @@ -112,10 +111,59 @@ public void deserialize(DeserializerBuffer deser) throws ValueDeserializationExc @Override @JsonIgnore protected void setChildTypes(Map, ? extends AbstractCLValue> value) { - Entry, ? extends AbstractCLValue> entry = value.entrySet().iterator() - .next(); + Entry, ? extends AbstractCLValue> entry = value.entrySet().iterator().next(); - clType.setKeyValueTypes( - new CLTypeMap.CLTypeMapEntryType(entry.getKey().getClType(), entry.getValue().getClType())); + clType.setKeyValueTypes(new CLTypeMap.CLTypeMapEntryType(entry.getKey().getClType(), entry.getValue().getClType())); + } + + // This needed to be customized to ensure equality is being checked correctly. + // The java Map equals method tries to get the "other" map entry's value by using "this" key object, + // which then fails to find the object since they are "different" and returns always null. + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof CLValueMap)) return false; + final CLValueMap other = (CLValueMap) o; + if (!other.canEqual(this)) return false; + + final Object this$clType = this.getClType(); + final Object other$clType = other.getClType(); + if (!Objects.equals(this$clType, other$clType)) return false; + + final Object this$bytes = this.getBytes(); + final Object other$bytes = other.getBytes(); + if (!Objects.equals(this$bytes, other$bytes)) return false; + final Map, ? extends AbstractCLValue> this$value = this.getValue(); + final Map, ? extends AbstractCLValue> other$value = other.getValue(); + + for (Entry, ? extends AbstractCLValue> this$entry : this$value.entrySet()) { + AbstractCLValue this$entryKey = this$entry.getKey(); + AbstractCLValue this$entryValue = this$entry.getValue(); + boolean found = false; + for (Entry, ? extends AbstractCLValue> other$entry : other$value.entrySet()) { + AbstractCLValue other$entryKey = other$entry.getKey(); + AbstractCLValue other$entryValue = other$entry.getValue(); + if (this$entryKey.equals(other$entryKey) && this$entryValue.equals(other$entryValue)) { + found = true; + break; + } + } + if (!found) return false; + } + + return true; + } + + protected boolean canEqual(final Object other) { + return other instanceof CLValueMap; + } + + @Override + public int hashCode() { + final int PRIME = 59; + int result = super.hashCode(); + final Object $clType = this.getClType(); + result = result * PRIME + ($clType == null ? 43 : $clType.hashCode()); + return result; } } \ No newline at end of file diff --git a/src/main/java/com/casper/sdk/model/clvalue/cltype/AbstractCLTypeWithChildren.java b/src/main/java/com/casper/sdk/model/clvalue/cltype/AbstractCLTypeWithChildren.java index 27e972d90..a301b0834 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/cltype/AbstractCLTypeWithChildren.java +++ b/src/main/java/com/casper/sdk/model/clvalue/cltype/AbstractCLTypeWithChildren.java @@ -8,7 +8,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -82,7 +82,7 @@ private void addChildType(Object childTypeObject, List parent) addChildType(child, parent); } } else if (childTypeObject instanceof Map) { - Map subChildTypes = (HashMap) childTypeObject; + Map subChildTypes = (LinkedHashMap) childTypeObject; for (Entry entry : subChildTypes.entrySet()) { AbstractCLType nextParent = CLTypeData.getTypeByName(entry.getKey().toString()).getClTypeClass() diff --git a/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java b/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java index ea5dea4b7..1ae9e4a48 100644 --- a/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java +++ b/src/test/java/com/casper/sdk/model/storedvalue/StoredValueTests.java @@ -2,7 +2,31 @@ import com.casper.sdk.model.AbstractJsonTests; import com.casper.sdk.model.account.Account; -import com.casper.sdk.model.clvalue.*; +import com.casper.sdk.model.clvalue.AbstractCLValue; +import com.casper.sdk.model.clvalue.CLValueAny; +import com.casper.sdk.model.clvalue.CLValueBool; +import com.casper.sdk.model.clvalue.CLValueByteArray; +import com.casper.sdk.model.clvalue.CLValueFixedList; +import com.casper.sdk.model.clvalue.CLValueI32; +import com.casper.sdk.model.clvalue.CLValueI64; +import com.casper.sdk.model.clvalue.CLValueKey; +import com.casper.sdk.model.clvalue.CLValueList; +import com.casper.sdk.model.clvalue.CLValueMap; +import com.casper.sdk.model.clvalue.CLValueOption; +import com.casper.sdk.model.clvalue.CLValuePublicKey; +import com.casper.sdk.model.clvalue.CLValueResult; +import com.casper.sdk.model.clvalue.CLValueString; +import com.casper.sdk.model.clvalue.CLValueTuple1; +import com.casper.sdk.model.clvalue.CLValueTuple2; +import com.casper.sdk.model.clvalue.CLValueTuple3; +import com.casper.sdk.model.clvalue.CLValueU128; +import com.casper.sdk.model.clvalue.CLValueU256; +import com.casper.sdk.model.clvalue.CLValueU32; +import com.casper.sdk.model.clvalue.CLValueU512; +import com.casper.sdk.model.clvalue.CLValueU64; +import com.casper.sdk.model.clvalue.CLValueU8; +import com.casper.sdk.model.clvalue.CLValueURef; +import com.casper.sdk.model.clvalue.CLValueUnit; import com.casper.sdk.model.contract.Contract; import com.casper.sdk.model.key.AlgorithmTag; import com.casper.sdk.model.key.Key; @@ -28,9 +52,14 @@ import java.io.IOException; import java.math.BigInteger; import java.nio.BufferUnderflowException; -import java.util.*; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link StoredValueData} @@ -572,7 +601,7 @@ void validate_CLValueMap_Mapping_with_string_tuple1_i32() throws IOException, StoredValueData sv = OBJECT_MAPPER.readValue(inputJson, StoredValueData.class); // Should be CLValueMap assertTrue(sv.getStoredValue().getValue() instanceof CLValueMap); - Map map = new HashMap<>(); + Map map = new LinkedHashMap<>(); map.put(new CLValueString("ABC"), new CLValueTuple1(new Unit<>(new CLValueI32(10)))); CLValueMap expectedClValue = new CLValueMap(map); @@ -600,8 +629,8 @@ void validate_CLValueMap_Mapping_with_Map_i32_Any() throws IOException, // Should be CLValueMap assertTrue(sv.getStoredValue().getValue() instanceof CLValueMap); - Map map = new HashMap<>(); - Map childMap = new HashMap<>(); + Map map = new LinkedHashMap<>(); + Map childMap = new LinkedHashMap<>(); childMap.put(new CLValueI32(1), new CLValueAny(DummyClass.builder().name("One").value(1).build())); childMap.put(new CLValueI32(2), new CLValueAny(DummyClass.builder().name("Two").value(2).build())); map.put(new CLValueU64(BigInteger.ONE), new CLValueMap(childMap)); From 9a47cb436f46672c8a131c132cbde6ce70217942 Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Thu, 6 Oct 2022 19:41:16 -0300 Subject: [PATCH 25/35] Improved deserialization exception handling --- .../sdk/model/clvalue/AbstractCLValue.java | 58 +++++++++-------- .../casper/sdk/model/clvalue/CLValueAny.java | 12 ++-- .../casper/sdk/model/clvalue/CLValueBool.java | 14 ++--- .../sdk/model/clvalue/CLValueByteArray.java | 9 +-- .../sdk/model/clvalue/CLValueFixedList.java | 45 ++++++-------- .../casper/sdk/model/clvalue/CLValueI32.java | 15 +++-- .../casper/sdk/model/clvalue/CLValueI64.java | 9 +-- .../casper/sdk/model/clvalue/CLValueKey.java | 10 +-- .../casper/sdk/model/clvalue/CLValueList.java | 40 +++++------- .../casper/sdk/model/clvalue/CLValueMap.java | 62 +++++++++---------- .../sdk/model/clvalue/CLValueOption.java | 32 ++++------ .../sdk/model/clvalue/CLValuePublicKey.java | 11 +--- .../sdk/model/clvalue/CLValueResult.java | 61 +++++++++--------- .../sdk/model/clvalue/CLValueString.java | 9 +-- .../sdk/model/clvalue/CLValueTuple1.java | 24 +++---- .../sdk/model/clvalue/CLValueTuple2.java | 38 +++++------- .../sdk/model/clvalue/CLValueTuple3.java | 58 ++++++++--------- .../casper/sdk/model/clvalue/CLValueU128.java | 9 +-- .../casper/sdk/model/clvalue/CLValueU256.java | 9 +-- .../casper/sdk/model/clvalue/CLValueU32.java | 9 +-- .../casper/sdk/model/clvalue/CLValueU512.java | 15 +++-- .../casper/sdk/model/clvalue/CLValueU64.java | 15 +++-- .../casper/sdk/model/clvalue/CLValueU8.java | 9 +-- .../casper/sdk/model/clvalue/CLValueURef.java | 24 +++---- .../casper/sdk/model/clvalue/CLValueUnit.java | 2 +- .../serde/SerializerDeserializerTests.java | 18 ++++-- 26 files changed, 267 insertions(+), 350 deletions(-) diff --git a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java index 6817486a7..51eaf05b7 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java +++ b/src/main/java/com/casper/sdk/model/clvalue/AbstractCLValue.java @@ -28,8 +28,6 @@ import lombok.Setter; import lombok.SneakyThrows; -import java.lang.reflect.InvocationTargetException; - /** * Base class for CLValues * @@ -61,14 +59,17 @@ public void setValue(T value) throws ValueSerializationException { this.serialize(new SerializerBuffer()); } - @SneakyThrows({ValueDeserializationException.class}) - @JsonSetter(value = "bytes") - @ExcludeFromJacocoGeneratedReport - protected void setJsonBytes(String bytes) { - this.bytes = bytes; - - DeserializerBuffer deser = new DeserializerBuffer(this.bytes); - this.deserialize(deser); + public static AbstractCLValue createInstanceFromBytes(DeserializerBuffer deser) throws ValueDeserializationException { + int length = deser.readI32(); + byte[] bytes = deser.readByteArray(length); + byte clType = deser.readU8(); + try { + AbstractCLValue clValue = CLTypeData.getTypeBySerializationTag(clType).getClazz().getDeclaredConstructor().newInstance(); + clValue.deserializeCustom(new DeserializerBuffer(Hex.encode(bytes))); + return clValue; + } catch (Exception e) { + throw new ValueDeserializationException("Error while instantiating CLValue", e); + } } @SneakyThrows({ValueSerializationException.class, NoSuchTypeException.class}) @@ -95,8 +96,19 @@ protected void serializePrefixWithLength(SerializerBuffer ser) throws ValueSeria ser.writeI32(size); } + @SneakyThrows({ValueDeserializationException.class}) + @JsonSetter(value = "bytes") + @ExcludeFromJacocoGeneratedReport + protected void setJsonBytes(String bytes) { + this.bytes = bytes; + + DeserializerBuffer deser = new DeserializerBuffer(this.bytes); + + this.deserialize(deser); + } + @Override - public AbstractCLValue deserialize(DeserializerBuffer deser, Target target) throws ValueDeserializationException, NoSuchTypeException { + public AbstractCLValue deserialize(DeserializerBuffer deser, Target target) throws ValueDeserializationException { if (target.equals(Target.BYTE)) { return AbstractCLValue.createInstanceFromBytes(deser); } else { @@ -105,25 +117,19 @@ protected void serializePrefixWithLength(SerializerBuffer ser) throws ValueSeria } } - public static AbstractCLValue createInstanceFromBytes(DeserializerBuffer deser) throws ValueDeserializationException, NoSuchTypeException { - int length = deser.readI32(); - byte[] bytes = deser.readByteArray(length); - byte clType = deser.readU8(); - try { - AbstractCLValue clValue = CLTypeData.getTypeBySerializationTag(clType).getClazz().getDeclaredConstructor().newInstance(); - clValue.deserialize(new DeserializerBuffer(Hex.encode(bytes))); - return clValue; - } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | - InvocationTargetException e) { - throw new ValueDeserializationException("Error while instantiating CLValue", e); - } - } - @Override public abstract void serialize(SerializerBuffer ser, Target target) throws ValueSerializationException, NoSuchTypeException; + public abstract void deserializeCustom(DeserializerBuffer deserializerBuffer) throws Exception; + @Override - public abstract void deserialize(DeserializerBuffer deserializerBuffer) throws ValueDeserializationException; + public void deserialize(DeserializerBuffer deserializerBuffer) throws ValueDeserializationException { + try { + this.deserializeCustom(deserializerBuffer); + } catch (Exception e) { + throw new ValueDeserializationException("Error serializing value", e); + } + } protected void encodeType(SerializerBuffer ser) throws NoSuchTypeException { byte val = (getClType().getClTypeData().getSerializationTag()); diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java index a094da83b..ed1d20549 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java @@ -8,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -16,7 +15,11 @@ import lombok.Setter; import org.bouncycastle.util.encoders.Hex; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; /** * Casper Object CLValue implementation @@ -75,13 +78,12 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { + public void deserializeCustom(DeserializerBuffer deser) + throws Exception { int objectByteArrayLength = deser.readI32(); try (ByteArrayInputStream bis = new ByteArrayInputStream(deser.readByteArray(objectByteArrayLength)); ObjectInputStream ois = new ObjectInputStream(bis)) { this.setValue(ois.readObject()); - } catch (IOException | ClassNotFoundException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); } } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java index a32566aa1..f0a0ad662 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueBool.java @@ -8,9 +8,11 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.*; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.bouncycastle.util.encoders.Hex; import org.jetbrains.annotations.NotNull; @@ -63,11 +65,7 @@ public void serialize(@NotNull SerializerBuffer ser, Target target) throws NoSuc } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readBool()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException("Error serializing value", e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readBool()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java index a27627b99..0a71164e5 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueByteArray.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.Getter; import lombok.NoArgsConstructor; @@ -55,12 +54,8 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readByteArray(this.getClType().getLength())); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readByteArray(this.getClType().getLength())); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java index 693ac2bc9..a11d03bce 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueFixedList.java @@ -1,6 +1,5 @@ package com.casper.sdk.model.clvalue; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; @@ -63,34 +62,30 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - CLTypeData childrenType = getClType().getListType().getClTypeData(); + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + CLTypeData childrenType = getClType().getListType().getClTypeData(); - List> list = new LinkedList<>(); + List> list = new LinkedList<>(); - boolean hasMoreItems = true; - do { - AbstractCLValue child = CLTypeData.createCLValueFromCLTypeData(childrenType); - if (child.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getListType()).getChildTypes()); + boolean hasMoreItems = true; + do { + AbstractCLValue child = CLTypeData.createCLValueFromCLTypeData(childrenType); + if (child.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getListType()).getChildTypes()); + } + try { + child.deserializeCustom(deser); + list.add(child); + } catch (ValueDeserializationException valueDeserializationException) { + hasMoreItems = false; + if (deser.getBuffer().hasRemaining()) { + throw valueDeserializationException; } - try { - child.deserialize(deser); - list.add(child); - } catch (ValueDeserializationException valueDeserializationException) { - hasMoreItems = false; - if (deser.getBuffer().hasRemaining()) { - throw valueDeserializationException; - } - } - } while (hasMoreItems); + } + } while (hasMoreItems); - setValue(list); - } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + setValue(list); } protected void setListType(List> value) { diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java index 0cc64939e..6378633bb 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueI32.java @@ -8,9 +8,12 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.bouncycastle.util.encoders.Hex; /** @@ -63,11 +66,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readI32()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readI32()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java index a850d3e9f..b8ef9a1e0 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueI64.java @@ -8,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -65,11 +64,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readI64()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readI64()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java index a956feee1..615699808 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueKey.java @@ -1,7 +1,6 @@ package com.casper.sdk.model.clvalue; import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; -import com.casper.sdk.exception.NoSuchKeyTagException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeKey; import com.casper.sdk.model.clvalue.serde.Target; @@ -10,7 +9,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import dev.oak3.sbs4j.util.ByteUtils; import lombok.EqualsAndHashCode; @@ -69,11 +67,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(Key.fromTaggedHexString(ByteUtils.encodeHexString(deser.readByteArray(33)))); - } catch (IllegalArgumentException | NoSuchKeyTagException | ValueSerializationException e) { - throw new ValueDeserializationException("Error decoding CLValuePublicKey", e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(Key.fromTaggedHexString(ByteUtils.encodeHexString(deser.readByteArray(33)))); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java index be1df69fd..0be322f3f 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueList.java @@ -1,6 +1,5 @@ package com.casper.sdk.model.clvalue; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; @@ -9,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -67,29 +65,25 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - CLTypeData childrenType = getClType().getListType().getClTypeData(); - - // List length is sent first - CLValueI32 length = new CLValueI32(); - length.deserialize(deser); - - List> list = new LinkedList<>(); - for (int i = 0; i < length.getValue(); i++) { - AbstractCLValue child = CLTypeData.createCLValueFromCLTypeData(childrenType); - if (child.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getListType()).getChildTypes()); - } - child.deserialize(deser); - list.add(child); + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + CLTypeData childrenType = getClType().getListType().getClTypeData(); + + // List length is sent first + CLValueI32 length = new CLValueI32(); + length.deserializeCustom(deser); + + List> list = new LinkedList<>(); + for (int i = 0; i < length.getValue(); i++) { + AbstractCLValue child = CLTypeData.createCLValueFromCLTypeData(childrenType); + if (child.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getListType()).getChildTypes()); } - - setValue(list); - } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + child.deserializeCustom(deser); + list.add(child); } + + setValue(list); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java index 2525d90df..bd271c464 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueMap.java @@ -1,6 +1,5 @@ package com.casper.sdk.model.clvalue; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; @@ -10,7 +9,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.Getter; import lombok.NoArgsConstructor; @@ -69,43 +67,39 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - CLTypeData keyType = clType.getKeyValueTypes().getKeyType().getClTypeData(); - CLTypeData valType = clType.getKeyValueTypes().getValueType().getClTypeData(); - - Map, AbstractCLValue> map = new LinkedHashMap<>(); - CLValueI32 mapLength = new CLValueI32(0); - mapLength.deserialize(deser); - - for (int i = 0; i < mapLength.getValue(); i++) { - AbstractCLValue key = CLTypeData.createCLValueFromCLTypeData(keyType); - if (key.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) key.getClType()) - .setChildTypes( - ((AbstractCLTypeWithChildren) clType.getKeyValueTypes().getKeyType()).getChildTypes()); - } - key.deserialize(deser); + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + CLTypeData keyType = clType.getKeyValueTypes().getKeyType().getClTypeData(); + CLTypeData valType = clType.getKeyValueTypes().getValueType().getClTypeData(); + + Map, AbstractCLValue> map = new LinkedHashMap<>(); + CLValueI32 mapLength = new CLValueI32(0); + mapLength.deserializeCustom(deser); + + for (int i = 0; i < mapLength.getValue(); i++) { + AbstractCLValue key = CLTypeData.createCLValueFromCLTypeData(keyType); + if (key.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) key.getClType()) + .setChildTypes( + ((AbstractCLTypeWithChildren) clType.getKeyValueTypes().getKeyType()).getChildTypes()); + } + key.deserializeCustom(deser); - AbstractCLValue val = CLTypeData.createCLValueFromCLTypeData(valType); + AbstractCLValue val = CLTypeData.createCLValueFromCLTypeData(valType); - if (val.getClType() instanceof CLTypeMap) { - ((CLTypeMap) val.getClType()) - .setKeyValueTypes(((CLTypeMap) clType.getKeyValueTypes().getValueType()).getKeyValueTypes()); - } else if (val.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) val.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getKeyValueTypes().getValueType()) - .getChildTypes()); - } - val.deserialize(deser); - - map.put(key, val); + if (val.getClType() instanceof CLTypeMap) { + ((CLTypeMap) val.getClType()) + .setKeyValueTypes(((CLTypeMap) clType.getKeyValueTypes().getValueType()).getKeyValueTypes()); + } else if (val.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) val.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getKeyValueTypes().getValueType()) + .getChildTypes()); } + val.deserializeCustom(deser); - setValue(map); - } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + map.put(key, val); } + + setValue(map); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java index 2a97bcbdb..d31d8bf95 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueOption.java @@ -1,6 +1,5 @@ package com.casper.sdk.model.clvalue; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; @@ -9,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -74,28 +72,24 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - CLValueBool isPresent = new CLValueBool(); - isPresent.deserialize(deser); + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + CLValueBool isPresent = new CLValueBool(); + isPresent.deserializeCustom(deser); - CLTypeData childTypeData = clType.getChildType().getClTypeData(); + CLTypeData childTypeData = clType.getChildType().getClTypeData(); - AbstractCLValue child = CLTypeData.createCLValueFromCLTypeData(childTypeData); + AbstractCLValue child = CLTypeData.createCLValueFromCLTypeData(childTypeData); - if (child.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildType()).getChildTypes()); - } - - if (isPresent.getValue().equals(Boolean.TRUE)) { - child.deserialize(deser); - } + if (child.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildType()).getChildTypes()); + } - setValue(Optional.of(child)); - } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + if (isPresent.getValue().equals(Boolean.TRUE)) { + child.deserializeCustom(deser); } + + setValue(Optional.of(child)); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java b/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java index b62612681..9c9055699 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValuePublicKey.java @@ -9,7 +9,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import dev.oak3.sbs4j.util.ByteUtils; import lombok.EqualsAndHashCode; @@ -18,8 +17,6 @@ import lombok.Setter; import org.bouncycastle.util.encoders.Hex; -import java.security.NoSuchAlgorithmException; - /** * Casper PublicKey CLValue implementation * @@ -70,11 +67,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(PublicKey.fromTaggedHexString(ByteUtils.encodeHexString(deser.readByteArray(33)))); - } catch (NoSuchAlgorithmException | IllegalArgumentException | ValueSerializationException e) { - throw new ValueDeserializationException("Error decoding CLValuePublicKey", e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(PublicKey.fromTaggedHexString(ByteUtils.encodeHexString(deser.readByteArray(33)))); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java index 0690b0930..28c6fd7d6 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueResult.java @@ -1,6 +1,5 @@ package com.casper.sdk.model.clvalue; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; @@ -9,9 +8,13 @@ import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.*; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.bouncycastle.util.encoders.Hex; /** @@ -82,35 +85,31 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - Result result = new Result(); - CLValueBool bool = new CLValueBool(); - bool.setValue(deser.readBool()); - CLTypeData typeOk = clType.getOkErrTypes().getOkClType().getClTypeData(); - AbstractCLValue clValueOk = CLTypeData.createCLValueFromCLTypeData(typeOk); - if (clValueOk.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) clValueOk.getClType()).getChildTypes() - .addAll(((AbstractCLTypeWithChildren) clType.getOkErrTypes().getOkClType()).getChildTypes()); - } - clValueOk.deserialize(deser); - result.setOk(clValueOk); - - bool = new CLValueBool(); - bool.deserialize(deser); - CLTypeData typeErr = clType.getOkErrTypes().getErrClType().getClTypeData(); - AbstractCLValue clValueErr = CLTypeData.createCLValueFromCLTypeData(typeErr); - if (clValueErr.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) clValueErr.getClType()).getChildTypes() - .addAll(((AbstractCLTypeWithChildren) clType.getOkErrTypes().getErrClType()).getChildTypes()); - } - clValueErr.deserialize(deser); - result.setErr(clValueErr); - - setValue(result); - } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + Result result = new Result(); + CLValueBool bool = new CLValueBool(); + bool.setValue(deser.readBool()); + CLTypeData typeOk = clType.getOkErrTypes().getOkClType().getClTypeData(); + AbstractCLValue clValueOk = CLTypeData.createCLValueFromCLTypeData(typeOk); + if (clValueOk.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) clValueOk.getClType()).getChildTypes() + .addAll(((AbstractCLTypeWithChildren) clType.getOkErrTypes().getOkClType()).getChildTypes()); } + clValueOk.deserializeCustom(deser); + result.setOk(clValueOk); + + bool = new CLValueBool(); + bool.deserializeCustom(deser); + CLTypeData typeErr = clType.getOkErrTypes().getErrClType().getClTypeData(); + AbstractCLValue clValueErr = CLTypeData.createCLValueFromCLTypeData(typeErr); + if (clValueErr.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) clValueErr.getClType()).getChildTypes() + .addAll(((AbstractCLTypeWithChildren) clType.getOkErrTypes().getErrClType()).getChildTypes()); + } + clValueErr.deserializeCustom(deser); + result.setErr(clValueErr); + + setValue(result); } protected void setChildTypes(AbstractCLValue ok, AbstractCLValue err) { diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java index 1e5f50af8..8ae56b8b5 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueString.java @@ -8,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -65,11 +64,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readString()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readString()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java index 6e84d5bb1..68ab7a974 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple1.java @@ -1,6 +1,5 @@ package com.casper.sdk.model.clvalue; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; @@ -9,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -60,21 +58,17 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - CLTypeData childTypeData1 = clType.getChildClTypeData(0); + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + CLTypeData childTypeData1 = clType.getChildClTypeData(0); - AbstractCLValue child1 = CLTypeData.createCLValueFromCLTypeData(childTypeData1); - if (child1.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child1.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(0)).getChildTypes()); - } - child1.deserialize(deser); - - setValue(new Unit<>(child1)); - } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + AbstractCLValue child1 = CLTypeData.createCLValueFromCLTypeData(childTypeData1); + if (child1.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child1.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(0)).getChildTypes()); } + child1.deserializeCustom(deser); + + setValue(new Unit<>(child1)); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java index fd155ca76..2fa748487 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple2.java @@ -1,6 +1,5 @@ package com.casper.sdk.model.clvalue; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; @@ -9,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -62,29 +60,25 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - CLTypeData childTypeData1 = clType.getChildClTypeData(0); - CLTypeData childTypeData2 = clType.getChildClTypeData(1); + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + CLTypeData childTypeData1 = clType.getChildClTypeData(0); + CLTypeData childTypeData2 = clType.getChildClTypeData(1); - AbstractCLValue child1 = CLTypeData.createCLValueFromCLTypeData(childTypeData1); - if (child1.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child1.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(0)).getChildTypes()); - } - child1.deserialize(deser); - - AbstractCLValue child2 = CLTypeData.createCLValueFromCLTypeData(childTypeData2); - if (child2.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child2.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(1)).getChildTypes()); - } - child2.deserialize(deser); + AbstractCLValue child1 = CLTypeData.createCLValueFromCLTypeData(childTypeData1); + if (child1.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child1.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(0)).getChildTypes()); + } + child1.deserializeCustom(deser); - setValue(new Pair<>(child1, child2)); - } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + AbstractCLValue child2 = CLTypeData.createCLValueFromCLTypeData(childTypeData2); + if (child2.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child2.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(1)).getChildTypes()); } + child2.deserializeCustom(deser); + + setValue(new Pair<>(child1, child2)); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java index 42ab49f88..18b5d23e5 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueTuple3.java @@ -1,6 +1,5 @@ package com.casper.sdk.model.clvalue; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.AbstractCLTypeWithChildren; import com.casper.sdk.model.clvalue.cltype.CLTypeData; @@ -9,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -64,37 +62,33 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - CLTypeData childTypeData1 = clType.getChildClTypeData(0); - CLTypeData childTypeData2 = clType.getChildClTypeData(1); - CLTypeData childTypeData3 = clType.getChildClTypeData(2); - - AbstractCLValue child1 = CLTypeData.createCLValueFromCLTypeData(childTypeData1); - if (child1.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child1.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(0)).getChildTypes()); - } - child1.deserialize(deser); - - AbstractCLValue child2 = CLTypeData.createCLValueFromCLTypeData(childTypeData2); - if (child2.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child2.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(1)).getChildTypes()); - } - child2.deserialize(deser); - - AbstractCLValue child3 = CLTypeData.createCLValueFromCLTypeData(childTypeData3); - if (child3.getClType() instanceof AbstractCLTypeWithChildren) { - ((AbstractCLTypeWithChildren) child3.getClType()) - .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(2)).getChildTypes()); - } - child3.deserialize(deser); - - setValue(new Triplet<>(child1, child2, child3)); - } catch (NoSuchTypeException | DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + CLTypeData childTypeData1 = clType.getChildClTypeData(0); + CLTypeData childTypeData2 = clType.getChildClTypeData(1); + CLTypeData childTypeData3 = clType.getChildClTypeData(2); + + AbstractCLValue child1 = CLTypeData.createCLValueFromCLTypeData(childTypeData1); + if (child1.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child1.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(0)).getChildTypes()); } + child1.deserializeCustom(deser); + + AbstractCLValue child2 = CLTypeData.createCLValueFromCLTypeData(childTypeData2); + if (child2.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child2.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(1)).getChildTypes()); + } + child2.deserializeCustom(deser); + + AbstractCLValue child3 = CLTypeData.createCLValueFromCLTypeData(childTypeData3); + if (child3.getClType() instanceof AbstractCLTypeWithChildren) { + ((AbstractCLTypeWithChildren) child3.getClType()) + .setChildTypes(((AbstractCLTypeWithChildren) clType.getChildTypes().get(2)).getChildTypes()); + } + child3.deserializeCustom(deser); + + setValue(new Triplet<>(child1, child2, child3)); } @Override diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java index 96d38bf82..f82bad8b6 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU128.java @@ -8,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -67,11 +66,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readU128()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readU128()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java index af158a303..034509e65 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU256.java @@ -8,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -67,11 +66,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readU256()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readU256()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java index 8f231dfaa..1b87828ee 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU32.java @@ -8,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -65,11 +64,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readU32()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readU32()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java index 99a100706..a63ade2fa 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU512.java @@ -8,9 +8,12 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.bouncycastle.util.encoders.Hex; import java.math.BigInteger; @@ -65,11 +68,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readU512()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readU512()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java index 747185418..63a81f3e1 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU64.java @@ -8,9 +8,12 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.bouncycastle.util.encoders.Hex; import java.math.BigInteger; @@ -65,11 +68,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readU64()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readU64()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java index d161bc9e0..186170d6b 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueU8.java @@ -8,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -65,11 +64,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - this.setValue(deser.readU8()); - } catch (ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + this.setValue(deser.readU8()); } } diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java index 88f425072..92607a0a9 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueURef.java @@ -1,7 +1,6 @@ package com.casper.sdk.model.clvalue; import com.casper.sdk.annotation.ExcludeFromJacocoGeneratedReport; -import com.casper.sdk.exception.DynamicInstanceException; import com.casper.sdk.exception.NoSuchTypeException; import com.casper.sdk.model.clvalue.cltype.CLTypeURef; import com.casper.sdk.model.clvalue.serde.Target; @@ -11,7 +10,6 @@ import com.fasterxml.jackson.annotation.JsonSetter; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; -import dev.oak3.sbs4j.exception.ValueDeserializationException; import dev.oak3.sbs4j.exception.ValueSerializationException; import lombok.Getter; import lombok.NoArgsConstructor; @@ -77,19 +75,15 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) throws ValueDeserializationException { - try { - URef uref = new URef(); - CLValueByteArray clValueByteArray = new CLValueByteArray(new byte[32]); - clValueByteArray.deserialize(deser); - uref.setAddress(clValueByteArray.getValue()); - CLValueU8 serializationTag = new CLValueU8((byte) 0); - serializationTag.deserialize(deser); - uref.setAccessRight(URefAccessRight.getTypeBySerializationTag(serializationTag.getValue())); - setValue(uref); - } catch (DynamicInstanceException | ValueSerializationException e) { - throw new ValueDeserializationException(String.format("Error deserializing %s", this.getClass().getSimpleName()), e); - } + public void deserializeCustom(DeserializerBuffer deser) throws Exception { + URef uref = new URef(); + CLValueByteArray clValueByteArray = new CLValueByteArray(new byte[32]); + clValueByteArray.deserializeCustom(deser); + uref.setAddress(clValueByteArray.getValue()); + CLValueU8 serializationTag = new CLValueU8((byte) 0); + serializationTag.deserializeCustom(deser); + uref.setAccessRight(URefAccessRight.getTypeBySerializationTag(serializationTag.getValue())); + setValue(uref); } @ExcludeFromJacocoGeneratedReport diff --git a/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java b/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java index 299cca2a3..3c44be5bb 100644 --- a/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java +++ b/src/main/java/com/casper/sdk/model/clvalue/CLValueUnit.java @@ -67,7 +67,7 @@ public void serialize(SerializerBuffer ser, Target target) throws NoSuchTypeExce } @Override - public void deserialize(DeserializerBuffer deser) { + public void deserializeCustom(DeserializerBuffer deser) throws Exception { setBytes(UNITY_EMPTY_VALUE); } } \ No newline at end of file diff --git a/src/test/java/com/casper/sdk/model/clvalue/serde/SerializerDeserializerTests.java b/src/test/java/com/casper/sdk/model/clvalue/serde/SerializerDeserializerTests.java index 949296b47..81568e6aa 100644 --- a/src/test/java/com/casper/sdk/model/clvalue/serde/SerializerDeserializerTests.java +++ b/src/test/java/com/casper/sdk/model/clvalue/serde/SerializerDeserializerTests.java @@ -1,7 +1,16 @@ package com.casper.sdk.model.clvalue.serde; import com.casper.sdk.exception.NoSuchTypeException; -import com.casper.sdk.model.clvalue.*; +import com.casper.sdk.model.clvalue.CLValueBool; +import com.casper.sdk.model.clvalue.CLValueI32; +import com.casper.sdk.model.clvalue.CLValueI64; +import com.casper.sdk.model.clvalue.CLValueString; +import com.casper.sdk.model.clvalue.CLValueU128; +import com.casper.sdk.model.clvalue.CLValueU256; +import com.casper.sdk.model.clvalue.CLValueU32; +import com.casper.sdk.model.clvalue.CLValueU512; +import com.casper.sdk.model.clvalue.CLValueU64; +import com.casper.sdk.model.clvalue.CLValueU8; import com.casper.sdk.model.clvalue.cltype.AbstractCLType; import dev.oak3.sbs4j.DeserializerBuffer; import dev.oak3.sbs4j.SerializerBuffer; @@ -17,7 +26,9 @@ import java.util.Arrays; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Unit tests for {@link SerializerBuffer} and {@link DeserializerBuffer} @@ -74,7 +85,7 @@ private static class TestData { new TestData<>(AbstractCLType.U512, SerializerBuffer.MAX_U512.add(SerializerBuffer.ONE), null, null, Target.JSON)); @Test - void validateDeserialize_with_SampleData() throws ValueDeserializationException, NoSuchTypeException { + void validateDeserialize_with_SampleData() throws ValueDeserializationException { for (TestData testData : successTestDataList) { DeserializerBuffer deser = new DeserializerBuffer(testData.getHexEncodedValue()); switch (testData.getName()) { @@ -273,7 +284,6 @@ void dataOutOfBounds_should_throw_ValueSerializationException() { @Test void dataWithWrongInputLength_should_throw_IllegalArgumentException_or_ValueDeserializationException() { - assertThrows(IllegalArgumentException.class, () -> new DeserializerBuffer("0")); final DeserializerBuffer deser2 = new DeserializerBuffer("01"); From 0fd0369a8c52609ffb367eef0a5bfc5502aa19fe Mon Sep 17 00:00:00 2001 From: Alexandre C Date: Fri, 14 Oct 2022 09:36:45 -0300 Subject: [PATCH 26/35] Fixes to get the test working --- .../model/event/deployprocessed/DeployProcessed.java | 11 ++++++++--- .../sdk/service/impl/event/EventBuilderTest.java | 10 ++++++---- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/casper/sdk/model/event/deployprocessed/DeployProcessed.java b/src/main/java/com/casper/sdk/model/event/deployprocessed/DeployProcessed.java index dbfafe818..048de74d9 100644 --- a/src/main/java/com/casper/sdk/model/event/deployprocessed/DeployProcessed.java +++ b/src/main/java/com/casper/sdk/model/event/deployprocessed/DeployProcessed.java @@ -1,10 +1,15 @@ package com.casper.sdk.model.event.deployprocessed; +import com.casper.sdk.model.common.Digest; import com.casper.sdk.model.deploy.executionresult.ExecutionResult; import com.casper.sdk.model.event.EventData; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import java.util.List; @@ -22,10 +27,10 @@ public class DeployProcessed implements EventData { @JsonProperty("deploy_hash") - private String deployHash; + private Digest deployHash; @JsonProperty("account") - private String account; + private Digest account; @JsonProperty("timestamp") private String timestamp; // TODO convert to data diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java index 31054c6f0..279a51a37 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -15,7 +15,6 @@ import com.casper.sdk.model.event.step.Step; import com.casper.sdk.model.event.version.ApiVersion; import com.casper.sdk.model.key.PublicKey; - import org.joda.time.DateTime; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -153,15 +152,18 @@ void buildDeployAcceptedEvent() throws IOException { } @Test - @Disabled void buildDeployProcessedEvent() throws IOException { final PojoEvent deployProcessedEvent = getEvent(EventType.MAIN, EventTarget.POJO, DEPLOY_PROCESSED_EVENT); assertThat(deployProcessedEvent, is(notNullValue())); - assertThat(deployProcessedEvent.getData(), is(instanceOf(DeployAccepted.class))); + // TODO: Shouldn't this be a DeployProcessed? + //assertThat(deployProcessedEvent.getData(), is(instanceOf(DeployAccepted.class))); + assertThat(deployProcessedEvent.getData(), is(instanceOf(DeployProcessed.class))); final DeployProcessed deployProcessed = deployProcessedEvent.getData(); - assertThat(deployProcessed.getBlockHash(), is(new Digest("fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087"))); + // TODO: Shouldn't this be getDeployHash? + //assertThat(deployProcessed.getBlockHash(), is(new Digest("fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087"))); + assertThat(deployProcessed.getDeployHash(), is(new Digest("fb81219f33aa58a2c2f50f7eea20c3065963f61bc3c74810729f10dc21981087"))); assertThat(deployProcessed.getAccount(), is(new Digest("01959d01aa68197e8cb91aa06bcc920f8d4a245dff60ea726bb89255349107a565"))); // TODO rest of fields From b33deddd193974fd9c8c07cc78d238db960e004e Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Mon, 31 Oct 2022 16:12:59 +0000 Subject: [PATCH 27/35] issues/120 - Fix erroneous timeout settings in EventServiceImpl.java --- build.gradle | 2 +- .../com/casper/sdk/service/impl/event/EventServiceImpl.java | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index 44328f030..8f14884a2 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,7 @@ plugins { apply plugin: 'java' group = 'network.casper' -version='0.5.2-SNAPSHOT' +version='0.5.4-SNAPSHOT' sourceCompatibility = 1.8 targetCompatibility = 1.8 diff --git a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java index 806c703fa..2d4b72d5b 100644 --- a/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java +++ b/src/main/java/com/casper/sdk/service/impl/event/EventServiceImpl.java @@ -50,8 +50,9 @@ private EventServiceImpl(final URI uri) { this.uri = uri; this.client = new OkHttpClient.Builder() - .connectTimeout(Duration.ofDays(1)) - .readTimeout(Duration.ofDays(1)) + .connectTimeout(Duration.ofSeconds(10)) + // The node issues an empty event every 10 seconds if no new events so give 30 seconds for read + .readTimeout(Duration.ofSeconds(30)) .build(); } From 5ae059af312fad695af5dad7bc7e6e6e0c12f1a2 Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Tue, 15 Nov 2022 11:10:50 +0000 Subject: [PATCH 28/35] issues/149 - apply patch from cnorburn for changes needed by Event Store --- build.gradle | 2 +- .../java/com/casper/sdk/model/deploy/UnbondingPurse.java | 5 ++++- src/main/java/com/casper/sdk/model/uref/URef.java | 2 +- .../com/casper/sdk/service/impl/event/EventBuilderTest.java | 1 - 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 8f14884a2..77d7e3d8b 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,7 @@ plugins { apply plugin: 'java' group = 'network.casper' -version='0.5.4-SNAPSHOT' +version='0.5.5-SNAPSHOT' sourceCompatibility = 1.8 targetCompatibility = 1.8 diff --git a/src/main/java/com/casper/sdk/model/deploy/UnbondingPurse.java b/src/main/java/com/casper/sdk/model/deploy/UnbondingPurse.java index 9274a5238..d6197726b 100644 --- a/src/main/java/com/casper/sdk/model/deploy/UnbondingPurse.java +++ b/src/main/java/com/casper/sdk/model/deploy/UnbondingPurse.java @@ -30,9 +30,12 @@ public class UnbondingPurse { /** * Unbonding amount */ - @JsonIgnore + @JsonProperty("amount") private BigInteger unbondingAmount; + @JsonIgnore + private BigInteger amount; + /** * the bondingPurse's {@link URef} */ diff --git a/src/main/java/com/casper/sdk/model/uref/URef.java b/src/main/java/com/casper/sdk/model/uref/URef.java index 99d86a39f..2d7e160db 100644 --- a/src/main/java/com/casper/sdk/model/uref/URef.java +++ b/src/main/java/com/casper/sdk/model/uref/URef.java @@ -59,7 +59,7 @@ public void createURef(String uref) throws IOException, DynamicInstanceException @JsonValue @ExcludeFromJacocoGeneratedReport - protected String getJsonURef() { + public String getJsonURef() { return "uref-" + ByteUtils.encodeHexString(this.address) + "-0" + ByteUtils.encodeHexString(new byte[]{this.accessRight.serializationTag}); } diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java index 279a51a37..b9634877e 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -194,7 +194,6 @@ void buildFaultEvent() throws IOException, NoSuchAlgorithmException { } @Test - @Disabled void buildStepEvent() throws IOException { final PojoEvent stepEvent = getEvent(EventType.MAIN, EventTarget.POJO, STEP_EVENT); From eee3257d0c011a88ea41e35fe21b631c1a808839 Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Wed, 23 Nov 2022 10:00:40 +0100 Subject: [PATCH 29/35] issues/15q - Apply patch from cnorburn --- .../java/com/casper/sdk/model/common/Digest.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main/java/com/casper/sdk/model/common/Digest.java b/src/main/java/com/casper/sdk/model/common/Digest.java index 86ae77c53..fe3463721 100644 --- a/src/main/java/com/casper/sdk/model/common/Digest.java +++ b/src/main/java/com/casper/sdk/model/common/Digest.java @@ -2,6 +2,7 @@ import com.casper.sdk.model.clvalue.serde.CasperSerializableObject; import com.casper.sdk.model.clvalue.serde.Target; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonValue; import dev.oak3.sbs4j.SerializerBuffer; import lombok.AllArgsConstructor; @@ -10,6 +11,8 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + +import org.bouncycastle.util.encoders.DecoderException; import org.bouncycastle.util.encoders.Hex; /** @@ -55,4 +58,14 @@ public void serialize(SerializerBuffer ser, Target target) { public String toString() { return digest; } + + @JsonIgnore + public boolean isValid(){ + try { + Hex.decode(this.digest); + return true; + } catch (DecoderException e){ + return false; + } + } } \ No newline at end of file From 70fa38984414936e29d3750e8502abfb989814c0 Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Wed, 23 Nov 2022 10:10:35 +0100 Subject: [PATCH 30/35] issues/151 - apply patch from cnorburn for digest validation needed by Event Store --- .../com/casper/sdk/model/common/Digest.java | 2 +- .../casper/sdk/model/common/DigestTest.java | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/casper/sdk/model/common/DigestTest.java diff --git a/src/main/java/com/casper/sdk/model/common/Digest.java b/src/main/java/com/casper/sdk/model/common/Digest.java index fe3463721..6d1516338 100644 --- a/src/main/java/com/casper/sdk/model/common/Digest.java +++ b/src/main/java/com/casper/sdk/model/common/Digest.java @@ -68,4 +68,4 @@ public boolean isValid(){ return false; } } -} \ No newline at end of file +} diff --git a/src/test/java/com/casper/sdk/model/common/DigestTest.java b/src/test/java/com/casper/sdk/model/common/DigestTest.java new file mode 100644 index 000000000..73403bab0 --- /dev/null +++ b/src/test/java/com/casper/sdk/model/common/DigestTest.java @@ -0,0 +1,18 @@ +package com.casper.sdk.model.common; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class DigestTest { + + @Test + void testDigestIsValid(){ + assertTrue(new Digest("99483863a391510b8d3447dd5cfc446b42d65e598672d569abc4cdded85b81e6").isValid()); + } + + @Test + void testDigestIsInValid(){ + assertFalse(new Digest("9483863a391510b8d3447dd5cfc446b42d65e598672d569abc4cdded85b81e6").isValid()); + assertFalse(new Digest("uref-99483863a391510b8d3447dd5cfc446b42d65e598672d569abc4cdded85b81e6").isValid()); + } +} From fda1b6183994889e21e383684eb4d997e77b1d36 Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Wed, 23 Nov 2022 09:14:11 +0000 Subject: [PATCH 31/35] Fixed typo --- src/test/java/com/casper/sdk/model/common/DigestTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/casper/sdk/model/common/DigestTest.java b/src/test/java/com/casper/sdk/model/common/DigestTest.java index 73403bab0..2d7ded3a1 100644 --- a/src/test/java/com/casper/sdk/model/common/DigestTest.java +++ b/src/test/java/com/casper/sdk/model/common/DigestTest.java @@ -11,7 +11,7 @@ void testDigestIsValid(){ } @Test - void testDigestIsInValid(){ + void testDigestIsinValid(){ assertFalse(new Digest("9483863a391510b8d3447dd5cfc446b42d65e598672d569abc4cdded85b81e6").isValid()); assertFalse(new Digest("uref-99483863a391510b8d3447dd5cfc446b42d65e598672d569abc4cdded85b81e6").isValid()); } From c3ea1adf4dd9562636c89a5228b19f757351d056 Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Wed, 23 Nov 2022 09:14:34 +0000 Subject: [PATCH 32/35] Fix typo 2nd attempt --- src/test/java/com/casper/sdk/model/common/DigestTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/casper/sdk/model/common/DigestTest.java b/src/test/java/com/casper/sdk/model/common/DigestTest.java index 2d7ded3a1..f95a7147c 100644 --- a/src/test/java/com/casper/sdk/model/common/DigestTest.java +++ b/src/test/java/com/casper/sdk/model/common/DigestTest.java @@ -11,7 +11,7 @@ void testDigestIsValid(){ } @Test - void testDigestIsinValid(){ + void testDigestIsInvalid(){ assertFalse(new Digest("9483863a391510b8d3447dd5cfc446b42d65e598672d569abc4cdded85b81e6").isValid()); assertFalse(new Digest("uref-99483863a391510b8d3447dd5cfc446b42d65e598672d569abc4cdded85b81e6").isValid()); } From 827df24476b754d9f8c595835ab08021381bbcf3 Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Wed, 23 Nov 2022 10:30:17 +0100 Subject: [PATCH 33/35] Disable failing test until CL Type ANY is supported --- .../java/com/casper/sdk/service/impl/event/EventBuilderTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java index b9634877e..279a51a37 100644 --- a/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java +++ b/src/test/java/com/casper/sdk/service/impl/event/EventBuilderTest.java @@ -194,6 +194,7 @@ void buildFaultEvent() throws IOException, NoSuchAlgorithmException { } @Test + @Disabled void buildStepEvent() throws IOException { final PojoEvent stepEvent = getEvent(EventType.MAIN, EventTarget.POJO, STEP_EVENT); From a1920672e2991b0f8d0e866a99df2ab7ee5275f5 Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Wed, 23 Nov 2022 10:53:08 +0100 Subject: [PATCH 34/35] Added clean to gradle build --- .github/workflows/gradle.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 2d2c0329f..c724eac46 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -26,7 +26,7 @@ jobs: run: chmod +x gradlew - name: Build with Gradle - run: ./gradlew build + run: ./gradlew clean build publish-docs-reports: needs: build @@ -49,7 +49,7 @@ jobs: run: echo "PROJECT_VERSION=$(./gradlew properties -q | grep "version:" | awk '{print $2}')" >> $GITHUB_ENV - name: Generate Javadoc - run: ./gradlew javadoc + run: ./gradlew clean javadoc - name: Run tests and generate reports run: ./gradlew test From 5534e20cb4f7b797c6bb0c85667af1b31947171c Mon Sep 17 00:00:00 2001 From: meywood <105049338+meywood@users.noreply.github.com> Date: Wed, 23 Nov 2022 11:11:52 +0100 Subject: [PATCH 35/35] Updated build to 2.0.0 --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 77d7e3d8b..44e243ce2 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,7 @@ plugins { apply plugin: 'java' group = 'network.casper' -version='0.5.5-SNAPSHOT' +version='2.0.0' sourceCompatibility = 1.8 targetCompatibility = 1.8 @@ -55,7 +55,7 @@ java { task casperJar(type: Jar) { archiveBaseName = 'casper-java-sdk' - archiveVersion = "0.5.2-SNAPSHOT" + archiveVersion = "${version}" from { configurations.compileClasspath.findAll { it.isDirectory() ? it : zipTree(it) } } with jar }