github.com/ethersphere/bee/v2@v2.2.0/pkg/crypto/mock/signer.go (about)

     1  // Copyright 2020 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package mock
     6  
     7  import (
     8  	"crypto/ecdsa"
     9  	"math/big"
    10  
    11  	"github.com/ethereum/go-ethereum/common"
    12  	"github.com/ethereum/go-ethereum/core/types"
    13  	"github.com/ethersphere/bee/v2/pkg/crypto"
    14  	"github.com/ethersphere/bee/v2/pkg/crypto/eip712"
    15  )
    16  
    17  type signerMock struct {
    18  	signTx          func(transaction *types.Transaction, chainID *big.Int) (*types.Transaction, error)
    19  	signTypedData   func(*eip712.TypedData) ([]byte, error)
    20  	ethereumAddress func() (common.Address, error)
    21  	signFunc        func([]byte) ([]byte, error)
    22  }
    23  
    24  func (m *signerMock) EthereumAddress() (common.Address, error) {
    25  	if m.ethereumAddress != nil {
    26  		return m.ethereumAddress()
    27  	}
    28  	return common.Address{}, nil
    29  }
    30  
    31  func (m *signerMock) Sign(data []byte) ([]byte, error) {
    32  	return m.signFunc(data)
    33  }
    34  
    35  func (m *signerMock) SignTx(transaction *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
    36  	return m.signTx(transaction, chainID)
    37  }
    38  
    39  func (*signerMock) PublicKey() (*ecdsa.PublicKey, error) {
    40  	return nil, nil
    41  }
    42  
    43  func (m *signerMock) SignTypedData(d *eip712.TypedData) ([]byte, error) {
    44  	return m.signTypedData(d)
    45  }
    46  
    47  func New(opts ...Option) crypto.Signer {
    48  	mock := new(signerMock)
    49  	for _, o := range opts {
    50  		o.apply(mock)
    51  	}
    52  	return mock
    53  }
    54  
    55  // Option is the option passed to the mock Chequebook service
    56  type Option interface {
    57  	apply(*signerMock)
    58  }
    59  
    60  type optionFunc func(*signerMock)
    61  
    62  func (f optionFunc) apply(r *signerMock) { f(r) }
    63  
    64  func WithSignFunc(f func(data []byte) ([]byte, error)) Option {
    65  	return optionFunc(func(s *signerMock) {
    66  		s.signFunc = f
    67  	})
    68  }
    69  
    70  func WithSignTxFunc(f func(transaction *types.Transaction, chainID *big.Int) (*types.Transaction, error)) Option {
    71  	return optionFunc(func(s *signerMock) {
    72  		s.signTx = f
    73  	})
    74  }
    75  
    76  func WithSignTypedDataFunc(f func(*eip712.TypedData) ([]byte, error)) Option {
    77  	return optionFunc(func(s *signerMock) {
    78  		s.signTypedData = f
    79  	})
    80  }
    81  
    82  func WithEthereumAddressFunc(f func() (common.Address, error)) Option {
    83  	return optionFunc(func(s *signerMock) {
    84  		s.ethereumAddress = f
    85  	})
    86  }