Rename bits -> bytes, as it normally indicates a byte array

This commit is contained in:
Andrius Dagys 2016-11-21 12:58:23 +00:00
parent 9256056ebc
commit 635ee8df79
34 changed files with 84 additions and 86 deletions

View File

@ -195,7 +195,7 @@ class CordaRPCClientImpl(private val session: ClientSession,
} catch (e: KryoException) { } catch (e: KryoException) {
throw RPCException("Could not serialize RPC arguments", e) throw RPCException("Could not serialize RPC arguments", e)
} }
msg.writeBodyBufferBytes(serializedArgs.bits) msg.writeBodyBufferBytes(serializedArgs.bytes)
producer!!.send(ArtemisMessagingComponent.RPC_REQUESTS_QUEUE, msg) producer!!.send(ArtemisMessagingComponent.RPC_REQUESTS_QUEUE, msg)
return kryo return kryo
} }

View File

@ -73,9 +73,9 @@ class ClientRPCInfrastructureTests {
override val users: List<User> get() = throw UnsupportedOperationException() override val users: List<User> get() = throw UnsupportedOperationException()
} }
val dispatcher = object : RPCDispatcher(TestOpsImpl(), userService) { val dispatcher = object : RPCDispatcher(TestOpsImpl(), userService) {
override fun send(bits: SerializedBytes<*>, toAddress: String) { override fun send(data: SerializedBytes<*>, toAddress: String) {
val msg = serverSession.createMessage(false).apply { val msg = serverSession.createMessage(false).apply {
writeBodyBufferBytes(bits.bits) writeBodyBufferBytes(data.bytes)
// Use the magic deduplication property built into Artemis as our message identity too // Use the magic deduplication property built into Artemis as our message identity too
putStringProperty(HDR_DUPLICATE_DETECTION_ID, SimpleString(UUID.randomUUID().toString())) putStringProperty(HDR_DUPLICATE_DETECTION_ID, SimpleString(UUID.randomUUID().toString()))
} }

View File

@ -1,7 +1,7 @@
package net.corda.core.crypto; package net.corda.core.crypto;
import java.math.*; import java.math.BigInteger;
import java.util.*; import java.util.Arrays;
/** /**
* Base58 is a way to encode Bitcoin addresses (or arbitrary data) as alphanumeric strings. * Base58 is a way to encode Bitcoin addresses (or arbitrary data) as alphanumeric strings.
@ -136,7 +136,7 @@ public class Base58 {
throw new AddressFormatException("Input too short"); throw new AddressFormatException("Input too short");
byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - 4); byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - 4);
byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 4, decoded.length); byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 4, decoded.length);
byte[] actualChecksum = Arrays.copyOfRange(SecureHash.sha256Twice(data).getBits(), 0, 4); byte[] actualChecksum = Arrays.copyOfRange(SecureHash.sha256Twice(data).getBytes(), 0, 4);
if (!Arrays.equals(checksum, actualChecksum)) if (!Arrays.equals(checksum, actualChecksum))
throw new AddressFormatException("Checksum does not validate"); throw new AddressFormatException("Checksum does not validate");
return data; return data;

View File

@ -315,7 +315,7 @@ interface FixableDealState : DealState {
} }
/** Returns the SHA-256 hash of the serialised contents of this state (not cached!) */ /** Returns the SHA-256 hash of the serialised contents of this state (not cached!) */
fun ContractState.hash(): SecureHash = SecureHash.sha256(serialize().bits) fun ContractState.hash(): SecureHash = SecureHash.sha256(serialize().bytes)
/** /**
* A stateref is a pointer (reference) to a state, this is an equivalent of an "outpoint" in Bitcoin. It records which * A stateref is a pointer (reference) to a state, this is an equivalent of an "outpoint" in Bitcoin. It records which

View File

@ -28,7 +28,7 @@ open class DigitalSignature(bits: ByteArray) : OpaqueBytes(bits) {
/** A digital signature that identifies who the public key is owned by. */ /** A digital signature that identifies who the public key is owned by. */
open class WithKey(val by: PublicKey, bits: ByteArray) : DigitalSignature(bits) { open class WithKey(val by: PublicKey, bits: ByteArray) : DigitalSignature(bits) {
fun verifyWithECDSA(content: ByteArray) = by.verifyWithECDSA(content, this) fun verifyWithECDSA(content: ByteArray) = by.verifyWithECDSA(content, this)
fun verifyWithECDSA(content: OpaqueBytes) = by.verifyWithECDSA(content.bits, this) fun verifyWithECDSA(content: OpaqueBytes) = by.verifyWithECDSA(content.bytes, this)
} }
// TODO: consider removing this as whoever needs to identify the signer should be able to derive it from the public key // TODO: consider removing this as whoever needs to identify the signer should be able to derive it from the public key
@ -60,16 +60,16 @@ class DummyPublicKey(val s: String) : PublicKey, Comparable<PublicKey> {
object NullSignature : DigitalSignature.WithKey(NullPublicKey, ByteArray(32)) object NullSignature : DigitalSignature.WithKey(NullPublicKey, ByteArray(32))
/** Utility to simplify the act of signing a byte array */ /** Utility to simplify the act of signing a byte array */
fun PrivateKey.signWithECDSA(bits: ByteArray): DigitalSignature { fun PrivateKey.signWithECDSA(bytes: ByteArray): DigitalSignature {
val signer = EdDSAEngine() val signer = EdDSAEngine()
signer.initSign(this) signer.initSign(this)
signer.update(bits) signer.update(bytes)
val sig = signer.sign() val sig = signer.sign()
return DigitalSignature(sig) return DigitalSignature(sig)
} }
fun PrivateKey.signWithECDSA(bitsToSign: ByteArray, publicKey: PublicKey): DigitalSignature.WithKey { fun PrivateKey.signWithECDSA(bytesToSign: ByteArray, publicKey: PublicKey): DigitalSignature.WithKey {
return DigitalSignature.WithKey(publicKey, signWithECDSA(bitsToSign).bits) return DigitalSignature.WithKey(publicKey, signWithECDSA(bytesToSign).bytes)
} }
val ed25519Curve = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512) val ed25519Curve = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512)
@ -77,13 +77,13 @@ val ed25519Curve = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED2
fun parsePublicKeyBase58(base58String: String) = EdDSAPublicKey(EdDSAPublicKeySpec(Base58.decode(base58String), ed25519Curve)) fun parsePublicKeyBase58(base58String: String) = EdDSAPublicKey(EdDSAPublicKeySpec(Base58.decode(base58String), ed25519Curve))
fun PublicKey.toBase58String() = Base58.encode((this as EdDSAPublicKey).abyte) fun PublicKey.toBase58String() = Base58.encode((this as EdDSAPublicKey).abyte)
fun KeyPair.signWithECDSA(bitsToSign: ByteArray) = private.signWithECDSA(bitsToSign, public) fun KeyPair.signWithECDSA(bytesToSign: ByteArray) = private.signWithECDSA(bytesToSign, public)
fun KeyPair.signWithECDSA(bitsToSign: OpaqueBytes) = private.signWithECDSA(bitsToSign.bits, public) fun KeyPair.signWithECDSA(bytesToSign: OpaqueBytes) = private.signWithECDSA(bytesToSign.bytes, public)
fun KeyPair.signWithECDSA(bitsToSign: OpaqueBytes, party: Party) = signWithECDSA(bitsToSign.bits, party) fun KeyPair.signWithECDSA(bytesToSign: OpaqueBytes, party: Party) = signWithECDSA(bytesToSign.bytes, party)
fun KeyPair.signWithECDSA(bitsToSign: ByteArray, party: Party): DigitalSignature.LegallyIdentifiable { fun KeyPair.signWithECDSA(bytesToSign: ByteArray, party: Party): DigitalSignature.LegallyIdentifiable {
check(public in party.owningKey.keys) check(public in party.owningKey.keys)
val sig = signWithECDSA(bitsToSign) val sig = signWithECDSA(bytesToSign)
return DigitalSignature.LegallyIdentifiable(party, sig.bits) return DigitalSignature.LegallyIdentifiable(party, sig.bytes)
} }
/** Utility to simplify the act of verifying a signature */ /** Utility to simplify the act of verifying a signature */
@ -91,7 +91,7 @@ fun PublicKey.verifyWithECDSA(content: ByteArray, signature: DigitalSignature) {
val verifier = EdDSAEngine() val verifier = EdDSAEngine()
verifier.initVerify(this) verifier.initVerify(this)
verifier.update(content) verifier.update(content)
if (verifier.verify(signature.bits) == false) if (verifier.verify(signature.bytes) == false)
throw SignatureException("Signature did not match") throw SignatureException("Signature did not match")
} }
@ -122,8 +122,8 @@ fun generateKeyPair(): KeyPair = KeyPairGenerator().generateKeyPair()
*/ */
fun entropyToKeyPair(entropy: BigInteger): KeyPair { fun entropyToKeyPair(entropy: BigInteger): KeyPair {
val params = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512) val params = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512)
val bits = entropy.toByteArray().copyOf(params.curve.field.getb() / 8) val bytes = entropy.toByteArray().copyOf(params.curve.field.getb() / 8)
val priv = EdDSAPrivateKeySpec(bits, params) val priv = EdDSAPrivateKeySpec(bytes, params)
val pub = EdDSAPublicKeySpec(priv.a, params) val pub = EdDSAPublicKeySpec(priv.a, params)
val key = KeyPair(EdDSAPublicKey(pub), EdDSAPrivateKey(priv)) val key = KeyPair(EdDSAPublicKey(pub), EdDSAPrivateKey(priv))
return key return key

View File

@ -32,7 +32,7 @@ sealed class PublicKeyTree {
fun containsAny(otherKeys: Iterable<PublicKey>) = keys.intersect(otherKeys).isNotEmpty() fun containsAny(otherKeys: Iterable<PublicKey>) = keys.intersect(otherKeys).isNotEmpty()
// TODO: implement a proper encoding/decoding mechanism // TODO: implement a proper encoding/decoding mechanism
fun toBase58String(): String = Base58.encode(this.serialize().bits) fun toBase58String(): String = Base58.encode(this.serialize().bytes)
companion object { companion object {
fun parseFromBase58(encoded: String) = Base58.decode(encoded).deserialize<PublicKeyTree>() fun parseFromBase58(encoded: String) = Base58.decode(encoded).deserialize<PublicKeyTree>()

View File

@ -8,15 +8,15 @@ import java.security.MessageDigest
* Container for a cryptographically secure hash value. * Container for a cryptographically secure hash value.
* Provides utilities for generating a cryptographic hash using different algorithms (currently only SHA-256 supported). * Provides utilities for generating a cryptographic hash using different algorithms (currently only SHA-256 supported).
*/ */
sealed class SecureHash(bits: ByteArray) : OpaqueBytes(bits) { sealed class SecureHash(bytes: ByteArray) : OpaqueBytes(bytes) {
/** SHA-256 is part of the SHA-2 hash function family. Generated hash is fixed size, 256-bits (32-bytes) */ /** SHA-256 is part of the SHA-2 hash function family. Generated hash is fixed size, 256-bits (32-bytes) */
class SHA256(bits: ByteArray) : SecureHash(bits) { class SHA256(bytes: ByteArray) : SecureHash(bytes) {
init { init {
require(bits.size == 32) require(bytes.size == 32)
} }
} }
override fun toString() = BaseEncoding.base16().encode(bits) override fun toString() = BaseEncoding.base16().encode(bytes)
fun prefixChars(prefixLen: Int = 6) = toString().substring(0, prefixLen) fun prefixChars(prefixLen: Int = 6) = toString().substring(0, prefixLen)
@ -30,8 +30,8 @@ sealed class SecureHash(bits: ByteArray) : OpaqueBytes(bits) {
} }
} }
@JvmStatic fun sha256(bits: ByteArray) = SHA256(MessageDigest.getInstance("SHA-256").digest(bits)) @JvmStatic fun sha256(bytes: ByteArray) = SHA256(MessageDigest.getInstance("SHA-256").digest(bytes))
@JvmStatic fun sha256Twice(bits: ByteArray) = sha256(sha256(bits).bits) @JvmStatic fun sha256Twice(bytes: ByteArray) = sha256(sha256(bytes).bytes)
@JvmStatic fun sha256(str: String) = sha256(str.toByteArray()) @JvmStatic fun sha256(str: String) = sha256(str.toByteArray())
@JvmStatic fun randomSHA256() = sha256(newSecureRandom().generateSeed(32)) @JvmStatic fun randomSHA256() = sha256(newSecureRandom().generateSeed(32))
@ -41,4 +41,4 @@ sealed class SecureHash(bits: ByteArray) : OpaqueBytes(bits) {
} }
fun ByteArray.sha256(): SecureHash.SHA256 = SecureHash.sha256(this) fun ByteArray.sha256(): SecureHash.SHA256 = SecureHash.sha256(this)
fun OpaqueBytes.sha256(): SecureHash.SHA256 = SecureHash.sha256(this.bits) fun OpaqueBytes.sha256(): SecureHash.SHA256 = SecureHash.sha256(this.bytes)

View File

@ -20,7 +20,7 @@ open class SignedData<T : Any>(val raw: SerializedBytes<T>, val sig: DigitalSign
*/ */
@Throws(SignatureException::class) @Throws(SignatureException::class)
fun verified(): T { fun verified(): T {
sig.by.verifyWithECDSA(raw.bits, sig) sig.by.verifyWithECDSA(raw.bytes, sig)
val data = raw.deserialize() val data = raw.deserialize()
verifyData(data) verifyData(data)
return data return data

View File

@ -142,7 +142,7 @@ fun MessagingService.send(topic: String, sessionID: Long, payload: Any, to: Mess
= send(TopicSession(topic, sessionID), payload, to, uuid) = send(TopicSession(topic, sessionID), payload, to, uuid)
fun MessagingService.send(topicSession: TopicSession, payload: Any, to: MessageRecipients, uuid: UUID = UUID.randomUUID()) fun MessagingService.send(topicSession: TopicSession, payload: Any, to: MessageRecipients, uuid: UUID = UUID.randomUUID())
= send(createMessage(topicSession, payload.serialize().bits, uuid), to) = send(createMessage(topicSession, payload.serialize().bytes, uuid), to)
interface MessageHandlerRegistration interface MessageHandlerRegistration

View File

@ -61,6 +61,6 @@ data class PersistentStateRef(
@Column(name = "output_index") @Column(name = "output_index")
var index: Int? var index: Int?
) : Serializable { ) : Serializable {
constructor(stateRef: StateRef) : this(stateRef.txhash.bits.toHexString(), stateRef.index) constructor(stateRef: StateRef) : this(stateRef.txhash.bytes.toHexString(), stateRef.index)
constructor() : this(null, null) constructor() : this(null, null)
} }

View File

@ -9,9 +9,9 @@ import java.util.*
* In an ideal JVM this would be a value type and be completely overhead free. Project Valhalla is adding such * In an ideal JVM this would be a value type and be completely overhead free. Project Valhalla is adding such
* functionality to Java, but it won't arrive for a few years yet! * functionality to Java, but it won't arrive for a few years yet!
*/ */
open class OpaqueBytes(val bits: ByteArray) { open class OpaqueBytes(val bytes: ByteArray) {
init { init {
check(bits.isNotEmpty()) check(bytes.isNotEmpty())
} }
companion object { companion object {
@ -21,16 +21,16 @@ open class OpaqueBytes(val bits: ByteArray) {
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (this === other) return true if (this === other) return true
if (other !is OpaqueBytes) return false if (other !is OpaqueBytes) return false
return Arrays.equals(bits, other.bits) return Arrays.equals(bytes, other.bytes)
} }
override fun hashCode() = Arrays.hashCode(bits) override fun hashCode() = Arrays.hashCode(bytes)
override fun toString() = "[" + bits.toHexString() + "]" override fun toString() = "[" + bytes.toHexString() + "]"
val size: Int get() = bits.size val size: Int get() = bytes.size
/** Returns a [ByteArrayInputStream] of the bytes */ /** Returns a [ByteArrayInputStream] of the bytes */
fun open() = ByteArrayInputStream(bits) fun open() = ByteArrayInputStream(bytes)
} }
fun ByteArray.opaque(): OpaqueBytes = OpaqueBytes(this) fun ByteArray.opaque(): OpaqueBytes = OpaqueBytes(this)

View File

@ -72,11 +72,11 @@ val THREAD_LOCAL_KRYO = ThreadLocal.withInitial { createKryo() }
* A type safe wrapper around a byte array that contains a serialised object. You can call [SerializedBytes.deserialize] * A type safe wrapper around a byte array that contains a serialised object. You can call [SerializedBytes.deserialize]
* to get the original object back. * to get the original object back.
*/ */
class SerializedBytes<T : Any>(bits: ByteArray) : OpaqueBytes(bits) { class SerializedBytes<T : Any>(bytes: ByteArray) : OpaqueBytes(bytes) {
// It's OK to use lazy here because SerializedBytes is configured to use the ImmutableClassSerializer. // It's OK to use lazy here because SerializedBytes is configured to use the ImmutableClassSerializer.
val hash: SecureHash by lazy { bits.sha256() } val hash: SecureHash by lazy { bytes.sha256() }
fun writeToFile(path: Path) = Files.write(path, bits) fun writeToFile(path: Path) = Files.write(path, bytes)
} }
// Some extension functions that make deserialisation convenient and provide auto-casting of the result. // Some extension functions that make deserialisation convenient and provide auto-casting of the result.
@ -86,14 +86,14 @@ fun <T : Any> ByteArray.deserialize(kryo: Kryo = THREAD_LOCAL_KRYO.get()): T {
} }
fun <T : Any> OpaqueBytes.deserialize(kryo: Kryo = THREAD_LOCAL_KRYO.get()): T { fun <T : Any> OpaqueBytes.deserialize(kryo: Kryo = THREAD_LOCAL_KRYO.get()): T {
return this.bits.deserialize(kryo) return this.bytes.deserialize(kryo)
} }
// The more specific deserialize version results in the bytes being cached, which is faster. // The more specific deserialize version results in the bytes being cached, which is faster.
@JvmName("SerializedBytesWireTransaction") @JvmName("SerializedBytesWireTransaction")
fun SerializedBytes<WireTransaction>.deserialize(kryo: Kryo = THREAD_LOCAL_KRYO.get()): WireTransaction = WireTransaction.deserialize(this, kryo) fun SerializedBytes<WireTransaction>.deserialize(kryo: Kryo = THREAD_LOCAL_KRYO.get()): WireTransaction = WireTransaction.deserialize(this, kryo)
fun <T : Any> SerializedBytes<T>.deserialize(kryo: Kryo = THREAD_LOCAL_KRYO.get()): T = bits.deserialize(kryo) fun <T : Any> SerializedBytes<T>.deserialize(kryo: Kryo = THREAD_LOCAL_KRYO.get()): T = bytes.deserialize(kryo)
/** /**
* A serialiser that avoids writing the wrapper class to the byte stream, thus ensuring [SerializedBytes] is a pure * A serialiser that avoids writing the wrapper class to the byte stream, thus ensuring [SerializedBytes] is a pure
@ -101,8 +101,8 @@ fun <T : Any> SerializedBytes<T>.deserialize(kryo: Kryo = THREAD_LOCAL_KRYO.get(
*/ */
object SerializedBytesSerializer : Serializer<SerializedBytes<Any>>() { object SerializedBytesSerializer : Serializer<SerializedBytes<Any>>() {
override fun write(kryo: Kryo, output: Output, obj: SerializedBytes<Any>) { override fun write(kryo: Kryo, output: Output, obj: SerializedBytes<Any>) {
output.writeVarInt(obj.bits.size, true) output.writeVarInt(obj.bytes.size, true)
output.writeBytes(obj.bits) output.writeBytes(obj.bytes)
} }
override fun read(kryo: Kryo, input: Input, type: Class<SerializedBytes<Any>>): SerializedBytes<Any> { override fun read(kryo: Kryo, input: Input, type: Class<SerializedBytes<Any>>): SerializedBytes<Any> {

View File

@ -4,12 +4,13 @@ import net.corda.core.contracts.Command
import net.corda.core.contracts.ContractState import net.corda.core.contracts.ContractState
import net.corda.core.contracts.StateRef import net.corda.core.contracts.StateRef
import net.corda.core.contracts.TransactionState import net.corda.core.contracts.TransactionState
import net.corda.core.crypto.*
import net.corda.core.serialization.*
import net.corda.core.crypto.MerkleTreeException import net.corda.core.crypto.MerkleTreeException
import net.corda.core.crypto.PartialMerkleTree import net.corda.core.crypto.PartialMerkleTree
import net.corda.core.crypto.SecureHash import net.corda.core.crypto.SecureHash
import net.corda.core.crypto.sha256 import net.corda.core.crypto.sha256
import net.corda.core.serialization.createKryo
import net.corda.core.serialization.extendKryoHash
import net.corda.core.serialization.serialize
import java.util.* import java.util.*
/** /**
@ -29,7 +30,7 @@ fun WireTransaction.calculateLeavesHashes(): List<SecureHash> {
return resultHashes return resultHashes
} }
fun SecureHash.hashConcat(other: SecureHash) = (this.bits + other.bits).sha256() fun SecureHash.hashConcat(other: SecureHash) = (this.bytes + other.bytes).sha256()
fun <T: Any> serializedHash(x: T): SecureHash { fun <T: Any> serializedHash(x: T): SecureHash {
val kryo = extendKryoHash(createKryo()) //Dealing with HashMaps inside states. val kryo = extendKryoHash(createKryo()) //Dealing with HashMaps inside states.

View File

@ -82,7 +82,7 @@ data class SignedTransaction(val txBits: SerializedBytes<WireTransaction>,
@Throws(SignatureException::class) @Throws(SignatureException::class)
fun checkSignaturesAreValid() { fun checkSignaturesAreValid() {
for (sig in sigs) { for (sig in sigs) {
sig.verifyWithECDSA(id.bits) sig.verifyWithECDSA(id.bytes)
} }
} }

View File

@ -97,7 +97,7 @@ open class TransactionBuilder(
fun signWith(key: KeyPair): TransactionBuilder { fun signWith(key: KeyPair): TransactionBuilder {
check(currentSigs.none { it.by == key.public }) { "This partial transaction was already signed by ${key.public}" } check(currentSigs.none { it.by == key.public }) { "This partial transaction was already signed by ${key.public}" }
val data = toWireTransaction().id val data = toWireTransaction().id
addSignatureUnchecked(key.signWithECDSA(data.bits)) addSignatureUnchecked(key.signWithECDSA(data.bytes))
return this return this
} }

View File

@ -37,8 +37,8 @@ class WireTransaction(
init { checkInvariants() } init { checkInvariants() }
// Cache the serialised form of the transaction and its hash to give us fast access to it. // Cache the serialised form of the transaction and its hash to give us fast access to it.
@Volatile @Transient private var cachedBits: SerializedBytes<WireTransaction>? = null @Volatile @Transient private var cachedBytes: SerializedBytes<WireTransaction>? = null
val serialized: SerializedBytes<WireTransaction> get() = cachedBits ?: serialize().apply { cachedBits = this } val serialized: SerializedBytes<WireTransaction> get() = cachedBytes ?: serialize().apply { cachedBytes = this }
//We need cashed leaves hashes and whole tree for an id and Partial Merkle Tree calculation. //We need cashed leaves hashes and whole tree for an id and Partial Merkle Tree calculation.
@Volatile @Transient private var cachedLeavesHashes: List<SecureHash>? = null @Volatile @Transient private var cachedLeavesHashes: List<SecureHash>? = null
@ -50,9 +50,9 @@ class WireTransaction(
override val id: SecureHash get() = merkleTree.hash override val id: SecureHash get() = merkleTree.hash
companion object { companion object {
fun deserialize(bits: SerializedBytes<WireTransaction>, kryo: Kryo = THREAD_LOCAL_KRYO.get()): WireTransaction { fun deserialize(data: SerializedBytes<WireTransaction>, kryo: Kryo = THREAD_LOCAL_KRYO.get()): WireTransaction {
val wtx = bits.bits.deserialize<WireTransaction>(kryo) val wtx = data.bytes.deserialize<WireTransaction>(kryo)
wtx.cachedBits = bits wtx.cachedBytes = data
return wtx return wtx
} }
} }

View File

@ -61,7 +61,7 @@ object NotaryProtocol {
progressTracker.currentStep = VALIDATING progressTracker.currentStep = VALIDATING
when (notaryResult) { when (notaryResult) {
is Result.Success -> { is Result.Success -> {
validateSignature(notaryResult.sig, stx.id.bits) validateSignature(notaryResult.sig, stx.id.bytes)
notaryResult.sig notaryResult.sig
} }
is Result.Error -> { is Result.Error -> {
@ -103,7 +103,7 @@ object NotaryProtocol {
beforeCommit(stx, reqIdentity) beforeCommit(stx, reqIdentity)
commitInputStates(wtx, reqIdentity) commitInputStates(wtx, reqIdentity)
val sig = sign(stx.id.bits) val sig = sign(stx.id.bytes)
Result.Success(sig) Result.Success(sig)
} catch(e: NotaryException) { } catch(e: NotaryException) {
Result.Error(e.error) Result.Error(e.error)
@ -135,7 +135,7 @@ object NotaryProtocol {
uniquenessProvider.commit(tx.inputs, tx.id, reqIdentity) uniquenessProvider.commit(tx.inputs, tx.id, reqIdentity)
} catch (e: UniquenessException) { } catch (e: UniquenessException) {
val conflictData = e.error.serialize() val conflictData = e.error.serialize()
val signedConflict = SignedData(conflictData, sign(conflictData.bits)) val signedConflict = SignedData(conflictData, sign(conflictData.bytes))
throw NotaryException(NotaryError.Conflict(tx, signedConflict)) throw NotaryException(NotaryError.Conflict(tx, signedConflict))
} }
} }

View File

@ -34,8 +34,8 @@ class TransactionTests {
type = TransactionType.General(), type = TransactionType.General(),
timestamp = null timestamp = null
) )
val bits: SerializedBytes<WireTransaction> = wtx.serialized val bytes: SerializedBytes<WireTransaction> = wtx.serialized
fun make(vararg keys: KeyPair) = SignedTransaction(bits, keys.map { it.signWithECDSA(wtx.id.bits) }, wtx.id) fun make(vararg keys: KeyPair) = SignedTransaction(bytes, keys.map { it.signWithECDSA(wtx.id.bytes) }, wtx.id)
assertFailsWith<IllegalArgumentException> { make().verifySignatures() } assertFailsWith<IllegalArgumentException> { make().verifySignatures() }
assertEquals( assertEquals(

View File

@ -12,7 +12,7 @@ class SignedDataTest {
@Test @Test
fun `make sure correctly signed data is released`() { fun `make sure correctly signed data is released`() {
val keyPair = generateKeyPair() val keyPair = generateKeyPair()
val sig = keyPair.private.signWithECDSA(serialized.bits, keyPair.public) val sig = keyPair.private.signWithECDSA(serialized.bytes, keyPair.public)
val wrappedData = SignedData(serialized, sig) val wrappedData = SignedData(serialized, sig)
val unwrappedData = wrappedData.verified() val unwrappedData = wrappedData.verified()
@ -23,7 +23,7 @@ class SignedDataTest {
fun `make sure incorrectly signed data raises an exception`() { fun `make sure incorrectly signed data raises an exception`() {
val keyPairA = generateKeyPair() val keyPairA = generateKeyPair()
val keyPairB = generateKeyPair() val keyPairB = generateKeyPair()
val sig = keyPairA.private.signWithECDSA(serialized.bits, keyPairB.public) val sig = keyPairA.private.signWithECDSA(serialized.bytes, keyPairB.public)
val wrappedData = SignedData(serialized, sig) val wrappedData = SignedData(serialized, sig)
wrappedData.verified() wrappedData.verified()
} }

View File

@ -26,7 +26,7 @@ class BroadcastTransactionProtocolTest {
@Property @Property
fun serialiseDeserialiseOfNotifyMessageWorks(@From(NotifyTxRequestMessageGenerator::class) message: NotifyTxRequest) { fun serialiseDeserialiseOfNotifyMessageWorks(@From(NotifyTxRequestMessageGenerator::class) message: NotifyTxRequest) {
val kryo = createKryo() val kryo = createKryo()
val serialized = message.serialize().bits val serialized = message.serialize().bytes
val deserialized = kryo.readClassAndObject(Input(serialized)) val deserialized = kryo.readClassAndObject(Input(serialized))
assertEquals(deserialized, message) assertEquals(deserialized, message)
} }

View File

@ -30,9 +30,9 @@ class SerializationTokenTest {
val numBytes: Int val numBytes: Int
get() = bytes.size get() = bytes.size
override fun hashCode() = bytes.bits.size override fun hashCode() = bytes.size
override fun equals(other: Any?) = other is LargeTokenizable && other.bytes.bits.size == this.bytes.bits.size override fun equals(other: Any?) = other is LargeTokenizable && other.bytes.size == this.bytes.size
} }
@Test @Test

View File

@ -68,7 +68,7 @@ class TransactionSerializationTests {
signedTX.verifySignatures() signedTX.verifySignatures()
// Corrupt the data and ensure the signature catches the problem. // Corrupt the data and ensure the signature catches the problem.
signedTX.id.bits[5] = 0 signedTX.id.bytes[5] = 0
assertFailsWith(SignatureException::class) { assertFailsWith(SignatureException::class) {
signedTX.verifySignatures() signedTX.verifySignatures()
} }

View File

@ -8,9 +8,9 @@ import com.google.common.collect.testing.testers.CollectionAddAllTester
import com.google.common.collect.testing.testers.CollectionClearTester import com.google.common.collect.testing.testers.CollectionClearTester
import com.google.common.collect.testing.testers.CollectionRemoveAllTester import com.google.common.collect.testing.testers.CollectionRemoveAllTester
import com.google.common.collect.testing.testers.CollectionRetainAllTester import com.google.common.collect.testing.testers.CollectionRetainAllTester
import junit.framework.TestSuite
import net.corda.core.serialization.deserialize import net.corda.core.serialization.deserialize
import net.corda.core.serialization.serialize import net.corda.core.serialization.serialize
import junit.framework.TestSuite
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.junit.runners.Suite import org.junit.runners.Suite
@ -104,7 +104,7 @@ class NonEmptySetTest {
@Test @Test
fun `serialize deserialize`() { fun `serialize deserialize`() {
val expected: NonEmptySet<Int> = nonEmptySetOf(-17, 22, 17) val expected: NonEmptySet<Int> = nonEmptySetOf(-17, 22, 17)
val serialized = expected.serialize().bits val serialized = expected.serialize().bytes
val actual = serialized.deserialize<NonEmptySet<Int>>() val actual = serialized.deserialize<NonEmptySet<Int>>()
assertEquals(expected, actual) assertEquals(expected, actual)

View File

@ -88,13 +88,13 @@ class CommercialPaper : Contract {
return when (schema) { return when (schema) {
is CommercialPaperSchemaV1 -> CommercialPaperSchemaV1.PersistentCommericalPaperState( is CommercialPaperSchemaV1 -> CommercialPaperSchemaV1.PersistentCommericalPaperState(
issuanceParty = this.issuance.party.owningKey.toBase58String(), issuanceParty = this.issuance.party.owningKey.toBase58String(),
issuanceRef = this.issuance.reference.bits, issuanceRef = this.issuance.reference.bytes,
owner = this.owner.toBase58String(), owner = this.owner.toBase58String(),
maturity = this.maturityDate, maturity = this.maturityDate,
faceValue = this.faceValue.quantity, faceValue = this.faceValue.quantity,
currency = this.faceValue.token.product.currencyCode, currency = this.faceValue.token.product.currencyCode,
faceValueIssuerParty = this.faceValue.token.issuer.party.owningKey.toBase58String(), faceValueIssuerParty = this.faceValue.token.issuer.party.owningKey.toBase58String(),
faceValueIssuerRef = this.faceValue.token.issuer.reference.bits faceValueIssuerRef = this.faceValue.token.issuer.reference.bytes
) )
else -> throw IllegalArgumentException("Unrecognised schema $schema") else -> throw IllegalArgumentException("Unrecognised schema $schema")
} }

View File

@ -108,7 +108,7 @@ class Cash : OnLedgerAsset<Currency, Cash.Commands, Cash.State>() {
pennies = this.amount.quantity, pennies = this.amount.quantity,
currency = this.amount.token.product.currencyCode, currency = this.amount.token.product.currencyCode,
issuerParty = this.amount.token.issuer.party.owningKey.toBase58String(), issuerParty = this.amount.token.issuer.party.owningKey.toBase58String(),
issuerRef = this.amount.token.issuer.reference.bits issuerRef = this.amount.token.issuer.reference.bytes
) )
else -> throw IllegalArgumentException("Unrecognised schema $schema") else -> throw IllegalArgumentException("Unrecognised schema $schema")
} }

View File

@ -37,7 +37,7 @@ abstract class AbstractNodeService(val services: ServiceHubInternal) : Singleton
val response = handler(request) val response = handler(request)
// If the return type R is Unit, then do not send a response // If the return type R is Unit, then do not send a response
if (response.javaClass != Unit.javaClass) { if (response.javaClass != Unit.javaClass) {
val msg = net.createMessage(topic, request.sessionID, response.serialize().bits) val msg = net.createMessage(topic, request.sessionID, response.serialize().bytes)
net.send(msg, request.replyTo) net.send(msg, request.replyTo)
} }
} catch(e: Exception) { } catch(e: Exception) {

View File

@ -426,10 +426,10 @@ class NodeMessagingClient(override val config: NodeConfiguration,
var dispatcher: RPCDispatcher? = null var dispatcher: RPCDispatcher? = null
private fun createRPCDispatcher(ops: RPCOps, userService: RPCUserService) = object : RPCDispatcher(ops, userService) { private fun createRPCDispatcher(ops: RPCOps, userService: RPCUserService) = object : RPCDispatcher(ops, userService) {
override fun send(bits: SerializedBytes<*>, toAddress: String) { override fun send(data: SerializedBytes<*>, toAddress: String) {
state.locked { state.locked {
val msg = session!!.createMessage(false).apply { val msg = session!!.createMessage(false).apply {
writeBodyBufferBytes(bits.bits) writeBodyBufferBytes(data.bytes)
// Use the magic deduplication property built into Artemis as our message identity too // Use the magic deduplication property built into Artemis as our message identity too
putStringProperty(HDR_DUPLICATE_DETECTION_ID, SimpleString(UUID.randomUUID().toString())) putStringProperty(HDR_DUPLICATE_DETECTION_ID, SimpleString(UUID.randomUUID().toString()))
} }

View File

@ -100,7 +100,7 @@ abstract class RPCDispatcher(val ops: RPCOps, val userService: RPCUserService) {
send(responseBits, replyTo) send(responseBits, replyTo)
} }
abstract fun send(bits: SerializedBytes<*>, toAddress: String) abstract fun send(data: SerializedBytes<*>, toAddress: String)
fun start(rpcConsumer: ClientConsumer, rpcNotificationConsumer: ClientConsumer?, onExecutor: AffinityExecutor) { fun start(rpcConsumer: ClientConsumer, rpcNotificationConsumer: ClientConsumer?, onExecutor: AffinityExecutor) {
rpcNotificationConsumer?.setMessageHandler { msg -> rpcNotificationConsumer?.setMessageHandler { msg ->

View File

@ -110,7 +110,7 @@ open class InMemoryNetworkMapCache : SingletonSerializeAsToken(), NetworkMapCach
try { try {
val req = message.data.deserialize<NetworkMapService.Update>() val req = message.data.deserialize<NetworkMapService.Update>()
val ackMessage = net.createMessage(NetworkMapService.PUSH_ACK_PROTOCOL_TOPIC, DEFAULT_SESSION_ID, val ackMessage = net.createMessage(NetworkMapService.PUSH_ACK_PROTOCOL_TOPIC, DEFAULT_SESSION_ID,
NetworkMapService.UpdateAcknowledge(req.mapVersion, net.myAddress).serialize().bits) NetworkMapService.UpdateAcknowledge(req.mapVersion, net.myAddress).serialize().bytes)
net.send(ackMessage, req.replyTo) net.send(ackMessage, req.replyTo)
processUpdatePush(req) processUpdatePush(req)
} catch(e: NodeMapError) { } catch(e: NodeMapError) {

View File

@ -199,7 +199,7 @@ abstract class AbstractNetworkMapService
// TODO: Once we have a better established messaging system, we can probably send // TODO: Once we have a better established messaging system, we can probably send
// to a MessageRecipientGroup that nodes join/leave, rather than the network map // to a MessageRecipientGroup that nodes join/leave, rather than the network map
// service itself managing the group // service itself managing the group
val update = NetworkMapService.Update(wireReg, mapVersion, net.myAddress).serialize().bits val update = NetworkMapService.Update(wireReg, mapVersion, net.myAddress).serialize().bytes
val message = net.createMessage(NetworkMapService.PUSH_PROTOCOL_TOPIC, DEFAULT_SESSION_ID, update) val message = net.createMessage(NetworkMapService.PUSH_PROTOCOL_TOPIC, DEFAULT_SESSION_ID, update)
subscribers.locked { subscribers.locked {
@ -333,7 +333,7 @@ class NodeRegistration(val node: NodeInfo, val serial: Long, val type: AddOrRemo
*/ */
fun toWire(privateKey: PrivateKey): WireNodeRegistration { fun toWire(privateKey: PrivateKey): WireNodeRegistration {
val regSerialized = this.serialize() val regSerialized = this.serialize()
val regSig = privateKey.signWithECDSA(regSerialized.bits, node.legalIdentity.owningKey.singleKey) val regSig = privateKey.signWithECDSA(regSerialized.bytes, node.legalIdentity.owningKey.singleKey)
return WireNodeRegistration(regSerialized, regSig) return WireNodeRegistration(regSerialized, regSig)
} }

View File

@ -117,7 +117,7 @@ class RaftUniquenessProvider(storagePath: Path, myAddress: HostAndPort, clusterA
*/ */
private fun encode(items: List<Pair<StateRef, UniquenessProvider.ConsumingTx>>): Map<String, ByteArray> { private fun encode(items: List<Pair<StateRef, UniquenessProvider.ConsumingTx>>): Map<String, ByteArray> {
fun StateRef.encoded() = "$txhash:$index" fun StateRef.encoded() = "$txhash:$index"
return items.map { it.first.encoded() to it.second.serialize().bits }.toMap() return items.map { it.first.encoded() to it.second.serialize().bytes }.toMap()
} }
private fun decode(items: Map<String, ByteArray>): Map<StateRef, UniquenessProvider.ConsumingTx> { private fun decode(items: Map<String, ByteArray>): Map<StateRef, UniquenessProvider.ConsumingTx> {

View File

@ -52,7 +52,7 @@ class JDBCHashMap<K : Any, V : Any>(tableName: String,
fun bytesToBlob(value: SerializedBytes<*>, finalizables: MutableList<() -> Unit>): Blob { fun bytesToBlob(value: SerializedBytes<*>, finalizables: MutableList<() -> Unit>): Blob {
val blob = TransactionManager.current().connection.createBlob() val blob = TransactionManager.current().connection.createBlob()
finalizables += { blob.free() } finalizables += { blob.free() }
blob.setBytes(1, value.bits) blob.setBytes(1, value.bytes)
return blob return blob
} }

View File

@ -15,7 +15,6 @@ import net.corda.core.node.NodeInfo
import net.corda.core.node.services.IdentityService import net.corda.core.node.services.IdentityService
import net.corda.core.serialization.deserialize import net.corda.core.serialization.deserialize
import net.corda.core.serialization.serialize import net.corda.core.serialization.serialize
import net.corda.core.crypto.*
import net.i2p.crypto.eddsa.EdDSAPublicKey import net.i2p.crypto.eddsa.EdDSAPublicKey
import java.math.BigDecimal import java.math.BigDecimal
import java.time.LocalDate import java.time.LocalDate
@ -113,7 +112,7 @@ object JsonSupport {
object NodeInfoSerializer : JsonSerializer<NodeInfo>() { object NodeInfoSerializer : JsonSerializer<NodeInfo>() {
override fun serialize(value: NodeInfo, gen: JsonGenerator, serializers: SerializerProvider) { override fun serialize(value: NodeInfo, gen: JsonGenerator, serializers: SerializerProvider) {
gen.writeString(Base58.encode(value.serialize().bits)) gen.writeString(Base58.encode(value.serialize().bytes))
} }
} }

View File

@ -13,12 +13,10 @@ import net.corda.core.node.services.ServiceType
import net.corda.core.protocols.ProtocolLogic import net.corda.core.protocols.ProtocolLogic
import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.core.transactions.FilteredTransaction import net.corda.core.transactions.FilteredTransaction
import net.corda.core.transactions.WireTransaction
import net.corda.core.utilities.ProgressTracker import net.corda.core.utilities.ProgressTracker
import net.corda.irs.protocols.FixingProtocol import net.corda.irs.protocols.FixingProtocol
import net.corda.irs.protocols.RatesFixProtocol import net.corda.irs.protocols.RatesFixProtocol
import net.corda.node.services.api.AcceptsFileUpload import net.corda.node.services.api.AcceptsFileUpload
import net.corda.node.services.api.ServiceHubInternal
import net.corda.node.utilities.AbstractJDBCHashSet import net.corda.node.utilities.AbstractJDBCHashSet
import net.corda.node.utilities.FiberBox import net.corda.node.utilities.FiberBox
import net.corda.node.utilities.JDBCHashedTable import net.corda.node.utilities.JDBCHashedTable
@ -224,7 +222,7 @@ object NodeInterestRates {
// //
// Note that we will happily sign an invalid transaction: we don't bother trying to validate the whole // Note that we will happily sign an invalid transaction: we don't bother trying to validate the whole
// thing. This is so that later on we can start using tear-offs. // thing. This is so that later on we can start using tear-offs.
return signingKey.signWithECDSA(merkleRoot.bits, identity) return signingKey.signWithECDSA(merkleRoot.bytes, identity)
} }
} }