From 94a57fc82b3ef9babb11bfc4e7efa196970b171e Mon Sep 17 00:00:00 2001 From: chatton Date: Thu, 12 Sep 2024 11:08:52 +0100 Subject: [PATCH] chore: adding commitV2 hash fn --- modules/core/04-channel/types/packet.go | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/modules/core/04-channel/types/packet.go b/modules/core/04-channel/types/packet.go index 49b569af9b2..434d33df692 100644 --- a/modules/core/04-channel/types/packet.go +++ b/modules/core/04-channel/types/packet.go @@ -26,6 +26,7 @@ func CommitPacket(packet Packet) []byte { case IBC_VERSION_UNSPECIFIED, IBC_VERSION_1: return commitV1Packet(packet) case IBC_VERSION_2: + // TODO: convert to PacketV2 and commit. return commitV2Packet(packet) default: panic("unsupported version") @@ -100,6 +101,43 @@ func commitV2Packet(packet Packet) []byte { return hash[:] } +// CommitPacketV2 returns the V2 packet commitment bytes. The commitment consists of: +// sha256_hash(timeout) + sha256_hash(destinationID) + sha256_hash(packetData) from a given packet. +// This results in a fixed length preimage. +// NOTE: A fixed length preimage is ESSENTIAL to prevent relayers from being able +// to malleate the packet fields and create a commitment hash that matches the original packet. +func CommitPacketV2(packet PacketV2) []byte { + timeoutHash := sha256.Sum256([]byte(packet.Timeout)) + buf := timeoutHash[:] + + destIDHash := sha256.Sum256([]byte(packet.DestinationId)) + buf = append(buf, destIDHash[:]...) + + for _, data := range packet.Data { + buf = append(buf, hashPacketData(data)...) + } + + hash := sha256.Sum256(buf) + return hash[:] +} + +// hashPacketData returns the hash of the packet data. +func hashPacketData(data PacketData) []byte { + var buf []byte + sourceHash := sha256.Sum256([]byte(data.SourcePort)) + buf = append(buf, sourceHash[:]...) + destHash := sha256.Sum256([]byte(data.DestinationPort)) + buf = append(buf, destHash[:]...) + payloadValueHash := sha256.Sum256(data.Payload.Value) + buf = append(buf, payloadValueHash[:]...) + payloadEncodingHash := sha256.Sum256([]byte(data.Payload.Encoding)) + buf = append(buf, payloadEncodingHash[:]...) + payloadVersionHash := sha256.Sum256([]byte(data.Payload.Version)) + buf = append(buf, payloadVersionHash[:]...) + hash := sha256.Sum256(buf) + return hash[:] +} + // CommitAcknowledgement returns the hash of commitment bytes func CommitAcknowledgement(data []byte) []byte { hash := sha256.Sum256(data)