github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/identity/extractor.go (about) 1 /* 2 * Copyright (C) 2017 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU 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 * This program 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 General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package identity 19 20 import ( 21 "github.com/ethereum/go-ethereum/crypto" 22 "github.com/pkg/errors" 23 ) 24 25 // Extractor is able to message signer's identity 26 type Extractor interface { 27 Extract(message []byte, signature Signature) (Identity, error) 28 } 29 30 // NewExtractor constructs Extractor instance 31 func NewExtractor() *extractor { 32 return &extractor{} 33 } 34 35 type extractor struct{} 36 37 // Extractor extracts identity which was used to sign given message 38 func (extractor *extractor) Extract(message []byte, signature Signature) (Identity, error) { 39 signatureBytes := signature.Bytes() 40 if len(signatureBytes) == 0 { 41 return Identity{}, errors.New("empty signature") 42 } 43 44 recoveredKey, err := crypto.Ecrecover(messageHash(message), signatureBytes) 45 if err != nil { 46 return Identity{}, err 47 } 48 49 key, err := crypto.UnmarshalPubkey(recoveredKey) 50 if err != nil { 51 return Identity{}, err 52 } 53 54 recoveredAddress := crypto.PubkeyToAddress(*key).Hex() 55 56 return FromAddress(recoveredAddress), nil 57 }