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
|
package main
import ( "bytes" "crypto/sha256" "encoding/json" "fmt" "log" "time"
"github.com/golang/protobuf/ptypes" "github.com/hyperledger/fabric-chaincode-go/pkg/statebased" "github.com/hyperledger/fabric-chaincode-go/shim" "github.com/hyperledger/fabric-contract-api-go/contractapi" )
const ( typeAssetForSale = "S" typeAssetBid = "B" typeAssetSaleReceipt = "SR" typeAssetBuyReceipt = "BR" statusEnable = "enable" statusDelete = "delete" )
type SmartContract struct { contractapi.Contract }
type Asset struct { ObjectType string `json:"objectType"` ID string `json:"assetID"` OwnerOrg string `json:"ownerOrg"` PublicDescription string `json:"publicDescription"` Status string `json:"status"` ParentID string `json:"parentID"` }
type receipt struct { price int timestamp time.Time }
type AssetProperties struct { ObjectType string `json:"objectType"` ID string `json:"assetID"` Issuer string `json:"issuer"` Amount int `json:"amount"` CreateDate time.Time `json:"createDate"` EndDate time.Time `json:"endDate"` Salt string `json:"salt"` }
func (s *SmartContract) CreateAsset(ctx contractapi.TransactionContextInterface, assetID, publicDescription string) error { transientMap, err := ctx.GetStub().GetTransient() if err != nil { return fmt.Errorf("error getting transient: %v", err) }
immutablePropertiesJSON, ok := transientMap["asset_properties"] fmt.Println("immutablePropertiesJSON:", immutablePropertiesJSON) if !ok { return fmt.Errorf("asset_properties key not found in the transient map") }
return createAsset(ctx, immutablePropertiesJSON, assetID, publicDescription, "") }
func createAsset(ctx contractapi.TransactionContextInterface, immutablePropertiesJSON []byte, assetID, publicDescription string, parentID string) error { clientOrgID, err := getClientOrgID(ctx, true) fmt.Println("clientOrgID:", clientOrgID) if err != nil { return fmt.Errorf("failed to get verified OrgID: %v", err) }
asset := Asset{ ObjectType: "asset", ID: assetID, OwnerOrg: clientOrgID, PublicDescription: publicDescription, Status: statusEnable, ParentID: parentID, } fmt.Println("asset:", asset) assetBytes, err := json.Marshal(asset) if err != nil { return fmt.Errorf("failed to create asset JSON: %v", err) }
err = ctx.GetStub().PutState(asset.ID, assetBytes) if err != nil { return fmt.Errorf("failed to put asset in public data: %v", err) }
err = setAssetStateBasedEndorsement(ctx, asset.ID, clientOrgID) if err != nil { return fmt.Errorf("failed setting state based endorsement for owner: %v", err) }
collection := buildCollectionName(clientOrgID) fmt.Println("collection:", collection) err = ctx.GetStub().PutPrivateData(collection, asset.ID, immutablePropertiesJSON) if err != nil { return fmt.Errorf("failed to put Asset private details: %v", err) } return nil }
func (s *SmartContract) ChangePublicDescription(ctx contractapi.TransactionContextInterface, assetID string, newDescription string) error { asset, err := s.ReadAsset(ctx, assetID) if err != nil { return fmt.Errorf("failed to get asset: %v", err) } return changeOriginAssetInfo(ctx, *asset, "", newDescription) }
func (s *SmartContract) AgreeToSell(ctx contractapi.TransactionContextInterface, assetID string) error { asset, err := s.ReadAsset(ctx, assetID) if err != nil { return err }
clientOrgID, err := getClientOrgID(ctx, true) if err != nil { return fmt.Errorf("failed to get verified OrgID: %v", err) }
if clientOrgID != asset.OwnerOrg { return fmt.Errorf("a client from %s cannot sell an asset owned by %s", clientOrgID, asset.OwnerOrg) }
return agreeToPrice(ctx, assetID, typeAssetForSale) }
func (s *SmartContract) AgreeToBuy(ctx contractapi.TransactionContextInterface, assetID string) error { return agreeToPrice(ctx, assetID, typeAssetBid) }
func agreeToPrice(ctx contractapi.TransactionContextInterface, assetID string, priceType string) error { clientOrgID, err := getClientOrgID(ctx, true) if err != nil { return fmt.Errorf("failed to get verified OrgID: %v", err) }
transMap, err := ctx.GetStub().GetTransient() if err != nil { return fmt.Errorf("error getting transient: %v", err) }
price, ok := transMap["asset_price"] if !ok { return fmt.Errorf("asset_price key not found in the transient map") }
collection := buildCollectionName(clientOrgID)
assetPriceKey, err := ctx.GetStub().CreateCompositeKey(priceType, []string{assetID}) if err != nil { return fmt.Errorf("failed to create composite key: %v", err) }
err = ctx.GetStub().PutPrivateData(collection, assetPriceKey, price) if err != nil { return fmt.Errorf("failed to put asset bid: %v", err) }
return nil }
func (s *SmartContract) VerifyAssetProperties(ctx contractapi.TransactionContextInterface, assetID string) (bool, error) { transMap, err := ctx.GetStub().GetTransient() if err != nil { return false, fmt.Errorf("error getting transient: %v", err) }
immutablePropertiesJSON, ok := transMap["asset_properties"] if !ok { return false, fmt.Errorf("asset_properties key not found in the transient map") }
asset, err := s.ReadAsset(ctx, assetID) if err != nil { return false, fmt.Errorf("failed to get asset: %v", err) }
if (*asset).Status != statusEnable { return false, fmt.Errorf("资产不可以,不允许交易: %v", err) }
collectionOwner := buildCollectionName(asset.OwnerOrg) immutablePropertiesOnChainHash, err := ctx.GetStub().GetPrivateDataHash(collectionOwner, assetID) if err != nil { return false, fmt.Errorf("failed to read asset private properties hash from seller's collection: %v", err) } if immutablePropertiesOnChainHash == nil { return false, fmt.Errorf("asset private properties hash does not exist: %s", assetID) }
hash := sha256.New() hash.Write(immutablePropertiesJSON) calculatedPropertiesHash := hash.Sum(nil)
if !bytes.Equal(immutablePropertiesOnChainHash, calculatedPropertiesHash) { return false, fmt.Errorf("hash %x for passed immutable properties %s does not match on-chain hash %x", calculatedPropertiesHash, immutablePropertiesJSON, immutablePropertiesOnChainHash, ) }
return true, nil }
func (s *SmartContract) TransferAsset(ctx contractapi.TransactionContextInterface, assetID string, buyerOrgID string) error { clientOrgID, err := getClientOrgID(ctx, false) if err != nil { return fmt.Errorf("failed to get verified OrgID: %v", err) }
transMap, err := ctx.GetStub().GetTransient() if err != nil { return fmt.Errorf("error getting transient data: %v", err) }
immutablePropertiesJSON, ok := transMap["asset_properties"] if !ok { return fmt.Errorf("asset_properties key not found in the transient map") }
priceJSON, ok := transMap["asset_price"] if !ok { return fmt.Errorf("asset_price key not found in the transient map") }
var agreement Agreement err = json.Unmarshal(priceJSON, &agreement) if err != nil { return fmt.Errorf("failed to unmarshal price JSON: %v", err) }
asset, err := s.ReadAsset(ctx, assetID) if err != nil { return fmt.Errorf("failed to get asset: %v", err) }
if (*asset).Status != statusEnable { return fmt.Errorf("资产不可以,不允许交易") }
err = verifyTransferConditions(ctx, asset, immutablePropertiesJSON, clientOrgID, buyerOrgID, priceJSON) if err != nil { return fmt.Errorf("failed transfer verification: %v", err) }
err = transferAssetState(ctx, asset, immutablePropertiesJSON, clientOrgID, buyerOrgID, agreement.Price) if err != nil { return fmt.Errorf("failed asset transfer: %v", err) }
return nil
}
func (s *SmartContract) SplitAsset(ctx contractapi.TransactionContextInterface, assetID string, amount int) error { asset, err := s.ReadAsset(ctx, assetID) if err != nil { return err } immutableProperties, err := getAssetPrivateProperties(ctx, assetID) if err != nil { return err } assetProperties, err := getAssetProperties(immutableProperties) if err != nil { return err } if assetProperties.Amount <= amount { return fmt.Errorf("资产ID的金额为%d小于想要拆分的金额为%d,不允许拆分", assetProperties.Amount, amount) } if err := splitAsset(ctx, assetProperties, assetID+"1", amount, *asset); err != nil { return err } if err := splitAsset(ctx, assetProperties, assetID+"2", assetProperties.Amount-amount, *asset); err != nil { return err } collection := buildCollectionName((*asset).OwnerOrg) err = ctx.GetStub().DelPrivateData(collection, asset.ID) if err != nil { return fmt.Errorf("failed to delete Asset private details from org: %v", err) } changeOriginAssetInfo(ctx, *asset, statusDelete, "已拆分") return nil }
func getAssetProperties(immutablePropertiesJSON []byte) (AssetProperties, error) { var assetProperties AssetProperties if err := json.Unmarshal(immutablePropertiesJSON, &assetProperties); err != nil { return assetProperties, fmt.Errorf("failed to unmarshal price JSON: %v", err) } return assetProperties, nil }
func changeOriginAssetInfo(ctx contractapi.TransactionContextInterface, asset Asset, status string, newDescription string) error { clientOrgID, err := getClientOrgID(ctx, false) if err != nil { return fmt.Errorf("failed to get verified OrgID: %v", err) }
if clientOrgID != asset.OwnerOrg { return fmt.Errorf("a client from %s cannot update the description of a asset owned by %s", clientOrgID, asset.OwnerOrg) }
if asset.Status != statusEnable { return fmt.Errorf("资产不可用,不允许修改") } if status != "" { asset.Status = status } if newDescription != "" { asset.PublicDescription = newDescription } updatedAssetJSON, err := json.Marshal(asset) if err != nil { return fmt.Errorf("failed to marshal asset: %v", err) }
return ctx.GetStub().PutState(asset.ID, updatedAssetJSON) }
func splitAsset(ctx contractapi.TransactionContextInterface, originAssetProperties AssetProperties, newAssetID string, newAmount int, asset Asset) error { originAssetProperties.Amount = newAmount originAssetProperties.ID = newAssetID immutablePropertiesJSON, err := json.Marshal(originAssetProperties) if err != nil { return err } return createAsset(ctx, immutablePropertiesJSON, newAssetID, asset.PublicDescription, asset.ID) }
func verifyTransferConditions(ctx contractapi.TransactionContextInterface, asset *Asset, immutablePropertiesJSON []byte, clientOrgID string, buyerOrgID string, priceJSON []byte) error {
if clientOrgID != asset.OwnerOrg { return fmt.Errorf("a client from %s cannot transfer a asset owned by %s", clientOrgID, asset.OwnerOrg) }
collectionSeller := buildCollectionName(clientOrgID) immutablePropertiesOnChainHash, err := ctx.GetStub().GetPrivateDataHash(collectionSeller, asset.ID) if err != nil { return fmt.Errorf("failed to read asset private properties hash from seller's collection: %v", err) } if immutablePropertiesOnChainHash == nil { return fmt.Errorf("asset private properties hash does not exist: %s", asset.ID) }
hash := sha256.New() hash.Write(immutablePropertiesJSON) calculatedPropertiesHash := hash.Sum(nil)
if !bytes.Equal(immutablePropertiesOnChainHash, calculatedPropertiesHash) { return fmt.Errorf("hash %x for passed immutable properties %s does not match on-chain hash %x", calculatedPropertiesHash, immutablePropertiesJSON, immutablePropertiesOnChainHash, ) }
assetForSaleKey, err := ctx.GetStub().CreateCompositeKey(typeAssetForSale, []string{asset.ID}) if err != nil { return fmt.Errorf("failed to create composite key: %v", err) } sellerPriceHash, err := ctx.GetStub().GetPrivateDataHash(collectionSeller, assetForSaleKey) if err != nil { return fmt.Errorf("failed to get seller price hash: %v", err) } if sellerPriceHash == nil { return fmt.Errorf("seller price for %s does not exist", asset.ID) }
collectionBuyer := buildCollectionName(buyerOrgID) assetBidKey, err := ctx.GetStub().CreateCompositeKey(typeAssetBid, []string{asset.ID}) if err != nil { return fmt.Errorf("failed to create composite key: %v", err) } buyerPriceHash, err := ctx.GetStub().GetPrivateDataHash(collectionBuyer, assetBidKey) if err != nil { return fmt.Errorf("failed to get buyer price hash: %v", err) } if buyerPriceHash == nil { return fmt.Errorf("buyer price for %s does not exist", asset.ID) }
hash = sha256.New() hash.Write(priceJSON) calculatedPriceHash := hash.Sum(nil)
if !bytes.Equal(calculatedPriceHash, sellerPriceHash) { return fmt.Errorf("hash %x for passed price JSON %s does not match on-chain hash %x, seller hasn't agreed to the passed trade id and price", calculatedPriceHash, priceJSON, sellerPriceHash, ) }
if !bytes.Equal(calculatedPriceHash, buyerPriceHash) { return fmt.Errorf("hash %x for passed price JSON %s does not match on-chain hash %x, buyer hasn't agreed to the passed trade id and price", calculatedPriceHash, priceJSON, buyerPriceHash, ) }
return nil }
func transferAssetState(ctx contractapi.TransactionContextInterface, asset *Asset, immutablePropertiesJSON []byte, clientOrgID string, buyerOrgID string, price int) error { asset.OwnerOrg = buyerOrgID updatedAsset, err := json.Marshal(asset) if err != nil { return err }
err = ctx.GetStub().PutState(asset.ID, updatedAsset) if err != nil { return fmt.Errorf("failed to write asset for buyer: %v", err) }
err = setAssetStateBasedEndorsement(ctx, asset.ID, buyerOrgID) if err != nil { return fmt.Errorf("failed setting state based endorsement for new owner: %v", err) }
collectionSeller := buildCollectionName(clientOrgID) err = ctx.GetStub().DelPrivateData(collectionSeller, asset.ID) if err != nil { return fmt.Errorf("failed to delete Asset private details from seller: %v", err) }
collectionBuyer := buildCollectionName(buyerOrgID) err = ctx.GetStub().PutPrivateData(collectionBuyer, asset.ID, immutablePropertiesJSON) if err != nil { return fmt.Errorf("failed to put Asset private properties for buyer: %v", err) }
assetPriceKey, err := ctx.GetStub().CreateCompositeKey(typeAssetForSale, []string{asset.ID}) if err != nil { return fmt.Errorf("failed to create composite key for seller: %v", err) }
err = ctx.GetStub().DelPrivateData(collectionSeller, assetPriceKey) if err != nil { return fmt.Errorf("failed to delete asset price from implicit private data collection for seller: %v", err) }
assetPriceKey, err = ctx.GetStub().CreateCompositeKey(typeAssetBid, []string{asset.ID}) if err != nil { return fmt.Errorf("failed to create composite key for buyer: %v", err) }
err = ctx.GetStub().DelPrivateData(collectionBuyer, assetPriceKey) if err != nil { return fmt.Errorf("failed to delete asset price from implicit private data collection for buyer: %v", err) }
receiptBuyKey, err := ctx.GetStub().CreateCompositeKey(typeAssetBuyReceipt, []string{asset.ID, ctx.GetStub().GetTxID()}) if err != nil { return fmt.Errorf("failed to create composite key for receipt: %v", err) }
txTimestamp, err := ctx.GetStub().GetTxTimestamp() if err != nil { return fmt.Errorf("failed to create timestamp for receipt: %v", err) }
timestamp, err := ptypes.Timestamp(txTimestamp) if err != nil { return err } assetReceipt := receipt{ price: price, timestamp: timestamp, } receipt, err := json.Marshal(assetReceipt) if err != nil { return fmt.Errorf("failed to marshal receipt: %v", err) }
err = ctx.GetStub().PutPrivateData(collectionBuyer, receiptBuyKey, receipt) if err != nil { return fmt.Errorf("failed to put private asset receipt for buyer: %v", err) }
receiptSaleKey, err := ctx.GetStub().CreateCompositeKey(typeAssetSaleReceipt, []string{ctx.GetStub().GetTxID(), asset.ID}) if err != nil { return fmt.Errorf("failed to create composite key for receipt: %v", err) }
err = ctx.GetStub().PutPrivateData(collectionSeller, receiptSaleKey, receipt) if err != nil { return fmt.Errorf("failed to put private asset receipt for seller: %v", err) }
return nil }
func getClientOrgID(ctx contractapi.TransactionContextInterface, verifyOrg bool) (string, error) {
clientOrgID, err := ctx.GetClientIdentity().GetMSPID() if err != nil { return "", fmt.Errorf("failed getting client's orgID: %v", err) }
if verifyOrg { err = verifyClientOrgMatchesPeerOrg(clientOrgID) if err != nil { return "", err } }
return clientOrgID, nil }
func verifyClientOrgMatchesPeerOrg(clientOrgID string) error { peerOrgID, err := shim.GetMSPID() if err != nil { return fmt.Errorf("failed getting peer's orgID: %v", err) }
if clientOrgID != peerOrgID { return fmt.Errorf("client from org %s is not authorized to read or write private data from an org %s peer", clientOrgID, peerOrgID, ) }
return nil }
func setAssetStateBasedEndorsement(ctx contractapi.TransactionContextInterface, assetID string, orgToEndorse string) error {
endorsementPolicy, err := statebased.NewStateEP(nil) if err != nil { return err } err = endorsementPolicy.AddOrgs(statebased.RoleTypeMember, orgToEndorse) if err != nil { return fmt.Errorf("failed to add org to endorsement policy: %v", err) } policy, err := endorsementPolicy.Policy() if err != nil { return fmt.Errorf("failed to create endorsement policy bytes from org: %v", err) } return ctx.GetStub().SetStateValidationParameter(assetID, policy) }
func buildCollectionName(clientOrgID string) string { return fmt.Sprintf("_implicit_org_%s", clientOrgID) }
func getClientImplicitCollectionName(ctx contractapi.TransactionContextInterface) (string, error) { clientOrgID, err := getClientOrgID(ctx, true) if err != nil { return "", fmt.Errorf("failed to get verified OrgID: %v", err) }
err = verifyClientOrgMatchesPeerOrg(clientOrgID) if err != nil { return "", err }
return buildCollectionName(clientOrgID), nil }
func main() { chaincode, err := contractapi.NewChaincode(new(SmartContract)) if err != nil { log.Panicf("Error create transfer asset chaincode: %v", err) }
if err := chaincode.Start(); err != nil { log.Panicf("Error starting asset chaincode: %v", err) } }
|