commit 67623f04a30ec17c97fe34204a587492e66a3106 Author: Chris Rankin Date: Mon Sep 2 16:12:49 2019 +0100 CORDA-3174: Implement Corda serialization modules. (#59) * Create DJVM serialization modules. * Create test cases for Array, List and List>. * Refactor SandboxPrimiveSerializer for all primitive types. * Implement SandboxCollectionSerializer to support Collection types. * Implement SandboxMapSerializer to support Map types. * Attempt to fix infinite loop when computing Collection and Map fingerprints. * Apply special handling when deserialising sandbox.java.lang.Character. * Remap Java primitive types to sandbox Java object types to deter evolution. * Use Class.getPackage().getName() to determine sandbox package name. * Implement SandboxEnumSerializer to support Enum types. * Implement SandboxPublicKeySerializer to support Java security keys. * Add serialization projects to the composite example project. * Implement serializers for BigInteger, BigDecimal, Currency and StringBuffer. * Test that deserialising does not instantiate the untrusted user classes. * Implement serializers for java.time.* types. * Add serialiser for BitSet - currently disabled until BitSet itself is supported. * Add serialisers for EnumSet and Class. * Include support for EnumMap in the SandboxMapSerializer. * Ensure the DJVM Example project's tests preserve @CordaSerializable. * Add support for UUID as a primitive type. * Use common abortReadOnly() method for declaring serialization as unsupported. * Streamline the API for deserialising into the sandbox. * Add preliminary support for deserialising X.509 certificates. * Implement serializer for java.util.Optional. * Refactor configuration of the sandbox serialization scheme. * Add tests for deserialising arrays of basic types. * Include method annotations in annotation stitching. This ensures that `@ConstructorForDeserialization` is not dropped. * Enable test for SandboxBitSetSerializer. * Enable tests for X.509 serializers. * Implement serializers for ProtonJ primitive types. * Serialize java.util.Date as a primitive type. * Add the bintray Gradle plugin to the serialisation modules. * Do not publish serialisation modules - they will become part of Corda itself. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..30395c53f3 --- /dev/null +++ b/build.gradle @@ -0,0 +1,102 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' + id 'java-library' + id 'idea' +} + +ext { + corda_version = '5.0-SNAPSHOT' +} + +description 'Serialization support for the DJVM' + +configurations { + sandboxTesting + jdkRt.resolutionStrategy { + // Always check the repository for a newer SNAPSHOT. + cacheChangingModulesFor 0, 'seconds' + } +} + +allprojects { + repositories { + maven { + url "$artifactory_contextUrl/corda-dev" + } + } + + configurations{ + // This is for the latest deterministic Corda SNAPSHOT artifacts... + [ compileClasspath, runtimeClasspath ].forEach { cfg -> + cfg.resolutionStrategy { + // Always check the repository for a newer SNAPSHOT. + cacheChangingModulesFor 0, 'seconds' + + dependencySubstitution { + substitute module("net.corda:corda-core:$corda_version") with module("net.corda:corda-core-deterministic:$corda_version") + substitute module("net.corda:corda-serialization:$corda_version") with module("net.corda:corda-serialization-deterministic:$corda_version") + } + } + } + } + + /* + * Corda serialization requires parameter names + * to be available via Java reflection. + */ + tasks.withType(JavaCompile) { + options.compilerArgs += '-parameters' + } + + tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) { + kotlinOptions { + javaParameters = true + } + } +} + +dependencies { + api project(path: ':djvm', configuration: 'shadow') + api "net.corda:corda-core:$corda_version" + api "net.corda:corda-serialization:$corda_version" + implementation project(':serialization:deserializers') + + testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_jupiter_version" + testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_jupiter_version" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_jupiter_version" + + // Test utilities + testImplementation "org.assertj:assertj-core:$assertj_version" + testRuntimeOnly "org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version" + jdkRt "net.corda:deterministic-rt:latest.integration" + + // The DJVM will need this classpath to run the unit tests. + sandboxTesting files(sourceSets.getByName("test").output) + sandboxTesting(project(':serialization:deserializers')) { + exclude group: 'net.corda' + } + sandboxTesting "net.corda:corda-serialization-deterministic:$corda_version" + sandboxTesting "org.slf4j:slf4j-nop:$slf4j_version" +} + +jar { + manifest { + attributes('Sealed': true) + } +} + +tasks.withType(Test) { + systemProperty 'deterministic-rt.path', configurations.jdkRt.asPath + systemProperty 'sandbox-libraries.path', configurations.sandboxTesting.asPath +} + +//publish { +// name 'corda-djvm-serialization' +//} + +idea { + module { + downloadJavadoc = true + downloadSources = true + } +} diff --git a/deserializers/build.gradle b/deserializers/build.gradle new file mode 100644 index 0000000000..d6a087a58f --- /dev/null +++ b/deserializers/build.gradle @@ -0,0 +1,29 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' + id 'java-library' + id 'idea' +} + +description 'Deserializers for the DJVM' + +dependencies { + api "net.corda:corda-core:$corda_version" + api "net.corda:corda-serialization:$corda_version" +} + +jar { + manifest { + attributes('Sealed': true) + } +} + +//publish { +// name 'corda-djvm-deserializers' +//} + +idea { + module { + downloadJavadoc = true + downloadSources = true + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/BitSetDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/BitSetDeserializer.kt new file mode 100644 index 0000000000..3e8c77a844 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/BitSetDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.BitSetSerializer.BitSetProxy +import java.util.* +import java.util.function.Function + +class BitSetDeserializer : Function { + override fun apply(proxy: BitSetProxy): BitSet { + return BitSet.valueOf(proxy.bytes) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CertPathDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CertPathDeserializer.kt new file mode 100644 index 0000000000..8ccd55849f --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CertPathDeserializer.kt @@ -0,0 +1,13 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.CertPathSerializer.CertPathProxy +import java.security.cert.CertPath +import java.security.cert.CertificateFactory +import java.util.function.Function + +class CertPathDeserializer : Function { + override fun apply(proxy: CertPathProxy): CertPath { + val factory = CertificateFactory.getInstance(proxy.type) + return factory.generateCertPath(proxy.encoded.inputStream()) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ClassDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ClassDeserializer.kt new file mode 100644 index 0000000000..b3f44751cb --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ClassDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.ClassSerializer.ClassProxy + +import java.util.function.Function + +class ClassDeserializer : Function> { + override fun apply(proxy: ClassProxy): Class<*> { + return Class.forName(proxy.className) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateCollection.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateCollection.kt new file mode 100644 index 0000000000..0a1cb0e8db --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateCollection.kt @@ -0,0 +1,47 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.core.utilities.NonEmptySet +import java.util.* +import java.util.function.Function + +class CreateCollection : Function, Collection> { + private val concreteConstructors: Map>, (Array) -> Collection> = mapOf( + List::class.java to ::createList, + Set::class.java to ::createSet, + SortedSet::class.java to ::createSortedSet, + NavigableSet::class.java to ::createNavigableSet, + Collection::class.java to ::createCollection, + NonEmptySet::class.java to ::createNonEmptySet + ) + + private fun createList(values: Array): List { + return Collections.unmodifiableList(arrayListOf(*values)) + } + + private fun createSet(values: Array): Set { + return Collections.unmodifiableSet(linkedSetOf(*values)) + } + + private fun createSortedSet(values: Array): SortedSet { + return Collections.unmodifiableSortedSet(sortedSetOf(*values)) + } + + private fun createNavigableSet(values: Array): NavigableSet { + return Collections.unmodifiableNavigableSet(sortedSetOf(*values)) + } + + private fun createCollection(values: Array): Collection { + return Collections.unmodifiableCollection(arrayListOf(*values)) + } + + private fun createNonEmptySet(values: Array): NonEmptySet { + return NonEmptySet.copyOf(arrayListOf(*values)) + } + + @Suppress("unchecked_cast") + override fun apply(inputs: Array): Collection { + val collectionClass = inputs[0] as Class> + val args = inputs[1] as Array + return concreteConstructors[collectionClass]?.invoke(args)!! + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateCurrency.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateCurrency.kt new file mode 100644 index 0000000000..51230b8372 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateCurrency.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import java.util.* +import java.util.function.Function + +class CreateCurrency : Function { + override fun apply(currencyCode: String): Currency { + return Currency.getInstance(currencyCode) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateFromString.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateFromString.kt new file mode 100644 index 0000000000..027858091b --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateFromString.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import java.lang.reflect.Constructor +import java.util.function.Function + +class CreateFromString(private val factory: Constructor) : Function { + override fun apply(text: String): Any { + return factory.newInstance(text) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateMap.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateMap.kt new file mode 100644 index 0000000000..d22d0427d6 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/CreateMap.kt @@ -0,0 +1,48 @@ +package net.corda.djvm.serialization.deserializers + +import java.util.* +import java.util.function.Function + +class CreateMap : Function, Map> { + private val concreteConstructors: Map>, (Array>) -> Map> = mapOf( + Map::class.java to ::createMap, + SortedMap::class.java to ::createSortedMap, + LinkedHashMap::class.java to ::createLinkedHashMap, + NavigableMap::class.java to ::createNavigableMap, + TreeMap::class.java to ::createTreeMap, + EnumMap::class.java to ::createEnumMap + ) + + private fun createMap(values: Array>): Map { + return Collections.unmodifiableMap(values.map { it[0] to it[1] }.toMap()) + } + + private fun createSortedMap(values: Array>): SortedMap { + return Collections.unmodifiableSortedMap(createTreeMap(values)) + } + + private fun createNavigableMap(values: Array>): NavigableMap { + return Collections.unmodifiableNavigableMap(createTreeMap(values)) + } + + private fun createLinkedHashMap(values: Array>): LinkedHashMap { + return values.map { it[0] to it[1] }.toMap(LinkedHashMap()) + } + + private fun createTreeMap(values: Array>): TreeMap { + return values.map { it[0] to it[1] }.toMap(TreeMap()) + } + + private fun createEnumMap(values: Array>): Map { + val map = values.map { it[0] to it[1] }.toMap() + @Suppress("unchecked_cast") + return EnumMap(map as Map) as Map + } + + @Suppress("unchecked_cast") + override fun apply(inputs: Array): Map { + val mapClass = inputs[0] as Class> + val args = inputs[1] as Array> + return concreteConstructors[mapClass]?.invoke(args)!! + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal128Deserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal128Deserializer.kt new file mode 100644 index 0000000000..065418cdbd --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal128Deserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import org.apache.qpid.proton.amqp.Decimal128 +import java.util.function.Function + +class Decimal128Deserializer : Function { + override fun apply(underlying: LongArray): Decimal128 { + return Decimal128(underlying[0], underlying[1]) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal32Deserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal32Deserializer.kt new file mode 100644 index 0000000000..3820329a41 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal32Deserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import org.apache.qpid.proton.amqp.Decimal32 +import java.util.function.Function + +class Decimal32Deserializer : Function { + override fun apply(underlying: IntArray): Decimal32 { + return Decimal32(underlying[0]) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal64Deserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal64Deserializer.kt new file mode 100644 index 0000000000..4f298cb5e9 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/Decimal64Deserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import org.apache.qpid.proton.amqp.Decimal64 +import java.util.function.Function + +class Decimal64Deserializer : Function { + override fun apply(underlying: LongArray): Decimal64 { + return Decimal64(underlying[0]) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/DescribeEnum.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/DescribeEnum.kt new file mode 100644 index 0000000000..1d8d7e371e --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/DescribeEnum.kt @@ -0,0 +1,9 @@ +package net.corda.djvm.serialization.deserializers + +import java.util.function.Function + +class DescribeEnum : Function, Array> { + override fun apply(enumClass: Class<*>): Array { + return enumClass.enumConstants + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/DurationDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/DurationDeserializer.kt new file mode 100644 index 0000000000..7369932a0d --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/DurationDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.DurationSerializer.DurationProxy +import java.time.Duration +import java.util.function.Function + +class DurationDeserializer : Function { + override fun apply(proxy: DurationProxy): Duration { + return Duration.ofSeconds(proxy.seconds, proxy.nanos.toLong()) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/EnumSetDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/EnumSetDeserializer.kt new file mode 100644 index 0000000000..510ee2b4b0 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/EnumSetDeserializer.kt @@ -0,0 +1,16 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.core.internal.uncheckedCast +import net.corda.serialization.internal.amqp.custom.EnumSetSerializer.EnumSetProxy +import java.util.* +import java.util.function.Function + +class EnumSetDeserializer : Function> { + override fun apply(proxy: EnumSetProxy): EnumSet<*> { + return if (proxy.elements.isEmpty()) { + EnumSet.noneOf(uncheckedCast, Class>(proxy.clazz)) + } else { + EnumSet.copyOf(uncheckedCast, List>(proxy.elements)) + } + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/InstantDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/InstantDeserializer.kt new file mode 100644 index 0000000000..084495ee2b --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/InstantDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.InstantSerializer.InstantProxy +import java.time.Instant +import java.util.function.Function + +class InstantDeserializer : Function { + override fun apply(proxy: InstantProxy): Instant { + return Instant.ofEpochSecond(proxy.epochSeconds, proxy.nanos.toLong()) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/JustForCasting.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/JustForCasting.kt new file mode 100644 index 0000000000..17860c31c5 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/JustForCasting.kt @@ -0,0 +1,6 @@ +package net.corda.djvm.serialization.deserializers + +@Suppress("unused") +enum class JustForCasting { + UNUSED +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalDateDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalDateDeserializer.kt new file mode 100644 index 0000000000..121298ae6b --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalDateDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.LocalDateSerializer.LocalDateProxy +import java.time.LocalDate +import java.util.function.Function + +class LocalDateDeserializer : Function { + override fun apply(proxy: LocalDateProxy): LocalDate { + return LocalDate.of(proxy.year, proxy.month.toInt(), proxy.day.toInt()) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalDateTimeDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalDateTimeDeserializer.kt new file mode 100644 index 0000000000..fd26c625b9 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalDateTimeDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.LocalDateTimeSerializer.LocalDateTimeProxy +import java.time.LocalDateTime +import java.util.function.Function + +class LocalDateTimeDeserializer : Function { + override fun apply(proxy: LocalDateTimeProxy): LocalDateTime { + return LocalDateTime.of(proxy.date, proxy.time) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalTimeDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalTimeDeserializer.kt new file mode 100644 index 0000000000..f346333692 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/LocalTimeDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.LocalTimeSerializer.LocalTimeProxy +import java.time.LocalTime +import java.util.function.Function + +class LocalTimeDeserializer : Function { + override fun apply(proxy: LocalTimeProxy): LocalTime { + return LocalTime.of(proxy.hour.toInt(), proxy.minute.toInt(), proxy.second.toInt(), proxy.nano) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/MonthDayDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/MonthDayDeserializer.kt new file mode 100644 index 0000000000..4b5827b462 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/MonthDayDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.MonthDaySerializer.MonthDayProxy +import java.time.MonthDay +import java.util.function.Function + +class MonthDayDeserializer : Function { + override fun apply(proxy: MonthDayProxy): MonthDay { + return MonthDay.of(proxy.month.toInt(), proxy.day.toInt()) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OffsetDateTimeDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OffsetDateTimeDeserializer.kt new file mode 100644 index 0000000000..d91976ab67 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OffsetDateTimeDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.OffsetDateTimeSerializer.OffsetDateTimeProxy +import java.time.OffsetDateTime +import java.util.function.Function + +class OffsetDateTimeDeserializer : Function { + override fun apply(proxy: OffsetDateTimeProxy): OffsetDateTime { + return OffsetDateTime.of(proxy.dateTime, proxy.offset) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OffsetTimeDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OffsetTimeDeserializer.kt new file mode 100644 index 0000000000..b668affce0 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OffsetTimeDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.OffsetTimeSerializer.OffsetTimeProxy +import java.time.OffsetTime +import java.util.function.Function + +class OffsetTimeDeserializer : Function { + override fun apply(proxy: OffsetTimeProxy): OffsetTime { + return OffsetTime.of(proxy.time, proxy.offset) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OptionalDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OptionalDeserializer.kt new file mode 100644 index 0000000000..483757e3dd --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/OptionalDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.OptionalSerializer.OptionalProxy +import java.util.* +import java.util.function.Function + +class OptionalDeserializer : Function> { + override fun apply(proxy: OptionalProxy): Optional { + return Optional.ofNullable(proxy.item) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/PeriodDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/PeriodDeserializer.kt new file mode 100644 index 0000000000..7b5100d5fd --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/PeriodDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.PeriodSerializer.PeriodProxy +import java.time.Period +import java.util.function.Function + +class PeriodDeserializer : Function { + override fun apply(proxy: PeriodProxy): Period { + return Period.of(proxy.years, proxy.months, proxy.days) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/PublicKeyDecoder.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/PublicKeyDecoder.kt new file mode 100644 index 0000000000..9c27dde405 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/PublicKeyDecoder.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.core.crypto.Crypto +import java.security.PublicKey +import java.util.function.Function + +class PublicKeyDecoder : Function { + override fun apply(encoded: ByteArray): PublicKey { + return Crypto.decodePublicKey(encoded) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/SymbolDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/SymbolDeserializer.kt new file mode 100644 index 0000000000..63833392b3 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/SymbolDeserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import org.apache.qpid.proton.amqp.Symbol +import java.util.function.Function + +class SymbolDeserializer : Function { + override fun apply(value: String): Symbol { + return Symbol.valueOf(value) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedByteDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedByteDeserializer.kt new file mode 100644 index 0000000000..3e32c25787 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedByteDeserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import org.apache.qpid.proton.amqp.UnsignedByte +import java.util.function.Function + +class UnsignedByteDeserializer : Function { + override fun apply(underlying: ByteArray): UnsignedByte { + return UnsignedByte(underlying[0]) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedIntegerDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedIntegerDeserializer.kt new file mode 100644 index 0000000000..7424430ff1 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedIntegerDeserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import org.apache.qpid.proton.amqp.UnsignedInteger +import java.util.function.Function + +class UnsignedIntegerDeserializer : Function { + override fun apply(underlying: IntArray): UnsignedInteger { + return UnsignedInteger(underlying[0]) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedLongDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedLongDeserializer.kt new file mode 100644 index 0000000000..0ef378abec --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedLongDeserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import org.apache.qpid.proton.amqp.UnsignedLong +import java.util.function.Function + +class UnsignedLongDeserializer : Function { + override fun apply(underlying: LongArray): UnsignedLong { + return UnsignedLong(underlying[0]) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedShortDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedShortDeserializer.kt new file mode 100644 index 0000000000..2f38994378 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/UnsignedShortDeserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import org.apache.qpid.proton.amqp.UnsignedShort +import java.util.function.Function + +class UnsignedShortDeserializer : Function { + override fun apply(underlying: ShortArray): UnsignedShort { + return UnsignedShort(underlying[0]) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/X509CRLDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/X509CRLDeserializer.kt new file mode 100644 index 0000000000..5e4b9b8e7c --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/X509CRLDeserializer.kt @@ -0,0 +1,12 @@ +package net.corda.djvm.serialization.deserializers + +import java.security.cert.CertificateFactory +import java.security.cert.X509CRL +import java.util.function.Function + +class X509CRLDeserializer : Function { + override fun apply(bytes: ByteArray): X509CRL { + val factory = CertificateFactory.getInstance("X.509") + return factory.generateCRL(bytes.inputStream()) as X509CRL + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/X509CertificateDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/X509CertificateDeserializer.kt new file mode 100644 index 0000000000..1cbd2f7491 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/X509CertificateDeserializer.kt @@ -0,0 +1,12 @@ +package net.corda.djvm.serialization.deserializers + +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import java.util.function.Function + +class X509CertificateDeserializer : Function { + override fun apply(bits: ByteArray): X509Certificate { + val factory = CertificateFactory.getInstance("X.509") + return factory.generateCertificate(bits.inputStream()) as X509Certificate + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/YearDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/YearDeserializer.kt new file mode 100644 index 0000000000..d259c0a95a --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/YearDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.YearSerializer.YearProxy +import java.time.Year +import java.util.function.Function + +class YearDeserializer : Function { + override fun apply(proxy: YearProxy): Year { + return Year.of(proxy.year) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/YearMonthDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/YearMonthDeserializer.kt new file mode 100644 index 0000000000..31cb123d8f --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/YearMonthDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.YearMonthSerializer.YearMonthProxy +import java.time.YearMonth +import java.util.function.Function + +class YearMonthDeserializer : Function { + override fun apply(proxy: YearMonthProxy): YearMonth { + return YearMonth.of(proxy.year, proxy.month.toInt()) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ZoneIdDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ZoneIdDeserializer.kt new file mode 100644 index 0000000000..b0e64c6e7d --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ZoneIdDeserializer.kt @@ -0,0 +1,11 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.ZoneIdSerializer.ZoneIdProxy +import java.time.ZoneId +import java.util.function.Function + +class ZoneIdDeserializer : Function { + override fun apply(proxy: ZoneIdProxy): ZoneId { + return ZoneId.of(proxy.id) + } +} diff --git a/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ZonedDateTimeDeserializer.kt b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ZonedDateTimeDeserializer.kt new file mode 100644 index 0000000000..3ac0744283 --- /dev/null +++ b/deserializers/src/main/kotlin/net/corda/djvm/serialization/deserializers/ZonedDateTimeDeserializer.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization.deserializers + +import net.corda.serialization.internal.amqp.custom.ZonedDateTimeSerializer.ZonedDateTimeProxy +import java.util.function.Function + +class ZonedDateTimeDeserializer : Function?> { + override fun apply(proxy: ZonedDateTimeProxy): Array? { + return arrayOf(proxy.dateTime, proxy.offset, proxy.zone) + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/AMQPSerializationScheme.kt b/src/main/kotlin/net/corda/djvm/serialization/AMQPSerializationScheme.kt new file mode 100644 index 0000000000..90981d486a --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/AMQPSerializationScheme.kt @@ -0,0 +1,89 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.SerializationContext +import net.corda.core.serialization.SerializationContext.UseCase +import net.corda.core.serialization.SerializedBytes +import net.corda.core.utilities.ByteSequence +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.serializers.* +import net.corda.serialization.internal.CordaSerializationMagic +import net.corda.serialization.internal.SerializationScheme +import net.corda.serialization.internal.amqp.* +import java.math.BigDecimal +import java.math.BigInteger +import java.util.* +import java.util.function.BiFunction +import java.util.function.Function + +class AMQPSerializationScheme( + private val classLoader: SandboxClassLoader, + private val sandboxBasicInput: Function, + private val executor: BiFunction, + private val serializerFactoryFactory: SerializerFactoryFactory +) : SerializationScheme { + + private fun getSerializerFactory(context: SerializationContext): SerializerFactory { + return serializerFactoryFactory.make(context).apply { + register(SandboxBitSetSerializer(classLoader, executor, this)) + register(SandboxCertPathSerializer(classLoader, executor, this)) + register(SandboxDurationSerializer(classLoader, executor, this)) + register(SandboxEnumSetSerializer(classLoader, executor, this)) + register(SandboxInstantSerializer(classLoader, executor, this)) + register(SandboxLocalDateSerializer(classLoader, executor, this)) + register(SandboxLocalDateTimeSerializer(classLoader, executor, this)) + register(SandboxLocalTimeSerializer(classLoader, executor, this)) + register(SandboxMonthDaySerializer(classLoader, executor, this)) + register(SandboxOffsetDateTimeSerializer(classLoader, executor, this)) + register(SandboxOffsetTimeSerializer(classLoader, executor, this)) + register(SandboxPeriodSerializer(classLoader, executor, this)) + register(SandboxYearMonthSerializer(classLoader, executor, this)) + register(SandboxYearSerializer(classLoader, executor, this)) + register(SandboxZonedDateTimeSerializer(classLoader, executor, this)) + register(SandboxZoneIdSerializer(classLoader, executor, this)) + register(SandboxOptionalSerializer(classLoader, executor, this)) + register(SandboxPrimitiveSerializer(UUID::class.java, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(String::class.java, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(Byte::class.javaObjectType, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(Short::class.javaObjectType, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(Int::class.javaObjectType, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(Long::class.javaObjectType, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(Float::class.javaObjectType, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(Double::class.javaObjectType, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(Boolean::class.javaObjectType, classLoader, sandboxBasicInput)) + register(SandboxPrimitiveSerializer(Date::class.javaObjectType, classLoader, sandboxBasicInput)) + register(SandboxCharacterSerializer(classLoader, sandboxBasicInput)) + register(SandboxCollectionSerializer(classLoader, executor, this)) + register(SandboxMapSerializer(classLoader, executor, this)) + register(SandboxEnumSerializer(classLoader, executor, this)) + register(SandboxPublicKeySerializer(classLoader, executor)) + register(SandboxToStringSerializer(BigDecimal::class.java, classLoader, executor, sandboxBasicInput)) + register(SandboxToStringSerializer(BigInteger::class.java, classLoader, executor, sandboxBasicInput)) + register(SandboxToStringSerializer(StringBuffer::class.java, classLoader, executor, sandboxBasicInput)) + register(SandboxCurrencySerializer(classLoader, executor, sandboxBasicInput)) + register(SandboxX509CertificateSerializer(classLoader, executor)) + register(SandboxX509CRLSerializer(classLoader, executor)) + register(SandboxUnsignedLongSerializer(classLoader, executor)) + register(SandboxUnsignedIntegerSerializer(classLoader, executor)) + register(SandboxUnsignedShortSerializer(classLoader, executor)) + register(SandboxUnsignedByteSerializer(classLoader, executor)) + register(SandboxDecimal128Serializer(classLoader, executor)) + register(SandboxDecimal64Serializer(classLoader, executor)) + register(SandboxDecimal32Serializer(classLoader, executor)) + register(SandboxSymbolSerializer(classLoader, executor, sandboxBasicInput)) + } + } + + override fun deserialize(byteSequence: ByteSequence, clazz: Class, context: SerializationContext): T { + val serializerFactory = getSerializerFactory(context) + return DeserializationInput(serializerFactory).deserialize(byteSequence, clazz, context) + } + + override fun serialize(obj: T, context: SerializationContext): SerializedBytes { + val serializerFactory = getSerializerFactory(context) + return SerializationOutput(serializerFactory).serialize(obj, context) + } + + override fun canDeserializeVersion(magic: CordaSerializationMagic, target: UseCase): Boolean { + return magic == amqpMagic && target == UseCase.P2P + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/DelegatingClassLoader.kt b/src/main/kotlin/net/corda/djvm/serialization/DelegatingClassLoader.kt new file mode 100644 index 0000000000..2d530d08f9 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/DelegatingClassLoader.kt @@ -0,0 +1,10 @@ +package net.corda.djvm.serialization + +import net.corda.djvm.rewiring.SandboxClassLoader + +class DelegatingClassLoader(private val delegate: SandboxClassLoader) : ClassLoader(null) { + @Throws(ClassNotFoundException::class) + override fun loadClass(name: String, resolve: Boolean): Class<*> { + return delegate.loadForSandbox(name).type + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/SandboxSerializerFactoryFactory.kt b/src/main/kotlin/net/corda/djvm/serialization/SandboxSerializerFactoryFactory.kt new file mode 100644 index 0000000000..442a3265ca --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/SandboxSerializerFactoryFactory.kt @@ -0,0 +1,85 @@ +@file:Suppress("platform_class_mapped_to_kotlin") +package net.corda.djvm.serialization + +import net.corda.core.serialization.SerializationContext +import net.corda.serialization.internal.amqp.* +import net.corda.serialization.internal.model.* +import java.lang.Boolean +import java.lang.Byte +import java.lang.Double +import java.lang.Float +import java.lang.Long +import java.lang.Short +import java.util.Collections.singleton +import java.util.Collections.unmodifiableMap +import java.util.function.Function + +/** + * This has all been lovingly copied from [SerializerFactoryBuilder]. + */ +class SandboxSerializerFactoryFactory( + private val primitiveSerializerFactory: Function, AMQPSerializer> +) : SerializerFactoryFactory { + + override fun make(context: SerializationContext): SerializerFactory { + val classLoader = context.deserializationClassLoader + + val primitiveTypes = unmodifiableMap(mapOf, Class<*>>( + classLoader.loadClass("sandbox.java.lang.Boolean") to Boolean.TYPE, + classLoader.loadClass("sandbox.java.lang.Byte") to Byte.TYPE, + classLoader.loadClass("sandbox.java.lang.Character") to Character.TYPE, + classLoader.loadClass("sandbox.java.lang.Double") to Double.TYPE, + classLoader.loadClass("sandbox.java.lang.Float") to Float.TYPE, + classLoader.loadClass("sandbox.java.lang.Integer") to Integer.TYPE, + classLoader.loadClass("sandbox.java.lang.Long") to Long.TYPE, + classLoader.loadClass("sandbox.java.lang.Short") to Short.TYPE + )) + + val classCarpenter = createClassCarpenter(context) + val descriptorBasedSerializerRegistry = DefaultDescriptorBasedSerializerRegistry() + val customSerializerRegistry = CachingCustomSerializerRegistry( + descriptorBasedSerializerRegistry = descriptorBasedSerializerRegistry, + allowedFor = singleton(classLoader.loadClass("sandbox.java.lang.Object")) + ) + + val localTypeModel = ConfigurableLocalTypeModel( + WhitelistBasedTypeModelConfiguration(context.whitelist, customSerializerRegistry) + ) + + val fingerPrinter = TypeModellingFingerPrinter(customSerializerRegistry) + + val localSerializerFactory = DefaultLocalSerializerFactory( + whitelist = context.whitelist, + typeModel = localTypeModel, + fingerPrinter = fingerPrinter, + classloader = classLoader, + descriptorBasedSerializerRegistry = descriptorBasedSerializerRegistry, + primitiveSerializerFactory = primitiveSerializerFactory, + customSerializerRegistry = customSerializerRegistry, + onlyCustomSerializers = false + ) + + val typeLoader: TypeLoader = ClassCarpentingTypeLoader( + carpenter = SchemaBuildingRemoteTypeCarpenter(classCarpenter), + classLoader = classLoader + ) + + val evolutionSerializerFactory = DefaultEvolutionSerializerFactory( + localSerializerFactory = localSerializerFactory, + classLoader = classLoader, + mustPreserveDataWhenEvolving = context.preventDataLoss, + primitiveTypes = primitiveTypes + ) + + val remoteSerializerFactory = DefaultRemoteSerializerFactory( + evolutionSerializerFactory = evolutionSerializerFactory, + descriptorBasedSerializerRegistry = descriptorBasedSerializerRegistry, + remoteTypeModel = AMQPRemoteTypeModel(), + localTypeModel = localTypeModel, + typeLoader = typeLoader, + localSerializerFactory = localSerializerFactory + ) + + return ComposedSerializerFactory(localSerializerFactory, remoteSerializerFactory, customSerializerRegistry) + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/SandboxWhitelist.kt b/src/main/kotlin/net/corda/djvm/serialization/SandboxWhitelist.kt new file mode 100644 index 0000000000..12c21a2c65 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/SandboxWhitelist.kt @@ -0,0 +1,13 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.ClassWhitelist + +class SandboxWhitelist : ClassWhitelist { + companion object { + private val packageName = "^sandbox\\.(?:java|kotlin)(?:[.]|$)".toRegex() + } + + override fun hasListed(type: Class<*>): Boolean { + return packageName.containsMatchIn(type.`package`.name) + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/Serialization.kt b/src/main/kotlin/net/corda/djvm/serialization/Serialization.kt new file mode 100644 index 0000000000..8e1f16d4a4 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/Serialization.kt @@ -0,0 +1,87 @@ +@file:JvmName("Serialization") +package net.corda.djvm.serialization + +import net.corda.core.serialization.SerializationContext +import net.corda.core.serialization.SerializationContext.UseCase +import net.corda.core.serialization.SerializationFactory +import net.corda.core.serialization.SerializedBytes +import net.corda.core.serialization.internal.SerializationEnvironment +import net.corda.djvm.execution.SandboxRuntimeException +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.serializers.PrimitiveSerializer +import net.corda.djvm.source.ClassSource +import net.corda.serialization.internal.GlobalTransientClassWhiteList +import net.corda.serialization.internal.SerializationContextImpl +import net.corda.serialization.internal.SerializationFactoryImpl +import net.corda.serialization.internal.amqp.AMQPSerializer +import net.corda.serialization.internal.amqp.amqpMagic +import java.lang.reflect.InvocationTargetException +import java.util.function.BiFunction +import java.util.function.Function + +fun SandboxClassLoader.loadClassForSandbox(clazz: Class<*>): Class { + @Suppress("unchecked_cast") + return loadClassForSandbox(ClassSource.fromClassName(clazz.name)) as Class +} + +fun createSandboxSerializationEnv(classLoader: SandboxClassLoader): SerializationEnvironment { + val p2pContext: SerializationContext = SerializationContextImpl( + preferredSerializationVersion = amqpMagic, + deserializationClassLoader = DelegatingClassLoader(classLoader), + whitelist = GlobalTransientClassWhiteList(SandboxWhitelist()), + properties = emptyMap(), + objectReferencesEnabled = true, + carpenterDisabled = true, + useCase = UseCase.P2P, + encoding = null + ) + + val taskClass = classLoader.loadClass("sandbox.RawTask") + val taskApply = taskClass.getDeclaredMethod("apply", Any::class.java) + val taskConstructor = taskClass.getDeclaredConstructor(classLoader.loadClassForSandbox(Function::class.java)) + val executor: BiFunction = BiFunction { userTask, arg -> + try { + taskApply(taskConstructor.newInstance(userTask), arg) + } catch (ex: InvocationTargetException) { + val target = ex.targetException + throw when (target) { + is RuntimeException, is Error -> target + else -> SandboxRuntimeException(target.message, target) + } + } + } + + val sandboxBasicInput = classLoader.createBasicInput() + + val primitiveSerializerFactory: Function, AMQPSerializer> = Function { clazz -> + PrimitiveSerializer(clazz, sandboxBasicInput) + } + + val factory = SerializationFactoryImpl(mutableMapOf()).apply { + registerScheme(AMQPSerializationScheme( + classLoader = classLoader, + sandboxBasicInput = sandboxBasicInput, + executor = executor, + serializerFactoryFactory = SandboxSerializerFactoryFactory(primitiveSerializerFactory) + )) + } + return SerializationEnvironment.with(factory, p2pContext = p2pContext) +} + +inline fun SerializedBytes.deserializeFor(classLoader: SandboxClassLoader): Any { + val clazz = classLoader.loadClassForSandbox(T::class.java) + return deserializeTo(clazz, classLoader) +} + +fun SerializedBytes<*>.deserializeTo(clazz: Class<*>, classLoader: SandboxClassLoader): Any { + return deserializeTo(clazz, classLoader, SerializationFactory.defaultFactory) +} + +fun SerializedBytes<*>.deserializeTo(clazz: Class<*>, classLoader: SandboxClassLoader, factory: SerializationFactory): Any { + val obj = factory.deserialize(this, Any::class.java, factory.defaultContext) + return if (clazz.isInstance(obj)) { + obj + } else { + classLoader.createBasicInput().apply(obj)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/ExceptionUtils.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/ExceptionUtils.kt new file mode 100644 index 0000000000..2ec59cc99d --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/ExceptionUtils.kt @@ -0,0 +1,38 @@ +@file:JvmName("ExceptionUtils") +package net.corda.djvm.serialization.serializers + +import net.corda.serialization.internal.amqp.AMQPNotSerializableException + +/** + * Utility function which helps tracking the path in the object graph when exceptions are thrown. + * Since there might be a chain of nested calls it is useful to record which part of the graph caused an issue. + * Path information is added to the message of the exception being thrown. + */ +internal inline fun ifThrowsAppend(strToAppendFn: () -> String, block: () -> T): T { + try { + return block() + } catch (th: Throwable) { + when (th) { + is AMQPNotSerializableException -> th.classHierarchy.add(strToAppendFn()) + // Do not overwrite the message of these exceptions as it may be used. + is ClassNotFoundException -> {} + is NoClassDefFoundError -> {} + else -> th.resetMessage("${strToAppendFn()} -> ${th.message}") + } + throw th + } +} + +/** + * Not a public property so will have to use reflection + */ +private fun Throwable.resetMessage(newMsg: String) { + val detailMessageField = Throwable::class.java.getDeclaredField("detailMessage") + detailMessageField.isAccessible = true + detailMessageField.set(this, newMsg) +} + +/** + * We currently only support deserialisation, and so we're going to need this. + */ +fun abortReadOnly(): Nothing = throw UnsupportedOperationException("Read Only!") \ No newline at end of file diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/PrimitiveSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/PrimitiveSerializer.kt new file mode 100644 index 0000000000..bd70965e3c --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/PrimitiveSerializer.kt @@ -0,0 +1,28 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.Binary +import org.apache.qpid.proton.amqp.Symbol +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.Function + +class PrimitiveSerializer( + override val type: Class<*>, + private val sandboxBasicInput: Function +) : AMQPSerializer { + override val typeDescriptor: Symbol = typeDescriptorFor(type) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return (obj as? Binary)?.array ?: sandboxBasicInput.apply(obj)!! + } + + override fun writeClassInfo(output: SerializationOutput) { + abortReadOnly() + } + + override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext, debugIndent: Int) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxBitSetSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxBitSetSerializer.kt new file mode 100644 index 0000000000..b6a2791944 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxBitSetSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.BitSetDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.BitSetSerializer.BitSetProxy +import java.util.* +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxBitSetSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(BitSet::class.java), + proxyClass = classLoader.loadClassForSandbox(BitSetProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(BitSetDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(BitSet::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCertPathSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCertPathSerializer.kt new file mode 100644 index 0000000000..e7380aaeaf --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCertPathSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.CertPathDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.CertPathSerializer.CertPathProxy +import java.security.cert.CertPath +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxCertPathSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(CertPath::class.java), + proxyClass = classLoader.loadClassForSandbox(CertPathProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(CertPathDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(CertPath::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCharacterSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCharacterSerializer.kt new file mode 100644 index 0000000000..3793808587 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCharacterSerializer.kt @@ -0,0 +1,33 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.Function + +class SandboxCharacterSerializer( + classLoader: SandboxClassLoader, + private val basicInput: Function +) : CustomSerializer.Is(classLoader.loadClassForSandbox(Char::class.javaObjectType)) { + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return basicInput.apply(convertToChar(obj))!! + } + + private fun convertToChar(obj: Any): Any { + return when (obj) { + is Short -> obj.toChar() + is Int -> obj.toChar() + else -> obj + } + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxClassSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxClassSerializer.kt new file mode 100644 index 0000000000..28b275a62a --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxClassSerializer.kt @@ -0,0 +1,54 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.execution.SandboxRuntimeException +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.ClassDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.AMQPNotSerializableException +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.ClassSerializer.ClassProxy +import java.util.function.BiFunction +import java.util.function.Function + +@Suppress("unchecked_cast") +class SandboxClassSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = Class::class.java as Class, + proxyClass = classLoader.loadClassForSandbox(ClassProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(ClassDeserializer::class.java).newInstance() + private val nameOf: Function + + init { + val fetch = proxyClass.getMethod("getClassName") + nameOf = Function { proxy -> + fetch(proxy).toString() + } + } + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return try { + executor.apply(task, proxy)!! + } catch (e: SandboxRuntimeException) { + val cause = e.cause ?: throw e + if (cause !is ClassNotFoundException) { + throw cause + } + + val className = nameOf.apply(proxy) + throw AMQPNotSerializableException(type, + "Could not instantiate $className - not on the classpath", + "$className was not found by the node, check the Node containing the CorDapp that " + + "implements $className is loaded and on the Classpath", + mutableListOf(className) + ) + } + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCollectionSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCollectionSerializer.kt new file mode 100644 index 0000000000..3aad78113f --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCollectionSerializer.kt @@ -0,0 +1,120 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.core.utilities.NonEmptySet +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.CreateCollection +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import net.corda.serialization.internal.model.LocalTypeInformation +import net.corda.serialization.internal.model.TypeIdentifier +import org.apache.qpid.proton.amqp.Symbol +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.ParameterizedType +import java.lang.reflect.Type +import java.util.* +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxCollectionSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction, + private val localFactory: LocalSerializerFactory +) : CustomSerializer.Implements(clazz = classLoader.loadClassForSandbox(Collection::class.java)) { + private val creator: Function, out Any?> + + init { + val createTask = classLoader.loadClassForSandbox(CreateCollection::class.java).newInstance() + creator = Function { inputs -> + executor.apply(createTask, inputs) + } + } + + private val unsupportedTypes: Set> = listOf( + EnumSet::class.java + ).map { + classLoader.loadClassForSandbox(it) + }.toSet() + + // The order matters here - the first match should be the most specific one. + // Kotlin preserves the ordering for us by associating into a LinkedHashMap. + private val supportedTypes: Map, Class>> = listOf( + List::class.java, + NonEmptySet::class.java, + NavigableSet::class.java, + SortedSet::class.java, + Set::class.java, + Collection::class.java + ).associateBy { + classLoader.loadClassForSandbox(it) + } + + private fun getBestMatchFor(type: Class): Map.Entry, Class>> + = supportedTypes.entries.first { it.key.isAssignableFrom(type) } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun isSerializerFor(clazz: Class<*>): Boolean { + return super.isSerializerFor(clazz) && unsupportedTypes.none { it.isAssignableFrom(clazz) } + } + + override fun specialiseFor(declaredType: Type): AMQPSerializer? { + if (declaredType !is ParameterizedType) { + return null + } + + @Suppress("unchecked_cast") + val rawType = declaredType.rawType as Class + return ConcreteCollectionSerializer(declaredType, getBestMatchFor(rawType), creator, localFactory) + } + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + throw UnsupportedOperationException("Factory only") + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + throw UnsupportedOperationException("Factory Only") + } +} + +private class ConcreteCollectionSerializer( + declaredType: ParameterizedType, + private val matchingType: Map.Entry, Class>>, + private val creator: Function, out Any?>, + factory: LocalSerializerFactory +) : AMQPSerializer { + override val type: ParameterizedType = declaredType + + override val typeDescriptor: Symbol by lazy { + factory.createDescriptor( + LocalTypeInformation.ACollection( + observedType = declaredType.rawType, + typeIdentifier = TypeIdentifier.forGenericType(declaredType), + elementType =factory.getTypeInformation(declaredType.actualTypeArguments[0]) + ) + ) + } + + override fun readObject( + obj: Any, + schemas: SerializationSchemas, + input: DeserializationInput, + context: SerializationContext + ): Any { + val inboundType = type.actualTypeArguments[0] + return ifThrowsAppend({ type.typeName }) { + val args = (obj as List<*>).map { + input.readObjectOrNull(redescribe(it, inboundType), schemas, inboundType, context) + }.toTypedArray() + creator.apply(arrayOf(matchingType.key, args))!! + } + } + + override fun writeClassInfo(output: SerializationOutput) { + abortReadOnly() + } + + override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext, debugIndent: Int) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCurrencySerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCurrencySerializer.kt new file mode 100644 index 0000000000..9eee16cb33 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxCurrencySerializer.kt @@ -0,0 +1,39 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.CreateCurrency +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.* +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxCurrencySerializer( + classLoader: SandboxClassLoader, + executor: BiFunction, + basicInput: Function +) : CustomSerializer.Is(classLoader.loadClassForSandbox(Currency::class.java)) { + private val creator: Function + + init { + val createTask = classLoader.loadClassForSandbox(CreateCurrency::class.java).newInstance() + creator = basicInput.andThen { input -> + executor.apply(createTask, input) + } + } + + override val deserializationAliases: Set> = Collections.singleton(Currency::class.java) + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return creator.apply(obj)!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal128Serializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal128Serializer.kt new file mode 100644 index 0000000000..7f5da69f5e --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal128Serializer.kt @@ -0,0 +1,37 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.Decimal128Deserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.Decimal128 +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxDecimal128Serializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Is(classLoader.loadClassForSandbox(Decimal128::class.java)) { + private val transformer: Function + + init { + val transformTask = classLoader.loadClassForSandbox(Decimal128Deserializer::class.java).newInstance() + transformer = Function { inputs -> + executor.apply(transformTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + val decimal128 = obj as Decimal128 + return transformer.apply(longArrayOf(decimal128.mostSignificantBits, decimal128.leastSignificantBits))!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal32Serializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal32Serializer.kt new file mode 100644 index 0000000000..d0d8016683 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal32Serializer.kt @@ -0,0 +1,36 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.Decimal32Deserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.Decimal32 +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxDecimal32Serializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Is(classLoader.loadClassForSandbox(Decimal32::class.java)) { + private val transformer: Function + + init { + val transformTask = classLoader.loadClassForSandbox(Decimal32Deserializer::class.java).newInstance() + transformer = Function { inputs -> + executor.apply(transformTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return transformer.apply(intArrayOf((obj as Decimal32).bits))!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal64Serializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal64Serializer.kt new file mode 100644 index 0000000000..c77820712d --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDecimal64Serializer.kt @@ -0,0 +1,36 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.Decimal64Deserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.Decimal64 +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxDecimal64Serializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Is(classLoader.loadClassForSandbox(Decimal64::class.java)) { + private val transformer: Function + + init { + val transformTask = classLoader.loadClassForSandbox(Decimal64Deserializer::class.java).newInstance() + transformer = Function { inputs -> + executor.apply(transformTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return transformer.apply(longArrayOf((obj as Decimal64).bits))!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDurationSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDurationSerializer.kt new file mode 100644 index 0000000000..48586ce4df --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxDurationSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.DurationDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.DurationSerializer.DurationProxy +import java.time.Duration +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxDurationSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(Duration::class.java), + proxyClass = classLoader.loadClassForSandbox(DurationProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(DurationDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(Duration::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxEnumSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxEnumSerializer.kt new file mode 100644 index 0000000000..fedb92450a --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxEnumSerializer.kt @@ -0,0 +1,95 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.DescribeEnum +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import net.corda.serialization.internal.model.EnumTransforms +import net.corda.serialization.internal.model.LocalTypeInformation +import net.corda.serialization.internal.model.TypeIdentifier +import org.apache.qpid.proton.amqp.Symbol +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxEnumSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction, + private val localFactory: LocalSerializerFactory +) : CustomSerializer.Implements(clazz = classLoader.loadClassForSandbox(Enum::class.java)) { + private val describer: Function, Array> + + init { + val describeTask = classLoader.loadClassForSandbox(DescribeEnum::class.java).newInstance() + describer = Function { inputs -> + @Suppress("unchecked_cast") + executor.apply(describeTask, inputs) as Array + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun specialiseFor(declaredType: Type): AMQPSerializer? { + if (declaredType !is Class<*>) { + return null + } + val members = describer.apply(declaredType) + return ConcreteEnumSerializer(declaredType, members, localFactory) + } + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + throw UnsupportedOperationException("Factory only") + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + throw UnsupportedOperationException("Factory Only") + } +} + +private class ConcreteEnumSerializer( + declaredType: Class<*>, + private val members: Array, + factory: LocalSerializerFactory +) : AMQPSerializer { + override val type: Class<*> = declaredType + + override val typeDescriptor: Symbol by lazy { + factory.createDescriptor( + /* + * Partially populated, providing just the information + * required by the fingerprinter. + */ + LocalTypeInformation.AnEnum( + declaredType, + TypeIdentifier.forGenericType(declaredType), + members.map { it.toString() }, + emptyList(), + EnumTransforms.empty + ) + ) + } + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + val enumName = (obj as List<*>)[0] as String + val enumOrd = obj[1] as Int + val fromOrd = members[enumOrd] + + if (enumName != fromOrd.toString()) { + throw AMQPNotSerializableException( + type, + "Deserializing obj as enum $type with value $enumName.$enumOrd but ordinality has changed" + ) + } + return fromOrd + } + + override fun writeClassInfo(output: SerializationOutput) { + abortReadOnly() + } + + override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext, debugIndent: Int) { + abortReadOnly() + } +} \ No newline at end of file diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxEnumSetSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxEnumSetSerializer.kt new file mode 100644 index 0000000000..fe839f2b5c --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxEnumSetSerializer.kt @@ -0,0 +1,35 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.EnumSetDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.EnumSetSerializer.EnumSetProxy +import java.util.* +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxEnumSetSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(EnumSet::class.java), + proxyClass = classLoader.loadClassForSandbox(EnumSetProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(EnumSetDeserializer::class.java).newInstance() + + override val additionalSerializers: Set> = singleton( + SandboxClassSerializer(classLoader, executor, factory) + ) + + override val deserializationAliases: Set> = singleton(EnumSet::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxInstantSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxInstantSerializer.kt new file mode 100644 index 0000000000..ea867b146a --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxInstantSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.InstantDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.InstantSerializer.InstantProxy +import java.time.Instant +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxInstantSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(Instant::class.java), + proxyClass = classLoader.loadClassForSandbox(InstantProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(InstantDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(Instant::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalDateSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalDateSerializer.kt new file mode 100644 index 0000000000..4a8cbb256b --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalDateSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.LocalDateDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.LocalDateSerializer.LocalDateProxy +import java.time.LocalDate +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxLocalDateSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(LocalDate::class.java), + proxyClass = classLoader.loadClassForSandbox(LocalDateProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(LocalDateDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(LocalDate::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalDateTimeSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalDateTimeSerializer.kt new file mode 100644 index 0000000000..d027a5b61c --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalDateTimeSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.LocalDateTimeDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.LocalDateTimeSerializer.LocalDateTimeProxy +import java.time.LocalDateTime +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxLocalDateTimeSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(LocalDateTime::class.java), + proxyClass = classLoader.loadClassForSandbox(LocalDateTimeProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(LocalDateTimeDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(LocalDateTime::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalTimeSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalTimeSerializer.kt new file mode 100644 index 0000000000..87dfa15e26 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxLocalTimeSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.LocalTimeDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.LocalTimeSerializer.LocalTimeProxy +import java.time.LocalTime +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxLocalTimeSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(LocalTime::class.java), + proxyClass = classLoader.loadClassForSandbox(LocalTimeProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(LocalTimeDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(LocalTime::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxMapSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxMapSerializer.kt new file mode 100644 index 0000000000..2489b53742 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxMapSerializer.kt @@ -0,0 +1,114 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.CreateMap +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import net.corda.serialization.internal.model.LocalTypeInformation +import net.corda.serialization.internal.model.TypeIdentifier +import org.apache.qpid.proton.amqp.Symbol +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.ParameterizedType +import java.lang.reflect.Type +import java.util.* +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxMapSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction, + private val localFactory: LocalSerializerFactory +) : CustomSerializer.Implements(clazz = classLoader.loadClassForSandbox(Map::class.java)) { + private val creator: Function, out Any?> + + init { + val createTask = classLoader.loadClassForSandbox(CreateMap::class.java).newInstance() + creator = Function { inputs -> + executor.apply(createTask, inputs) + } + } + + // The order matters here - the first match should be the most specific one. + // Kotlin preserves the ordering for us by associating into a LinkedHashMap. + private val supportedTypes: Map, Class>> = listOf( + TreeMap::class.java, + LinkedHashMap::class.java, + NavigableMap::class.java, + SortedMap::class.java, + EnumMap::class.java, + Map::class.java + ).associateBy { + classLoader.loadClassForSandbox(it) + } + + private fun getBestMatchFor(type: Class): Map.Entry, Class>> + = supportedTypes.entries.first { it.key.isAssignableFrom(type) } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun specialiseFor(declaredType: Type): AMQPSerializer? { + if (declaredType !is ParameterizedType) { + return null + } + + @Suppress("unchecked_cast") + val rawType = declaredType.rawType as Class + return ConcreteMapSerializer(declaredType, getBestMatchFor(rawType), creator, localFactory) + } + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + throw UnsupportedOperationException("Factory only") + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + throw UnsupportedOperationException("Factory Only") + } +} + +private class ConcreteMapSerializer( + declaredType: ParameterizedType, + private val matchingType: Map.Entry, Class>>, + private val creator: Function, out Any?>, + factory: LocalSerializerFactory +) : AMQPSerializer { + override val type: ParameterizedType = declaredType + + override val typeDescriptor: Symbol by lazy { + factory.createDescriptor( + LocalTypeInformation.AMap( + observedType = declaredType.rawType, + typeIdentifier = TypeIdentifier.forGenericType(declaredType), + keyType =factory.getTypeInformation(declaredType.actualTypeArguments[0]), + valueType = factory.getTypeInformation(declaredType.actualTypeArguments[1]) + ) + ) + } + + override fun readObject( + obj: Any, + schemas: SerializationSchemas, + input: DeserializationInput, + context: SerializationContext + ): Any { + val inboundKeyType = type.actualTypeArguments[0] + val inboundValueType = type.actualTypeArguments[1] + return ifThrowsAppend({ type.typeName }) { + val entries = (obj as Map<*, *>).map { + arrayOf( + input.readObjectOrNull(redescribe(it.key, inboundKeyType), schemas, inboundKeyType, context), + input.readObjectOrNull(redescribe(it.value, inboundValueType), schemas, inboundValueType, context) + ) + }.toTypedArray() + creator.apply(arrayOf(matchingType.key, entries))!! + } + } + + override fun writeClassInfo(output: SerializationOutput) { + abortReadOnly() + } + + override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext, debugIndent: Int) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxMonthDaySerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxMonthDaySerializer.kt new file mode 100644 index 0000000000..cd489228b2 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxMonthDaySerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.MonthDayDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.MonthDaySerializer.MonthDayProxy +import java.time.MonthDay +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxMonthDaySerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(MonthDay::class.java), + proxyClass = classLoader.loadClassForSandbox(MonthDayProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(MonthDayDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(MonthDay::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOffsetDateTimeSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOffsetDateTimeSerializer.kt new file mode 100644 index 0000000000..54091ab2be --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOffsetDateTimeSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.OffsetDateTimeDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.OffsetDateTimeSerializer.OffsetDateTimeProxy +import java.time.OffsetDateTime +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxOffsetDateTimeSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(OffsetDateTime::class.java), + proxyClass = classLoader.loadClassForSandbox(OffsetDateTimeProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(OffsetDateTimeDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(OffsetDateTime::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOffsetTimeSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOffsetTimeSerializer.kt new file mode 100644 index 0000000000..284465a4de --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOffsetTimeSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.OffsetTimeDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.OffsetTimeSerializer.OffsetTimeProxy +import java.time.OffsetTime +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxOffsetTimeSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(OffsetTime::class.java), + proxyClass = classLoader.loadClassForSandbox(OffsetTimeProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(OffsetTimeDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(OffsetTime::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOptionalSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOptionalSerializer.kt new file mode 100644 index 0000000000..733ceabc93 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxOptionalSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.OptionalDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.OptionalSerializer.OptionalProxy +import java.util.* +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxOptionalSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(Optional::class.java), + proxyClass = classLoader.loadClassForSandbox(OptionalProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(OptionalDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(Optional::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPeriodSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPeriodSerializer.kt new file mode 100644 index 0000000000..31ad835f1c --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPeriodSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.PeriodDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.PeriodSerializer.PeriodProxy +import java.time.Period +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxPeriodSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(Period::class.java), + proxyClass = classLoader.loadClassForSandbox(PeriodProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(PeriodDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(Period::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPrimitiveSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPrimitiveSerializer.kt new file mode 100644 index 0000000000..b5eeb43927 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPrimitiveSerializer.kt @@ -0,0 +1,26 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.Function + +class SandboxPrimitiveSerializer( + clazz: Class<*>, + classLoader: SandboxClassLoader, + private val basicInput: Function +) : CustomSerializer.Is(classLoader.loadClassForSandbox(clazz)) { + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return basicInput.apply(obj)!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPublicKeySerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPublicKeySerializer.kt new file mode 100644 index 0000000000..4bbca81690 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxPublicKeySerializer.kt @@ -0,0 +1,40 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.PublicKeyDecoder +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.security.PublicKey +import java.util.Collections.singleton +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxPublicKeySerializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Implements(classLoader.loadClassForSandbox(PublicKey::class.java)) { + private val decoder: Function + + init { + val decodeTask = classLoader.loadClassForSandbox(PublicKeyDecoder::class.java).newInstance() + decoder = Function { inputs -> + executor.apply(decodeTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override val deserializationAliases: Set> = singleton(PublicKey::class.java) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + val bits = input.readObject(obj, schemas, ByteArray::class.java, context) as ByteArray + return decoder.apply(bits)!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxSymbolSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxSymbolSerializer.kt new file mode 100644 index 0000000000..95ce4a7694 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxSymbolSerializer.kt @@ -0,0 +1,38 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.SymbolDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.Symbol +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxSymbolSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction, + basicInput: Function +) : CustomSerializer.Is(classLoader.loadClassForSandbox(Symbol::class.java)) { + private val transformer: Function + + init { + val transformTask = classLoader.loadClassForSandbox(SymbolDeserializer::class.java).newInstance() + @Suppress("unchecked_cast") + transformer = basicInput.andThen { input -> + executor.apply(transformTask, input) + } as Function + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return transformer.apply((obj as Symbol).toString())!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxToStringSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxToStringSerializer.kt new file mode 100644 index 0000000000..765a406e1a --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxToStringSerializer.kt @@ -0,0 +1,44 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.CreateFromString +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Constructor +import java.lang.reflect.Type +import java.util.Collections.singleton +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxToStringSerializer( + unsafeClass: Class<*>, + classLoader: SandboxClassLoader, + executor: BiFunction, + basicInput: Function +) : CustomSerializer.Is(classLoader.loadClassForSandbox(unsafeClass)) { + private val creator: Function + + init { + val stringClass = classLoader.loadClass("sandbox.java.lang.String") + val createTask = classLoader.loadClassForSandbox(CreateFromString::class.java) + .getConstructor(Constructor::class.java) + .newInstance(clazz.getConstructor(stringClass)) + creator = basicInput.andThen { input -> + executor.apply(createTask, input) + } + } + + override val deserializationAliases: Set> = singleton(unsafeClass) + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return creator.apply(obj)!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedByteSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedByteSerializer.kt new file mode 100644 index 0000000000..30a208471a --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedByteSerializer.kt @@ -0,0 +1,36 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.UnsignedByteDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.UnsignedByte +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxUnsignedByteSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Is(classLoader.loadClassForSandbox(UnsignedByte::class.java)) { + private val transformer: Function + + init { + val transformTask = classLoader.loadClassForSandbox(UnsignedByteDeserializer::class.java).newInstance() + transformer = Function { inputs -> + executor.apply(transformTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return transformer.apply(byteArrayOf((obj as UnsignedByte).toByte()))!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedIntegerSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedIntegerSerializer.kt new file mode 100644 index 0000000000..15b7ee6bcb --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedIntegerSerializer.kt @@ -0,0 +1,36 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.UnsignedIntegerDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.UnsignedInteger +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxUnsignedIntegerSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Is(classLoader.loadClassForSandbox(UnsignedInteger::class.java)) { + private val transformer: Function + + init { + val transformTask = classLoader.loadClassForSandbox(UnsignedIntegerDeserializer::class.java).newInstance() + transformer = Function { inputs -> + executor.apply(transformTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return transformer.apply(intArrayOf((obj as UnsignedInteger).toInt()))!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedLongSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedLongSerializer.kt new file mode 100644 index 0000000000..d63d7469da --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedLongSerializer.kt @@ -0,0 +1,37 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.UnsignedLongDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.UnsignedLong +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.Collections.singleton +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxUnsignedLongSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Is(classLoader.loadClassForSandbox(UnsignedLong::class.java)) { + private val transformer: Function + + init { + val transformTask = classLoader.loadClassForSandbox(UnsignedLongDeserializer::class.java).newInstance() + transformer = Function { inputs -> + executor.apply(transformTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return transformer.apply(longArrayOf((obj as UnsignedLong).toLong()))!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} \ No newline at end of file diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedShortSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedShortSerializer.kt new file mode 100644 index 0000000000..6eaa91b9ef --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxUnsignedShortSerializer.kt @@ -0,0 +1,36 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.UnsignedShortDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.amqp.UnsignedShort +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxUnsignedShortSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Is(classLoader.loadClassForSandbox(UnsignedShort::class.java)) { + private val transformer: Function + + init { + val transformTask = classLoader.loadClassForSandbox(UnsignedShortDeserializer::class.java).newInstance() + transformer = Function { inputs -> + executor.apply(transformTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + return transformer.apply(shortArrayOf((obj as UnsignedShort).toShort()))!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxX509CRLSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxX509CRLSerializer.kt new file mode 100644 index 0000000000..a9f4ae85a2 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxX509CRLSerializer.kt @@ -0,0 +1,40 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.X509CRLDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.security.cert.X509CRL +import java.util.Collections.singleton +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxX509CRLSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Implements(classLoader.loadClassForSandbox(X509CRL::class.java)) { + private val generator: Function + + init { + val generateTask = classLoader.loadClassForSandbox(X509CRLDeserializer::class.java).newInstance() + generator = Function { inputs -> + executor.apply(generateTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override val deserializationAliases: Set> = singleton(X509CRL::class.java) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + val bits = input.readObject(obj, schemas, ByteArray::class.java, context) as ByteArray + return generator.apply(bits)!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxX509CertificateSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxX509CertificateSerializer.kt new file mode 100644 index 0000000000..ccb8d3c266 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxX509CertificateSerializer.kt @@ -0,0 +1,40 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.core.serialization.SerializationContext +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.X509CertificateDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.codec.Data +import java.lang.reflect.Type +import java.security.cert.X509Certificate +import java.util.Collections.singleton +import java.util.function.BiFunction +import java.util.function.Function + +class SandboxX509CertificateSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction +) : CustomSerializer.Implements(classLoader.loadClassForSandbox(X509Certificate::class.java)) { + private val generator: Function + + init { + val generateTask = classLoader.loadClassForSandbox(X509CertificateDeserializer::class.java).newInstance() + generator = Function { inputs -> + executor.apply(generateTask, inputs) + } + } + + override val schemaForDocumentation: Schema = Schema(emptyList()) + + override val deserializationAliases: Set> = singleton(X509Certificate::class.java) + + override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext): Any { + val bits = input.readObject(obj, schemas, ByteArray::class.java, context) as ByteArray + return generator.apply(bits)!! + } + + override fun writeDescribedObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext) { + abortReadOnly() + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxYearMonthSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxYearMonthSerializer.kt new file mode 100644 index 0000000000..6c91ca9a03 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxYearMonthSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.YearMonthDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.YearMonthSerializer.YearMonthProxy +import java.time.YearMonth +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxYearMonthSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(YearMonth::class.java), + proxyClass = classLoader.loadClassForSandbox(YearMonthProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(YearMonthDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(YearMonth::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxYearSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxYearSerializer.kt new file mode 100644 index 0000000000..3d01eb1ff8 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxYearSerializer.kt @@ -0,0 +1,31 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.YearDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.YearSerializer.YearProxy +import java.time.Year +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxYearSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(Year::class.java), + proxyClass = classLoader.loadClassForSandbox(YearProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(YearDeserializer::class.java).newInstance() + + override val deserializationAliases: Set> = singleton(Year::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxZoneIdSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxZoneIdSerializer.kt new file mode 100644 index 0000000000..6ca73ee520 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxZoneIdSerializer.kt @@ -0,0 +1,33 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.ZoneIdDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.ZoneIdSerializer.ZoneIdProxy +import java.time.ZoneId +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxZoneIdSerializer( + classLoader: SandboxClassLoader, + private val executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(ZoneId::class.java), + proxyClass = classLoader.loadClassForSandbox(ZoneIdProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(ZoneIdDeserializer::class.java).newInstance() + + override val revealSubclassesInSchema: Boolean = true + + override val deserializationAliases: Set> = singleton(ZoneId::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return executor.apply(task, proxy)!! + } +} diff --git a/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxZonedDateTimeSerializer.kt b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxZonedDateTimeSerializer.kt new file mode 100644 index 0000000000..5ef4f04f52 --- /dev/null +++ b/src/main/kotlin/net/corda/djvm/serialization/serializers/SandboxZonedDateTimeSerializer.kt @@ -0,0 +1,48 @@ +package net.corda.djvm.serialization.serializers + +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.serialization.deserializers.ZonedDateTimeDeserializer +import net.corda.djvm.serialization.loadClassForSandbox +import net.corda.serialization.internal.amqp.CustomSerializer +import net.corda.serialization.internal.amqp.SerializerFactory +import net.corda.serialization.internal.amqp.custom.ZonedDateTimeSerializer.ZonedDateTimeProxy +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.util.Collections.singleton +import java.util.function.BiFunction + +class SandboxZonedDateTimeSerializer( + classLoader: SandboxClassLoader, + executor: BiFunction, + factory: SerializerFactory +) : CustomSerializer.Proxy( + clazz = classLoader.loadClassForSandbox(ZonedDateTime::class.java), + proxyClass = classLoader.loadClassForSandbox(ZonedDateTimeProxy::class.java), + factory = factory +) { + private val task = classLoader.loadClassForSandbox(ZonedDateTimeDeserializer::class.java).newInstance() + private val creator: BiFunction + + init { + val createTask = clazz.getMethod( + "createDJVM", + classLoader.loadClassForSandbox(LocalDateTime::class.java), + classLoader.loadClassForSandbox(ZoneOffset::class.java), + classLoader.loadClassForSandbox(ZoneId::class.java) + ) + creator = executor.andThen { input -> + @Suppress("unchecked_cast") + createTask(null, *(input as Array))!! + } + } + + override val deserializationAliases: Set> = singleton(ZonedDateTime::class.java) + + override fun toProxy(obj: Any): Any = abortReadOnly() + + override fun fromProxy(proxy: Any): Any { + return creator.apply(task, proxy)!! + } +} diff --git a/src/test/java/greymalkin/ExternalData.java b/src/test/java/greymalkin/ExternalData.java new file mode 100644 index 0000000000..8774478bdb --- /dev/null +++ b/src/test/java/greymalkin/ExternalData.java @@ -0,0 +1,13 @@ +package greymalkin; + +public class ExternalData { + private final String data; + + public ExternalData(String data) { + this.data = data; + } + + public String getData() { + return data; + } +} diff --git a/src/test/java/greymalkin/ExternalEnum.java b/src/test/java/greymalkin/ExternalEnum.java new file mode 100644 index 0000000000..2180693367 --- /dev/null +++ b/src/test/java/greymalkin/ExternalEnum.java @@ -0,0 +1,11 @@ +package greymalkin; + +import net.corda.core.serialization.CordaSerializable; + +@SuppressWarnings("unused") +@CordaSerializable +public enum ExternalEnum { + DOH, + RAY, + ME +} diff --git a/src/test/java/net/corda/djvm/serialization/InnocentData.java b/src/test/java/net/corda/djvm/serialization/InnocentData.java new file mode 100644 index 0000000000..c4c2bd24e8 --- /dev/null +++ b/src/test/java/net/corda/djvm/serialization/InnocentData.java @@ -0,0 +1,22 @@ +package net.corda.djvm.serialization; + +import net.corda.core.serialization.CordaSerializable; + +@CordaSerializable +public class InnocentData { + private final String message; + private final Short number; + + public InnocentData(String message, Short number) { + this.message = message; + this.number = number; + } + + public String getMessage() { + return message; + } + + public Short getNumber() { + return number; + } +} diff --git a/src/test/java/net/corda/djvm/serialization/MultiConstructorData.java b/src/test/java/net/corda/djvm/serialization/MultiConstructorData.java new file mode 100644 index 0000000000..f08b41a148 --- /dev/null +++ b/src/test/java/net/corda/djvm/serialization/MultiConstructorData.java @@ -0,0 +1,53 @@ +package net.corda.djvm.serialization; + +import net.corda.core.serialization.ConstructorForDeserialization; +import net.corda.core.serialization.CordaSerializable; + +@SuppressWarnings({"unused", "WeakerAccess"}) +@CordaSerializable +public class MultiConstructorData { + private final String message; + private final long bigNumber; + private final Character tag; + + @ConstructorForDeserialization + public MultiConstructorData(String message, long bigNumber, Character tag) { + this.message = message; + this.bigNumber = bigNumber; + this.tag = tag; + } + + public MultiConstructorData(String message, long bigNumber) { + this(message, bigNumber, null); + } + + public MultiConstructorData(String message, char tag) { + this(message, 0, tag); + } + + public MultiConstructorData(String message) { + this(message, 0); + } + + public String getMessage() { + return message; + } + + public long getBigNumber() { + return bigNumber; + } + + public Character getTag() { + return tag; + } + + @SuppressWarnings("StringBufferReplaceableByString") + @Override + public String toString() { + return new StringBuilder("MultiConstructor[message='").append(message) + .append("', bigNumber=").append(bigNumber) + .append(", tag=").append(tag) + .append(']') + .toString(); + } +} diff --git a/src/test/java/net/corda/djvm/serialization/VeryEvilData.java b/src/test/java/net/corda/djvm/serialization/VeryEvilData.java new file mode 100644 index 0000000000..1fcbc0dec2 --- /dev/null +++ b/src/test/java/net/corda/djvm/serialization/VeryEvilData.java @@ -0,0 +1,15 @@ +package net.corda.djvm.serialization; + +@SuppressWarnings("unused") +public class VeryEvilData extends InnocentData { + static { + if (!VeryEvilData.class.getName().startsWith("sandbox.")) { + // Execute our evil payload OUTSIDE the sandbox! + throw new IllegalStateException("Victory is mine!"); + } + } + + public VeryEvilData(String message, Short number) { + super(message, number); + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeBigDecimalTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeBigDecimalTest.kt new file mode 100644 index 0000000000..58dc242a98 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeBigDecimalTest.kt @@ -0,0 +1,51 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.math.BigDecimal +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeBigDecimalTest : TestBase(KOTLIN) { + companion object { + const val VERY_BIG_DECIMAL = 994349993939.32737232 + } + + @Test + fun `test deserializing big decimal`() { + val bigDecimal = BigDecimalData(BigDecimal.valueOf(VERY_BIG_DECIMAL)) + val data = bigDecimal.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxBigInteger = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowBigDecimal::class.java).newInstance(), + sandboxBigInteger + ) ?: fail("Result cannot be null") + + assertEquals(ShowBigDecimal().apply(bigDecimal), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowBigDecimal : Function { + override fun apply(data: BigDecimalData): String { + return with(data) { + "BigDecimal: $number" + } + } + } +} + +@CordaSerializable +data class BigDecimalData(val number: BigDecimal) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeBigIntegerTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeBigIntegerTest.kt new file mode 100644 index 0000000000..b89e2443ee --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeBigIntegerTest.kt @@ -0,0 +1,51 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.math.BigInteger +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeBigIntegerTest : TestBase(KOTLIN) { + companion object { + const val VERY_BIG_NUMBER = 1234567890123456789 + } + + @Test + fun `test deserializing big integer`() { + val bigInteger = BigIntegerData(BigInteger.valueOf(VERY_BIG_NUMBER)) + val data = bigInteger.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxBigInteger = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowBigInteger::class.java).newInstance(), + sandboxBigInteger + ) ?: fail("Result cannot be null") + + assertEquals(ShowBigInteger().apply(bigInteger), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowBigInteger : Function { + override fun apply(data: BigIntegerData): String { + return with(data) { + "BigInteger: $number" + } + } + } +} + +@CordaSerializable +data class BigIntegerData(val number: BigInteger) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeBitSetTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeBitSetTest.kt new file mode 100644 index 0000000000..5b59a1fe4f --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeBitSetTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.* +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeBitSetTest : TestBase(KOTLIN) { + @Test + fun `test deserializing bitset`() { + val bitSet = BitSet.valueOf(byteArrayOf(0x00, 0x70, 0x55, 0x3A, 0x48, 0x12)) + val data = bitSet.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxBitSet = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowBitSet::class.java).newInstance(), + sandboxBitSet + ) ?: fail("Result cannot be null") + + assertEquals(bitSet.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowBitSet : Function { + override fun apply(bitSet: BitSet): String { + return bitSet.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeCertificatesTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeCertificatesTest.kt new file mode 100644 index 0000000000..ce8b0b33d5 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeCertificatesTest.kt @@ -0,0 +1,135 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.assertj.core.api.Assertions.assertThat +import org.bouncycastle.asn1.x509.CRLReason +import org.bouncycastle.asn1.x500.X500Name +import org.bouncycastle.cert.X509v2CRLBuilder +import org.bouncycastle.cert.jcajce.JcaX509CRLConverter +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.security.KeyPairGenerator +import java.security.cert.CertPath +import java.security.cert.CertificateFactory +import java.security.cert.X509CRL +import java.security.cert.X509Certificate +import java.util.Date +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeCertificatesTest : TestBase(KOTLIN) { + companion object { + // The sandbox's localisation may not match that of the host. + // E.g. line separator characters and time zone format. + fun localise(str: String): String { + return str.replace("\n", System.lineSeparator()) + } + + val factory: CertificateFactory = CertificateFactory.getInstance("X.509") + lateinit var certificate: X509Certificate + + @Suppress("unused") + @BeforeAll + @JvmStatic + fun loadCertificate() { + certificate = this::class.java.classLoader.getResourceAsStream("testing.cert")?.use { input -> + factory.generateCertificate(input) as X509Certificate + } ?: fail("Certificate not found") + } + } + + @Test + fun `test deserialize certificate path`() { + val certPath = factory.generateCertPath(listOf(certificate)) + val data = certPath.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxCertPath = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowCertPath::class.java).newInstance(), + sandboxCertPath + ) ?: fail("Result cannot be null") + + assertEquals(ShowCertPath().apply(certPath), localise(result.toString())) + assertThat(result::class.java.name).startsWith("sandbox.") + } + } + + class ShowCertPath : Function { + override fun apply(certPath: CertPath): String { + return "CertPath -> $certPath" + } + } + + @Test + fun `test deserialize X509 certificate`() { + val data = certificate.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxCertificate = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowCertificate::class.java).newInstance(), + sandboxCertificate + ) ?: fail("Result cannot be null") + + assertEquals(ShowCertificate().apply(certificate), localise(result.toString())) + assertThat(result::class.java.name).startsWith("sandbox.") + } + } + + class ShowCertificate : Function { + override fun apply(certificate: X509Certificate): String { + return "X.509 Certificate -> $certificate" + } + } + + @Test + fun `test X509 CRL`() { + val caKeyPair = KeyPairGenerator.getInstance("RSA") + .generateKeyPair() + val signer = JcaContentSignerBuilder("SHA256WithRSAEncryption") + .build(caKeyPair.private) + + val now = Date() + val crl = with(X509v2CRLBuilder(X500Name("CN=Test CA"), now)) { + addCRLEntry(certificate.serialNumber, now, CRLReason.privilegeWithdrawn) + JcaX509CRLConverter().getCRL(build(signer)) + } + val data = crl.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxCRL = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowCRL::class.java).newInstance(), + sandboxCRL + ) ?: fail("Result cannot be null") + + assertEquals(ShowCRL().apply(crl), localise(result.toString())) + assertThat(result::class.java.name).startsWith("sandbox.") + } + } + + class ShowCRL : Function { + override fun apply(crl: X509CRL): String { + return "X.509 CRL -> $crl" + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeClassTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeClassTest.kt new file mode 100644 index 0000000000..13b7a4f30e --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeClassTest.kt @@ -0,0 +1,60 @@ +package net.corda.djvm.serialization + +import greymalkin.ExternalData +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.io.NotSerializableException +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeClassTest : TestBase(KOTLIN) { + @Test + fun `test deserializing existing class`() { + val myClass = ExternalData::class.java + val data = myClass.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxInstant = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowClass::class.java).newInstance(), + sandboxInstant + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.${myClass.name}", result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + @Test + fun `test deserializing missing class`() { + // The DJVM will refuse to find this class because it belongs to net.corda.djvm.**. + val myClass = VeryEvilData::class.java + val data = myClass.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val ex = assertThrows{ data.deserializeFor(classLoader) } + assertThat(ex) + .isExactlyInstanceOf(NotSerializableException::class.java) + .hasMessageContaining("VeryEvilData was not found by the node,") + } + } +} + +class ShowClass : Function, String> { + override fun apply(type: Class<*>): String { + return type.name + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeCollectionsTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeCollectionsTest.kt new file mode 100644 index 0000000000..2548ad88d5 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeCollectionsTest.kt @@ -0,0 +1,227 @@ +package net.corda.djvm.serialization + +import greymalkin.ExternalEnum +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.core.utilities.NonEmptySet +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.* +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeCollectionsTest : TestBase(KOTLIN) { + @Test + fun `test deserializing string list`() { + val stringList = StringList(listOf("Hello", "World", "!")) + val data = stringList.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxList = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringList::class.java).newInstance(), + sandboxList + ) ?: fail("Result cannot be null") + + assertEquals(stringList.lines.joinToString(), result.toString()) + assertEquals("Hello, World, !", result.toString()) + } + } + + class ShowStringList : Function { + override fun apply(data: StringList): String { + return data.lines.joinToString() + } + } + + @Test + fun `test deserializing integer set`() { + val integerSet = IntegerSet(linkedSetOf(10, 3, 15, 2, 10)) + val data = integerSet.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxSet = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowIntegerSet::class.java).newInstance(), + sandboxSet + ) ?: fail("Result cannot be null") + + assertEquals(integerSet.numbers.joinToString(), result.toString()) + assertEquals("10, 3, 15, 2", result.toString()) + } + } + + class ShowIntegerSet : Function { + override fun apply(data: IntegerSet): String { + return data.numbers.joinToString() + } + } + + @Test + fun `test deserializing integer sorted set`() { + val integerSortedSet = IntegerSortedSet(sortedSetOf(10, 15, 1000, 3, 2, 10)) + val data = integerSortedSet.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxSet = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowIntegerSortedSet::class.java).newInstance(), + sandboxSet + ) ?: fail("Result cannot be null") + + assertEquals(integerSortedSet.numbers.joinToString(), result.toString()) + assertEquals("2, 3, 10, 15, 1000", result.toString()) + } + } + + class ShowIntegerSortedSet : Function { + override fun apply(data: IntegerSortedSet): String { + return data.numbers.joinToString() + } + } + + @Test + fun `test deserializing long navigable set`() { + val longNavigableSet = LongNavigableSet(sortedSetOf(99955L, 10, 15, 1000, 3, 2, 10)) + val data = longNavigableSet.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxSet = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowLongNavigableSet::class.java).newInstance(), + sandboxSet + ) ?: fail("Result cannot be null") + + assertEquals(longNavigableSet.numbers.joinToString(), result.toString()) + assertEquals("2, 3, 10, 15, 1000, 99955", result.toString()) + } + } + + class ShowLongNavigableSet : Function { + override fun apply(data: LongNavigableSet): String { + return data.numbers.joinToString() + } + } + + @Test + fun `test deserializing short collection`() { + val shortCollection = ShortCollection(listOf(10, 200, 3000)) + val data = shortCollection.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxCollection = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowShortCollection::class.java).newInstance(), + sandboxCollection + ) ?: fail("Result cannot be null") + + assertEquals(shortCollection.numbers.joinToString(), result.toString()) + assertEquals("10, 200, 3000", result.toString()) + } + } + + class ShowShortCollection : Function { + override fun apply(data: ShortCollection): String { + return data.numbers.joinToString() + } + } + + @Test + fun `test deserializing non-empty string set`() { + val nonEmptyStrings = NonEmptyStringSet(NonEmptySet.of("Hello", "World", "!")) + val data = nonEmptyStrings.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxSet = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowNonEmptyStringSet::class.java).newInstance(), + sandboxSet + ) ?: fail("Result cannot be null") + + assertEquals(nonEmptyStrings.lines.joinToString(), result.toString()) + assertEquals("Hello, World, !", result.toString()) + } + } + + class ShowNonEmptyStringSet : Function { + override fun apply(data: NonEmptyStringSet): String { + return data.lines.joinToString() + } + } + + @Test + fun `test deserializing enum set`() { + val enumSet = HasEnumSet(EnumSet.of(ExternalEnum.DOH)) + val data = enumSet.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxSet = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowHasEnumSet::class.java).newInstance(), + sandboxSet + ) ?: fail("Result cannot be null") + + assertEquals(enumSet.values.toString(), result.toString()) + assertEquals("[DOH]", result.toString()) + } + } + + class ShowHasEnumSet : Function { + override fun apply(data: HasEnumSet): String { + return data.values.toString() + } + } +} + +@CordaSerializable +class StringList(val lines: List) + +@CordaSerializable +class IntegerSet(val numbers: Set) + +@CordaSerializable +class IntegerSortedSet(val numbers: SortedSet) + +@CordaSerializable +class LongNavigableSet(val numbers: NavigableSet) + +@CordaSerializable +class ShortCollection(val numbers: Collection) + +@CordaSerializable +class NonEmptyStringSet(val lines: NonEmptySet) + +@CordaSerializable +class HasEnumSet(val values: EnumSet) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeCurrencyTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeCurrencyTest.kt new file mode 100644 index 0000000000..aa5870951e --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeCurrencyTest.kt @@ -0,0 +1,47 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.* +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeCurrencyTest : TestBase(KOTLIN) { + @Test + fun `test deserializing currency`() { + val currency = CurrencyData(Currency.getInstance("GBP")) + val data = currency.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxCurrency = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowCurrency::class.java).newInstance(), + sandboxCurrency + ) ?: fail("Result cannot be null") + + assertEquals(ShowCurrency().apply(currency), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowCurrency : Function { + override fun apply(data: CurrencyData): String { + return with(data) { + "Currency: $currency" + } + } + } +} + +@CordaSerializable +data class CurrencyData(val currency: Currency) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeEnumSetTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeEnumSetTest.kt new file mode 100644 index 0000000000..2dba16c4ed --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeEnumSetTest.kt @@ -0,0 +1,45 @@ +package net.corda.djvm.serialization + +import greymalkin.ExternalEnum +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.KOTLIN +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource +import java.util.* +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeEnumSetTest : TestBase(KOTLIN) { + @ParameterizedTest + @EnumSource(ExternalEnum::class) + fun `test deserialize enum set`(value: ExternalEnum) { + val enumSet = EnumSet.of(value) + val data = enumSet.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxEnumSet = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowEnumSet::class.java).newInstance(), + sandboxEnumSet + ) ?: fail("Result cannot be null") + + assertEquals(ShowEnumSet().apply(enumSet), result.toString()) + assertEquals("EnumSet: [$value]'", result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowEnumSet : Function, String> { + override fun apply(input: EnumSet<*>): String { + return "EnumSet: $input'" + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeEnumTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeEnumTest.kt new file mode 100644 index 0000000000..2ff7d78e39 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeEnumTest.kt @@ -0,0 +1,57 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.KOTLIN +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeEnumTest : TestBase(KOTLIN) { + @ParameterizedTest + @EnumSource(ExampleEnum::class) + fun `test deserialize basic enum`(value: ExampleEnum) { + val example = ExampleData(value) + val data =example.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxExample = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowExampleData::class.java).newInstance(), + sandboxExample + ) ?: fail("Result cannot be null") + + assertEquals(ShowExampleData().apply(example), result.toString()) + assertEquals("Example: name='${value.name}', ordinal='${value.ordinal}'", result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowExampleData : Function { + override fun apply(input: ExampleData): String { + return with(input) { + "Example: name='${value.name}', ordinal='${value.ordinal}'" + } + } + } +} + +@Suppress("unused") +@CordaSerializable +enum class ExampleEnum { + ONE, + TWO, + THREE +} + +@CordaSerializable +data class ExampleData(val value: ExampleEnum) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeGenericsTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeGenericsTest.kt new file mode 100644 index 0000000000..5e887e1b4b --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeGenericsTest.kt @@ -0,0 +1,81 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Disabled +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeGenericsTest : TestBase(KOTLIN) { + @Disabled + @Test + fun `test deserializing generic wrapper`() { + val wrappedString = GenericWrapper(data = "Hello World!") + val data = wrappedString.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxWrapper = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowGenericWrapper::class.java).newInstance(), + sandboxWrapper + ) ?: fail("Result cannot be null") + + assertEquals("Hello World!", result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowGenericWrapper : Function, String> { + override fun apply(input: GenericWrapper): String { + return input.data + } + } + + @Test + fun `test deserializing concrete wrapper`() { + val wrapped = ConcreteWrapper( + first = GenericWrapper("Hello World"), + second = GenericWrapper('!') + ) + val data = wrapped.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxWrapped = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowConcreteWrapper::class.java).newInstance(), + sandboxWrapped + ) ?: fail("Result cannot be null") + + assertEquals("Concrete: first='Hello World', second='!'", result.toString()) + } + } + + class ShowConcreteWrapper : Function { + override fun apply(input: ConcreteWrapper): String { + return "Concrete: first='${input.first.data}', second='${input.second.data}'" + } + } +} + +@CordaSerializable +data class GenericWrapper(val data: T) + +@CordaSerializable +data class ConcreteWrapper( + val first: GenericWrapper, + val second: GenericWrapper +) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeInstantTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeInstantTest.kt new file mode 100644 index 0000000000..2316de6dfa --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeInstantTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.Instant +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeInstantTest : TestBase(KOTLIN) { + @Test + fun `test deserializing instant`() { + val instant = Instant.now() + val data = instant.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxInstant = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowInstant::class.java).newInstance(), + sandboxInstant + ) ?: fail("Result cannot be null") + + assertEquals(instant.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowInstant : Function { + override fun apply(instant: Instant): String { + return instant.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeJavaWithMultipleConstructorsTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeJavaWithMultipleConstructorsTest.kt new file mode 100644 index 0000000000..719d28a03e --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeJavaWithMultipleConstructorsTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail + +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeJavaWithMultipleConstructorsTest : TestBase(KOTLIN) { + @Test + fun `test deserializing existing class`() { + val multiData = MultiConstructorData("Hello World", Long.MAX_VALUE, '!') + val data = multiData.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxData = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowMultiData::class.java).newInstance(), + sandboxData + ) ?: fail("Result cannot be null") + + assertThat(result.toString()) + .isEqualTo("MultiConstructor[message='Hello World', bigNumber=9223372036854775807, tag=!]") + } + } + + class ShowMultiData : Function { + override fun apply(data: MultiConstructorData): String { + return data.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalDateTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalDateTest.kt new file mode 100644 index 0000000000..007ca86548 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalDateTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.LocalDate +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeLocalDateTest : TestBase(KOTLIN) { + @Test + fun `test deserializing local date`() { + val date = LocalDate.now() + val data = date.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxDate = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowLocalDate::class.java).newInstance(), + sandboxDate + ) ?: fail("Result cannot be null") + + assertEquals(date.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowLocalDate : Function { + override fun apply(date: LocalDate): String { + return date.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalDateTimeTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalDateTimeTest.kt new file mode 100644 index 0000000000..1dd9debfbe --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalDateTimeTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.LocalDateTime +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeLocalDateTimeTest : TestBase(KOTLIN) { + @Test + fun `test deserializing local date-time`() { + val dateTime = LocalDateTime.now() + val data = dateTime.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxDateTime = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowLocalDateTime::class.java).newInstance(), + sandboxDateTime + ) ?: fail("Result cannot be null") + + assertEquals(dateTime.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowLocalDateTime : Function { + override fun apply(dateTime: LocalDateTime): String { + return dateTime.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalTimeTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalTimeTest.kt new file mode 100644 index 0000000000..2bfb4c2956 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeLocalTimeTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.LocalTime +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeLocalTimeTest : TestBase(KOTLIN) { + @Test + fun `test deserializing local time`() { + val time = LocalTime.now() + val data = time.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxTime = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowLocalTime::class.java).newInstance(), + sandboxTime + ) ?: fail("Result cannot be null") + + assertEquals(time.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowLocalTime : Function { + override fun apply(time: LocalTime): String { + return time.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeMapsTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeMapsTest.kt new file mode 100644 index 0000000000..b4f8d692ef --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeMapsTest.kt @@ -0,0 +1,211 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.* +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeMapsTest : TestBase(KOTLIN) { + @Test + fun `test deserializing map`() { + val stringMap = StringMap(mapOf("Open" to "Hello World", "Close" to "Goodbye, Cruel World")) + val data = stringMap.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxMap = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringMap::class.java).newInstance(), + sandboxMap + ) ?: fail("Result cannot be null") + + assertEquals(stringMap.values.entries.joinToString(), result.toString()) + assertEquals("Open=Hello World, Close=Goodbye, Cruel World", result.toString()) + } + } + + class ShowStringMap : Function { + override fun apply(data: StringMap): String { + return data.values.entries.joinToString() + } + } + + @Test + fun `test deserializing sorted map`() { + val sortedMap = StringSortedMap(sortedMapOf( + 100 to "Goodbye, Cruel World", + 10 to "Hello World", + 50 to "Having Fun!" + )) + val data = sortedMap.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxMap = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringSortedMap::class.java).newInstance(), + sandboxMap + ) ?: fail("Result cannot be null") + + assertEquals(sortedMap.values.entries.joinToString(), result.toString()) + assertEquals("10=Hello World, 50=Having Fun!, 100=Goodbye, Cruel World", result.toString()) + } + } + + class ShowStringSortedMap : Function { + override fun apply(data: StringSortedMap): String { + return data.values.entries.joinToString() + } + } + + @Test + fun `test deserializing navigable map`() { + val navigableMap = StringNavigableMap(mapOf( + 10000L to "Goodbye, Cruel World", + 1000L to "Hello World", + 5000L to "Having Fun!" + ).toMap(TreeMap())) + val data = navigableMap.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxMap = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringNavigableMap::class.java).newInstance(), + sandboxMap + ) ?: fail("Result cannot be null") + + assertEquals(navigableMap.values.entries.joinToString(), result.toString()) + assertEquals("1000=Hello World, 5000=Having Fun!, 10000=Goodbye, Cruel World", result.toString()) + } + } + + class ShowStringNavigableMap : Function { + override fun apply(data: StringNavigableMap): String { + return data.values.entries.joinToString() + } + } + + @Test + fun `test deserializing linked hash map`() { + val linkedHashMap = StringLinkedHashMap(linkedMapOf( + "Close" to "Goodbye, Cruel World", + "Open" to "Hello World", + "During" to "Having Fun!" + )) + val data = linkedHashMap.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxMap = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringLinkedHashMap::class.java).newInstance(), + sandboxMap + ) ?: fail("Result cannot be null") + + assertEquals(linkedHashMap.values.entries.joinToString(), result.toString()) + assertEquals("Close=Goodbye, Cruel World, Open=Hello World, During=Having Fun!", result.toString()) + } + } + + class ShowStringLinkedHashMap : Function { + override fun apply(data: StringLinkedHashMap): String { + return data.values.entries.joinToString() + } + } + + @Test + fun `test deserializing tree map`() { + val treeMap = StringTreeMap(mapOf( + 10000 to "Goodbye, Cruel World", + 1000 to "Hello World", + 5000 to "Having Fun!" + ).toMap(TreeMap())) + val data = treeMap.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxMap = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringTreeMap::class.java).newInstance(), + sandboxMap + ) ?: fail("Result cannot be null") + + assertEquals(treeMap.values.entries.joinToString(), result.toString()) + assertEquals("1000=Hello World, 5000=Having Fun!, 10000=Goodbye, Cruel World", result.toString()) + } + } + + class ShowStringTreeMap : Function { + override fun apply(data: StringTreeMap): String { + return data.values.entries.joinToString() + } + } + + @Test + fun `test deserializing enum map`() { + val enumMap = EnumMap(mapOf( + ExampleEnum.ONE to "One!", + ExampleEnum.TWO to "Two!" + )) + val data = enumMap.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxMap = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowEnumMap::class.java).newInstance(), + sandboxMap + ) ?: fail("Result cannot be null") + + assertEquals(enumMap.toString(), result.toString()) + assertEquals("{ONE=One!, TWO=Two!}", result.toString()) + } + } + + class ShowEnumMap : Function, String> { + override fun apply(data: EnumMap<*, String>): String { + return data.toString() + } + } +} + +@CordaSerializable +class StringMap(val values: Map) + +@CordaSerializable +class StringSortedMap(val values: SortedMap) + +@CordaSerializable +class StringNavigableMap(val values: NavigableMap) + +@CordaSerializable +class StringLinkedHashMap(val values: LinkedHashMap) + +@CordaSerializable +class StringTreeMap(val values: TreeMap) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeMonthDayTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeMonthDayTest.kt new file mode 100644 index 0000000000..b9e7fac533 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeMonthDayTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.MonthDay +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeMonthDayTest : TestBase(KOTLIN) { + @Test + fun `test deserializing month-day`() { + val monthDay = MonthDay.now() + val data = monthDay.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxMonthDay = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowMonthDay::class.java).newInstance(), + sandboxMonthDay + ) ?: fail("Result cannot be null") + + assertEquals(monthDay.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowMonthDay : Function { + override fun apply(monthDay: MonthDay): String { + return monthDay.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeObjectArraysTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeObjectArraysTest.kt new file mode 100644 index 0000000000..b1b1a74928 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeObjectArraysTest.kt @@ -0,0 +1,318 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.* +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeObjectArraysTest : TestBase(KOTLIN) { + @Test + fun `test deserializing string array`() { + val stringArray = HasStringArray(arrayOf("Hello", "World", "!")) + val data = stringArray.serialize() + assertEquals("Hello, World, !", ShowStringArray().apply(stringArray)) + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals(SANDBOX_STRING, result::class.java.name) + assertEquals("Hello, World, !", result.toString()) + } + } + + class ShowStringArray : Function { + override fun apply(data: HasStringArray): String { + return data.lines.joinToString() + } + } + + @Test + fun `test deserializing character array`() { + val charArray = HasCharacterArray(arrayOf('H', 'e', 'l', 'l', 'o', '!')) + val data = charArray.serialize() + assertEquals("Hello!", ShowCharacterArray().apply(charArray)) + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowCharacterArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals(SANDBOX_STRING, result::class.java.name) + assertEquals("Hello!", result.toString()) + } + } + + class ShowCharacterArray : Function { + override fun apply(data: HasCharacterArray): String { + return data.letters.joinTo(StringBuilder(), separator = "").toString() + } + } + + @Test + fun `test deserializing long array`() { + val longArray = HasLongArray(arrayOf(1000, 2000, 3000, 4000, 5000)) + val data = longArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowLongArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Long", result::class.java.name) + assertEquals("15000", result.toString()) + } + } + + class ShowLongArray : Function { + override fun apply(data: HasLongArray): Long { + return data.longs.sum() + } + } + + @Test + fun `test deserializing integer array`() { + val integerArray = HasIntegerArray(arrayOf(100, 200, 300, 400, 500)) + val data = integerArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowIntegerArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Integer", result::class.java.name) + assertEquals("1500", result.toString()) + } + } + + class ShowIntegerArray : Function { + override fun apply(data: HasIntegerArray): Int { + return data.integers.sum() + } + } + + @Test + fun `test deserializing short array`() { + val shortArray = HasShortArray(arrayOf(100, 200, 300, 400, 500)) + val data = shortArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowShortArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Integer", result::class.java.name) + assertEquals("1500", result.toString()) + } + } + + class ShowShortArray : Function { + override fun apply(data: HasShortArray): Int { + return data.shorts.sum() + } + } + + @Test + fun `test deserializing byte array`() { + val byteArray = HasByteArray(arrayOf(10, 20, 30, 40, 50)) + val data = byteArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowByteArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Integer", result::class.java.name) + assertEquals("150", result.toString()) + } + } + + class ShowByteArray : Function { + override fun apply(data: HasByteArray): Int { + return data.bytes.sum() + } + } + + @Test + fun `test deserializing double array`() { + val doubleArray = HasDoubleArray(arrayOf(1000.0, 2000.0, 3000.0, 4000.0, 5000.0)) + val data = doubleArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowDoubleArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Double", result::class.java.name) + assertEquals("15000.0", result.toString()) + } + } + + class ShowDoubleArray : Function { + override fun apply(data: HasDoubleArray): Double { + return data.doubles.sum() + } + } + + @Test + fun `test deserializing float array`() { + val floatArray = HasFloatArray(arrayOf(10.0f, 20.0f, 30.0f, 40.0f, 50.0f)) + val data = floatArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowFloatArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Float", result::class.java.name) + assertEquals("150.0", result.toString()) + } + } + + class ShowFloatArray : Function { + override fun apply(data: HasFloatArray): Float { + return data.floats.sum() + } + } + + @Test + fun `test deserializing boolean array`() { + val booleanArray = HasBooleanArray(arrayOf(true, true, true)) + val data = booleanArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowBooleanArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Boolean", result::class.java.name) + assertEquals("true", result.toString()) + } + } + + class ShowBooleanArray : Function { + override fun apply(data: HasBooleanArray): Boolean { + return data.bools.all { it } + } + } + + @Test + fun `test deserializing uuid array`() { + val uuid = UUID.randomUUID() + val uuidArray = HasUUIDArray(arrayOf(uuid)) + val data = uuidArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowUUIDArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals(SANDBOX_STRING, result::class.java.name) + assertEquals(uuid.toString(), result.toString()) + } + } + + class ShowUUIDArray : Function { + override fun apply(data: HasUUIDArray): String { + return data.uuids.joinTo(StringBuilder()).toString() + } + } +} + +@CordaSerializable +class HasStringArray(val lines: Array) + +@CordaSerializable +class HasCharacterArray(val letters: Array) + +@CordaSerializable +class HasLongArray(val longs: Array) + +@CordaSerializable +class HasIntegerArray(val integers: Array) + +@CordaSerializable +class HasShortArray(val shorts: Array) + +@CordaSerializable +class HasByteArray(val bytes: Array) + +@CordaSerializable +class HasDoubleArray(val doubles: Array) + +@CordaSerializable +class HasFloatArray(val floats: Array) + +@CordaSerializable +class HasBooleanArray(val bools: Array) + +@CordaSerializable +class HasUUIDArray(val uuids: Array) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeOffsetDateTimeTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeOffsetDateTimeTest.kt new file mode 100644 index 0000000000..cfc004522e --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeOffsetDateTimeTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.OffsetDateTime +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeOffsetDateTimeTest : TestBase(KOTLIN) { + @Test + fun `test deserializing offset date-time`() { + val dateTime = OffsetDateTime.now() + val data = dateTime.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxDateTime = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowOffsetDateTime::class.java).newInstance(), + sandboxDateTime + ) ?: fail("Result cannot be null") + + assertEquals(dateTime.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowOffsetDateTime : Function { + override fun apply(dateTime: OffsetDateTime): String { + return dateTime.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeOffsetTimeTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeOffsetTimeTest.kt new file mode 100644 index 0000000000..a9eaad89f4 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeOffsetTimeTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.OffsetTime +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeOffsetTimeTest : TestBase(KOTLIN) { + @Test + fun `test deserializing instant`() { + val time = OffsetTime.now() + val data = time.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxTime = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowOffsetTime::class.java).newInstance(), + sandboxTime + ) ?: fail("Result cannot be null") + + assertEquals(time.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowOffsetTime : Function { + override fun apply(time: OffsetTime): String { + return time.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeOptionalTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeOptionalTest.kt new file mode 100644 index 0000000000..8104f282ab --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeOptionalTest.kt @@ -0,0 +1,62 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.* +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeOptionalTest : TestBase(KOTLIN) { + @Test + fun `test deserializing optional with object`() { + val optional = Optional.of("Hello World!") + val data = optional.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxOptional = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowOptional::class.java).newInstance(), + sandboxOptional + ) ?: fail("Result cannot be null") + + assertEquals("Optional -> Optional[Hello World!]", result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + @Test + fun `test deserializing optional without object`() { + val optional = Optional.empty() + val data = optional.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxOptional = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowOptional::class.java).newInstance(), + sandboxOptional + ) ?: fail("Result cannot be null") + + assertEquals("Optional -> Optional.empty", result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } +} + +class ShowOptional : Function, String> { + override fun apply(optional: Optional<*>): String { + return "Optional -> $optional" + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializePeriodTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializePeriodTest.kt new file mode 100644 index 0000000000..2784dbd8aa --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializePeriodTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.Period +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializePeriodTest : TestBase(KOTLIN) { + @Test + fun `test deserializing period`() { + val period = Period.of(1, 2, 3) + val data = period.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxPeriod = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowPeriod::class.java).newInstance(), + sandboxPeriod + ) ?: fail("Result cannot be null") + + assertEquals(period.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowPeriod : Function { + override fun apply(period: Period): String { + return period.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializePrimitiveArraysTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializePrimitiveArraysTest.kt new file mode 100644 index 0000000000..4cb3b4b30a --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializePrimitiveArraysTest.kt @@ -0,0 +1,255 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializePrimitiveArraysTest : TestBase(KOTLIN) { + @Test + fun `test deserializing character array`() { + val charArray = PrimitiveCharArray(charArrayOf('H', 'e', 'l', 'l', 'o', '!')) + val data = charArray.serialize() + assertEquals("Hello!", ShowCharArray().apply(charArray)) + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowCharArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals(SANDBOX_STRING, result::class.java.name) + assertEquals("Hello!", result.toString()) + } + } + + class ShowCharArray : Function { + override fun apply(data: PrimitiveCharArray): String { + return data.letters.joinTo(StringBuilder(), separator = "").toString() + } + } + + @Test + fun `test deserializing integer array`() { + val intArray = PrimitiveIntegerArray(intArrayOf(100, 200, 300, 400, 500)) + val data = intArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowIntegerArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Integer", result::class.java.name) + assertEquals("1500", result.toString()) + } + } + + class ShowIntegerArray : Function { + override fun apply(data: PrimitiveIntegerArray): Int { + return data.integers.sum() + } + } + + @Test + fun `test deserializing long array`() { + val longArray = PrimitiveLongArray(longArrayOf(1000, 2000, 3000, 4000, 5000)) + val data = longArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowLongArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Long", result::class.java.name) + assertEquals("15000", result.toString()) + } + } + + class ShowLongArray : Function { + override fun apply(data: PrimitiveLongArray): Long { + return data.longs.sum() + } + } + + @Test + fun `test deserializing short array`() { + val shortArray = PrimitiveShortArray(shortArrayOf(100, 200, 300, 400, 500)) + val data = shortArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowShortArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Integer", result::class.java.name) + assertEquals("1500", result.toString()) + } + } + + class ShowShortArray : Function { + override fun apply(data: PrimitiveShortArray): Int { + return data.shorts.sum() + } + } + + @Test + fun `test deserializing byte array`() { + val byteArray = PrimitiveByteArray(byteArrayOf(10, 20, 30, 40, 50)) + val data = byteArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowByteArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Integer", result::class.java.name) + assertEquals("150", result.toString()) + } + } + + class ShowByteArray : Function { + override fun apply(data: PrimitiveByteArray): Int { + return data.bytes.sum() + } + } + + @Test + fun `test deserializing boolean array`() { + val booleanArray = PrimitiveBooleanArray(booleanArrayOf(true, true)) + val data = booleanArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowBooleanArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Boolean", result::class.java.name) + assertEquals("true", result.toString()) + } + } + + class ShowBooleanArray : Function { + override fun apply(data: PrimitiveBooleanArray): Boolean { + return data.bools.all { it } + } + } + + @Test + fun `test deserializing double array`() { + val doubleArray = PrimitiveDoubleArray(doubleArrayOf(1000.0, 2000.0, 3000.0, 4000.0, 5000.0)) + val data = doubleArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowDoubleArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Double", result::class.java.name) + assertEquals("15000.0", result.toString()) + } + } + + class ShowDoubleArray : Function { + override fun apply(data: PrimitiveDoubleArray): Double { + return data.doubles.sum() + } + } + + @Test + fun `test deserializing float array`() { + val floatArray = PrimitiveFloatArray(floatArrayOf(100.0f, 200.0f, 300.0f, 400.0f, 500.0f)) + val data = floatArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowFloatArray::class.java).newInstance(), + sandboxArray + ) ?: fail("Result cannot be null") + + assertEquals("sandbox.java.lang.Float", result::class.java.name) + assertEquals("1500.0", result.toString()) + } + } + + class ShowFloatArray : Function { + override fun apply(data: PrimitiveFloatArray): Float { + return data.floats.sum() + } + } +} + +@CordaSerializable +class PrimitiveCharArray(val letters: CharArray) + +@CordaSerializable +class PrimitiveShortArray(val shorts: ShortArray) + +@CordaSerializable +class PrimitiveIntegerArray(val integers: IntArray) + +@CordaSerializable +class PrimitiveLongArray(val longs: LongArray) + +@CordaSerializable +class PrimitiveByteArray(val bytes: ByteArray) + +@CordaSerializable +class PrimitiveBooleanArray(val bools: BooleanArray) + +@CordaSerializable +class PrimitiveDoubleArray(val doubles: DoubleArray) + +@CordaSerializable +class PrimitiveFloatArray(val floats: FloatArray) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializePrimitivesTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializePrimitivesTest.kt new file mode 100644 index 0000000000..894cb2a392 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializePrimitivesTest.kt @@ -0,0 +1,75 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import java.util.* + +@ExtendWith(LocalSerialization::class) +class DeserializePrimitivesTest : TestBase(KOTLIN) { + @Test + fun `test naked uuid`() { + val uuid = UUID.randomUUID() + val data = uuid.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxUUID = data.deserializeFor(classLoader) + assertEquals(uuid.toString(), sandboxUUID.toString()) + assertEquals("sandbox.${uuid::class.java.name}", sandboxUUID::class.java.name) + } + } + + @Test + fun `test wrapped uuid`() { + val uuid = WrappedUUID(UUID.randomUUID()) + val data = uuid.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxUUID = data.deserializeFor(classLoader) + assertEquals(uuid.toString(), sandboxUUID.toString()) + assertEquals("sandbox.${uuid::class.java.name}", sandboxUUID::class.java.name) + } + } + + @Test + fun `test naked date`() { + val now = Date() + val data = now.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxNow = data.deserializeFor(classLoader) + assertEquals(now.toString(), sandboxNow.toString()) + assertEquals("sandbox.${now::class.java.name}", sandboxNow::class.java.name) + } + } + + @Test + fun `test wrapped date`() { + val now = WrappedDate(Date()) + val data = now.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxNow = data.deserializeFor(classLoader) + assertEquals(now.toString(), sandboxNow.toString()) + assertEquals("sandbox.${now::class.java.name}", sandboxNow::class.java.name) + } + } +} + +@CordaSerializable +data class WrappedUUID(val uuid: UUID) + +@CordaSerializable +data class WrappedDate(val date: Date) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeProtonJTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeProtonJTest.kt new file mode 100644 index 0000000000..2de052b5d1 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeProtonJTest.kt @@ -0,0 +1,254 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.apache.qpid.proton.amqp.* +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeProtonJTest : TestBase(KOTLIN) { + @Test + fun `test deserializing unsigned long`() { + val protonJ = HasUnsignedLong(UnsignedLong.valueOf(12345678)) + val data = protonJ.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxProtonJ = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowUnsignedLong::class.java).newInstance(), + sandboxProtonJ + ) ?: fail("Result cannot be null") + + assertEquals(protonJ.number.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowUnsignedLong : Function { + override fun apply(data: HasUnsignedLong): String { + return data.number.toString() + } + } + + @Test + fun `test deserializing unsigned integer`() { + val protonJ = HasUnsignedInteger(UnsignedInteger.valueOf(123456)) + val data = protonJ.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxProtonJ = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowUnsignedInteger::class.java).newInstance(), + sandboxProtonJ + ) ?: fail("Result cannot be null") + + assertEquals(protonJ.number.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowUnsignedInteger : Function { + override fun apply(data: HasUnsignedInteger): String { + return data.number.toString() + } + } + + @Test + fun `test deserializing unsigned short`() { + val protonJ = HasUnsignedShort(UnsignedShort.valueOf(12345)) + val data = protonJ.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxProtonJ = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowUnsignedShort::class.java).newInstance(), + sandboxProtonJ + ) ?: fail("Result cannot be null") + + assertEquals(protonJ.number.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowUnsignedShort : Function { + override fun apply(data: HasUnsignedShort): String { + return data.number.toString() + } + } + + @Test + fun `test deserializing unsigned byte`() { + val protonJ = HasUnsignedByte(UnsignedByte.valueOf(0x8f.toByte())) + val data = protonJ.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxProtonJ = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowUnsignedByte::class.java).newInstance(), + sandboxProtonJ + ) ?: fail("Result cannot be null") + + assertEquals(protonJ.number.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowUnsignedByte : Function { + override fun apply(data: HasUnsignedByte): String { + return data.number.toString() + } + } + + @Test + fun `test deserializing 128 bit decimal`() { + val protonJ = HasDecimal128(Decimal128(12345678, 98765432)) + val data = protonJ.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxProtonJ = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowDecimal128::class.java).newInstance(), + sandboxProtonJ + ) ?: fail("Result cannot be null") + + assertThat(result) + .isEqualTo(protonJ.number.let { longArrayOf(it.mostSignificantBits, it.leastSignificantBits) }) + } + } + + class ShowDecimal128 : Function { + override fun apply(data: HasDecimal128): LongArray { + return data.number.let { longArrayOf(it.mostSignificantBits, it.leastSignificantBits) } + } + } + + @Test + fun `test deserializing 64 bit decimal`() { + val protonJ = HasDecimal64(Decimal64(98765432)) + val data = protonJ.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxProtonJ = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowDecimal64::class.java).newInstance(), + sandboxProtonJ + ) ?: fail("Result cannot be null") + + assertEquals(protonJ.number.bits.toString(), result.toString()) + } + } + + class ShowDecimal64 : Function { + override fun apply(data: HasDecimal64): Long { + return data.number.bits + } + } + + @Test + fun `test deserializing 32 bit decimal`() { + val protonJ = HasDecimal32(Decimal32(123456)) + val data = protonJ.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxProtonJ = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowDecimal32::class.java).newInstance(), + sandboxProtonJ + ) ?: fail("Result cannot be null") + + assertEquals(protonJ.number.bits.toString(), result.toString()) + } + } + + class ShowDecimal32 : Function { + override fun apply(data: HasDecimal32): Int { + return data.number.bits + } + } + + @Test + fun `test deserializing symbol`() { + val protonJ = HasSymbol(Symbol.valueOf("-my-symbol-value-")) + val data = protonJ.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxProtonJ = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowSymbol::class.java).newInstance(), + sandboxProtonJ + ) ?: fail("Result cannot be null") + + assertEquals(protonJ.symbol.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowSymbol : Function { + override fun apply(data: HasSymbol): String { + return data.symbol.toString() + } + } +} + +@CordaSerializable +class HasUnsignedLong(val number: UnsignedLong) + +@CordaSerializable +class HasUnsignedInteger(val number: UnsignedInteger) + +@CordaSerializable +class HasUnsignedShort(val number: UnsignedShort) + +@CordaSerializable +class HasUnsignedByte(val number: UnsignedByte) + +@CordaSerializable +class HasDecimal32(val number: Decimal32) + +@CordaSerializable +class HasDecimal64(val number: Decimal64) + +@CordaSerializable +class HasDecimal128(val number: Decimal128) + +@CordaSerializable +class HasSymbol(val symbol: Symbol) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializePublicKeyTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializePublicKeyTest.kt new file mode 100644 index 0000000000..e6834d0a39 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializePublicKeyTest.kt @@ -0,0 +1,96 @@ +package net.corda.djvm.serialization + +import net.corda.core.crypto.CompositeKey +import net.corda.core.crypto.Crypto +import net.corda.core.crypto.SignatureScheme +import net.corda.core.internal.hash +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.extension.ExtensionContext +import org.junit.jupiter.api.fail +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.ArgumentsProvider +import org.junit.jupiter.params.provider.ArgumentsSource +import java.security.PublicKey +import java.util.function.Function +import java.util.stream.Stream + +@ExtendWith(LocalSerialization::class) +class DeserializePublicKeyTest : TestBase(KOTLIN) { + class SignatureSchemeProvider : ArgumentsProvider { + override fun provideArguments(context: ExtensionContext?): Stream { + return Crypto.supportedSignatureSchemes().stream() + .filter { it != Crypto.COMPOSITE_KEY } + .map { Arguments.of(it) } + } + } + + @ArgumentsSource(SignatureSchemeProvider::class) + @ParameterizedTest(name = "{index} => {0}") + fun `test deserializing public key`(signatureScheme: SignatureScheme) { + val keyPair = Crypto.generateKeyPair(signatureScheme) + val publicKey = PublicKeyData(keyPair.public) + val data = publicKey.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxKey = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowPublicKey::class.java).newInstance(), + sandboxKey + ) ?: fail("Result cannot be null") + + assertEquals(ShowPublicKey().apply(publicKey), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + @Test + fun `test composite public key`() { + val key1 = Crypto.generateKeyPair(Crypto.ECDSA_SECP256K1_SHA256).public + val key2 = Crypto.generateKeyPair(Crypto.ECDSA_SECP256R1_SHA256).public + val key3 = Crypto.generateKeyPair(Crypto.EDDSA_ED25519_SHA512).public + + val compositeKey = CompositeKey.Builder() + .addKey(key1, weight = 1) + .addKey(key2, weight = 1) + .addKey(key3, weight = 1) + .build(2) + val compositeData = PublicKeyData(compositeKey) + val data = compositeData.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxKey = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowPublicKey::class.java).newInstance(), + sandboxKey + ) ?: fail("Result cannot be null") + + assertEquals(ShowPublicKey().apply(compositeData), result.toString()) + } + } + + class ShowPublicKey : Function { + override fun apply(data: PublicKeyData): String { + return with(data) { + "PublicKey: algorithm='${key.algorithm}', format='${key.format}', hash=${key.hash}" + } + } + } +} + +@CordaSerializable +data class PublicKeyData(val key: PublicKey) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeStringBufferTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeStringBufferTest.kt new file mode 100644 index 0000000000..6ae12c8c66 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeStringBufferTest.kt @@ -0,0 +1,40 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeStringBufferTest : TestBase(KOTLIN) { + @Test + fun `test deserializing string buffer`() { + val buffer = StringBuffer("Hello World!") + val data = buffer.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxBigInteger = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringBuffer::class.java).newInstance(), + sandboxBigInteger + ) ?: fail("Result cannot be null") + + assertEquals(ShowStringBuffer().apply(buffer), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowStringBuffer : Function { + override fun apply(buffer: StringBuffer): String { + return buffer.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeStringTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeStringTest.kt new file mode 100644 index 0000000000..860952a8ab --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeStringTest.kt @@ -0,0 +1,75 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeStringTest : TestBase(KOTLIN) { + @Test + fun `test deserializing string`() { + val stringMessage = StringMessage("Hello World!") + val data = stringMessage.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxString = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringMessage::class.java).newInstance(), + sandboxString + ) ?: fail("Result cannot be null") + + assertEquals(stringMessage.message, result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowStringMessage : Function { + override fun apply(data: StringMessage): String { + return data.message + } + } + + @Test + fun `test deserializing string list of arrays`() { + val stringListArray = StringListOfArray(listOf( + arrayOf("Hello"), arrayOf("World"), arrayOf("!")) + ) + val data = stringListArray.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxListArray = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowStringListOfArray::class.java).newInstance(), + sandboxListArray + ) ?: fail("Result cannot be null") + + assertEquals(stringListArray.data.flatMap(Array::toList).joinToString(), result.toString()) + } + } + + class ShowStringListOfArray : Function { + override fun apply(obj: StringListOfArray): String { + return obj.data.flatMap(Array::toList).joinToString() + } + } +} + +@CordaSerializable +data class StringMessage(val message: String) + +@CordaSerializable +class StringListOfArray(val data: List>) diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeYearMonthTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeYearMonthTest.kt new file mode 100644 index 0000000000..0369972dc6 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeYearMonthTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.YearMonth +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeYearMonthTest : TestBase(KOTLIN) { + @Test + fun `test deserializing year-month`() { + val yearMonth = YearMonth.now() + val data = yearMonth.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxYearMonth = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowYearMonth::class.java).newInstance(), + sandboxYearMonth + ) ?: fail("Result cannot be null") + + assertEquals(yearMonth.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowYearMonth : Function { + override fun apply(yearMonth: YearMonth): String { + return yearMonth.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeYearTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeYearTest.kt new file mode 100644 index 0000000000..5056586636 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeYearTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.Year +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeYearTest : TestBase(KOTLIN) { + @Test + fun `test deserializing year`() { + val year = Year.now() + val data = year.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxYear = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowYear::class.java).newInstance(), + sandboxYear + ) ?: fail("Result cannot be null") + + assertEquals(year.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowYear : Function { + override fun apply(year: Year): String { + return year.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeZoneIdTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeZoneIdTest.kt new file mode 100644 index 0000000000..27afdf6978 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeZoneIdTest.kt @@ -0,0 +1,53 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.extension.ExtensionContext +import org.junit.jupiter.api.fail +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.ArgumentsProvider +import org.junit.jupiter.params.provider.ArgumentsSource +import java.time.ZoneId +import java.util.function.Function +import java.util.stream.Stream + +@ExtendWith(LocalSerialization::class) +class DeserializeZoneIdTest : TestBase(KOTLIN) { + class ZoneIdProvider : ArgumentsProvider { + override fun provideArguments(context: ExtensionContext?): Stream { + return ZoneId.getAvailableZoneIds().stream() + .sorted().limit(10).map { Arguments.of(ZoneId.of(it)) } + } + } + + @ArgumentsSource(ZoneIdProvider::class) + @ParameterizedTest(name = "{index} => {0}") + fun `test deserializing zone id`(zoneId: ZoneId) { + val data = zoneId.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxZoneId = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowZoneId::class.java).newInstance(), + sandboxZoneId + ) ?: fail("Result cannot be null") + + assertEquals(zoneId.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowZoneId : Function { + override fun apply(zoneId: ZoneId): String { + return zoneId.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/DeserializeZonedDateTimeTest.kt b/src/test/kotlin/net/corda/djvm/serialization/DeserializeZonedDateTimeTest.kt new file mode 100644 index 0000000000..70a8f6b03b --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/DeserializeZonedDateTimeTest.kt @@ -0,0 +1,41 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.time.ZonedDateTime +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class DeserializeZonedDateTimeTest : TestBase(KOTLIN) { + @Test + fun `test deserializing zoned date-time`() { + val dateTime = ZonedDateTime.now() + val data = dateTime.serialize() + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxDateTime = data.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowZonedDateTime::class.java).newInstance(), + sandboxDateTime + ) ?: fail("Result cannot be null") + + assertEquals(dateTime.toString(), result.toString()) + assertEquals(SANDBOX_STRING, result::class.java.name) + } + } + + class ShowZonedDateTime : Function { + override fun apply(dateTime: ZonedDateTime): String { + return dateTime.toString() + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/LocalSerialization.kt b/src/test/kotlin/net/corda/djvm/serialization/LocalSerialization.kt new file mode 100644 index 0000000000..9eac387abf --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/LocalSerialization.kt @@ -0,0 +1,60 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.SerializationContext +import net.corda.core.serialization.SerializationContext.UseCase +import net.corda.core.serialization.SerializationCustomSerializer +import net.corda.core.serialization.SerializationWhitelist +import net.corda.core.serialization.internal.SerializationEnvironment +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.serialization.internal.* +import net.corda.serialization.internal.amqp.* +import org.junit.jupiter.api.extension.AfterEachCallback +import org.junit.jupiter.api.extension.BeforeEachCallback +import org.junit.jupiter.api.extension.ExtensionContext + +class LocalSerialization : BeforeEachCallback, AfterEachCallback { + private companion object { + private val AMQP_P2P_CONTEXT = SerializationContextImpl( + amqpMagic, + LocalSerialization::class.java.classLoader, + GlobalTransientClassWhiteList(BuiltInExceptionsWhitelist()), + emptyMap(), + true, + UseCase.P2P, + null + ) + } + + override fun beforeEach(context: ExtensionContext) { + _contextSerializationEnv.set(createTestSerializationEnv()) + } + + override fun afterEach(context: ExtensionContext) { + _contextSerializationEnv.set(null) + } + + private fun createTestSerializationEnv(): SerializationEnvironment { + val factory = SerializationFactoryImpl(mutableMapOf()).apply { + registerScheme(AMQPSerializationScheme(emptySet(), emptySet(), AccessOrderLinkedHashMap(128))) + } + return SerializationEnvironment.with(factory, AMQP_P2P_CONTEXT) + } + + private class AMQPSerializationScheme( + customSerializers: Set>, + serializationWhitelists: Set, + serializerFactoriesForContexts: AccessOrderLinkedHashMap + ) : AbstractAMQPSerializationScheme(customSerializers, serializationWhitelists, serializerFactoriesForContexts) { + override fun rpcServerSerializerFactory(context: SerializationContext): SerializerFactory { + throw UnsupportedOperationException() + } + + override fun rpcClientSerializerFactory(context: SerializationContext): SerializerFactory { + throw UnsupportedOperationException() + } + + override fun canDeserializeVersion(magic: CordaSerializationMagic, target: UseCase): Boolean { + return canDeserializeVersion(magic) && target == UseCase.P2P + } + } +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/SafeDeserialisationTest.kt b/src/test/kotlin/net/corda/djvm/serialization/SafeDeserialisationTest.kt new file mode 100644 index 0000000000..cf7d9cd8be --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/SafeDeserialisationTest.kt @@ -0,0 +1,89 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.SerializedBytes +import net.corda.core.serialization.internal._contextSerializationEnv +import net.corda.core.serialization.serialize +import net.corda.djvm.serialization.SandboxType.* +import net.corda.serialization.internal.SectionId +import net.corda.serialization.internal.amqp.* +import org.apache.qpid.proton.codec.Data +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.fail +import java.io.ByteArrayOutputStream +import java.util.function.Function + +@ExtendWith(LocalSerialization::class) +class SafeDeserialisationTest : TestBase(KOTLIN) { + companion object { + const val MESSAGE = "Nothing to see here..." + const val NUMBER = 123.toShort() + } + + @Test + fun `test deserialising an evil class`() { + val context = (_contextSerializationEnv.get() ?: fail("No serialization environment!")).p2pContext + + val innocent = InnocentData(MESSAGE, NUMBER) + val innocentData = innocent.serialize() + val envelope = DeserializationInput.getEnvelope(innocentData, context.encodingWhitelist).apply { + val innocentType = schema.types[0] as CompositeType + (schema.types as MutableList)[0] = CompositeType( + name = innocentType.name.replace("Innocent", "VeryEvil"), + label = innocentType.label, + provides = innocentType.provides, + descriptor = innocentType.descriptor, + fields = innocentType.fields + ) + } + val evilData = SerializedBytes(envelope.write()) + + sandbox { + _contextSerializationEnv.set(createSandboxSerializationEnv(classLoader)) + + val sandboxData = evilData.deserializeFor(classLoader) + + val executor = createExecutorFor(classLoader) + val result = executor.apply( + classLoader.loadClassForSandbox(ShowInnocentData::class.java).newInstance(), + sandboxData + ) ?: fail("Result cannot be null") + + // Check that we have deserialised the data without instantiating the Evil class. + assertThat(result.toString()) + .isEqualTo("sandbox.net.corda.djvm.serialization.VeryEvilData: $MESSAGE, $NUMBER") + + // Check that instantiating the Evil class does indeed cause an error. + val ex = assertThrows{ VeryEvilData("Naughty!", 0) } + assertThat(ex.cause) + .isExactlyInstanceOf(IllegalStateException::class.java) + .hasMessageContaining("Victory is mine!") + } + } + + private fun Envelope.write(): ByteArray { + val data = Data.Factory.create() + data.withDescribed(Envelope.DESCRIPTOR_OBJECT) { + withList { + putObject(obj) + putObject(schema) + putObject(transformsSchema) + } + } + return ByteArrayOutputStream().use { + amqpMagic.writeTo(it) + SectionId.DATA_AND_STOP.writeTo(it) + it.alsoAsByteBuffer(data.encodedSize().toInt(), data::encode) + it.toByteArray() + } + } + + class ShowInnocentData : Function { + override fun apply(data: InnocentData): String { + return "${data::class.java.name}: ${data.message}, ${data.number}" + } + } +} + diff --git a/src/test/kotlin/net/corda/djvm/serialization/SandboxType.kt b/src/test/kotlin/net/corda/djvm/serialization/SandboxType.kt new file mode 100644 index 0000000000..03d07affc6 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/SandboxType.kt @@ -0,0 +1,6 @@ +package net.corda.djvm.serialization + +enum class SandboxType { + JAVA, + KOTLIN +} diff --git a/src/test/kotlin/net/corda/djvm/serialization/TestBase.kt b/src/test/kotlin/net/corda/djvm/serialization/TestBase.kt new file mode 100644 index 0000000000..0a178a5575 --- /dev/null +++ b/src/test/kotlin/net/corda/djvm/serialization/TestBase.kt @@ -0,0 +1,139 @@ +package net.corda.djvm.serialization + +import net.corda.core.serialization.ConstructorForDeserialization +import net.corda.core.serialization.CordaSerializable +import net.corda.djvm.SandboxConfiguration +import net.corda.djvm.SandboxConfiguration.Companion.ALL_DEFINITION_PROVIDERS +import net.corda.djvm.SandboxConfiguration.Companion.ALL_EMITTERS +import net.corda.djvm.SandboxConfiguration.Companion.ALL_RULES +import net.corda.djvm.SandboxRuntimeContext +import net.corda.djvm.analysis.AnalysisConfiguration +import net.corda.djvm.analysis.Whitelist.Companion.MINIMAL +import net.corda.djvm.execution.ExecutionProfile.* +import net.corda.djvm.execution.SandboxRuntimeException +import net.corda.djvm.messages.Severity +import net.corda.djvm.messages.Severity.* +import net.corda.djvm.rewiring.SandboxClassLoader +import net.corda.djvm.source.BootstrapClassLoader +import net.corda.djvm.source.UserPathSource +import org.junit.jupiter.api.AfterAll +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.fail +import java.io.File +import java.lang.reflect.InvocationTargetException +import java.nio.file.Files.exists +import java.nio.file.Files.isDirectory +import java.nio.file.Path +import java.nio.file.Paths +import java.util.function.BiFunction +import kotlin.concurrent.thread + +@Suppress("unused", "MemberVisibilityCanBePrivate") +abstract class TestBase(type: SandboxType) { + companion object { + const val SANDBOX_STRING = "sandbox.java.lang.String" + + @JvmField + val DETERMINISTIC_RT: Path = Paths.get( + System.getProperty("deterministic-rt.path") ?: fail("deterministic-rt.path property not set")) + + @JvmField + val TESTING_LIBRARIES: List = (System.getProperty("sandbox-libraries.path") ?: fail("sandbox-libraries.path property not set")) + .split(File.pathSeparator).map { Paths.get(it) }.filter { exists(it) } + + private lateinit var configuration: SandboxConfiguration + private lateinit var classLoader: SandboxClassLoader + + @BeforeAll + @JvmStatic + fun setupClassLoader() { + val rootConfiguration = AnalysisConfiguration.createRoot( + userSource = UserPathSource(emptyList()), + whitelist = MINIMAL, + visibleAnnotations = setOf( + CordaSerializable::class.java, + ConstructorForDeserialization::class.java + ), + bootstrapSource = BootstrapClassLoader(DETERMINISTIC_RT) + ) + configuration = SandboxConfiguration.of( + UNLIMITED, + ALL_RULES, + ALL_EMITTERS, + ALL_DEFINITION_PROVIDERS, + true, + rootConfiguration + ) + classLoader = SandboxClassLoader.createFor(configuration) + } + + @AfterAll + @JvmStatic + fun destroyRootContext() { + configuration.analysisConfiguration.closeAll() + } + } + + val classPaths: List = when(type) { + SandboxType.KOTLIN -> TESTING_LIBRARIES + SandboxType.JAVA -> TESTING_LIBRARIES.filter { isDirectory(it) } + } + + fun sandbox(action: SandboxRuntimeContext.() -> Unit) { + return sandbox(WARNING, emptySet(), false, action) + } + + fun sandbox(visibleAnnotations: Set>, action: SandboxRuntimeContext.() -> Unit) { + return sandbox(WARNING, visibleAnnotations, false, action) + } + + fun sandbox( + minimumSeverityLevel: Severity, + visibleAnnotations: Set>, + enableTracing: Boolean, + action: SandboxRuntimeContext.() -> Unit + ) { + var thrownException: Throwable? = null + thread { + try { + configuration.analysisConfiguration.createChild( + userSource = UserPathSource(classPaths), + newMinimumSeverityLevel = minimumSeverityLevel, + visibleAnnotations = visibleAnnotations + ).use { analysisConfiguration -> + SandboxRuntimeContext(SandboxConfiguration.of( + configuration.executionProfile, + configuration.rules, + configuration.emitters, + configuration.definitionProviders, + enableTracing, + analysisConfiguration, + classLoader + )).use { + action(this) + } + } + } catch (exception: Throwable) { + thrownException = exception + } + }.join() + throw thrownException ?: return + } + + fun createExecutorFor(classLoader: SandboxClassLoader): BiFunction { + val taskClass = classLoader.loadClass("sandbox.RawTask") + val taskApply = taskClass.getDeclaredMethod("apply", Any::class.java) + val taskConstructor = taskClass.getDeclaredConstructor(classLoader.loadClass("sandbox.java.util.function.Function")) + return BiFunction { userTask, arg -> + try { + taskApply(taskConstructor.newInstance(userTask), arg) + } catch (ex: InvocationTargetException) { + val target = ex.targetException + throw when (target) { + is RuntimeException, is Error -> target + else -> SandboxRuntimeException(target.message, target) + } + } + } + } +} \ No newline at end of file diff --git a/src/test/resources/log4j2-test.xml b/src/test/resources/log4j2-test.xml new file mode 100644 index 0000000000..cf527ff319 --- /dev/null +++ b/src/test/resources/log4j2-test.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/testing.cert b/src/test/resources/testing.cert new file mode 100644 index 0000000000..03e1558cca Binary files /dev/null and b/src/test/resources/testing.cert differ diff --git a/src/test/scripts/generate-certificate.sh b/src/test/scripts/generate-certificate.sh new file mode 100755 index 0000000000..4863542cd5 --- /dev/null +++ b/src/test/scripts/generate-certificate.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +KEYPASS=deterministic +STOREPASS=deterministic + +rm -f keystore testing.cert + +keytool -keystore keystore -storetype pkcs12 -genkey -dname 'CN=localhost, O=R3, L=London, C=UK' -keyalg RSA -validity 3650 -keypass ${KEYPASS} -storepass ${STOREPASS} +keytool -keystore keystore -storetype pkcs12 -export -keyalg RSA -file testing.cert -keypass ${KEYPASS} -storepass ${STOREPASS} + +rm -f keystore