forked from ethereum/go-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 5
feat: libevm/triedb/firewood
scaffolding with proposal propagation
#237
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
Open
ARR4N
wants to merge
7
commits into
main
Choose a base branch
from
arr4n/trienode-payloads
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
999f2c0
feat: `trienode` payloads for `Node`, `NodeSet`, and `MergedNodeSet`
ARR4N 42a256e
feat: `libevm/triedb/firewood` scaffolding with integration test for …
ARR4N 7cb9347
refactor: collapse `handle` into `proposal`
ARR4N 7bb95a5
chore: placate the linter
ARR4N 5253009
doc: `trienode` hook methods + `proposal` finalizer test
ARR4N 079a98e
Merge branch 'main' into arr4n/trienode-payloads
ARR4N 058bc81
feat: allow multiple handles per proposal payload
ARR4N File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
// Copyright 2025 the libevm authors. | ||
// | ||
// The libevm additions to go-ethereum are free software: you can redistribute | ||
// them and/or modify them 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 libevm additions are distributed in the hope that they 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 | ||
// <http://www.gnu.org/licenses/>. | ||
|
||
// The firewood package provides a [triedb.DBOverride] backed by [Firewood]. | ||
// | ||
// [Firewood]: https://github.com/ava-labs/firewood | ||
package firewood | ||
|
||
import ( | ||
"errors" | ||
"runtime" | ||
|
||
"github.com/ava-labs/libevm/common" | ||
"github.com/ava-labs/libevm/libevm/stateconf" | ||
"github.com/ava-labs/libevm/trie/trienode" | ||
"github.com/ava-labs/libevm/trie/triestate" | ||
"github.com/ava-labs/libevm/triedb" | ||
) | ||
|
||
var _ triedb.DBOverride = (*database)(nil) | ||
|
||
type database struct { | ||
triedb.DBOverride // TODO(alarso16) remove once this type implements the interface | ||
} | ||
|
||
func (db *database) Update(root, parent common.Hash, block uint64, nodes *trienode.MergedNodeSet, states *triestate.Set, opts ...stateconf.TrieDBUpdateOption) error { | ||
// TODO(alarso16) | ||
var _ *proposals = extras.MergedNodeSet.Get(nodes) | ||
|
||
db.afterUpdate(nodes) // MUST be the last statement before the final return | ||
return errors.New("unimplemented") | ||
} | ||
|
||
// afterUpdate MUST be called at the end of [database.Update] to ensure that the | ||
// Rust handle isn't freed any earlier. This is an overly cautious, defensive | ||
// approach that will make Rustaceans scream "I told you so". | ||
func (db *database) afterUpdate(nodes *trienode.MergedNodeSet) { | ||
runtime.KeepAlive(extras.MergedNodeSet.Get(nodes)) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
// Copyright 2025 the libevm authors. | ||
// | ||
// The libevm additions to go-ethereum are free software: you can redistribute | ||
// them and/or modify them 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 libevm additions are distributed in the hope that they 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 | ||
// <http://www.gnu.org/licenses/>. | ||
|
||
package firewood | ||
|
||
import ( | ||
"fmt" | ||
"runtime" | ||
|
||
"github.com/ava-labs/libevm/common" | ||
"github.com/ava-labs/libevm/trie/trienode" | ||
) | ||
|
||
// RegisterExtras registers Firewood proposals with [trienode.RegisterExtras]. | ||
// This MUST be called in and only in tests / package main to avoid polluting | ||
// other packages. A call to RegisterExtras is required for the rest of this | ||
// package to function correctly. | ||
func RegisterExtras() { | ||
extras = trienode.RegisterExtras[proposals, proposals, struct{}]() | ||
} | ||
|
||
var extras trienode.ExtraPayloads[*proposals, *proposals, *struct{}] | ||
|
||
// A proposals carrier is embedded as a payload in the [trienode.NodeSet] object | ||
// returned by trie `Commit()`. A preceding call to [RegisterExtras] ensures | ||
// that the proposals will be propagated to [Database.Update]. | ||
type proposals struct { | ||
// root MUST match the argument returned by the trie's `Commit()` method. | ||
root common.Hash | ||
// handles MAY carry >=1 handle, based off different parents, but all MUST | ||
// result in the same root (i.e. the one specified in the other field). | ||
handles []*handle | ||
} | ||
|
||
func (p *proposals) injectInto(ns *trienode.NodeSet) { | ||
extras.NodeSet.Set(ns, p) | ||
} | ||
|
||
// A handle carries a Firewood FFI proposal handle (i.e. Rust-owned memory). | ||
// After construction, [handle.setFinalizer] SHOULD be called to ensure release | ||
// of resources via [handle.free] once the handle is garbage collected. | ||
type handle struct { | ||
// TODO(alarso16) place the FFI handle here | ||
|
||
// finalized is set by [handle.setFinalizer] to signal when said finalizer | ||
// has run; see https://go.dev/doc/gc-guide#Testing_object_death | ||
finalized chan struct{} | ||
} | ||
|
||
// setFinalizer calls [runtime.SetFinalizer] with `p`. | ||
func (h *handle) setFinalizer() { | ||
h.finalized = make(chan struct{}) | ||
runtime.SetFinalizer(h, (*handle).finalizer) | ||
} | ||
|
||
// finalizer is expected to be passed to [runtime.SetFinalizer], abstracted as a | ||
// method to guarantee that it doesn't accidentally capture the value being | ||
// collected, thus resurrecting it. | ||
func (h *handle) finalizer() { | ||
h.free() | ||
close(h.finalized) | ||
} | ||
|
||
// free is called when the [proposal] is no longer reachable. | ||
func (h *handle) free() { | ||
// TODO(alarso16) free the Rust object(s). | ||
} | ||
|
||
// AfterMergeNodeSet implements [trienode.MergedNodeSetHooks], copying at most | ||
// one proposal handle into the merged set. | ||
func (p *proposals) AfterMergeNodeSet(into *trienode.MergedNodeSet, ns *trienode.NodeSet) error { | ||
if p := extras.MergedNodeSet.Get(into); p.root != (common.Hash{}) { | ||
return fmt.Errorf(">1 %T carrying non-zero %T", ns, p) | ||
} | ||
// The GC finalizer is attached to the [payload], not to the [handle], so | ||
// we have to copy the entire object to ensure that it remains reachable. | ||
extras.MergedNodeSet.Set(into, extras.NodeSet.Get(ns)) | ||
return nil | ||
} | ||
|
||
// AfterAddNode implements [trienode.NodeSetHooks] as a noop. | ||
func (p *proposals) AfterAddNode(*trienode.NodeSet, []byte, *trienode.Node) {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
// Copyright 2025 the libevm authors. | ||
// | ||
// The libevm additions to go-ethereum are free software: you can redistribute | ||
// them and/or modify them 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 libevm additions are distributed in the hope that they 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 | ||
// <http://www.gnu.org/licenses/>. | ||
|
||
package firewood | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"os" | ||
"runtime" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/require" | ||
"golang.org/x/sync/errgroup" | ||
|
||
"github.com/ava-labs/libevm/common" | ||
"github.com/ava-labs/libevm/core/rawdb" | ||
"github.com/ava-labs/libevm/core/state" | ||
"github.com/ava-labs/libevm/core/types" | ||
"github.com/ava-labs/libevm/ethdb" | ||
"github.com/ava-labs/libevm/libevm/stateconf" | ||
"github.com/ava-labs/libevm/trie" | ||
"github.com/ava-labs/libevm/trie/trienode" | ||
"github.com/ava-labs/libevm/trie/triestate" | ||
"github.com/ava-labs/libevm/triedb" | ||
databasepkg "github.com/ava-labs/libevm/triedb/database" | ||
"github.com/ava-labs/libevm/triedb/hashdb" | ||
) | ||
|
||
func TestMain(m *testing.M) { | ||
alarso16 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
RegisterExtras() | ||
os.Exit(m.Run()) | ||
} | ||
|
||
// A cacheWithDummyProposals overrides `OpenTrie()` to returns a | ||
// [trieWithDummyProposals]. | ||
type cacheWithDummyProposals struct { | ||
state.Database | ||
} | ||
|
||
func (db *cacheWithDummyProposals) OpenTrie(root common.Hash) (state.Trie, error) { | ||
t, err := db.Database.OpenTrie(root) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &trieWithDummyProposals{Trie: t}, nil | ||
} | ||
|
||
// A trieWithDummyProposals overrides `Commit()` to inject a [proposal] into the | ||
// returned [trienode.NodeSet]. | ||
type trieWithDummyProposals struct { | ||
state.Trie | ||
} | ||
|
||
func (t *trieWithDummyProposals) Commit(collectLeaf bool) (common.Hash, *trienode.NodeSet, error) { | ||
root, set, err := t.Trie.Commit(collectLeaf) | ||
if err != nil { | ||
return common.Hash{}, nil, err | ||
} | ||
// This, combined with [proposalPayload.MergeNodeSet], is where the magic | ||
// happens. We use the existing geth plumbing to carry the proposal back to | ||
// [hashDBWithDummyProposals.Update], knowing that the Go GC will trigger | ||
// the FFI call to free the Rust memory. | ||
p := &proposals{ | ||
root: root, | ||
handles: []*handle{{}, {}}, | ||
} | ||
for _, h := range p.handles { | ||
h.setFinalizer() | ||
} | ||
p.injectInto(set) | ||
|
||
return root, set, nil | ||
} | ||
|
||
// A hashDBWithDummyProposals overrides `Update()` to capture the [proposal] | ||
// propagated from [trieWithDummyProposals.Commit]. | ||
type hashDBWithDummyProposals struct { | ||
*hashdb.Database | ||
got *proposals | ||
} | ||
|
||
func (db *hashDBWithDummyProposals) Reader(root common.Hash) (databasepkg.Reader, error) { | ||
return db.Database.Reader(root) | ||
} | ||
|
||
func (db *hashDBWithDummyProposals) Update(root, parent common.Hash, block uint64, nodes *trienode.MergedNodeSet, states *triestate.Set, opts ...stateconf.TrieDBUpdateOption) error { | ||
db.got = extras.MergedNodeSet.Get(nodes) | ||
return db.Database.Update(root, parent, block, nodes, states, opts...) | ||
} | ||
|
||
func TestProposalPropagation(t *testing.T) { | ||
db := rawdb.NewMemoryDatabase() | ||
backend := &hashDBWithDummyProposals{ | ||
Database: hashdb.New(db, nil, trie.MerkleResolver{}), | ||
} | ||
tdb := triedb.NewDatabase(db, &triedb.Config{ | ||
DBOverride: func(db ethdb.Database) triedb.DBOverride { | ||
return backend | ||
}, | ||
}) | ||
|
||
cache := &cacheWithDummyProposals{ | ||
Database: state.NewDatabaseWithNodeDB(db, tdb), | ||
} | ||
sdb, err := state.New(types.EmptyRootHash, cache, nil) | ||
require.NoError(t, err, "state.New([empty root], ...)") | ||
|
||
sdb.SetState(common.Address{}, common.Hash{}, common.Hash{42}) | ||
root, err := sdb.Commit(1, false) | ||
require.NoErrorf(t, err, "%T.Commit()", sdb) | ||
|
||
if got, want := backend.got.root, root; got != want { | ||
t.Errorf("got %v; want %v", got, want) | ||
} | ||
|
||
t.Run("GC_finalizers_invoked", func(t *testing.T) { | ||
var finalized []chan struct{} | ||
for _, h := range backend.got.handles { | ||
finalized = append(finalized, h.finalized) | ||
} | ||
|
||
// Everything that might still hold a reference to the `proposal`, | ||
// stopping it from being garbage collected. | ||
sdb = nil | ||
ARR4N marked this conversation as resolved.
Show resolved
Hide resolved
|
||
cache = nil | ||
tdb = nil | ||
backend = nil | ||
|
||
// Note that [runtime.GC] doesn't block on finalizers; see | ||
// https://go.dev/doc/gc-guide#Testing_object_death | ||
runtime.GC() | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
defer cancel() | ||
g, ctx := errgroup.WithContext(ctx) | ||
|
||
for i, ch := range finalized { | ||
g.Go(func() error { | ||
select { | ||
case <-ch: | ||
return nil | ||
case <-ctx.Done(): | ||
return fmt.Errorf("%T[%d] finalizer didn't run", &handle{}, i) | ||
} | ||
}) | ||
} | ||
|
||
require.NoError(t, g.Wait()) | ||
}) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this the correct license for our firewood code?