-
Notifications
You must be signed in to change notification settings - Fork 0
/
notary.go
200 lines (171 loc) · 4.5 KB
/
notary.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package notary
import (
"context"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/NTRYPlatform/ntry-backend/config"
"github.com/NTRYPlatform/ntry-backend/eth"
"github.com/NTRYPlatform/ntry-backend/ws"
uuid "github.com/satori/go.uuid"
log "go.uber.org/zap"
"upper.io/db.v3/mysql"
)
// TODO:
// Handle read write locking
type Notary struct {
id uuid.UUID
db *dbServer
conf *config.Config
email *emailConf
logger *log.Logger
ethClient *eth.EthClient
ctx context.Context
cancel context.CancelFunc
contracts chan interface{}
}
// New returns ninstance of Notary
func New(args map[string]interface{}) (*Notary, error) {
var (
logPath = args["--logpath"].(string)
confPath = args["--confpath"].(string)
debug bool = args["--debug"].(bool)
)
ntry := &Notary{}
err := ntry.makeID()
if err != nil {
return nil, err
}
if ntry.logger, err = initLogger(&logPath, ntry.id.String(), &debug); err != nil {
return nil, err
}
// Loading the congiguration
ntry.logger.Info("[notary ] Loading configurations from: " + confPath)
if ntry.conf, err = config.Init(confPath, ntry.logger); err != nil {
return nil, err
}
return ntry, nil
}
func (n *Notary) Init() error {
ctx := context.Background()
n.ctx, n.cancel = context.WithCancel(ctx)
// TODO:
// Conf and DB structs have publid variables
// as well as Getters, access must be filtered
dbConf := n.conf.GetDatabaseSettings()
script, err := dbConf.GetDBScript()
if err != nil {
return err
}
// initilizing db session
if n.db, err =
dbInit(script, mysql.ConnectionURL{
Host: dbConf.Host,
Database: dbConf.Name,
User: dbConf.User,
Password: dbConf.Password,
}, n.logger); err != nil {
return err
}
n.email = newEmail()
n.email.from, n.email.pass, n.email.server = n.conf.GetEmailInfo()
if !n.email.ok() {
return fmt.Errorf("[notary ] incomplete email configuration", nil)
}
// Initialize ETH client
ethKey, err := n.conf.GetEthKey()
if err != nil {
return fmt.Errorf("[notary ] Unable to get ETH key: %v", err)
}
n.ethClient, err = eth.NewEthClient(n.conf.GetEthIPC(), n.conf.GetCarContract(), n.conf.GetTokenContract(), ethKey, n.conf.GetEthPassphrase())
if err != nil {
return fmt.Errorf("[notary ] Unable to initialize ETH client: %v", err)
}
if err = n.ethClient.SubscribeToMapperContract(n.conf.GetMapperContract()); err != nil {
return fmt.Errorf("[notary ] Unable to bind event listener: %v", err)
}
return nil
}
func (n *Notary) makeID() error {
dirName := "/var/lib/notary"
fileName := "notary.id"
filePath := filepath.Join(dirName, fileName)
err := os.MkdirAll(dirName, 0644)
if err != nil {
return err
}
if f, err := os.OpenFile(filePath, os.O_RDWR, 0644); os.IsNotExist(err) {
n.id = uuid.NewV4()
errWrite := ioutil.WriteFile(filePath, n.id.Bytes(), 0644)
if err != nil {
return errWrite
}
} else {
if err != nil {
return err
}
buff, err := ioutil.ReadAll(f)
if err != nil {
return err
}
n.id, err = uuid.FromBytes(buff)
if err != nil {
return err
}
}
return nil
}
func (n *Notary) Start() error {
go n.EthWatcher()
router := n.muxServer()
addr := n.conf.GetServerAddress()
//TODO:generate cert and serve on TLS
n.logger.Info("[notary ] Server waiting for request...")
return http.ListenAndServe(addr, router)
}
func (n *Notary) EthWatcher() {
out := make(chan string)
err := make(chan struct{})
go ws.WriteToRegisterChannel(out, err)
for {
select {
case ethLog := <-n.ethClient.Events:
n.logger.Info(fmt.Sprintf("[notary ] %+v", ethLog))
data := hex.EncodeToString(ethLog.Data)
address := data[24:64]
uid := data[64:96]
n.logger.Info(fmt.Sprintf("Address: %s, UID: %s, Tx Hash: %s", address, uid, ethLog.TxHash.String()))
u := VerifyUser(uid, address, ethLog.TxHash.String())
if err := n.db.UpdateUser(u); err != nil {
n.logger.Error(fmt.Sprintf("Couldn't update user! %v", err.Error()))
} else {
out <- uid
}
case <-err:
n.logger.Error("WebSocket register stopped working, stopping eth watcher")
return
}
}
}
func (n *Notary) ContractWatcher() {
out := make(chan interface{})
err := make(chan struct{})
go ws.WriteToContractChannel(out, err)
for {
select {
case m := <-n.contracts:
n.logger.Info(fmt.Sprintf("[notary ] %+v", m))
out <- m
case <-err:
n.logger.Error("WebSocket register stopped working, stopping eth watcher")
return
}
}
}
func (n *Notary) Shutdown() error {
n.db.CloseSession()
return nil
}