dione/wallet/key.go

76 lines
1.6 KiB
Go

package wallet
import (
"fmt"
"github.com/Secured-Finance/dione/types"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/lotus/lib/sigs"
)
type Key struct {
types.KeyInfo
PublicKey []byte
Address address.Address
}
func GenerateKey(typ types.KeyType) (*Key, error) {
ctyp := ActSigType(typ)
if ctyp == crypto.SigTypeUnknown {
return nil, fmt.Errorf("unknown sig type: %s", typ)
}
pk, err := sigs.Generate(ctyp)
if err != nil {
return nil, err
}
ki := types.KeyInfo{
Type: typ,
PrivateKey: pk,
}
return NewKey(ki)
}
// NewKey generates a new Key based on private key and signature type
// it works with both types of signatures Secp256k1 and BLS
func NewKey(keyinfo types.KeyInfo) (*Key, error) {
k := &Key{
KeyInfo: keyinfo,
}
var err error
k.PublicKey, err = sigs.ToPublic(ActSigType(k.Type), k.PrivateKey)
if err != nil {
return nil, err
}
switch k.Type {
case types.KTSecp256k1:
k.Address, err = address.NewSecp256k1Address(k.PublicKey)
if err != nil {
return nil, fmt.Errorf("converting Secp256k1 to address: %w", err)
}
case types.KTBLS:
k.Address, err = address.NewBLSAddress(k.PublicKey)
if err != nil {
return nil, fmt.Errorf("converting BLS to address: %w", err)
}
default:
return nil, fmt.Errorf("unsupported key type: %s", k.Type)
}
return k, nil
}
func ActSigType(typ types.KeyType) crypto.SigType {
switch typ {
case types.KTBLS:
return crypto.SigTypeBLS
case types.KTSecp256k1:
return crypto.SigTypeSecp256k1
default:
return crypto.SigTypeUnknown
}
}