mirror of
https://github.com/sonr-io/sonr.git
synced 2026-08-02 17:31:39 +00:00
feature/1121 implement ucan validation (#1176)
- **refactor: remove unused auth components** - **refactor: improve devbox configuration and deployment process** - **refactor: improve devnet and testnet setup** - **fix: update templ version to v0.2.778** - **refactor: rename pkl/net.matrix to pkl/matrix.net** - **refactor: migrate webapp components to nebula** - **refactor: protobuf types** - **chore: update dependencies for improved security and stability** - **feat: implement landing page and vault gateway servers** - **refactor: Migrate data models to new module structure and update related files** - **feature/1121-implement-ucan-validation** - **refactor: Replace hardcoded constants with model types in attns.go** - **feature/1121-implement-ucan-validation** - **chore: add origin Host struct and update main function to handle multiple hosts** - **build: remove unused static files from dwn module** - **build: remove unused static files from dwn module** - **refactor: Move DWN models to common package** - **refactor: move models to pkg/common** - **refactor: move vault web app assets to embed module** - **refactor: update session middleware import path** - **chore: configure port labels and auto-forwarding behavior** - **feat: enhance devcontainer configuration** - **feat: Add UCAN middleware for Echo with flexible token validation** - **feat: add JWT middleware for UCAN authentication** - **refactor: update package URI and versioning in PklProject files** - **fix: correct sonr.pkl import path** - **refactor: move JWT related code to auth package** - **feat: introduce vault configuration retrieval and management** - **refactor: Move vault components to gateway module and update file paths** - **refactor: remove Dexie and SQLite database implementations** - **feat: enhance frontend with PWA features and WASM integration** - **feat: add Devbox features and streamline Dockerfile** - **chore: update dependencies to include TigerBeetle** - **chore(deps): update go version to 1.23** - **feat: enhance devnet setup with PATH environment variable and updated PWA manifest** - **fix: upgrade tigerbeetle-go dependency and remove indirect dependency** - **feat: add PostgreSQL support to devnet and testnet deployments** - **refactor: rename keyshare cookie to token cookie** - **feat: upgrade Go version to 1.23.3 and update dependencies** - **refactor: update devnet and testnet configurations** - **feat: add IPFS configuration for devnet** - **I'll help you update the ipfs.config.pkl to include all the peers from the shell script. Here's the updated configuration:** - **refactor: move mpc package to crypto directory** - **feat: add BIP32 support for various cryptocurrencies** - **feat: enhance ATN.pkl with additional capabilities** - **refactor: simplify smart account and vault attenuation creation** - **feat: add new capabilities to the Attenuation type** - **refactor: Rename MPC files for clarity and consistency** - **feat: add DIDKey support for cryptographic operations** - **feat: add devnet and testnet deployment configurations** - **fix: correct key derivation in bip32 package** - **refactor: rename crypto/bip32 package to crypto/accaddr** - **fix: remove duplicate indirect dependency** - **refactor: move vault package to root directory** - **refactor: update routes for gateway and vault** - **refactor: remove obsolete web configuration file** - **refactor: remove unused TigerBeetle imports and update host configuration** - **refactor: adjust styles directory path** - **feat: add broadcastTx and simulateTx functions to gateway** - **feat: add PinVault handler**
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
package mpc
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
)
|
||||
|
||||
type exportData struct {
|
||||
Address string `json:"addr"`
|
||||
PubKey []byte `json:"pubKey"`
|
||||
ValData []byte `json:"val"`
|
||||
UserData []byte `json:"user"`
|
||||
}
|
||||
|
||||
func (e *exportData) Marshal() ([]byte, error) {
|
||||
return json.Marshal(e)
|
||||
}
|
||||
|
||||
func (e *exportData) Unmarshal(data []byte) error {
|
||||
return json.Unmarshal(data, e)
|
||||
}
|
||||
|
||||
func ImportKeyset(secret []byte, dat File) (Keyset, error) {
|
||||
data, err := io.ReadAll(dat)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ed exportData
|
||||
err = ed.Unmarshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user, val, err := loadShareFromExportData(&ed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k := keyset{
|
||||
user: user,
|
||||
val: val,
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func (k keyset) Export(client IPFSClient, secret []byte) (ExportedKeyset, error) {
|
||||
valData, err := k.val.Marshal()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userData, err := k.user.Marshal()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addr, err := ComputeSonrAddr(k.val.PublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ed := exportData{
|
||||
Address: addr,
|
||||
PubKey: k.val.PublicKey,
|
||||
ValData: valData,
|
||||
UserData: userData,
|
||||
}
|
||||
return ed.Marshal()
|
||||
}
|
||||
|
||||
func loadShareFromExportData(data *exportData) (*UserKeyshare, *ValKeyshare, error) {
|
||||
var (
|
||||
valMsg Message
|
||||
userMsg Message
|
||||
)
|
||||
err := json.Unmarshal(data.UserData, &userMsg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
err = json.Unmarshal(data.ValData, &valMsg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
user := &UserKeyshare{
|
||||
Message: userMsg,
|
||||
Role: 2,
|
||||
PublicKey: data.PubKey,
|
||||
}
|
||||
val := &ValKeyshare{
|
||||
Message: valMsg,
|
||||
Role: 1,
|
||||
PublicKey: data.PubKey,
|
||||
}
|
||||
return user, val, nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package mpc
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
// MPCSigningMethod implements the SigningMethod interface for MPC-based signing
|
||||
type MPCSigningMethod struct {
|
||||
Name string
|
||||
ks ucanKeyshare
|
||||
}
|
||||
|
||||
// NewJWTSigningMethod creates a new MPC signing method with the given keyshare source
|
||||
func NewJWTSigningMethod(name string, ks ucanKeyshare) *MPCSigningMethod {
|
||||
return &MPCSigningMethod{
|
||||
Name: name,
|
||||
ks: ks,
|
||||
}
|
||||
}
|
||||
|
||||
// Alg returns the signing method's name
|
||||
func (m *MPCSigningMethod) Alg() string {
|
||||
return m.Name
|
||||
}
|
||||
|
||||
// Verify verifies the signature using the MPC public key
|
||||
func (m *MPCSigningMethod) Verify(signingString, signature string, key interface{}) error {
|
||||
// Decode the signature
|
||||
sig, err := base64.RawURLEncoding.DecodeString(signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Hash the signing string
|
||||
hasher := sha256.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
digest := hasher.Sum(nil)
|
||||
|
||||
// Verify using the keyshare's public key
|
||||
valid, err := VerifySignature(m.ks.valShare.PublicKey, digest, sig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to verify signature: %w", err)
|
||||
}
|
||||
if !valid {
|
||||
return fmt.Errorf("invalid signature")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sign signs the data using MPC
|
||||
func (m *MPCSigningMethod) Sign(signingString string, key interface{}) (string, error) {
|
||||
// Hash the signing string
|
||||
hasher := sha256.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
digest := hasher.Sum(nil)
|
||||
|
||||
// Create signing functions
|
||||
signFunc, err := m.ks.userShare.SignFunc(digest)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create sign function: %w", err)
|
||||
}
|
||||
|
||||
valSignFunc, err := m.ks.valShare.SignFunc(digest)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create validator sign function: %w", err)
|
||||
}
|
||||
|
||||
// Run the signing protocol
|
||||
sig, err := RunSignProtocol(valSignFunc, signFunc)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to run sign protocol: %w", err)
|
||||
}
|
||||
|
||||
// Serialize the signature
|
||||
sigBytes, err := SerializeSignature(sig)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to serialize signature: %w", err)
|
||||
}
|
||||
|
||||
// Encode the signature
|
||||
encoded := base64.RawURLEncoding.EncodeToString(sigBytes)
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
// Register the MPC signing method
|
||||
jwt.RegisterSigningMethod("MPC256", func() jwt.SigningMethod {
|
||||
return &MPCSigningMethod{
|
||||
Name: "MPC256",
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package mpc
|
||||
|
||||
import (
|
||||
genericecdsa "crypto/ecdsa"
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
"github.com/cosmos/cosmos-sdk/types/bech32"
|
||||
"github.com/ipfs/boxo/files"
|
||||
"github.com/ipfs/kubo/client/rpc"
|
||||
"github.com/onsonr/sonr/crypto/core/curves"
|
||||
"github.com/onsonr/sonr/crypto/core/protocol"
|
||||
"golang.org/x/crypto/sha3"
|
||||
)
|
||||
|
||||
type (
|
||||
ExportedKeyset = []byte
|
||||
IPFSClient = *rpc.HttpApi
|
||||
File = files.File
|
||||
)
|
||||
|
||||
type Keyset interface {
|
||||
Val() *ValKeyshare
|
||||
User() *UserKeyshare
|
||||
Export(client IPFSClient, secret []byte) (ExportedKeyset, error)
|
||||
}
|
||||
|
||||
type keyset struct {
|
||||
val *ValKeyshare
|
||||
user *UserKeyshare
|
||||
}
|
||||
|
||||
func (k keyset) Val() *ValKeyshare {
|
||||
return k.val
|
||||
}
|
||||
|
||||
func (k keyset) User() *UserKeyshare {
|
||||
return k.user
|
||||
}
|
||||
|
||||
func ComputeIssuerDID(pk []byte) (string, string, error) {
|
||||
addr, err := ComputeSonrAddr(pk)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return fmt.Sprintf("did:sonr:%s", addr), addr, nil
|
||||
}
|
||||
|
||||
func ComputeSonrAddr(pk []byte) (string, error) {
|
||||
sonrAddr, err := bech32.ConvertAndEncode("idx", pk)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return sonrAddr, nil
|
||||
}
|
||||
|
||||
// For DKG bob starts first. For refresh and sign, Alice starts first.
|
||||
func runIteratedProtocol(firstParty protocol.Iterator, secondParty protocol.Iterator) (error, error) {
|
||||
var (
|
||||
message *protocol.Message
|
||||
aErr error
|
||||
bErr error
|
||||
)
|
||||
|
||||
for aErr != protocol.ErrProtocolFinished || bErr != protocol.ErrProtocolFinished {
|
||||
// Crank each protocol forward one iteration
|
||||
message, bErr = firstParty.Next(message)
|
||||
if bErr != nil && bErr != protocol.ErrProtocolFinished {
|
||||
return nil, bErr
|
||||
}
|
||||
|
||||
message, aErr = secondParty.Next(message)
|
||||
if aErr != nil && aErr != protocol.ErrProtocolFinished {
|
||||
return aErr, nil
|
||||
}
|
||||
}
|
||||
return aErr, bErr
|
||||
}
|
||||
|
||||
// ComputeEcPoint builds an elliptic curve point from a compressed byte slice
|
||||
func ComputeEcPoint(pubKey []byte) (*curves.EcPoint, error) {
|
||||
crv := curves.K256()
|
||||
x := new(big.Int).SetBytes(pubKey[1:33])
|
||||
y := new(big.Int).SetBytes(pubKey[33:])
|
||||
ecCurve, err := crv.ToEllipticCurve()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error converting curve: %v", err)
|
||||
}
|
||||
return &curves.EcPoint{X: x, Y: y, Curve: ecCurve}, nil
|
||||
}
|
||||
|
||||
func ComputeEcdsaPublicKey(pubKey []byte) (*genericecdsa.PublicKey, error) {
|
||||
pk, err := ComputeEcPoint(pubKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &genericecdsa.PublicKey{
|
||||
Curve: pk.Curve,
|
||||
X: pk.X,
|
||||
Y: pk.Y,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// VerifySignature verifies the signature of a message
|
||||
func VerifySignature(pk []byte, msg []byte, sig []byte) (bool, error) {
|
||||
pp, err := ComputeEcPoint(pk)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
sigEd, err := DeserializeSignature(sig)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
hash := sha3.New256()
|
||||
_, err = hash.Write(msg)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
digest := hash.Sum(nil)
|
||||
return curves.VerifyEcdsa(pp, digest[:], sigEd), nil
|
||||
}
|
||||
|
||||
func checkIteratedErrors(aErr, bErr error) error {
|
||||
if aErr == protocol.ErrProtocolFinished && bErr == protocol.ErrProtocolFinished {
|
||||
return nil
|
||||
}
|
||||
if aErr != protocol.ErrProtocolFinished {
|
||||
return aErr
|
||||
}
|
||||
if bErr != protocol.ErrProtocolFinished {
|
||||
return bErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package mpc
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"errors"
|
||||
"math/big"
|
||||
|
||||
"github.com/onsonr/sonr/crypto/core/curves"
|
||||
"github.com/onsonr/sonr/crypto/core/protocol"
|
||||
"github.com/onsonr/sonr/crypto/tecdsa/dklsv1"
|
||||
)
|
||||
|
||||
// NewKeyshareSource generates a new MPC keyshare
|
||||
func NewKeyset() (Keyset, error) {
|
||||
curve := curves.K256()
|
||||
valKs := dklsv1.NewAliceDkg(curve, protocol.Version1)
|
||||
userKs := dklsv1.NewBobDkg(curve, protocol.Version1)
|
||||
aErr, bErr := runIteratedProtocol(userKs, valKs)
|
||||
if err := checkIteratedErrors(aErr, bErr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valRes, err := valKs.Result(protocol.Version1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valShare, err := NewValKeyshare(valRes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userRes, err := userKs.Result(protocol.Version1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userShare, err := NewUserKeyshare(userRes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return keyset{val: valShare, user: userShare}, nil
|
||||
}
|
||||
|
||||
// RunSignProtocol runs the MPC signing protocol
|
||||
func RunSignProtocol(signFuncVal SignFunc, signFuncUser SignFunc) (Signature, error) {
|
||||
aErr, bErr := runIteratedProtocol(signFuncVal, signFuncUser)
|
||||
if err := checkIteratedErrors(aErr, bErr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := signFuncUser.Result(protocol.Version1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dklsv1.DecodeSignature(out)
|
||||
}
|
||||
|
||||
// RunRefreshProtocol runs the MPC refresh protocol
|
||||
func RunRefreshProtocol(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc) (Keyset, error) {
|
||||
aErr, bErr := runIteratedProtocol(refreshFuncVal, refreshFuncUser)
|
||||
if err := checkIteratedErrors(aErr, bErr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valRefreshResult, err := refreshFuncVal.Result(protocol.Version1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valShare, err := NewValKeyshare(valRefreshResult)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userRefreshResult, err := refreshFuncUser.Result(protocol.Version1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userShare, err := NewUserKeyshare(userRefreshResult)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return keyset{val: valShare, user: userShare}, nil
|
||||
}
|
||||
|
||||
// SerializeSecp256k1Signature serializes an ECDSA signature into a byte slice
|
||||
func SerializeSignature(sig Signature) ([]byte, error) {
|
||||
rBytes := sig.R.Bytes()
|
||||
sBytes := sig.S.Bytes()
|
||||
|
||||
sigBytes := make([]byte, 66) // V (1 byte) + R (32 bytes) + S (32 bytes)
|
||||
sigBytes[0] = byte(sig.V)
|
||||
copy(sigBytes[33-len(rBytes):33], rBytes)
|
||||
copy(sigBytes[66-len(sBytes):66], sBytes)
|
||||
return sigBytes, nil
|
||||
}
|
||||
|
||||
// DeserializeSecp256k1Signature deserializes an ECDSA signature from a byte slice
|
||||
func DeserializeSignature(sigBytes []byte) (Signature, error) {
|
||||
if len(sigBytes) != 66 {
|
||||
return nil, errors.New("malformed signature: not the correct size")
|
||||
}
|
||||
sig := &curves.EcdsaSignature{
|
||||
V: int(sigBytes[0]),
|
||||
R: new(big.Int).SetBytes(sigBytes[1:33]),
|
||||
S: new(big.Int).SetBytes(sigBytes[33:66]),
|
||||
}
|
||||
return sig, nil
|
||||
}
|
||||
|
||||
// VerifyMPCSignature verifies an MPC signature
|
||||
func VerifyMPCSignature(sig Signature, msg []byte, publicKey *ecdsa.PublicKey) bool {
|
||||
return ecdsa.Verify(publicKey, msg, sig.R, sig.S)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mpc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"fmt"
|
||||
|
||||
cometcrypto "github.com/cometbft/cometbft/crypto"
|
||||
)
|
||||
|
||||
type PublicKeyType string
|
||||
|
||||
const (
|
||||
PublicKeyTypeRaw PublicKeyType = "secp256k1"
|
||||
PublicKeyTypeCosmos PublicKeyType = "cosmos"
|
||||
PublicKeyTypeBitcoin PublicKeyType = "bitcoin"
|
||||
PublicKeyTypeEthereum PublicKeyType = "ethereum"
|
||||
PublicKeyTypeSonr PublicKeyType = "sonr"
|
||||
)
|
||||
|
||||
type ECDSAPublicKey *ecdsa.PublicKey
|
||||
|
||||
type PublicKey interface {
|
||||
Address() cometcrypto.Address
|
||||
Bytes() []byte
|
||||
DID() string
|
||||
VerifySignature(msg []byte, sig []byte) bool
|
||||
Equals(cometcrypto.PubKey) bool
|
||||
Type() string
|
||||
}
|
||||
|
||||
type rootPublicKey struct {
|
||||
data []byte
|
||||
kind string
|
||||
}
|
||||
|
||||
func (k rootPublicKey) Address() cometcrypto.Address {
|
||||
return cometcrypto.AddressHash(k.data)
|
||||
}
|
||||
|
||||
func (k rootPublicKey) Bytes() []byte {
|
||||
return k.data
|
||||
}
|
||||
|
||||
func (k rootPublicKey) DID() string {
|
||||
return fmt.Sprintf("did:sonr:%s", k.Address())
|
||||
}
|
||||
|
||||
func (k rootPublicKey) VerifySignature(msg []byte, sig []byte) bool {
|
||||
ok, err := VerifySignature(k.data, msg, sig)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
func (k rootPublicKey) Equals(other cometcrypto.PubKey) bool {
|
||||
return bytes.Equal(k.data, other.Bytes())
|
||||
}
|
||||
|
||||
func (k rootPublicKey) Type() string {
|
||||
return k.kind
|
||||
}
|
||||
|
||||
func createPublicKey(pk []byte, kind string) PublicKey {
|
||||
return rootPublicKey{
|
||||
data: pk,
|
||||
kind: kind,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package mpc
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/onsonr/sonr/crypto/core/curves"
|
||||
"github.com/onsonr/sonr/crypto/core/protocol"
|
||||
"github.com/onsonr/sonr/crypto/tecdsa/dklsv1"
|
||||
"golang.org/x/crypto/sha3"
|
||||
)
|
||||
|
||||
var ErrInvalidKeyshareRole = errors.New("invalid keyshare role")
|
||||
|
||||
type Role int
|
||||
|
||||
const (
|
||||
RoleUnknown Role = iota
|
||||
RoleUser
|
||||
RoleValidator
|
||||
)
|
||||
|
||||
func (r Role) IsUser() bool {
|
||||
return r == RoleUser
|
||||
}
|
||||
|
||||
func (r Role) IsValidator() bool {
|
||||
return r == RoleValidator
|
||||
}
|
||||
|
||||
// Message is the protocol.Message that is used for MPC
|
||||
type Message *protocol.Message
|
||||
|
||||
type Signature *curves.EcdsaSignature
|
||||
|
||||
// RefreshFunc is the type for the refresh function
|
||||
type RefreshFunc interface {
|
||||
protocol.Iterator
|
||||
}
|
||||
|
||||
// SignFunc is the type for the sign function
|
||||
type SignFunc interface {
|
||||
protocol.Iterator
|
||||
}
|
||||
|
||||
type ValKeyshare struct {
|
||||
Message Message `json:"message"`
|
||||
Role int `json:"role"` // 1 for validator, 2 for user
|
||||
PublicKey []byte `json:"public-key"`
|
||||
}
|
||||
|
||||
func NewValKeyshare(msg Message) (*ValKeyshare, error) {
|
||||
valShare, err := dklsv1.DecodeAliceDkgResult(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ValKeyshare{
|
||||
Message: msg,
|
||||
Role: 1,
|
||||
PublicKey: valShare.PublicKey.ToAffineUncompressed(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) GetPayloads() map[string][]byte {
|
||||
return v.Message.Payloads
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) GetMetadata() map[string]string {
|
||||
return v.Message.Metadata
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) GetPublicKey() []byte {
|
||||
return v.PublicKey
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) GetProtocol() string {
|
||||
return v.Message.Protocol
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) GetRole() int32 {
|
||||
return int32(v.Role)
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) GetVersion() uint32 {
|
||||
return uint32(v.Message.Version)
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) ECDSAPublicKey() (*ecdsa.PublicKey, error) {
|
||||
return ComputeEcdsaPublicKey(v.PublicKey)
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) ExtractMessage() *protocol.Message {
|
||||
return &protocol.Message{
|
||||
Payloads: v.GetPayloads(),
|
||||
Metadata: v.GetMetadata(),
|
||||
Protocol: v.GetProtocol(),
|
||||
Version: uint(v.GetVersion()),
|
||||
}
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) RefreshFunc() (RefreshFunc, error) {
|
||||
curve := curves.K256()
|
||||
return dklsv1.NewAliceRefresh(curve, v.ExtractMessage(), protocol.Version1)
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) SignFunc(msg []byte) (SignFunc, error) {
|
||||
curve := curves.K256()
|
||||
return dklsv1.NewAliceSign(curve, sha3.New256(), msg, v.ExtractMessage(), protocol.Version1)
|
||||
}
|
||||
|
||||
func (v *ValKeyshare) Marshal() ([]byte, error) {
|
||||
return json.Marshal(v.Message)
|
||||
}
|
||||
|
||||
type UserKeyshare struct {
|
||||
Message Message `json:"message"` // BobOutput
|
||||
Role int `json:"role"` // 2 for user, 1 for validator
|
||||
PublicKey []byte `json:"public-key"`
|
||||
}
|
||||
|
||||
func NewUserKeyshare(msg Message) (*UserKeyshare, error) {
|
||||
out, err := dklsv1.DecodeBobDkgResult(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UserKeyshare{
|
||||
Message: msg,
|
||||
Role: 2,
|
||||
PublicKey: out.PublicKey.ToAffineUncompressed(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) GetPayloads() map[string][]byte {
|
||||
return u.Message.Payloads
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) GetMetadata() map[string]string {
|
||||
return u.Message.Metadata
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) GetPublicKey() []byte {
|
||||
return u.PublicKey
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) GetProtocol() string {
|
||||
return u.Message.Protocol
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) GetRole() int32 {
|
||||
return int32(u.Role)
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) GetVersion() uint32 {
|
||||
return uint32(u.Message.Version)
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) ECDSAPublicKey() (*ecdsa.PublicKey, error) {
|
||||
return ComputeEcdsaPublicKey(u.PublicKey)
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) ExtractMessage() *protocol.Message {
|
||||
return &protocol.Message{
|
||||
Payloads: u.GetPayloads(),
|
||||
Metadata: u.GetMetadata(),
|
||||
Protocol: u.GetProtocol(),
|
||||
Version: uint(u.GetVersion()),
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) RefreshFunc() (RefreshFunc, error) {
|
||||
curve := curves.K256()
|
||||
return dklsv1.NewBobRefresh(curve, u.ExtractMessage(), protocol.Version1)
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) SignFunc(msg []byte) (SignFunc, error) {
|
||||
curve := curves.K256()
|
||||
return dklsv1.NewBobSign(curve, sha3.New256(), msg, u.ExtractMessage(), protocol.Version1)
|
||||
}
|
||||
|
||||
func (u *UserKeyshare) Marshal() ([]byte, error) {
|
||||
jsonBytes, err := json.Marshal(u.Message)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return jsonBytes, nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package mpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/onsonr/sonr/crypto/didkey"
|
||||
"github.com/onsonr/sonr/x/dwn/types/attns"
|
||||
"github.com/ucan-wg/go-ucan"
|
||||
"lukechampine.com/blake3"
|
||||
)
|
||||
|
||||
type KeyshareSource interface {
|
||||
ucan.Source
|
||||
|
||||
Address() string
|
||||
Issuer() string
|
||||
ChainCode() ([]byte, error)
|
||||
OriginToken() (*Token, error)
|
||||
PublicKey() PublicKey
|
||||
SignData(data []byte) ([]byte, error)
|
||||
VerifyData(data []byte, sig []byte) (bool, error)
|
||||
UCANParser() *didkey.TokenParser
|
||||
}
|
||||
|
||||
func NewSource(ks Keyset) (KeyshareSource, error) {
|
||||
val := ks.Val()
|
||||
user := ks.User()
|
||||
iss, addr, err := ComputeIssuerDID(val.GetPublicKey())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ucanKeyshare{
|
||||
userShare: user,
|
||||
valShare: val,
|
||||
addr: addr,
|
||||
issuerDID: iss,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Address returns the address of the keyshare
|
||||
func (k ucanKeyshare) Address() string {
|
||||
return k.addr
|
||||
}
|
||||
|
||||
// Issuer returns the DID of the issuer of the keyshare
|
||||
func (k ucanKeyshare) Issuer() string {
|
||||
return k.issuerDID
|
||||
}
|
||||
|
||||
// ChainCode returns the chain code of the keyshare
|
||||
func (k ucanKeyshare) ChainCode() ([]byte, error) {
|
||||
sig, err := k.SignData([]byte(k.addr))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hash := blake3.Sum256(sig)
|
||||
// Return the first 32 bytes of the hash
|
||||
return hash[:32], nil
|
||||
}
|
||||
|
||||
// PublicKey returns the public key of the keyshare
|
||||
func (k ucanKeyshare) PublicKey() PublicKey {
|
||||
return createPublicKey(k.valShare.PublicKey, "secp256k1")
|
||||
}
|
||||
|
||||
// DefaultOriginToken returns a default token with the keyshare's issuer as the audience
|
||||
func (k ucanKeyshare) OriginToken() (*Token, error) {
|
||||
att := attns.CreateSmartAccountAttenuations(k.addr)
|
||||
zero := time.Time{}
|
||||
return k.NewOriginToken(k.issuerDID, att, nil, zero, zero)
|
||||
}
|
||||
|
||||
func (k ucanKeyshare) SignData(data []byte) ([]byte, error) {
|
||||
// Create signing functions
|
||||
signFunc, err := k.userShare.SignFunc(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create sign function: %w", err)
|
||||
}
|
||||
|
||||
valSignFunc, err := k.valShare.SignFunc(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create validator sign function: %w", err)
|
||||
}
|
||||
|
||||
// Run the signing protocol
|
||||
sig, err := RunSignProtocol(valSignFunc, signFunc)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to run sign protocol: %w", err)
|
||||
}
|
||||
return SerializeSignature(sig)
|
||||
}
|
||||
|
||||
func (k ucanKeyshare) VerifyData(data []byte, sig []byte) (bool, error) {
|
||||
return VerifySignature(k.userShare.PublicKey, data, sig)
|
||||
}
|
||||
|
||||
// TokenParser returns a token parser that can be used to parse tokens
|
||||
func (k ucanKeyshare) UCANParser() *didkey.TokenParser {
|
||||
caps := attns.AttentuationSmartAccount.GetCapabilities()
|
||||
ac := func(m map[string]interface{}) (ucan.Attenuation, error) {
|
||||
var (
|
||||
cap string
|
||||
rsc ucan.Resource
|
||||
)
|
||||
for key, vali := range m {
|
||||
val, ok := vali.(string)
|
||||
if !ok {
|
||||
return ucan.Attenuation{}, fmt.Errorf(`expected attenuation value to be a string`)
|
||||
}
|
||||
|
||||
if key == ucan.CapKey {
|
||||
cap = val
|
||||
} else {
|
||||
rsc = ucan.NewStringLengthResource(key, val)
|
||||
}
|
||||
}
|
||||
|
||||
return ucan.Attenuation{
|
||||
Rsc: rsc,
|
||||
Cap: caps.Cap(cap),
|
||||
}, nil
|
||||
}
|
||||
|
||||
store := ucan.NewMemTokenStore()
|
||||
return didkey.NewTokenParser(ac, customDIDPubKeyResolver{}, store.(ucan.CIDBytesResolver))
|
||||
}
|
||||
|
||||
// customDIDPubKeyResolver implements the DIDPubKeyResolver interface without
|
||||
// any network backing. Works if the key string given contains the public key
|
||||
// itself
|
||||
type customDIDPubKeyResolver struct{}
|
||||
|
||||
// ResolveDIDKey extracts a public key from a did:key string
|
||||
func (customDIDPubKeyResolver) ResolveDIDKey(ctx context.Context, didStr string) (didkey.ID, error) {
|
||||
return didkey.Parse(didStr)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package mpc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/ucan-wg/go-ucan"
|
||||
)
|
||||
|
||||
type (
|
||||
Token = ucan.Token
|
||||
Claims = ucan.Claims
|
||||
Proof = ucan.Proof
|
||||
|
||||
Attenuations = ucan.Attenuations
|
||||
Fact = ucan.Fact
|
||||
)
|
||||
|
||||
var (
|
||||
UCANVersion = ucan.UCANVersion
|
||||
UCANVersionKey = ucan.UCANVersionKey
|
||||
PrfKey = ucan.PrfKey
|
||||
FctKey = ucan.FctKey
|
||||
AttKey = ucan.AttKey
|
||||
CapKey = ucan.CapKey
|
||||
)
|
||||
|
||||
type ucanKeyshare struct {
|
||||
userShare *UserKeyshare
|
||||
valShare *ValKeyshare
|
||||
|
||||
addr string
|
||||
issuerDID string
|
||||
}
|
||||
|
||||
func (k ucanKeyshare) NewOriginToken(audienceDID string, att Attenuations, fct []Fact, notBefore, expires time.Time) (*ucan.Token, error) {
|
||||
return k.newToken(audienceDID, nil, att, fct, notBefore, expires)
|
||||
}
|
||||
|
||||
func (k ucanKeyshare) NewAttenuatedToken(parent *Token, audienceDID string, att ucan.Attenuations, fct []ucan.Fact, nbf, exp time.Time) (*Token, error) {
|
||||
if !parent.Attenuations.Contains(att) {
|
||||
return nil, fmt.Errorf("scope of ucan attenuations must be less than it's parent")
|
||||
}
|
||||
return k.newToken(audienceDID, append(parent.Proofs, Proof(parent.Raw)), att, fct, nbf, exp)
|
||||
}
|
||||
|
||||
func (k ucanKeyshare) newToken(audienceDID string, prf []Proof, att Attenuations, fct []Fact, nbf, exp time.Time) (*ucan.Token, error) {
|
||||
t := jwt.New(NewJWTSigningMethod("MPC256", k))
|
||||
|
||||
// if _, err := did.Parse(audienceDID); err != nil {
|
||||
// return nil, fmt.Errorf("invalid audience DID: %w", err)
|
||||
// }
|
||||
|
||||
t.Header[UCANVersionKey] = UCANVersion
|
||||
|
||||
var (
|
||||
nbfUnix int64
|
||||
expUnix int64
|
||||
)
|
||||
|
||||
if !nbf.IsZero() {
|
||||
nbfUnix = nbf.Unix()
|
||||
}
|
||||
if !exp.IsZero() {
|
||||
expUnix = exp.Unix()
|
||||
}
|
||||
|
||||
// set our claims
|
||||
t.Claims = &Claims{
|
||||
StandardClaims: &jwt.StandardClaims{
|
||||
Issuer: k.issuerDID,
|
||||
Audience: audienceDID,
|
||||
NotBefore: nbfUnix,
|
||||
// set the expire time
|
||||
// see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4
|
||||
ExpiresAt: expUnix,
|
||||
},
|
||||
Attenuations: att,
|
||||
Facts: fct,
|
||||
Proofs: prf,
|
||||
}
|
||||
|
||||
raw, err := t.SignedString(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Token{
|
||||
Raw: raw,
|
||||
Attenuations: att,
|
||||
Facts: fct,
|
||||
Proofs: prf,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user