-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_solution.go
52 lines (42 loc) · 1.23 KB
/
check_solution.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
48
49
50
51
52
package pow
import (
"context"
"fmt"
"github.com/daniel-orlov/quotes-server/pkg/hashcash"
)
// CheckSolution checks if the solution with the given challenge key exists in the store and if it is correct.
func (s *Service) CheckSolution(ctx context.Context, solution string, key Key) (bool, error) {
// If the key is nil, return error
if key == nil {
return false, ErrChallengeKeyEmpty
}
// Stringify the key
stringKey := key.String()
// If the key is empty, return error
if stringKey == ":" {
return false, ErrChallengeKeyEmpty
}
// Check if the solution exists in the store
exists, err := s.Store.Get(ctx, stringKey)
if err != nil {
return false, fmt.Errorf("getting challenge from store: %w", err)
}
// If the solution does not exist in the store, return error
if !exists {
return false, ErrChallengeNotFound
}
// Check if the solution is correct
correct, err := hashcash.CheckSolution(solution)
if err != nil {
return false, fmt.Errorf("checking solution: %w", err)
}
// if the solution is correct, delete it from the store
if correct {
err = s.Store.Delete(ctx, stringKey)
if err != nil {
return false, fmt.Errorf("deleting challenge from store: %w", err)
}
}
// Return the result
return correct, nil
}