This commit is contained in:
Vishal More 2026-06-04 10:57:06 +05:30 committed by GitHub
commit 9929354fb3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 488 additions and 1 deletions

View file

@ -0,0 +1,11 @@
#
# SPDX-License-Identifier: Apache-2.0
#
---
smart_contract_name: "asset-transfer"
smart_contract_version: "1.0.0"
smart_contract_sequence: 1
smart_contract_package: "asset-transfer.tgz"
# smart_contract_constructor: "initLedger"
smart_contract_endorsement_policy: ""
smart_contract_collections_file: ""

View file

@ -0,0 +1,363 @@
package main
import (
"encoding/json"
"fmt"
"github.com/hyperledger/fabric-chaincode-go/v2/pkg/statebased"
"github.com/hyperledger/fabric-contract-api-go/v2/contractapi"
)
type SmartContract struct {
contractapi.Contract
}
type Asset struct {
AppraisedValue int `json:"AppraisedValue"`
Color string `json:"Color"`
ID string `json:"ID"`
Owner string `json:"Owner"`
Size int `json:"Size"`
}
type OwnerIdentifier struct {
Org string `json:"org"`
User string `json:"user"`
}
type AssetCreateInput struct {
ID string `json:"ID"`
Color string `json:"Color,omitempty"`
Owner *string `json:"Owner,omitempty"`
AppraisedValue *int `json:"AppraisedValue,omitempty"`
Size *int `json:"Size,omitempty"`
}
type AssetUpdateInput struct {
ID string `json:"ID"`
Color *string `json:"Color,omitempty"`
AppraisedValue *int `json:"AppraisedValue,omitempty"`
Size *int `json:"Size,omitempty"`
Owner *string `json:"Owner,omitempty"`
}
func (s *SmartContract) CreateAsset(ctx contractapi.TransactionContextInterface, assetJSON string) error {
input, err := parseCreateInput(assetJSON)
if err != nil {
return err
}
exists, err := s.AssetExists(ctx, input.ID)
if err != nil {
return err
}
if exists {
return fmt.Errorf("the asset %s already exists", input.ID)
}
owner, err := clientIdentifier(ctx, input.Owner)
if err != nil {
return err
}
asset := Asset{
ID: input.ID,
Color: input.Color,
Size: valueOrDefault(input.Size, 0),
Owner: marshalOwner(owner),
AppraisedValue: valueOrDefault(input.AppraisedValue, 0),
}
assetBytes, err := json.Marshal(asset)
if err != nil {
return err
}
if err := ctx.GetStub().PutState(asset.ID, assetBytes); err != nil {
return fmt.Errorf("failed to put asset in world state: %w", err)
}
if err := setEndorsingOrgs(ctx, asset.ID, owner.Org); err != nil {
return err
}
return ctx.GetStub().SetEvent("CreateAsset", assetBytes)
}
func (s *SmartContract) ReadAsset(ctx contractapi.TransactionContextInterface, id string) (*Asset, error) {
asset, err := s.readAsset(ctx, id)
if err != nil {
return nil, err
}
return asset, nil
}
func (s *SmartContract) UpdateAsset(ctx contractapi.TransactionContextInterface, assetJSON string) error {
input, err := parseUpdateInput(assetJSON)
if err != nil {
return err
}
existingAsset, err := s.readAsset(ctx, input.ID)
if err != nil {
return err
}
if err := hasWritePermission(ctx, existingAsset); err != nil {
return err
}
updatedAsset := *existingAsset
if input.Color != nil {
updatedAsset.Color = *input.Color
}
if input.Size != nil {
updatedAsset.Size = *input.Size
}
if input.AppraisedValue != nil {
updatedAsset.AppraisedValue = *input.AppraisedValue
}
// Owner cannot be updated via UpdateAsset. TransferAsset must be used for ownership changes.
assetBytes, err := json.Marshal(updatedAsset)
if err != nil {
return err
}
if err := ctx.GetStub().PutState(updatedAsset.ID, assetBytes); err != nil {
return fmt.Errorf("failed to put updated asset in world state: %w", err)
}
clientOrg, err := getClientOrg(ctx)
if err != nil {
return err
}
if err := setEndorsingOrgs(ctx, updatedAsset.ID, clientOrg); err != nil {
return err
}
if err := ctx.GetStub().SetEvent("UpdateAsset", assetBytes); err != nil {
return err
}
return nil
}
func (s *SmartContract) DeleteAsset(ctx contractapi.TransactionContextInterface, id string) error {
asset, err := s.readAsset(ctx, id)
if err != nil {
return err
}
if err := hasWritePermission(ctx, asset); err != nil {
return err
}
if err := ctx.GetStub().DelState(id); err != nil {
return fmt.Errorf("failed to delete asset %s: %w", id, err)
}
return ctx.GetStub().SetEvent("DeleteAsset", []byte(id))
}
func (s *SmartContract) AssetExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) {
assetBytes, err := ctx.GetStub().GetState(id)
if err != nil {
return false, fmt.Errorf("failed to read world state: %w", err)
}
return len(assetBytes) > 0, nil
}
func (s *SmartContract) TransferAsset(ctx contractapi.TransactionContextInterface, id string, newOwner string, newOwnerOrg string) error {
asset, err := s.readAsset(ctx, id)
if err != nil {
return err
}
if err := hasWritePermission(ctx, asset); err != nil {
return err
}
owner := ownerIdentifier(newOwner, newOwnerOrg)
ownerJSON, err := json.Marshal(owner)
if err != nil {
return err
}
asset.Owner = string(ownerJSON)
assetBytes, err := json.Marshal(asset)
if err != nil {
return err
}
if err := ctx.GetStub().PutState(id, assetBytes); err != nil {
return fmt.Errorf("failed to update asset owner in world state: %w", err)
}
if err := setEndorsingOrgs(ctx, id, newOwnerOrg); err != nil {
return err
}
return ctx.GetStub().SetEvent("TransferAsset", assetBytes)
}
func (s *SmartContract) GetAllAssets(ctx contractapi.TransactionContextInterface) ([]Asset, error) {
resultsIterator, err := ctx.GetStub().GetStateByRange("", "")
if err != nil {
return nil, err
}
defer resultsIterator.Close()
var assets []Asset
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return nil, err
}
var asset Asset
if err := json.Unmarshal(queryResponse.Value, &asset); err != nil {
continue
}
assets = append(assets, asset)
}
return assets, nil
}
func (s *SmartContract) readAsset(ctx contractapi.TransactionContextInterface, id string) (*Asset, error) {
assetBytes, err := ctx.GetStub().GetState(id)
if err != nil {
return nil, fmt.Errorf("failed to read world state: %w", err)
}
if assetBytes == nil || len(assetBytes) == 0 {
return nil, fmt.Errorf("sorry, asset %s has not been created", id)
}
var asset Asset
if err := json.Unmarshal(assetBytes, &asset); err != nil {
return nil, fmt.Errorf("failed to unmarshal asset %s: %w", id, err)
}
return &asset, nil
}
func parseCreateInput(assetJSON string) (*AssetCreateInput, error) {
var input AssetCreateInput
if err := json.Unmarshal([]byte(assetJSON), &input); err != nil {
return nil, fmt.Errorf("failed to parse asset JSON: %w", err)
}
if input.ID == "" {
return nil, fmt.Errorf("missing ID")
}
return &input, nil
}
func parseUpdateInput(assetJSON string) (*AssetUpdateInput, error) {
var input AssetUpdateInput
if err := json.Unmarshal([]byte(assetJSON), &input); err != nil {
return nil, fmt.Errorf("failed to parse asset JSON: %w", err)
}
if input.ID == "" {
return nil, fmt.Errorf("no asset ID specified")
}
return &input, nil
}
func valueOrDefault(value *int, def int) int {
if value == nil {
return def
}
return *value
}
func hasWritePermission(ctx contractapi.TransactionContextInterface, asset *Asset) error {
clientOrg, err := getClientOrg(ctx)
if err != nil {
return err
}
var owner OwnerIdentifier
if err := json.Unmarshal([]byte(asset.Owner), &owner); err != nil {
return fmt.Errorf("invalid owner identity: %w", err)
}
if clientOrg != owner.Org {
return fmt.Errorf("only owner can update assets")
}
return nil
}
func getClientOrg(ctx contractapi.TransactionContextInterface) (string, error) {
return ctx.GetClientIdentity().GetMSPID()
}
func clientIdentifier(ctx contractapi.TransactionContextInterface, user *string) (OwnerIdentifier, error) {
clientOrg, err := getClientOrg(ctx)
if err != nil {
return OwnerIdentifier{}, err
}
userName := ""
if user != nil {
userName = *user
} else {
userName, err = clientCommonName(ctx)
if err != nil {
return OwnerIdentifier{}, err
}
}
return OwnerIdentifier{
Org: clientOrg,
User: userName,
}, nil
}
func clientCommonName(ctx contractapi.TransactionContextInterface) (string, error) {
cert, err := ctx.GetClientIdentity().GetX509Certificate()
if err != nil {
return "", fmt.Errorf("unable to get client certificate: %w", err)
}
if cert.Subject.CommonName == "" {
return "", fmt.Errorf("unable to identify client identity common name")
}
return cert.Subject.CommonName, nil
}
func marshalOwner(owner OwnerIdentifier) string {
ownerBytes, _ := json.Marshal(owner)
return string(ownerBytes)
}
func ownerIdentifier(user string, org string) OwnerIdentifier {
return OwnerIdentifier{Org: org, User: user}
}
func setEndorsingOrgs(ctx contractapi.TransactionContextInterface, ledgerKey string, orgs ...string) error {
policy, err := statebased.NewStateEP(nil)
if err != nil {
return err
}
if err = policy.AddOrgs(statebased.RoleTypePeer, orgs...); err != nil {
return err
}
policyBytes, err := policy.Policy()
if err != nil {
return err
}
return ctx.GetStub().SetStateValidationParameter(ledgerKey, policyBytes)
}

View file

@ -0,0 +1,28 @@
module github.com/hyperledger/fabric-samples/full-stack-asset-transfer-guide/contracts/asset-transfer-go
go 1.21.0
require (
github.com/hyperledger/fabric-chaincode-go/v2 v2.0.0
github.com/hyperledger/fabric-contract-api-go/v2 v2.2.0
)
require (
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonreference v0.21.0 // indirect
github.com/go-openapi/spec v0.21.0 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/hyperledger/fabric-protos-go-apiv2 v0.3.4 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/text v0.17.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 // indirect
google.golang.org/grpc v1.67.0 // indirect
google.golang.org/protobuf v1.36.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View file

@ -0,0 +1,61 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY=
github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/hyperledger/fabric-chaincode-go/v2 v2.0.0 h1:IhkHfrl5X/fVnmB6pWeCYCdIJRi9bxj+WTnVN8DtW3c=
github.com/hyperledger/fabric-chaincode-go/v2 v2.0.0/go.mod h1:PHHaFffjw7p7n9bmCfcm7RqDqYdivNEsJdiNIKZo5Lk=
github.com/hyperledger/fabric-contract-api-go/v2 v2.2.0 h1:rmUoBmciB0GL/miqcbJmJbgp5QTWoJUrZo+CNxrNLF4=
github.com/hyperledger/fabric-contract-api-go/v2 v2.2.0/go.mod h1:FeWeO/jwGjiME7ak3GufqKIcwkejtzrDG4QxbfKydWs=
github.com/hyperledger/fabric-protos-go-apiv2 v0.3.4 h1:YJrd+gMaeY0/vsN0aS0QkEKTivGoUnSRIXxGJ7KI+Pc=
github.com/hyperledger/fabric-protos-go-apiv2 v0.3.4/go.mod h1:bau/6AJhvEcu9GKKYHlDXAxXKzYNfhP6xu2GXuxEcFk=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 h1:e7S5W7MGGLaSu8j3YjdezkZ+m1/Nm0uRVRMEMGk26Xs=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU=
google.golang.org/grpc v1.67.0 h1:IdH9y6PF5MPSdAntIcpjQ+tXO41pcQsfZV2RxtQgVcw=
google.golang.org/grpc v1.67.0/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA=
google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk=
google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View file

@ -0,0 +1,18 @@
package main
import (
"log"
"github.com/hyperledger/fabric-contract-api-go/v2/contractapi"
)
func main() {
chaincode, err := contractapi.NewChaincode(&SmartContract{})
if err != nil {
log.Panicf("Error creating asset-transfer-go chaincode: %v", err)
}
if err := chaincode.Start(); err != nil {
log.Panicf("Error starting asset-transfer-go chaincode: %v", err)
}
}

View file

@ -1,13 +1,19 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@tsconfig/node20/tsconfig.json",
"compilerOptions": {
"target": "ES2023",
"module": "es2022",
"moduleResolution": "bundler",
"lib": ["ES2023"],
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "dist",
"rootDir": "src",
"strict": true,
"noUnusedLocals": true,
"noImplicitReturns": true,