Skip to content

Commit

Permalink
chore: Optimize receiptCommitment function for parallel processing
Browse files Browse the repository at this point in the history
  • Loading branch information
AnkushinDaniil committed Sep 19, 2024
1 parent 37ed095 commit f31cc09
Showing 1 changed file with 30 additions and 8 deletions.
38 changes: 30 additions & 8 deletions core/receipt.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package core

import (
"runtime"
"sync"

"github.com/NethermindEth/juno/core/crypto"
"github.com/NethermindEth/juno/core/felt"
"github.com/NethermindEth/juno/core/trie"
"github.com/sourcegraph/conc/pool"
)

type GasConsumed struct {
Expand Down Expand Up @@ -62,22 +66,40 @@ func messagesSentHash(messages []*L2ToL1Message) *felt.Felt {

func receiptCommitment(receipts []*TransactionReceipt) (*felt.Felt, error) {
var commitment *felt.Felt

return commitment, trie.RunOnTempTriePoseidon(commitmentTrieHeight, func(trie *trie.Trie) error {
for i, receipt := range receipts {
receiptTrieKey := new(felt.Felt).SetUint64(uint64(i))
_, err := trie.Put(receiptTrieKey, receipt.hash())
if err != nil {
return err
}
numWorkers := runtime.GOMAXPROCS(0)
receiptsPerWorker := max(1, len(receipts)/numWorkers)
workerPool := pool.New().WithErrors().WithMaxGoroutines(numWorkers)
var trieMutex sync.Mutex

for receiptIdx := 0; receiptIdx < len(receipts); receiptIdx += receiptsPerWorker {
startIdx := receiptIdx
endIdx := min(startIdx+receiptsPerWorker, len(receipts))
workerPool.Go(func() error {
for i, receipt := range receipts[startIdx:endIdx] {
receiptTrieKey := new(felt.Felt).SetUint64(uint64(receiptIdx + i))
receiptHash := receipt.hash()

trieMutex.Lock()
_, err := trie.Put(receiptTrieKey, receiptHash)
trieMutex.Unlock()
if err != nil {
return err

Check warning on line 87 in core/receipt.go

View check run for this annotation

Codecov / codecov/patch

core/receipt.go#L87

Added line #L87 was not covered by tests
}
}
return nil
})
}

if err := workerPool.Wait(); err != nil {
return err

Check warning on line 95 in core/receipt.go

View check run for this annotation

Codecov / codecov/patch

core/receipt.go#L95

Added line #L95 was not covered by tests
}

root, err := trie.Root()
if err != nil {
return err
}
commitment = root

return nil
})
}

0 comments on commit f31cc09

Please sign in to comment.