github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/accounts/abi/bind/auth.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  package bind
    13  
    14  import (
    15  	"crypto/ecdsa"
    16  	"errors"
    17  	"io"
    18  	"io/ioutil"
    19  
    20  	"github.com/Sberex/go-sberex/accounts/keystore"
    21  	"github.com/Sberex/go-sberex/common"
    22  	"github.com/Sberex/go-sberex/core/types"
    23  	"github.com/Sberex/go-sberex/crypto"
    24  )
    25  
    26  // NewTransactor is a utility method to easily create a transaction signer from
    27  // an encrypted json key stream and the associated passphrase.
    28  func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error) {
    29  	json, err := ioutil.ReadAll(keyin)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	key, err := keystore.DecryptKey(json, passphrase)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	return NewKeyedTransactor(key.PrivateKey), nil
    38  }
    39  
    40  // NewKeyedTransactor is a utility method to easily create a transaction signer
    41  // from a single private key.
    42  func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
    43  	keyAddr := crypto.PubkeyToAddress(key.PublicKey)
    44  	return &TransactOpts{
    45  		From: keyAddr,
    46  		Signer: func(signer types.Signer, address common.Address, tx *types.Transaction) (*types.Transaction, error) {
    47  			if address != keyAddr {
    48  				return nil, errors.New("not authorized to sign this account")
    49  			}
    50  			signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key)
    51  			if err != nil {
    52  				return nil, err
    53  			}
    54  			return tx.WithSignature(signer, signature)
    55  		},
    56  	}
    57  }