github.com/storacha/go-ucanto@v0.7.2/principal/signer/signer.go (about)

     1  package signer
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/storacha/go-ucanto/did"
     8  	"github.com/storacha/go-ucanto/principal"
     9  	"github.com/storacha/go-ucanto/principal/verifier"
    10  	"github.com/storacha/go-ucanto/ucan/crypto/signature"
    11  )
    12  
    13  type Unwrapper interface {
    14  	// Unwrap returns the unwrapped did:key of this signer.
    15  	Unwrap() principal.Signer
    16  }
    17  
    18  type WrappedSigner interface {
    19  	principal.Signer
    20  	Unwrapper
    21  }
    22  
    23  type wrapsgn struct {
    24  	key      principal.Signer
    25  	verifier principal.Verifier
    26  }
    27  
    28  func (w wrapsgn) Code() uint64 {
    29  	return w.key.Code()
    30  }
    31  
    32  func (w wrapsgn) DID() did.DID {
    33  	return w.verifier.DID()
    34  }
    35  
    36  func (w wrapsgn) Encode() []byte {
    37  	return w.key.Encode()
    38  }
    39  
    40  func (w wrapsgn) Raw() []byte {
    41  	return w.key.Raw()
    42  }
    43  
    44  func (w wrapsgn) Sign(msg []byte) signature.SignatureView {
    45  	return w.key.Sign(msg)
    46  }
    47  
    48  func (w wrapsgn) SignatureAlgorithm() string {
    49  	return w.key.SignatureAlgorithm()
    50  }
    51  
    52  func (w wrapsgn) SignatureCode() uint64 {
    53  	return w.key.SignatureCode()
    54  }
    55  
    56  func (w wrapsgn) Unwrap() principal.Signer {
    57  	return w.key
    58  }
    59  
    60  func (w wrapsgn) Verifier() principal.Verifier {
    61  	return w.verifier
    62  }
    63  
    64  // Wrap the key of this signer into a signer with a different DID. This is
    65  // primarily used to wrap a did:key signer with a signer that has a DID of
    66  // a different method.
    67  func Wrap(key principal.Signer, id did.DID) (WrappedSigner, error) {
    68  	if !strings.HasPrefix(key.DID().String(), "did:key:") {
    69  		return nil, fmt.Errorf("verifier is not a did:key")
    70  	}
    71  	vrf, err := verifier.Wrap(key.Verifier(), id)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  	return wrapsgn{key, vrf}, nil
    76  }