Skip to content

Commit

Permalink
Make cached sha256 of message data available. (#239)
Browse files Browse the repository at this point in the history
  • Loading branch information
ajsutton authored May 10, 2022
1 parent 0fafa5d commit 9bd7190
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/main/kotlin/io/libp2p/pubsub/PubsubRouter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import io.libp2p.core.Stream
import io.libp2p.core.crypto.sha256
import io.libp2p.core.pubsub.ValidationResult
import io.libp2p.etc.types.WBytes
import io.libp2p.etc.types.toWBytes
import io.netty.channel.ChannelHandler
import pubsub.pb.Rpc
import java.util.Random
Expand All @@ -25,6 +24,8 @@ interface PubsubMessage {
val topics: List<Topic>
get() = protobufMessage.topicIDsList

fun messageSha256() = sha256(protobufMessage.toByteArray())

override fun equals(other: Any?): Boolean

/**
Expand All @@ -35,17 +36,20 @@ interface PubsubMessage {
}

abstract class AbstractPubsubMessage : PubsubMessage {
@Volatile var hashCode: Int? = null
override fun equals(other: Any?) = protobufMessage == (other as? PubsubMessage)?.protobufMessage
override fun hashCode(): Int {
val cached = hashCode
@Volatile private var sha256: ByteArray? = null

override fun messageSha256(): ByteArray {
val cached = sha256
if (cached != null) {
return cached
}
val result = sha256(protobufMessage.toByteArray()).toWBytes().hashCode()
hashCode = result
val result = sha256(protobufMessage.toByteArray())
sha256 = result
return result
}

override fun equals(other: Any?) = protobufMessage == (other as? PubsubMessage)?.protobufMessage
override fun hashCode() = messageSha256().contentHashCode()
override fun toString() = "PubsubMessage{$protobufMessage}"
}

Expand Down

0 comments on commit 9bd7190

Please sign in to comment.