-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdb.go
81 lines (65 loc) · 1.48 KB
/
db.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"encoding/json"
"log"
"github.com/garyburd/redigo/redis"
)
// DB used to handle all the share handing.
type DB struct {
pool *redis.Pool
SubmitChan chan Share
}
// A Share submitted to redis.
type Share struct {
Submitter string `json:"addr"`
Difficulty float64 `json:"diff"`
NetDifficulty float64 `json:"net_diff"`
Subsidy float64 `json:"sub"`
Host string `json:"host"`
Server string `json:"srv"`
Valid bool `json:"valid"`
}
// NewDB from redis.
func NewDB(redisHost, redisPass string) (*DB, error) {
pool := redis.NewPool(func() (redis.Conn, error) {
c, err := redis.Dial("tcp", redisHost)
if err != nil {
return nil, err
}
// Authenticate with the auth.
if redisPass != "" {
if _, err := c.Do("AUTH", redisPass); err != nil {
c.Close()
return nil, err
}
}
return c, err
}, 10)
conn := pool.Get()
defer conn.Close()
// Test the connection
if _, err := conn.Do("PING"); err != nil {
return nil, err
}
db := DB{
pool: pool,
SubmitChan: make(chan Share, 1024),
}
go db.serve()
return &db, nil
}
// serve runs a loop that handles share submissions.
func (db *DB) serve() {
for share := range db.SubmitChan {
func() {
conn := db.pool.Get()
defer conn.Close()
// Encode the share
data, _ := json.Marshal(share)
_, err := conn.Do("PUBLISH", "shares", data)
if err != nil {
log.Println("[db] ! Could not publish share: " + string(data))
}
}()
}
}