forked from ITPeople-Blockchain/auction
-
Notifications
You must be signed in to change notification settings - Fork 0
/
art_app_bmixv21.070216.go
2946 lines (2441 loc) · 104 KB
/
art_app_bmixv21.070216.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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************
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.
******************************************************************/
///////////////////////////////////////////////////////////////////////
// Author : Mohan Venkataraman
// Purpose: Explore the Hyperledger/fabric and understand
// how to write an chain code, application/chain code boundaries
// The code is not the best as it has just hammered out in a day or two
// Feedback and updates are appreciated
///////////////////////////////////////////////////////////////////////
package main
import (
"bufio"
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
//"github.com/op/go-logging"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
// "github.com/errorpkg"
)
//////////////////////////////////////////////////////////////////////////////////////////////////
// The recType is a mandatory attribute. The original app was written with a single table
// in mind. The only way to know how to process a record was the 70's style 80 column punch card
// which used a record type field. The array below holds a list of valid record types.
// This could be stored on a blockchain table or an application
//////////////////////////////////////////////////////////////////////////////////////////////////
var recType = []string{"ARTINV", "USER", "BID", "AUCREQ", "POSTTRAN", "OPENAUC", "CLAUC", "XFER"}
//////////////////////////////////////////////////////////////////////////////////////////////////
// The following array holds the list of tables that should be created
// The deploy/init deletes the tables and recreates them every time a deploy is invoked
//////////////////////////////////////////////////////////////////////////////////////////////////
var aucTables = []string{"UserTable", "UserCatTable", "ItemTable", "ItemCatTable", "ItemHistoryTable", "AuctionTable", "AucInitTable", "AucOpenTable", "BidTable", "TransTable"}
///////////////////////////////////////////////////////////////////////////////////////
// This creates a record of the Asset (Inventory)
// Includes Description, title, certificate of authenticity or image whatever..idea is to checkin a image and store it
// in encrypted form
// Example:
// Item { 113869, "Flower Urn on a Patio", "Liz Jardine", "10102007", "Original", "Floral", "Acrylic", "15 x 15 in", "sample_9.png","$600", "My Gallery }
///////////////////////////////////////////////////////////////////////////////////////
type ItemObject struct {
ItemID string
RecType string
ItemDesc string
ItemDetail string // Could included details such as who created the Art work if item is a Painting
ItemDate string
ItemType string
ItemSubject string
ItemMedia string
ItemSize string
ItemPicFN string
ItemImage []byte // This has to be generated AES encrypted using the file name
AES_Key []byte // This is generated by the AES Algorithms
ItemImageType string // should be used to regenerate the appropriate image type
ItemBasePrice string // Reserve Price at Auction must be greater than this price
CurrentOwnerID string // This is validated for a user registered record
}
////////////////////////////////////////////////////////////////////////////////
// Has an item entry every time the item changes hands
////////////////////////////////////////////////////////////////////////////////
type ItemLog struct {
ItemID string // PRIMARY KEY
Status string // SECONDARY KEY - OnAuc, OnSale, NA
AuctionedBy string // SECONDARY KEY - Auction House ID if applicable
RecType string // ITEMHIS
ItemDesc string
CurrentOwner string
Date string // Date when status changed
}
/////////////////////////////////////////////////////////////
// Create Buyer, Seller , Auction House, Authenticator
// Could establish valid UserTypes -
// AH (Auction House)
// TR (Buyer or Seller)
// AP (Appraiser)
// IN (Insurance)
// BK (bank)
// SH (Shipper)
/////////////////////////////////////////////////////////////
type UserObject struct {
UserID string
RecType string // Type = USER
Name string
UserType string // Auction House (AH), Bank (BK), Buyer or Seller (TR), Shipper (SH), Appraiser (AP)
Address string
Phone string
Email string
Bank string
AccountNo string
RoutingNo string
}
/////////////////////////////////////////////////////////////////////////////
// Register a request for participating in an auction
// Usually posted by a seller who owns a piece of ITEM
// The Auction house will determine when to open the item for Auction
// The Auction House may conduct an appraisal and genuineness of the item
/////////////////////////////////////////////////////////////////////////////
type AuctionRequest struct {
AuctionID string
RecType string // AUCREQ
ItemID string
AuctionHouseID string // ID of the Auction House managing the auction
SellerID string // ID Of Seller - to verified against the Item CurrentOwnerId
RequestDate string // Date on which Auction Request was filed
ReservePrice string // reserver price > previous purchase price
BuyItNowPrice string // 0 (Zero) if not applicable else specify price
Status string // INIT, OPEN, CLOSED (To be Updated by Trgger Auction)
OpenDate string // Date on which auction will occur (To be Updated by Trigger Auction)
CloseDate string // Date and time when Auction will close (To be Updated by Trigger Auction)
}
/////////////////////////////////////////////////////////////
// POST the transaction after the Auction Completes
// Post an Auction Transaction
// Post an Updated Item Object
// Once an auction request is opened for auctions, a timer is kicked
// off and bids are accepted. When the timer expires, the highest bid
// is selected and converted into a Transaction
// This transaction is a simple view
/////////////////////////////////////////////////////////////
type ItemTransaction struct {
AuctionID string
RecType string // POSTTRAN
ItemID string
TransType string // Sale, Buy, Commission
UserId string // Buyer or Seller ID
TransDate string // Date of Settlement (Buyer or Seller)
HammerTime string // Time of hammer strike - SOLD
HammerPrice string // Total Settlement price
Details string // Details about the Transaction
}
////////////////////////////////////////////////////////////////
// This is a Bid. Bids are accepted only if an auction is OPEN
////////////////////////////////////////////////////////////////
type Bid struct {
AuctionID string
RecType string // BID
BidNo string
ItemID string
BuyerID string // ID Of Buyer - to be verified against the Item CurrentOwnerId
BidPrice string // BidPrice > Previous Bid
BidTime string // Time the bid was received
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// A Map that holds TableNames and the number of Keys
// This information is used to dynamically Create, Update
// Replace , and Query the Ledger
// In this model all attributes in a table are strings
// The chain code does both validation
// A dummy key like 2016 in some cases is used for a query to get all rows
//
// "UserTable": 1, Key: UserID
// "ItemTable": 1, Key: ItemID
// "UserCatTable": 3, Key: "2016", UserType, UserID
// "ItemCatTable": 3, Key: "2016", ItemSubject, ItemID
// "AuctionTable": 1, Key: AuctionID
// "AucInitTable": 2, Key: Year, AuctionID
// "AucOpenTable": 2, Key: Year, AuctionID
// "TransTable": 2, Key: AuctionID, ItemID
// "BidTable": 2, Key: AuctionID, BidNo
// "ItemHistoryTable": 4, Key: ItemID, Status, AuctionHouseID(if applicable),date-time
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
func GetNumberOfKeys(tname string) int {
TableMap := map[string]int{
"UserTable": 1,
"ItemTable": 1,
"UserCatTable": 3,
"ItemCatTable": 3,
"AuctionTable": 1,
"AucInitTable": 2,
"AucOpenTable": 2,
"TransTable": 2,
"BidTable": 2,
"ItemHistoryTable": 4,
}
return TableMap[tname]
}
//////////////////////////////////////////////////////////////
// Invoke Functions based on Function name
// The function name gets resolved to one of the following calls
// during an invoke
//
//////////////////////////////////////////////////////////////
func InvokeFunction(fname string) func(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
InvokeFunc := map[string]func(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error){
"PostItem": PostItem,
"PostUser": PostUser,
"PostAuctionRequest": PostAuctionRequest,
"PostTransaction": PostTransaction,
"PostBid": PostBid,
"OpenAuctionForBids": OpenAuctionForBids,
"BuyItNow": BuyItNow,
"TransferItem": TransferItem,
"CloseAuction": CloseAuction,
"CloseOpenAuctions": CloseOpenAuctions,
}
return InvokeFunc[fname]
}
//////////////////////////////////////////////////////////////
// Query Functions based on Function name
//
//////////////////////////////////////////////////////////////
func QueryFunction(fname string) func(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
QueryFunc := map[string]func(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error){
"GetItem": GetItem,
"GetUser": GetUser,
"GetAuctionRequest": GetAuctionRequest,
"GetTransaction": GetTransaction,
"GetBid": GetBid,
"GetLastBid": GetLastBid,
"GetHighestBid": GetHighestBid,
"GetNoOfBidsReceived": GetNoOfBidsReceived,
"GetListOfBids": GetListOfBids,
"GetItemLog": GetItemLog,
"GetItemListByCat": GetItemListByCat,
"GetUserListByCat": GetUserListByCat,
"GetListOfInitAucs": GetListOfInitAucs,
"GetListOfOpenAucs": GetListOfOpenAucs,
"ValidateItemOwnership": ValidateItemOwnership,
}
return QueryFunc[fname]
}
//var myLogger = logging.MustGetLogger("auction_trading")
type SimpleChaincode struct {
}
var gopath string
var ccPath string
////////////////////////////////////////////////////////////////////////////////
// Chain Code Kick-off Main function
////////////////////////////////////////////////////////////////////////////////
func main() {
// maximize CPU usage for maximum performance
runtime.GOMAXPROCS(runtime.NumCPU())
fmt.Println("Starting Item Auction Application chaincode BlueMix ver 21 Dated 2016-07-02 09.45.00: ")
gopath = os.Getenv("GOPATH")
ccPath = fmt.Sprintf("%s/src/github.com/ITPeople-Blockchain/auction/art/artchaincode/", gopath)
//ccPath = fmt.Sprintf("%s/src/github.com/hyperledger/fabric/examples/chaincode/go/artfun/", gopath)
// Start the shim -- running the fabric
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Println("Error starting Item Fun Application chaincode: %s", err)
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SimpleChaincode - Init Chaincode implementation - The following sequence of transactions can be used to test the Chaincode
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
// TODO - Include all initialization to be complete before Invoke and Query
// Uses aucTables to delete tables if they exist and re-create them
//myLogger.Info("[Trade and Auction Application] Init")
fmt.Println("[Trade and Auction Application] Init")
var err error
for _, val := range aucTables {
err = stub.DeleteTable(val)
if err != nil {
return nil, fmt.Errorf("Init(): DeleteTable of %s Failed ", val)
}
err = InitLedger(stub, val)
if err != nil {
return nil, fmt.Errorf("Init(): InitLedger of %s Failed ", val)
}
}
fmt.Println("Init() Initialization Complete : ", args)
return []byte("Init(): Initialization Complete"), nil
}
////////////////////////////////////////////////////////////////
// SimpleChaincode - INVOKE Chaincode implementation
// User Can Invoke
// - Register a user using PostUser
// - Register an item using PostItem
// - The Owner of the item (User) can request that the item be put on auction using PostAuctionRequest
// - The Auction House can request that the auction request be Opened for bids using OpenAuctionForBids
// - One the auction is OPEN, registered buyers (Buyers) can send in bids vis PostBid
// - No bid is accepted when the status of the auction request is INIT or CLOSED
// - Either manually or by OpenAuctionRequest, the auction can be closed using CloseAuction
// - The CloseAuction creates a transaction and invokes PostTransaction
////////////////////////////////////////////////////////////////
func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var err error
var buff []byte
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Check Type of Transaction and apply business rules
// before adding record to the block chain
// In this version, the assumption is that args[1] specifies recType for all defined structs
// Newer structs - the recType can be positioned anywhere and ChkReqType will check for recType
// example:
// ./peer chaincode invoke -l golang -n mycc -c '{"Function": "PostBid", "Args":["1111", "BID", "1", "1000", "300", "1200"]}'
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if ChkReqType(args) == true {
InvokeRequest := InvokeFunction(function)
if InvokeRequest != nil {
buff, err = InvokeRequest(stub, function, args)
}
} else {
fmt.Println("Invoke() Invalid recType : ", args, "\n")
return nil, errors.New("Invoke() : Invalid recType : " + args[0])
}
return buff, err
}
//////////////////////////////////////////////////////////////////////////////////////////
// SimpleChaincode - QUERY Chaincode implementation
// Client Can Query
// Sample Data
// ./peer chaincode query -l golang -n mycc -c '{"Function": "GetUser", "Args": ["4000"]}'
// ./peer chaincode query -l golang -n mycc -c '{"Function": "GetItem", "Args": ["2000"]}'
//////////////////////////////////////////////////////////////////////////////////////////
func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var err error
var buff []byte
fmt.Println("ID Extracted and Type = ", args[0])
fmt.Println("Args supplied : ", args)
if len(args) < 1 {
fmt.Println("Query() : Include at least 1 arguments Key ")
return nil, errors.New("Query() : Expecting Transation type and Key value for query")
}
QueryRequest := QueryFunction(function)
if QueryRequest != nil {
buff, err = QueryRequest(stub, function, args)
} else {
fmt.Println("Query() Invalid function call : ", function)
return nil, errors.New("Query() : Invalid function call : " + function)
}
if err != nil {
fmt.Println("Query() Object not found : ", args[0])
return nil, errors.New("Query() : Object not found : " + args[0])
}
return buff, err
}
//////////////////////////////////////////////////////////////////////////////////////////
// Retrieve User Information
// example:
// ./peer chaincode query -l golang -n mycc -c '{"Function": "GetUser", "Args": ["100"]}'
//
//////////////////////////////////////////////////////////////////////////////////////////
func GetUser(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var err error
// Get the Object and Display it
Avalbytes, err := QueryLedger(stub, "UserTable", args)
if err != nil {
fmt.Println("GetUser() : Failed to Query Object ")
jsonResp := "{\"Error\":\"Failed to get Object Data for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
if Avalbytes == nil {
fmt.Println("GetUser() : Incomplete Query Object ")
jsonResp := "{\"Error\":\"Incomplete information about the key for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
fmt.Println("GetUser() : Response : Successfull -")
return Avalbytes, nil
}
/////////////////////////////////////////////////////////////////////////////////////////
// Query callback representing the query of a chaincode
// Retrieve a Item by Item ID
// ./peer chaincode query -l golang -n mycc -c '{"Function": "GetItem", "Args": ["1000"]}'
/////////////////////////////////////////////////////////////////////////////////////////
func GetItem(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var err error
// Get the Objects and Display it
Avalbytes, err := QueryLedger(stub, "ItemTable", args)
if err != nil {
fmt.Println("GetItem() : Failed to Query Object ")
jsonResp := "{\"Error\":\"Failed to get Object Data for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
if Avalbytes == nil {
fmt.Println("GetItem() : Incomplete Query Object ")
jsonResp := "{\"Error\":\"Incomplete information about the key for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
fmt.Println("GetItem() : Response : Successfull ")
return Avalbytes, nil
}
/////////////////////////////////////////////////////////////////////////////////////////
// Validates The Ownership of an Asset using ItemID, OwnerID, and HashKey
//
// ./peer chaincode query -l golang -n mycc -c '{"Function": "ValidateItemOwnership", "Args": ["1000", "100", "tGEBaZuKUBmwTjzNEyd+nr/fPUASuVJAZ1u7gha5fJg="]}'
//
/////////////////////////////////////////////////////////////////////////////////////////
func ValidateItemOwnership(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var err error
if len(args) < 3 {
fmt.Println("ValidateItemOwnership() : Requires 3 arguments Item#, Owner# and Key ")
return nil, errors.New("ValidateItemOwnership() : Requires 3 arguments Item#, Owner# and Key")
}
// Get the Object Information
Avalbytes, err := QueryLedger(stub, "ItemTable", []string{args[0]})
if err != nil {
fmt.Println("ValidateItemOwnership() : Failed to Query Object ")
jsonResp := "{\"Error\":\"Failed to get Object Data for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
if Avalbytes == nil {
fmt.Println("ValidateItemOwnership() : Incomplete Query Object ")
jsonResp := "{\"Error\":\"Incomplete information about the key for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
myItem, err := JSONtoAR(Avalbytes)
if err != nil {
fmt.Println("ValidateItemOwnership() : Failed to Query Object ")
jsonResp := "{\"Error\":\"Failed to get Object Data for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
myKey := GetKeyValue(Avalbytes, "AES_Key")
fmt.Println("Key String := ", myKey)
if myKey != args[2] {
fmt.Println("ValidateItemOwnership() : Key does not match supplied key ", args[2], " - ", myKey)
jsonResp := "{\"Error\":\"ValidateItemOwnership() : Key does not match asset owner supplied key " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
if myItem.CurrentOwnerID != args[1] {
fmt.Println("ValidateItemOwnership() : ValidateItemOwnership() : Owner-Id does not match supplied ID ", args[1])
jsonResp := "{\"Error\":\"ValidateItemOwnership() : Owner-Id does not match supplied ID " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
fmt.Print("ValidateItemOwnership() : Response : Successfull - \n")
return Avalbytes, nil
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Retrieve Auction Information
// This query runs against the AuctionTable
// ./peer chaincode query -l golang -n mycc -c '{"Function": "GetAuctionRequest", "Args": ["1111"]}'
// There are two other tables just for query purposes - AucInitTable, AucOpenTable
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
func GetAuctionRequest(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var err error
// Get the Objects and Display it
Avalbytes, err := QueryLedger(stub, "AuctionTable", args)
if err != nil {
fmt.Println("GetAuctionRequest() : Failed to Query Object ")
jsonResp := "{\"Error\":\"Failed to get Object Data for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
if Avalbytes == nil {
fmt.Println("GetAuctionRequest() : Incomplete Query Object ")
jsonResp := "{\"Error\":\"Incomplete information about the key for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
fmt.Println("GetAuctionRequest() : Response : Successfull - \n")
return Avalbytes, nil
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Retrieve a Bid based on two keys - AucID, BidNo
// A Bid has two Keys - The Auction Request Number and Bid Number
// ./peer chaincode query -l golang -n mycc -c '{"Function": "GetLastBid", "Args": ["1111"], "1"}'
//
///////////////////////////////////////////////////////////////////////////////////////////////////
func GetBid(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var err error
// Check there are 2 Arguments provided as per the the struct - two are computed
// See example
if len(args) < 2 {
fmt.Println("GetBid(): Incorrect number of arguments. Expecting 2 ")
fmt.Println("GetBid(): ./peer chaincode query -l golang -n mycc -c '{\"Function\": \"GetBid\", \"Args\": [\"1111\",\"6\"]}'")
return nil, errors.New("GetBid(): Incorrect number of arguments. Expecting 2 ")
}
// Get the Objects and Display it
Avalbytes, err := QueryLedger(stub, "BidTable", args)
if err != nil {
fmt.Println("GetBid() : Failed to Query Object ")
jsonResp := "{\"Error\":\"Failed to get Object Data for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
if Avalbytes == nil {
fmt.Println("GetBid() : Incomplete Query Object ")
jsonResp := "{\"Error\":\"Incomplete information about the key for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
fmt.Println("GetBid() : Response : Successfull -")
return Avalbytes, nil
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Retrieve Auction Closeout Information. When an Auction closes
// The highest bid is retrieved and converted to a Transaction
// ./peer chaincode query -l golang -n mycc -c '{"Function": "GetTransaction", "Args": ["1111"]}'
//
///////////////////////////////////////////////////////////////////////////////////////////////////
func GetTransaction(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
//var err error
// Get the Objects and Display it
Avalbytes, err := QueryLedger(stub, "TransTable", args)
if Avalbytes == nil {
fmt.Println("GetTransaction() : Incomplete Query Object ")
jsonResp := "{\"Error\":\"Incomplete information about the key for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
if err != nil {
fmt.Println("GetTransaction() : Failed to Query Object ")
jsonResp := "{\"Error\":\"Failed to get Object Data for " + args[0] + "\"}"
return nil, errors.New(jsonResp)
}
fmt.Println("GetTransaction() : Response : Successfull")
return Avalbytes, nil
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create a User Object. The first step is to have users
// registered
// There are different types of users - Traders (TRD), Auction Houses (AH)
// Shippers (SHP), Insurance Companies (INS), Banks (BNK)
// While this version of the chain code does not enforce strict validation
// the business process recomends validating each persona for the service
// they provide or their participation on the auction blockchain, future enhancements will do that
// ./peer chaincode invoke -l golang -n mycc -c '{"Function": "PostUser", "Args":["100", "USER", "Ashley Hart", "TRD", "Morrisville Parkway, #216, Morrisville, NC 27560", "9198063535", "ashley@itpeople.com", "SUNTRUST", "00017102345", "0234678"]}'
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func PostUser(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
record, err := CreateUserObject(args[0:]) //
if err != nil {
return nil, err
}
buff, err := UsertoJSON(record) //
if err != nil {
fmt.Println("PostuserObject() : Failed Cannot create object buffer for write : ", args[1])
return nil, errors.New("PostUser(): Failed Cannot create object buffer for write : " + args[1])
} else {
// Update the ledger with the Buffer Data
// err = stub.PutState(args[0], buff)
keys := []string{args[0]}
err = UpdateLedger(stub, "UserTable", keys, buff)
if err != nil {
fmt.Println("PostUser() : write error while inserting record")
return nil, err
}
// Post Entry into UserCatTable - i.e. User Category Table
keys = []string{"2016", args[3], args[0]}
err = UpdateLedger(stub, "UserCatTable", keys, buff)
if err != nil {
fmt.Println("PostUser() : write error while inserting recordinto UserCatTable \n")
return nil, err
}
}
return buff, err
}
func CreateUserObject(args []string) (UserObject, error) {
var err error
var aUser UserObject
// Check there are 10 Arguments
if len(args) != 10 {
fmt.Println("CreateUserObject(): Incorrect number of arguments. Expecting 10 ")
return aUser, errors.New("CreateUserObject() : Incorrect number of arguments. Expecting 10 ")
}
// Validate UserID is an integer
_, err = strconv.Atoi(args[0])
if err != nil {
return aUser, errors.New("CreateUserObject() : User ID should be an integer")
}
aUser = UserObject{args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]}
fmt.Println("CreateUserObject() : User Object : ", aUser)
return aUser, nil
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create a master Object of the Item
// Since the Owner Changes hands, a record has to be written for each
// Transaction with the updated Encryption Key of the new owner
// Example
//./peer chaincode invoke -l golang -n mycc -c '{"Function": "PostItem", "Args":["1000", "ARTINV", "Shadows by Asppen", "Asppen Messer", "20140202", "Original", "Landscape" , "Canvas", "15 x 15 in", "sample_7.png","$600", "100"]}'
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
func PostItem(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
itemObject, err := CreateItemObject(args[0:])
if err != nil {
fmt.Println("PostItem(): Cannot create item object \n")
return nil, err
}
// Check if the Owner ID specified is registered and valid
ownerInfo, err := ValidateMember(stub, itemObject.CurrentOwnerID)
fmt.Println("Owner information ", ownerInfo, itemObject.CurrentOwnerID)
if err != nil {
fmt.Println("PostItem() : Failed Owner information not found for ", itemObject.CurrentOwnerID)
return nil, err
}
// Convert Item Object to JSON
buff, err := ARtoJSON(itemObject) //
if err != nil {
fmt.Println("PostItem() : Failed Cannot create object buffer for write : ", args[1])
return nil, errors.New("PostItem(): Failed Cannot create object buffer for write : " + args[1])
} else {
// Update the ledger with the Buffer Data
// err = stub.PutState(args[0], buff)
keys := []string{args[0]}
err = UpdateLedger(stub, "ItemTable", keys, buff)
if err != nil {
fmt.Println("PostItem() : write error while inserting record\n")
return buff, err
}
// Put an entry into the Item History Table
_, err = PostItemLog(stub, itemObject, "INITIAL", "DEFAULT")
if err != nil {
fmt.Println("PostItemLog() : write error while inserting record\n")
return nil, err
}
// Post Entry into ItemCatTable - i.e. Item Category Table
// The first key 2016 is a dummy (band aid) key to extract all values
keys = []string{"2016", args[6], args[0]}
err = UpdateLedger(stub, "ItemCatTable", keys, buff)
if err != nil {
fmt.Println("PostItem() : Write error while inserting record into ItemCatTable \n")
return buff, err
}
}
secret_key, _ := json.Marshal(itemObject.AES_Key)
fmt.Println(string(secret_key))
return secret_key, nil
}
func CreateItemObject(args []string) (ItemObject, error) {
var err error
var myItem ItemObject
// Check there are 12 Arguments provided as per the the struct - two are computed
if len(args) != 12 {
fmt.Println("CreateItemObject(): Incorrect number of arguments. Expecting 12 ")
return myItem, errors.New("CreateItemObject(): Incorrect number of arguments. Expecting 12 ")
}
// Validate ItemID is an integer
_, err = strconv.Atoi(args[0])
if err != nil {
fmt.Println("CreateItemObject(): ART ID should be an integer create failed! ")
return myItem, errors.New("CreateItemObject(): ART ID should be an integer create failed!")
}
// Validate Picture File exists based on the name provided
// Looks for file in current directory of application and must be fixed for other locations
// Validate Picture File exists based on the name provided
// Looks for file in current directory of application and must be fixed for other locations
imagePath := ccPath +args[9];
if _, err := os.Stat(imagePath); err == nil {
fmt.Println(imagePath, " exists!")
} else {
fmt.Println("CreateItemObject(): Cannot find or load Picture File = %s : %s\n", imagePath, err)
return myItem, errors.New("CreateItemObject(): ART Picture File not found " + imagePath)
}
// Get the Item Image and convert it to a byte array
imagebytes, fileType := imageToByteArray(imagePath)
// Generate a new key and encrypt the image
AES_key, _ := GenAESKey()
AES_enc := Encrypt(AES_key, imagebytes)
// Append the AES Key, The Encrypted Image Byte Array and the file type
myItem = ItemObject{args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], AES_enc, AES_key, fileType, args[10], args[11]}
fmt.Println("CreateItemObject(): Item Object created: ", myItem.ItemID, myItem.AES_Key)
// Code to Validate the Item Object)
// If User presents Crypto Key then key is used to validate the picture that is stored as part of the title
// TODO
return myItem, nil
}
///////////////////////////////////////////////////////////////////////////////////
// Since the Owner Changes hands, a record has to be written for each
// Transaction with the updated Encryption Key of the new owner
// This function is internally invoked by PostTransaction and is not a Public API
///////////////////////////////////////////////////////////////////////////////////
func UpdateItemObject(stub *shim.ChaincodeStub, ar []byte, hammerPrice string, buyer string) ([]byte, error) {
var err error
myItem, err := JSONtoAR(ar)
if err != nil {
fmt.Println("U() : UpdateItemObject() : Failed to create Art Record Object from JSON ")
return nil, err
}
// Insert logic to re-encrypt image by first fetching the current Key
CurrentAES_Key := myItem.AES_Key
// Decrypt Image and Save Image in a file
image := Decrypt(CurrentAES_Key, myItem.ItemImage)
// Get a New Key & Encrypt Image with New Key
myItem.AES_Key, _ = GenAESKey()
myItem.ItemImage = Encrypt(myItem.AES_Key, image)
// Update the owner to the Buyer and update price to auction hammer price
myItem.ItemBasePrice = hammerPrice
myItem.CurrentOwnerID = buyer
ar, err = ARtoJSON(myItem)
keys := []string{myItem.ItemID, myItem.CurrentOwnerID}
err = ReplaceLedgerEntry(stub, "ItemTable", keys, ar)
if err != nil {
fmt.Println("UpdateItemObject() : Failed ReplaceLedgerEntry in ItemTable into Blockchain ")
return nil, err
}
fmt.Println("UpdateItemObject() : ReplaceLedgerEntry in ItemTable successful ")
// Update entry in Item Category Table as it holds the Item object as wekk
keys = []string{"2016", myItem.ItemSubject, myItem.ItemID}
err = ReplaceLedgerEntry(stub, "ItemCatTable", keys, ar)
if err != nil {
fmt.Println("UpdateItemObject() : Failed ReplaceLedgerEntry in ItemCategoryTable into Blockchain ")
return nil, err
}
fmt.Println("UpdateItemObject() : ReplaceLedgerEntry in ItemCategoryTable successful ")
return myItem.AES_Key, nil
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Obtain Asset Details and Validate Item
// Transfer Item to new owner - no change in price - In the example XFER is the recType
// ./peer chaincode invoke -l golang -n mycc -c '{"Function": "TransferItem", "Args": ["1000", "100", "tGEBaZuKUBmwTjzNEyd+nr/fPUASuVJAZ1u7gha5fJg=", "300", "XFER"]}'
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func TransferItem(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var err error
if len(args) < 5 {
fmt.Println("TransferItem() : Requires 5 arguments Item#, Owner#, Key#, newOwnerID#, XFER \n")
return nil, errors.New("TransferItem() : Requires 5 arguments Item#, Owner#, Key#, newOwnerID#, XFER")
}
// Let us make sure that the Item is not on Auction
err = VerifyIfItemIsOnAuction(stub, args[0])
if err != nil {
fmt.Println("TransferItem() : Failed Item is either initiated or opened for Auction ", args[0])
return nil, err
}
// Validate New Owner's ID
_, err = ValidateMember(stub, args[3])
if err != nil {
fmt.Println("TransferItem() : Failed transferee not Registered in Blockchain ", args[3])
return nil, err
}
// Validate Item or Asset Ownership
ar, err := ValidateItemOwnership(stub, "ValidateItemOwnership", args[:3])
if err != nil {
fmt.Println("TransferItem() : ValidateItemOwnership() : Failed to authenticate item or asset ownership")
return nil, err
}
myItem, err := JSONtoAR(ar)
if err != nil {
fmt.Println("TransferItem() : Failed to create item Object from JSON ")
return nil, err
}
// Insert logic to re-encrypt image by first fetching the current Key
CurrentAES_Key := myItem.AES_Key
// Decrypt Image and Save Image in a file
image := Decrypt(CurrentAES_Key, myItem.ItemImage)
// Get a New Key & Encrypt Image with New Key
myItem.AES_Key, _ = GenAESKey()
myItem.ItemImage = Encrypt(myItem.AES_Key, image)
// Update the owner to the new owner transfered to
myItem.CurrentOwnerID = args[3]
ar, err = ARtoJSON(myItem)
keys := []string{myItem.ItemID, myItem.CurrentOwnerID}
err = ReplaceLedgerEntry(stub, "ItemTable", keys, ar)
if err != nil {
fmt.Println("TransferAsset() : Failed ReplaceLedgerEntry in ItemTable into Blockchain ")
return nil, err
}
fmt.Println("TransferAsset() : ReplaceLedgerEntry in ItemTable successful ")
// Update entry in Item Category Table as it holds the Item object as well
keys = []string{"2016", myItem.ItemSubject, myItem.ItemID}
err = ReplaceLedgerEntry(stub, "ItemCatTable", keys, ar)
if err != nil {
fmt.Println("TransferAsset() : Failed ReplaceLedgerEntry in ItemCategoryTable into Blockchain ")
return nil, err
}
_, err = PostItemLog(stub, myItem, "Transfer", args[1])
if err != nil {
fmt.Println("TransferItem() : PostItemLog() write error while inserting record\n")
return nil, err
}
fmt.Println("TransferAsset() : ReplaceLedgerEntry in ItemCategoryTable successful ")
return myItem.AES_Key, nil
}
////////////////////////////////////////////////////////////////////////////////////
// Validate Item Status - Is it currently on Auction, if so Reject Transfer Request
// This can be written better - will do so if things work
// The function return the Auction ID and the Status = OPEN or INIT
////////////////////////////////////////////////////////////////////////////////////
func VerifyIfItemIsOnAuction(stub *shim.ChaincodeStub, itemID string) (error) {
rows, err := GetListOfOpenAucs(stub, "AucOpenTable", []string{"2016"})
if err != nil {
return fmt.Errorf("VerifyIfItemIsOnAuction() operation failed. Error retrieving values from AucOpenTable: %s", err)
}
tlist := make([]AuctionRequest, len(rows))
err = json.Unmarshal([]byte(rows), &tlist)
if err != nil {
fmt.Println("VerifyIfItemIsOnAuction: Unmarshal failed : ", err)
return fmt.Errorf("VerifyIfItemIsOnAuction: operation failed. Error un-marshaling JSON: %s", err)
}
for i := 0; i < len(tlist); i++ {
ar := tlist[i]
// Compare Auction IDs
if ar.ItemID == itemID {
fmt.Println("VerifyIfItemIsOnAuction() Failed : Ummarshall error")
return fmt.Errorf("VerifyIfItemIsOnAuction() operation failed. %s", itemID)
}
}
// Now Check if an Auction Has been inititiated
// If so , it has to be removed from Auction for a Transfer
rows, err = GetListOfInitAucs(stub, "AucInitTable", []string{"2016"})
if err != nil {
return fmt.Errorf("VerifyIfItemIsOnAuction() operation failed. Error retrieving values from AucInitTable: %s", err)
}
tlist = make([]AuctionRequest, len(rows))
err = json.Unmarshal([]byte(rows), &tlist)
if err != nil {
fmt.Println("VerifyIfItemIsOnAuction() Unmarshal failed : ", err)
return fmt.Errorf("VerifyIfItemIsOnAuction: operation failed. Error un-marshaling JSON: %s", err)
}
for i := 0; i < len(tlist); i++ {
ar := tlist[i]
if err != nil {
fmt.Println("VerifyIfItemIsOnAuction() Failed : Ummarshall error")
return fmt.Errorf("VerifyIfItemIsOnAuction() operation failed. %s", err)
}
// Compare Auction IDs
if ar.ItemID == itemID {
return fmt.Errorf("VerifyIfItemIsOnAuction() operation failed." )
}
}
return nil
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// POSTS A LOG ENTRY Every Time the Item is transacted
// Valid Status for ItemLog = OnAuc, OnSale, NA, INITIAL
// Valid AuctionedBy: This value is set to "DEFAULT" but when it is put on auction Auction House ID is assigned
// PostItemLog IS NOT A PUBLIC API and is invoked every time some event happens in the Item's life
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func PostItemLog(stub *shim.ChaincodeStub, item ItemObject, status string, ah string) ([]byte, error) {
iLog := ItemToItemLog(item)
iLog.Status = status
iLog.AuctionedBy = ah
buff, err := ItemLogtoJSON(iLog)
if err != nil {
fmt.Println("PostItemLog() : Failed Cannot create object buffer for write : ", item.ItemID)
return nil, errors.New("PostItemLog(): Failed Cannot create object buffer for write : " + item.ItemID)
} else {
// Update the ledger with the Buffer Data
keys := []string{iLog.ItemID, iLog.Status, iLog.AuctionedBy, time.Now().Format("2006-01-02 15:04:05")}
err = UpdateLedger(stub, "ItemHistoryTable", keys, buff)
if err != nil {
fmt.Println("PostItemLog() : write error while inserting record\n")
return buff, err
}