2020-10-28 17:35:56 +00:00
|
|
|
package wallet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2020-11-12 14:18:30 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/crypto"
|
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
|
|
|
|
|
|
|
"github.com/Secured-Finance/dione/sigs"
|
2020-10-28 17:35:56 +00:00
|
|
|
"github.com/Secured-Finance/dione/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Key struct {
|
|
|
|
types.KeyInfo
|
|
|
|
|
|
|
|
PublicKey []byte
|
2020-11-12 14:18:30 +00:00
|
|
|
Address peer.ID
|
2020-10-28 17:35:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func GenerateKey(typ types.KeyType) (*Key, error) {
|
|
|
|
ctyp := ActSigType(typ)
|
2020-11-12 14:18:30 +00:00
|
|
|
if ctyp == types.SigTypeUnknown {
|
2020-10-28 17:35:56 +00:00
|
|
|
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 {
|
2020-11-12 14:18:30 +00:00
|
|
|
case types.KTEd25519:
|
|
|
|
pubKey, err := crypto.UnmarshalEd25519PublicKey(k.PublicKey)
|
2020-10-28 17:35:56 +00:00
|
|
|
if err != nil {
|
2020-11-12 14:18:30 +00:00
|
|
|
return nil, fmt.Errorf("failed to unmarshal ed25519 public key: %w", err)
|
2020-10-28 17:35:56 +00:00
|
|
|
}
|
2020-11-12 14:18:30 +00:00
|
|
|
k.Address, err = peer.IDFromPublicKey(pubKey)
|
2020-10-28 17:35:56 +00:00
|
|
|
if err != nil {
|
2020-11-12 14:18:30 +00:00
|
|
|
return nil, fmt.Errorf("converting Secp256k1 to address: %w", err)
|
2020-10-28 17:35:56 +00:00
|
|
|
}
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unsupported key type: %s", k.Type)
|
|
|
|
}
|
|
|
|
return k, nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2020-11-12 14:18:30 +00:00
|
|
|
func ActSigType(typ types.KeyType) types.SigType {
|
2020-10-28 17:35:56 +00:00
|
|
|
switch typ {
|
2020-11-12 14:18:30 +00:00
|
|
|
case types.KTEd25519:
|
|
|
|
return types.SigTypeEd25519
|
2020-10-28 17:35:56 +00:00
|
|
|
default:
|
2020-11-12 14:18:30 +00:00
|
|
|
return types.SigTypeUnknown
|
2020-10-28 17:35:56 +00:00
|
|
|
}
|
|
|
|
}
|