Skip to content

fix(store): replace panics with error returns in SMT - #591

Open
yasinlex wants to merge 1 commit into
canopy-network:mainfrom
yasinlex:fix/replace-panics-with-errors-in-smt
Open

yasinlex wants to merge 1 commit into
canopy-network:mainfrom
yasinlex:fix/replace-panics-with-errors-in-smt

Conversation

@yasinlex

@yasinlex yasinlex commented Sep 5, 2026

Copy link
Copy Markdown

Problem

The SMT (Sparse Merkle Tree) implementation in store/smt.go uses panic() in 5 places for conditions that should return errors. In a production blockchain node, these panics cause an unrecoverable crash when encountering corrupted data or database errors.

Changes

getOtherChild() (line 1156)

  • Before: panics if child key doesn't match
  • After: returns ErrChildNotFound error

replaceChild() (line 1167)

  • Before: panics if old key doesn't match any child
  • After: returns ErrChildNotReplaced error

initializeTree() (line 481)

  • Before: 4 panic() calls on database write failures
  • After: returns errors from each database operation

NewSMT() (line 154)

  • Before: panics on getNode() error and calls initializeTree() without error handling
  • After: returns errors from both operations

NewDefaultSMT() (line 149)

  • Before: no error return
  • After: propagates error from NewSMT()

New Error Types

Added to store/error.go:

  • ErrChildNotFound(childKey string) - for missing child nodes
  • ErrChildNotReplaced(oldKey string) - for failed child replacements

Impact

  • Before: Corrupted SMT data on disk → node crashes with panic
  • After: Corrupted SMT data on disk → error propagated to caller, node can handle gracefully

Testing

  • All existing tests pass
  • Build succeeds with go build ./store/...

Replace all panic() calls in store/smt.go with proper error returns
to prevent node crashes on corrupted data or database errors.

Changes:
- getOtherChild(): returns error instead of panicking when child not found
- replaceChild(): returns error instead of panicking when child not replaced
- initializeTree(): returns error instead of panicking on DB write failures
- NewSMT(): returns error from initializeTree() instead of panicking
- NewDefaultSMT(): propagates error from NewSMT()
- Update all callers in store.go and smt_test.go

This ensures the node handles corrupted Merkle tree data gracefully
rather than crashing with an unrecoverable panic.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants