refactor: remove unnecessary proxy config

This commit is contained in:
Prad Nukala
2024-09-26 13:52:03 -04:00
parent 6aacee387f
commit a190e1eac6
37 changed files with 298 additions and 353 deletions
+1 -1
View File
@@ -301,7 +301,7 @@ sh-testnet: mod-tidy
dwn: dwn:
@echo "(dwn) Building dwn.wasm -> IPFS Vault" @echo "(dwn) Building dwn.wasm -> IPFS Vault"
GOOS=js GOARCH=wasm go build -o ./x/vault/internal/app.wasm ./x/vault/client/htmx/dwn.go GOOS=js GOARCH=wasm go build -o ./x/vault/types/internal/app.wasm ./x/vault/client/dwn/dwn.go
templ: templ:
@echo "(templ) Generating templ files" @echo "(templ) Generating templ files"
+4 -4
View File
@@ -810,7 +810,7 @@ func (x *fastReflection_Params) ProtoMethods() *protoiface.Methods {
copy(dAtA[i:], encoded) copy(dAtA[i:], encoded)
i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded))) i = runtime.EncodeVarint(dAtA, i, uint64(len(encoded)))
i-- i--
dAtA[i] = 0x1a dAtA[i] = 0x22
} }
if x.LocalRegistrationEnabled { if x.LocalRegistrationEnabled {
i-- i--
@@ -921,7 +921,7 @@ func (x *fastReflection_Params) ProtoMethods() *protoiface.Methods {
} }
} }
x.LocalRegistrationEnabled = bool(v != 0) x.LocalRegistrationEnabled = bool(v != 0)
case 3: case 4:
if wireType != 2 { if wireType != 2 {
return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType) return protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType)
} }
@@ -2030,7 +2030,7 @@ type Params struct {
IpfsActive bool `protobuf:"varint,1,opt,name=ipfs_active,json=ipfsActive,proto3" json:"ipfs_active,omitempty"` IpfsActive bool `protobuf:"varint,1,opt,name=ipfs_active,json=ipfsActive,proto3" json:"ipfs_active,omitempty"`
LocalRegistrationEnabled bool `protobuf:"varint,2,opt,name=local_registration_enabled,json=localRegistrationEnabled,proto3" json:"local_registration_enabled,omitempty"` LocalRegistrationEnabled bool `protobuf:"varint,2,opt,name=local_registration_enabled,json=localRegistrationEnabled,proto3" json:"local_registration_enabled,omitempty"`
Schema *Schema `protobuf:"bytes,3,opt,name=schema,proto3" json:"schema,omitempty"` Schema *Schema `protobuf:"bytes,4,opt,name=schema,proto3" json:"schema,omitempty"`
} }
func (x *Params) Reset() { func (x *Params) Reset() {
@@ -2200,7 +2200,7 @@ var file_vault_v1_genesis_proto_rawDesc = []byte{
0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x18, 0x6c, 0x6f, 0x63, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x18, 0x6c, 0x6f, 0x63,
0x61, 0x6c, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x61, 0x6c, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e,
0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x28, 0x0a, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x18, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x28, 0x0a, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x18,
0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x76, 0x61, 0x75, 0x6c, 0x74, 0x2e, 0x76, 0x31, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x76, 0x61, 0x75, 0x6c, 0x74, 0x2e, 0x76, 0x31,
0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x52, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x3a, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x52, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x3a,
0x19, 0x98, 0xa0, 0x1f, 0x00, 0xe8, 0xa0, 0x1f, 0x01, 0x8a, 0xe7, 0xb0, 0x2a, 0x0c, 0x76, 0x61, 0x19, 0x98, 0xa0, 0x1f, 0x00, 0xe8, 0xa0, 0x1f, 0x01, 0x8a, 0xe7, 0xb0, 0x2a, 0x0c, 0x76, 0x61,
0x75, 0x6c, 0x74, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x84, 0x02, 0x0a, 0x06, 0x53, 0x75, 0x6c, 0x74, 0x2f, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x84, 0x02, 0x0a, 0x06, 0x53,
-22
View File
@@ -1,22 +0,0 @@
package proxy
import (
"github.com/spf13/cobra"
)
func NewProxyCmd() *cobra.Command {
return &cobra.Command{
Use: "dwn-proxy",
Short: "Starts the DWN proxy server for the local IPFS node",
RunE: func(cmd *cobra.Command, args []string) error {
// Load config
// c, err := LoadConfig(".")
// if err != nil {
// return err
// }
// log.Printf("Config: %+v", c)
startServer()
return nil
},
}
}
-28
View File
@@ -1,28 +0,0 @@
package proxy
import "github.com/spf13/viper"
type Config struct {
Host string `mapstructure:"HOST"`
Port string `mapstructure:"PORT"`
}
func (c *Config) GetHostname() string {
return c.Host + ":" + c.Port
}
func LoadConfig(path string) (config Config, err error) {
viper.AddConfigPath(path)
viper.SetConfigName("app")
viper.SetConfigType("env")
viper.AutomaticEnv()
err = viper.ReadInConfig()
if err != nil {
return
}
err = viper.Unmarshal(&config)
return
}
+52
View File
@@ -0,0 +1,52 @@
package proxy
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
"github.com/onsonr/sonr/nebula"
"github.com/onsonr/sonr/nebula/pages"
"github.com/spf13/cobra"
)
func NewProxyCmd() *cobra.Command {
return &cobra.Command{
Use: "dwn-proxy",
Short: "Starts the DWN proxy server for the local IPFS node",
Run: func(cmd *cobra.Command, args []string) {
// Echo instance
e := echo.New()
e.Logger.SetLevel(log.INFO)
// Configure the server
nebula.UseAssets(e)
e.GET("/", pages.Home)
e.GET("/allocate", pages.Profile)
// Start server
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
// Start server
go func() {
if err := e.Start(":1323"); err != nil && err != http.ErrServerClosed {
e.Logger.Fatal("shutting down the server")
}
}()
// Wait for interrupt signal to gracefully shutdown the server with a timeout of 10 seconds.
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Shutdown the server with 10 seconds timeout.
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
},
}
}
-45
View File
@@ -1,45 +0,0 @@
package proxy
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
"github.com/onsonr/sonr/nebula"
"github.com/onsonr/sonr/nebula/pages"
)
func startServer() {
// Echo instance
e := echo.New()
e.Logger.SetLevel(log.INFO)
// Configure the server
nebula.UseAssets(e)
e.GET("/", pages.Home)
e.GET("/allocate", pages.Profile)
// Start server
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
// Start server
go func() {
if err := e.Start(":1323"); err != nil && err != http.ErrServerClosed {
e.Logger.Fatal("shutting down the server")
}
}()
// Wait for interrupt signal to gracefully shutdown the server with a timeout of 10 seconds.
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Shutdown the server with 10 seconds timeout.
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
}
BIN
View File
Binary file not shown.
+1
View File
@@ -13,6 +13,7 @@
"typescript": "^4.9.0" "typescript": "^4.9.0"
}, },
"dependencies": { "dependencies": {
"@tailwindcss/typography": "^0.5.15",
"alpinejs": "^3.14.1", "alpinejs": "^3.14.1",
"htmx.org": "^1.9.12", "htmx.org": "^1.9.12",
"node-fetch": "^3.3.2" "node-fetch": "^3.3.2"
+1 -1
View File
@@ -8,5 +8,5 @@ module.exports = {
theme: { theme: {
extend: {}, extend: {},
}, },
plugins: [], plugins: [require("@tailwindcss/typography")],
}; };
+1 -1
View File
@@ -20,7 +20,7 @@ message Params {
bool ipfs_active = 1; bool ipfs_active = 1;
bool local_registration_enabled = 2; bool local_registration_enabled = 2;
Schema schema = 3; Schema schema = 4;
} }
message Schema { message Schema {
-27
View File
@@ -1,27 +0,0 @@
package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/onsonr/crypto/mpc"
"github.com/onsonr/sonr/x/did/types"
)
func (k Keeper) NewController(ctx sdk.Context) (uint64, types.ControllerI, error) {
shares, err := mpc.GenerateKeyshares()
if err != nil {
return 0, nil, err
}
controller, err := types.NewController(shares)
if err != nil {
return 0, nil, err
}
entry, err := controller.GetTableEntry()
if err != nil {
return 0, nil, err
}
num, err := k.OrmDB.ControllerTable().InsertReturningNumber(ctx, entry)
if err != nil {
return 0, nil, err
}
return num, controller, nil
}
+46
View File
@@ -1,18 +1,24 @@
package keeper package keeper
import ( import (
"crypto/sha256"
"fmt"
"cosmossdk.io/collections" "cosmossdk.io/collections"
storetypes "cosmossdk.io/core/store" storetypes "cosmossdk.io/core/store"
"cosmossdk.io/log" "cosmossdk.io/log"
"cosmossdk.io/orm/model/ormdb" "cosmossdk.io/orm/model/ormdb"
nftkeeper "cosmossdk.io/x/nft/keeper" nftkeeper "cosmossdk.io/x/nft/keeper"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"gopkg.in/macaroon.v2"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
stakkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/onsonr/crypto/mpc"
apiv1 "github.com/onsonr/sonr/api/did/v1" apiv1 "github.com/onsonr/sonr/api/did/v1"
"github.com/onsonr/sonr/x/did/types" "github.com/onsonr/sonr/x/did/types"
) )
@@ -86,3 +92,43 @@ func NewKeeper(
k.Schema = schema k.Schema = schema
return k return k
} }
func (k Keeper) NewController(ctx sdk.Context) (uint64, types.ControllerI, error) {
shares, err := mpc.GenerateKeyshares()
if err != nil {
return 0, nil, err
}
controller, err := types.NewController(shares)
if err != nil {
return 0, nil, err
}
entry, err := controller.GetTableEntry()
if err != nil {
return 0, nil, err
}
num, err := k.OrmDB.ControllerTable().InsertReturningNumber(ctx, entry)
if err != nil {
return 0, nil, err
}
return num, controller, nil
}
// IssueMacaroon creates a macaroon with the specified parameters.
func (k Keeper) IssueMacaroon(ctx sdk.Context, sharedMPCPubKey, location, id string, blockExpiry uint64) (*macaroon.Macaroon, error) {
// Derive the root key by hashing the shared MPC public key
rootKey := sha256.Sum256([]byte(sharedMPCPubKey))
// Create the macaroon
m, err := macaroon.New(rootKey[:], []byte(id), location, macaroon.LatestVersion)
if err != nil {
return nil, err
}
// Add the block expiry caveat
caveat := fmt.Sprintf("block-expiry=%d", blockExpiry)
err = m.AddFirstPartyCaveat([]byte(caveat))
if err != nil {
return nil, err
}
return m, nil
}
-29
View File
@@ -1,29 +0,0 @@
package keeper
import (
"crypto/sha256"
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"gopkg.in/macaroon.v2"
)
// IssueMacaroon creates a macaroon with the specified parameters.
func (k Keeper) IssueMacaroon(ctx sdk.Context, sharedMPCPubKey, location, id string, blockExpiry uint64) (*macaroon.Macaroon, error) {
// Derive the root key by hashing the shared MPC public key
rootKey := sha256.Sum256([]byte(sharedMPCPubKey))
// Create the macaroon
m, err := macaroon.New(rootKey[:], []byte(id), location, macaroon.LatestVersion)
if err != nil {
return nil, err
}
// Add the block expiry caveat
caveat := fmt.Sprintf("block-expiry=%d", blockExpiry)
err = m.AddFirstPartyCaveat([]byte(caveat))
if err != nil {
return nil, err
}
return m, nil
}
@@ -15,20 +15,35 @@ import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
promise "github.com/nlepage/go-js-promise" promise "github.com/nlepage/go-js-promise"
"github.com/onsonr/sonr/nebula/pages" "github.com/onsonr/sonr/nebula/pages"
"github.com/onsonr/sonr/x/vault/client/htmx/middleware" "github.com/onsonr/sonr/x/vault/client/dwn/middleware"
"github.com/onsonr/sonr/x/vault/client/htmx/state" "github.com/onsonr/sonr/x/vault/client/dwn/state"
) )
func main() { func main() {
e := echo.New() e := echo.New()
e.Use(middleware.UseSession) e.Use(middleware.UseSession)
registerViews(e)
registerState(e)
Serve(e)
}
func registerState(e *echo.Echo) {
g := e.Group("state")
g.POST("/login/:identifier", state.HandleCredentialAssertion)
// g.GET("/discovery", state.GetDiscovery)
g.GET("/jwks", state.GetJWKS)
g.GET("/token", state.GetToken)
g.POST("/:origin/grant/:subject", state.GrantAuthorization)
g.POST("/register/:subject", state.HandleCredentialCreation)
g.POST("/register/:subject/check", state.CheckSubjectIsValid)
}
func registerViews(e *echo.Echo) {
e.GET("/home", pages.Home) e.GET("/home", pages.Home)
e.GET("/login", pages.Login) e.GET("/login", pages.Login)
e.GET("/register", pages.Register) e.GET("/register", pages.Register)
e.GET("/profile", pages.Profile) e.GET("/profile", pages.Profile)
e.GET("/authorize", pages.Authorize) e.GET("/authorize", pages.Authorize)
state.RegisterHandlers(e)
Serve(e)
} }
// Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil. // Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil.
@@ -8,16 +8,16 @@ import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
) )
func checkSubjectIsValid(e echo.Context) error { func CheckSubjectIsValid(e echo.Context) error {
credentialID := e.FormValue("credentialID") credentialID := e.FormValue("credentialID")
return e.JSON(200, credentialID) return e.JSON(200, credentialID)
} }
func handleCredentialAssertion(e echo.Context) error { func HandleCredentialAssertion(e echo.Context) error {
return e.JSON(200, "HandleCredentialAssertion") return e.JSON(200, "HandleCredentialAssertion")
} }
func handleCredentialCreation(e echo.Context) error { func HandleCredentialCreation(e echo.Context) error {
// Get the serialized credential data from the form // Get the serialized credential data from the form
credentialDataJSON := e.FormValue("credentialData") credentialDataJSON := e.FormValue("credentialData")
@@ -4,19 +4,19 @@ import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
) )
func grantAuthorization(e echo.Context) error { func GrantAuthorization(e echo.Context) error {
// Implement authorization endpoint using passkey authentication // Implement authorization endpoint using passkey authentication
// Store session data in cache // Store session data in cache
return nil return nil
} }
func getJWKS(e echo.Context) error { func GetJWKS(e echo.Context) error {
// Implement token endpoint // Implement token endpoint
// Use cached session data for validation // Use cached session data for validation
return nil return nil
} }
func getToken(e echo.Context) error { func GetToken(e echo.Context) error {
// Implement token endpoint // Implement token endpoint
// Use cached session data for validation // Use cached session data for validation
return nil return nil
-16
View File
@@ -1,16 +0,0 @@
package state
import (
"github.com/labstack/echo/v4"
)
func RegisterHandlers(e *echo.Echo) {
g := e.Group("state")
g.POST("/login/:identifier", handleCredentialAssertion)
// g.GET("/discovery", state.GetDiscovery)
g.GET("/jwks", getJWKS)
g.GET("/token", getToken)
g.POST("/:origin/grant/:subject", grantAuthorization)
g.POST("/register/:subject", handleCredentialCreation)
g.POST("/register/:subject/check", checkSubjectIsValid)
}
-1
View File
@@ -1 +0,0 @@
package state
-59
View File
@@ -1,59 +0,0 @@
package keeper
import (
"context"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/onsonr/sonr/config/dwn"
vault "github.com/onsonr/sonr/x/vault/internal"
"github.com/onsonr/sonr/x/vault/types"
)
// AssembleVault assembles the initial vault
func (k Keeper) AssembleVault(ctx sdk.Context, subject string, origin string) (string, int64, error) {
_, con, err := k.DIDKeeper.NewController(ctx)
if err != nil {
return "", 0, err
}
usrKs, err := con.ExportUserKs()
if err != nil {
return "", 0, err
}
sch, err := k.CurrentSchema(ctx)
if err != nil {
return "", 0, err
}
cnfg := vault.NewConfig(usrKs, con.SonrAddress(), con.ChainID(), sch)
v, err := types.NewVault(cnfg, "sonr-testnet")
if err != nil {
return "", 0, err
}
cid, err := k.ipfsClient.Unixfs().Add(context.Background(), v.FS)
if err != nil {
return "", 0, err
}
return cid.String(), k.CalculateExpiration(ctx, time.Second*15), nil
}
// CurrentSchema returns the current schema
func (k Keeper) CurrentSchema(ctx sdk.Context) (*dwn.Schema, error) {
p, err := k.Params.Get(ctx)
if err != nil {
return nil, err
}
schema := p.Schema
return &dwn.Schema{
Version: int(schema.Version),
Account: schema.Account,
Asset: schema.Asset,
Chain: schema.Chain,
Credential: schema.Credential,
Jwk: schema.Jwk,
Grant: schema.Grant,
Keyshare: schema.Keyshare,
PublicKey: schema.PublicKey,
Profile: schema.Profile,
}, nil
}
+81
View File
@@ -0,0 +1,81 @@
package keeper
import (
"context"
"time"
"cosmossdk.io/log"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ipfs/boxo/path"
"github.com/ipfs/kubo/client/rpc"
"github.com/onsonr/sonr/x/vault/types"
)
func (k Keeper) Logger() log.Logger {
return k.logger
}
// InitGenesis initializes the module's state from a genesis state.
func (k *Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) error {
// this line is used by starport scaffolding # genesis/module/init
if err := data.Params.Validate(); err != nil {
return err
}
return k.Params.Set(ctx, data.Params)
}
// ExportGenesis exports the module's state to a genesis state.
func (k *Keeper) ExportGenesis(ctx context.Context) *types.GenesisState {
params, err := k.Params.Get(ctx)
if err != nil {
panic(err)
}
// this line is used by starport scaffolding # genesis/module/export
return &types.GenesisState{
Params: params,
}
}
// IPFSConnected returns true if the IPFS client is initialized
func (c Keeper) IPFSConnected() bool {
if c.ipfsClient == nil {
ipfsClient, err := rpc.NewLocalApi()
if err != nil {
return false
}
c.ipfsClient = ipfsClient
}
return c.ipfsClient != nil
}
// CalculateExpiration calculates the expiration time for a vault
func (k Keeper) CalculateExpiration(c sdk.Context, duration time.Duration) int64 {
blockTime := c.BlockTime()
avgBlockTime := float64(blockTime.Sub(blockTime).Seconds())
return int64(duration.Seconds() / avgBlockTime)
}
// HasPathInIPFS checks if a file is in the local IPFS node
func (k Keeper) HasPathInIPFS(ctx sdk.Context, cid string) (bool, error) {
path, err := path.NewPath(cid)
if err != nil {
return false, err
}
v, err := k.ipfsClient.Unixfs().Get(ctx, path)
if err != nil {
return false, err
}
if v == nil {
return false, nil
}
return true, nil
}
// validateSubjectOrigin checks if the subject and origin are valid
func (k Keeper) validateSubjectOrigin(ctx sdk.Context, subject string, origin string) error {
return nil
}
+35 -53
View File
@@ -15,9 +15,9 @@ import (
"cosmossdk.io/log" "cosmossdk.io/log"
"cosmossdk.io/orm/model/ormdb" "cosmossdk.io/orm/model/ormdb"
"github.com/ipfs/boxo/path"
"github.com/ipfs/kubo/client/rpc" "github.com/ipfs/kubo/client/rpc"
apiv1 "github.com/onsonr/sonr/api/vault/v1" apiv1 "github.com/onsonr/sonr/api/vault/v1"
"github.com/onsonr/sonr/config/dwn"
"github.com/onsonr/sonr/x/vault/types" "github.com/onsonr/sonr/x/vault/types"
@@ -89,66 +89,48 @@ func NewKeeper(
return k return k
} }
func (k Keeper) Logger() log.Logger { // currentSchema returns the current schema
return k.logger func (k Keeper) CurrentSchema(ctx sdk.Context) (*dwn.Schema, error) {
} p, err := k.Params.Get(ctx)
// InitGenesis initializes the module's state from a genesis state.
func (k *Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) error {
// this line is used by starport scaffolding # genesis/module/init
if err := data.Params.Validate(); err != nil {
return err
}
return k.Params.Set(ctx, data.Params)
}
// ExportGenesis exports the module's state to a genesis state.
func (k *Keeper) ExportGenesis(ctx context.Context) *types.GenesisState {
params, err := k.Params.Get(ctx)
if err != nil { if err != nil {
panic(err) return nil, err
}
schema := p.Schema
return &dwn.Schema{
Version: int(schema.Version),
Account: schema.Account,
Asset: schema.Asset,
Chain: schema.Chain,
Credential: schema.Credential,
Jwk: schema.Jwk,
Grant: schema.Grant,
Keyshare: schema.Keyshare,
PublicKey: schema.PublicKey,
Profile: schema.Profile,
}, nil
} }
// this line is used by starport scaffolding # genesis/module/export // assembleVault assembles the initial vault
func (k Keeper) AssembleVault(ctx sdk.Context) (string, int64, error) {
return &types.GenesisState{ _, con, err := k.DIDKeeper.NewController(ctx)
Params: params,
}
}
// IPFSConnected returns true if the IPFS client is initialized
func (c Keeper) IPFSConnected() bool {
if c.ipfsClient == nil {
ipfsClient, err := rpc.NewLocalApi()
if err != nil { if err != nil {
return false return "", 0, err
} }
c.ipfsClient = ipfsClient usrKs, err := con.ExportUserKs()
}
return c.ipfsClient != nil
}
// CalculateExpiration calculates the expiration time for a vault
func (k Keeper) CalculateExpiration(c sdk.Context, duration time.Duration) int64 {
blockTime := c.BlockTime()
avgBlockTime := float64(blockTime.Sub(blockTime).Seconds())
return int64(duration.Seconds() / avgBlockTime)
}
// HasPathInIPFS checks if a file is in the local IPFS node
func (k Keeper) HasPathInIPFS(ctx sdk.Context, cid string) (bool, error) {
path, err := path.NewPath(cid)
if err != nil { if err != nil {
return false, err return "", 0, err
} }
v, err := k.ipfsClient.Unixfs().Get(ctx, path) sch, err := k.CurrentSchema(ctx)
if err != nil { if err != nil {
return false, err return "", 0, err
} }
v, err := types.NewVault(usrKs, con.SonrAddress(), con.ChainID(), sch)
if v == nil { if err != nil {
return false, nil return "", 0, err
} }
return true, nil cid, err := k.ipfsClient.Unixfs().Add(context.Background(), v.FS)
if err != nil {
return "", 0, err
}
return cid.String(), k.CalculateExpiration(ctx, time.Second*15), nil
} }
@@ -34,8 +34,8 @@ func (ms msgServer) AllocateVault(goCtx context.Context, msg *types.MsgAllocateV
// 1.Check if the service origin is valid // 1.Check if the service origin is valid
ctx := sdk.UnwrapSDKContext(goCtx) ctx := sdk.UnwrapSDKContext(goCtx)
// 2.Allocate the vault // 2.Allocate the vault msg.GetSubject(), msg.GetOrigin()
cid, expiryBlock, err := ms.k.AssembleVault(ctx, msg.GetSubject(), msg.GetOrigin()) cid, expiryBlock, err := ms.k.AssembleVault(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+6 -6
View File
@@ -74,7 +74,7 @@ func (m *GenesisState) GetParams() Params {
type Params struct { type Params struct {
IpfsActive bool `protobuf:"varint,1,opt,name=ipfs_active,json=ipfsActive,proto3" json:"ipfs_active,omitempty"` IpfsActive bool `protobuf:"varint,1,opt,name=ipfs_active,json=ipfsActive,proto3" json:"ipfs_active,omitempty"`
LocalRegistrationEnabled bool `protobuf:"varint,2,opt,name=local_registration_enabled,json=localRegistrationEnabled,proto3" json:"local_registration_enabled,omitempty"` LocalRegistrationEnabled bool `protobuf:"varint,2,opt,name=local_registration_enabled,json=localRegistrationEnabled,proto3" json:"local_registration_enabled,omitempty"`
Schema *Schema `protobuf:"bytes,3,opt,name=schema,proto3" json:"schema,omitempty"` Schema *Schema `protobuf:"bytes,4,opt,name=schema,proto3" json:"schema,omitempty"`
} }
func (m *Params) Reset() { *m = Params{} } func (m *Params) Reset() { *m = Params{} }
@@ -270,11 +270,11 @@ var fileDescriptor_4c971b352fb6cc17 = []byte{
0xfa, 0xd2, 0x8d, 0x85, 0xf4, 0xaa, 0x41, 0xfa, 0xbe, 0x5f, 0x40, 0x8b, 0x5e, 0x12, 0x61, 0x2f, 0xfa, 0xd2, 0x8d, 0x85, 0xf4, 0xaa, 0x41, 0xfa, 0xbe, 0x5f, 0x40, 0x8b, 0x5e, 0x12, 0x61, 0x2f,
0x60, 0x58, 0x19, 0x29, 0xaa, 0xb1, 0xc5, 0x52, 0x39, 0x6f, 0x85, 0x57, 0x46, 0x8f, 0x51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 0xcb, 0x8d, 0x76, 0x46, 0xdb, 0x9c, 0x8e, 0x8f, 0x79,
0x78, 0x47, 0xbf, 0xa8, 0xd1, 0x4d, 0x12, 0xfa, 0x79, 0x9e, 0xfd, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x78, 0x47, 0xbf, 0xa8, 0xd1, 0x4d, 0x12, 0xfa, 0x79, 0x9e, 0xfd, 0x0d, 0x00, 0x00, 0xff, 0xff,
0xed, 0xdc, 0x3c, 0x7d, 0x89, 0x02, 0x00, 0x00, 0x57, 0x11, 0x84, 0xf3, 0x89, 0x02, 0x00, 0x00,
} }
func (this *Params) Equal(that interface{}) bool { func (this *Params) Equal(that interface{}) bool {
@@ -379,7 +379,7 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i = encodeVarintGenesis(dAtA, i, uint64(size)) i = encodeVarintGenesis(dAtA, i, uint64(size))
} }
i-- i--
dAtA[i] = 0x1a dAtA[i] = 0x22
} }
if m.LocalRegistrationEnabled { if m.LocalRegistrationEnabled {
i-- i--
@@ -742,7 +742,7 @@ func (m *Params) Unmarshal(dAtA []byte) error {
} }
} }
m.LocalRegistrationEnabled = bool(v != 0) m.LocalRegistrationEnabled = bool(v != 0)
case 3: case 4:
if wireType != 2 { if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType) return fmt.Errorf("proto: wrong wireType = %d for field Schema", wireType)
} }
@@ -26,17 +26,6 @@ var (
swJSFile = files.NewBytesFile(swJSData) swJSFile = files.NewBytesFile(swJSData)
) )
// NewConfig uses the config template to generate the dwn config file
func NewConfig(keyshareJSON string, adddress string, chainID string, schema *dwn.Schema) *dwn.Config {
dwnCfg := &dwn.Config{
Motr: createMotrConfig(keyshareJSON, adddress, "sonr.id"),
Ipfs: defaultIPFSConfig(),
Sonr: defaultSonrConfig(chainID),
Schema: schema,
}
return dwnCfg
}
// NewVaultDirectory creates a new directory with the default files // NewVaultDirectory creates a new directory with the default files
func NewVaultDirectory(cnfg *dwn.Config) (files.Node, error) { func NewVaultDirectory(cnfg *dwn.Config) (files.Node, error) {
dwnJSON, err := json.Marshal(cnfg) dwnJSON, err := json.Marshal(cnfg)
@@ -86,28 +75,3 @@ func MarshalConfigFile(c *dwn.Config) (files.Node, error) {
} }
return files.NewBytesFile(dwnConfigData), nil return files.NewBytesFile(dwnConfigData), nil
} }
func createMotrConfig(keyshareJSON string, adddress string, origin string) *dwn.Motr {
return &dwn.Motr{
Keyshare: keyshareJSON,
Address: adddress,
Origin: origin,
}
}
func defaultIPFSConfig() *dwn.IPFS {
return &dwn.IPFS{
ApiUrl: "https://api.sonr-ipfs.land",
GatewayUrl: "https://ipfs.sonr.land",
}
}
func defaultSonrConfig(chainID string) *dwn.Sonr {
return &dwn.Sonr{
ApiUrl: "https://api.sonr.land",
GrpcUrl: "https://grpc.sonr.land",
RpcUrl: "https://rpc.sonr.land",
WebSocketUrl: "wss://rpc.sonr.land/ws",
ChainId: chainID,
}
}
+34 -3
View File
@@ -4,15 +4,21 @@ import (
"github.com/ipfs/boxo/files" "github.com/ipfs/boxo/files"
"github.com/onsonr/sonr/config/dwn" "github.com/onsonr/sonr/config/dwn"
vault "github.com/onsonr/sonr/x/vault/internal" vault "github.com/onsonr/sonr/x/vault/types/internal"
) )
type Vault struct { type Vault struct {
FS files.Node FS files.Node
} }
func NewVault(cnfg *dwn.Config, chainID string) (*Vault, error) { func NewVault(keyshareJSON string, adddress string, chainID string, schema *dwn.Schema) (*Vault, error) {
fileMap, err := vault.NewVaultDirectory(cnfg) dwnCfg := &dwn.Config{
Motr: createMotrConfig(keyshareJSON, adddress, "sonr.id"),
Ipfs: defaultIPFSConfig(),
Sonr: defaultSonrConfig(chainID),
Schema: schema,
}
fileMap, err := vault.NewVaultDirectory(dwnCfg)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -20,3 +26,28 @@ func NewVault(cnfg *dwn.Config, chainID string) (*Vault, error) {
FS: fileMap, FS: fileMap,
}, nil }, nil
} }
func createMotrConfig(keyshareJSON string, adddress string, origin string) *dwn.Motr {
return &dwn.Motr{
Keyshare: keyshareJSON,
Address: adddress,
Origin: origin,
}
}
func defaultIPFSConfig() *dwn.IPFS {
return &dwn.IPFS{
ApiUrl: "https://api.sonr-ipfs.land",
GatewayUrl: "https://ipfs.sonr.land",
}
}
func defaultSonrConfig(chainID string) *dwn.Sonr {
return &dwn.Sonr{
ApiUrl: "https://api.sonr.land",
GrpcUrl: "https://grpc.sonr.land",
RpcUrl: "https://rpc.sonr.land",
WebSocketUrl: "wss://rpc.sonr.land/ws",
ChainId: chainID,
}
}