github.com/leovct/zkevm-bridge-service@v0.4.4/bridgectrl/hash.go (about)

     1  package bridgectrl
     2  
     3  import (
     4  	"encoding/binary"
     5  
     6  	"github.com/0xPolygonHermez/zkevm-bridge-service/etherman"
     7  	"github.com/iden3/go-iden3-crypto/keccak256"
     8  	"golang.org/x/crypto/sha3"
     9  )
    10  
    11  // Hash calculates  the keccak hash of elements.
    12  func Hash(data ...[KeyLen]byte) [KeyLen]byte {
    13  	var res [KeyLen]byte
    14  	hash := sha3.NewLegacyKeccak256()
    15  	for _, d := range data {
    16  		hash.Write(d[:]) //nolint:errcheck,gosec
    17  	}
    18  	copy(res[:], hash.Sum(nil))
    19  	return res
    20  }
    21  
    22  // HashZero is an empty hash
    23  var HashZero = [KeyLen]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    24  
    25  func generateZeroHashes(height uint8) [][KeyLen]byte {
    26  	var zeroHashes = [][KeyLen]byte{
    27  		HashZero,
    28  	}
    29  	// This generates a leaf = HashZero in position 0. In the rest of the positions that are equivalent to the ascending levels,
    30  	// we set the hashes of the nodes. So all nodes from level i=5 will have the same value and same children nodes.
    31  	for i := 1; i <= int(height); i++ {
    32  		zeroHashes = append(zeroHashes, Hash(zeroHashes[i-1], zeroHashes[i-1]))
    33  	}
    34  	return zeroHashes
    35  }
    36  
    37  func hashDeposit(deposit *etherman.Deposit) [KeyLen]byte {
    38  	var res [KeyLen]byte
    39  	origNet := make([]byte, 4) //nolint:gomnd
    40  	binary.BigEndian.PutUint32(origNet, uint32(deposit.OriginalNetwork))
    41  	destNet := make([]byte, 4) //nolint:gomnd
    42  	binary.BigEndian.PutUint32(destNet, uint32(deposit.DestinationNetwork))
    43  	var buf [KeyLen]byte
    44  	metaHash := keccak256.Hash(deposit.Metadata)
    45  	copy(res[:], keccak256.Hash([]byte{deposit.LeafType}, origNet, deposit.OriginalAddress[:], destNet, deposit.DestinationAddress[:], deposit.Amount.FillBytes(buf[:]), metaHash))
    46  	return res
    47  }