Skip to content

Commit

Permalink
refactor v1
Browse files Browse the repository at this point in the history
  • Loading branch information
gohumble committed Oct 14, 2023
1 parent 8ff4951 commit dd58f28
Show file tree
Hide file tree
Showing 20 changed files with 546 additions and 491 deletions.
33 changes: 6 additions & 27 deletions cmd/cashu/feni.go
Original file line number Diff line number Diff line change
@@ -1,61 +1,40 @@
package main

import (
"fmt"
"os"
"regexp"
"strings"

"github.com/c-bata/go-prompt"
"github.com/cashubtc/cashu-feni/cmd/cashu/feni"
)

var sendRegex = regexp.MustCompile("send [0-9]")
var advancedPrompt = &feni.CobraPrompt{
RootCmd: feni.RootCmd,
PersistFlagValues: true,
ShowHelpCommandAndFlags: false,
DisableCompletionCommand: true,
AddDefaultExitCommand: false,

DynamicSuggestionsFunc: feni.DynamicSuggestion(feni.RootCmd),
GoPromptOptions: []prompt.Option{
prompt.OptionTitle("cashu-feni"),
prompt.OptionPrefix(">(cashu-feni)> "),
prompt.OptionMaxSuggestion(10),
},
DynamicSuggestionsFunc: func(annotationValue string, document *prompt.Document) []prompt.Suggest {
if document.Text == "-w " || document.Text == "--wallet " {
fmt.Println(document.Text)
if suggestions := feni.GetWalletsDynamic(annotationValue); suggestions != nil {
return suggestions
}
} else if document.Text == "locks " || document.Text == "-l " {
if suggestions := feni.GetLocksDynamic(annotationValue); suggestions != nil {
return suggestions
}
} else if sendRegex.MatchString(document.Text) {
document.Text = fmt.Sprintf("%s %s", document.Text, "-m ")
if suggestions := feni.GetMintsDynamic(annotationValue); suggestions != nil {
return suggestions
}
}

return nil
},
OnErrorFunc: func(err error) {
if strings.Contains(err.Error(), "unknown command") {
feni.RootCmd.PrintErrln(err)
feni.RootCmd.Command().PrintErrln(err)
return
}

feni.RootCmd.PrintErr(err)
feni.RootCmd.Command().PrintErr(err)
os.Exit(1)
},
}

func main() {
feni.StartClientConfiguration()
advancedPrompt.RootCmd.PersistentFlags().StringVarP(&feni.WalletUsed, "wallet", "w", "wallet", "Name of your wallet")
advancedPrompt.RootCmd.PersistentFlags().StringVarP(&feni.Host, "host", "H", "", "Mint host address")

advancedPrompt.RootCmd.Command().PersistentFlags().StringVarP(&feni.WalletName, "wallet", "w", "wallet", "Name of your wallet")
advancedPrompt.RootCmd.Command().PersistentFlags().StringVarP(&advancedPrompt.RootCmd.Wallet().Config.MintServerHost, "host", "H", "", "Mint host address")
advancedPrompt.Run()
}
23 changes: 15 additions & 8 deletions cmd/cashu/feni/balance.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,30 @@ package feni

import (
"fmt"
"github.com/cashubtc/cashu-feni/wallet"
"github.com/spf13/cobra"
)

func init() {
RootCmd.AddCommand(balanceCommand)
RootCmd.Command().AddCommand(balanceCommand)
}

var balanceCommand = &cobra.Command{
Use: "balance",
Short: "Check your balance",
Long: ``,
PreRun: PreRunFeni,
Run: balance,
Use: "balance",
Short: "Check your balance",
Long: ``,
PreRun: RunCommandWithWallet(RootCmd, func(w *wallet.Wallet, params cobraParameter) {
opts := make([]wallet.Option, 0)
if WalletName != "" {
opts = append(opts, wallet.WithName(WalletName))
}
RootCmd.wallet = wallet.New(opts...)
}),
Run: RunCommandWithWallet(RootCmd, balance),
}

func balance(cmd *cobra.Command, args []string) {
balances, err := Wallet.balancePerKeySet()
func balance(wallet *wallet.Wallet, params cobraParameter) {
balances, err := wallet.Balances()
if err != nil {
panic(err)
}
Expand Down
24 changes: 12 additions & 12 deletions cmd/cashu/feni/burn.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,32 @@ import (
"encoding/base64"
"encoding/json"
"github.com/cashubtc/cashu-feni/cashu"
"github.com/cashubtc/cashu-feni/wallet"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

var burnCommand = &cobra.Command{
Use: "burn",
Short: "Burn spent tokens",
Long: ``,
PreRun: PreRunFeni,
Run: burnCmd,
Use: "burn",
Short: "Burn spent tokens",
Long: ``,
Run: RunCommandWithWallet(RootCmd, burnCmd),
}
var all bool
var force bool

func init() {
burnCommand.PersistentFlags().BoolVarP(&all, "all", "a", false, "burn all spent tokens.")
burnCommand.PersistentFlags().BoolVarP(&force, "force", "f", false, "force check on all tokens.")
RootCmd.AddCommand(burnCommand)
RootCmd.Command().AddCommand(burnCommand)
}
func burnCmd(cmd *cobra.Command, args []string) {
func burnCmd(wallet *wallet.Wallet, params cobraParameter) {
var token string
if len(args) == 1 {
token = args[0]
if len(params.args) == 1 {
token = params.args[0]
}
if !(all || force || token != "") || (token != "" && all) {
cmd.Println("Error: enter a token or use --all to burn all pending tokens or --force to check all tokens.")
params.cmd.Println("Error: enter a token or use --all to burn all pending tokens or --force to check all tokens.")
return
}
proofs := make([]cashu.Proof, 0)
Expand All @@ -40,7 +40,7 @@ func burnCmd(cmd *cobra.Command, args []string) {
log.Fatal(err)
}
} else if force {
proofs = Wallet.proofs
// invalidate all wallet proofs
} else {
p, err := base64.URLEncoding.DecodeString(token)
if err != nil {
Expand All @@ -56,7 +56,7 @@ func burnCmd(cmd *cobra.Command, args []string) {
return
}

err = invalidate(proofs)
err = wallet.Invalidate(proofs)
if err != nil {
log.Fatal(err)
}
Expand Down
32 changes: 32 additions & 0 deletions cmd/cashu/feni/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package feni

import (
"github.com/cashubtc/cashu-feni/wallet"
"github.com/spf13/cobra"
)

type command func(wallet *wallet.Wallet, params cobraParameter)
type cobraParameter struct {
cmd *cobra.Command
args []string
}
type RootCommand struct {
cmd *cobra.Command
wallet *wallet.Wallet
}

func (r *RootCommand) SetCommand(cmd *cobra.Command) {
r.cmd = cmd
}
func (r *RootCommand) Command() *cobra.Command {
return r.cmd
}
func (r *RootCommand) Wallet() *wallet.Wallet {
return r.wallet
}
func RunCommandWithWallet(root *RootCommand, command command) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
cmd.ParseFlags(args)
command(root.wallet, cobraParameter{cmd: cmd, args: args})
}
}
185 changes: 2 additions & 183 deletions cmd/cashu/feni/config.go
Original file line number Diff line number Diff line change
@@ -1,188 +1,7 @@
package feni

import (
"fmt"
"github.com/caarlos0/env/v6"
"github.com/cashubtc/cashu-feni/cashu"
"github.com/cashubtc/cashu-feni/crypto"
"github.com/cashubtc/cashu-feni/db"
"github.com/cashubtc/cashu-feni/lightning"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/joho/godotenv"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"math/rand"
"os"
"path"
"time"
"github.com/cashubtc/cashu-feni/wallet"
)

var Config WalletConfig

type WalletConfig struct {
Debug bool `env:"DEBUG"`
Lightning bool `env:"LIGHTNING"`
MintServerHost string `env:"MINT_HOST"`
MintServerPort string `env:"MINT_PORT"`
Wallet string `env:"WALLET"`
}

func defaultConfig() {
log.Infof("Loading default configuration")
Config = WalletConfig{
Debug: true,
Lightning: true,
MintServerHost: "https://8333.space",
MintServerPort: "3339",
Wallet: "wallet",
}

}
func StartClientConfiguration() {
loaded := false
dirname, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
p := path.Join(dirname, ".cashu", ".env")
err = godotenv.Load(p)
if err != nil {
defaultConfig()
loaded = true
}
if !loaded {
err = env.Parse(&Config)
if err != nil {
defaultConfig()
}
}

// initialize the default wallet (no other option selected using -w)
lightning.Config.Lightning.Enabled = Config.Lightning
InitializeDatabase(Config.Wallet)

rand.Seed(time.Now().UnixNano())

Wallet = MintWallet{
proofs: make([]cashu.Proof, 0),
Client: &Client{Url: fmt.Sprintf("%s:%s", Config.MintServerHost, Config.MintServerPort)},
}

Wallet.loadDefaultMint()

}
func (w *MintWallet) loadMint(keySetId string) {
/*keySet, err := storage.GetKeySet(db.KeySetWithId(keySetId))
if err != nil {
panic(err)
}
*/
for _, set := range w.keySets {
if set.Id == keySetId {
w.currentKeySet = &set
}
}
w.Client.Url = w.currentKeySet.MintUrl
w.loadDefaultMint()
}
func (w *MintWallet) setCurrentKeySet(keySet crypto.KeySet) {
for _, set := range w.keySets {
if set.Id == keySet.Id {
w.currentKeySet = &keySet
}
}
}
func (w *MintWallet) loadPersistedKeySets() {
persistedKeySets, err := storage.GetKeySet()
if err != nil {
panic(err)
}
w.keySets = persistedKeySets
}
func (w *MintWallet) loadDefaultMint() {
keySet, _ := w.persistCurrentKeysSet()
w.loadPersistedKeySets()
w.setCurrentKeySet(keySet)
k, err := w.Client.KeySets()
if err != nil {
panic(err)
}
for _, set := range k.KeySets {
if _, found := lo.Find[crypto.KeySet](w.keySets, func(k crypto.KeySet) bool {
return set == k.Id
}); !found {
err = w.checkAndPersistKeySet(set)
if err != nil {
panic(err)
}
}
}

}
func (w *MintWallet) persistCurrentKeysSet() (crypto.KeySet, error) {
activeKeys, err := w.Client.Keys()
if err != nil {
panic(err)
}
return w.persistKeysSet(activeKeys)
}
func (w *MintWallet) persistKeysSet(keys map[uint64]*secp256k1.PublicKey) (crypto.KeySet, error) {
keySet := crypto.KeySet{MintUrl: w.Client.Url, FirstSeen: time.Now(), PublicKeys: crypto.PublicKeyList{}}
keySet.SetPublicKeyList(keys)
keySet.DeriveKeySetId()
err := storage.StoreKeySet(keySet)
if err != nil {
return keySet, err
}
return keySet, nil
}
func (w *MintWallet) checkAndPersistKeySet(id string) error {
var ks []crypto.KeySet
var err error
if ks, err = storage.GetKeySet(db.KeySetWithId(id)); err != nil || len(ks) == 0 {
keys, err := w.Client.KeysForKeySet(id)
if err != nil {
return err
}
k, err := w.persistKeysSet(keys)
ks = append(ks, k)
if err != nil {
return err
}
}
Wallet.keySets = append(Wallet.keySets, ks...)
return nil
}
func InitializeDatabase(wallet string) {
dirname, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
walletPath := path.Join(dirname, ".cashu", wallet)
db.Config.Database.Sqlite = &db.SqliteConfig{Path: walletPath, FileName: "wallet.sqlite3"}
err = env.Parse(&Config)
if err != nil {
panic(err)
}
storage = db.NewSqlDatabase()
err = storage.Migrate(cashu.Proof{})
if err != nil {
panic(err)
}
err = storage.Migrate(cashu.ProofsUsed{})
if err != nil {
panic(err)
}
err = storage.Migrate(crypto.KeySet{})
if err != nil {
panic(err)
}
err = storage.Migrate(cashu.P2SHScript{})
if err != nil {
panic(err)
}
err = storage.Migrate(cashu.CreateInvoice())
if err != nil {
panic(err)
}
}
var Config wallet.Config
Loading

0 comments on commit dd58f28

Please sign in to comment.