Skip to content

Commit

Permalink
chore: adding commitV2 hash fn
Browse files Browse the repository at this point in the history
  • Loading branch information
chatton committed Sep 12, 2024
1 parent 354dbe9 commit 94a57fc
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions modules/core/04-channel/types/packet.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 94a57fc

Please sign in to comment.