github.com/ConsenSys/Quorum@v20.10.0+incompatible/consensus/istanbul/utils.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package istanbul
    18  
    19  import (
    20  	"github.com/ethereum/go-ethereum/common"
    21  	"github.com/ethereum/go-ethereum/crypto"
    22  	"github.com/ethereum/go-ethereum/log"
    23  	"github.com/ethereum/go-ethereum/rlp"
    24  	"golang.org/x/crypto/sha3"
    25  )
    26  
    27  func RLPHash(v interface{}) (h common.Hash) {
    28  	hw := sha3.NewLegacyKeccak256()
    29  	rlp.Encode(hw, v)
    30  	hw.Sum(h[:0])
    31  	return h
    32  }
    33  
    34  // GetSignatureAddress gets the signer address from the signature
    35  func GetSignatureAddress(data []byte, sig []byte) (common.Address, error) {
    36  	// 1. Keccak data
    37  	hashData := crypto.Keccak256(data)
    38  	// 2. Recover public key
    39  	pubkey, err := crypto.SigToPub(hashData, sig)
    40  	if err != nil {
    41  		return common.Address{}, err
    42  	}
    43  	return crypto.PubkeyToAddress(*pubkey), nil
    44  }
    45  
    46  func CheckValidatorSignature(valSet ValidatorSet, data []byte, sig []byte) (common.Address, error) {
    47  	// 1. Get signature address
    48  	signer, err := GetSignatureAddress(data, sig)
    49  	if err != nil {
    50  		log.Error("Failed to get signer address", "err", err)
    51  		return common.Address{}, err
    52  	}
    53  
    54  	// 2. Check validator
    55  	if _, val := valSet.GetByAddress(signer); val != nil {
    56  		return val.Address(), nil
    57  	}
    58  
    59  	return common.Address{}, ErrUnauthorizedAddress
    60  }