2022-06-14 17:21:34 +00:00
|
|
|
package key
|
2020-09-04 20:17:28 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
|
|
|
|
"github.com/filecoin-project/go-address"
|
2020-10-08 22:51:04 +00:00
|
|
|
"github.com/filecoin-project/go-state-types/crypto"
|
2020-09-04 20:17:28 +00:00
|
|
|
|
|
|
|
"github.com/filecoin-project/lotus/chain/types"
|
|
|
|
"github.com/filecoin-project/lotus/lib/sigs"
|
|
|
|
)
|
|
|
|
|
2020-10-11 18:12:01 +00:00
|
|
|
func GenerateKey(typ types.KeyType) (*Key, error) {
|
|
|
|
ctyp := ActSigType(typ)
|
|
|
|
if ctyp == crypto.SigTypeUnknown {
|
2020-10-11 22:48:23 +00:00
|
|
|
return nil, xerrors.Errorf("unknown sig type: %s", typ)
|
2020-10-11 18:12:01 +00:00
|
|
|
}
|
|
|
|
pk, err := sigs.Generate(ctyp)
|
2020-09-04 20:17:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ki := types.KeyInfo{
|
2020-10-11 18:12:01 +00:00
|
|
|
Type: typ,
|
2020-09-04 20:17:28 +00:00
|
|
|
PrivateKey: pk,
|
|
|
|
}
|
|
|
|
return NewKey(ki)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Key struct {
|
|
|
|
types.KeyInfo
|
|
|
|
|
|
|
|
PublicKey []byte
|
|
|
|
Address address.Address
|
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2022-09-29 20:46:59 +00:00
|
|
|
case types.KTSecp256k1, types.KTDelegated:
|
2020-09-04 20:17:28 +00:00
|
|
|
k.Address, err = address.NewSecp256k1Address(k.PublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, xerrors.Errorf("converting Secp256k1 to address: %w", err)
|
|
|
|
}
|
2020-10-11 18:12:01 +00:00
|
|
|
case types.KTBLS:
|
2020-09-04 20:17:28 +00:00
|
|
|
k.Address, err = address.NewBLSAddress(k.PublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, xerrors.Errorf("converting BLS to address: %w", err)
|
|
|
|
}
|
|
|
|
default:
|
2020-10-11 22:48:23 +00:00
|
|
|
return nil, xerrors.Errorf("unsupported key type: %s", k.Type)
|
2020-09-04 20:17:28 +00:00
|
|
|
}
|
|
|
|
return k, nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2020-10-11 18:12:01 +00:00
|
|
|
func ActSigType(typ types.KeyType) crypto.SigType {
|
2020-09-04 20:17:28 +00:00
|
|
|
switch typ {
|
2020-10-11 18:12:01 +00:00
|
|
|
case types.KTBLS:
|
2020-09-04 20:17:28 +00:00
|
|
|
return crypto.SigTypeBLS
|
2020-10-11 18:12:01 +00:00
|
|
|
case types.KTSecp256k1:
|
2020-09-04 20:17:28 +00:00
|
|
|
return crypto.SigTypeSecp256k1
|
2022-09-29 20:46:59 +00:00
|
|
|
case types.KTDelegated:
|
|
|
|
return crypto.SigTypeDelegated
|
2020-09-04 20:17:28 +00:00
|
|
|
default:
|
2020-10-11 18:12:01 +00:00
|
|
|
return crypto.SigTypeUnknown
|
2020-09-04 20:17:28 +00:00
|
|
|
}
|
|
|
|
}
|