Skip to content

Commit

Permalink
ETCM-254: Optionally allow decoding packets bigger than the maximum.
Browse files Browse the repository at this point in the history
  • Loading branch information
aakoshh committed Oct 20, 2020
1 parent ec459dc commit 30693b4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
Expand Up @@ -34,12 +34,12 @@ object Packet {
Attempt.successful(DecodeResult(bits, BitVector.empty))
}

private val packetDecoder: Decoder[Packet] =
private def packetDecoder(allowDecodeOverMaxPacketSize: Boolean): Decoder[Packet] =
for {
_ <- Decoder { bits =>
Attempt
.guard(
bits.size <= MaxPacketBitsSize,
allowDecodeOverMaxPacketSize || bits.size <= MaxPacketBitsSize,
"Packet to decode exceeds maximum size."
)
.map(_ => DecodeResult((), bits))
Expand All @@ -61,8 +61,11 @@ object Packet {
} yield bits
}

implicit val packetCodec: Codec[Packet] =
Codec[Packet](packetEncoder, packetDecoder)
/** Create a codec for packets. Some Ethereum clients don't respect the size limits;
* for compatibility with them the check during decode can be turned off.
*/
def packetCodec(allowDecodeOverMaxPacketSize: Boolean): Codec[Packet] =
Codec[Packet](packetEncoder, packetDecoder(allowDecodeOverMaxPacketSize))

/** Serialize the payload, sign the data and compute the hash. */
def pack(
Expand Down
Expand Up @@ -14,6 +14,8 @@ class PacketSpec extends FlatSpec with Matchers {
import DefaultCodecs._
implicit val sigalg = new MockSigAlg()

implicit val packetCodec = Packet.packetCodec(allowDecodeOverMaxPacketSize = false)

val MaxPacketBytesSize = Packet.MaxPacketBitsSize / 8
val MacBytesSize = Packet.MacBitsSize / 8
val SigBytesSize = Packet.SigBitsSize / 8
Expand Down Expand Up @@ -78,6 +80,12 @@ class PacketSpec extends FlatSpec with Matchers {
Codec.decode[Packet](nBytesAsBits(MaxPacketBytesSize + 1))
}
}

it should "optionally allow the data to exceed the maximum size" in {
val permissiblePacketCodec: Codec[Packet] = Packet.packetCodec(allowDecodeOverMaxPacketSize = true)
Codec.decode[Packet](nBytesAsBits(MaxPacketBytesSize * 2))(permissiblePacketCodec).isSuccessful shouldBe true
}

it should "fail if there's less data than the hash size" in {
expectFailure(
s"Hash: cannot acquire ${Packet.MacBitsSize} bits from a vector that contains ${Packet.MacBitsSize - 8} bits"
Expand Down

0 comments on commit 30693b4

Please sign in to comment.