feature/1120 leverage service authorization (#1188)

* refactor: remove redundant branch trigger for scheduled releases

* refactor: simplify process-compose commands and improve logging

* refactor: remove redundant  command

* refactor: remove unused error variables and simplify database configuration

* feat: introduce task runner for project automation

* refactor: Remove hardcoded action and method from form components

* refactor: move server setup to main.go and add prometheus metrics

* refactor: move index handlers to render handlers

* refactor: improve user identification logic in gateway and vault handlers

* refactor: rename TitleDescription to TitleDesc for consistency

* feat: integrate go-useragent library for enhanced user agent parsing

* feat: enhance initial view rendering based on device type

* feat: Add support for PostgreSQL database

* fix: Use formatPsqlDSN() to properly set PostgreSQL DSN from command flags

* feat: Add PostgreSQL support with fallback to SQLite in NewGormDB

* feat: Add PostgreSQL connection validation with SQLite fallback

* chore: update golang.org/x/crypto dependency to v0.31.0

* feat: add PKL-based configuration initialization

* refactor: improve file naming consistency in cmd/sonrd

* refactor: Improve init-pkl command with safer config file generation and error handling

* fix: add logging for pkl evaluation results

* refactor: Move credential handling to gateway context

* refactor: Migrate session models to gateway package

* refactor: rename models and update User model

* chore: initial commit for address and pubkey functionality

* refactor: move pubkey package to keys package

* refactor: Rename models and add resolver service

* feat: add gRPC clients for bank, DID, DWN, and SVC modules

* refactor: Migrate title and description components from text package to hero package

* refactor: improve file naming conventions

* feat: add user credential validation

* refactor: rename registration handlers and routes for clarity

* <no value>

* refactor: Decouple database and IPFS interactions from server setup

* refactor: Migrate configuration from class-based to TOML-based structure

* refactor: move network configuration files to sonr.net module

* feature/1120-leverage-service-authorization

* fix: correct DID identifier creation function name

* feat: add compressed and uncompressed public keys to keyset

* refactor: move address packages to crypto/address

* feat: implement pubkey verification

* refactor: remove ECDSA-related functions from keyshare and protocol modules

* feat: Implement ECDSA signature serialization

* <no value>

* feat: add vault service for IPFS token storage

* refactor: update ucan codec to use new DID generation method

* refactor: refactor key management and move address parsers to keys package

* refactor: rename key parsers and move to parsers package

* fix: resolved import issues with the new spec

* feat: improve user onboarding experience by updating button text and functionality

* refactor: update point marshaling and unmarshaling methods to use JSON

* refactor: remove unnecessary DID method from PubKey

* refactor: Rename and refactor MPC key generation functions

* test: Add comprehensive test suite for keyshare generation and validation

* test: Fix keyshare role validation and encoding tests

* feat: Update key share role tests with enclave initialization validation

* test(mpc): refactor tests to focus on public API and remove internal role checks

* refactor: Remove unnecessary role check in initKeyEnclave function

* fix: Enforce strict order for validator and user keyshares in enclave initialization

* fix: Update codec_test to match latest codec implementation

* refactor: Update KeyEnclave to use string-based key shares and improve error handling

* fix: Refactor MPC enclave to use string-based encoding and simplify key management

* refactor: Remove redundant keyshare decoding tests in codec_test.go

* fix: Resolve type conversion issues in MPC crypto enclave initialization

* fix: Convert CID to byte slice in addEnclaveIPFS function

* fix: Resolve type conversion and constant definition errors in MPC crypto utils

* refactor: Simplify KeyShare encoding and role handling in MPC codec

* fix: Resolve JSON unmarshaling type mismatch in KeyShare.Message()

* fix: Refactor KeyEnclave to use struct and Enclave interface

* fix: Resolve type and naming conflicts in MPC crypto package

* refactor: Update codec_test.go to use new KeyEnclave struct fields

* refactor: remove keyshare encoding and decoding logic

* refactor: Remove unused JSON marshaling functions for curve points

* fix: Improve signature serialization and deserialization in MPC crypto

This commit addresses several issues with signature handling:
- Fixed signature length to 65 bytes
- Added proper padding for R and S values
- Added nil and zero value checks
- Improved error messages for signature parsing

The changes ensure more robust signature encoding and decoding, preventing potential nil pointer and invalid signature issues.

* fix: Update signature serialization to match protocol test approach

* refactor: Simplify KeyEnclave struct and improve message handling

* fix: Improve signature serialization and verification in MPC crypto module

* refactor: Simplify enclave validation using IsValid method in test

* refactor: Add marshaling and comprehensive tests for KeyEnclave

* feat: Add JSON marshaling support for Point in KeyEnclave

* refactor: Rename KeyEnclave to Enclave and update related functions

* refactor: Update PubKey verification to use SHA3-256 hashing

* test: Add comprehensive tests for DID and PubKey implementations

* refactor: simplify DID key retrieval

* test: refactor CI workflow and remove unused DIDAuth middleware

* The changes look good! The updated workflows will now:

1. Run tests on push to master
2. Bump the version if the commit doesn't already start with 'bump:'
3. Trigger a release workflow automatically with the new version tag
4. Create and publish the release

A few things to note:
- Make sure you have the `peter-evans/repository-dispatch` action installed/available
- The `commitizen-tools/commitizen-action` should output the new tag for this to work
- Ensure your release workflow can handle the repository dispatch event

Would you like me to review or suggest any additional modifications to the workflows?

* ci(github actions): add build stage dependency for tests

* fix(workflow): update workflow to trigger on PR edits

* test: Update unit test dependencies

* ci: Add GoReleaser dry-run check for merge group events

* test: remove unnecessary dependencies between test jobs

* ci: Make race and coverage tests depend on build tests
This commit is contained in:
Prad Nukala
2024-12-13 20:10:27 +00:00
committed by GitHub
parent ee12bf684e
commit ac8c153b28
132 changed files with 2879 additions and 3397 deletions
+4 -4
View File
@@ -601,11 +601,11 @@ func (p *PointBls12377G1) UnmarshalText(input []byte) error {
}
func (p *PointBls12377G1) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *PointBls12377G1) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
@@ -874,11 +874,11 @@ func (p *PointBls12377G2) UnmarshalText(input []byte) error {
}
func (p *PointBls12377G2) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *PointBls12377G2) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
+4 -4
View File
@@ -573,11 +573,11 @@ func (p *PointBls12381G1) UnmarshalText(input []byte) error {
}
func (p *PointBls12381G1) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *PointBls12381G1) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
@@ -823,11 +823,11 @@ func (p *PointBls12381G2) UnmarshalText(input []byte) error {
}
func (p *PointBls12381G2) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *PointBls12381G2) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
+2 -2
View File
@@ -336,14 +336,14 @@ func pointUnmarshalText(input []byte) (Point, error) {
return curve.Point.FromAffineCompressed(buffer)
}
func pointMarshalJson(point Point) ([]byte, error) {
func pointMarshalJSON(point Point) ([]byte, error) {
m := make(map[string]string, 2)
m["type"] = point.CurveName()
m["value"] = hex.EncodeToString(point.ToAffineCompressed())
return json.Marshal(m)
}
func pointUnmarshalJson(input []byte) (Point, error) {
func pointUnmarshalJSON(input []byte) (Point, error) {
var m map[string]string
err := json.Unmarshal(input, &m)
+2 -2
View File
@@ -682,11 +682,11 @@ func (p *PointEd25519) UnmarshalText(input []byte) error {
}
func (p *PointEd25519) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *PointEd25519) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
+2 -2
View File
@@ -653,11 +653,11 @@ func (p *PointK256) UnmarshalText(input []byte) error {
}
func (p *PointK256) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *PointK256) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
+2 -2
View File
@@ -701,11 +701,11 @@ func (p *BenchPointP256) UnmarshalText(input []byte) error {
}
func (p *BenchPointP256) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *BenchPointP256) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
+2 -2
View File
@@ -651,11 +651,11 @@ func (p *PointP256) UnmarshalText(input []byte) error {
}
func (p *PointP256) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *PointP256) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
+2 -2
View File
@@ -669,11 +669,11 @@ func (p *PointPallas) UnmarshalText(input []byte) error {
}
func (p *PointPallas) MarshalJSON() ([]byte, error) {
return pointMarshalJson(p)
return pointMarshalJSON(p)
}
func (p *PointPallas) UnmarshalJSON(input []byte) error {
pt, err := pointUnmarshalJson(input)
pt, err := pointUnmarshalJSON(input)
if err != nil {
return err
}
+157
View File
@@ -0,0 +1,157 @@
package keys
import (
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"fmt"
"strings"
"github.com/libp2p/go-libp2p/core/crypto"
mb "github.com/multiformats/go-multibase"
varint "github.com/multiformats/go-varint"
)
const (
// KeyPrefix indicates a decentralized identifier that uses the key method
KeyPrefix = "did:key"
// MulticodecKindRSAPubKey rsa-x509-pub https://github.com/multiformats/multicodec/pull/226
MulticodecKindRSAPubKey = 0x1205
// MulticodecKindEd25519PubKey ed25519-pub
MulticodecKindEd25519PubKey = 0xed
// MulticodecKindSecp256k1PubKey secp256k1-pub
MulticodecKindSecp256k1PubKey = 0x1206
)
// DID is a DID:key identifier
type DID struct {
crypto.PubKey
}
// NewDID constructs an Identifier from a public key
func NewDID(pub crypto.PubKey) (DID, error) {
switch pub.Type() {
case crypto.Ed25519, crypto.RSA, crypto.Secp256k1:
return DID{PubKey: pub}, nil
default:
return DID{}, fmt.Errorf("unsupported key type: %s", pub.Type())
}
}
// MulticodecType indicates the type for this multicodec
func (id DID) MulticodecType() uint64 {
switch id.Type() {
case crypto.RSA:
return MulticodecKindRSAPubKey
case crypto.Ed25519:
return MulticodecKindEd25519PubKey
case crypto.Secp256k1:
return MulticodecKindSecp256k1PubKey
default:
panic("unexpected crypto type")
}
}
// String returns this did:key formatted as a string
func (id DID) String() string {
raw, err := id.Raw()
if err != nil {
return ""
}
t := id.MulticodecType()
size := varint.UvarintSize(t)
data := make([]byte, size+len(raw))
n := varint.PutUvarint(data, t)
copy(data[n:], raw)
b58BKeyStr, err := mb.Encode(mb.Base58BTC, data)
if err != nil {
return ""
}
return fmt.Sprintf("%s:%s", KeyPrefix, b58BKeyStr)
}
// VerifyKey returns the backing implementation for a public key, one of:
// *rsa.PublicKey, ed25519.PublicKey
func (id DID) VerifyKey() (interface{}, error) {
rawPubBytes, err := id.Raw()
if err != nil {
return nil, err
}
switch id.Type() {
case crypto.RSA:
verifyKeyiface, err := x509.ParsePKIXPublicKey(rawPubBytes)
if err != nil {
return nil, err
}
verifyKey, ok := verifyKeyiface.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("public key is not an RSA key. got type: %T", verifyKeyiface)
}
return verifyKey, nil
case crypto.Ed25519:
return ed25519.PublicKey(rawPubBytes), nil
case crypto.Secp256k1:
// Handle both compressed and uncompressed Secp256k1 public keys
if len(rawPubBytes) == 65 || len(rawPubBytes) == 33 {
return rawPubBytes, nil
}
return nil, fmt.Errorf("invalid Secp256k1 public key length: %d", len(rawPubBytes))
default:
return nil, fmt.Errorf("unrecognized Public Key type: %s", id.Type())
}
}
// Parse turns a string into a key method ID
func Parse(keystr string) (DID, error) {
var id DID
if !strings.HasPrefix(keystr, KeyPrefix) {
return id, fmt.Errorf("decentralized identifier is not a 'key' type")
}
keystr = strings.TrimPrefix(keystr, KeyPrefix+":")
enc, data, err := mb.Decode(keystr)
if err != nil {
return id, fmt.Errorf("decoding multibase: %w", err)
}
if enc != mb.Base58BTC {
return id, fmt.Errorf("unexpected multibase encoding: %s", mb.EncodingToStr[enc])
}
keyType, n, err := varint.FromUvarint(data)
if err != nil {
return id, err
}
switch keyType {
case MulticodecKindRSAPubKey:
pub, err := crypto.UnmarshalRsaPublicKey(data[n:])
if err != nil {
return id, err
}
return DID{pub}, nil
case MulticodecKindEd25519PubKey:
pub, err := crypto.UnmarshalEd25519PublicKey(data[n:])
if err != nil {
return id, err
}
return DID{pub}, nil
case MulticodecKindSecp256k1PubKey:
// Handle both compressed and uncompressed formats
keyData := data[n:]
if len(keyData) != 33 && len(keyData) != 65 {
return id, fmt.Errorf("invalid Secp256k1 public key length: %d", len(keyData))
}
pub, err := crypto.UnmarshalSecp256k1PublicKey(keyData)
if err != nil {
return id, fmt.Errorf("failed to unmarshal Secp256k1 key: %w", err)
}
return DID{pub}, nil
}
return id, fmt.Errorf("unrecognized key type multicodec prefix: %x", data[0])
}
+17
View File
@@ -0,0 +1,17 @@
package keys
type DIDMethod string
const (
DIDMethodKey DIDMethod = "key"
DIDMethodSonr DIDMethod = "sonr"
DIDMehthodBitcoin DIDMethod = "btcr"
DIDMethodEthereum DIDMethod = "ethr"
DIDMethodCbor DIDMethod = "cbor"
DIDMethodCID DIDMethod = "cid"
DIDMethodIPFS DIDMethod = "ipfs"
)
func (d DIDMethod) String() string {
return string(d)
}
+1
View File
@@ -0,0 +1 @@
package parsers
+12
View File
@@ -0,0 +1,12 @@
package parsers
type CosmosPrefix string
const (
ATOMPrefix CosmosPrefix = "cosmos"
AXELARPrefix CosmosPrefix = "axelar"
EVMOSPrefix CosmosPrefix = "evmos"
OSMOPrefix CosmosPrefix = "osmo"
SONRPrefix CosmosPrefix = "idx"
STARSPrefix CosmosPrefix = "stars"
)
+1
View File
@@ -0,0 +1 @@
package parsers
+1
View File
@@ -0,0 +1 @@
package parsers
@@ -1,4 +1,4 @@
package didkey
package parsers
import (
"crypto/ed25519"
@@ -23,23 +23,23 @@ const (
MulticodecKindSecp256k1PubKey = 0x1206
)
// ID is a DID:key identifier
type ID struct {
// DIDKey is a DID:key identifier
type DIDKey struct {
crypto.PubKey
}
// NewID constructs an Identifier from a public key
func NewID(pub crypto.PubKey) (ID, error) {
// NewKeyDID constructs an Identifier from a public key
func NewKeyDID(pub crypto.PubKey) (DIDKey, error) {
switch pub.Type() {
case crypto.Ed25519, crypto.RSA, crypto.Secp256k1:
return ID{PubKey: pub}, nil
return DIDKey{PubKey: pub}, nil
default:
return ID{}, fmt.Errorf("unsupported key type: %s", pub.Type())
return DIDKey{}, fmt.Errorf("unsupported key type: %s", pub.Type())
}
}
// MulticodecType indicates the type for this multicodec
func (id ID) MulticodecType() uint64 {
func (id DIDKey) MulticodecType() uint64 {
switch id.Type() {
case crypto.RSA:
return MulticodecKindRSAPubKey
@@ -53,7 +53,7 @@ func (id ID) MulticodecType() uint64 {
}
// String returns this did:key formatted as a string
func (id ID) String() string {
func (id DIDKey) String() string {
raw, err := id.Raw()
if err != nil {
return ""
@@ -75,7 +75,7 @@ func (id ID) String() string {
// VerifyKey returns the backing implementation for a public key, one of:
// *rsa.PublicKey, ed25519.PublicKey
func (id ID) VerifyKey() (interface{}, error) {
func (id DIDKey) VerifyKey() (interface{}, error) {
rawPubBytes, err := id.PubKey.Raw()
if err != nil {
return nil, err
@@ -100,13 +100,13 @@ func (id ID) VerifyKey() (interface{}, error) {
}
return nil, fmt.Errorf("invalid Secp256k1 public key length: %d", len(rawPubBytes))
default:
return nil, fmt.Errorf("unrecognized Public Key type: %s", id.PubKey.Type())
return nil, fmt.Errorf("unrecognized Public Key type: %s", id.Type())
}
}
// Parse turns a string into a key method ID
func Parse(keystr string) (ID, error) {
var id ID
func Parse(keystr string) (DIDKey, error) {
var id DIDKey
if !strings.HasPrefix(keystr, KeyPrefix) {
return id, fmt.Errorf("decentralized identifier is not a 'key' type")
}
@@ -133,13 +133,13 @@ func Parse(keystr string) (ID, error) {
if err != nil {
return id, err
}
return ID{pub}, nil
return DIDKey{pub}, nil
case MulticodecKindEd25519PubKey:
pub, err := crypto.UnmarshalEd25519PublicKey(data[n:])
if err != nil {
return id, err
}
return ID{pub}, nil
return DIDKey{pub}, nil
case MulticodecKindSecp256k1PubKey:
// Handle both compressed and uncompressed formats
keyData := data[n:]
@@ -150,7 +150,7 @@ func Parse(keystr string) (ID, error) {
if err != nil {
return id, fmt.Errorf("failed to unmarshal Secp256k1 key: %w", err)
}
return ID{pub}, nil
return DIDKey{pub}, nil
}
return id, fmt.Errorf("unrecognized key type multicodec prefix: %x", data[0])
+1
View File
@@ -0,0 +1 @@
package parsers
+1
View File
@@ -0,0 +1 @@
package parsers
+62
View File
@@ -0,0 +1,62 @@
package keys
import (
"crypto/ecdsa"
"encoding/hex"
"github.com/onsonr/sonr/crypto/core/curves"
"golang.org/x/crypto/sha3"
)
type PubKey interface {
Bytes() []byte
Type() string
Hex() string
Verify(msg []byte, sig []byte) (bool, error)
}
type pubKey struct {
publicPoint curves.Point
method string
}
func NewPubKey(pk curves.Point) PubKey {
return &pubKey{
publicPoint: pk,
}
}
func (p pubKey) Bytes() []byte {
return p.publicPoint.ToAffineCompressed()
}
func (p pubKey) Hex() string {
return hex.EncodeToString(p.publicPoint.ToAffineCompressed())
}
func (p pubKey) Type() string {
return "secp256k1"
}
func (p pubKey) Verify(data []byte, sigBz []byte) (bool, error) {
sig, err := deserializeSignature(sigBz)
if err != nil {
return false, err
}
pp, err := getEcdsaPoint(p.Bytes())
if err != nil {
return false, err
}
pk := &ecdsa.PublicKey{
Curve: pp.Curve,
X: pp.X,
Y: pp.Y,
}
// Hash the message using SHA3-256
hash := sha3.New256()
hash.Write(data)
digest := hash.Sum(nil)
return ecdsa.Verify(pk, digest, sig.R, sig.S), nil
}
+46
View File
@@ -0,0 +1,46 @@
package keys
import (
"errors"
"fmt"
"math/big"
"github.com/onsonr/sonr/crypto/core/curves"
)
// getEcdsaPoint builds an elliptic curve point from a compressed byte slice
func getEcdsaPoint(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
}
// SerializeSecp256k1Signature serializes an ECDSA signature into a byte slice
func serializeSignature(sig *curves.EcdsaSignature) ([]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) (*curves.EcdsaSignature, 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
}
+22
View File
@@ -0,0 +1,22 @@
package mpc
import (
"github.com/onsonr/sonr/crypto/core/curves"
"github.com/onsonr/sonr/crypto/core/protocol"
"github.com/onsonr/sonr/crypto/tecdsa/dklsv1/dkg"
)
// ╭───────────────────────────────────────────────────────────╮
// │ Exported Generics │
// ╰───────────────────────────────────────────────────────────╯
type (
AliceOut *dkg.AliceOutput
BobOut *dkg.BobOutput
Point curves.Point
Role string // Role is the type for the role
Message *protocol.Message // Message is the protocol.Message that is used for MPC
Signature *curves.EcdsaSignature // Signature is the type for the signature
RefreshFunc interface{ protocol.Iterator } // RefreshFunc is the type for the refresh function
SignFunc interface{ protocol.Iterator } // SignFunc is the type for the sign function
)
+105
View File
@@ -0,0 +1,105 @@
package mpc
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestKeyShareGeneration(t *testing.T) {
t.Run("Generate Valid Enclave", func(t *testing.T) {
// Generate enclave
enclave, err := GenEnclave()
require.NoError(t, err)
require.NotNil(t, enclave)
// Validate enclave contents
assert.True(t, enclave.IsValid())
})
}
func TestEnclaveOperations(t *testing.T) {
t.Run("Signing and Verification", func(t *testing.T) {
// Generate valid enclave
enclave, err := GenEnclave()
require.NoError(t, err)
// Test signing
testData := []byte("test message")
signature, err := enclave.Sign(testData)
require.NoError(t, err)
require.NotNil(t, signature)
// Verify the signature
valid, err := enclave.Verify(testData, signature)
require.NoError(t, err)
assert.True(t, valid)
// Test invalid data verification
invalidData := []byte("wrong message")
valid, err = enclave.Verify(invalidData, signature)
require.NoError(t, err)
assert.False(t, valid)
})
t.Run("Address and Public Key", func(t *testing.T) {
enclave, err := GenEnclave()
require.NoError(t, err)
// Test Address
addr := enclave.Address()
assert.NotEmpty(t, addr)
assert.True(t, strings.HasPrefix(addr, "idx"))
// Test Public Key
pubKey := enclave.PubKey()
assert.NotNil(t, pubKey)
assert.NotEmpty(t, pubKey.Bytes())
})
t.Run("Refresh Operation", func(t *testing.T) {
enclave, err := GenEnclave()
require.NoError(t, err)
// Test refresh
refreshedEnclave, err := enclave.Refresh()
require.NoError(t, err)
require.NotNil(t, refreshedEnclave)
// Verify refreshed enclave is valid
assert.True(t, refreshedEnclave.IsValid())
// Verify it maintains the same address
assert.Equal(t, enclave.Address(), refreshedEnclave.Address())
})
}
func TestEnclaveSerialization(t *testing.T) {
t.Run("Marshal and Unmarshal", func(t *testing.T) {
// Generate original enclave
original, err := GenEnclave()
require.NoError(t, err)
require.NotNil(t, original)
// Marshal
keyEnclave, ok := original.(*KeyEnclave)
require.True(t, ok)
data, err := keyEnclave.Marshal()
require.NoError(t, err)
require.NotEmpty(t, data)
// Unmarshal
restored := &KeyEnclave{}
err = restored.Unmarshal(data)
require.NoError(t, err)
// Verify restored enclave
assert.Equal(t, keyEnclave.Addr, restored.Addr)
assert.True(t, keyEnclave.PubPoint.Equal(restored.PubPoint))
assert.Equal(t, keyEnclave.VaultCID, restored.VaultCID)
assert.True(t, restored.IsValid())
})
}
+151
View File
@@ -0,0 +1,151 @@
package mpc
import (
"crypto/ecdsa"
"encoding/json"
"github.com/onsonr/sonr/crypto/core/curves"
"github.com/onsonr/sonr/crypto/core/protocol"
"github.com/onsonr/sonr/crypto/keys"
"github.com/onsonr/sonr/crypto/tecdsa/dklsv1"
"golang.org/x/crypto/sha3"
)
// Enclave defines the interface for key management operations
type Enclave interface {
Address() string
IsValid() bool
PubKey() keys.PubKey
Refresh() (Enclave, error)
Sign(data []byte) ([]byte, error)
Verify(data []byte, sig []byte) (bool, error)
}
// KeyEnclave implements the Enclave interface
type KeyEnclave struct {
Addr string `json:"address"`
PubPoint curves.Point `json:"-"`
PubBytes []byte `json:"pub_key"`
ValShare Message `json:"val_share"`
UserShare Message `json:"user_share"`
VaultCID string `json:"vault_cid,omitempty"`
}
// Marshal returns the JSON encoding of KeyEnclave
func (k *KeyEnclave) Marshal() ([]byte, error) {
// Store compressed public point bytes before marshaling
k.PubBytes = k.PubPoint.ToAffineCompressed()
return json.Marshal(k)
}
// Unmarshal parses the JSON-encoded data and stores the result
func (k *KeyEnclave) Unmarshal(data []byte) error {
if err := json.Unmarshal(data, k); err != nil {
return err
}
// Reconstruct Point from bytes
curve := curves.K256()
point, err := curve.NewIdentityPoint().FromAffineCompressed(k.PubBytes)
if err != nil {
return err
}
k.PubPoint = point
return nil
}
func (k *KeyEnclave) IsValid() bool {
return k.PubPoint != nil && k.ValShare != nil && k.UserShare != nil && k.Addr != ""
}
func initKeyEnclave(valShare, userShare Message) (*KeyEnclave, error) {
pubPoint, err := getAlicePubPoint(valShare)
if err != nil {
return nil, err
}
addr, err := computeSonrAddr(pubPoint)
if err != nil {
return nil, err
}
return &KeyEnclave{
Addr: addr,
PubPoint: pubPoint,
ValShare: valShare,
UserShare: userShare,
}, nil
}
func (k *KeyEnclave) Address() string {
return k.Addr
}
func (k *KeyEnclave) PubKey() keys.PubKey {
return keys.NewPubKey(k.PubPoint)
}
func (k *KeyEnclave) Refresh() (Enclave, error) {
refreshFuncVal, err := k.valRefreshFunc()
if err != nil {
return nil, err
}
refreshFuncUser, err := k.userRefreshFunc()
if err != nil {
return nil, err
}
return ExecuteRefresh(refreshFuncVal, refreshFuncUser)
}
func (k *KeyEnclave) Sign(data []byte) ([]byte, error) {
userSign, err := k.userSignFunc(data)
if err != nil {
return nil, err
}
valSign, err := k.valSignFunc(data)
if err != nil {
return nil, err
}
return ExecuteSigning(valSign, userSign)
}
func (k *KeyEnclave) Verify(data []byte, sig []byte) (bool, error) {
edSig, err := deserializeSignature(sig)
if err != nil {
return false, err
}
ePub, err := getEcdsaPoint(k.PubPoint.ToAffineUncompressed())
if err != nil {
return false, err
}
pk := &ecdsa.PublicKey{
Curve: ePub.Curve,
X: ePub.X,
Y: ePub.Y,
}
// Hash the message using SHA3-256
hash := sha3.New256()
hash.Write(data)
digest := hash.Sum(nil)
return ecdsa.Verify(pk, digest, edSig.R, edSig.S), nil
}
func (k *KeyEnclave) userSignFunc(bz []byte) (SignFunc, error) {
curve := curves.K256()
return dklsv1.NewBobSign(curve, sha3.New256(), bz, k.UserShare, protocol.Version1)
}
func (k *KeyEnclave) userRefreshFunc() (RefreshFunc, error) {
curve := curves.K256()
return dklsv1.NewBobRefresh(curve, k.UserShare, protocol.Version1)
}
func (k *KeyEnclave) valSignFunc(bz []byte) (SignFunc, error) {
curve := curves.K256()
return dklsv1.NewAliceSign(curve, sha3.New256(), bz, k.ValShare, protocol.Version1)
}
func (k *KeyEnclave) valRefreshFunc() (RefreshFunc, error) {
curve := curves.K256()
return dklsv1.NewAliceRefresh(curve, k.ValShare, protocol.Version1)
}
-61
View File
@@ -1,61 +0,0 @@
package mpc
import (
"fmt"
"github.com/cosmos/cosmos-sdk/types/bech32"
)
type (
ExportedKeyset = []byte
)
type Keyset interface {
Address() string
Val() *ValKeyshare
ValJSON() string
User() *UserKeyshare
UserJSON() string
}
type keyset struct {
val *ValKeyshare
user *UserKeyshare
addr string
}
func (k keyset) Address() string {
return k.addr
}
func (k keyset) Val() *ValKeyshare {
return k.val
}
func (k keyset) User() *UserKeyshare {
return k.user
}
func (k keyset) ValJSON() string {
return k.val.String()
}
func (k keyset) UserJSON() string {
return k.user.String()
}
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
}
-71
View File
@@ -1,71 +0,0 @@
package mpc
import (
"crypto/ecdsa"
"github.com/onsonr/sonr/crypto/core/protocol"
"github.com/onsonr/sonr/crypto/tecdsa/dklsv1/dkg"
)
// BaseKeyshare contains common fields and methods for both validator and user keyshares
type BaseKeyshare struct {
Message *protocol.Message `json:"message"`
Role int `json:"role"`
UncompressedPubKey []byte `json:"public_key"`
CompressedPubKey []byte `json:"compressed_public_key"`
}
func initFromAlice(aliceOut *dkg.AliceOutput, originalMsg *protocol.Message) BaseKeyshare {
return BaseKeyshare{
Message: originalMsg,
Role: 1,
UncompressedPubKey: aliceOut.PublicKey.ToAffineUncompressed(),
CompressedPubKey: aliceOut.PublicKey.ToAffineCompressed(),
}
}
func initFromBob(bobOut *dkg.BobOutput, originalMsg *protocol.Message) BaseKeyshare {
return BaseKeyshare{
Message: originalMsg,
Role: 2,
UncompressedPubKey: bobOut.PublicKey.ToAffineUncompressed(),
CompressedPubKey: bobOut.PublicKey.ToAffineCompressed(),
}
}
func (b *BaseKeyshare) GetPayloads() map[string][]byte {
return b.Message.Payloads
}
func (b *BaseKeyshare) GetMetadata() map[string]string {
return b.Message.Metadata
}
func (b *BaseKeyshare) GetPublicKey() []byte {
return b.UncompressedPubKey
}
func (b *BaseKeyshare) GetProtocol() string {
return b.Message.Protocol
}
func (b *BaseKeyshare) GetRole() int32 {
return int32(b.Role)
}
func (b *BaseKeyshare) GetVersion() uint32 {
return uint32(b.Message.Version)
}
func (b *BaseKeyshare) ECDSAPublicKey() (*ecdsa.PublicKey, error) {
return ComputeEcdsaPublicKey(b.UncompressedPubKey)
}
func (b *BaseKeyshare) ExtractMessage() *protocol.Message {
return &protocol.Message{
Payloads: b.GetPayloads(),
Metadata: b.GetMetadata(),
Protocol: b.GetProtocol(),
Version: uint(b.GetVersion()),
}
}
+34 -118
View File
@@ -1,20 +1,14 @@
package mpc
import (
"crypto/ecdsa"
genericecdsa "crypto/ecdsa"
"errors"
"fmt"
"math/big"
"github.com/ipfs/kubo/client/rpc"
"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"
)
// NewKeyshareSource generates a new MPC keyshare
func NewKeyset() (Keyset, error) {
// GenEnclave generates a new MPC keyshare
func GenEnclave() (Enclave, error) {
curve := curves.K256()
valKs := dklsv1.NewAliceDkg(curve, protocol.Version1)
userKs := dklsv1.NewBobDkg(curve, protocol.Version1)
@@ -26,7 +20,23 @@ func NewKeyset() (Keyset, error) {
if err != nil {
return nil, err
}
valShare, err := NewValKeyshare(valRes)
userRes, err := userKs.Result(protocol.Version1)
if err != nil {
return nil, err
}
return initKeyEnclave(valRes, userRes)
}
// GenEnclaveIPFS generates a new MPC keyshare
func GenEnclaveIPFS(ipc *rpc.HttpApi) (Enclave, error) {
curve := curves.K256()
valKs := dklsv1.NewAliceDkg(curve, protocol.Version1)
userKs := dklsv1.NewBobDkg(curve, protocol.Version1)
aErr, bErr := RunProtocol(userKs, valKs)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
}
valRes, err := valKs.Result(protocol.Version1)
if err != nil {
return nil, err
}
@@ -34,19 +44,15 @@ func NewKeyset() (Keyset, error) {
if err != nil {
return nil, err
}
userShare, err := NewUserKeyshare(userRes)
e, err := initKeyEnclave(valRes, userRes)
if err != nil {
return nil, err
}
addr, err := computeSonrAddr(valShare.CompressedPublicKey())
if err != nil {
return nil, err
}
return keyset{val: valShare, user: userShare, addr: addr}, nil
return addEnclaveIPFS(e, ipc)
}
// ExecuteSigning runs the MPC signing protocol
func ExecuteSigning(signFuncVal SignFunc, signFuncUser SignFunc) (Signature, error) {
func ExecuteSigning(signFuncVal SignFunc, signFuncUser SignFunc) ([]byte, error) {
aErr, bErr := RunProtocol(signFuncVal, signFuncUser)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
@@ -55,11 +61,19 @@ func ExecuteSigning(signFuncVal SignFunc, signFuncUser SignFunc) (Signature, err
if err != nil {
return nil, err
}
return dklsv1.DecodeSignature(out)
s, err := dklsv1.DecodeSignature(out)
if err != nil {
return nil, err
}
sig, err := serializeSignature(s)
if err != nil {
return nil, err
}
return sig, nil
}
// ExecuteRefresh runs the MPC refresh protocol
func ExecuteRefresh(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc) (Keyset, error) {
func ExecuteRefresh(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc) (*KeyEnclave, error) {
aErr, bErr := RunProtocol(refreshFuncVal, refreshFuncUser)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
@@ -68,53 +82,11 @@ func ExecuteRefresh(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc) (Ke
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
}
addr, err := computeSonrAddr(valShare.CompressedPublicKey())
if err != nil {
return nil, err
}
return keyset{val: valShare, user: userShare, addr: addr}, 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)
return initKeyEnclave(valRefreshResult, userRefreshResult)
}
// For DKG bob starts first. For refresh and sign, Alice starts first.
@@ -139,59 +111,3 @@ func RunProtocol(firstParty protocol.Iterator, secondParty protocol.Iterator) (e
}
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
}
-150
View File
@@ -1,150 +0,0 @@
package mpc
import (
"errors"
"github.com/cosmos/cosmos-sdk/types/bech32"
"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 {
BaseKeyshare
encoded string
}
func computeSonrAddr(pk []byte) (string, error) {
sonrAddr, err := bech32.ConvertAndEncode("idx", pk)
if err != nil {
return "", err
}
return sonrAddr, nil
}
func NewValKeyshare(msg *protocol.Message) (*ValKeyshare, error) {
vks := new(ValKeyshare)
encoded, err := protocol.EncodeMessage(msg)
if err != nil {
return nil, err
}
valShare, err := dklsv1.DecodeAliceDkgResult(msg)
if err != nil {
return nil, err
}
vks.BaseKeyshare = initFromAlice(valShare, msg)
vks.encoded = encoded
return vks, nil
}
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) String() string {
return v.encoded
}
// PublicKey returns the uncompressed public key (65 bytes)
func (v *ValKeyshare) PublicKey() []byte {
return v.UncompressedPubKey
}
// CompressedPublicKey returns the compressed public key (33 bytes)
func (v *ValKeyshare) CompressedPublicKey() []byte {
return v.CompressedPubKey
}
type UserKeyshare struct {
BaseKeyshare
encoded string
}
func NewUserKeyshare(msg *protocol.Message) (*UserKeyshare, error) {
uks := new(UserKeyshare)
encoded, err := protocol.EncodeMessage(msg)
if err != nil {
return nil, err
}
out, err := dklsv1.DecodeBobDkgResult(msg)
if err != nil {
return nil, err
}
uks.BaseKeyshare = initFromBob(out, msg)
uks.encoded = encoded
return uks, nil
}
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) String() string {
return u.encoded
}
// PublicKey returns the uncompressed public key (65 bytes)
func (u *UserKeyshare) PublicKey() []byte {
return u.UncompressedPubKey
}
// CompressedPublicKey returns the compressed public key (33 bytes)
func (u *UserKeyshare) CompressedPublicKey() []byte {
return u.CompressedPubKey
}
func encodeMessage(m *protocol.Message) (string, error) {
return protocol.EncodeMessage(m)
}
func decodeMessage(s string) (*protocol.Message, error) {
return protocol.DecodeMessage(s)
}
+83
View File
@@ -0,0 +1,83 @@
package spec
import (
"crypto/sha256"
"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)
// valid, err := m.ks.valShare.PublicKey().Verify(digest, sig)
// if !valid || err != nil {
// 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 := mpc.ExecuteSigning(valSignFunc, signFunc)
// if err != nil {
// return "", fmt.Errorf("failed to run sign protocol: %w", err)
// }
// Encode the signature
// encoded := base64.RawURLEncoding.EncodeToString(sig)
return "", nil
}
func init() {
// Register the MPC signing method
jwt.RegisterSigningMethod("MPC256", func() jwt.SigningMethod {
return &MPCSigningMethod{
Name: "MPC256",
}
})
}
@@ -5,9 +5,8 @@ import (
"fmt"
"time"
"github.com/onsonr/sonr/crypto/mpc"
"github.com/onsonr/sonr/crypto/keys"
"github.com/onsonr/sonr/crypto/ucan"
"github.com/onsonr/sonr/crypto/ucan/didkey"
"lukechampine.com/blake3"
)
@@ -23,21 +22,18 @@ type KeyshareSource interface {
UCANParser() *ucan.TokenParser
}
func NewSource(ks mpc.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
}
// func NewSource(ks mpc.KeyEnclave) (KeyshareSource, error) {
// iss, addr, err := getIssuerDID(val.PublicKey())
// if err != nil {
// return nil, err
// }
//
// return ucanKeyshare{
// issuerDID: iss,
// addr: addr,
// }, nil
// }
//
// Address returns the address of the keyshare
func (k ucanKeyshare) Address() string {
return k.addr
@@ -67,27 +63,25 @@ func (k ucanKeyshare) OriginToken() (*Token, error) {
}
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)
}
// // 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 := mpc.ExecuteSigning(valSignFunc, signFunc)
if err != nil {
return nil, fmt.Errorf("failed to run sign protocol: %w", err)
}
return mpc.SerializeSignature(sig)
// return mpc.ExecuteSigning(valSignFunc, signFunc)
return nil, nil
}
func (k ucanKeyshare) VerifyData(data []byte, sig []byte) (bool, error) {
return mpc.VerifySignature(k.userShare.PublicKey(), data, sig)
return false, nil
// return k.valShare.PublicKey().Verify(data, sig)
}
// TokenParser returns a token parser that can be used to parse tokens
@@ -127,6 +121,6 @@ func (k ucanKeyshare) UCANParser() *ucan.TokenParser {
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)
func (customDIDPubKeyResolver) ResolveDIDKey(ctx context.Context, didStr string) (keys.DID, error) {
return keys.Parse(didStr)
}
@@ -7,7 +7,7 @@ import (
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/golang-jwt/jwt"
"github.com/onsonr/sonr/crypto/mpc"
"github.com/onsonr/sonr/crypto/keys"
"github.com/onsonr/sonr/crypto/ucan"
)
@@ -30,9 +30,6 @@ var (
)
type ucanKeyshare struct {
userShare *mpc.UserKeyshare
valShare *mpc.ValKeyshare
addr string
issuerDID string
}
@@ -97,20 +94,10 @@ func (k ucanKeyshare) newToken(audienceDID string, prf []Proof, att Attenuations
}, nil
}
// ComputeIssuerDID computes the issuer DID from a public key
func ComputeIssuerDID(pk []byte) (string, string, error) {
addr, err := ComputeSonrAddr(pk)
func getIssuerDID(pk keys.PubKey) (string, string, error) {
addr, err := bech32.ConvertAndEncode("idx", pk.Bytes())
if err != nil {
return "", "", err
}
return fmt.Sprintf("did:sonr:%s", addr), addr, nil
}
// ComputeSonrAddr computes the Sonr address from a public key
func ComputeSonrAddr(pk []byte) (string, error) {
sonrAddr, err := bech32.ConvertAndEncode("idx", pk)
if err != nil {
return "", err
}
return sonrAddr, nil
}
+124
View File
@@ -0,0 +1,124 @@
package mpc
import (
"context"
"encoding/json"
"errors"
"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"
"github.com/onsonr/sonr/crypto/tecdsa/dklsv1"
)
func addEnclaveIPFS(enclave *KeyEnclave, ipc *rpc.HttpApi) (Enclave, error) {
jsonEnclave, err := json.Marshal(enclave)
if err != nil {
return nil, err
}
// Save enclave to IPFS
cid, err := ipc.Unixfs().Add(context.Background(), files.NewBytesFile(jsonEnclave))
if err != nil {
return nil, err
}
enclave.VaultCID = cid.String()
return enclave, 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
}
func computeSonrAddr(pp Point) (string, error) {
pk := pp.ToAffineCompressed()
sonrAddr, err := bech32.ConvertAndEncode("idx", pk)
if err != nil {
return "", err
}
return sonrAddr, nil
}
func getAliceOut(msg *protocol.Message) (AliceOut, error) {
return dklsv1.DecodeAliceDkgResult(msg)
}
func getAlicePubPoint(msg *protocol.Message) (Point, error) {
out, err := dklsv1.DecodeAliceDkgResult(msg)
if err != nil {
return nil, err
}
return out.PublicKey, nil
}
func getBobOut(msg *protocol.Message) (BobOut, error) {
return dklsv1.DecodeBobDkgResult(msg)
}
func getBobPubPoint(msg *protocol.Message) (Point, error) {
out, err := dklsv1.DecodeBobDkgResult(msg)
if err != nil {
return nil, err
}
return out.PublicKey, nil
}
// getEcdsaPoint builds an elliptic curve point from a compressed byte slice
func getEcdsaPoint(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 serializeSignature(sig *curves.EcdsaSignature) ([]byte, error) {
if sig == nil {
return nil, errors.New("nil signature")
}
rBytes := sig.R.Bytes()
sBytes := sig.S.Bytes()
// Ensure both components are 32 bytes
rPadded := make([]byte, 32)
sPadded := make([]byte, 32)
copy(rPadded[32-len(rBytes):], rBytes)
copy(sPadded[32-len(sBytes):], sBytes)
// Concatenate R and S
result := make([]byte, 64)
copy(result[0:32], rPadded)
copy(result[32:64], sPadded)
return result, nil
}
func deserializeSignature(sigBytes []byte) (*curves.EcdsaSignature, error) {
if len(sigBytes) != 64 {
return nil, fmt.Errorf("invalid signature length: expected 64 bytes, got %d", len(sigBytes))
}
r := new(big.Int).SetBytes(sigBytes[:32])
s := new(big.Int).SetBytes(sigBytes[32:])
return &curves.EcdsaSignature{
R: r,
S: s,
}, nil
}
@@ -1 +0,0 @@
package capability
@@ -1,33 +0,0 @@
package resourcetype
// Resource is a unique identifier for a thing, usually stored state. Resources
// are organized by string types
type Resource interface {
Type() ResourceType
Value() string
Contains(b Resource) bool
}
type stringResource struct {
t ResourceType
v string
}
func (r stringResource) Type() ResourceType {
return r.t
}
func (r stringResource) Value() string {
return r.v
}
func (r stringResource) Contains(b Resource) bool {
return r.Type() == b.Type() && len(r.Value()) <= len(b.Value())
}
func NewResource(typ ResourceType, val string) Resource {
return stringResource{
t: typ,
v: val,
}
}
+2 -5
View File
@@ -98,12 +98,9 @@ func ServiceCapabilities() []string {
// NewVault creates default attenuations for a smart account
func NewVault(
kss mpc.Keyset,
kss mpc.KeyEnclave,
) Attenuations {
accountAddr, err := mpc.ComputeSonrAddr(kss.User().GetPublicKey())
if err != nil {
return nil
}
accountAddr := kss.Address()
caps := VaultPermissions.GetCapabilities()
return Attenuations{
// Owner capabilities
-86
View File
@@ -1,86 +0,0 @@
package didkey
import (
"log"
"testing"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/onsonr/sonr/crypto/mpc"
)
func TestID_Parse(t *testing.T) {
keyStrED := "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH"
id, err := Parse(keyStrED)
if err != nil {
t.Fatal(err)
}
if id.String() != keyStrED {
t.Errorf("string mismatch.\nwant: %q\ngot: %q", keyStrED, id.String())
}
keyStrRSA := "did:key:z2MGw4gk84USotaWf4AkJ83DcnrfgGaceF86KQXRYMfQ7xqnUFp38UZ6Le8JPfkb4uCLGjHBzKpjEXb9hx9n2ftecQWCHXKtKszkke4FmENdTZ7i9sqRmL3pLnEEJ774r3HMuuC7tNRQ6pqzrxatXx2WinCibdhUmvh3FobnA9ygeqkSGtV6WLa7NVFw9cAvnv8Y6oHcaoZK7fNP4ASGs6AHmSC6ydSR676aKYMe95QmEAj4xJptDsSxG7zLAGzAdwCgm56M4fTno8GdWNmU6Pdghnuf6fWyYus9ASwdfwyaf3SDf4uo5T16PRJssHkQh6DJHfK4Rka7RNQLjzfGBPjFLHbUSvmf4EdbHasbVaveAArD68ZfazRCCvjdovQjWr6uyLCwSAQLPUFZBTT8mW"
id, err = Parse(keyStrRSA)
if err != nil {
t.Fatal(err)
}
if id.String() != keyStrRSA {
t.Errorf("string mismatch.\nwant: %q\ngot: %q", keyStrRSA, id.String())
}
}
func TestID_FromMPCKey(t *testing.T) {
// Generate new MPC keyset
ks, err := mpc.NewKeyset()
if err != nil {
t.Fatalf("failed to generate MPC keyset: %v", err)
}
// Get public key from validator share
pubKey := ks.Val().PublicKey()
if len(pubKey) != 65 {
t.Fatalf("expected 65-byte uncompressed public key, got %d bytes", len(pubKey))
}
// Create crypto.PubKey from raw bytes
cryptoPubKey, err := crypto.UnmarshalSecp256k1PublicKey(pubKey)
if err != nil {
t.Fatalf("failed to unmarshal public key: %v", err)
}
// Create DID Key ID
id, err := NewID(cryptoPubKey)
if err != nil {
t.Fatalf("failed to create DID Key ID: %v", err)
}
log.Printf("%s\n", id.String())
// Verify the key can be parsed back
parsed, err := Parse(id.String())
if err != nil {
t.Fatalf("failed to parse DID Key string: %v", err)
}
// Verify the parsed key matches original
if parsed.String() != id.String() {
t.Errorf("parsed key doesn't match original.\nwant: %q\ngot: %q",
id.String(), parsed.String())
}
// Verify we can get back a valid verify key
verifyKey, err := id.VerifyKey()
if err != nil {
t.Fatalf("failed to get verify key: %v", err)
}
// Verify the key is the right type and length
rawKey, ok := verifyKey.([]byte)
if !ok {
t.Fatalf("expected []byte verify key, got %T", verifyKey)
}
if len(rawKey) != 65 && len(rawKey) != 33 {
t.Errorf("invalid key length %d, expected 65 or 33 bytes", len(rawKey))
}
}
-98
View File
@@ -1,98 +0,0 @@
package spec
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"github.com/golang-jwt/jwt"
"github.com/onsonr/sonr/crypto/mpc"
)
// 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 := mpc.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 := mpc.ExecuteSigning(valSignFunc, signFunc)
if err != nil {
return "", fmt.Errorf("failed to run sign protocol: %w", err)
}
// Serialize the signature
sigBytes, err := mpc.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",
}
})
}
-143
View File
@@ -1,143 +0,0 @@
package store
import (
"context"
"fmt"
"sort"
"sync"
"github.com/golang-jwt/jwt"
"github.com/ipfs/go-cid"
"github.com/onsonr/sonr/crypto/ucan"
"github.com/onsonr/sonr/crypto/ucan/didkey"
"github.com/onsonr/sonr/pkg/common/ipfs"
)
type IPFSTokenStore interface {
ucan.TokenStore
ResolveCIDBytes(ctx context.Context, id cid.Cid) ([]byte, error)
ResolveDIDKey(ctx context.Context, did string) (didkey.ID, error)
}
// ipfsTokenStore is a token store that uses IPFS to store tokens. It uses the memory store as a cache
// for CID strings to be used as keys for retrieving tokens.
type ipfsTokenStore struct {
sync.Mutex
ipfs ipfs.Client
cache map[string]string
}
// NewIPFSTokenStore creates a new IPFS-backed token store
func NewIPFSTokenStore(ipfsClient ipfs.Client) IPFSTokenStore {
return &ipfsTokenStore{
ipfs: ipfsClient,
cache: make(map[string]string),
}
}
func (st *ipfsTokenStore) PutToken(ctx context.Context, key string, raw string) error {
// Validate token format
p := &jwt.Parser{
UseJSONNumber: true,
SkipClaimsValidation: false,
}
if _, _, err := p.ParseUnverified(raw, jwt.MapClaims{}); err != nil {
return fmt.Errorf("%w: %s", ucan.ErrInvalidToken, err)
}
// Store token in IPFS
cid, err := st.ipfs.Add([]byte(raw))
if err != nil {
return fmt.Errorf("failed to store token in IPFS: %w", err)
}
// Update cache
st.Lock()
defer st.Unlock()
st.cache[key] = cid
return nil
}
func (st *ipfsTokenStore) RawToken(ctx context.Context, key string) (string, error) {
st.Lock()
cid, exists := st.cache[key]
st.Unlock()
if !exists {
return "", ucan.ErrTokenNotFound
}
// Retrieve token from IPFS
data, err := st.ipfs.Get(cid)
if err != nil {
return "", fmt.Errorf("failed to retrieve token from IPFS: %w", err)
}
return string(data), nil
}
func (st *ipfsTokenStore) DeleteToken(ctx context.Context, key string) error {
st.Lock()
defer st.Unlock()
cid, exists := st.cache[key]
if !exists {
return ucan.ErrTokenNotFound
}
// Unpin from IPFS
if err := st.ipfs.Unpin(cid); err != nil {
return fmt.Errorf("failed to unpin token from IPFS: %w", err)
}
delete(st.cache, key)
return nil
}
func (st *ipfsTokenStore) ListTokens(ctx context.Context, offset, limit int) ([]ucan.RawToken, error) {
st.Lock()
defer st.Unlock()
tokens := make(ucan.RawTokens, 0, len(st.cache))
for key, cid := range st.cache {
data, err := st.ipfs.Get(cid)
if err != nil {
continue // Skip invalid tokens
}
tokens = append(tokens, ucan.RawToken{
Key: key,
Raw: string(data),
})
}
// Sort tokens
sort.Sort(tokens)
// Apply pagination
if offset >= len(tokens) {
return []ucan.RawToken{}, nil
}
end := offset + limit
if end > len(tokens) || limit <= 0 {
end = len(tokens)
}
return tokens[offset:end], nil
}
func (st *ipfsTokenStore) ResolveCIDBytes(ctx context.Context, id cid.Cid) ([]byte, error) {
data, err := st.ipfs.Get(id.String())
if err != nil {
return nil, fmt.Errorf("failed to resolve CID bytes: %w", err)
}
return data, nil
}
func (st *ipfsTokenStore) ResolveDIDKey(ctx context.Context, did string) (didkey.ID, error) {
id, err := didkey.Parse(did)
if err != nil {
return didkey.ID{}, fmt.Errorf("failed to parse DID: %w", err)
}
return id, nil
}
+11 -11
View File
@@ -21,7 +21,7 @@ import (
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p/core/crypto"
mh "github.com/multiformats/go-multihash"
"github.com/onsonr/sonr/crypto/ucan/didkey"
"github.com/onsonr/sonr/crypto/keys"
)
// ErrInvalidToken indicates an access token is invalid
@@ -47,8 +47,8 @@ const (
type Token struct {
// Entire UCAN as a signed JWT string
Raw string
Issuer didkey.ID
Audience didkey.ID
Issuer keys.DID
Audience keys.DID
// the "inputs" to this token, a chain UCAN tokens with broader scopes &
// deadlines than this token
Proofs []Proof `json:"prf,omitempty"`
@@ -261,12 +261,12 @@ func (a *pkSource) newToken(audienceDID string, prf []Proof, att Attenuations, f
// DIDPubKeyResolver turns did:key Decentralized IDentifiers into a public key,
// possibly using a network request
type DIDPubKeyResolver interface {
ResolveDIDKey(ctx context.Context, did string) (didkey.ID, error)
ResolveDIDKey(ctx context.Context, did string) (keys.DID, error)
}
// DIDStringFromPublicKey creates a did:key identifier string from a public key
func DIDStringFromPublicKey(pub crypto.PubKey) (string, error) {
id, err := didkey.NewID(pub)
id, err := keys.NewDID(pub)
if err != nil {
return "", err
}
@@ -279,8 +279,8 @@ func DIDStringFromPublicKey(pub crypto.PubKey) (string, error) {
type StringDIDPubKeyResolver struct{}
// ResolveDIDKey extracts a public key from a did:key string
func (StringDIDPubKeyResolver) ResolveDIDKey(ctx context.Context, didStr string) (didkey.ID, error) {
return didkey.Parse(didStr)
func (StringDIDPubKeyResolver) ResolveDIDKey(ctx context.Context, didStr string) (keys.DID, error) {
return keys.Parse(didStr)
}
// TokenParser parses a raw string into a Token
@@ -315,11 +315,11 @@ func (p *TokenParser) parseAndVerify(ctx context.Context, raw string, child *Tok
return nil, fmt.Errorf("parser fail")
}
var iss didkey.ID
var iss keys.DID
// TODO(b5): we're double parsing here b/c the jwt lib we're using doesn't expose
// an API (that I know of) for storing parsed issuer / audience
if issStr, ok := mc["iss"].(string); ok {
iss, err = didkey.Parse(issStr)
iss, err = keys.Parse(issStr)
if err != nil {
return nil, err
}
@@ -327,11 +327,11 @@ func (p *TokenParser) parseAndVerify(ctx context.Context, raw string, child *Tok
return nil, fmt.Errorf(`"iss" key is not in claims`)
}
var aud didkey.ID
var aud keys.DID
// TODO(b5): we're double parsing here b/c the jwt lib we're using doesn't expose
// an API (that I know of) for storing parsed issuer / audience
if audStr, ok := mc["aud"].(string); ok {
aud, err = didkey.Parse(audStr)
aud, err = keys.Parse(audStr)
if err != nil {
return nil, err
}