Skip to content

Commit

Permalink
Merge pull request #165 from casper-network/dev
Browse files Browse the repository at this point in the history
merge dev into main ready for release
  • Loading branch information
meywood authored Feb 15, 2023
2 parents b7baad6 + bb49b72 commit 98db079
Show file tree
Hide file tree
Showing 11 changed files with 153 additions and 125 deletions.
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,53 @@ Deploy deploy = CasperDeployService.buildTransferDeploy(from, to,

DeployResult deployResult = casperServiceTestnet.putDeploy(deploy);
```

### 12. Consuming Events

The Java SDK supports the consumption of casper events using the event service API. This API allows the consumer to
choose the events to be provided as Pojos or as raw JSON via the EventTarget enum values. Each event stream is consumed
individually by providing the required stream (main, sigs, and deploys) using the EventType parameter to the consumeEvents method.

For more information on events see: [Monitoring and Consuming Events](https://docs.casperlabs.io/dapp-dev-guide/building-dapps/monitoring-events/).

#### Consuming Raw JSON Event Strings
```Java
// Construct an events service
final EventService eventService = EventService.usingPeer(new URI("http://localhost:28101"));

// Consume the main events as raw JSON
eventService.consumeEvents(EventType.MAIN, EventTarget.RAW, 0L, new EventConsumer<String>(){

@Override
public void accept(final Event<String> event) {
// Obtain the raw JSON event as a String
final String json = event.getData();
// Obtain the optional event ID
final long id = event.getId().orElse(0L);
}
});
```

#### Consuming Pojo Events

```Java
// Construct an events service
final EventService eventService = EventService.usingPeer(new URI("http://localhost:28101"));

// Consume the main events as Casper Java SDK Pojos
eventService.consumeEvents(EventType.MAIN, EventTarget.POJO, 0L, new EventConsumer<EventData>() {

@Override
public void accept(final Event<EventData> event) {

switch (event.getDataType()) {

case BLOCK_ADDED:
handleBlockAdded(event.getId().get(), ((BlockAdded) event.getData()));
break;

// And so on...
}
}
});
```
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ plugins {
apply plugin: 'java'

group = 'network.casper'
version='2.0.0'
version='2.1.0'
sourceCompatibility = 1.8
targetCompatibility = 1.8

Expand Down
7 changes: 5 additions & 2 deletions src/main/java/com/casper/sdk/helper/CasperTransferHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,11 @@ public static Deploy buildTransferDeploy(AbstractPrivateKey signer, PublicKey to
NamedArg<CLTypePublicKey> publicKeyNamedArg = new NamedArg<>("target",
new CLValuePublicKey(to));
transferArgs.add(publicKeyNamedArg);
CLValueOption idArg = new CLValueOption(Optional.of(
new CLValueU64(BigInteger.valueOf(id))));

CLValueOption idArg = (id == null) ?
new CLValueOption(Optional.of(new CLValueU64())) :
new CLValueOption(Optional.of(new CLValueU64(BigInteger.valueOf(id))));

NamedArg<CLTypeOption> idNamedArg = new NamedArg<>("id", idArg);
transferArgs.add(idNamedArg);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public abstract class AbstractCLValue<T, P extends AbstractCLType>
@Setter
@JsonProperty("parsed")
@JsonInclude(Include.NON_NULL)
private String parsed;
private Object parsed;

@JsonIgnore
private T value;
Expand Down
79 changes: 46 additions & 33 deletions src/main/java/com/casper/sdk/model/clvalue/CLValueAny.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,13 @@
import dev.oak3.sbs4j.DeserializerBuffer;
import dev.oak3.sbs4j.SerializerBuffer;
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.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Objects;

/**
* Casper Object CLValue implementation
Expand All @@ -32,8 +28,8 @@
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class CLValueAny extends AbstractCLValue<Object, CLTypeAny> {
//@EqualsAndHashCode(callSuper = true)
public class CLValueAny extends AbstractCLValue<byte[], CLTypeAny> {
private CLTypeAny clType = new CLTypeAny();

@JsonSetter("cl_type")
Expand All @@ -48,42 +44,59 @@ protected String getJsonClType() {
return this.getClType().getTypeName();
}

public CLValueAny(Object value) throws ValueSerializationException {
public CLValueAny(byte[] value) throws ValueSerializationException {
this.setValue(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);
ser.writeByteArray(objectByteArray);

if (target.equals(Target.BYTE)) {
this.encodeType(ser);
}
} catch (IOException e) {
throw new ValueSerializationException(String.format("Error serializing %s", this.getClass().getSimpleName()), e);
}

ser.writeByteArray(this.getValue());
this.setBytes(Hex.toHexString(ser.toByteArray()));
}

@Override
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());
}
this.setValue(deser.readByteArray(deser.getBuffer().remaining()));
}

@Override
@ExcludeFromJacocoGeneratedReport
public boolean equals(final Object o) {
if (o == this)
return true;
if (!(o instanceof CLValueAny))
return false;
final CLValueAny other = (CLValueAny) o;
if (!other.canEqual(this))
return false;
final Object thisBytes = this.getBytes();
final Object otherBytes = other.getBytes();
if (!Objects.equals(thisBytes, otherBytes))
return false;
final byte[] thisValue = this.getValue();
final byte[] otherValue = other.getValue();
if (thisValue == null ? otherValue != null : !Arrays.equals(thisValue, otherValue))
return false;
final Object thisClType = this.getClType();
final Object otherClType = other.getClType();
return Objects.equals(thisClType, otherClType);
}

@ExcludeFromJacocoGeneratedReport
@Override
protected boolean canEqual(final Object other) {
return other instanceof CLValueAny;
}

@Override
@ExcludeFromJacocoGeneratedReport
public int hashCode() {
final int PRIME = 59;
int result = super.hashCode();
final Object thisClType = this.getClType();
result = result * PRIME + (thisClType == null ? 43 : thisClType.hashCode());
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public void serialize(SerializerBuffer ser, Target target) throws ValueSerializa

if (target.equals(Target.BYTE)) {
this.encodeType(ser);
if (child.isPresent() && isPresent.getValue().equals(Boolean.TRUE)) {
if (child.isPresent()) {
child.get().encodeType(ser);
}
}
Expand Down
38 changes: 36 additions & 2 deletions src/test/java/com/casper/sdk/helper/CasperTransferHelperTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import com.syntifi.crypto.key.Ed25519PrivateKey;
import dev.oak3.sbs4j.exception.ValueSerializationException;
import org.bouncycastle.util.encoders.Hex;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -24,6 +23,8 @@
import java.util.Objects;
import java.util.Random;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
* Casper Deploy Service test
*
Expand Down Expand Up @@ -74,6 +75,39 @@ void testTransferOnTestnet() throws IOException, NoSuchTypeException, GeneralSec
id, BigInteger.valueOf(100000000L), 1L, ttl, new Date(),
new ArrayList<>());
DeployResult deployResult = casperServiceTestnet.putDeploy(deploy);
Assertions.assertEquals(deployResult.getDeployHash(), Hex.toHexString(deploy.getHash().getDigest()));
assertEquals(deployResult.getDeployHash(), Hex.toHexString(deploy.getHash().getDigest()));
}

@Test
void testTransferWithNullIdOnTestnet() throws IOException, NoSuchTypeException, GeneralSecurityException, URISyntaxException, ValueSerializationException {
Ed25519PrivateKey alice = new Ed25519PrivateKey();
Ed25519PrivateKey bob = new Ed25519PrivateKey();
alice.readPrivateKey(getResourcesKeyPath("deploy-accounts/Alice_SyntiFi_secret_key.pem"));
bob.readPrivateKey(getResourcesKeyPath("deploy-accounts/Bob_SyntiFi_secret_key.pem"));

Long id = null;
Ttl ttl = Ttl
.builder()
.ttl("30m")
.build();
Random rnd = new Random();
boolean coin = rnd.nextBoolean();
Ed25519PrivateKey from;
PublicKey to;
if (coin) {
from = alice;
to = PublicKey.fromAbstractPublicKey(bob.derivePublicKey());
} else {
from = bob;
to = PublicKey.fromAbstractPublicKey(alice.derivePublicKey());
}

Deploy deploy = CasperTransferHelper.buildTransferDeploy(from, to,
BigInteger.valueOf(2500000000L), "casper-test",
id, BigInteger.valueOf(100000000L), 1L, ttl, new Date(),
new ArrayList<>());
DeployResult deployResult = casperServiceTestnet.putDeploy(deploy);
LOGGER.debug("deploy hash: " + deployResult.getDeployHash());
assertEquals(deployResult.getDeployHash(), Hex.toHexString(deploy.getHash().getDigest()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -39,11 +15,11 @@
import dev.oak3.sbs4j.SerializerBuffer;
import dev.oak3.sbs4j.exception.ValueSerializationException;
import dev.oak3.sbs4j.util.ByteUtils;
import org.bouncycastle.util.encoders.Hex;
import org.javatuples.Pair;
import org.javatuples.Triplet;
import org.javatuples.Unit;
import org.json.JSONException;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.slf4j.Logger;
Expand All @@ -57,9 +33,7 @@
import java.util.Map;
import java.util.Optional;

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}
Expand All @@ -77,7 +51,6 @@ public class StoredValueTests extends AbstractJsonTests {


@Test
@Disabled("CLValuesAny deser is not well understood yet")
void validate_CLValueAny_Mapping() throws IOException, JSONException, ValueSerializationException {
String inputJson = getPrettyJson(loadJsonFromFile("stored-value-samples/stored-value-any.json"));

Expand All @@ -87,11 +60,11 @@ void validate_CLValueAny_Mapping() throws IOException, JSONException, ValueSeria
// Should be CLValueAny
assertTrue(sv.getStoredValue().getValue() instanceof CLValueAny);

CLValueAny expectedClValue = new CLValueAny("Any Object Test");
CLValueAny expectedClValue = new CLValueAny(Hex.decode("aced000574000f416e79204f626a6563742054657374"));

StoredValueData expected = createAndInitExpectedStoredValueData(expectedClValue);

// assertEquals(expected, sv);
assertEquals(expected, sv);

String expectedJson = getPrettyJson(expected);

Expand Down Expand Up @@ -616,37 +589,6 @@ void validate_CLValueMap_Mapping_with_string_tuple1_i32() throws IOException,
JSONAssert.assertEquals(inputJson, expectedJson, false);
}

@Test
@Disabled("CLValuesAny deser is not well understood yet")
void validate_CLValueMap_Mapping_with_Map_i32_Any() throws IOException,
JSONException, ValueSerializationException {
String inputJson = getPrettyJson(
loadJsonFromFile("stored-value-samples/stored-value-map-u64-map-i32-any.json"));

LOGGER.debug("Original JSON: {}", inputJson);

StoredValueData sv = OBJECT_MAPPER.readValue(inputJson, StoredValueData.class);
// Should be CLValueMap
assertTrue(sv.getStoredValue().getValue() instanceof CLValueMap);

Map<CLValueU64, CLValueMap> map = new LinkedHashMap<>();
Map<CLValueI32, CLValueAny> 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));
CLValueMap expectedClValue = new CLValueMap(map);

StoredValueData expected = createAndInitExpectedStoredValueData(expectedClValue);

assertEquals(expected, sv);

String expectedJson = getPrettyJson(expected);

LOGGER.debug("Serialized JSON: {}", expectedJson);

JSONAssert.assertEquals(inputJson, expectedJson, false);
}

@Test
void validate_CLValueResult_Mapping_with_i32_string() throws IOException,
JSONException, ValueSerializationException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public abstract class AbstractJsonRpcTests extends AbstractJsonTests {
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public enum CasperNetwork {
MAIN_NET("152.32.239.13", 7777), TEST_NET("85.114.132.133", 7777);
MAIN_NET("63.33.251.206", 7777), TEST_NET("95.214.55.138", 7777);

private final String ip;
private final int port;
Expand Down
Loading

0 comments on commit 98db079

Please sign in to comment.