-
Notifications
You must be signed in to change notification settings - Fork 19
/
audit.go
303 lines (284 loc) · 8.77 KB
/
audit.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package zkledger
import (
"fmt"
"log"
"math/big"
"net"
"net/rpc"
"sync"
"github.com/mit-dci/zksigma"
)
type Auditor struct {
num int
local_ledger *LocalLedger
receivedTxns chan *EncryptedTransaction
mu *sync.Mutex
lastSeen int
Done chan bool
banks []BankClient
pki *PKI
CommsCache []zksigma.ECPoint
RTokenCache []zksigma.ECPoint
Setup chan struct{}
}
func MakeAuditor(num int, pki *PKI) *Auditor {
a := &Auditor{
num: num,
local_ledger: MakeLocalLedger(),
receivedTxns: make(chan *EncryptedTransaction, TXN_BUFFER),
mu: new(sync.Mutex),
lastSeen: -1,
Done: make(chan bool),
pki: pki,
Setup: make(chan struct{}),
}
a.CommsCache = make([]zksigma.ECPoint, a.num)
a.RTokenCache = make([]zksigma.ECPoint, a.num)
for i := 0; i < a.num; i++ {
a.CommsCache[i] = zksigma.Zero
a.RTokenCache[i] = zksigma.Zero
}
go a.start()
return a
}
func (a *Auditor) Go(c APLClientConfig, _ *struct{}) error {
go a.register(c.Hostname, c.BasePort, c.BankHostnames)
a.listen(c.Hostname, c.BasePort)
return nil
}
func (a *Auditor) listen(hostname string, basePort int) {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", basePort+a.num+2))
if err != nil {
log.Fatalf("[A] Could not listen %v\n", err)
}
err = rpc.Register(a)
if err != nil {
panic(err)
}
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
continue
}
go rpc.ServeConn(conn)
}
}
func (a *Auditor) register(hostname string, baseport int, bankHostnames []string) {
var wg sync.WaitGroup
a.banks = make([]BankClient, a.num)
for i := 0; i < a.num; i++ {
wg.Add(1)
go func(i int) {
x := MakeRemoteBankClient()
x.connect(bankHostnames[i], baseport+i+1)
a.banks[i] = x
wg.Done()
}(i)
}
wg.Wait()
Dprintf("[A] Registered with banks\n")
close(a.Setup)
}
func (a *Auditor) start() {
<-a.Setup
Dprintf("[A] Starting audit loop...\n")
var pks []zksigma.ECPoint
for {
select {
case etx := <-a.receivedTxns:
Dprintf("[A][%v] Received txn...\n", etx.Index)
// Verify
if pks == nil {
pks = make([]zksigma.ECPoint, a.num+1) // all the banks and the issuer
for i := 0; i < a.num+1; i++ {
pks[i] = a.pki.Get(i)
}
}
if *emptyTxn {
continue
}
a.mu.Lock()
if !etx.Verify(pks, a.CommsCache, a.RTokenCache, "A") {
log.Fatalf("[A][%v] Bad transaction!\n", etx.Index)
}
Dprintf("[A][%v] Verified txn...\n", etx.Index)
lastSeen := a.lastSeen
a.mu.Unlock()
if etx.Index < lastSeen {
log.Fatalf("[A] lastSeen %v out of whack with received transactions %v\n", lastSeen, etx.Index)
} else if etx.Index == lastSeen {
log.Fatalf("[A] lastSeen %v out of whack with received transactions %v\n", lastSeen, etx.Index)
} else if etx.Index == lastSeen+1 {
a.mu.Lock()
a.lastSeen = a.lastSeen + 1
etx.reduce()
a.local_ledger.add(etx)
if etx.Type == Transfer {
for i := 0; i < len(etx.Entries); i++ {
//Dprintf("[A] Adding RToken %v...\n", etx.Entries[i].RToken)
a.RTokenCache[i] = ZKLedgerCurve.Add(a.RTokenCache[i], etx.Entries[i].RToken)
a.CommsCache[i] = ZKLedgerCurve.Add(a.CommsCache[i], etx.Entries[i].Comm)
}
} else if etx.Type == Issuance || etx.Type == Withdrawal {
// Only one bank for now
en := &etx.Entries[etx.Sender]
gval := ZKLedgerCurve.Mult(ZKLedgerCurve.G, en.V)
a.CommsCache[etx.Sender] = ZKLedgerCurve.Add(a.CommsCache[etx.Sender], gval)
}
Dprintf("[A][%v] Processed txn\n", etx.Index)
a.mu.Unlock()
} else {
Dprintf("[A][%v] Received txn out of order, expected %v\n", etx.Index, a.lastSeen)
a.receivedTxns <- etx
}
case <-a.Done:
Dprintf("[A] Shutting down audit loop...\n")
close(a.receivedTxns)
return
}
}
}
func (a *Auditor) Stop(_ *struct{}, _ *struct{}) error {
a.Done <- true
return nil
}
func (a *Auditor) Notify(etx *EncryptedTransaction, _ *struct{}) error {
Dprintf("[A][%v] Notified of txn\n", etx.Index)
a.receivedTxns <- etx
return nil
}
// Compute # of asset for a given bank according to the ledger.
func (a *Auditor) computeSum(bank_i int) (*big.Int, bool) {
Dprintf("[A] Auditing bank %v \n", bank_i)
var rep AuditRep
a.banks[bank_i].Audit(&struct{}{}, &rep)
comms := zksigma.Zero
rtokens := zksigma.Zero
a.mu.Lock()
if *useCache {
comms = a.CommsCache[bank_i]
rtokens = a.RTokenCache[bank_i]
} else {
for i := 0; i < len(a.local_ledger.Transactions); i++ {
etx := &a.local_ledger.Transactions[i]
if etx.Type == Transfer {
comms = ZKLedgerCurve.Add(comms, etx.Entries[bank_i].Comm)
rtokens = ZKLedgerCurve.Add(rtokens, etx.Entries[bank_i].RToken)
} else if (etx.Type == Issuance || etx.Type == Withdrawal) && etx.Sender == bank_i {
gval := ZKLedgerCurve.Mult(ZKLedgerCurve.G, etx.Entries[etx.Sender].V)
comms = ZKLedgerCurve.Add(comms, gval)
}
}
}
a.mu.Unlock()
gv := ZKLedgerCurve.Neg(ZKLedgerCurve.Mult(ZKLedgerCurve.G, rep.Sum)) // 1 / g^\sum{v_i}
T := ZKLedgerCurve.Add(comms, gv)
// TODO: Error handling
verifies, _ := rep.Eproof.Verify(ZKLedgerCurve, T, rtokens, ZKLedgerCurve.H, a.pki.Get(bank_i))
if !verifies {
Dprintf("[A] Bank %v proof didn't verify! Their total: %v\n", bank_i, rep.Sum)
Dprintf(" My \\sum{rtks_i}: %v\n", rtokens)
Dprintf(" My \\sum{comms_i}: %v\n", comms)
Dprintf(" gv: %v\n", gv)
Dprintf(" T: %v\n", T)
}
return rep.Sum, verifies
}
// Should hold a.mu. OK to call in parallel for different banks.
func (a *Auditor) sumOneBank(wg *sync.WaitGroup, bank_i int, totals []*big.Int, cache bool) {
var rep AuditRep
a.banks[bank_i].Audit(&struct{}{}, &rep)
comms := zksigma.Zero
rtokens := zksigma.Zero
if *useCache && cache {
comms = a.CommsCache[bank_i]
rtokens = a.RTokenCache[bank_i]
} else {
for i := 0; i < len(a.local_ledger.Transactions); i++ {
etx := &a.local_ledger.Transactions[i]
if etx.Type == Transfer {
comms = ZKLedgerCurve.Add(comms, etx.Entries[bank_i].Comm)
rtokens = ZKLedgerCurve.Add(rtokens, etx.Entries[bank_i].RToken)
} else if (etx.Type == Issuance || etx.Type == Withdrawal) && etx.Sender == bank_i {
gval := ZKLedgerCurve.Mult(ZKLedgerCurve.G, etx.Entries[etx.Sender].V)
comms = ZKLedgerCurve.Add(comms, gval)
}
}
}
gv := ZKLedgerCurve.Neg(ZKLedgerCurve.Mult(ZKLedgerCurve.G, rep.Sum)) // 1 / g^\sum{v_i}
T := ZKLedgerCurve.Add(comms, gv)
// TODO: Error handling
verifies, _ := rep.Eproof.Verify(ZKLedgerCurve, T, rtokens, ZKLedgerCurve.H, a.pki.Get(bank_i))
if !verifies {
Dprintf("[A] Bank %v proof didn't verify! Their total: %v\n", bank_i, rep.Sum)
Dprintf(" My \\sum{rtks_i}: %v\n", rtokens)
Dprintf(" My \\sum{comms_i}: %v\n", comms)
Dprintf(" gv: %v\n", gv)
Dprintf(" T: %v\n", T)
}
totals[bank_i] = rep.Sum
wg.Done()
}
func (a *Auditor) Herfindahl(cache bool, _ *struct{}) (*big.Rat, error) {
<-a.Setup
totals := make([]*big.Int, a.num)
total := big.NewInt(0)
concentrations := make([]*big.Rat, a.num)
var wg sync.WaitGroup
a.mu.Lock()
defer a.mu.Unlock()
wg.Add(a.num)
for i := 0; i < a.num; i++ {
go a.sumOneBank(&wg, i, totals, cache)
concentrations[i] = new(big.Rat)
}
wg.Wait()
for i := 0; i < a.num; i++ {
total.Add(total, totals[i])
}
Dprintf("[A] Herfindahl: %v totals, %v total\n", totals, total)
hIndex := big.NewRat(0, 1)
for i := 0; i < a.num; i++ {
marketShare := new(big.Rat).Quo(new(big.Rat).SetInt(totals[i]), new(big.Rat).SetInt(total))
hIndex.Add(hIndex, new(big.Rat).Mul(marketShare, marketShare)) // add the sum of squares of the market share
}
return hIndex, nil
}
// Compute # of asset for a given bank according to unencrypted test
// values in the ledger. ONLY TO BE USED FOR TESTING.
func (a *Auditor) computeClearSum(bank_i int) *big.Int {
total := big.NewInt(0)
for i := 0; i < len(a.local_ledger.Transactions); i++ {
total.Add(total, a.local_ledger.Transactions[i].Entries[bank_i].V)
}
return total
}
// Compute # total outstanding of an asset.
func (a *Auditor) computeOutstanding() *big.Int {
total := big.NewInt(0)
for i := 0; i < a.num; i++ {
v, err := a.computeSum(i)
if !err {
log.Fatalf("Commitments and rvals did not match for bank %v\n", i)
}
total.Add(total, v)
}
return total
}
func (a *Auditor) Audit(_ *struct{}, _ *struct{}) *big.Int {
<-a.Setup
Dprintf("[A] Auditing all banks \n")
return a.computeOutstanding()
}
func (a *Auditor) GetNumTX(_ *struct{}, _ *struct{}) int {
return len(a.local_ledger.Transactions)
}
// X Amount of some risky thing outstanding (outstanding sum)
// X Amount of some risky thing at one bank (sum)
// - Aggregate risk exposures (outstanding sum?)
// X Herfindahl concentration index
// - Aggregate leverage
// - Margin-to-equity ratios
// - Leverage ratios
// - Average correlations between *changes* in securities holdings