cosmos / interchain-security

Interchain Security is an open sourced IBC application which allows cosmos blockchains to lease their proof-of-stake security to one another.
https://cosmos.github.io/interchain-security/
Other
156 stars 127 forks source link

refactor key generation and parsing functions #423

Closed MSalopek closed 2 years ago

MSalopek commented 2 years ago

Key generation in this repo uses copy() with basic slice concatenation. This can be a bit difficult to follow when parsing through the code.

We could make the key generation more readble by switching from something like this:

// tsAndChainIdKey returns the key with the following format:
// bytePrefix | len(timestamp) | timestamp | chainID
func tsAndChainIdKey(prefix byte, timestamp time.Time, chainID string) []byte {
    timeBz := sdk.FormatTimeBytes(timestamp)
    timeBzL := len(timeBz)

    bz := make([]byte, len([]byte{prefix})+8+timeBzL+len(chainID))
    // copy the prefix
    byteLen := copy(bz, []byte{prefix})
    // copy the time length
    byteLen += copy(bz[byteLen:], sdk.Uint64ToBigEndian(uint64(timeBzL)))
    // copy the time bytes
    byteLen += copy(bz[byteLen:], timeBz)
    // copy the chainId
    copy(bz[byteLen:], chainID)
    return bz
}

to this (uses consecutive append operations):

func tsAndChainIdKey(prefix byte, timestamp time.Time, chainID string) []byte {
    timeBytes := sdk.FormatTimeBytes(timestamp)
    lenTimeBytes := sdk.Uint64ToBigEndian(uint64(len(timeBytes)))
        lenKey := len([]byte{prefix})+8+len(timeBytes)+len(chainID)

        // allocates array but does not populate with zero vals
    bz := make([]byte, 0, lenKey)
    bz = append(bz, []byte{prefix}...)
    bz = append(bz, lenTimeBytes...)
    bz = append(bz, timeBytes...)
    bz = append(bz, chainID...)
    return bz
}

Originally posted in discussion: https://github.com/cosmos/interchain-security/pull/422#discussion_r1011704124

mpoke commented 2 years ago

Fixed by https://github.com/cosmos/interchain-security/pull/426