Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating handlers to handle new wallet format #22

Open
wants to merge 4 commits into
base: cleanup
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
*.env

# Dependency directories (remove the comment below to include it)
# vendor/
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ require (
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.1 // indirect
github.com/ipfs/go-cid v0.4.1
github.com/joho/godotenv v1.5.1
github.com/klauspost/compress v1.17.8 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/libp2p/go-libp2p-core v0.20.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
Expand Down
14 changes: 14 additions & 0 deletions lib/transports/websocket/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/nbd-wtf/go-nostr"

lib_nostr "github.com/HORNET-Storage/hornet-storage/lib/handlers/nostr"
"github.com/HORNET-Storage/hornet-storage/lib/sessions"
)

func handleAuthMessage(c *websocket.Conn, env *nostr.AuthEnvelope, challenge string, state *connectionState) {
Expand Down Expand Up @@ -57,6 +58,12 @@ func handleAuthMessage(c *websocket.Conn, env *nostr.AuthEnvelope, challenge str
return
}

err = sessions.CreateSession(env.Event.PubKey)
if err != nil {
write("NOTICE", "Failed to create session")
return
}

err = AuthenticateConnection(c)
if err != nil {
write("OK", env.Event.ID, false, "Error authorizing connection")
Expand All @@ -65,5 +72,12 @@ func handleAuthMessage(c *websocket.Conn, env *nostr.AuthEnvelope, challenge str

state.authenticated = true

if state.authenticated {
// Authenticating user session.
userSession := sessions.GetSession(env.Event.PubKey)
userSession.Signature = &env.Event.Sig
userSession.Authenticated = true
}

write("OK", env.Event.ID, true, "")
}
32 changes: 23 additions & 9 deletions lib/web/bitcoin-rate-from-apis.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,25 @@ type BinanceResponse struct {
Price string `json:"price"`
}

type MempoolResponse struct {
USD float64 `json:"USD"`
}

func fetchCoinGeckoPrice() (float64, error) {
resp, err := http.Get("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd")
if err != nil {
return 0, err
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}

var result CoinGeckoResponse
err = json.Unmarshal(body, &result)
if err != nil {
return 0, err
}

return result.Bitcoin.USD, nil
}

Expand All @@ -51,32 +52,46 @@ func fetchBinancePrice() (float64, error) {
return 0, err
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}

var result BinanceResponse
err = json.Unmarshal(body, &result)
if err != nil {
return 0, err
}

price, err := strconv.ParseFloat(result.Price, 64)
if err != nil {
return 0, err
}

return price, nil
}

func fetchMempoolPrice() (float64, error) {
resp, err := http.Get("https://mempool.space/api/v1/prices")
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
var result MempoolResponse
err = json.Unmarshal(body, &result)
if err != nil {
return 0, err
}
return result.USD, nil
}

func fetchBitcoinPrice(apiIndex int) (float64, int, error) {
apis := []func() (float64, error){
fetchCoinGeckoPrice,
fetchBinancePrice,
fetchMempoolPrice,
}

for i := 0; i < len(apis); i++ {
index := (apiIndex + i) % len(apis)
price, err := apis[index]()
Expand All @@ -85,7 +100,6 @@ func fetchBitcoinPrice(apiIndex int) (float64, int, error) {
}
fmt.Println("Error fetching price from API", index, ":", err)
}

return 0, apiIndex, fmt.Errorf("all API calls failed")
}

Expand Down
4 changes: 2 additions & 2 deletions lib/web/get-wallet-addresses.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package web
import (
"log"

types "github.com/HORNET-Storage/hornet-storage/lib" // Adjust the import path to your actual project structure
"github.com/HORNET-Storage/hornet-storage/lib/stores/graviton" // Adjust the import path to your actual project structure
types "github.com/HORNET-Storage/hornet-storage/lib"
"github.com/HORNET-Storage/hornet-storage/lib/stores/graviton"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
Expand Down
8 changes: 4 additions & 4 deletions lib/web/get-wallet-transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func handleLatestTransactions(c *fiber.Ctx) error {

// Get the latest 10 transactions
var transactions []types.WalletTransactions
result := db.Order("date desc").Limit(10).Find(&transactions)
result := db.Order("date desc").Limit(-1).Find(&transactions)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does Limit(-1) do here? Also should update the comment @Maphikza

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I have recently moved back to relay code and this is no longer necessary as we are no longer setting limits.

This is how it looks now.

var transactions []types.WalletTransactions
result := db.Order("date desc").Find(&transactions)


if result.Error != nil {
log.Printf("Error querying transactions: %v", result.Error)
Expand All @@ -48,14 +48,14 @@ func handleLatestTransactions(c *fiber.Ctx) error {

// Process each transaction to convert the value to USD
for i, transaction := range transactions {
satoshis, err := strconv.ParseInt(transaction.Value, 10, 64)
value, err := strconv.ParseFloat(transaction.Value, 64)
if err != nil {
log.Printf("Error converting value to int64: %v", err)
log.Printf("Error converting value to float64: %v", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "Conversion error",
})
}
transactions[i].Value = fmt.Sprintf("%.2f", satoshiToUSD(bitcoinRate.Rate, satoshis))
transactions[i].Value = fmt.Sprintf("%.8f", value)
}

// Respond with the transactions
Expand Down
17 changes: 13 additions & 4 deletions lib/web/update-wallet-transactions.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package web

import (
"fmt"
"log"
"strconv"
"time"

types "github.com/HORNET-Storage/hornet-storage/lib"
Expand Down Expand Up @@ -42,7 +44,8 @@ func handleTransactions(c *fiber.Ctx) error {
continue
}

date, err := time.Parse("2006-01-02 15:04:05", dateStr)
// Correct format for ISO 8601 datetime string with timezone
date, err := time.Parse(time.RFC3339, dateStr)
if err != nil {
log.Printf("Error parsing date: %v", err)
continue
Expand All @@ -54,14 +57,20 @@ func handleTransactions(c *fiber.Ctx) error {
continue
}

value, ok := transaction["value"].(string)
valueStr, ok := transaction["value"].(string)
if !ok {
log.Printf("Invalid value format: %v", transaction["value"])
continue
}

value, err := strconv.ParseFloat(valueStr, 64)
if err != nil {
log.Printf("Error parsing value to float64: %v", err)
continue
}

var existingTransaction types.WalletTransactions
result := db.Where("address = ? AND date = ? AND output = ? AND value = ?", address, date, output, value).First(&existingTransaction)
result := db.Where("address = ? AND date = ? AND output = ? AND value = ?", address, date, output, valueStr).First(&existingTransaction)

if result.Error == nil {
// Transaction already exists, skip it
Expand All @@ -79,7 +88,7 @@ func handleTransactions(c *fiber.Ctx) error {
Address: address,
Date: date,
Output: output,
Value: value,
Value: fmt.Sprintf("%.8f", value),
}
if err := db.Create(&newTransaction).Error; err != nil {
log.Printf("Error saving new transaction: %v", err)
Expand Down
Loading