-
Notifications
You must be signed in to change notification settings - Fork 0
/
new_challenge.go
47 lines (38 loc) · 1.29 KB
/
new_challenge.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package pow
import (
"context"
"fmt"
"github.com/daniel-orlov/quotes-server/pkg/hashcash"
)
// NewChallenge generates a new challenge, saves it to the store and returns it.
func (s *Service) NewChallenge(ctx context.Context, key Key, difficulty, saltLength int) (string, error) {
// Check if the challenge key is empty
if key == nil || key.String() == "" || key.ResourceID() == "" || key.ClientID() == "" {
// Return an error if the challenge key is empty
return "", ErrChallengeKeyEmpty
}
// Check if the difficulty is valid
if difficulty <= 0 {
// Return an error if the difficulty is invalid
return "", ErrChallengeDifficultyInvalid
}
// Check if the salt length is valid
if saltLength <= 0 {
// Return an error if the salt length is invalid
return "", ErrChallengeSaltLengthInvalid
}
// Generate a new challenge
challenge, err := hashcash.New(difficulty, saltLength, hashcash.DateFormatYYMMDD, key.ClientID())
if err != nil {
return "", fmt.Errorf("generating new challenge: %w", err)
}
// Stringify the challenge
challengeStr := challenge.String()
// Save the challenge to the store
err = s.Store.Add(ctx, key.String(), challengeStr)
if err != nil {
return "", fmt.Errorf("saving challenge to store: %w", err)
}
// Return the challenge
return challengeStr, nil
}