github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/consensus/pbft/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 pbft 18 19 import ( 20 "github.com/bigzoro/my_simplechain/common" 21 "github.com/bigzoro/my_simplechain/crypto" 22 "github.com/bigzoro/my_simplechain/log" 23 "github.com/bigzoro/my_simplechain/rlp" 24 25 "golang.org/x/crypto/sha3" 26 ) 27 28 func RLPHash(v interface{}) (h common.Hash) { 29 hw := sha3.NewLegacyKeccak256() 30 rlp.Encode(hw, v) 31 hw.Sum(h[:0]) 32 return h 33 } 34 35 // GetSignatureAddress gets the signer address from the signature 36 func GetSignatureAddress(data []byte, sig []byte) (common.Address, error) { 37 // 1. Keccak data 38 hashData := crypto.Keccak256(data) 39 // 2. Recover public key 40 pubkey, err := crypto.SigToPub(hashData, sig) 41 if err != nil { 42 return common.Address{}, err 43 } 44 return crypto.PubkeyToAddress(*pubkey), nil 45 } 46 47 func CheckValidatorSignature(valSet ValidatorSet, data []byte, sig []byte) (common.Address, error) { 48 // 1. Get signature address 49 signer, err := GetSignatureAddress(data, sig) 50 if err != nil { 51 log.Error("Failed to get signer address", "err", err) 52 return common.Address{}, err 53 } 54 55 // 2. Check validator 56 if _, val := valSet.GetByAddress(signer); val != nil { 57 return val.Address(), nil 58 } 59 60 return common.Address{}, ErrUnauthorizedAddress 61 }