github.com/inklabsfoundation/inkchain@v0.17.1-0.20181025012015-c3cef8062f19/common/localmsp/signer.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8                   http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package localmsp
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/inklabsfoundation/inkchain/common/crypto"
    23  	mspmgmt "github.com/inklabsfoundation/inkchain/msp/mgmt"
    24  	cb "github.com/inklabsfoundation/inkchain/protos/common"
    25  )
    26  
    27  type mspSigner struct {
    28  }
    29  
    30  // NewSigner returns a new instance of the msp-based LocalSigner.
    31  // It assumes that the local msp has been already initialized.
    32  // Look at mspmgmt.LoadLocalMsp for further information.
    33  func NewSigner() crypto.LocalSigner {
    34  	return &mspSigner{}
    35  }
    36  
    37  // NewSignatureHeader creates a SignatureHeader with the correct signing identity and a valid nonce
    38  func (s *mspSigner) NewSignatureHeader() (*cb.SignatureHeader, error) {
    39  	signer, err := mspmgmt.GetLocalMSP().GetDefaultSigningIdentity()
    40  	if err != nil {
    41  		return nil, fmt.Errorf("Failed getting MSP-based signer [%s]", err)
    42  	}
    43  
    44  	creatorIdentityRaw, err := signer.Serialize()
    45  	if err != nil {
    46  		return nil, fmt.Errorf("Failed serializing creator public identity [%s]", err)
    47  	}
    48  
    49  	nonce, err := crypto.GetRandomNonce()
    50  	if err != nil {
    51  		return nil, fmt.Errorf("Failed creating nonce [%s]", err)
    52  	}
    53  
    54  	sh := &cb.SignatureHeader{}
    55  	sh.Creator = creatorIdentityRaw
    56  	sh.Nonce = nonce
    57  
    58  	return sh, nil
    59  }
    60  
    61  // Sign a message which should embed a signature header created by NewSignatureHeader
    62  func (s *mspSigner) Sign(message []byte) ([]byte, error) {
    63  	signer, err := mspmgmt.GetLocalMSP().GetDefaultSigningIdentity()
    64  	if err != nil {
    65  		return nil, fmt.Errorf("Failed getting MSP-based signer [%s]", err)
    66  	}
    67  
    68  	signature, err := signer.Sign(message)
    69  	if err != nil {
    70  		return nil, fmt.Errorf("Failed generating signature [%s]", err)
    71  	}
    72  
    73  	return signature, nil
    74  }