forked from DropMorePackets/berghain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
berghain.go
59 lines (46 loc) · 946 Bytes
/
berghain.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
53
54
55
56
57
58
59
package berghain
import (
"crypto/hmac"
"crypto/sha256"
"hash"
"log"
"sync"
"time"
)
type LevelConfig struct {
Duration time.Duration
Type ValidationType
}
type Berghain struct {
Levels []*LevelConfig
secret []byte
hmac sync.Pool
}
var hashAlgo = sha256.New
func NewBerghain(secret []byte) *Berghain {
return &Berghain{
secret: secret,
hmac: sync.Pool{
New: func() any {
return NewZeroHasher(hmac.New(hashAlgo, secret))
},
},
}
}
func (b *Berghain) acquireHMAC() hash.Hash {
return b.hmac.Get().(hash.Hash)
}
func (b *Berghain) releaseHMAC(h hash.Hash) {
h.Reset()
b.hmac.Put(h)
}
func (b *Berghain) LevelConfig(level uint8) *LevelConfig {
if level == 0 {
log.Println("level cannot be zero. correcting to 1")
}
if level > uint8(len(b.Levels)) {
log.Printf("level too high. correcting to %d", len(b.Levels))
}
level = min(uint8(len(b.Levels)), max(1, level))
return b.Levels[level-1]
}