Search Apps Documentation Source Content File Folder Download Copy Actions Download

commitment.gno

2.18 Kb · 68 lines
 1package types
 2
 3import (
 4	"crypto/sha256"
 5
 6	"gno.land/p/aib/encoding"
 7)
 8
 9// CommitPacket returns the V2 packet commitment bytes. The commitment consists of:
10// ha256_hash(0x02 + sha256_hash(destinationClient) + sha256_hash(timeout) + sha256_hash(payload)) from a given packet.
11// This results in a fixed length preimage of 32 bytes.
12// NOTE: A fixed length preimage is ESSENTIAL to prevent relayers from being able
13// to malleate the packet fields and create a commitment hash that matches the original packet.
14func CommitPacket(packet Packet) []byte {
15	var buf []byte
16	destIDHash := sha256.Sum256([]byte(packet.DestinationClient))
17	buf = append(buf, destIDHash[:]...)
18
19	timeoutBytes := encoding.Uint64ToBigEndian(packet.TimeoutTimestamp)
20	timeoutHash := sha256.Sum256(timeoutBytes)
21	buf = append(buf, timeoutHash[:]...)
22
23	var appBytes []byte
24	for _, payload := range packet.Payloads {
25		appBytes = append(appBytes, hashPayload(payload)...)
26	}
27	appHash := sha256.Sum256(appBytes)
28	buf = append(buf, appHash[:]...)
29
30	buf = append([]byte{byte(2)}, buf...)
31
32	hash := sha256.Sum256(buf)
33	return hash[:]
34}
35
36// CommitAcknowledgement returns the V2 acknowledgement commitment bytes.
37// The commitment consists of:
38// sha256_hash(0x02 + sha256_hash(ack1) + sha256_hash(ack2) + ...) from a given
39// acknowledgement.
40func CommitAcknowledgement(acknowledgement Acknowledgement) []byte {
41	var buf []byte
42	for _, ack := range acknowledgement.AppAcknowledgements {
43		hash := sha256.Sum256(ack)
44		buf = append(buf, hash[:]...)
45	}
46
47	buf = append([]byte{byte(2)}, buf...)
48
49	hash := sha256.Sum256(buf)
50	return hash[:]
51}
52
53// hashPayload returns the hash of the payload.
54func hashPayload(data Payload) []byte {
55	var buf []byte
56	sourceHash := sha256.Sum256([]byte(data.SourcePort))
57	buf = append(buf, sourceHash[:]...)
58	destHash := sha256.Sum256([]byte(data.DestinationPort))
59	buf = append(buf, destHash[:]...)
60	payloadVersionHash := sha256.Sum256([]byte(data.Version))
61	buf = append(buf, payloadVersionHash[:]...)
62	payloadEncodingHash := sha256.Sum256([]byte(data.Encoding))
63	buf = append(buf, payloadEncodingHash[:]...)
64	payloadValueHash := sha256.Sum256(data.Value)
65	buf = append(buf, payloadValueHash[:]...)
66	hash := sha256.Sum256(buf)
67	return hash[:]
68}