satdress/db.go

98 lines
1.9 KiB
Go
Raw Normal View History

package main
2021-08-20 12:32:45 +00:00
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
2021-08-21 16:52:21 +00:00
"strings"
2021-08-20 12:32:45 +00:00
"github.com/cockroachdb/pebble"
)
type Params struct {
Name string `json:"name"`
Kind string `json:"kind"`
Host string `json:"host"`
Key string `json:"key"`
Pak string `json:"pak"`
Waki string `json:"waki"`
Pin string `json:"pin"`
MinSendable string `json:"minSendable"`
MaxSendable string `json:"maxSendable"`
}
2021-08-20 12:32:45 +00:00
func SaveName(
name string,
params *Params,
providedPin string,
) (pin string, inv string, err error) {
2021-08-21 16:52:21 +00:00
name = strings.ToLower(name)
2021-08-20 13:30:20 +00:00
key := []byte(name)
2021-08-20 12:32:45 +00:00
pin = ComputePIN(name)
2021-08-20 12:32:45 +00:00
if _, closer, err := db.Get(key); err == nil {
defer closer.Close()
if pin != providedPin {
return "", "", errors.New("name already exists! must provide pin")
2021-08-20 12:32:45 +00:00
}
}
if err != nil {
return "", "", errors.New("that name does not exist")
}
2021-08-20 12:32:45 +00:00
params.Name = name
2021-08-20 12:32:45 +00:00
// check if the given data works
if inv, err = makeInvoice(params, 1000, &pin); err != nil {
return "", "", fmt.Errorf("couldn't make an invoice with the given data: %w", err)
2021-08-20 12:32:45 +00:00
}
// save it
data, _ := json.Marshal(params)
if err := db.Set(key, data, pebble.Sync); err != nil {
return "", "", err
2021-08-20 12:32:45 +00:00
}
return pin, inv, nil
2021-08-20 12:32:45 +00:00
}
2021-08-20 13:12:06 +00:00
func GetName(name string) (*Params, error) {
2021-08-21 16:52:21 +00:00
name = strings.ToLower(name)
2021-08-20 12:32:45 +00:00
val, closer, err := db.Get([]byte(name))
if err != nil {
return nil, err
}
defer closer.Close()
2021-08-20 13:12:06 +00:00
var params Params
if err := json.Unmarshal(val, &params); err != nil {
2021-08-20 12:32:45 +00:00
return nil, err
}
params.Name = name
2021-08-20 13:12:06 +00:00
return &params, nil
2021-08-20 12:32:45 +00:00
}
func DeleteName(name string) error {
name = strings.ToLower(name)
key := []byte(name)
if err := db.Delete(key, pebble.Sync); err != nil {
return err
}
return nil
}
func ComputePIN(name string) string {
name = strings.ToLower(name)
mac := hmac.New(sha256.New, []byte(s.Secret))
mac.Write([]byte(name + "@" + s.Domain))
return hex.EncodeToString(mac.Sum(nil))
}