Skip to content

Commit 19d565b

Browse files
author
conghonglei
committed
Fix example-chaincode assert_management
table-api removed from chaincode/shim interface. Fix the following chaincode, which was based previous table-api, to get/putstate. Change-Id: I306757777daf0298b4c21a5b8db1dfcf2cd4dedb Signed-off-by: conghonglei <[email protected]>
1 parent 1b53e6e commit 19d565b

File tree

3 files changed

+69
-115
lines changed

3 files changed

+69
-115
lines changed

examples/chaincode/go/asset_management/asset_management.go

+12-49
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import (
2828
"github.com/op/go-logging"
2929
)
3030

31-
var myLogger = logging.MustGetLogger("asset_mgm")
31+
var myLogger = logging.MustGetLogger("asset_mgmt")
3232

3333
// AssetManagementChaincode is simple chaincode implementing a basic Asset Management system
3434
// with access control enforcement at chaincode level.
@@ -47,15 +47,6 @@ func (t *AssetManagementChaincode) Init(stub shim.ChaincodeStubInterface) pb.Res
4747
return shim.Error("Incorrect number of arguments. Expecting 0")
4848
}
4949

50-
// Create ownership table
51-
err := stub.CreateTable("AssetsOwnership", []*shim.ColumnDefinition{
52-
&shim.ColumnDefinition{Name: "Asset", Type: shim.ColumnDefinition_STRING, Key: true},
53-
&shim.ColumnDefinition{Name: "Owner", Type: shim.ColumnDefinition_BYTES, Key: false},
54-
})
55-
if err != nil {
56-
return shim.Error("Failed creating AssetsOnwership table.")
57-
}
58-
5950
// Set the admin
6051
// The metadata will contain the certificate of the administrator
6152
adminCert, err := stub.GetCallerMetadata()
@@ -105,19 +96,15 @@ func (t *AssetManagementChaincode) assign(stub shim.ChaincodeStubInterface, args
10596
return shim.Error("The caller is not an administrator")
10697
}
10798

108-
// Register assignment
109-
myLogger.Debugf("New owner of [%s] is [% x]", asset, owner)
110-
111-
ok, err = stub.InsertRow("AssetsOwnership", shim.Row{
112-
Columns: []*shim.Column{
113-
&shim.Column{Value: &shim.Column_String_{String_: asset}},
114-
&shim.Column{Value: &shim.Column_Bytes{Bytes: owner}}},
115-
})
116-
117-
if !ok && err == nil {
99+
currentOwner, err := stub.GetState(asset)
100+
if len(currentOwner) > 0 && err == nil {
118101
return shim.Error("Asset was already assigned.")
119102
}
120103

104+
// Register assignment
105+
myLogger.Debugf("New owner of [%s] is [% x]", asset, owner)
106+
err = stub.PutState(asset, owner)
107+
121108
myLogger.Debug("Assign...done!")
122109

123110
return shim.Success(nil)
@@ -138,16 +125,11 @@ func (t *AssetManagementChaincode) transfer(stub shim.ChaincodeStubInterface, ar
138125

139126
// Verify the identity of the caller
140127
// Only the owner can transfer one of his assets
141-
var columns []shim.Column
142-
col1 := shim.Column{Value: &shim.Column_String_{String_: asset}}
143-
columns = append(columns, col1)
144-
145-
row, err := stub.GetRow("AssetsOwnership", columns)
128+
prvOwner, err := stub.GetState(asset)
146129
if err != nil {
147130
return shim.Error(fmt.Sprintf("Failed retrieving asset [%s]: [%s]", asset, err))
148131
}
149132

150-
prvOwner := row.Columns[1].GetBytes()
151133
myLogger.Debugf("Previous owener of [%s] is [% x]", asset, prvOwner)
152134
if len(prvOwner) == 0 {
153135
return shim.Error("Invalid previous owner. Nil")
@@ -163,22 +145,7 @@ func (t *AssetManagementChaincode) transfer(stub shim.ChaincodeStubInterface, ar
163145
}
164146

165147
// At this point, the proof of ownership is valid, then register transfer
166-
err = stub.DeleteRow(
167-
"AssetsOwnership",
168-
[]shim.Column{shim.Column{Value: &shim.Column_String_{String_: asset}}},
169-
)
170-
if err != nil {
171-
return shim.Error("Failed deliting row.")
172-
}
173-
174-
_, err = stub.InsertRow(
175-
"AssetsOwnership",
176-
shim.Row{
177-
Columns: []*shim.Column{
178-
&shim.Column{Value: &shim.Column_String_{String_: asset}},
179-
&shim.Column{Value: &shim.Column_Bytes{Bytes: newOwner}},
180-
},
181-
})
148+
err = stub.PutState(asset, newOwner)
182149
if err != nil {
183150
return shim.Error("Failed inserting row.")
184151
}
@@ -278,19 +245,15 @@ func (t *AssetManagementChaincode) query(stub shim.ChaincodeStubInterface, args
278245

279246
myLogger.Debugf("Query [%s]", string(asset))
280247

281-
var columns []shim.Column
282-
col1 := shim.Column{Value: &shim.Column_String_{String_: asset}}
283-
columns = append(columns, col1)
284-
285-
row, err := stub.GetRow("AssetsOwnership", columns)
248+
owner, err := stub.GetState(asset)
286249
if err != nil {
287250
myLogger.Debugf("Failed retriving asset [%s]: [%s]", string(asset), err)
288251
return shim.Error(fmt.Sprintf("Failed retriving asset [%s]: [%s]", string(asset), err))
289252
}
290253

291-
myLogger.Debugf("Query done [% x]", row.Columns[1].GetBytes())
254+
myLogger.Debugf("Query done [% x]", owner)
292255

293-
return shim.Success(row.Columns[1].GetBytes())
256+
return shim.Success([]byte(base64.StdEncoding.EncodeToString(owner)))
294257
}
295258

296259
func main() {

examples/chaincode/go/asset_management02/asset_management02.go

-5
Original file line numberDiff line numberDiff line change
@@ -209,11 +209,6 @@ func (t *AssetManagementChaincode) Init(stub shim.ChaincodeStubInterface) pb.Res
209209
return shim.Error("Incorrect number of arguments. Expecting 0")
210210
}
211211

212-
err := dHandler.createTable(stub)
213-
if err != nil {
214-
return shim.Error(err.Error())
215-
}
216-
217212
return shim.Success(nil)
218213
}
219214

examples/chaincode/go/asset_management02/depository_handler.go

+57-61
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,10 @@ package main
1919
import (
2020
"errors"
2121

22-
"github.com/hyperledger/fabric/core/chaincode/shim"
23-
)
22+
"encoding/json"
23+
"fmt"
2424

25-
// consts associated with chaincode table
26-
const (
27-
tableColumn = "AssetsOwnership"
28-
columnAccountID = "Account"
29-
columnContactInfo = "ContactInfo"
30-
columnAmount = "Amount"
25+
"github.com/hyperledger/fabric/core/chaincode/shim"
3126
)
3227

3328
//DepositoryHandler provides APIs used to perform operations on CC's KV store
@@ -39,17 +34,10 @@ func NewDepositoryHandler() *depositoryHandler {
3934
return &depositoryHandler{}
4035
}
4136

42-
// createTable initiates a new asset depository table in the chaincode state
43-
// stub: chaincodestub
44-
func (t *depositoryHandler) createTable(stub shim.ChaincodeStubInterface) error {
45-
46-
// Create asset depository table
47-
return stub.CreateTable(tableColumn, []*shim.ColumnDefinition{
48-
&shim.ColumnDefinition{Name: columnAccountID, Type: shim.ColumnDefinition_STRING, Key: true},
49-
&shim.ColumnDefinition{Name: columnContactInfo, Type: shim.ColumnDefinition_STRING, Key: false},
50-
&shim.ColumnDefinition{Name: columnAmount, Type: shim.ColumnDefinition_UINT64, Key: false},
51-
})
52-
37+
type depositoryAccount struct {
38+
AccountID string `json:"account_id"`
39+
ContactInfo string `json:"contact_info"`
40+
Amount uint64 `json:"amount"`
5341
}
5442

5543
// assign allocates assets to account IDs in the chaincode state for each of the
@@ -64,21 +52,27 @@ func (t *depositoryHandler) assign(stub shim.ChaincodeStubInterface,
6452

6553
myLogger.Debugf("insert accountID= %v", accountID)
6654

67-
//insert a new row for this account ID that includes contact information and balance
68-
ok, err := stub.InsertRow(tableColumn, shim.Row{
69-
Columns: []*shim.Column{
70-
&shim.Column{Value: &shim.Column_String_{String_: accountID}},
71-
&shim.Column{Value: &shim.Column_String_{String_: contactInfo}},
72-
&shim.Column{Value: &shim.Column_Uint64{Uint64: amount}}},
73-
})
74-
7555
// you can only assign balances to new account IDs
76-
if !ok && err == nil {
56+
accountBytes, err := stub.GetState(accountID)
57+
if err == nil && len(accountBytes) > 0 {
7758
myLogger.Errorf("system error %v", err)
7859
return errors.New("Asset was already assigned.")
7960
}
8061

81-
return nil
62+
account := depositoryAccount{
63+
AccountID: accountID,
64+
ContactInfo: contactInfo,
65+
Amount: amount,
66+
}
67+
accountBytes, err = json.Marshal(account)
68+
if err != nil {
69+
myLogger.Errorf("account marshaling error %v", err)
70+
return errors.New("Failed to serialize account info." + err.Error())
71+
}
72+
73+
//update this account that includes contact information and balance
74+
err = stub.PutState(accountID, accountBytes)
75+
return err
8276
}
8377

8478
// updateAccountBalance updates the balance amount of an account ID
@@ -94,18 +88,20 @@ func (t *depositoryHandler) updateAccountBalance(stub shim.ChaincodeStubInterfac
9488
myLogger.Debugf("insert accountID= %v", accountID)
9589

9690
//replace the old record row associated with the account ID with the new record row
97-
ok, err := stub.ReplaceRow(tableColumn, shim.Row{
98-
Columns: []*shim.Column{
99-
&shim.Column{Value: &shim.Column_String_{String_: accountID}},
100-
&shim.Column{Value: &shim.Column_String_{String_: contactInfo}},
101-
&shim.Column{Value: &shim.Column_Uint64{Uint64: amount}}},
102-
})
103-
104-
if !ok && err == nil {
105-
myLogger.Errorf("system error %v", err)
106-
return errors.New("failed to replace row with account Id." + accountID)
91+
account := depositoryAccount{
92+
AccountID: accountID,
93+
ContactInfo: contactInfo,
94+
Amount: amount,
10795
}
108-
return nil
96+
accountBytes, err := json.Marshal(account)
97+
if err != nil {
98+
myLogger.Errorf("account marshaling error %v", err)
99+
return errors.New("Failed to serialize account info." + err.Error())
100+
}
101+
102+
//update this account that includes contact information and balance
103+
err = stub.PutState(accountID, accountBytes)
104+
return err
109105
}
110106

111107
// deleteAccountRecord deletes the record row associated with an account ID on the chaincode state table
@@ -116,10 +112,7 @@ func (t *depositoryHandler) deleteAccountRecord(stub shim.ChaincodeStubInterface
116112
myLogger.Debugf("insert accountID= %v", accountID)
117113

118114
//delete record matching account ID passed in
119-
err := stub.DeleteRow(
120-
"AssetsOwnership",
121-
[]shim.Column{shim.Column{Value: &shim.Column_String_{String_: accountID}}},
122-
)
115+
err := stub.DelState(accountID)
123116

124117
if err != nil {
125118
myLogger.Errorf("system error %v", err)
@@ -179,12 +172,12 @@ func (t *depositoryHandler) transfer(stub shim.ChaincodeStubInterface, fromAccou
179172
// stub: chaincodestub
180173
// accountID: account ID
181174
func (t *depositoryHandler) queryContactInfo(stub shim.ChaincodeStubInterface, accountID string) (string, error) {
182-
row, err := t.queryTable(stub, accountID)
175+
account, err := t.queryTable(stub, accountID)
183176
if err != nil {
184177
return "", err
185178
}
186179

187-
return row.Columns[1].GetString_(), nil
180+
return account.ContactInfo, nil
188181
}
189182

190183
// queryBalance queries the balance information matching a correponding account ID on the chaincode state table
@@ -194,40 +187,43 @@ func (t *depositoryHandler) queryBalance(stub shim.ChaincodeStubInterface, accou
194187

195188
myLogger.Debugf("insert accountID= %v", accountID)
196189

197-
row, err := t.queryTable(stub, accountID)
190+
account, err := t.queryTable(stub, accountID)
198191
if err != nil {
199192
return 0, err
200193
}
201-
if len(row.Columns) == 0 || row.Columns[2] == nil {
202-
return 0, errors.New("row or column value not found")
203-
}
204194

205-
return row.Columns[2].GetUint64(), nil
195+
return account.Amount, nil
206196
}
207197

208198
// queryAccount queries the balance and contact information matching a correponding account ID on the chaincode state table
209199
// stub: chaincodestub
210200
// accountID: account ID
211201
func (t *depositoryHandler) queryAccount(stub shim.ChaincodeStubInterface, accountID string) (string, uint64, error) {
212-
row, err := t.queryTable(stub, accountID)
202+
account, err := t.queryTable(stub, accountID)
213203
if err != nil {
214204
return "", 0, err
215205
}
216-
if len(row.Columns) == 0 || row.Columns[2] == nil {
217-
return "", 0, errors.New("row or column value not found")
218-
}
219206

220-
return row.Columns[1].GetString_(), row.Columns[2].GetUint64(), nil
207+
return account.ContactInfo, account.Amount, nil
221208
}
222209

223210
// queryTable returns the record row matching a correponding account ID on the chaincode state table
224211
// stub: chaincodestub
225212
// accountID: account ID
226-
func (t *depositoryHandler) queryTable(stub shim.ChaincodeStubInterface, accountID string) (shim.Row, error) {
213+
func (t *depositoryHandler) queryTable(stub shim.ChaincodeStubInterface, accountID string) (*depositoryAccount, error) {
227214

228-
var columns []shim.Column
229-
col1 := shim.Column{Value: &shim.Column_String_{String_: accountID}}
230-
columns = append(columns, col1)
215+
accountBytes, err := stub.GetState(accountID)
216+
if err != nil {
217+
return nil, errors.New("Failed to get account." + err.Error())
218+
}
219+
if len(accountBytes) == 0 {
220+
return nil, fmt.Errorf("Account %s not exists.", accountID)
221+
}
231222

232-
return stub.GetRow(tableColumn, columns)
223+
account := &depositoryAccount{}
224+
err = json.Unmarshal(accountBytes, account)
225+
if err != nil {
226+
return nil, errors.New("Failed to parse account Info. " + err.Error())
227+
}
228+
return account, nil
233229
}

0 commit comments

Comments
 (0)