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

New media branch #37

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
1238888
Updating relay settings type to allow for filtering through relay set…
Maphikza Oct 10, 2024
75f13c4
Improving IsFilePermitted to handle miscellanious files as we account…
Maphikza Oct 10, 2024
c6967d0
Fixing data pull bug.
Maphikza Oct 11, 2024
c7adc01
updating relays settings type and relay setting handler.
Maphikza Oct 12, 2024
9e116e6
Changing panel settings management via viper
Maphikza Oct 16, 2024
d00fb0f
removing redundant debug logs.
Maphikza Oct 16, 2024
9a6b2f6
Updating relay settings type to include app buckets
Maphikza Oct 16, 2024
280b74c
adding subscription filter and changing address handling to be done w…
Maphikza Oct 30, 2024
70304d0
Adding media handler
Maphikza Oct 30, 2024
3842096
Working to get subscription process simplified.
Maphikza Nov 6, 2024
39bec60
working version for subscription with nip 88 event 764, pre clean up
Maphikza Nov 7, 2024
a16d66a
Adding auto address generation implentation
Maphikza Nov 9, 2024
60a33b8
feat(settings): add subscription tiers support to relay settings
Maphikza Nov 12, 2024
e2404d3
feat: Add conditional kind 411 event creation on subscription tier up…
Maphikza Nov 12, 2024
4872a18
feat: Add conditional kind 411 event creation on subscription tier up…
Maphikza Nov 12, 2024
29f28c0
It is not necessary to update kind 411 when tiers change. we need to …
Maphikza Nov 13, 2024
7f9641b
changing kind 764 to 888
Maphikza Nov 14, 2024
d9815c3
feat: Add dynamic subscription_tier tags to NIP-88 events
Maphikza Nov 14, 2024
89653d9
Since kind 888 will have a lot of copies updating the subscription ti…
Maphikza Nov 15, 2024
b022fad
updating kind 411 to correctly handle subscription tiers
Maphikza Nov 15, 2024
a1d864c
feat: add GetSubscriberByAddress method to GORM store
Maphikza Nov 16, 2024
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
24 changes: 19 additions & 5 deletions lib/handlers/blossom/blossom.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log"

utils "github.com/HORNET-Storage/hornet-storage/lib/handlers/scionic"
"github.com/HORNET-Storage/hornet-storage/lib/stores"
"github.com/gofiber/fiber/v2"
"github.com/nbd-wtf/go-nostr"
Expand Down Expand Up @@ -35,34 +37,46 @@ func (s *Server) getBlob(c *fiber.Ctx) error {
func (s *Server) uploadBlob(c *fiber.Ctx) error {
pubkey := c.Query("pubkey")

// Validate subscription status and storage quota using NIP-88
if err := utils.ValidateUploadEligibility(s.storage, pubkey, c.Body()); err != nil {
log.Printf("Upload validation failed for subscriber %s: %v", pubkey, err)
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
"message": err.Error(),
})
}

data := c.Body()

// Compute the hash of the data
checkHash := sha256.Sum256(data)
encodedHash := hex.EncodeToString(checkHash[:])

// Filter to find matching events with the computed hash
filter := nostr.Filter{
Kinds: []int{117},
Kinds: []int{117}, // Assuming 117 is the correct kind for blossom events
Authors: []string{pubkey},
Tags: nostr.TagMap{"blossom_hash": []string{encodedHash}},
}

fmt.Println("Recieved a blossom blob")
fmt.Println("Received a blossom blob")

// Query for events matching the filter
events, err := s.storage.QueryEvents(filter)
if err != nil {
return err
}

var event *nostr.Event
// Handle case where no matching events are found
if len(events) <= 0 {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "no events match this file upload"})
}

event = events[0]
event := events[0]

// Extract the "blossom_hash" tag value from the event
fileHash := event.Tags.GetFirst([]string{"blossom_hash"})

// Check the submitted hash matches the data being submitted
// Check if the submitted hash matches the expected value from the event
if encodedHash != fileHash.Value() {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "submitted hex encoded hash does not match hex encoded hash of data"})
}
Expand Down
129 changes: 26 additions & 103 deletions lib/handlers/nostr/kind411/subscriptionEventsCreator.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,10 @@ import (
"log"
"time"

types "github.com/HORNET-Storage/hornet-storage/lib"
"github.com/HORNET-Storage/hornet-storage/lib/signing"
"github.com/HORNET-Storage/hornet-storage/lib/stores"
stores_graviton "github.com/HORNET-Storage/hornet-storage/lib/stores/graviton"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/deroproject/graviton"
"github.com/nbd-wtf/go-nostr"
"github.com/spf13/viper"
)
Expand All @@ -30,14 +26,15 @@ const (
)

type RelayInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Pubkey string `json:"pubkey"`
Contact string `json:"contact"`
SupportedNIPs []int `json:"supported_nips"`
Software string `json:"software"`
Version string `json:"version"`
DHTkey string `json:"dhtkey,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Pubkey string `json:"pubkey"`
Contact string `json:"contact"`
SupportedNIPs []int `json:"supported_nips"`
Software string `json:"software"`
Version string `json:"version"`
DHTkey string `json:"dhtkey,omitempty"`
SubscriptionTiers []map[string]interface{} `json:"subscription_tiers,omitempty"` // New field
}

func CreateKind411Event(privateKey *secp256k1.PrivateKey, publicKey *secp256k1.PublicKey, store stores.Store) error {
Expand All @@ -60,16 +57,25 @@ func CreateKind411Event(privateKey *secp256k1.PrivateKey, publicKey *secp256k1.P
}
}

// Retrieve subscription tiers from Viper using UnmarshalKey
var subscriptionTiers []map[string]interface{}
if err := viper.UnmarshalKey("subscription_tiers", &subscriptionTiers); err != nil {
log.Printf("Error unmarshaling subscription tiers: %v", err)
} else {
log.Println("Successfully fetched subscription tiers:", subscriptionTiers)
}

// Get relay info
relayInfo := RelayInfo{
Name: viper.GetString("RelayName"),
Description: viper.GetString("RelayDescription"),
Pubkey: viper.GetString("RelayPubkey"),
Contact: viper.GetString("RelayContact"),
SupportedNIPs: []int{1, 11, 2, 9, 18, 23, 24, 25, 51, 56, 57, 42, 45, 50, 65, 116},
Software: viper.GetString("RelaySoftware"),
Version: viper.GetString("RelayVersion"),
DHTkey: viper.GetString("RelayDHTkey"),
Name: viper.GetString("RelayName"),
Description: viper.GetString("RelayDescription"),
Pubkey: viper.GetString("RelayPubkey"),
Contact: viper.GetString("RelayContact"),
SupportedNIPs: []int{1, 11, 2, 9, 18, 23, 24, 25, 51, 56, 57, 42, 45, 50, 65, 116},
Software: viper.GetString("RelaySoftware"),
Version: viper.GetString("RelayVersion"),
DHTkey: viper.GetString("RelayDHTkey"),
SubscriptionTiers: subscriptionTiers,
}

// Convert relay info to JSON
Expand Down Expand Up @@ -156,86 +162,3 @@ func serializeEventForID(event *nostr.Event) string {

return compactSerialized
}

func allocateAddress(store *stores_graviton.GravitonStore) (*types.Address, error) {
ss, err := store.Database.LoadSnapshot(0)
if err != nil {
return nil, fmt.Errorf("failed to load snapshot: %v", err)
}

addressTree, err := ss.GetTree("relay_addresses")
if err != nil {
return nil, fmt.Errorf("failed to get address tree: %v", err)
}

cursor := addressTree.Cursor()
for _, v, err := cursor.First(); err == nil; _, v, err = cursor.Next() {
var addr types.Address
if err := json.Unmarshal(v, &addr); err != nil {
return nil, err
}
if addr.Status == AddressStatusAvailable {
now := time.Now()
addr.Status = AddressStatusAllocated
addr.AllocatedAt = &now

value, err := json.Marshal(addr)
if err != nil {
return nil, err
}
if err := addressTree.Put([]byte(addr.Index), value); err != nil {
return nil, err
}
if _, err := graviton.Commit(addressTree); err != nil {
return nil, err
}
return &addr, nil
}
}

return nil, fmt.Errorf("no available addresses")
}

func CreateNIP88Event(relayPrivKey *btcec.PrivateKey, userPubKey string, store *stores_graviton.GravitonStore) (*nostr.Event, error) {
subscriptionTiers := []types.SubscriptionTier{
{DataLimit: "1 GB per month", Price: "10,000 sats"},
{DataLimit: "5 GB per month", Price: "40,000 sats"},
{DataLimit: "10 GB per month", Price: "70,000 sats"},
}

// Allocate a new address for this subscription
addr, err := allocateAddress(store)
if err != nil {
return nil, fmt.Errorf("failed to allocate address: %v", err)
}

tags := []nostr.Tag{
{"subscription-duration", "1 month"},
{"npub", userPubKey},
{"relay-bitcoin-address", addr.Address},
// Add Lightning invoice if applicable
{"relay-dht-key", viper.GetString("RelayDHTkey")},
}

for _, tier := range subscriptionTiers {
tags = append(tags, nostr.Tag{"subscription-tier", tier.DataLimit, tier.Price})
}

event := &nostr.Event{
PubKey: hex.EncodeToString(relayPrivKey.PubKey().SerializeCompressed()),
CreatedAt: nostr.Timestamp(time.Now().Unix()),
Kind: 764,
Tags: tags,
Content: "",
}

hash := sha256.Sum256(event.Serialize())
sig, err := schnorr.Sign(relayPrivKey, hash[:])
if err != nil {
return nil, fmt.Errorf("error signing event: %v", err)
}
event.ID = hex.EncodeToString(hash[:])
event.Sig = hex.EncodeToString(sig.Serialize())

return event, nil
}
6 changes: 6 additions & 0 deletions lib/handlers/scionic/upload/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ func BuildUploadStreamHandler(store stores.Store, canUploadDag func(rootLeaf *me
return
}

// Add subscription and storage validation here using NIP-88 validation and update
if err := utils.ValidateUploadEligibility(store, message.PublicKey, message.Leaf.Content); err != nil {
write(utils.BuildErrorMessage("Invalid or inactive subscription", err))
return
}

err = message.Leaf.VerifyRootLeaf()
if err != nil {
write(utils.BuildErrorMessage("Failed to verify root leaf", err))
Expand Down
Loading