Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add predicate packing helper #710

Merged
merged 7 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions core/predicate_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/ava-labs/subnet-evm/core/types"
"github.com/ava-labs/subnet-evm/params"
"github.com/ava-labs/subnet-evm/precompile/precompileconfig"
"github.com/ava-labs/subnet-evm/utils"
predicateutils "github.com/ava-labs/subnet-evm/utils/predicate"
"github.com/ethereum/go-ethereum/common"
)

Expand Down Expand Up @@ -49,7 +49,7 @@ func checkPrecompilePredicates(rules params.Rules, predicateContext *precompilec
return fmt.Errorf("predicate %s failed verification for tx %s: specified %s in access list multiple times", address, tx.Hash(), address)
}
precompileAddressChecks[address] = struct{}{}
predicateBytes := utils.HashSliceToBytes(accessTuple.StorageKeys)
predicateBytes := predicateutils.HashSliceToBytes(accessTuple.StorageKeys)
if err := predicater.VerifyPredicate(predicateContext, predicateBytes); err != nil {
return fmt.Errorf("predicate %s failed verification for tx %s: %w", address, tx.Hash(), err)
}
Expand Down Expand Up @@ -77,7 +77,7 @@ func checkProposerPrecompilePredicates(rules params.Rules, predicateContext *pre
return fmt.Errorf("predicate %s failed verification for tx %s: specified %s in access list multiple times", address, tx.Hash(), address)
}
precompileAddressChecks[address] = struct{}{}
predicateBytes := utils.HashSliceToBytes(accessTuple.StorageKeys)
predicateBytes := predicateutils.HashSliceToBytes(accessTuple.StorageKeys)
if err := predicater.VerifyPredicate(predicateContext, predicateBytes); err != nil {
return fmt.Errorf("predicate %s failed verification for tx %s: %w", address, tx.Hash(), err)
}
Expand Down
4 changes: 2 additions & 2 deletions core/state/statedb.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import (
"github.com/ava-labs/subnet-evm/metrics"
"github.com/ava-labs/subnet-evm/params"
"github.com/ava-labs/subnet-evm/trie"
"github.com/ava-labs/subnet-evm/utils"
predicateutils "github.com/ava-labs/subnet-evm/utils/predicate"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
Expand Down Expand Up @@ -1109,7 +1109,7 @@ func (s *StateDB) preparePredicateStorageSlots(rules params.Rules, list types.Ac
if !rules.PredicateExists(el.Address) {
continue
}
s.predicateStorageSlots[el.Address] = utils.HashSliceToBytes(el.StorageKeys)
s.predicateStorageSlots[el.Address] = predicateutils.HashSliceToBytes(el.StorageKeys)
}
}

Expand Down
26 changes: 0 additions & 26 deletions utils/bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

package utils

import "github.com/ethereum/go-ethereum/common"

// IncrOne increments bytes value by one
func IncrOne(bytes []byte) {
index := len(bytes) - 1
Expand All @@ -18,27 +16,3 @@ func IncrOne(bytes []byte) {
}
}
}

// HashSliceToBytes serializes a []common.Hash into a tightly packed byte array.
func HashSliceToBytes(hashes []common.Hash) []byte {
bytes := make([]byte, common.HashLength*len(hashes))
for i, hash := range hashes {
copy(bytes[i*common.HashLength:], hash[:])
}
return bytes
}

// BytesToHashSlice packs [b] into a slice of hash values with zero padding
// to the right if the length of b is not a multiple of 32.
func BytesToHashSlice(b []byte) []common.Hash {
var (
numHashes = (len(b) + 31) / 32
hashes = make([]common.Hash, numHashes)
)

for i := range hashes {
start := i * common.HashLength
copy(hashes[i][:], b[start:])
}
return hashes
}
28 changes: 0 additions & 28 deletions utils/bytes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@
package utils

import (
"bytes"
"testing"

"github.com/ava-labs/avalanchego/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestIncrOne(t *testing.T) {
Expand Down Expand Up @@ -39,28 +36,3 @@ func TestIncrOne(t *testing.T) {
})
}
}

func testBytesToHashSlice(t testing.TB, b []byte) {
hashSlice := BytesToHashSlice(b)

copiedBytes := HashSliceToBytes(hashSlice)

if len(b)%32 == 0 {
require.Equal(t, b, copiedBytes)
} else {
require.Equal(t, b, copiedBytes[:len(b)])
// Require that any additional padding is all zeroes
padding := copiedBytes[len(b):]
require.Equal(t, bytes.Repeat([]byte{0x00}, len(padding)), padding)
}
}

func FuzzHashSliceToBytes(f *testing.F) {
for i := 0; i < 100; i++ {
f.Add(utils.RandomBytes(i))
}

f.Fuzz(func(t *testing.T, a []byte) {
testBytesToHashSlice(t, a)
})
}
11 changes: 11 additions & 0 deletions utils/predicate/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Predicate Utils

This package provides simple helpers to pack/unpack byte slices for a predicate transaction, where a byte slice of size N is encoded in the access list of a transaction.

## Encoding

A byte slice of size N is encoded as:

1. Slice of N bytes
2. Delimiter byte `0xff`
3. Appended 0s to the nearest multiple of 32 bytes
68 changes: 68 additions & 0 deletions utils/predicate/predicate_bytes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// (c) 2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package predicateutils

import (
"fmt"

"github.com/ethereum/go-ethereum/common"
)

// PredicateEndByte is used as a delimiter for the bytes packed into a precompile predicate.
// Precompile predicates are encoded in the Access List of transactions in the access tuples
// which means that its length must be a multiple of 32 (common.HashLength).
// For messages with a length that does not comply to that, this delimiter is used to
// append/remove padding.
var PredicateEndByte = byte(0xff)

// PackPredicate packs [predicate] by delimiting the actual message with [PredicateEndByte]
// and zero padding to reach a length that is a multiple of 32.
func PackPredicate(predicate []byte) []byte {
predicate = append(predicate, PredicateEndByte)
return common.RightPadBytes(predicate, (len(predicate)+31)/32*32)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we use common.HashLength instead of using hardcoded 32?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also in the rest of the file

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is copying the style used here: https://github.com/ethereum/go-ethereum/blob/master/accounts/abi/pack.go#L33. I think it's clearer to use 32 in this case since we're using 31 as well, so we can either have the current code or:

always use constant and relative constant

return common.RightPadBytes(predicate, (len(predicate)+(common.HashLength-1))/common.HashLength*common.HashLength)

use 31 but the constant for 32

return common.RightPadBytes(predicate, (len(predicate)+31)/common.HashLength*common.HashLength)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if these are supposed to be same with hash length then I'd say we should (and geth should) use constant. but no pressure.

}

// UnpackPredicate unpacks a predicate by stripping right padded zeroes, checking for the delimter,
// ensuring there is not excess padding, and returning the original message.
// Returns an error if it finds an incorrect encoding.
func UnpackPredicate(paddedPredicate []byte) ([]byte, error) {
trimmedPredicateBytes := common.TrimRightZeroes(paddedPredicate)
if len(trimmedPredicateBytes) == 0 {
return nil, fmt.Errorf("predicate specified invalid all zero bytes: 0x%x", paddedPredicate)
}

if expectedPaddedLength := (len(trimmedPredicateBytes) + 31) / 32 * 32; expectedPaddedLength != len(paddedPredicate) {
return nil, fmt.Errorf("predicate specified invalid padding with length (%d), expected length (%d)", len(paddedPredicate), expectedPaddedLength)
}

if trimmedPredicateBytes[len(trimmedPredicateBytes)-1] != PredicateEndByte {
return nil, fmt.Errorf("invalid end delimiter")
}

return trimmedPredicateBytes[:len(trimmedPredicateBytes)-1], nil
}

// HashSliceToBytes serializes a []common.Hash into a tightly packed byte array.
func HashSliceToBytes(hashes []common.Hash) []byte {
bytes := make([]byte, common.HashLength*len(hashes))
for i, hash := range hashes {
copy(bytes[i*common.HashLength:], hash[:])
}
return bytes
}

// BytesToHashSlice packs [b] into a slice of hash values with zero padding
// to the right if the length of b is not a multiple of 32.
func BytesToHashSlice(b []byte) []common.Hash {
var (
numHashes = (len(b) + 31) / 32
hashes = make([]common.Hash, numHashes)
)

for i := range hashes {
start := i * common.HashLength
copy(hashes[i][:], b[start:])
}
return hashes
}
73 changes: 73 additions & 0 deletions utils/predicate/predicate_bytes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// (c) 2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package predicateutils

import (
"bytes"
"testing"

"github.com/ava-labs/avalanchego/utils"
"github.com/stretchr/testify/require"
)

func testBytesToHashSlice(t testing.TB, b []byte) {
hashSlice := BytesToHashSlice(b)

copiedBytes := HashSliceToBytes(hashSlice)

if len(b)%32 == 0 {
require.Equal(t, b, copiedBytes)
} else {
require.Equal(t, b, copiedBytes[:len(b)])
// Require that any additional padding is all zeroes
padding := copiedBytes[len(b):]
require.Equal(t, bytes.Repeat([]byte{0x00}, len(padding)), padding)
}
}

func FuzzHashSliceToBytes(f *testing.F) {
for i := 0; i < 100; i++ {
f.Add(utils.RandomBytes(i))
}

f.Fuzz(func(t *testing.T, b []byte) {
testBytesToHashSlice(t, b)
})
}

func testPackPredicate(t testing.TB, b []byte) {
packedPredicate := PackPredicate(b)
unpackedPredicated, err := UnpackPredicate(packedPredicate)
require.NoError(t, err)
require.Equal(t, b, unpackedPredicated)
}

func FuzzPackPredicate(f *testing.F) {
for i := 0; i < 100; i++ {
f.Add(utils.RandomBytes(i))
}

f.Fuzz(func(t *testing.T, b []byte) {
testPackPredicate(t, b)
})
}

func FuzzUnpackInvalidPredicate(f *testing.F) {
// Seed the fuzzer with non-zero length padding of zeroes or non-zeroes.
for i := 1; i < 100; i++ {
f.Add(utils.RandomBytes(i))
f.Add(make([]byte, i))
}

f.Fuzz(func(t *testing.T, b []byte) {
// Ensure that adding the invalid padding to any length correctly packed predicate
// results in failing to unpack it.
for _, l := range []int{0, 1, 31, 32, 33, 63, 64, 65} {
validPredicate := PackPredicate(utils.RandomBytes(l))
invalidPredicate := append(validPredicate, b...)
_, err := UnpackPredicate(invalidPredicate)
require.Error(t, err)
}
})
}