github.com/klaytn/klaytn@v1.10.2/consensus/istanbul/utils.go (about)

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