-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtoken_chaincode.go
655 lines (561 loc) · 24.5 KB
/
token_chaincode.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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
//Modified from Marbles default contract
package main
import (
"errors"
"fmt"
"strconv"
"encoding/json"
"time"
"strings"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}
var tokenIndexStr = "_tokenindex" //name for the key/value that will store a list of all known tokens
var openTradesStr = "_opentrades" //name for the key/value that will store all open trades
type Token struct{
Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around
Color string `json:"color"`
Size int `json:"size"`
User string `json:"user"`
}
type Description struct{
Color string `json:"color"`
Size int `json:"size"`
}
type AnOpenTrade struct{
User string `json:"user"` //user who created the open trade order
Timestamp int64 `json:"timestamp"` //utc timestamp of creation
Want Description `json:"want"` //description of desired token
Willing []Description `json:"willing"` //array of tokens willing to trade away
}
type AllTrades struct{
OpenTrades []AnOpenTrade `json:"open_trades"`
}
// ============================================================================================================================
// Main
// ============================================================================================================================
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
// ============================================================================================================================
// Init - reset all the things
// ============================================================================================================================
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
var Aval int
var err error
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
// Initialize the chaincode
Aval, err = strconv.Atoi(args[0])
if err != nil {
return nil, errors.New("Expecting integer value for asset holding")
}
// Write the state to the ledger
err = stub.PutState("abc", []byte(strconv.Itoa(Aval))) //making a test var "abc", I find it handy to read/write to it right away to test the network
if err != nil {
return nil, err
}
var empty []string
jsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index
err = stub.PutState(tokenIndexStr, jsonAsBytes)
if err != nil {
return nil, err
}
var trades AllTrades
jsonAsBytes, _ = json.Marshal(trades) //clear the open trade struct
err = stub.PutState(openTradesStr, jsonAsBytes)
if err != nil {
return nil, err
}
return nil, nil
}
// ============================================================================================================================
// Run - Our entry point for Invocations - [LEGACY] obc-peer 4/25/2016
// ============================================================================================================================
func (t *SimpleChaincode) Run(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("run is running " + function)
return t.Invoke(stub, function, args)
}
// ============================================================================================================================
// Invoke - Our entry point for Invocations
// ============================================================================================================================
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("invoke is running " + function)
// Handle different functions
if function == "init" { //initialize the chaincode state, used as reset
return t.Init(stub, "init", args)
} else if function == "delete" { //deletes an entity from its state
res, err := t.Delete(stub, args)
cleanTrades(stub) //lets make sure all open trades are still valid
return res, err
} else if function == "write" { //writes a value to the chaincode state
return t.Write(stub, args)
} else if function == "init_token" { //create a new token
return t.init_token(stub, args)
} else if function == "set_user" { //change owner of a token
res, err := t.set_user(stub, args)
cleanTrades(stub) //lets make sure all open trades are still valid
return res, err
} else if function == "open_trade" { //create a new trade order
return t.open_trade(stub, args)
} else if function == "perform_trade" { //forfill an open trade order
res, err := t.perform_trade(stub, args)
cleanTrades(stub) //lets clean just in case
return res, err
} else if function == "remove_trade" { //cancel an open trade order
return t.remove_trade(stub, args)
}
fmt.Println("invoke did not find func: " + function) //error
return nil, errors.New("Received unknown function invocation")
}
// ============================================================================================================================
// Query - Our entry point for Queries
// ============================================================================================================================
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("query is running " + function)
// Handle different functions
if function == "read" { //read a variable
return t.read(stub, args)
}
fmt.Println("query did not find func: " + function) //error
return nil, errors.New("Received unknown function query")
}
// ============================================================================================================================
// Read - read a variable from chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var name, jsonResp string
var err error
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
}
name = args[0]
valAsbytes, err := stub.GetState(name) //get the var from chaincode state
if err != nil {
jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}"
return nil, errors.New(jsonResp)
}
return valAsbytes, nil //send it onward
}
// ============================================================================================================================
// Delete - remove a key/value pair from state
// ============================================================================================================================
func (t *SimpleChaincode) Delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
name := args[0]
err := stub.DelState(name) //remove the key from chaincode state
if err != nil {
return nil, errors.New("Failed to delete state")
}
//get the token index
tokensAsBytes, err := stub.GetState(tokenIndexStr)
if err != nil {
return nil, errors.New("Failed to get token index")
}
var tokenIndex []string
json.Unmarshal(tokensAsBytes, &tokenIndex) //un stringify it aka JSON.parse()
//remove token from index
for i,val := range tokenIndex{
fmt.Println(strconv.Itoa(i) + " - looking at " + val + " for " + name)
if val == name{ //find the correct token
fmt.Println("found token")
tokenIndex = append(tokenIndex[:i], tokenIndex[i+1:]...) //remove it
for x:= range tokenIndex{ //debug prints...
fmt.Println(string(x) + " - " + tokenIndex[x])
}
break
}
}
jsonAsBytes, _ := json.Marshal(tokenIndex) //save new index
err = stub.PutState(tokenIndexStr, jsonAsBytes)
return nil, nil
}
// ============================================================================================================================
// Write - write variable into chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) Write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var name, value string // Entities
var err error
fmt.Println("running write()")
if len(args) != 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the variable and value to set")
}
name = args[0] //rename for funsies
value = args[1]
err = stub.PutState(name, []byte(value)) //write the variable into the chaincode state
if err != nil {
return nil, err
}
return nil, nil
}
// ============================================================================================================================
// Init Token - create a new token, store into chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) init_token(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1 2 3
// "asdf", "blue", "35", "bob"
if len(args) != 4 {
return nil, errors.New("Incorrect number of arguments. Expecting 4")
}
//input sanitation
fmt.Println("- start init token")
if len(args[0]) <= 0 {
return nil, errors.New("1st argument must be a non-empty string")
}
if len(args[1]) <= 0 {
return nil, errors.New("2nd argument must be a non-empty string")
}
if len(args[2]) <= 0 {
return nil, errors.New("3rd argument must be a non-empty string")
}
if len(args[3]) <= 0 {
return nil, errors.New("4th argument must be a non-empty string")
}
name := args[0]
color := strings.ToLower(args[1])
user := strings.ToLower(args[3])
size, err := strconv.Atoi(args[2])
if err != nil {
return nil, errors.New("3rd argument must be a numeric string")
}
//check if token already exists
tokenAsBytes, err := stub.GetState(name)
if err != nil {
return nil, errors.New("Failed to get token name")
}
res := Token{}
json.Unmarshal(tokenAsBytes, &res)
if res.Name == name{
fmt.Println("This token arleady exists: " + name)
fmt.Println(res);
return nil, errors.New("This token arleady exists") //all stop a token by this name exists
}
//build the token json string manually
str := `{"name": "` + name + `", "color": "` + color + `", "size": ` + strconv.Itoa(size) + `, "user": "` + user + `"}`
err = stub.PutState(name, []byte(str)) //store token with id as key
if err != nil {
return nil, err
}
//get the token index
tokensAsBytes, err := stub.GetState(tokenIndexStr)
if err != nil {
return nil, errors.New("Failed to get token index")
}
var tokenIndex []string
json.Unmarshal(tokensAsBytes, &tokenIndex) //un stringify it aka JSON.parse()
//append
tokenIndex = append(tokenIndex, name) //add token name to index list
fmt.Println("! token index: ", tokenIndex)
jsonAsBytes, _ := json.Marshal(tokenIndex)
err = stub.PutState(tokenIndexStr, jsonAsBytes) //store name of token
fmt.Println("- end init token")
return nil, nil
}
// ============================================================================================================================
// Set User Permission on Token
// ============================================================================================================================
func (t *SimpleChaincode) set_user(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1
// "name", "bob"
if len(args) < 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2")
}
fmt.Println("- start set user")
fmt.Println(args[0] + " - " + args[1])
tokenAsBytes, err := stub.GetState(args[0])
if err != nil {
return nil, errors.New("Failed to get thing")
}
res := Token{}
json.Unmarshal(tokenAsBytes, &res) //un stringify it aka JSON.parse()
res.User = args[1] //change the user
jsonAsBytes, _ := json.Marshal(res)
err = stub.PutState(args[0], jsonAsBytes) //rewrite the token with id as key
if err != nil {
return nil, err
}
fmt.Println("- end set user")
return nil, nil
}
// ============================================================================================================================
// Open Trade - create an open trade for a token you want with tokens you have
// ============================================================================================================================
func (t *SimpleChaincode) open_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
var will_size int
var trade_away Description
// 0 1 2 3 4 5 6
//["bob", "blue", "16", "red", "16"] *"blue", "35*
if len(args) < 5 {
return nil, errors.New("Incorrect number of arguments. Expecting like 5?")
}
if len(args)%2 == 0{
return nil, errors.New("Incorrect number of arguments. Expecting an odd number")
}
size1, err := strconv.Atoi(args[2])
if err != nil {
return nil, errors.New("3rd argument must be a numeric string")
}
open := AnOpenTrade{}
open.User = args[0]
open.Timestamp = makeTimestamp() //use timestamp as an ID
open.Want.Color = args[1]
open.Want.Size = size1
fmt.Println("- start open trade")
jsonAsBytes, _ := json.Marshal(open)
err = stub.PutState("_debug1", jsonAsBytes)
for i:=3; i < len(args); i++ { //create and append each willing trade
will_size, err = strconv.Atoi(args[i + 1])
if err != nil {
msg := "is not a numeric string " + args[i + 1]
fmt.Println(msg)
return nil, errors.New(msg)
}
trade_away = Description{}
trade_away.Color = args[i]
trade_away.Size = will_size
fmt.Println("! created trade_away: " + args[i])
jsonAsBytes, _ = json.Marshal(trade_away)
err = stub.PutState("_debug2", jsonAsBytes)
open.Willing = append(open.Willing, trade_away)
fmt.Println("! appended willing to open")
i++;
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
trades.OpenTrades = append(trades.OpenTrades, open); //append to open trades
fmt.Println("! appended open to trades")
jsonAsBytes, _ = json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
fmt.Println("- end open trade")
return nil, nil
}
// ============================================================================================================================
// Perform Trade - close an open trade and move ownership
// ============================================================================================================================
func (t *SimpleChaincode) perform_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1 2 3 4 5
//[data.id, data.closer.user, data.closer.name, data.opener.user, data.opener.color, data.opener.size]
if len(args) < 6 {
return nil, errors.New("Incorrect number of arguments. Expecting 6")
}
fmt.Println("- start close trade")
timestamp, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return nil, errors.New("1st argument must be a numeric string")
}
size, err := strconv.Atoi(args[5])
if err != nil {
return nil, errors.New("6th argument must be a numeric string")
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
for i := range trades.OpenTrades{ //look for the trade
fmt.Println("looking at " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10) + " for " + strconv.FormatInt(timestamp, 10))
if trades.OpenTrades[i].Timestamp == timestamp{
fmt.Println("found the trade");
tokenAsBytes, err := stub.GetState(args[2])
if err != nil {
return nil, errors.New("Failed to get thing")
}
closersToken := Token{}
json.Unmarshal(tokenAsBytes, &closersToken) //un stringify it aka JSON.parse()
//verify if token meets trade requirements
if closersToken.Color != trades.OpenTrades[i].Want.Color || closersToken.Size != trades.OpenTrades[i].Want.Size {
msg := "token in input does not meet trade requriements"
fmt.Println(msg)
return nil, errors.New(msg)
}
token, e := findToken4Trade(stub, trades.OpenTrades[i].User, args[4], size) //find a token that is suitable from opener
if(e == nil){
fmt.Println("! no errors, proceeding")
t.set_user(stub, []string{args[2], trades.OpenTrades[i].User}) //change owner of selected token, closer -> opener
t.set_user(stub, []string{token.Name, args[1]}) //change owner of selected token, opener -> closer
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove trade
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
}
}
}
fmt.Println("- end close trade")
return nil, nil
}
// ============================================================================================================================
// findToken4Trade - look for a matching token that this user owns and return it
// ============================================================================================================================
func findToken4Trade(stub shim.ChaincodeStubInterface, user string, color string, size int )(m Token, err error){
var fail Token;
fmt.Println("- start find token 4 trade")
fmt.Println("looking for " + user + ", " + color + ", " + strconv.Itoa(size));
//get the token index
tokensAsBytes, err := stub.GetState(tokenIndexStr)
if err != nil {
return fail, errors.New("Failed to get token index")
}
var tokenIndex []string
json.Unmarshal(tokensAsBytes, &tokenIndex) //un stringify it aka JSON.parse()
for i:= range tokenIndex{ //iter through all the tokens
//fmt.Println("looking @ token name: " + tokenIndex[i]);
tokenAsBytes, err := stub.GetState(tokenIndex[i]) //grab this token
if err != nil {
return fail, errors.New("Failed to get token")
}
res := Token{}
json.Unmarshal(tokenAsBytes, &res) //un stringify it aka JSON.parse()
//fmt.Println("looking @ " + res.User + ", " + res.Color + ", " + strconv.Itoa(res.Size));
//check for user && color && size
if strings.ToLower(res.User) == strings.ToLower(user) && strings.ToLower(res.Color) == strings.ToLower(color) && res.Size == size{
fmt.Println("found a token: " + res.Name)
fmt.Println("! end find token 4 trade")
return res, nil
}
}
fmt.Println("- end find token 4 trade - error")
return fail, errors.New("Did not find token to use in this trade")
}
// ============================================================================================================================
// Make Timestamp - create a timestamp in ms
// ============================================================================================================================
func makeTimestamp() int64 {
return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}
// ============================================================================================================================
// Remove Open Trade - close an open trade
// ============================================================================================================================
func (t *SimpleChaincode) remove_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0
//[data.id]
if len(args) < 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
fmt.Println("- start remove trade")
timestamp, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return nil, errors.New("1st argument must be a numeric string")
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
for i := range trades.OpenTrades{ //look for the trade
//fmt.Println("looking at " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10) + " for " + strconv.FormatInt(timestamp, 10))
if trades.OpenTrades[i].Timestamp == timestamp{
fmt.Println("found the trade");
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove this trade
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
break
}
}
fmt.Println("- end remove trade")
return nil, nil
}
// ============================================================================================================================
// Clean Up Open Trades - make sure open trades are still possible, remove choices that are no longer possible, remove trades that have no valid choices
// ============================================================================================================================
func cleanTrades(stub shim.ChaincodeStubInterface)(err error){
var didWork = false
fmt.Println("- start clean trades")
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
fmt.Println("# trades " + strconv.Itoa(len(trades.OpenTrades)))
for i:=0; i<len(trades.OpenTrades); { //iter over all the known open trades
fmt.Println(strconv.Itoa(i) + ": looking at trade " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10))
fmt.Println("# options " + strconv.Itoa(len(trades.OpenTrades[i].Willing)))
for x:=0; x<len(trades.OpenTrades[i].Willing); { //find a token that is suitable
fmt.Println("! on next option " + strconv.Itoa(i) + ":" + strconv.Itoa(x))
_, e := findToken4Trade(stub, trades.OpenTrades[i].User, trades.OpenTrades[i].Willing[x].Color, trades.OpenTrades[i].Willing[x].Size)
if(e != nil){
fmt.Println("! errors with this option, removing option")
didWork = true
trades.OpenTrades[i].Willing = append(trades.OpenTrades[i].Willing[:x], trades.OpenTrades[i].Willing[x+1:]...) //remove this option
x--;
}else{
fmt.Println("! this option is fine")
}
x++
fmt.Println("! x:" + strconv.Itoa(x))
if x >= len(trades.OpenTrades[i].Willing) { //things might have shifted, recalcuate
break
}
}
if len(trades.OpenTrades[i].Willing) == 0 {
fmt.Println("! no more options for this trade, removing trade")
didWork = true
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove this trade
i--;
}
i++
fmt.Println("! i:" + strconv.Itoa(i))
if i >= len(trades.OpenTrades) { //things might have shifted, recalcuate
break
}
}
if(didWork){
fmt.Println("! saving open trade changes")
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return err
}
}else{
fmt.Println("! all open trades are fine")
}
fmt.Println("- end clean trades")
return nil
}