Skip to content

Commit

Permalink
Add thread-safe entityHasher
Browse files Browse the repository at this point in the history
  • Loading branch information
psiemens committed Jun 15, 2020
1 parent 06ca1da commit 3cfa5a4
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 6 deletions.
2 changes: 1 addition & 1 deletion collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Collection struct {

// ID returns the canonical SHA3-256 hash of this collection.
func (c Collection) ID() Identifier {
return HashToID(DefaultHasher.ComputeHash(c.Encode()))
return HashToID(defaultEntityHasher.ComputeHash(c.Encode()))
}

// Encode returns the canonical RLP byte representation of this collection.
Expand Down
2 changes: 1 addition & 1 deletion event.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (e Event) String() string {

// ID returns the canonical SHA3-256 hash of this event.
func (e Event) ID() string {
return DefaultHasher.ComputeHash(e.Encode()).Hex()
return defaultEntityHasher.ComputeHash(e.Encode()).Hex()
}

// Encode returns the canonical RLP byte representation of this event.
Expand Down
22 changes: 19 additions & 3 deletions flow.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package flow

import (
"encoding/hex"
"sync"

"github.com/ethereum/go-ethereum/rlp"

Expand Down Expand Up @@ -60,6 +61,7 @@ func HexToID(h string) Identifier {
return BytesToID(b)
}

// HashToID constructs an identifier from a 32-byte hash.
func HashToID(hash []byte) Identifier {
return BytesToID(hash)
}
Expand All @@ -82,11 +84,25 @@ func (id ChainID) String() string {
return string(id)
}

// DefaultHasher is the default hasher used by Flow.
var DefaultHasher crypto.Hasher
// entityHasher is a thread-safe hasher used to hash Flow entities.
type entityHasher struct {
mut sync.Mutex
hasher crypto.Hasher
}

func (h *entityHasher) ComputeHash(b []byte) crypto.Hash {
h.mut.Lock()
defer h.mut.Unlock()
return h.hasher.ComputeHash(b)
}

// defaultEntityHasher is the default hasher used to compute Flow identifiers.
var defaultEntityHasher *entityHasher

func init() {
DefaultHasher = crypto.NewSHA3_256()
defaultEntityHasher = &entityHasher{
hasher: crypto.NewSHA3_256(),
}
}

func rlpEncode(v interface{}) ([]byte, error) {
Expand Down
2 changes: 1 addition & 1 deletion transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func NewTransaction() *Transaction {

// ID returns the canonical SHA3-256 hash of this transaction.
func (t *Transaction) ID() Identifier {
return HashToID(DefaultHasher.ComputeHash(t.Encode()))
return HashToID(defaultEntityHasher.ComputeHash(t.Encode()))
}

// SetScript sets the Cadence script for this transaction.
Expand Down

0 comments on commit 3cfa5a4

Please sign in to comment.