Skip to content

Commit

Permalink
use correct minimum size when reading block / state headers (#6263)
Browse files Browse the repository at this point in the history
`sizeof` also includes padding between fields, while SSZ defines
`fixedPortionSize` (on type) or `sszSize` (on value) to denote
required bytes to encode. Switch forked block/state readers to SSZ size.
As blocks/states are much larger than the padding, this doesn't affect
practical use cases but is slightly more correct this way.
  • Loading branch information
etan-status authored May 25, 2024
1 parent de74019 commit 0efc81d
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions beacon_chain/spec/forks.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1360,31 +1360,31 @@ func readSszForkedHashedBeaconState*(cfg: RuntimeConfig, data: openArray[byte]):
ForkedHashedBeaconState {.raises: [SerializationError].} =
## Read a state picking the right fork by first reading the slot from the byte
## source
if data.len() < sizeof(BeaconStateHeader):
raise (ref MalformedSszError)(msg: "Not enough data for BeaconState header")
const numHeaderBytes = fixedPortionSize(BeaconStateHeader)
if data.len() < numHeaderBytes:
raise (ref MalformedSszError)(msg: "Incomplete BeaconState header")
let header = SSZ.decode(
data.toOpenArray(0, sizeof(BeaconStateHeader) - 1),
BeaconStateHeader)
data.toOpenArray(0, numHeaderBytes - 1), BeaconStateHeader)

# TODO https://github.com/nim-lang/Nim/issues/19357
result = readSszForkedHashedBeaconState(cfg, header.slot, data)

type
ForkedBeaconBlockHeader = object
message*: uint32 # message offset
signature*: ValidatorSig
message: uint32 # message offset
signature: ValidatorSig
slot: Slot # start of BeaconBlock

func readSszForkedSignedBeaconBlock*(
cfg: RuntimeConfig, data: openArray[byte]):
ForkedSignedBeaconBlock {.raises: [SerializationError].} =
## Helper to read a header from bytes when it's not certain what kind of block
## it is
if data.len() < sizeof(ForkedBeaconBlockHeader):
raise (ref MalformedSszError)(msg: "Not enough data for SignedBeaconBlock header")
const numHeaderBytes = fixedPortionSize(ForkedBeaconBlockHeader)
if data.len() < numHeaderBytes:
raise (ref MalformedSszError)(msg: "Incomplete SignedBeaconBlock header")
let header = SSZ.decode(
data.toOpenArray(0, sizeof(ForkedBeaconBlockHeader) - 1),
ForkedBeaconBlockHeader)
data.toOpenArray(0, numHeaderBytes - 1), ForkedBeaconBlockHeader)

# TODO https://github.com/nim-lang/Nim/issues/19357
result = ForkedSignedBeaconBlock(
Expand Down

0 comments on commit 0efc81d

Please sign in to comment.