Skip to content

Commit

Permalink
Optimize receiptCommitment function for parallel processing
Browse files Browse the repository at this point in the history
  • Loading branch information
AnkushinDaniil committed Sep 20, 2024
1 parent 2fcfa31 commit b31d2d9
Showing 1 changed file with 17 additions and 42 deletions.
59 changes: 17 additions & 42 deletions core/receipt.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,59 +64,34 @@ func messagesSentHash(messages []*L2ToL1Message) *felt.Felt {
}

func ReceiptCommitment(receipts []*TransactionReceipt) (*felt.Felt, error) {
type result struct {
key *felt.Felt
value *felt.Felt
}
var commitment *felt.Felt
return commitment, trie.RunOnTempTriePoseidon(commitmentTrieHeight, func(trie *trie.Trie) error {
numWorkers := min(runtime.GOMAXPROCS(0), len(receipts))
resultChan := make(chan result, len(receipts))
var trieMutex sync.Mutex

errChan := make(chan error, numWorkers)

var wg sync.WaitGroup
results := make([]*felt.Felt, len(receipts))
wg := sync.WaitGroup{}
wg.Add(numWorkers)

receiptsPerWorker := max(1, (len(receipts)+numWorkers-1)/numWorkers)
jobs := make(chan int, len(receipts))
for i := range receipts {
jobs <- i
}
close(jobs)

for workerID := 0; workerID < numWorkers; workerID++ {
go func(id int) {
for range numWorkers {
go func() {
defer wg.Done()
startIdx := id * receiptsPerWorker
endIdx := min(startIdx+receiptsPerWorker, len(receipts))

for i, receipt := range receipts[startIdx:endIdx] {
receiptTrieKey := new(felt.Felt).SetUint64(uint64(startIdx + i))
receiptHash := receipt.hash()
resultChan <- result{receiptTrieKey, receiptHash}
for i := range jobs {
results[i] = receipts[i].hash()
}

errChan <- nil
}(workerID)
}()
}

go func() {
wg.Wait()
close(resultChan)
}()

go func() {
for result := range resultChan {
trieMutex.Lock()
_, err := trie.Put(result.key, result.value)
trieMutex.Unlock()
if err != nil {
errChan <- err
return
}
}
errChan <- nil
}()
wg.Wait()

for i := 0; i < numWorkers+1; i++ {
if err := <-errChan; err != nil {
key := new(felt.Felt)
for i, res := range results {
key.SetUint64(uint64(i))
if _, err := trie.Put(key, res); err != nil {
return err
}
}
Expand Down

0 comments on commit b31d2d9

Please sign in to comment.