From a13c19212f29098e60490758afec4f00522de4b6 Mon Sep 17 00:00:00 2001 From: Angelo De Caro Date: Wed, 27 Nov 2024 14:15:56 +0100 Subject: [PATCH] remove fpc Signed-off-by: Angelo De Caro --- .github/workflows/tests.yml | 1 - Makefile | 14 +- go.mod | 1 - go.sum | 2 - integration/fabric/fpc/echo/README.md | 86 ---- .../fabric/fpc/echo/echo_suite_test.go | 25 - integration/fabric/fpc/echo/echo_test.go | 68 --- integration/fabric/fpc/echo/topology.go | 55 --- integration/fabric/fpc/echo/views/echo.go | 122 ----- integration/fabric/fpc/echo/views/ercc.go | 40 -- integration/nwo/fabric/fpc/attestation.go | 17 - integration/nwo/fabric/fpc/chaincode.go | 243 ---------- integration/nwo/fabric/fpc/connections.go | 142 ------ .../fabric/fpc/externalbuilders/scripts.go | 90 ---- integration/nwo/fabric/fpc/fpc.go | 442 ------------------ integration/nwo/fabric/platform.go | 14 - integration/nwo/fabric/topology/fpc.go | 113 ----- integration/nwo/fabric/topology/topology.go | 1 - integration/ports.go | 1 - .../fabric/services/chaincode/chaincode.go | 88 ---- platform/fabric/services/chaincode/endorse.go | 15 +- platform/fabric/services/chaincode/invoke.go | 15 +- platform/fabric/services/chaincode/query.go | 15 +- platform/fabric/services/fpc/chaincode.go | 99 ---- platform/fabric/services/fpc/channel.go | 78 ---- platform/fabric/services/fpc/contract.go | 217 --------- .../fabric/services/fpc/enclaveregistry.go | 90 ---- platform/fabric/services/fpc/endorse.go | 88 ---- platform/fabric/services/fpc/invoke.go | 59 --- platform/fabric/services/fpc/query.go | 84 ---- samples/README.md | 2 - 31 files changed, 6 insertions(+), 2321 deletions(-) delete mode 100644 integration/fabric/fpc/echo/README.md delete mode 100644 integration/fabric/fpc/echo/echo_suite_test.go delete mode 100644 integration/fabric/fpc/echo/echo_test.go delete mode 100644 integration/fabric/fpc/echo/topology.go delete mode 100644 integration/fabric/fpc/echo/views/echo.go delete mode 100644 integration/fabric/fpc/echo/views/ercc.go delete mode 100644 integration/nwo/fabric/fpc/attestation.go delete mode 100644 integration/nwo/fabric/fpc/chaincode.go delete mode 100644 integration/nwo/fabric/fpc/connections.go delete mode 100644 integration/nwo/fabric/fpc/externalbuilders/scripts.go delete mode 100644 integration/nwo/fabric/fpc/fpc.go delete mode 100644 integration/nwo/fabric/topology/fpc.go delete mode 100644 platform/fabric/services/fpc/chaincode.go delete mode 100644 platform/fabric/services/fpc/channel.go delete mode 100644 platform/fabric/services/fpc/contract.go delete mode 100644 platform/fabric/services/fpc/enclaveregistry.go delete mode 100644 platform/fabric/services/fpc/endorse.go delete mode 100644 platform/fabric/services/fpc/invoke.go delete mode 100644 platform/fabric/services/fpc/query.go diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7cfda7bd0..55e557bba 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -64,7 +64,6 @@ jobs: atsacc, fabric-stoprestart, atsafsc, - fpc-echo, iou, iou-hsm, orioncars, diff --git a/Makefile b/Makefile index 266cebbb9..1894af0c8 100755 --- a/Makefile +++ b/Makefile @@ -48,7 +48,7 @@ unit-tests-race: cd integration/nwo/; export FAB_BINS=$(FAB_BINS); go test -cover ./... .PHONY: docker-images -docker-images: fabric-docker-images weaver-docker-images fpc-docker-images orion-server-images monitoring-docker-images testing-docker-images +docker-images: fabric-docker-images weaver-docker-images orion-server-images monitoring-docker-images testing-docker-images .PHONY: fabric-docker-images fabric-docker-images: @@ -64,13 +64,6 @@ weaver-docker-images: docker pull ghcr.io/hyperledger-labs/weaver-relay-server:1.2.1 docker image tag ghcr.io/hyperledger-labs/weaver-relay-server:1.2.1 hyperledger-labs/weaver-relay-server:latest -.PHONY: fpc-docker-images -fpc-docker-images: - docker pull ghcr.io/mbrandenburger/fpc/ercc:main - docker image tag ghcr.io/mbrandenburger/fpc/ercc:main fpc/ercc:latest - docker pull ghcr.io/mbrandenburger/fpc/fpc-echo:main - docker image tag ghcr.io/mbrandenburger/fpc/fpc-echo:main fpc/fpc-echo:latest - .PHONY: monitoring-docker-images monitoring-docker-images: docker pull ghcr.io/hyperledger-labs/explorer-db:latest @@ -128,10 +121,6 @@ integration-tests-atsafsc: integration-tests-twonets: cd ./integration/fabric/twonets; export FAB_BINS=$(FAB_BINS); ginkgo $(GINKGO_TEST_OPTS) . -.PHONY: integration-tests-fpc-echo -integration-tests-fpc-echo: - cd ./integration/fabric/fpc/echo; export FAB_BINS=$(FAB_BINS); ginkgo $(GINKGO_TEST_OPTS) . - .PHONY: integration-tests-weaver-relay integration-tests-weaver-relay: cd ./integration/fabric/weaver/relay; export FAB_BINS=$(FAB_BINS); ginkgo $(GINKGO_TEST_OPTS) . @@ -172,7 +161,6 @@ clean: rm -rf ./integration/fabric/iou/testdata/ rm -rf ./integration/fabric/twonets/cmd rm -rf ./integration/fabric/weaver/relay/cmd - rm -rf ./integration/fabric/fpc/echo/cmd rm -rf ./integration/fabric/stoprestart/cmd rm -rf ./integration/fsc/stoprestart/cmd rm -rf ./integration/orion/cars/cmd diff --git a/go.mod b/go.mod index 8533df4ef..ea8aa12b5 100644 --- a/go.mod +++ b/go.mod @@ -29,7 +29,6 @@ require ( github.com/hyperledger/fabric-chaincode-go v0.0.0-20240704073638-9fb89180dc17 github.com/hyperledger/fabric-contract-api-go v1.2.2 github.com/hyperledger/fabric-lib-go v1.1.2 - github.com/hyperledger/fabric-private-chaincode v1.0.0-rc3.0.20231026135044-67a19b0fcda0 github.com/hyperledger/fabric-protos-go v0.3.3 github.com/jackc/pgx/v5 v5.6.0 github.com/jellydator/ttlcache/v2 v2.11.1 diff --git a/go.sum b/go.sum index 828b478e2..310fc7566 100644 --- a/go.sum +++ b/go.sum @@ -1181,8 +1181,6 @@ github.com/hyperledger/fabric-contract-api-go v1.2.2/go.mod h1:UnFLlRFn8GvXE7mXx github.com/hyperledger/fabric-lib-go v1.0.0/go.mod h1:H362nMlunurmHwkYqR5uHL2UDWbQdbfz74n8kbCFsqc= github.com/hyperledger/fabric-lib-go v1.1.2 h1:3eHwudGZC5Ex7go5UAzVKhpF34gypPZGfSZksBKLWvE= github.com/hyperledger/fabric-lib-go v1.1.2/go.mod h1:SHNCq8AB0VpHAmvJEtdbzabv6NNV1F48JdmDihasBjc= -github.com/hyperledger/fabric-private-chaincode v1.0.0-rc3.0.20231026135044-67a19b0fcda0 h1:TLVkWq6aTVttBJ5WiHMeh/gufo+lPnYN9rVuEb8qXRs= -github.com/hyperledger/fabric-private-chaincode v1.0.0-rc3.0.20231026135044-67a19b0fcda0/go.mod h1:Q7jUjJfkL/5ZmO6c0DL0DKjN63Yp7ULe9tun+9G76eY= github.com/hyperledger/fabric-protos-go v0.0.0-20200424173316-dd554ba3746e/go.mod h1:xVYTjK4DtZRBxZ2D9aE4y6AbLaPwue2o/criQyQbVD0= github.com/hyperledger/fabric-protos-go v0.0.0-20200707132912-fee30f3ccd23/go.mod h1:xVYTjK4DtZRBxZ2D9aE4y6AbLaPwue2o/criQyQbVD0= github.com/hyperledger/fabric-protos-go v0.3.3 h1:0nssqz8QWJNVNBVQz+IIfAd2j1ku7QPKFSM/1anKizI= diff --git a/integration/fabric/fpc/echo/README.md b/integration/fabric/fpc/echo/README.md deleted file mode 100644 index 24f4fb7cb..000000000 --- a/integration/fabric/fpc/echo/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# Fabric Private Chaincode - -[`Hyperledger Fabric Private Chaincode (FPC)`](https://github.com/hyperledger/fabric-private-chaincode) -enables the execution of chaincodes using Intel SGX for Hyperledger Fabric. - -## Echo - -Echo is a very simple chaincode written in C++ for SGX that returns the name of the function -that has been invoked. In our test, we will make sure that this is what happens. - -### Invoking Echo - -Here is an example of a View that invokes the Echo FPC: - -```go -// Echo models the parameters to be used to invoke the Echo FPC -type Echo struct { - // Function to invoke - Function string - // Args to pass to the function - Args []string -} - -// EchoView models a View that invokes the Echo FPC -type EchoView struct { - *Echo -} - -func (e *EchoView) Call(context view.Context) (interface{}, error) { - // Invoke the `echo` chaincode deployed on the default channel of the default Fbairc network - res, err := fpc.GetDefaultChannel(context).Chaincode( - "echo", - ).Invoke( - e.Function, fpc.StringsToArgs(e.Args)..., - ).Call() - assert.NoError(err, "failed invoking echo") - assert.Equal(e.Function, string(res)) - - return res, nil -} - -type EchoViewFactory struct{} - -func (l *EchoViewFactory) NewView(in []byte) (view.View, error) { - f := &EchoView{} - assert.NoError(json.Unmarshal(in, &f.Echo)) - return f, nil -} -``` - -### Topology - -It is very simple to add an FPC to a Fabric topology and have it ready to be used for our integration tests. -The important thing is to have already prepared the docker image with the FPC one wants to deploy. -On how to build an FPC, please, refer to the [`Fabric Private Chaincode documentation`](https://github.com/hyperledger/fabric-private-chaincode#build-fabric-private-chaincode). -In our case, we will use the following docker image `ghcr.io/mbrandenburger/fpc/fpc-echo:main`. - -Here is the topology we use in this case, it is self-explanatory: - -```go -func Topology() []api.Topology { - // Create an empty fabric topology - fabricTopology := fabric.NewDefaultTopology() - // Add two organizations - fabricTopology.AddOrganizationsByName("Org1", "Org2") - // Add an FPC by passing chaincode's id and docker image - fabricTopology.AddFPC("echo", "fpc/fpc-echo") - - // Create an empty FSC topology - fscTopology := fsc.NewTopology() - - // Alice - alice := fscTopology.AddNodeByName("alice") - alice.AddOptions(fabric.WithOrganization("Org2")) - alice.RegisterViewFactory("ListProvisionedEnclaves", &views.ListProvisionedEnclavesViewFactory{}) - alice.RegisterViewFactory("Echo", &views.EchoViewFactory{}) - - // Bob - bob := fscTopology.AddNodeByName("bob") - bob.AddOptions(fabric.WithOrganization("Org2")) - bob.RegisterViewFactory("ListProvisionedEnclaves", &views.ListProvisionedEnclavesViewFactory{}) - bob.RegisterViewFactory("Echo", &views.EchoViewFactory{}) - - return []api.Topology{fabricTopology, fscTopology} -} -``` \ No newline at end of file diff --git a/integration/fabric/fpc/echo/echo_suite_test.go b/integration/fabric/fpc/echo/echo_suite_test.go deleted file mode 100644 index 5b999054b..000000000 --- a/integration/fabric/fpc/echo/echo_suite_test.go +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright IBM Corp All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package echo_test - -import ( - "testing" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "github.com/hyperledger-labs/fabric-smart-client/integration" -) - -func TestEndToEnd(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "FPC Echo Suite") -} - -func StartPort() int { - return integration.FPCEchoPort.StartPortForNode() -} diff --git a/integration/fabric/fpc/echo/echo_test.go b/integration/fabric/fpc/echo/echo_test.go deleted file mode 100644 index 2fa66c32d..000000000 --- a/integration/fabric/fpc/echo/echo_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright IBM Corp All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package echo_test - -import ( - "github.com/hyperledger-labs/fabric-smart-client/integration/fabric/fpc/echo" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fsc" - fabricsdk "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/sdk/dig" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "github.com/hyperledger-labs/fabric-smart-client/integration" - "github.com/hyperledger-labs/fabric-smart-client/integration/fabric/fpc/echo/views" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/common" -) - -var _ = Describe("EndToEnd", func() { - Describe("Echo FPC With LibP2P", func() { - s := NewTestSuite(fsc.LibP2P, integration.NoReplication) - BeforeEach(s.Setup) - AfterEach(s.TearDown) - It("succeeded", s.TestSucceeded) - }) - - Describe("Echo FPC With Websockets", func() { - s := NewTestSuite(fsc.WebSocket, integration.NoReplication) - BeforeEach(s.Setup) - AfterEach(s.TearDown) - It("succeeded", s.TestSucceeded) - }) -}) - -type TestSuite struct { - *integration.TestSuite -} - -func NewTestSuite(commType fsc.P2PCommunicationType, nodeOpts *integration.ReplicationOptions) *TestSuite { - return &TestSuite{integration.NewTestSuite(func() (*integration.Infrastructure, error) { - return integration.Generate(StartPort(), true, echo.Topology(&fabricsdk.SDK{}, commType, nodeOpts)...) - })} -} - -func (s *TestSuite) TestSucceeded() { - provisionedEnclavesBoxed, err := s.II.Client("alice").CallView( - "ListProvisionedEnclaves", - common.JSONMarshall(&views.ListProvisionedEnclaves{ - CID: "echo", - }), - ) - Expect(err).ToNot(HaveOccurred()) - var provisionedEnclaves []string - common.JSONUnmarshal(provisionedEnclavesBoxed.([]byte), &provisionedEnclaves) - Expect(len(provisionedEnclaves)).To(BeEquivalentTo(1)) - - resBoxed, err := s.II.Client("alice").CallView( - "Echo", - common.JSONMarshall(&views.Echo{ - Function: "myFunction", - Args: []string{"arg1", "arg2", "arg3"}, - }), - ) - Expect(err).ToNot(HaveOccurred()) - Expect(resBoxed).To(BeEquivalentTo("myFunction")) -} diff --git a/integration/fabric/fpc/echo/topology.go b/integration/fabric/fpc/echo/topology.go deleted file mode 100644 index 402977adb..000000000 --- a/integration/fabric/fpc/echo/topology.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package echo - -import ( - "github.com/hyperledger-labs/fabric-smart-client/integration" - "github.com/hyperledger-labs/fabric-smart-client/integration/fabric/fpc/echo/views" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/api" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fsc" - api2 "github.com/hyperledger-labs/fabric-smart-client/pkg/api" -) - -func Topology(sdk api2.SDK, commType fsc.P2PCommunicationType, replicationOpts *integration.ReplicationOptions) []api.Topology { - // Create an empty fabric topology - fabricTopology := fabric.NewDefaultTopology() - // Note that Idemix is currently not supported by FPC - // fabricTopology.EnableIdemix() - // Add two organizations - fabricTopology.AddOrganizationsByName("Org1", "Org2") - // Add a standard chaincode - // fabricTopology.AddNamespaceWithUnanimity("mycc", "Org1", "Org2") - // Add an FPC by passing chaincode's id and docker image - fabricTopology.AddFPC("echo", "fpc/fpc-echo").AddPostRunInvocation( - "init", "init", []byte("init"), - ) - - // Create an empty FSC topology - fscTopology := fsc.NewTopology() - fscTopology.P2PCommunicationType = commType - //fscTopology.SetLogging("debug", "") - - // Alice - fscTopology.AddNodeByName("alice"). - AddOptions(fabric.WithOrganization("Org2")). - AddOptions(replicationOpts.For("alice")...). - RegisterViewFactory("ListProvisionedEnclaves", &views.ListProvisionedEnclavesViewFactory{}). - RegisterViewFactory("Echo", &views.EchoViewFactory{}) - - // Bob - fscTopology.AddNodeByName("bob"). - AddOptions(fabric.WithOrganization("Org2")). - AddOptions(replicationOpts.For("bob")...). - RegisterViewFactory("ListProvisionedEnclaves", &views.ListProvisionedEnclavesViewFactory{}). - RegisterViewFactory("Echo", &views.EchoViewFactory{}) - - // Add Fabric SDK to FSC Nodes - fscTopology.AddSDK(sdk) - - return []api.Topology{fabricTopology, fscTopology} -} diff --git a/integration/fabric/fpc/echo/views/echo.go b/integration/fabric/fpc/echo/views/echo.go deleted file mode 100644 index 864b73e02..000000000 --- a/integration/fabric/fpc/echo/views/echo.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright IBM Corp All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package views - -import ( - "encoding/json" - "time" - - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/chaincode" - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/fpc" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/assert" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" -) - -// Echo models the parameters to be used to invoke the Echo FPC -type Echo struct { - // Function to invoke - Function string - // Args to pass to the function - Args []string -} - -// EchoView models a View that invokes the Echo FPC -type EchoView struct { - *Echo -} - -func (e *EchoView) Call(context view.Context) (interface{}, error) { - ch, err := fpc.GetDefaultChannel(context) - assert.NoError(err) - v, err := ch.EnclaveRegistry().IsAvailable() - assert.NoError(err, "failed checking availability of the enclave registry") - assert.True(v, "the enclave registry is not available") - - v, err = ch.EnclaveRegistry().IsPrivate("echo") - assert.NoError(err, "failed checking echo deployment") - assert.True(v, "echo should be an FPC") - - v, err = ch.EnclaveRegistry().IsPrivate("mycc") - assert.NoError(err, "failed checking mycc deployment") - assert.False(v, "mycc should be a standard CC") - - // Invoke the `echo` chaincode deployed on the default channel of the default Fabric network - res, err := ch.Chaincode( - "echo", - ).Invoke( - e.Function, fpc.StringsToArgs(e.Args)..., - ).Call() - assert.NoError(err, "failed invoking echo") - assert.Equal(e.Function, string(res)) - - fns, err := fabric.GetDefaultFNS(context) - assert.NoError(err) - _, res, err = chaincode.NewInvokeView( - "echo", - e.Function, - fpc.StringsToArgs(e.Args)..., - ).WithSignerIdentity( - fns.LocalMembership().DefaultIdentity(), - ).Invoke(context) - assert.NoError(err, "failed invoking echo") - assert.Equal(e.Function, string(res)) - - // Query the `echo` chaincode deployed on the default channel of the default Fabric network - res, err = ch.Chaincode( - "echo", - ).Query( - e.Function, fpc.StringsToArgs(e.Args)..., - ).WithSignerIdentity( - fns.LocalMembership().DefaultIdentity(), - ).Call() - assert.NoError(err, "failed querying echo") - assert.Equal(e.Function, string(res)) - - res, err = chaincode.NewQueryView( - "echo", - e.Function, - fpc.StringsToArgs(e.Args)..., - ).WithSignerIdentity( - fns.LocalMembership().DefaultIdentity(), - ).Query(context) - assert.NoError(err, "failed querying echo") - assert.Equal(e.Function, string(res)) - - // Endorse the `echo` chaincode deployed on the default channel of the default Fabric network - envelope, err := ch.Chaincode( - "echo", - ).Endorse( - e.Function, fpc.StringsToArgs(e.Args)..., - ).WithSignerIdentity( - fns.LocalMembership().DefaultIdentity(), - ).Call() - assert.NoError(err, "failed endorsing echo") - assert.NotNil(envelope) - assert.NoError(fns.Ordering().Broadcast(context.Context(), envelope)) - - envelope, err = chaincode.NewEndorseView( - "echo", - e.Function, - fpc.StringsToArgs(e.Args)..., - ).WithSignerIdentity( - fns.LocalMembership().DefaultIdentity(), - ).WithNumRetries(4).WithRetrySleep(2 * time.Second).Endorse(context) - assert.NoError(err, "failed endorsing echo") - assert.Equal(e.Function, string(res)) - assert.NoError(fns.Ordering().Broadcast(context.Context(), envelope)) - - return res, nil -} - -type EchoViewFactory struct{} - -func (l *EchoViewFactory) NewView(in []byte) (view.View, error) { - f := &EchoView{} - assert.NoError(json.Unmarshal(in, &f.Echo)) - return f, nil -} diff --git a/integration/fabric/fpc/echo/views/ercc.go b/integration/fabric/fpc/echo/views/ercc.go deleted file mode 100644 index 70e4c4697..000000000 --- a/integration/fabric/fpc/echo/views/ercc.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright IBM Corp All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package views - -import ( - "encoding/json" - - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/fpc" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/assert" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" -) - -type ListProvisionedEnclaves struct { - CID string -} - -type ListProvisionedEnclavesView struct { - *ListProvisionedEnclaves -} - -func (l *ListProvisionedEnclavesView) Call(context view.Context) (interface{}, error) { - ch, err := fpc.GetDefaultChannel(context) - assert.NoError(err) - pEnclaves, err := ch.EnclaveRegistry().ListProvisionedEnclaves(l.CID) - assert.NoError(err, "failed getting list of provisioned enclaves for [%s]", l.CID) - - return pEnclaves, nil -} - -type ListProvisionedEnclavesViewFactory struct{} - -func (l *ListProvisionedEnclavesViewFactory) NewView(in []byte) (view.View, error) { - f := &ListProvisionedEnclavesView{} - assert.NoError(json.Unmarshal(in, &f.ListProvisionedEnclaves)) - return f, nil -} diff --git a/integration/nwo/fabric/fpc/attestation.go b/integration/nwo/fabric/fpc/attestation.go deleted file mode 100644 index c3f51a32c..000000000 --- a/integration/nwo/fabric/fpc/attestation.go +++ /dev/null @@ -1,17 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "github.com/hyperledger/fabric-private-chaincode/client_sdk/go/pkg/sgx" -) - -func CreateSIMAttestationParams() *sgx.AttestationParams { - return &sgx.AttestationParams{ - AttestationType: "simulated", - } -} diff --git a/integration/nwo/fabric/fpc/chaincode.go b/integration/nwo/fabric/fpc/chaincode.go deleted file mode 100644 index c7953ef37..000000000 --- a/integration/nwo/fabric/fpc/chaincode.go +++ /dev/null @@ -1,243 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "encoding/json" - "fmt" - - fpc "github.com/hyperledger/fabric-private-chaincode/client_sdk/go/pkg/core/contract" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" - - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/commands" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/network" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/topology" -) - -type ChannelProvider struct { - Network *network.Network - CC *topology.ChannelChaincode -} - -func (c *ChannelProvider) GetContract(id string) fpc.Contract { - // search the chaincode - switch id { - case c.CC.Chaincode.Name: - return &ChannelContract{ - Network: c.Network, - Channel: c.CC.Channel, - ChaincodeID: id, - CC: c.CC, - } - case "ercc": - for _, chaincode := range c.Network.Chaincodes(c.CC.Channel) { - if chaincode.Chaincode.Name == "ercc" { - return &ChannelContract{ - Network: c.Network, - Channel: chaincode.Channel, - ChaincodeID: id, - CC: chaincode, - } - } - } - panic(fmt.Sprintf("cannot find chaincode id [%s]", id)) - default: - panic(fmt.Sprintf("unspected chaincode id [%s]", id)) - } -} - -type ChannelTransaction struct { - Network *network.Network - ChaincodeID string - Channel string - CC *topology.ChannelChaincode - FunctionName string -} - -func (c *ChannelTransaction) Evaluate(args ...string) ([]byte, error) { - org := c.Network.PeerOrgs()[0] - peer := c.Network.Peer(org.Name, c.Network.PeersInOrgWithOptions(org.Name, false)[0].Name) - s := &struct { - Args []string `json:"Args,omitempty"` - }{} - s.Args = append(s.Args, c.FunctionName) - for _, arg := range args { - s.Args = append(s.Args, string(arg)) - } - ctor, err := json.Marshal(s) - Expect(err).NotTo(HaveOccurred()) - - sess, err := c.Network.PeerUserSession(peer, "User1", commands.ChaincodeQuery{ - ChannelID: c.Channel, - Name: c.CC.Chaincode.Name, - Ctor: string(ctor), - }) - Expect(err).NotTo(HaveOccurred()) - Eventually(sess, c.Network.EventuallyTimeout).Should(gexec.Exit(0)) - - return sess.Buffer().Contents(), nil -} - -type ChannelContract struct { - Network *network.Network - ChaincodeID string - Channel string - CC *topology.ChannelChaincode -} - -func (c *ChannelContract) Name() string { - return c.CC.Chaincode.Name -} - -func (c *ChannelContract) EvaluateTransaction(name string, args ...string) ([]byte, error) { - org := c.Network.PeerOrgs()[0] - peer := c.Network.Peer(org.Name, c.Network.PeersInOrgWithOptions(org.Name, false)[0].Name) - s := &struct { - Args []string `json:"Args,omitempty"` - }{} - s.Args = append(s.Args, name) - for _, arg := range args { - s.Args = append(s.Args, string(arg)) - } - ctor, err := json.Marshal(s) - Expect(err).NotTo(HaveOccurred()) - - sess, err := c.Network.PeerUserSession(peer, "User1", commands.ChaincodeQuery{ - ChannelID: c.Channel, - Name: c.CC.Chaincode.Name, - Ctor: string(ctor), - }) - Expect(err).NotTo(HaveOccurred()) - Eventually(sess, c.Network.EventuallyTimeout).Should(gexec.Exit(0)) - - return sess.Buffer().Contents(), nil -} - -func (c *ChannelContract) SubmitTransaction(name string, args ...string) ([]byte, error) { - orderer := c.Network.Orderer("orderer") - org := c.Network.PeerOrgs()[0] - peer := c.Network.Peer(org.Name, c.Network.PeersInOrgWithOptions(org.Name, false)[0].Name) - s := &struct { - Args []string `json:"Args,omitempty"` - }{} - s.Args = append(s.Args, name) - for _, arg := range args { - s.Args = append(s.Args, string(arg)) - } - ctor, err := json.Marshal(s) - Expect(err).NotTo(HaveOccurred()) - - // Peers - initOrgs := map[string]bool{} - var peerAddresses []string - peers := c.Network.PeersByName(c.CC.Peers) - for _, p := range peers { - if exists := initOrgs[p.Organization]; !exists { - peerAddresses = append(peerAddresses, c.Network.PeerAddress(p, network.ListenPort)) - initOrgs[p.Organization] = true - } - } - - sess, err := c.Network.PeerUserSession(peer, "User1", commands.ChaincodeInvoke{ - ChannelID: c.Channel, - Orderer: c.Network.OrdererAddress(orderer, network.ListenPort), - Name: c.CC.Chaincode.Name, - Ctor: string(ctor), - PeerAddresses: peerAddresses, - }) - Expect(err).NotTo(HaveOccurred()) - Eventually(sess, c.Network.EventuallyTimeout).Should(gexec.Exit(0)) - Expect(sess.Err).To(gbytes.Say("Chaincode invoke successful. result: status:200")) - - return sess.Buffer().Contents(), nil -} - -func (c *ChannelContract) CreateTransaction(name string, peerEndpoints ...string) (fpc.Transaction, error) { - return &ChannelTransaction{ - Network: c.Network, - ChaincodeID: c.ChaincodeID, - Channel: c.Channel, - CC: c.CC, - FunctionName: name, - }, nil -} - -type ChannelClient struct { - n *Extension - peer *topology.Peer - orderer *topology.Orderer - chaincode *topology.ChannelChaincode -} - -func (c *ChannelClient) Query(chaincodeID string, fcn string, args [][]byte, targetEndpoints ...string) ([]byte, error) { - ci := &ChaincodeInput{ - Args: append(append([]string{}, fcn), ArgsToStrings(args)...), - } - logger.Infof("query [%s] with args...", chaincodeID) - for i, arg := range ci.Args { - logger.Infof("arg [%d][%s]", i, arg) - } - ctor, err := json.Marshal(ci) - Expect(err).ToNot(HaveOccurred()) - - sess, err := c.n.network.PeerUserSession(c.peer, "User1", commands.ChaincodeQuery{ - ChannelID: c.chaincode.Channel, - Name: chaincodeID, - Ctor: string(ctor), - }) - Expect(err).NotTo(HaveOccurred()) - Eventually(sess, c.n.network.EventuallyTimeout).Should(gexec.Exit(0)) - - return sess.Buffer().Contents(), nil -} - -func (c *ChannelClient) Execute(chaincodeID string, fcn string, args [][]byte) (string, error) { - ci := &ChaincodeInput{ - Args: append(append([]string{}, fcn), ArgsToStrings(args)...), - } - ctor, err := json.Marshal(ci) - Expect(err).ToNot(HaveOccurred()) - - initOrgs := map[string]bool{} - var erccPeerAddresses []string - peers := c.n.network.PeersByName(c.n.FPCERCC.Peers) - for _, p := range peers { - if exists := initOrgs[p.Organization]; !exists { - erccPeerAddresses = append(erccPeerAddresses, c.n.network.PeerAddress(p, network.ListenPort)) - initOrgs[p.Organization] = true - } - } - - sess, err := c.n.network.PeerUserSession(c.peer, "User1", commands.ChaincodeInvoke{ - NetworkPrefix: c.n.network.Prefix, - ChannelID: c.chaincode.Channel, - Orderer: c.n.network.OrdererAddress(c.orderer, network.ListenPort), - Name: chaincodeID, - Ctor: string(ctor), - PeerAddresses: erccPeerAddresses, - WaitForEvent: true, - ClientAuth: c.n.network.ClientAuthRequired, - }) - Expect(err).NotTo(HaveOccurred()) - Eventually(sess, c.n.network.EventuallyTimeout).Should(gexec.Exit(0)) - for i := 0; i < len(erccPeerAddresses); i++ { - Eventually(sess.Err, c.n.network.EventuallyTimeout).Should(gbytes.Say(`\Qcommitted with status (VALID)\E`)) - } - Expect(sess.Err).To(gbytes.Say("Chaincode invoke successful. result: status:200")) - - return "", nil -} - -func ArgsToStrings(args [][]byte) []string { - var res []string - for _, arg := range args { - res = append(res, string(arg)) - } - return res -} diff --git a/integration/nwo/fabric/fpc/connections.go b/integration/nwo/fabric/fpc/connections.go deleted file mode 100644 index 01a0754d9..000000000 --- a/integration/nwo/fabric/fpc/connections.go +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "fmt" - "html/template" - "io" - "os" - "path/filepath" - - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/network" - "github.com/pkg/errors" -) - -const connectionsYaml = "connections.yaml" - -const connectionsTemplate = `--- -{{ with $w := . -}} -name: {{ .NetworkName }} -version: 1.0.0 -client: - organization: {{ .Name }} - connection: - timeout: - peer: - endorser: '300' - -organizations: - {{ .Name }}: - mspid: {{ .MSPID }} - peers: {{ range .PeersInOrg }} - - {{ . }} - {{- end }} - cryptoPath: {{ .MSPDir }} -{{- end }} - -peers:{{ range .Peers }} - {{- if .IsAnchor }} - {{ .Name }}: - url: grpcs://{{ .PeerAddr }} - tlsCACerts: - path: {{ .TLSDir }}/ca.crt - {{- end }} -{{- end }} -` - -type connections struct { - NetworkName string - Name string - MSPID string - PeersInOrg []string - MSPDir string - Peers []peer -} - -type peer struct { - Name string - IsAnchor bool - PeerAddr string - TLSDir string -} - -// generateConnections collects the network information to produce a connection.yaml for a given organization `myOrg`. -// Returns an error if generation has failed. The connection.yaml is stored in the artifact folder `crypto/peerOrganization/orgDomain`. -func (n *Extension) generateConnections(myOrg string) error { - logger.Infof("Generate connections for %s", myOrg) - - // get org - org := n.network.Organization(myOrg) - - co := connections{ - NetworkName: fmt.Sprintf("network-%s-%s", n.network.NetworkID, org.Name), - Name: org.Name, - MSPID: org.MSPID, - PeersInOrg: []string{}, - MSPDir: n.network.PeerOrgMSPDir(org), - Peers: []peer{}, - } - - // gather all peers of my org - for _, peer := range n.network.PeersInOrg(myOrg) { - co.PeersInOrg = append(co.PeersInOrg, fmt.Sprintf("%s.%s", peer.Name, org.Domain)) - } - - // gather anchor peers - for _, p := range n.network.Peers { - if !p.Anchor() { - // we only want anchor peers - continue - } - org := n.network.Organization(p.Organization) - co.Peers = append(co.Peers, peer{ - Name: fmt.Sprintf("%s.%s", p.Name, org.Domain), - IsAnchor: p.Anchor(), - PeerAddr: n.network.PeerAddress(p, network.ListenPort), - TLSDir: n.network.PeerLocalTLSDir(p), - }) - } - - // set path - p := filepath.Join( - n.network.Context.RootDir(), - n.network.Prefix, - "crypto", - "peerOrganizations", - org.Domain, - connectionsYaml, - ) - - if err := writeConnections(p, &co); err != nil { - return errors.Wrapf(err, "creating connections profile failed") - } - - return nil -} - -// writeConnections applies the connectionsTemplate to a connections data structure and writes the result at a given path. -// Returns an error if parsing the template failed or the resulting connections file cannot be written to path. -func writeConnections(path string, co *connections) error { - core, err := os.Create(path) - if err != nil { - return errors.Wrapf(err, "failed to create file (%s)", path) - } - defer core.Close() - - t, err := template.New(connectionsYaml).Parse(connectionsTemplate) - if err != nil { - return errors.Wrapf(err, "failed to parse connections template") - } - - err = t.Execute(io.Writer(core), co) - if err != nil { - return errors.Wrapf(err, "failed to apply data structure to template") - } - - return nil -} diff --git a/integration/nwo/fabric/fpc/externalbuilders/scripts.go b/integration/nwo/fabric/fpc/externalbuilders/scripts.go deleted file mode 100644 index 76056cc37..000000000 --- a/integration/nwo/fabric/fpc/externalbuilders/scripts.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package externalbuilders - -// This package provides the external builder scripts for FPC. -// The original scripts can be found at https://github.com/hyperledger/fabric-private-chaincode/tree/main/fabric/externalBuilder/chaincode_server/bin - -const ( - Build = `#!/bin/bash - -# Copyright 2020 Intel Corporation -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 - -set -euo pipefail - -SOURCE=$1 -OUTPUT=$3 - -#external chaincodes expect connection.json file in the chaincode package -if [ ! -f "$SOURCE/${CORE_PEER_ID}/connection.json" ]; then - >&2 echo "$SOURCE/connection.json not found" - exit 1 -fi - -#simply copy the endpoint information to specified output location -cp $SOURCE/${CORE_PEER_ID}/connection.json $OUTPUT/connection.json - -if [ -d "$SOURCE/metadata" ]; then - cp -a $SOURCE/metadata $OUTPUT/metadata -fi - -exit 0 -` - - Detect = `#!/bin/bash - -# Copyright 2020 Intel Corporation -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 - -set -euo pipefail - -METADIR=$2 -# check if the "type" field is set to "external" -# crude way without jq which is not in the default fabric peer image -TYPE=$(tr -d '\n' < "$METADIR/metadata.json" | awk -F':' '{ for (i = 1; i < NF; i++){ if ($i~/type/) { print $(i+1); break }}}'| cut -d\" -f2) - -if [ "$TYPE" = "external" ]; then - exit 0 -fi - -exit 1 -` - - Release = `#!/bin/bash - -# Copyright 2020 Intel Corporation -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 - -set -euo pipefail - -BLD="$1" -RELEASE="$2" - -if [ -d "$BLD/metadata" ]; then - cp -a "$BLD/metadata/"* "$RELEASE/" -fi - -#external chaincodes expect artifacts to be placed under "$RELEASE"/chaincode/server -if [ -f $BLD/connection.json ]; then - mkdir -p "$RELEASE"/chaincode/server - cp $BLD/connection.json "$RELEASE"/chaincode/server - - #if tls_required is true, copy TLS files (using above example, the fully qualified path for these fils would be "$RELEASE"/chaincode/server/tls) - - exit 0 -fi - -exit 1 -` -) diff --git a/integration/nwo/fabric/fpc/fpc.go b/integration/nwo/fabric/fpc/fpc.go deleted file mode 100644 index aab3b8617..000000000 --- a/integration/nwo/fabric/fpc/fpc.go +++ /dev/null @@ -1,442 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/client" - "github.com/docker/go-connections/nat" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/fabricconfig" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/fpc/externalbuilders" - nnetwork "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/network" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/packager" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/topology" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/flogging" - "github.com/hyperledger/fabric-private-chaincode/client_sdk/go/pkg/core/lifecycle" - . "github.com/onsi/gomega" - "github.com/pkg/errors" -) - -var logger = flogging.MustGetLogger("integration.nwo.fabric.fpc") - -type ChaincodeInput struct { - Args []string `json:"Args"` -} - -type Connection struct { - Address string `json:"address"` - DialTimeout string `json:"dial_timeout"` - TlsRequired bool `json:"tls_required"` -} - -type Extension struct { - network *nnetwork.Network - - ports map[string][]uint16 - FPCERCC *topology.ChannelChaincode -} - -func NewExtension(network *nnetwork.Network) *Extension { - return &Extension{ - network: network, - ports: map[string][]uint16{}, - } -} - -func (n *Extension) CheckTopology() { - if !n.network.Topology().FPC { - return - } - - path := n.prepareExternalBuilderScripts() - n.network.ExternalBuilders = append(n.network.ExternalBuilders, fabricconfig.ExternalBuilder{ - Path: path, - Name: "fpc-external-launcher", - PropagateEnvironment: []string{"CORE_PEER_ID", "FABRIC_LOGGING_SPEC"}, - }) - - // Reserve ports for each private chaincode - for _, chaincode := range n.network.Topology().Chaincodes { - if !chaincode.Private { - continue - } - - if chaincode.Chaincode.Name == "ercc" { - n.FPCERCC = chaincode - } - - var ports []uint16 - for range chaincode.Peers { - ports = append(ports, n.network.Context.ReservePort()) - } - - n.ports[chaincode.Chaincode.Name] = ports - } -} - -func (n *Extension) GenerateArtifacts() { - for _, chaincode := range n.network.Topology().Chaincodes { - if !chaincode.Private { - continue - } - n.preparePackage(chaincode) - } - - for _, org := range n.network.PeerOrgs() { - var p *topology.Peer - for _, peer := range n.network.Peers { - if peer.Organization == org.Name { - p = peer - break - } - } - Expect(p).NotTo(BeNil()) - - } -} - -func (n *Extension) PostRun(load bool) { - if !n.network.Topology().FPC { - return - } - - if load { - panic("Load is not supported. Restart from scratch.") - } - - // deploy and run containers - if len(n.network.Topology().Chaincodes) != 0 { - for _, chaincode := range n.network.Topology().Chaincodes { - if chaincode.Private { - n.reservePorts(chaincode) - n.preparePackage(chaincode) - n.deployChaincode(chaincode) - } - } - } - - // generate connection profiles - for _, org := range n.network.PeerOrgs() { - err := n.generateConnections(org.Name) - Expect(err).ToNot(HaveOccurred()) - } - - // Give some time to the enclave to get up and running... - time.Sleep(3 * time.Second) -} - -func (n *Extension) deployChaincode(chaincode *topology.ChannelChaincode) { - if !n.network.Topology().FPC { - return - } - - orderer := n.network.Orderer("orderer") - peers := n.network.PeersByName(chaincode.Peers) - // Install on each peer its own chaincode package - var packageIDs []string - for _, peer := range peers { - chaincode.Chaincode.PackageID = "" - org := n.network.Organization(peer.Organization) - chaincode.Chaincode.PackageFile = filepath.Join( - n.packagePath(chaincode.Chaincode.Name), - fmt.Sprintf("%s.%s.%s.tgz", chaincode.Chaincode.Name, peer.Name, org.Domain), - ) - nnetwork.InstallChaincode(n.network, &chaincode.Chaincode, peer) - nnetwork.ApproveChaincodeForMyOrg(n.network, chaincode.Channel, orderer, &chaincode.Chaincode, peer) - packageIDs = append(packageIDs, chaincode.Chaincode.PackageID) - } - - n.runDockerContainers(chaincode, packageIDs) - - nnetwork.CheckCommitReadinessUntilReady(n.network, chaincode.Channel, &chaincode.Chaincode, n.network.PeerOrgsByPeers(peers), peers...) - nnetwork.CommitChaincode(n.network, chaincode.Channel, orderer, &chaincode.Chaincode, peers[0], peers...) - time.Sleep(10 * time.Second) - for i, peer := range peers { - nnetwork.QueryInstalledReferences(n.network, - chaincode.Channel, chaincode.Chaincode.Label, packageIDs[i], - peer, - []string{chaincode.Chaincode.Name, chaincode.Chaincode.Version}, - ) - } - if chaincode.Chaincode.InitRequired { - nnetwork.InitChaincode(n.network, chaincode.Channel, orderer, &chaincode.Chaincode, peers...) - } - - // initEnclave if not an ERCC - if chaincode.Chaincode.Name != "ercc" { - n.initEnclave(chaincode) - } -} - -func (n *Extension) packagePath(suffix string) string { - return filepath.Join(n.network.Context.RootDir(), n.network.Prefix, "fpc", suffix) -} - -func (n *Extension) runDockerContainers(chaincode *topology.ChannelChaincode, packageIDs []string) { - ctx := context.Background() - cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) - Expect(err).ToNot(HaveOccurred()) - - var mounts []mount.Mount - var devices []container.DeviceMapping - - sgxMode := strings.ToUpper(chaincode.PrivateChaincode.SGXMode) - err = validateSGXMode(sgxMode) - Expect(err).ToNot(HaveOccurred()) - - if sgxMode == SGX_MODE_HW { - mounts = append(mounts, mount.Mount{ - Type: mount.TypeBind, - Source: "/var/run/aesmd", - Target: "/var/run/aesmd", - }) - - err := validateSGXDevicesPaths(chaincode.PrivateChaincode.SGXDevicesPaths) - Expect(err).ToNot(HaveOccurred()) - - // add sgx devices to the container depending on the driver installed on the platform - // we may attach /dev/isgx, or /dev/sgx/enclave and /dev/sgx/provision - for _, devicePath := range chaincode.PrivateChaincode.SGXDevicesPaths { - devices = append(devices, container.DeviceMapping{ - PathOnHost: devicePath, - PathInContainer: devicePath, - CgroupPermissions: "rwm", - }) - } - } - - // attach dcap qpl if exists - qcnlConfigPath := "/etc/sgx_default_qcnl.conf" - if exists, err := pathExists(qcnlConfigPath); exists && err == nil { - mounts = append(mounts, mount.Mount{ - Type: mount.TypeBind, - Source: qcnlConfigPath, - Target: qcnlConfigPath, - }) - } - - peers := n.network.PeersByName(chaincode.Peers) - for i, peer := range peers { - port := strconv.Itoa(int(n.ports[chaincode.Chaincode.Name][i])) - containerName := fmt.Sprintf("%s.%s.%s.%s", - n.network.NetworkID, - chaincode.Chaincode.Name, peer.Name, - n.network.Organization(peer.Organization).Domain) - - resp, err := cli.ContainerCreate(ctx, &container.Config{ - Image: chaincode.PrivateChaincode.Image, - Tty: false, - Env: []string{ - "CHAINCODE_SERVER_ADDRESS=0.0.0.0:" + port, - "CHAINCODE_PKG_ID=" + packageIDs[i], - "FABRIC_LOGGING_SPEC=debug", - fmt.Sprintf("SGX_MODE=%s", sgxMode), - }, - ExposedPorts: nat.PortSet{ - nat.Port(port + "/tcp"): struct{}{}, - }, - }, &container.HostConfig{ - Mounts: mounts, - Resources: container.Resources{ - Devices: devices, - }, - PortBindings: nat.PortMap{ - nat.Port(port + "/tcp"): []nat.PortBinding{ - { - HostIP: "127.0.0.1", - HostPort: port, - }, - }, - }, - }, - nil, nil, containerName, - ) - Expect(err).ToNot(HaveOccurred()) - Expect(cli.ContainerStart(ctx, resp.ID, container.StartOptions{})).ToNot(HaveOccurred()) - time.Sleep(3 * time.Second) - - dockerLogger := flogging.MustGetLogger("fpc.container." + containerName) - go func() { - reader, err := cli.ContainerLogs(context.Background(), resp.ID, container.LogsOptions{ - ShowStdout: true, - ShowStderr: true, - Follow: true, - Timestamps: false, - }) - Expect(err).ToNot(HaveOccurred()) - defer reader.Close() - - scanner := bufio.NewScanner(reader) - for scanner.Scan() { - dockerLogger.Debugf("%s", scanner.Text()) - } - }() - } -} - -const ( - SGX_MODE_HW = "HW" - SGX_MODE_SIM = "SIM" -) - -func validateSGXMode(mode string) error { - if strings.ToUpper(mode) == SGX_MODE_HW || strings.ToUpper(mode) == SGX_MODE_SIM { - return nil - } - return errors.Errorf("invalid SGX Mode = %s", mode) -} - -func validateSGXDevicesPaths(paths []string) error { - // remove duplicates - devicesPaths := make(map[string]bool, len(paths)) - for _, p := range paths { - devicesPaths[p] = true - } - - // check exists - for p := range devicesPaths { - if exists, err := pathExists(p); !exists || err != nil { - return errors.Wrapf(err, "invalid SGX device path = %s", p) - } - } - - // check some extra rules - allowedSettings := [][]string{ - {"/dev/sgx/isgx"}, - {"/dev/sgx/enclave"}, - {"/dev/sgx/enclave", "/dev/sgx/provision"}, - } - - for _, setting := range allowedSettings { - // TODO implement me - _ = setting - } - - return nil -} - -func pathExists(path string) (bool, error) { - if _, err := os.Stat(path); err == nil { - return true, nil - } else if errors.Is(err, os.ErrNotExist) { - return false, nil - } else { - return false, errors.Wrapf(err, "error checking path = %s", path) - } -} - -func (n *Extension) initEnclave(chaincode *topology.ChannelChaincode) { - initOrgs := map[string]bool{} - var erccPeerAddresses []string - peers := n.network.PeersByName(n.FPCERCC.Peers) - for _, p := range peers { - if exists := initOrgs[p.Organization]; !exists { - erccPeerAddresses = append(erccPeerAddresses, n.network.PeerAddress(p, nnetwork.ListenPort)) - initOrgs[p.Organization] = true - } - } - - orderer := n.network.Orderer("orderer") - peers = n.network.PeersByName(chaincode.Peers) - attestationParams := CreateSIMAttestationParams() - for _, peer := range peers { - lifecycleClient, err := lifecycle.New(func(channelID string) (lifecycle.ChannelClient, error) { - return &ChannelClient{ - n: n, - peer: peer, - orderer: orderer, - chaincode: chaincode, - }, nil - }) - Expect(err).ToNot(HaveOccurred()) - _, err = lifecycleClient.LifecycleInitEnclave(chaincode.Channel, lifecycle.LifecycleInitEnclaveRequest{ - ChaincodeID: chaincode.Chaincode.Name, - EnclavePeerEndpoint: erccPeerAddresses[0], - AttestationParams: attestationParams, - }) - Expect(err).ToNot(HaveOccurred()) - - // Enclave Init should happen once only - return - } -} - -func (n *Extension) preparePackage(chaincode *topology.ChannelChaincode) { - // Generate Enclave Registry CC package for each peer that will conn - Expect(os.MkdirAll(n.packagePath(chaincode.Chaincode.Name), 0770)).NotTo(HaveOccurred()) - - peers := n.network.PeersByName(chaincode.Peers) - for i, peer := range peers { - org := n.network.Organization(peer.Organization) - - packageFilePath := filepath.Join(n.packagePath(chaincode.Chaincode.Name), fmt.Sprintf("%s.%s.%s.tgz", chaincode.Chaincode.Name, peer.Name, org.Domain)) - if _, err := os.Stat(packageFilePath); os.IsNotExist(err) { - Expect(packager.New().PackageChaincode( - chaincode.Chaincode.Name, - chaincode.Chaincode.Lang, - chaincode.Chaincode.Label, - packageFilePath, - func(s string, s2 string) (string, []byte) { - if strings.HasSuffix(s, "connection.json") { - raw, err := json.MarshalIndent(&Connection{ - Address: "127.0.0.1:" + strconv.Itoa(int(n.ports[chaincode.Chaincode.Name][i])), - DialTimeout: "10s", - TlsRequired: false, - }, "", " ") - Expect(err).NotTo(HaveOccurred()) - return filepath.Join(fmt.Sprintf("%s.%s", peer.Name, org.Domain), "connection.json"), raw - } - return "", nil - }, - )).ToNot(HaveOccurred()) - } - } -} - -func (n *Extension) reservePorts(chaincode *topology.ChannelChaincode) { - if ports, ok := n.ports[chaincode.Chaincode.Name]; ok && len(ports) != 0 { - return - } - - var ports []uint16 - for range chaincode.Peers { - ports = append(ports, n.network.Context.ReservePort()) - } - n.ports[chaincode.Chaincode.Name] = ports -} - -func (n *Extension) externalBuilderPath() string { - return filepath.Join(n.network.Context.RootDir(), n.network.Prefix, "fpc", "externalbuilders", "chaincode_server") -} - -func (n *Extension) prepareExternalBuilderScripts() string { - path := n.externalBuilderPath() - Expect(os.MkdirAll(filepath.Join(path, "bin"), 0777)).NotTo(HaveOccurred()) - - // Store External Builder scripts to file - for _, script := range []struct{ name, content string }{ - {"build", externalbuilders.Build}, - {"detect", externalbuilders.Detect}, - {"release", externalbuilders.Release}, - } { - scriptPath := filepath.Join(path, "bin", script.name) - Expect(os.WriteFile(scriptPath, []byte(script.content), 0777)).NotTo(HaveOccurred()) - } - - return path -} diff --git a/integration/nwo/fabric/platform.go b/integration/nwo/fabric/platform.go index 366185ba6..06fa6b79b 100644 --- a/integration/nwo/fabric/platform.go +++ b/integration/nwo/fabric/platform.go @@ -18,12 +18,10 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/api" "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/common" "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/commands" - "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/fpc" "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/network" "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/topology" "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/topology/fabric" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/flogging" - "github.com/hyperledger/fabric-private-chaincode/client_sdk/go/pkg/core/contract" . "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" @@ -120,8 +118,6 @@ func NewPlatform(context api.Context, t api.Topology, components BuilderClient) Docker: &Docker{NetworkID: networkID, RequiredImages: []string{CCEnvDefaultImage}}, } - n.AddExtension(fpc.NewExtension(n)) - return p } @@ -397,16 +393,6 @@ func (p *Platform) Channels() []*fabric.Channel { } func (p *Platform) InvokeChaincode(cc *topology.ChannelChaincode, method string, args ...[]byte) []byte { - if cc.Private { - c := contract.GetContract( - &fpc.ChannelProvider{Network: p.Network, CC: cc}, - cc.Chaincode.Name, - ) - output, err := c.SubmitTransaction(method, fpc.ArgsToStrings(args)...) - Expect(err).NotTo(HaveOccurred()) - return output - } - orderer := p.Network.Orderer("orderer") org := p.PeerOrgs()[0] peer := p.Network.Peer(org.Name, p.PeersByOrg("", org.Name, false)[0].Name) diff --git a/integration/nwo/fabric/topology/fpc.go b/integration/nwo/fabric/topology/fpc.go deleted file mode 100644 index 86652cbf0..000000000 --- a/integration/nwo/fabric/topology/fpc.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package topology - -import ( - "fmt" - "strconv" -) - -// EnableFPC enables FPC by adding the Enclave Registry Chaincode definition. -// The ERCC is installed on all organizations and the endorsement policy is -// set to the majority of the organization on which the chaincode -// has been installed. -func (t *Topology) EnableFPC() { - if t.FPC { - return - } - t.FPC = true - t.AddFPC("ercc", "fpc/ercc") -} - -// AddFPCAtOrgs adds the Fabric Private Chaincode with the passed name, image, and organizations -// If no orgs are specified, then the Fabric Private Chaincode is installed on all organizations -// registered so far. -// The endorsement policy is set to the majority of the organization on which the chaincode -// has been installed. -func (t *Topology) AddFPCAtOrgs(name, image string, orgs []string, options ...func(*ChannelChaincode)) *ChannelChaincode { - t.EnableFPC() - - if len(orgs) == 0 { - orgs = t.Consortiums[0].Organizations - } - majority := len(orgs)/2 + 1 - policy := "OutOf(" + strconv.Itoa(majority) + "," - for i, org := range orgs { - if i > 0 { - policy += "," - } - policy += "'" + org + "MSP.member'" - } - policy += ")" - - var peers []string - for _, org := range orgs { - for _, peer := range t.Peers { - if peer.Organization == org { - peers = append(peers, peer.Name) - break - } - } - } - - cc := &ChannelChaincode{ - Chaincode: Chaincode{ - Name: name, - Version: "Version-1.0", - Sequence: "1", - InitRequired: false, - Path: name, - Lang: "external", - Label: fmt.Sprintf("%s_1.0", name), - Ctor: `{"Args":["init"]}`, - Policy: policy, - SignaturePolicy: policy, - }, - PrivateChaincode: PrivateChaincode{ - Image: image, - SGXMode: "sim", - }, - Channel: t.Channels[0].Name, - Private: true, - Peers: peers, - } - - // apply options - for _, o := range options { - o(cc) - } - - t.AddChaincode(cc) - - return cc -} - -// AddFPC adds the Fabric Private Chaincode with the passed name and image. -// The Fabric Private Chaincode is installed on all organizations registered so far. -// The endorsement policy is set to the majority of the organization on which the chaincode -// has been installed. -func (t *Topology) AddFPC(name, image string, options ...func(*ChannelChaincode)) *ChannelChaincode { - return t.AddFPCAtOrgs(name, image, nil, options...) -} - -func WithSGXMode(mode string) func(*ChannelChaincode) { - return func(cc *ChannelChaincode) { - cc.PrivateChaincode.SGXMode = mode - } -} - -func WithSGXDevicesPaths(paths []string) func(*ChannelChaincode) { - return func(cc *ChannelChaincode) { - cc.PrivateChaincode.SGXDevicesPaths = paths - } -} - -func WithMREnclave(mrenclave string) func(*ChannelChaincode) { - return func(cc *ChannelChaincode) { - cc.Chaincode.Version = mrenclave - } -} diff --git a/integration/nwo/fabric/topology/topology.go b/integration/nwo/fabric/topology/topology.go index 730c85df3..2fdc941aa 100755 --- a/integration/nwo/fabric/topology/topology.go +++ b/integration/nwo/fabric/topology/topology.go @@ -38,7 +38,6 @@ type Topology struct { FabTokenCCSupport bool `yaml:"fabtokenccsupport,omitempty"` GRPCLogging bool `yaml:"grpcLogging,omitempty"` NodeOUs bool `yaml:"nodeous,omitempty"` - FPC bool `yaml:"fpc,omitempty"` Weaver bool `yaml:"weaver,omitempty"` LogPeersToFile bool `yaml:"logPeersToFile,omitempty"` LogOrderersToFile bool `yaml:"logOrderersToFile,omitempty"` diff --git a/integration/ports.go b/integration/ports.go index 28a479fed..1bac30b96 100755 --- a/integration/ports.go +++ b/integration/ports.go @@ -34,7 +34,6 @@ const ( AssetTransferSecuredAgreementWithApprovers AssetTransferEventsAgreementWithChaincode TwoFabricNetworksPort - FPCEchoPort TwoFabricNetworksWithWeaverRelayPort FabricStopRestart PingPongOrion diff --git a/platform/fabric/services/chaincode/chaincode.go b/platform/fabric/services/chaincode/chaincode.go index 28f4e407d..9a6ffda01 100644 --- a/platform/fabric/services/chaincode/chaincode.go +++ b/platform/fabric/services/chaincode/chaincode.go @@ -10,7 +10,6 @@ import ( "time" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/fpc" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" ) @@ -132,90 +131,3 @@ func (s *stdChaincode) Endorse(function string, args ...interface{}) Endorse { func (s *stdChaincode) Query(function string, args ...interface{}) Query { return &stdQuery{chq: s.ch.Query(function, args...)} } - -type fpcEndorse struct { - che *fpc.ChaincodeEndorse -} - -func (s *fpcEndorse) Call() (*fabric.Envelope, error) { - return s.che.Call() -} - -func (s *fpcEndorse) WithTxID(txID fabric.TxID) Endorse { - s.che.WithTxID(txID) - return s -} - -func (s *fpcEndorse) WithInvokerIdentity(identity view.Identity) Endorse { - s.che.WithSignerIdentity(identity) - return s -} - -func (s *fpcEndorse) WithTransientEntry(k string, v interface{}) { - s.che.WithTransientEntry(k, v) -} - -func (s *fpcEndorse) WithEndorsersByMSPIDs(ds ...string) { - s.che.WithEndorsersByMSPIDs(ds...) -} - -func (s *fpcEndorse) WithEndorsersFromMyOrg() { - s.che.WithEndorsersFromMyOrg() -} - -func (s *fpcEndorse) WithNumRetries(numRetries uint) { -} - -func (s *fpcEndorse) WithRetrySleep(duration time.Duration) { -} - -type fpcQuery struct { - chq *fpc.ChaincodeQuery -} - -func (s *fpcQuery) Call() ([]byte, error) { - return s.chq.Call() -} - -func (s *fpcQuery) WithInvokerIdentity(identity view.Identity) Query { - s.chq.WithSignerIdentity(identity) - return s -} - -func (s *fpcQuery) WithTransientEntry(k string, v interface{}) { - s.chq.WithTransientEntry(k, v) -} - -func (s *fpcQuery) WithEndorsersByMSPIDs(ds ...string) { - s.chq.WithEndorsersByMSPIDs(ds...) -} - -func (s *fpcQuery) WithEndorsersFromMyOrg() { - s.chq.WithEndorsersFromMyOrg() -} - -func (s *fpcQuery) WithMatchEndorsementPolicy() { - s.chq.WithMatchEndorsementPolicy() -} - -func (s *fpcQuery) WithNumRetries(numRetries uint) { -} - -func (s *fpcQuery) WithRetrySleep(duration time.Duration) { -} - -type fpcChaincode struct { - ch *fpc.Chaincode -} - -func (s *fpcChaincode) IsPrivate() bool { - return s.ch.IsPrivate() -} - -func (s *fpcChaincode) Endorse(function string, args ...interface{}) Endorse { - return &fpcEndorse{che: s.ch.Endorse(function, args...)} -} - -func (s *fpcChaincode) Query(function string, args ...interface{}) Query { - return &fpcQuery{chq: s.ch.Query(function, args...)} -} diff --git a/platform/fabric/services/chaincode/endorse.go b/platform/fabric/services/chaincode/endorse.go index f1f44ce53..e246d9d60 100644 --- a/platform/fabric/services/chaincode/endorse.go +++ b/platform/fabric/services/chaincode/endorse.go @@ -10,7 +10,6 @@ import ( "time" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/fpc" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" "github.com/pkg/errors" ) @@ -52,18 +51,8 @@ func (i *endorseChaincodeView) Endorse(context view.Context) (*fabric.Envelope, var chaincode Chaincode stdChannelChaincode := channel.Chaincode(i.ChaincodeName) - if stdChannelChaincode.IsPrivate() { - // This is a Fabric Private Chaincode, use the corresponding service - fpcChannel, err := fpc.GetChannel(context, i.Network, i.Channel) - if err != nil { - return nil, err - } - chaincode = &fpcChaincode{fpcChannel.Chaincode(i.ChaincodeName)} - logger.Debugf("chaincode [%s:%s:%s] is a FPC", i.Network, i.Channel, i.ChaincodeName) - } else { - chaincode = &stdChaincode{ch: stdChannelChaincode} - logger.Debugf("chaincode [%s:%s:%s] is a standard chaincode", i.Network, i.Channel, i.ChaincodeName) - } + chaincode = &stdChaincode{ch: stdChannelChaincode} + logger.Debugf("chaincode [%s:%s:%s] is a standard chaincode", i.Network, i.Channel, i.ChaincodeName) invocation := chaincode.Endorse( i.Function, diff --git a/platform/fabric/services/chaincode/invoke.go b/platform/fabric/services/chaincode/invoke.go index 831f979a7..c98c9f10f 100644 --- a/platform/fabric/services/chaincode/invoke.go +++ b/platform/fabric/services/chaincode/invoke.go @@ -10,7 +10,6 @@ import ( "time" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/fpc" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" ) @@ -71,19 +70,7 @@ func (i *invokeChaincodeView) Invoke(context view.Context) (string, []byte, erro } i.InvokerIdentity = info.identitiy - if chaincode.IsPrivate() { - logger.Debugf("chaincode [%s:%s:%s] is a FPC", i.Network, i.Channel, i.ChaincodeName) - // This is a Fabric Private Chaincode, use the corresponding service - fpcChannel, err := fpc.GetChannel(context, i.Network, i.Channel) - if err != nil { - return "", nil, err - } - res, err := fpcChannel.Chaincode(i.ChaincodeName).Invoke(i.Function, i.Args...).Call() - return "", res, err - } else { - logger.Debugf("chaincode [%s:%s:%s] is a standard chaincode", i.Network, i.Channel, i.ChaincodeName) - } - + logger.Debugf("chaincode [%s:%s:%s] is a standard chaincode", i.Network, i.Channel, i.ChaincodeName) invocation := chaincode.Invoke(i.Function, i.Args...).WithInvokerIdentity(i.InvokerIdentity) for k, v := range i.TransientMap { invocation.WithTransientEntry(k, v) diff --git a/platform/fabric/services/chaincode/query.go b/platform/fabric/services/chaincode/query.go index cba4f88c6..33f55e420 100644 --- a/platform/fabric/services/chaincode/query.go +++ b/platform/fabric/services/chaincode/query.go @@ -10,7 +10,6 @@ import ( "time" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/fpc" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" "github.com/pkg/errors" ) @@ -52,18 +51,8 @@ func (i *queryChaincodeView) Query(context view.Context) ([]byte, error) { var chaincode Chaincode stdChannelChaincode := channel.Chaincode(i.ChaincodeName) - if stdChannelChaincode.IsPrivate() { - // This is a Fabric Private Chaincode, use the corresponding service - fpcChannel, err := fpc.GetChannel(context, i.Network, i.Channel) - if err != nil { - return nil, err - } - chaincode = &fpcChaincode{ch: fpcChannel.Chaincode(i.ChaincodeName)} - logger.Debugf("chaincode [%s:%s:%s] is a FPC", i.Network, i.Channel, i.ChaincodeName) - } else { - chaincode = &stdChaincode{ch: stdChannelChaincode} - logger.Debugf("chaincode [%s:%s:%s] is a standard chaincode", i.Network, i.Channel, i.ChaincodeName) - } + chaincode = &stdChaincode{ch: stdChannelChaincode} + logger.Debugf("chaincode [%s:%s:%s] is a standard chaincode", i.Network, i.Channel, i.ChaincodeName) invocation := chaincode.Query(i.Function, i.Args...).WithInvokerIdentity(i.InvokerIdentity) for k, v := range i.TransientMap { diff --git a/platform/fabric/services/fpc/chaincode.go b/platform/fabric/services/fpc/chaincode.go deleted file mode 100644 index bc0d79951..000000000 --- a/platform/fabric/services/fpc/chaincode.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" -) - -type invokerContract interface { - Name() string - EvaluateTransaction(name string, args ...string) ([]byte, error) - SubmitTransaction(name string, args ...string) ([]byte, error) -} - -type endorserContract interface { - EndorseTransaction(name string, args ...string) (*fabric.Envelope, error) - WithInvokerIdentity(identity view.Identity) - WithTxID(id fabric.TxID) -} - -type identityProvider interface { - Identity(label string) view.Identity -} - -// Chaincode models a Fabric Private Chaincode -type Chaincode struct { - Channel *fabric.Channel - EnclaveRegistry *EnclaveRegistry - InvokerContract invokerContract - EndorserContract endorserContract - Signer view.Identity - IdentityProvider identityProvider - - ID string -} - -// NewChaincode returns a new chaincode instance -func NewChaincode( - ch *fabric.Channel, - er *EnclaveRegistry, - invoker invokerContract, - endorser endorserContract, - id view.Identity, - ip identityProvider, - cid string, -) *Chaincode { - return &Chaincode{ - Channel: ch, - EnclaveRegistry: er, - InvokerContract: invoker, - EndorserContract: endorser, - Signer: id, - IdentityProvider: ip, - ID: cid, - } -} - -func (c *Chaincode) IsPrivate() bool { - return true -} - -// Invoke returns an object that models an FPC invocation for the passed function and arguments -func (c *Chaincode) Invoke(function string, args ...interface{}) *ChaincodeInvocation { - return &ChaincodeInvocation{ - Chaincode: c, - function: function, - args: args, - } -} - -func (c *Chaincode) Endorse(function string, args ...interface{}) *ChaincodeEndorse { - return &ChaincodeEndorse{ - Chaincode: c, - function: function, - args: args, - } -} - -func (c *Chaincode) Query(function string, args ...interface{}) *ChaincodeQuery { - return &ChaincodeQuery{ - Chaincode: c, - function: function, - args: args, - } -} - -// StringsToArgs converts a slice of strings into a slace of interface{} -func StringsToArgs(args []string) []interface{} { - var res []interface{} - for _, arg := range args { - res = append(res, arg) - } - return res -} diff --git a/platform/fabric/services/fpc/channel.go b/platform/fabric/services/fpc/channel.go deleted file mode 100644 index af51c6aab..000000000 --- a/platform/fabric/services/fpc/channel.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - fpc "github.com/hyperledger/fabric-private-chaincode/client_sdk/go/pkg/core/contract" - - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/view" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/flogging" -) - -var logger = flogging.MustGetLogger("fabric-sdk.fpc") - -// Channel models a Fabric channel that supports invocation of a Fabric Private Chaincode -type Channel struct { - FabricNetworkService *fabric.NetworkService - Channel *fabric.Channel - - ER *EnclaveRegistry -} - -func newChannel(fns *fabric.NetworkService, ch *fabric.Channel, er *EnclaveRegistry) *Channel { - return &Channel{FabricNetworkService: fns, Channel: ch, ER: er} -} - -// EnclaveRegistry returns the enclave registry for this channel -func (p *Channel) EnclaveRegistry() *EnclaveRegistry { - return p.ER -} - -// Chaincode returns a wrapper around the Fabric Private Chaincode whose name is cid -func (p *Channel) Chaincode(cid string) *Chaincode { - icp := &contractProvider{ - fns: p.FabricNetworkService, - ch: p.Channel, - } - - return NewChaincode( - p.Channel, - p.ER, - fpc.GetContract(icp, cid), - &endorserContractImpl{fns: p.FabricNetworkService, ch: p.Channel, cid: cid}, - p.FabricNetworkService.IdentityProvider().DefaultIdentity(), - p.FabricNetworkService.IdentityProvider(), - cid, - ) -} - -// GetDefaultChannel returns the default channel on which to invoke an FPC -func GetDefaultChannel(sp view.ServiceProvider) (*Channel, error) { - fns, err := fabric.GetDefaultFNS(sp) - if err != nil { - return nil, err - } - ch, err := fns.Channel("") - if err != nil { - return nil, err - } - return newChannel(fns, ch, NewEnclaveRegistry(fns, ch)), nil -} - -// GetChannel returns the channel for the passed network and channel name on which to invoke an FPC -func GetChannel(sp view.ServiceProvider, network, channelName string) (*Channel, error) { - fns, err := fabric.GetFabricNetworkService(sp, network) - if err != nil { - return nil, err - } - ch, err := fns.Channel(channelName) - if err != nil { - return nil, err - } - return newChannel(fns, ch, NewEnclaveRegistry(fns, ch)), nil -} diff --git a/platform/fabric/services/fpc/contract.go b/platform/fabric/services/fpc/contract.go deleted file mode 100644 index d4838c0f2..000000000 --- a/platform/fabric/services/fpc/contract.go +++ /dev/null @@ -1,217 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" - fpc "github.com/hyperledger/fabric-private-chaincode/client_sdk/go/pkg/core/contract" - "github.com/pkg/errors" -) - -type transaction struct { - fns *fabric.NetworkService - ch *fabric.Channel - id string - function string - endorserEndpoints []string - invoker view.Identity - txID fabric.TxID -} - -func (t *transaction) Evaluate(args ...string) ([]byte, error) { - var passedArgs []interface{} - for _, arg := range args { - passedArgs = append(passedArgs, arg) - } - raw, err := t.ch.Chaincode(t.id).Query( - t.function, passedArgs..., - ).WithInvokerIdentity( - t.invoker, - ).WithDiscoveredEndorsersByEndpoints( - t.endorserEndpoints..., - ).WithTxID( - t.txID, - ).Call() - if err != nil { - return nil, err - } - return raw, nil -} - -type contract struct { - fns *fabric.NetworkService - ch *fabric.Channel - id string -} - -func (c *contract) Name() string { - return c.id -} - -func (c *contract) EvaluateTransaction(name string, args ...string) ([]byte, error) { - var passedArgs []interface{} - for _, arg := range args { - passedArgs = append(passedArgs, arg) - } - raw, err := c.ch.Chaincode(c.id).Query( - name, passedArgs..., - ).WithInvokerIdentity( - c.fns.IdentityProvider().DefaultIdentity(), - ).Call() - if err != nil { - return nil, errors.Wrapf(err, "failed querying chaincode [%s:%s]", c.id, name) - } - return raw, err -} - -func (c *contract) SubmitTransaction(name string, args ...string) ([]byte, error) { - var passedArgs []interface{} - for _, arg := range args { - passedArgs = append(passedArgs, arg) - } - _, raw, err := c.ch.Chaincode(c.id).Invoke( - name, passedArgs..., - ).WithInvokerIdentity( - c.fns.IdentityProvider().DefaultIdentity(), - ).Call() - if err != nil { - return nil, errors.Wrapf(err, "failed invoking chaincode [%s:%s]", c.id, name) - } - return raw, err -} - -func (c *contract) CreateTransaction(name string, endorsersEndpoints ...string) (fpc.Transaction, error) { - return &transaction{ - fns: c.fns, - ch: c.ch, - id: c.id, - function: name, - endorserEndpoints: endorsersEndpoints, - invoker: c.fns.IdentityProvider().DefaultIdentity(), - }, nil -} - -type contractProvider struct { - fns *fabric.NetworkService - ch *fabric.Channel -} - -func (c *contractProvider) GetContract(id string) fpc.Contract { - return &contract{ - fns: c.fns, - ch: c.ch, - id: id, - } -} - -type contractProviderForEndorsement struct { - fns *fabric.NetworkService - ch *fabric.Channel - cid string - env *fabric.Envelope - invoker view.Identity - txID fabric.TxID -} - -func (c *contractProviderForEndorsement) GetContract(id string) fpc.Contract { - if id == "ercc" { - return &contract{ - fns: c.fns, - ch: c.ch, - id: id, - } - } - c.cid = id - return c -} - -func (c *contractProviderForEndorsement) Name() string { - return c.cid -} - -func (c *contractProviderForEndorsement) EvaluateTransaction(name string, args ...string) ([]byte, error) { - var passedArgs []interface{} - for _, arg := range args { - passedArgs = append(passedArgs, arg) - } - raw, err := c.ch.Chaincode(c.cid).Query( - name, passedArgs..., - ).WithInvokerIdentity( - c.invoker, - ).WithTxID( - c.txID, - ).Call() - if err != nil { - return nil, errors.Wrapf(err, "failed querying chaincode [%s:%s]", c.cid, name) - } - return raw, nil -} - -func (c *contractProviderForEndorsement) SubmitTransaction(name string, args ...string) ([]byte, error) { - var passedArgs []interface{} - for _, arg := range args { - passedArgs = append(passedArgs, arg) - } - var err error - c.env, err = c.ch.Chaincode(c.cid).Endorse( - name, passedArgs..., - ).WithInvokerIdentity( - c.invoker, - ).WithTxID( - c.txID, - ).Call() - - if err != nil { - return nil, errors.Wrapf(err, "failed invoking chaincode [%s:%s]", c.cid, name) - } - return nil, nil -} - -func (c *contractProviderForEndorsement) CreateTransaction(name string, endorserEndpoints ...string) (fpc.Transaction, error) { - return &transaction{ - fns: c.fns, - ch: c.ch, - id: c.cid, - txID: c.txID, - function: name, - endorserEndpoints: endorserEndpoints, - invoker: c.invoker, - }, nil -} - -type endorserContractImpl struct { - fns *fabric.NetworkService - ch *fabric.Channel - cid string - invoker view.Identity - txID fabric.TxID -} - -func (e *endorserContractImpl) WithInvokerIdentity(identity view.Identity) { - e.invoker = identity -} - -func (e *endorserContractImpl) WithTxID(id fabric.TxID) { - e.txID = id -} - -func (e *endorserContractImpl) EndorseTransaction(name string, args ...string) (*fabric.Envelope, error) { - p := &contractProviderForEndorsement{ - fns: e.fns, - ch: e.ch, - cid: e.cid, - invoker: e.invoker, - txID: e.txID, - } - c := fpc.GetContract(p, e.cid) - _, err := c.SubmitTransaction(name, args...) - if err != nil { - return nil, errors.Wrapf(err, "failed endorse transaction for [%s:%s]", e.cid, name) - } - return p.env, nil -} diff --git a/platform/fabric/services/fpc/enclaveregistry.go b/platform/fabric/services/fpc/enclaveregistry.go deleted file mode 100644 index e35dcec4c..000000000 --- a/platform/fabric/services/fpc/enclaveregistry.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "encoding/json" - "strings" - - "github.com/pkg/errors" - - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" -) - -// EnclaveRegistry models the enclave registry -type EnclaveRegistry struct { - FabricNetworkService *fabric.NetworkService - Channel *fabric.Channel -} - -// NewEnclaveRegistry returns a new instance of the enclave registry -func NewEnclaveRegistry(fns *fabric.NetworkService, ch *fabric.Channel) *EnclaveRegistry { - return &EnclaveRegistry{FabricNetworkService: fns, Channel: ch} -} - -func (e *EnclaveRegistry) IsAvailable() (bool, error) { - return e.Channel.Chaincode("ercc").IsAvailable() -} - -func (e *EnclaveRegistry) IsPrivate(cid string) (bool, error) { - _, err := e.ChaincodeEncryptionKey(cid) - if err != nil && strings.Contains(err.Error(), "no such key") { - return false, nil - } - return err == nil, err -} - -// ListProvisionedEnclaves returns the list of provisioned enclaves for the passed chaincode id -func (e *EnclaveRegistry) ListProvisionedEnclaves(cid string) ([]string, error) { - raw, err := e.Channel.Chaincode("ercc").Query( - "QueryListProvisionedEnclaves", cid, - ).WithInvokerIdentity( - e.FabricNetworkService.IdentityProvider().DefaultIdentity(), - ).Call() - if err != nil { - return nil, err - } - - if len(raw) == 0 { - return nil, nil - } - - var res []string - if err := json.Unmarshal(raw, &res); err != nil { - return nil, errors.Wrapf(err, "failed unmarshalling [%s:%v]", string(raw), raw) - } - - return res, nil -} - -// ChaincodeEncryptionKey returns the encryption key to be used for the passed chaincode id -func (e *EnclaveRegistry) ChaincodeEncryptionKey(cid string) ([]byte, error) { - raw, err := e.Channel.Chaincode("ercc").Query( - "QueryChaincodeEncryptionKey", cid, - ).WithInvokerIdentity( - e.FabricNetworkService.IdentityProvider().DefaultIdentity(), - ).Call() - if err != nil { - return nil, err - } - - return raw, nil -} - -// PeerEndpoints returns the peer endpoints to use when invoking chaincode cid -func (e *EnclaveRegistry) PeerEndpoints(cid string) ([]string, error) { - raw, err := e.Channel.Chaincode("ercc").Query( - "QueryChaincodeEndPoints", cid, - ).WithInvokerIdentity( - e.FabricNetworkService.IdentityProvider().DefaultIdentity(), - ).Call() - if err != nil { - return nil, err - } - - return strings.Split(string(raw), ","), nil -} diff --git a/platform/fabric/services/fpc/endorse.go b/platform/fabric/services/fpc/endorse.go deleted file mode 100644 index 9a442a348..000000000 --- a/platform/fabric/services/fpc/endorse.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "strconv" - - "github.com/pkg/errors" - - "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" -) - -// ChaincodeEndorse models the endorsement of an FPC -type ChaincodeEndorse struct { - *Chaincode - - function string - args []interface{} -} - -func (i *ChaincodeEndorse) WithTxID(txID fabric.TxID) *ChaincodeEndorse { - i.EndorserContract.WithTxID(txID) - return i -} - -func (i *ChaincodeEndorse) WithSignerIdentity(identity view.Identity) *ChaincodeEndorse { - i.EndorserContract.WithInvokerIdentity(identity) - return i -} - -func (i *ChaincodeEndorse) WithTransientEntry(k string, v interface{}) { - panic("implement me") -} - -func (i *ChaincodeEndorse) WithEndorsers(endorsers ...view.Identity) { - panic("implement me") -} - -func (i *ChaincodeEndorse) WithEndorsersByMSPIDs(ds ...string) { - panic("implement me") -} - -func (i *ChaincodeEndorse) WithEndorsersFromMyOrg() { - panic("implement me") -} - -// Call invokes the chaincode and returns a Fabric envelope -func (i *ChaincodeEndorse) Call() (*fabric.Envelope, error) { - args, err := i.prepareArgs() - if err != nil { - return nil, errors.WithMessagef(err, "failed preparing arguments") - } - return i.EndorserContract.EndorseTransaction(i.function, args...) -} - -func (i *ChaincodeEndorse) prepareArgs() ([]string, error) { - var args []string - for _, arg := range i.args { - b, err := i.toString(arg) - if err != nil { - return nil, err - } - args = append(args, b) - } - return args, nil -} - -func (i *ChaincodeEndorse) toString(arg interface{}) (string, error) { - switch v := arg.(type) { - case []byte: - return string(v), nil - case string: - return v, nil - case int: - return strconv.Itoa(v), nil - case int64: - return strconv.FormatInt(v, 10), nil - case uint64: - return strconv.FormatUint(v, 10), nil - default: - return "", errors.Errorf("arg type [%T] not recognized.", v) - } -} diff --git a/platform/fabric/services/fpc/invoke.go b/platform/fabric/services/fpc/invoke.go deleted file mode 100644 index 06b2fd30a..000000000 --- a/platform/fabric/services/fpc/invoke.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "strconv" - - "github.com/pkg/errors" -) - -// ChaincodeInvocation models the invocation of an FPC -type ChaincodeInvocation struct { - *Chaincode - - function string - args []interface{} -} - -// Call invokes the chaincode and returns the result -func (i *ChaincodeInvocation) Call() ([]byte, error) { - args, err := i.prepareArgs() - if err != nil { - return nil, errors.WithMessagef(err, "failed preparing arguments") - } - return i.InvokerContract.SubmitTransaction(i.function, args...) -} - -func (i *ChaincodeInvocation) prepareArgs() ([]string, error) { - var args []string - for _, arg := range i.args { - b, err := i.toString(arg) - if err != nil { - return nil, err - } - args = append(args, b) - } - return args, nil -} - -func (i *ChaincodeInvocation) toString(arg interface{}) (string, error) { - switch v := arg.(type) { - case []byte: - return string(v), nil - case string: - return v, nil - case int: - return strconv.Itoa(v), nil - case int64: - return strconv.FormatInt(v, 10), nil - case uint64: - return strconv.FormatUint(v, 10), nil - default: - return "", errors.Errorf("arg type [%T] not recognized.", v) - } -} diff --git a/platform/fabric/services/fpc/query.go b/platform/fabric/services/fpc/query.go deleted file mode 100644 index 68af38d31..000000000 --- a/platform/fabric/services/fpc/query.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package fpc - -import ( - "strconv" - - "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" - "github.com/pkg/errors" -) - -// ChaincodeQuery models the query of an FPC -type ChaincodeQuery struct { - *Chaincode - - function string - args []interface{} -} - -func (i *ChaincodeQuery) WithSignerIdentity(identity view.Identity) *ChaincodeQuery { - return i -} - -func (i *ChaincodeQuery) WithTransientEntry(k string, v interface{}) { - panic("implement me") -} - -func (i *ChaincodeQuery) WithEndorsers(endorsers ...view.Identity) { - panic("implement me") -} - -func (i *ChaincodeQuery) WithEndorsersByMSPIDs(ds ...string) { - panic("implement me") -} - -func (i *ChaincodeQuery) WithEndorsersFromMyOrg() { - panic("implement me") -} - -// Call invokes the chaincode and returns the result -func (i *ChaincodeQuery) Call() ([]byte, error) { - logger.Debugf("query FPC [%s:%s:%s]", i.Channel, i.ID, i.function) - args, err := i.prepareArgs() - if err != nil { - return nil, errors.WithMessagef(err, "failed preparing arguments") - } - return i.InvokerContract.EvaluateTransaction(i.function, args...) -} - -func (i *ChaincodeQuery) prepareArgs() ([]string, error) { - var args []string - for _, arg := range i.args { - b, err := i.toString(arg) - if err != nil { - return nil, err - } - args = append(args, b) - } - return args, nil -} - -func (i *ChaincodeQuery) toString(arg interface{}) (string, error) { - switch v := arg.(type) { - case []byte: - return string(v), nil - case string: - return v, nil - case int: - return strconv.Itoa(v), nil - case int64: - return strconv.FormatInt(v, 10), nil - case uint64: - return strconv.FormatUint(v, 10), nil - default: - return "", errors.Errorf("arg type [%T] not recognized.", v) - } -} - -func (i *ChaincodeQuery) WithMatchEndorsementPolicy() { -} diff --git a/samples/README.md b/samples/README.md index 55c27c1f6..d49f31376 100644 --- a/samples/README.md +++ b/samples/README.md @@ -39,8 +39,6 @@ Here is a list of available integration tests: chaincodes-based solutions. Already a huge improvement for the developers. - Second, to highlights the limitations of the current sample and show how these limitations can be overcome using the `Fabric Smart Client`'s advanced capabilities. -- [`Fabric Private Chaincode: Echo`](../integration/fabric/fpc/echo/README.md): In this example, we show how to invoke a Fabric - Private Chaincode called [`Echo`](https://github.com/hyperledger/fabric-private-chaincode/tree/main/samples/chaincode/echo). - [`Orion: Cars`](../integration/orion/cars/README.md): In this example, we show how to orchestrate transactions for [`Orion`](https://github.com/hyperledger-labs/orion-server). ## Logging configuration