feature/1115 execute ucan token (#1177)

- **deps: remove tigerbeetle-go dependency**
- **refactor: remove unused landing page components and models**
- **feat: add pin and publish vault handlers**
- **refactor: move payment and credential services to webui browser
package**
- **refactor: remove unused credentials management components**
- **feat: add landing page components and middleware for credentials and
payments**
- **refactor: remove unused imports in vault config**
- **refactor: remove unused bank, DID, and DWN gRPC clients**
- **refactor: rename client files and improve code structure**
- **feat: add session middleware helpers and landing page components**
- **feat: add user profile registration flow**
- **feat: Implement WebAuthn registration flow**
- **feat: add error view for users without WebAuthn devices**
- **chore: update htmx to include extensions**
- **refactor: rename pin handler to claim handler and update routes**
- **chore: update import paths after moving UI components and styles**
- **fix: address potential server errors by handling and logging them
properly**
- **refactor: move vault config to gateway package and update related
dependencies**
- **style: simplify form styling and remove unnecessary components**
- **feat: improve UI design for registration flow**
- **feat: implement passkey-based authentication**
- **refactor: migrate registration forms to use reusable form
components**
- **refactor: remove tailwindcss setup and use CDN instead**
- **style: update submit button style to use outline variant**
- **refactor: refactor server and IPFS client, remove MPC encryption**
- **refactor: Abstract keyshare functionality and improve message
encoding**
- **refactor: improve keyset JSON marshaling and error handling**
- **feat: add support for digital signatures using MPC keys**
- **fix: Refactor MarshalJSON to use standard json.Marshal for Message
serialization**
- **fix: Encode messages before storing in keyshare structs**
- **style: update form input styles for improved user experience**
- **refactor: improve code structure in registration handlers**
- **refactor: consolidate signer middleware and IPFS interaction**
- **refactor: rename MPC signing and refresh protocol functions**
- **refactor: update hway configuration loading mechanism**
- **feat: integrate database support for sessions and users**
- **refactor: remove devnet infrastructure and simplify build process**
- **docs(guides): add Sonr DID module guide**
- **feat: integrate progress bar into registration form**
- **refactor: migrate WebAuthn dependencies to protocol package**
- **feat: enhance user registration with passkey integration and
improved form styling**
- **refactor: move gateway view handlers to internal pages package**
- **refactor: Move address package to MPC module**
- **feat: integrate turnstile for registration**
- **style: remove unnecessary size attribute from buttons**
- **refactor: rename cookie package to session/cookie**
- **refactor: remove unnecessary types.Session dependency**
- **refactor: rename pkg/core to pkg/chain**
- **refactor: simplify deployment process by removing testnet-specific
Taskfile and devbox configuration**
- **feat: add error redirect functionality and improve routes**
- **feat: implement custom error handling for gateway**
- **chore: update version number to 0.0.7 in template**
- **feat: add IPFS client implementation**
- **feat: Implement full IPFS client interface with comprehensive
methods**
- **refactor: improve IPFS client path handling**
- **refactor: Move UCAN middleware to controller package**
- **feat: add UCAN middleware to motr**
- **refactor: update libp2p dependency**
- **docs: add UCAN specification document**
- **refactor: move UCAN controller logic to common package**
- **refactor: rename exports.go to common.go**
- **feat: add UCAN token support**
- **refactor: migrate UCAN token parsing to dedicated package**
- **refactor: improve CometBFT and app config initialization**
- **refactor: improve deployment scripts and documentation**
- **feat: integrate IPFS and producer middleware**
- **refactor: rename agent directory to aider**
- **fix: correct libp2p import path**
- **refactor: remove redundant dependency**
- **cleanup: remove unnecessary test files**
- **refactor: move attention types to crypto/ucan package**
- **feat: expand capabilities and resource types for UCANs**
- **refactor: rename sonr.go to codec.go and update related imports**
- **feat: add IPFS-based token store**
- **feat: Implement IPFS-based token store with caching and UCAN
integration**
- **feat: Add dynamic attenuation constructor for UCAN presets**
- **fix: Handle missing or invalid attenuation data with
EmptyAttenuation**
- **fix: Update UCAN attenuation tests with correct capability types**
- **feat: integrate UCAN-based authorization into the producer
middleware**
- **refactor: remove unused dependency on go-ucan**
- **refactor: Move address handling logic to DID module**
- **feat: Add support for compressed and uncompressed Secp256k1 public
keys in didkey**
- **test: Add test for generating DID key from MPC keyshares**
- **feat: Add methods for extracting compressed and uncompressed public
keys in share types**
- **feat: Add BaseKeyshare struct with public key conversion methods**
- **refactor: Use compressed and uncompressed public keys in keyshare,
fix public key usage in tests and verification**
- **feat: add support for key generation policy type**
- **fix: correct typo in VaultPermissions constant**
- **refactor: move JWT related code to ucan package**
- **refactor: move UCAN JWT and source code to spec package**
This commit is contained in:
Prad Nukala
2024-12-05 20:36:58 -05:00
committed by GitHub
parent e62ec45e82
commit bd51342fdf
256 changed files with 10823 additions and 7096 deletions
-90
View File
@@ -1,90 +0,0 @@
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
}
-97
View File
@@ -1,97 +0,0 @@
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",
}
})
}
+11 -6
View File
@@ -6,8 +6,6 @@ import (
"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"
@@ -15,14 +13,13 @@ import (
type (
ExportedKeyset = []byte
IPFSClient = *rpc.HttpApi
File = files.File
)
type Keyset interface {
Val() *ValKeyshare
ValJSON() string
User() *UserKeyshare
Export(client IPFSClient, secret []byte) (ExportedKeyset, error)
UserJSON() string
}
type keyset struct {
@@ -38,6 +35,14 @@ 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 {
@@ -55,7 +60,7 @@ func ComputeSonrAddr(pk []byte) (string, error) {
}
// For DKG bob starts first. For refresh and sign, Alice starts first.
func runIteratedProtocol(firstParty protocol.Iterator, secondParty protocol.Iterator) (error, error) {
func RunProtocol(firstParty protocol.Iterator, secondParty protocol.Iterator) (error, error) {
var (
message *protocol.Message
aErr error
+67
View File
@@ -0,0 +1,67 @@
package mpc
import (
"crypto/ecdsa"
"github.com/onsonr/sonr/crypto/core/protocol"
)
// Keyshare represents the common interface for both validator and user keyshares
type Keyshare interface {
GetPayloads() map[string][]byte
GetMetadata() map[string]string
GetPublicKey() []byte
GetProtocol() string
GetRole() int32
GetVersion() uint32
ECDSAPublicKey() (*ecdsa.PublicKey, error)
ExtractMessage() *protocol.Message
RefreshFunc() (RefreshFunc, error)
SignFunc(msg []byte) (SignFunc, error)
Marshal() (string, error)
}
// 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 (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()),
}
}
+7 -7
View File
@@ -15,7 +15,7 @@ func NewKeyset() (Keyset, error) {
curve := curves.K256()
valKs := dklsv1.NewAliceDkg(curve, protocol.Version1)
userKs := dklsv1.NewBobDkg(curve, protocol.Version1)
aErr, bErr := runIteratedProtocol(userKs, valKs)
aErr, bErr := RunProtocol(userKs, valKs)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
}
@@ -38,9 +38,9 @@ func NewKeyset() (Keyset, error) {
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)
// ExecuteSigning runs the MPC signing protocol
func ExecuteSigning(signFuncVal SignFunc, signFuncUser SignFunc) (Signature, error) {
aErr, bErr := RunProtocol(signFuncVal, signFuncUser)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
}
@@ -51,9 +51,9 @@ func RunSignProtocol(signFuncVal SignFunc, signFuncUser SignFunc) (Signature, er
return dklsv1.DecodeSignature(out)
}
// RunRefreshProtocol runs the MPC refresh protocol
func RunRefreshProtocol(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc) (Keyset, error) {
aErr, bErr := runIteratedProtocol(refreshFuncVal, refreshFuncUser)
// ExecuteRefresh runs the MPC refresh protocol
func ExecuteRefresh(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc) (Keyset, error) {
aErr, bErr := RunProtocol(refreshFuncVal, refreshFuncUser)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
}
-70
View File
@@ -1,70 +0,0 @@
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,
}
}
+60 -98
View File
@@ -1,8 +1,6 @@
package mpc
import (
"crypto/ecdsa"
"encoding/json"
"errors"
"github.com/onsonr/sonr/crypto/core/curves"
@@ -45,60 +43,30 @@ type SignFunc interface {
}
type ValKeyshare struct {
Message Message `json:"message"`
Role int `json:"role"` // 1 for validator, 2 for user
PublicKey []byte `json:"public-key"`
BaseKeyshare
encoded string
}
func NewValKeyshare(msg Message) (*ValKeyshare, error) {
func NewValKeyshare(msg *protocol.Message) (*ValKeyshare, error) {
encoded, err := protocol.EncodeMessage(msg)
if err != nil {
return nil, err
}
valShare, err := dklsv1.DecodeAliceDkgResult(msg)
if err != nil {
return nil, err
}
return &ValKeyshare{
Message: msg,
Role: 1,
PublicKey: valShare.PublicKey.ToAffineUncompressed(),
BaseKeyshare: BaseKeyshare{
Message: msg,
Role: 1,
UncompressedPubKey: valShare.PublicKey.ToAffineUncompressed(),
CompressedPubKey: valShare.PublicKey.ToAffineCompressed(),
},
encoded: encoded,
}, 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)
@@ -109,65 +77,45 @@ func (v *ValKeyshare) SignFunc(msg []byte) (SignFunc, error) {
return dklsv1.NewAliceSign(curve, sha3.New256(), msg, v.ExtractMessage(), protocol.Version1)
}
func (v *ValKeyshare) Marshal() ([]byte, error) {
return json.Marshal(v.Message)
func (v *ValKeyshare) String() string {
return v.encoded
}
// PublicKey returns the uncompressed public key (65 bytes)
func (v *ValKeyshare) PublicKey() []byte {
return v.BaseKeyshare.UncompressedPubKey
}
// CompressedPublicKey returns the compressed public key (33 bytes)
func (v *ValKeyshare) CompressedPublicKey() []byte {
return v.BaseKeyshare.CompressedPubKey
}
type UserKeyshare struct {
Message Message `json:"message"` // BobOutput
Role int `json:"role"` // 2 for user, 1 for validator
PublicKey []byte `json:"public-key"`
BaseKeyshare
encoded string
}
func NewUserKeyshare(msg Message) (*UserKeyshare, error) {
func NewUserKeyshare(msg *protocol.Message) (*UserKeyshare, error) {
encoded, err := protocol.EncodeMessage(msg)
if err != nil {
return nil, err
}
out, err := dklsv1.DecodeBobDkgResult(msg)
if err != nil {
return nil, err
}
return &UserKeyshare{
Message: msg,
Role: 2,
PublicKey: out.PublicKey.ToAffineUncompressed(),
BaseKeyshare: BaseKeyshare{
Message: msg,
Role: 2,
UncompressedPubKey: out.PublicKey.ToAffineUncompressed(),
CompressedPubKey: out.PublicKey.ToAffineCompressed(),
},
encoded: encoded,
}, 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)
@@ -178,10 +126,24 @@ func (u *UserKeyshare) SignFunc(msg []byte) (SignFunc, error) {
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
func (u *UserKeyshare) String() string {
return u.encoded
}
// PublicKey returns the uncompressed public key (65 bytes)
func (u *UserKeyshare) PublicKey() []byte {
return u.BaseKeyshare.UncompressedPubKey
}
// CompressedPublicKey returns the compressed public key (33 bytes)
func (u *UserKeyshare) CompressedPublicKey() []byte {
return u.BaseKeyshare.CompressedPubKey
}
func encodeMessage(m *protocol.Message) (string, error) {
return protocol.EncodeMessage(m)
}
func decodeMessage(s string) (*protocol.Message, error) {
return protocol.DecodeMessage(s)
}
-138
View File
@@ -1,138 +0,0 @@
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)
}
-95
View File
@@ -1,95 +0,0 @@
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
}