Skip to content

Commit

Permalink
Update EIP-3540: Use exceptions with error messages in reference code (
Browse files Browse the repository at this point in the history
  • Loading branch information
gumb0 authored Nov 10, 2022
1 parent da8b23d commit d646483
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions EIPS/eip-3540.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,45 +312,57 @@ S_DATA = 0x02
def is_eof(code: bytes) -> bool:
return code.startswith(MAGIC)

class ValidationException(Exception):
pass

# Validate EOF code.
# Raises ValidationException on invalid code
def validate_eof(code: bytes):
# Check version
assert len(code) >= 3 and code[2] == VERSION
if len(code) < 3 or code[2] != VERSION:
raise ValidationException("invalid version")

# Process section headers
section_sizes = {S_CODE: 0, S_DATA: 0}
pos = 3
while True:
# Terminator not found
assert pos < len(code)
if pos >= len(code):
raise ValidationException("no section terminator")

section_id = code[pos]
pos += 1
if section_id == S_TERMINATOR:
break

# Disallow unknown sections
assert section_id in section_sizes
if not section_id in section_sizes:
raise ValidationException("invalid section id")

# Data section preceding code section
assert section_id != S_DATA or section_sizes[S_CODE] != 0
if section_id == S_DATA and section_sizes[S_CODE] == 0:
raise ValidationException("data section preceding code section")

# Multiple sections with the same id
assert section_sizes[section_id] == 0
if section_sizes[section_id] != 0:
raise ValidationException("multiple sections with same id")

# Truncated section size
assert (pos + 1) < len(code)
if (pos + 1) >= len(code):
raise ValidationException("truncated section size")
section_sizes[section_id] = (code[pos] << 8) | code[pos + 1]
pos += 2

# Empty section
assert section_sizes[section_id] != 0
if section_sizes[section_id] == 0:
raise ValidationException("empty section")

# Code section cannot be absent
assert section_sizes[S_CODE] != 0
if section_sizes[S_CODE] == 0:
raise ValidationException("no code section")

# The entire container must be scanned
assert len(code) == (pos + section_sizes[S_CODE] + section_sizes[S_DATA])
if len(code) != (pos + section_sizes[S_CODE] + section_sizes[S_DATA]):
raise ValidationException("container size not equal to sum of section sizes")
```

## Security Considerations
Expand Down

0 comments on commit d646483

Please sign in to comment.