Skip to content

Commit

Permalink
Revert "pass config by parameter"
Browse files Browse the repository at this point in the history
This reverts commit 4aec589.
  • Loading branch information
iFrostizz committed Apr 26, 2024
1 parent a72ca67 commit dcabc00
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 0 deletions.
52 changes: 52 additions & 0 deletions merkle/merkle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package merkle

import (
"context"

"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/database/memdb"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/trace"
"github.com/ava-labs/avalanchego/utils/units"
"github.com/ava-labs/avalanchego/x/merkledb"
"github.com/ava-labs/hypersdk/utils"
)

// Generate merkle root for a set of items
func GenerateMerkleRoot(ctx context.Context, tracer trace.Tracer, merkleItems [][]byte, consumeBytes bool) (ids.ID, merkledb.MerkleDB, error) {
batchOps := make([]database.BatchOp, 0, len(merkleItems))

for _, item := range merkleItems {
key := utils.ToID(item)
batchOps = append(batchOps, database.BatchOp{
Key: key[:],
Value: item,
})
}

db, err := merkledb.New(ctx, memdb.New(), merkledb.Config{
BranchFactor: merkledb.BranchFactor16,
HistoryLength: 100,
IntermediateNodeCacheSize: units.MiB,
ValueNodeCacheSize: units.MiB,
Tracer: tracer,
})
if err != nil {
return ids.Empty, nil, err
}

view, err := db.NewView(ctx, merkledb.ViewChanges{BatchOps: batchOps, ConsumeBytes: consumeBytes})
if err != nil {
return ids.Empty, nil, err
}
if err := view.CommitToDB(ctx); err != nil {
return ids.Empty, nil, err
}

root, err := db.GetMerkleRoot(ctx)
if err != nil {
return ids.Empty, nil, err
}

return root, db, nil
}
52 changes: 52 additions & 0 deletions merkle/merkle_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package merkle

import (
"testing"

"crypto/rand"
"context"
"strconv"

"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/trace"
"github.com/ava-labs/avalanchego/x/merkledb"
)

var resRoot ids.ID
var resDb merkledb.MerkleDB
var resErr error

func BenchmarkMerkleTxRoot(b *testing.B) {
for _, size := range []int{10, 100, 1000, 10000} {
ctx := context.TODO()
tracer := trace.Noop
merkleItems := make([][]byte, 0, size)
for i := 0; i < size; i++ {
item := make([]byte, 32)
_, err := rand.Read(item)
if err != nil {
b.Fatal(err)
}
merkleItems = append(merkleItems, item)
}

var root ids.ID
var db merkledb.MerkleDB
var err error

b.Run(strconv.Itoa(size), func(b *testing.B) {
for n := 0; n < b.N; n++ {
for i := 0; i < size; i++ {
root, db, err = GenerateMerkleRoot(ctx, tracer, merkleItems, false)
}
}
})

// avoid compiler optimizations to cancel out the bench
resRoot = root
resDb = db
resErr = err
}

b.ReportAllocs()
}

0 comments on commit dcabc00

Please sign in to comment.