-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgridlock.go
More file actions
393 lines (357 loc) · 12.4 KB
/
gridlock.go
File metadata and controls
393 lines (357 loc) · 12.4 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package main
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"github.com/blockchain-research/gridlock/account"
"github.com/blockchain-research/gridlock/common"
"github.com/blockchain-research/gridlock/crypto/bn256"
"github.com/blockchain-research/gridlock/message"
"github.com/blockchain-research/gridlock/pedersengroup"
pb "github.com/blockchain-research/gridlock/proto"
"github.com/blockchain-research/gridlock/settlement"
"github.com/blockchain-research/gridlock/zkrangeproof"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/core/chaincode/shim"
pr "github.com/hyperledger/fabric/protos/peer"
)
var logger = shim.NewLogger("gridlock")
var pedersenParams pedersengroup.PedersenParams
// Gridlock struct
type Gridlock struct {
}
// Init function
func (t *Gridlock) Init(stub shim.ChaincodeStubInterface) pr.Response {
logger.Info("Init Gridlock Protocol chaincode")
return shim.Success(nil)
}
// Invoke function
func (t *Gridlock) Invoke(stub shim.ChaincodeStubInterface) pr.Response {
function, args := stub.GetFunctionAndParameters()
var result []byte
var err error
switch function {
case "initParams":
logger.Info("initParams")
err = t.initParams(stub, args)
case "mintAccount":
logger.Info("mintAccount")
err = account.MintAccount(stub, args)
case "addMessage":
logger.Info("addMessage")
err = message.AddMessage(stub, args)
case "grossSettlement":
logger.Info("grossSettlement")
err = settlement.GrossSettlement(stub, args)
case "startGLResolution":
logger.Info("startGLResolution")
err = t.startGLResolution(stub, args)
case "proposeNettableSet":
logger.Info("proposeNettableSet")
err = t.proposeNettableSet(stub, args)
case "tallyGridlockProposal":
logger.Info("tallyGridlockProposal")
err = t.tallyGridlockProposal(stub, args)
case "NetGLSettlement":
logger.Info("NetGLSettlement")
err = settlement.NetGLSettlement(stub, args)
default:
logger.Error(fmt.Sprintf("Invalid invocation function %s", function))
err = fmt.Errorf("Invalid invocation function %s", function)
}
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(result)
}
func (t *Gridlock) initPedersenGroup(stub shim.ChaincodeStubInterface, args []string) error {
if len(args) != 1 {
return errors.New("Need exactly one argument: <base64-encoded-pedersengroupmessage-object>")
}
pedersenToStoreBytes, err := base64.StdEncoding.DecodeString(args[0])
if err != nil {
logger.Error("Failed to base64-decode protobuf-encoded pedersengroup")
return err
}
err = stub.PutState(common.PedersenTable+"_GROUP", pedersenToStoreBytes)
if err != nil {
logger.Errorf("Failed to add to ledger")
return err
}
return nil
}
func (t *Gridlock) initParams(stub shim.ChaincodeStubInterface, args []string) error {
if len(args) != 1 {
return errors.New("Need exactly one argument: <base64-encoded-object>")
}
paramsToStoreBytes, err := base64.StdEncoding.DecodeString(args[0])
if err != nil {
logger.Error("Failed to base64-decode protobuf-encoded pedersencurve")
return err
}
err = stub.PutState(common.PedersenTable+"_CURVE", paramsToStoreBytes)
if err != nil {
logger.Errorf("Failed to add to ledger")
return err
}
return nil
}
func (t *Gridlock) startGLResolution(stub shim.ChaincodeStubInterface, args []string) error {
if len(args) != 1 {
return errors.New("Need exactly one argument: <base64-encoded-object>")
}
configBytes, err := base64.StdEncoding.DecodeString(args[0])
if err != nil {
logger.Error("Failed to base64-decode protobuf-encoded glr configuration")
return err
}
config := &pb.GLRConfiguration{}
err = proto.Unmarshal(configBytes, config)
if err != nil {
logger.Error("Failed to unmarshal glr configuration")
return err
}
//add GLR configuration to the ledger
err = common.AddGLRConfigurationToLedger(stub, common.ConfigTable+fmt.Sprint(config.GridlockId), config)
if err != nil {
return err
}
return nil
}
func (t *Gridlock) proposeNettableSet(stub shim.ChaincodeStubInterface, args []string) error {
if len(args) != 1 {
return errors.New("Need exactly one argument: <base64-encoded-object>")
}
proposalBytes, err := base64.StdEncoding.DecodeString(args[0])
if err != nil {
logger.Error("Failed to base64-decode protobuf-encoded gridlockproposal")
return err
}
proposal := &pb.GridlockProposal{}
err = proto.Unmarshal(proposalBytes, proposal)
if err != nil {
logger.Error("Failed to unmarshal gridlockProposal")
return err
}
//verify gridlock proposal
success, err := t.verifyGridlockProposal(stub, proposal)
if err != nil {
return err
}
if success != true {
logger.Error("Verification of gridlock proposal failed")
return errors.New("Verification of gridlock proposal failed")
}
//add the gridlock proposal to the ledger
err = common.AddGridlockProposalToLedger(
stub,
common.ProposalTable+fmt.Sprint(proposal.GridlockId)+fmt.Sprint(proposal.BankId),
&pb.StoredGridlockProposal{
OutgoingIds: proposal.OutgoingIds,
InfeasibleIds: proposal.InfeasibleIds,
CmBalance: proposal.CmBalance,
Zkrp1: proposal.Zkrp1,
Zkrp2: proposal.Zkrp2,
})
return nil
}
func (t *Gridlock) tallyGridlockProposal(stub shim.ChaincodeStubInterface, args []string) error {
if len(args) != 1 {
return errors.New("Need exactly one argument: <base64-encoded-object>")
}
tallyBytes, err := base64.StdEncoding.DecodeString(args[0])
if err != nil {
logger.Error("Failed to base64-decode protobuf-encoded tally proposal")
return err
}
tally := &pb.TallyGridlockProposal{}
err = proto.Unmarshal(tallyBytes, tally)
if err != nil {
logger.Error("Failed to unmarshal TallyGridlockProposal")
return err
}
config, err := common.GetGLRConfigFromLedger(stub, common.ConfigTable+fmt.Sprint(tally.GridlockId))
if config.Status != pb.GLRStatusType_START {
logger.Error("wrong state of current glr")
return errors.New("wrong state of current glr")
}
infeasibleObj, err := common.GetQueueFromLedger(stub, common.InfeasibleTable+fmt.Sprint(tally.GridlockId))
if err != nil {
logger.Error("Failed to read infeasible from ledger")
return err
}
logger.Info(infeasibleObj)
infeasible := []int32{}
for _, id := range config.BankIds {
proposal, err := common.GetGridlockProposalFromLedger(
stub,
common.ProposalTable+fmt.Sprint(tally.GridlockId)+fmt.Sprint(id),
)
if err != nil {
return err
}
infeasible = append(infeasible, proposal.InfeasibleIds...)
}
logger.Info(infeasible)
//add infeasible to the ledger
err = common.AddQueueToLedger(
stub,
common.InfeasibleTable+fmt.Sprint(tally.GridlockId),
&pb.StoredPaymentQueue{PaymentIds: infeasible},
)
if err != nil {
return err
}
//check if infeasible is unchanged, mark it as SUCCESS
if len(infeasible) == len(infeasibleObj.PaymentIds) {
logger.Info("Converged, the gridlock resolution is successful")
config.Status = pb.GLRStatusType_SUCCESS
err = common.AddGLRConfigurationToLedger(stub, common.ConfigTable+fmt.Sprint(config.GridlockId), config)
if err != nil {
return err
}
}
return nil
}
//verifyGridlockProposal verifies the zkrp1 of cmBalance-outgoing+incoming >=0
//zkrp2 of -(cmBalance-outgoing-highestInfeasible) >=0
func (t *Gridlock) verifyGridlockProposal(stub shim.ChaincodeStubInterface, proposal *pb.GridlockProposal) (bool, error) {
//check whether the BankId is in the config table
config, err := common.GetGLRConfigFromLedger(stub, common.ConfigTable+fmt.Sprint(proposal.GridlockId))
if config.Status != pb.GLRStatusType_START {
logger.Info("wrong state of current glr")
return false, nil
}
isValidBankId := false
for _, id := range config.BankIds {
if id == proposal.BankId {
isValidBankId = true
break
}
}
if isValidBankId == false {
logger.Error("Invalid bankId ", proposal.BankId)
return false, nil
}
//verify the priority is reserved for OutgoingIds
success, err := settlement.VerifyStrictPriority(stub, proposal.BankId, proposal.OutgoingIds)
if err != nil {
return false, err
}
if success != true {
logger.Error("Priority order is not reserved")
return false, errors.New("Priority order is not reserved")
}
//get stored params
paramsUL, err := common.GetParamsFromLedger(stub)
if err != nil {
logger.Error("Failed to read parameters from ledger")
return false, err
}
//get current bank balance and check it is the same as CmBalance in the settlementSet
account, err := common.GetAccountFromLedger(stub, common.AccountTable+fmt.Sprint(proposal.BankId))
if err != nil {
logger.Error("Failed to read account from ledger")
return false, err
}
if bytes.Compare(account.CmBalance, proposal.CmBalance) != 0 {
logger.Error("The cmBalance in account from ledger is different from the cmBalance in proposal")
return false, nil
}
//calculate the post-balance commitment = cmBalance - outgoing cmAmount + incoming payment not in infeasible set
infeasible, err := common.GetQueueFromLedger(stub, common.InfeasibleTable+fmt.Sprint(proposal.GridlockId))
if err != nil {
logger.Error("Failed to read infeasible from ledger")
return false, err
}
cmSum, _ := new(bn256.G2).Unmarshal(account.CmBalance)
//add all payments in the incoming queue excluding those in infeasible
inQueue, err := common.GetQueueFromLedger(stub, common.InQueueTable+fmt.Sprint(proposal.BankId))
if err != nil {
logger.Error("Failed to read inQueue from ledger")
return false, err
}
for _, id := range inQueue.PaymentIds {
isFeasible := true
for _, infeasibleId := range infeasible.PaymentIds {
if id == infeasibleId {
isFeasible = false
}
}
if isFeasible == true {
payment, err := common.GetPaymentFromLedger(stub, common.MessageTable+fmt.Sprint(id))
if err != nil {
return false, err
}
cmAmount, _ := new(bn256.G2).Unmarshal(payment.CmAmount)
cmSum = new(bn256.G2).Add(cmSum, cmAmount)
}
}
//subscract those outgoing payments from proposal.OutgoingIds
for _, id := range proposal.OutgoingIds {
payment, err := common.GetPaymentFromLedger(stub, common.MessageTable+fmt.Sprint(id))
if err != nil {
return false, err
}
cmAmount, _ := new(bn256.G2).Unmarshal(payment.CmAmount)
cmSum = new(bn256.G2).Add(cmSum, new(bn256.G2).Neg(cmAmount))
}
//check that cmSum's range proof: zkrp1
proof1 := new(zkrangeproof.ProofULVerifier).Unmarshal(proposal.Zkrp1, common.L)
//verify the committed value in the proof is the same as cmBalance-outgoing cmAmount
logger.Info("checking zkrp1")
if bytes.Compare(proof1.C.Marshal(), cmSum.Marshal()) != 0 {
logger.Error("The committed values does not match the one in the proof")
return false, nil
}
//verify the range proof
result, _ := zkrangeproof.VerifyUL(proof1, *paramsUL)
if result != true {
logger.Error("The zero knowledge range proof verification failed. The committed value in receiving amount is not within range.")
return false, errors.New("ZKP verification failed")
}
logger.Info("The committed post balance after settling all outgoingIds is whtin range (0,u^l)")
//calculate cmSum-smallestPidFromInfeasible
if len(proposal.InfeasibleIds) == 0 {
logger.Info("No infeasible set, no need to verify zkrp2")
return true, nil
}
logger.Info("checking zkrp2")
smallest := proposal.InfeasibleIds[0]
for _, id := range proposal.InfeasibleIds {
if smallest > id {
smallest = id
}
}
//subscract the amount of smallest id from cmSum
payment, err := common.GetPaymentFromLedger(stub, common.MessageTable+fmt.Sprint(smallest))
if err != nil {
return false, err
}
cmAmount, _ := new(bn256.G2).Unmarshal(payment.CmAmount)
cmSum = new(bn256.G2).Add(cmSum, new(bn256.G2).Neg(cmAmount))
cmSumNeg := new(bn256.G2).Neg(cmSum)
//check new NegcmSum's range proof: zkrp2
proof2 := new(zkrangeproof.ProofULVerifier).Unmarshal(proposal.Zkrp2, common.L)
//verify the committed value in the proof is the same as cmBalance-outgoing cmAmount
if bytes.Compare(proof2.C.Marshal(), cmSumNeg.Marshal()) != 0 {
logger.Error("The committed values does not match the one in the proof")
return false, nil
}
//verify the range proof
result, _ = zkrangeproof.VerifyUL(proof2, *paramsUL)
if result != true {
logger.Error("The zero knowledge range proof verification failed. The committed value is not within range.")
return false, errors.New("ZKP verification failed")
}
logger.Info("The neg committed post balance after settling all outgoingIds+smallest infeasible id is whtin range (0,u^l)")
return true, nil
}
// main function
func main() {
err := shim.Start(new(Gridlock))
if err != nil {
logger.Errorf("Error starting Gridlock: %s", err)
}
}