-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
tradeWorkflow.go
1326 lines (1140 loc) · 42.7 KB
/
tradeWorkflow.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
/*
* Copyright 2018 IBM All Rights Reserved.
*
* Licensed 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.
*/
package main
import (
"fmt"
"errors"
"strconv"
"strings"
"encoding/json"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
// TradeWorkflowChaincode implementation
type TradeWorkflowChaincode struct {
testMode bool
}
func (t *TradeWorkflowChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("Initializing Trade Workflow")
_, args := stub.GetFunctionAndParameters()
var err error
// Upgrade Mode 1: leave ledger state as it was
if len(args) == 0 {
return shim.Success(nil)
}
// Upgrade mode 2: change all the names and account balances
if len(args) != 8 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 8: {" +
"Exporter, " +
"Exporter's Bank, " +
"Exporter's Account Balance, " +
"Importer, " +
"Importer's Bank, " +
"Importer's Account Balance, " +
"Carrier, " +
"Regulatory Authority" +
"}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Type checks
_, err = strconv.Atoi(string(args[2]))
if err != nil {
fmt.Printf("Exporter's account balance must be an integer. Found %s\n", args[2])
return shim.Error(err.Error())
}
_, err = strconv.Atoi(string(args[5]))
if err != nil {
fmt.Printf("Importer's account balance must be an integer. Found %s\n", args[5])
return shim.Error(err.Error())
}
fmt.Printf("Exporter: %s\n", args[0])
fmt.Printf("Exporter's Bank: %s\n", args[1])
fmt.Printf("Exporter's Account Balance: %s\n", args[2])
fmt.Printf("Importer: %s\n", args[3])
fmt.Printf("Importer's Bank: %s\n", args[4])
fmt.Printf("Importer's Account Balance: %s\n", args[5])
fmt.Printf("Carrier: %s\n", args[6])
fmt.Printf("Regulatory Authority: %s\n", args[7])
// Map participant identities to their roles on the ledger
roleKeys := []string{ expKey, ebKey, expBalKey, impKey, ibKey, impBalKey, carKey, raKey }
for i, roleKey := range roleKeys {
err = stub.PutState(roleKey, []byte(args[i]))
if err != nil {
fmt.Errorf("Error recording key %s: %s\n", roleKey, err.Error())
return shim.Error(err.Error())
}
}
return shim.Success(nil)
}
func (t *TradeWorkflowChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
var creatorOrg, creatorCertIssuer string
var err error
fmt.Println("TradeWorkflow Invoke")
if !t.testMode {
creatorOrg, creatorCertIssuer, err = getTxCreatorInfo(stub)
if err != nil {
fmt.Errorf("Error extracting creator identity info: %s\n", err.Error())
return shim.Error(err.Error())
}
fmt.Printf("TradeWorkflow Invoke by '%s', '%s'\n", creatorOrg, creatorCertIssuer)
}
function, args := stub.GetFunctionAndParameters()
if function == "requestTrade" {
// Importer requests a trade
return t.requestTrade(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "acceptTrade" {
// Exporter accepts a trade
return t.acceptTrade(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "requestLC" {
// Importer requests an L/C
return t.requestLC(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "issueLC" {
// Importer's Bank issues an L/C
return t.issueLC(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "acceptLC" {
// Exporter's Bank accepts an L/C
return t.acceptLC(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "requestEL" {
// Exporter requests an E/L
return t.requestEL(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "issueEL" {
// Regulatory Authority issues an E/L
return t.issueEL(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "prepareShipment" {
// Exporter prepares a shipment
return t.prepareShipment(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "acceptShipmentAndIssueBL" {
// Carrier validates the shipment and issues a B/L
return t.acceptShipmentAndIssueBL(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "requestPayment" {
// Exporter's Bank requests a payment
return t.requestPayment(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "makePayment" {
// Importer's Bank makes a payment
return t.makePayment(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "updateShipmentLocation" {
// Carrier updates the shipment location
return t.updateShipmentLocation(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "getTradeStatus" {
// Get status of trade agreement
return t.getTradeStatus(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "getLCStatus" {
// Get the L/C status
return t.getLCStatus(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "getELStatus" {
// Get the E/L status
return t.getELStatus(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "getShipmentLocation" {
// Get the shipment location
return t.getShipmentLocation(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "getBillOfLading" {
// Get the bill of lading
return t.getBillOfLading(stub, creatorOrg, creatorCertIssuer, args)
} else if function == "getAccountBalance" {
// Get account balance: Exporter/Importer
return t.getAccountBalance(stub, creatorOrg, creatorCertIssuer, args)
/*} else if function == "delete" {
// Deletes an entity from its state
return t.delete(stub, creatorOrg, creatorCertIssuer, args)*/
}
return shim.Error("Invalid invoke function name")
}
// Request a trade agreement
func (t *TradeWorkflowChaincode) requestTrade(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var tradeKey string
var tradeAgreement *TradeAgreement
var tradeAgreementBytes []byte
var amount int
var err error
// ADD TRADELIMIT RETRIEVAL HERE
// Access control: Only an Importer Org member can invoke this transaction
if !t.testMode && !authenticateImporterOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Importer Org. Access denied.")
}
if len(args) != 3 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 3: {ID, Amount, Description of Goods}. Found %d", len(args)))
return shim.Error(err.Error())
}
amount, err = strconv.Atoi(string(args[1]))
if err != nil {
return shim.Error(err.Error())
}
// ADD TRADE LIMIT CHECK HERE
tradeAgreement = &TradeAgreement{amount, args[2], REQUESTED, 0}
tradeAgreementBytes, err = json.Marshal(tradeAgreement)
if err != nil {
return shim.Error("Error marshaling trade agreement structure")
}
// Write the state to the ledger
tradeKey, err = getTradeKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(tradeKey, tradeAgreementBytes)
if err != nil {
return shim.Error(err.Error())
}
fmt.Printf("Trade %s request recorded\n", args[0])
return shim.Success(nil)
}
// Accept a trade agreement
func (t *TradeWorkflowChaincode) acceptTrade(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var tradeKey string
var tradeAgreement *TradeAgreement
var tradeAgreementBytes []byte
var err error
// Access control: Only an Exporting Entity Org member can invoke this transaction
if !t.testMode && !authenticateExportingEntityOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Exporting Entity Org. Access denied.")
}
if len(args) != 1 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 1: {ID}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Get the state from the ledger
tradeKey, err = getTradeKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
tradeAgreementBytes, err = stub.GetState(tradeKey)
if err != nil {
return shim.Error(err.Error())
}
if len(tradeAgreementBytes) == 0 {
err = errors.New(fmt.Sprintf("No record found for trade ID %s", args[0]))
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(tradeAgreementBytes, &tradeAgreement)
if err != nil {
return shim.Error(err.Error())
}
if tradeAgreement.Status == ACCEPTED {
fmt.Printf("Trade %s already accepted", args[0])
} else {
tradeAgreement.Status = ACCEPTED
tradeAgreementBytes, err = json.Marshal(tradeAgreement)
if err != nil {
return shim.Error("Error marshaling trade agreement structure")
}
// Write the state to the ledger
err = stub.PutState(tradeKey, tradeAgreementBytes)
if err != nil {
return shim.Error(err.Error())
}
}
fmt.Printf("Trade %s acceptance recorded\n", args[0])
return shim.Success(nil)
}
// Request an L/C
func (t *TradeWorkflowChaincode) requestLC(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var tradeKey, lcKey string
var tradeAgreementBytes, letterOfCreditBytes, exporterBytes []byte
var tradeAgreement *TradeAgreement
var letterOfCredit *LetterOfCredit
var err error
// Access control: Only an Importer Org member can invoke this transaction
if !t.testMode && !authenticateImporterOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Importer Org. Access denied.")
}
if len(args) != 1 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 1: {Trade ID}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Lookup trade agreement from the ledger
tradeKey, err = getTradeKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
tradeAgreementBytes, err = stub.GetState(tradeKey)
if err != nil {
return shim.Error(err.Error())
}
if len(tradeAgreementBytes) == 0 {
err = errors.New(fmt.Sprintf("No record found for trade ID %s", args[0]))
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(tradeAgreementBytes, &tradeAgreement)
if err != nil {
return shim.Error(err.Error())
}
// Verify that the trade has been agreed to
if tradeAgreement.Status != ACCEPTED {
return shim.Error("Trade has not been accepted by the parties")
}
// Lookup exporter (L/C beneficiary)
exporterBytes, err = stub.GetState(expKey)
if err != nil {
return shim.Error(err.Error())
}
letterOfCredit = &LetterOfCredit{"", "", string(exporterBytes), tradeAgreement.Amount, []string{}, REQUESTED}
letterOfCreditBytes, err = json.Marshal(letterOfCredit)
if err != nil {
return shim.Error("Error marshaling letter of credit structure")
}
// Write the state to the ledger
lcKey, err = getLCKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(lcKey, letterOfCreditBytes)
if err != nil {
return shim.Error(err.Error())
}
fmt.Printf("Letter of Credit request for trade %s recorded\n", args[0])
return shim.Success(nil)
}
// Issue an L/C
// We don't need to check the trade status if the L/C request has already been recorded
func (t *TradeWorkflowChaincode) issueLC(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var lcKey string
var letterOfCreditBytes []byte
var letterOfCredit *LetterOfCredit
var err error
// Access control: Only an Importer Org member can invoke this transaction
if !t.testMode && !authenticateImporterOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Importer Org. Access denied.")
}
if len(args) < 3 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting at least 3: {Trade ID, L/C ID, Expiry Date} [List of Documents]. Found %d", len(args)))
return shim.Error(err.Error())
}
// Lookup L/C from the ledger
lcKey, err = getLCKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
letterOfCreditBytes, err = stub.GetState(lcKey)
if err != nil {
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(letterOfCreditBytes, &letterOfCredit)
if err != nil {
return shim.Error(err.Error())
}
if letterOfCredit.Status == ISSUED {
fmt.Printf("L/C for trade %s already issued", args[0])
} else if letterOfCredit.Status == ACCEPTED {
fmt.Printf("L/C for trade %s already accepted", args[0])
} else {
letterOfCredit.Id = args[1]
letterOfCredit.ExpirationDate = args[2]
letterOfCredit.Documents = args[3:]
letterOfCredit.Status = ISSUED
letterOfCreditBytes, err = json.Marshal(letterOfCredit)
if err != nil {
return shim.Error("Error marshaling L/C structure")
}
// Write the state to the ledger
err = stub.PutState(lcKey, letterOfCreditBytes)
if err != nil {
return shim.Error(err.Error())
}
}
fmt.Printf("L/C issuance for trade %s recorded\n", args[0])
return shim.Success(nil)
}
// Accept an L/C
func (t *TradeWorkflowChaincode) acceptLC(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var lcKey string
var letterOfCreditBytes []byte
var letterOfCredit *LetterOfCredit
var err error
// Access control: Only an Exporter Org member can invoke this transaction
if !t.testMode && !authenticateExporterOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Exporter Org. Access denied.")
}
if len(args) != 1 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 1: {Trade ID}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Lookup L/C from the ledger
lcKey, err = getLCKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
letterOfCreditBytes, err = stub.GetState(lcKey)
if err != nil {
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(letterOfCreditBytes, &letterOfCredit)
if err != nil {
return shim.Error(err.Error())
}
if letterOfCredit.Status == ACCEPTED {
fmt.Printf("L/C for trade %s already accepted", args[0])
} else if letterOfCredit.Status == REQUESTED {
fmt.Printf("L/C for trade %s has not been issued", args[0])
return shim.Error("L/C not issued yet")
} else {
letterOfCredit.Status = ACCEPTED
letterOfCreditBytes, err = json.Marshal(letterOfCredit)
if err != nil {
return shim.Error("Error marshaling L/C structure")
}
// Write the state to the ledger
err = stub.PutState(lcKey, letterOfCreditBytes)
if err != nil {
return shim.Error(err.Error())
}
}
fmt.Printf("L/C acceptance for trade %s recorded\n", args[0])
return shim.Success(nil)
}
// Request an E/L
func (t *TradeWorkflowChaincode) requestEL(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var tradeKey, lcKey, elKey string
var tradeAgreementBytes, letterOfCreditBytes, exportLicenseBytes, exporterBytes, carrierBytes, approverBytes []byte
var tradeAgreement *TradeAgreement
var letterOfCredit *LetterOfCredit
var exportLicense *ExportLicense
var err error
// Access control: Only an Exporting Entity Org member can invoke this transaction
if !t.testMode && !authenticateExportingEntityOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Exporting Entity Org. Access denied.")
}
if len(args) != 1 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 1: {Trade ID}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Lookup L/C from the ledger
lcKey, err = getLCKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
letterOfCreditBytes, err = stub.GetState(lcKey)
if err != nil {
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(letterOfCreditBytes, &letterOfCredit)
if err != nil {
return shim.Error(err.Error())
}
// Verify that the L/C has already been accepted
if letterOfCredit.Status != ACCEPTED {
fmt.Printf("L/C for trade %s has not been accepted", args[0])
return shim.Error("L/C not accepted yet")
}
// Lookup trade agreement from the ledger
tradeKey, err = getTradeKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
tradeAgreementBytes, err = stub.GetState(tradeKey)
if err != nil {
return shim.Error(err.Error())
}
if len(tradeAgreementBytes) == 0 {
err = errors.New(fmt.Sprintf("No record found for trade ID %s", args[0]))
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(tradeAgreementBytes, &tradeAgreement)
if err != nil {
return shim.Error(err.Error())
}
// Record the E/L request
exporterBytes, err = stub.GetState(expKey)
if err != nil {
return shim.Error(err.Error())
}
// Lookup exporter
exporterBytes, err = stub.GetState(expKey)
if err != nil {
return shim.Error(err.Error())
}
// Lookup carrier
carrierBytes, err = stub.GetState(carKey)
if err != nil {
return shim.Error(err.Error())
}
// Lookup regulatory authority (license approver)
approverBytes, err = stub.GetState(raKey)
if err != nil {
return shim.Error(err.Error())
}
exportLicense = &ExportLicense{"", "", string(exporterBytes), string(carrierBytes), tradeAgreement.DescriptionOfGoods, string(approverBytes), REQUESTED}
exportLicenseBytes, err = json.Marshal(exportLicense)
if err != nil {
return shim.Error("Error marshaling export license structure")
}
// Write the state to the ledger
elKey, err = getELKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(elKey, exportLicenseBytes)
if err != nil {
return shim.Error(err.Error())
}
fmt.Printf("Export License request for trade %s recorded\n", args[0])
return shim.Success(nil)
}
// Issue an E/L
func (t *TradeWorkflowChaincode) issueEL(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var elKey string
var exportLicenseBytes []byte
var exportLicense *ExportLicense
var err error
// Access control: Only a Regulator Org member can invoke this transaction
if !t.testMode && !authenticateRegulatorOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Regulator Org. Access denied.")
}
if len(args) != 3 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 3: {Trade ID, L/C ID, Expiry Date}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Lookup E/L from the ledger
elKey, err = getELKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
exportLicenseBytes, err = stub.GetState(elKey)
if err != nil {
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(exportLicenseBytes, &exportLicense)
if err != nil {
return shim.Error(err.Error())
}
// Verify that the E/L has not already been issued
if exportLicense.Status == ISSUED {
fmt.Printf("E/L for trade %s has already been issued", args[0])
} else {
exportLicense.Id = args[1]
exportLicense.ExpirationDate = args[2]
exportLicense.Status = ISSUED
exportLicenseBytes, err = json.Marshal(exportLicense)
if err != nil {
return shim.Error("Error marshaling E/L structure")
}
// Write the state to the ledger
err = stub.PutState(elKey, exportLicenseBytes)
if err != nil {
return shim.Error(err.Error())
}
}
fmt.Printf("Export License issuance for trade %s recorded\n", args[0])
return shim.Success(nil)
}
// Prepare a shipment; preparation is indicated by setting the location as SOURCE
func (t *TradeWorkflowChaincode) prepareShipment(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var elKey, shipmentLocationKey string
var shipmentLocationBytes, exportLicenseBytes []byte
var exportLicense *ExportLicense
var err error
// Access control: Only an Exporting Entity Org member can invoke this transaction
if !t.testMode && !authenticateExportingEntityOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Exporting Entity Org. Access denied.")
}
if len(args) != 1 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 1: {Trade ID}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Lookup shipment location from the ledger
shipmentLocationKey, err = getShipmentLocationKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
shipmentLocationBytes, err = stub.GetState(shipmentLocationKey)
if err != nil {
return shim.Error(err.Error())
}
if len(shipmentLocationBytes) != 0 {
if string(shipmentLocationBytes) == SOURCE {
fmt.Printf("Shipment for trade %s has already been prepared", args[0])
return shim.Success(nil)
} else {
fmt.Printf("Shipment for trade %s has passed the preparation stage", args[0])
return shim.Error("Shipment past the preparation stage")
}
}
// Lookup E/L from the ledger
elKey, err = getELKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
exportLicenseBytes, err = stub.GetState(elKey)
if err != nil {
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(exportLicenseBytes, &exportLicense)
if err != nil {
return shim.Error(err.Error())
}
// Verify that the E/L has already been issued
if exportLicense.Status != ISSUED {
fmt.Printf("E/L for trade %s has not been issued", args[0])
return shim.Error("E/L not issued yet")
}
shipmentLocationKey, err = getShipmentLocationKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
// Write the state to the ledger
err = stub.PutState(shipmentLocationKey, []byte(SOURCE))
if err != nil {
return shim.Error(err.Error())
}
fmt.Printf("Shipment preparation for trade %s recorded\n", args[0])
return shim.Success(nil)
}
// Accept a shipment and issue a B/L
func (t *TradeWorkflowChaincode) acceptShipmentAndIssueBL(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var shipmentLocationKey, blKey, tradeKey string
var shipmentLocationBytes, tradeAgreementBytes, billOfLadingBytes, exporterBytes, carrierBytes, beneficiaryBytes []byte
var billOfLading *BillOfLading
var tradeAgreement *TradeAgreement
var err error
// Access control: Only an Carrier Org member can invoke this transaction
if !t.testMode && !authenticateCarrierOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Carrier Org. Access denied.")
}
if len(args) != 5 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 5: {Trade ID, B/L ID, Expiration Date, Source Port, Destination Port}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Lookup shipment location from the ledger
shipmentLocationKey, err = getShipmentLocationKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
shipmentLocationBytes, err = stub.GetState(shipmentLocationKey)
if err != nil {
return shim.Error(err.Error())
}
if len(shipmentLocationBytes) == 0 {
fmt.Printf("Shipment for trade %s has not been prepared yet", args[0])
return shim.Error("Shipment not prepared yet")
}
if string(shipmentLocationBytes) != SOURCE {
fmt.Printf("Shipment for trade %s has passed the preparation stage", args[0])
return shim.Error("Shipment past the preparation stage")
}
// Lookup trade agreement from the ledger
tradeKey, err = getTradeKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
tradeAgreementBytes, err = stub.GetState(tradeKey)
if err != nil {
return shim.Error(err.Error())
}
if len(tradeAgreementBytes) == 0 {
err = errors.New(fmt.Sprintf("No record found for trade ID %s", args[0]))
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(tradeAgreementBytes, &tradeAgreement)
if err != nil {
return shim.Error(err.Error())
}
// Lookup exporter
exporterBytes, err = stub.GetState(expKey)
if err != nil {
return shim.Error(err.Error())
}
// Lookup carrier
carrierBytes, err = stub.GetState(carKey)
if err != nil {
return shim.Error(err.Error())
}
// Lookup importer's bank (beneficiary of the title to goods after paymen tis made)
beneficiaryBytes, err = stub.GetState(ibKey)
if err != nil {
return shim.Error(err.Error())
}
// Create and record a B/L
billOfLading = &BillOfLading{args[1], args[2], string(exporterBytes), string(carrierBytes), tradeAgreement.DescriptionOfGoods,
tradeAgreement.Amount, string(beneficiaryBytes), args[3], args[4]}
billOfLadingBytes, err = json.Marshal(billOfLading)
if err != nil {
return shim.Error("Error marshaling bill of lading structure")
}
// Write the state to the ledger
blKey, err = getBLKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(blKey, billOfLadingBytes)
if err != nil {
return shim.Error(err.Error())
}
fmt.Printf("Bill of Lading for trade %s recorded\n", args[0])
return shim.Success(nil)
}
// Request a payment
func (t *TradeWorkflowChaincode) requestPayment(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var shipmentLocationKey, paymentKey, tradeKey string
var shipmentLocationBytes, paymentBytes, tradeAgreementBytes []byte
var tradeAgreement *TradeAgreement
var err error
// Access control: Only an Exporting Entity Org member can invoke this transaction
if !t.testMode && !authenticateExportingEntityOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Exporting Entity Org. Access denied.")
}
if len(args) != 1 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 1: {Trade ID}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Lookup trade agreement from the ledger
tradeKey, err = getTradeKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
tradeAgreementBytes, err = stub.GetState(tradeKey)
if err != nil {
return shim.Error(err.Error())
}
if len(tradeAgreementBytes) == 0 {
err = errors.New(fmt.Sprintf("No record found for trade ID %s", args[0]))
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(tradeAgreementBytes, &tradeAgreement)
if err != nil {
return shim.Error(err.Error())
}
// Lookup shipment location from the ledger
shipmentLocationKey, err = getShipmentLocationKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
shipmentLocationBytes, err = stub.GetState(shipmentLocationKey)
if err != nil {
return shim.Error(err.Error())
}
if len(shipmentLocationBytes) == 0 {
fmt.Printf("Shipment for trade %s has not been prepared yet", args[0])
return shim.Error("Shipment not prepared yet")
}
// Check if there's already a pending payment request
paymentKey, err = getPaymentKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
paymentBytes, err = stub.GetState(paymentKey)
if err != nil {
return shim.Error(err.Error())
}
if len(paymentBytes) != 0 { // The value doesn't matter as this is a temporary key used as a marker
fmt.Printf("Payment request already pending for trade %s\n", args[0])
} else {
// Check what has been paid up to this point
fmt.Printf("Amount paid thus far for trade %s = %d; total required = %d\n", args[0], tradeAgreement.Payment, tradeAgreement.Amount)
if tradeAgreement.Amount == tradeAgreement.Payment { // Payment has already been settled
fmt.Printf("Payment already settled for trade %s\n", args[0])
return shim.Error("Payment already settled")
}
if string(shipmentLocationBytes) == SOURCE && tradeAgreement.Payment != 0 { // Suppress duplicate requests for partial payment
fmt.Printf("Partial payment already made for trade %s\n", args[0])
return shim.Error("Partial payment already made")
}
// Record request on ledger
err = stub.PutState(paymentKey, []byte(REQUESTED))
if err != nil {
return shim.Error(err.Error())
}
fmt.Printf("Payment request for trade %s recorded\n", args[0])
}
return shim.Success(nil)
}
// Make a payment
func (t *TradeWorkflowChaincode) makePayment(stub shim.ChaincodeStubInterface, creatorOrg string, creatorCertIssuer string, args []string) pb.Response {
var shipmentLocationKey, paymentKey, tradeKey string
var paymentAmount, expBal, impBal int
var shipmentLocationBytes, paymentBytes, tradeAgreementBytes, impBalBytes, expBalBytes []byte
var tradeAgreement *TradeAgreement
var err error
// Access control: Only an Importer Org member can invoke this transaction
if !t.testMode && !authenticateImporterOrg(creatorOrg, creatorCertIssuer) {
return shim.Error("Caller not a member of Importer Org. Access denied.")
}
if len(args) != 1 {
err = errors.New(fmt.Sprintf("Incorrect number of arguments. Expecting 1: {Trade ID}. Found %d", len(args)))
return shim.Error(err.Error())
}
// Check if there's already a pending payment request
paymentKey, err = getPaymentKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
paymentBytes, err = stub.GetState(paymentKey)
if err != nil {
return shim.Error(err.Error())
}
if len(paymentBytes) == 0 {
fmt.Printf("No payment request found for trade %s", args[0])
return shim.Error("No payment request found")
}
// Lookup trade agreement from the ledger
tradeKey, err = getTradeKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
tradeAgreementBytes, err = stub.GetState(tradeKey)
if err != nil {
return shim.Error(err.Error())
}
if len(tradeAgreementBytes) == 0 {
err = errors.New(fmt.Sprintf("No record found for trade ID %s", args[0]))
return shim.Error(err.Error())
}
// Unmarshal the JSON
err = json.Unmarshal(tradeAgreementBytes, &tradeAgreement)
if err != nil {
return shim.Error(err.Error())
}
// Lookup shipment location from the ledger
shipmentLocationKey, err = getShipmentLocationKey(stub, args[0])
if err != nil {
return shim.Error(err.Error())
}
shipmentLocationBytes, err = stub.GetState(shipmentLocationKey)
if err != nil {
return shim.Error(err.Error())
}
if len(shipmentLocationBytes) == 0 {
fmt.Printf("Shipment for trade %s has not been prepared yet", args[0])
return shim.Error("Shipment not prepared yet")
}
// Lookup account balances
expBalBytes, err = stub.GetState(expBalKey)
if err != nil {
return shim.Error(err.Error())
}
expBal, err = strconv.Atoi(string(expBalBytes))
if err != nil {
return shim.Error(err.Error())
}
impBalBytes, err = stub.GetState(impBalKey)
if err != nil {
return shim.Error(err.Error())
}
impBal, err = strconv.Atoi(string(impBalBytes))
if err != nil {
return shim.Error(err.Error())
}
// Record transfer of funds
if string(shipmentLocationBytes) == SOURCE {
paymentAmount = tradeAgreement.Amount/2
} else {
paymentAmount = tradeAgreement.Amount - tradeAgreement.Payment
}
tradeAgreement.Payment += paymentAmount
expBal += paymentAmount
if impBal < paymentAmount {
fmt.Printf("Importer's bank balance %d is insufficient to cover payment amount %d\n", impBal, paymentAmount)
}
impBal -= paymentAmount
// Update ledger state
tradeAgreementBytes, err = json.Marshal(tradeAgreement)
if err != nil {
return shim.Error("Error marshaling trade agreement structure")
}
err = stub.PutState(tradeKey, tradeAgreementBytes)
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(expBalKey, []byte(strconv.Itoa(expBal)))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(impBalKey, []byte(strconv.Itoa(impBal)))
if err != nil {
return shim.Error(err.Error())
}
// Delete request key from ledger