From 51e023800ea0810dd873a83aaec39c4c5e17df56 Mon Sep 17 00:00:00 2001 From: Weixie Cui Date: Thu, 2 Jul 2026 03:58:09 +0800 Subject: [PATCH] trie/bintrie: fix panic in code chunk key computation for chunknr=0 When chunknr is zero, codeOffset+chunknr encodes to a single byte. The short slice caused getBinaryTreeKey to panic on offset[:31]. Zero-pad the offset to 32 bytes before hashing. --- trie/bintrie/key_encoding.go | 3 ++- trie/bintrie/key_encoding_test.go | 34 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 trie/bintrie/key_encoding_test.go diff --git a/trie/bintrie/key_encoding.go b/trie/bintrie/key_encoding.go index 265935293b..62e471a014 100644 --- a/trie/bintrie/key_encoding.go +++ b/trie/bintrie/key_encoding.go @@ -105,7 +105,8 @@ func GetBinaryTreeKeyStorageSlot(address common.Address, slotnum []byte) []byte } func GetBinaryTreeKeyCodeChunk(address common.Address, chunknr *uint256.Int) []byte { - chunkOffset := new(uint256.Int).Add(codeOffset, chunknr).Bytes() + chunkOffsetBytes32 := new(uint256.Int).Add(codeOffset, chunknr).Bytes32() + chunkOffset := chunkOffsetBytes32[:] return GetBinaryTreeKey(address, chunkOffset) } diff --git a/trie/bintrie/key_encoding_test.go b/trie/bintrie/key_encoding_test.go new file mode 100644 index 0000000000..94deb04f73 --- /dev/null +++ b/trie/bintrie/key_encoding_test.go @@ -0,0 +1,34 @@ +// Copyright 2025 go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package bintrie + +import ( + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/holiman/uint256" +) + +// TestGetBinaryTreeKeyCodeChunkZero is a regression test: chunknr=0 encodes +// codeOffset (128) to a single byte, which caused getBinaryTreeKey to panic on +// offset[:31] before the offset was zero-padded to 32 bytes. +func TestGetBinaryTreeKeyCodeChunkZero(t *testing.T) { + key := GetBinaryTreeKeyCodeChunk(common.Address{}, uint256.NewInt(0)) + if len(key) != 32 { + t.Fatalf("expected 32-byte key, got %d", len(key)) + } +}