diff --git a/.env b/.env new file mode 100644 index 000000000..935e96d61 --- /dev/null +++ b/.env @@ -0,0 +1,7 @@ +GINKGO_TEST_OPTS ?= +#GINKGO_TEST_OPTS += --keep-going +GINKGO_TEST_OPTS += --vv +#GINKGO_TEST_OPTS += --until-it-fails +GINKGO_TEST_OPTS += --poll-progress-after 60s +GINKGO_TEST_OPTS += --fail-fast +#GINKGO_TEST_OPTS += --focus "generate artifacts & successful pingpong" \ No newline at end of file diff --git a/docs/platform/fabric/fabricdev/core/fabricdev/channelprovider.go b/docs/platform/fabric/fabricdev/core/fabricdev/channelprovider.go index ee252361f..69f01c585 100644 --- a/docs/platform/fabric/fabricdev/core/fabricdev/channelprovider.go +++ b/docs/platform/fabric/fabricdev/core/fabricdev/channelprovider.go @@ -13,7 +13,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" driver3 "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/chaincode" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/committer" @@ -41,7 +40,6 @@ type provider struct { metadataKVS driver.MetadataStore endorseTxKVS driver.EndorseTxStore publisher events.Publisher - hasher hash.Hasher newVault generic.VaultConstructor tracerProvider tracing.Provider metricsProvider metrics.Provider @@ -58,7 +56,6 @@ func NewChannelProvider( metadataKVS driver.MetadataStore, endorseTxKVS driver.EndorseTxStore, publisher events.Publisher, - hasher hash.Hasher, tracerProvider tracing.Provider, metricsProvider metrics.Provider, drivers multiplexed.Driver, @@ -74,7 +71,6 @@ func NewChannelProvider( metadataKVS: metadataKVS, endorseTxKVS: endorseTxKVS, publisher: publisher, - hasher: hasher, newVault: newVault, tracerProvider: tracerProvider, metricsProvider: metricsProvider, @@ -120,7 +116,6 @@ func (p *provider) NewChannel(nw driver.FabricNetworkService, channelName string nw.ConfigService(), peerService, nw.LocalMembership().DefaultSigningIdentity(), - p.hasher, channelConfig.FinalityWaitTimeout(), true, ) @@ -180,7 +175,6 @@ func (p *provider) NewChannel(nw driver.FabricNetworkService, channelName string deliveryService, err := delivery.NewService( channelName, channelConfig, - p.hasher, nw.Name(), nw.LocalMembership(), nw.ConfigService(), diff --git a/docs/platform/fabric/fabricdev/core/fabricdev/driver/provider.go b/docs/platform/fabric/fabricdev/core/fabricdev/driver/provider.go index 103bddb8f..8a8c0ecf1 100644 --- a/docs/platform/fabric/fabricdev/core/fabricdev/driver/provider.go +++ b/docs/platform/fabric/fabricdev/core/fabricdev/driver/provider.go @@ -15,7 +15,6 @@ import ( committer2 "github.com/hyperledger-labs/fabric-smart-client/platform/common/core/generic/committer" cdriver "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/committer" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/driver/config" @@ -62,7 +61,6 @@ func NewProvider( idProvider identity.ViewIdentityProvider, kvss *kvs.KVS, publisher events.Publisher, - hasher hash.Hasher, tracerProvider tracing.Provider, Drivers multiplexed.Driver, ) *Provider { @@ -74,7 +72,6 @@ func NewProvider( metadataKVS, endorseTxKVS, publisher, - hasher, tracerProvider, metricsProvider, Drivers, diff --git a/docs/platform/fabric/fabricdev/sdk/fabricdev/providers.go b/docs/platform/fabric/fabricdev/sdk/fabricdev/providers.go index da4b3ade7..d8bae17c7 100644 --- a/docs/platform/fabric/fabricdev/sdk/fabricdev/providers.go +++ b/docs/platform/fabric/fabricdev/sdk/fabricdev/providers.go @@ -8,7 +8,6 @@ package fabricdev import ( fdevdriver "github.com/hyperledger-labs/fabric-smart-client/docs/platform/fabric/fabricdev/core/fabricdev/driver" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/driver/config" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/driver/identity" @@ -37,7 +36,6 @@ func NewDriver(in struct { IdProvider identity.ViewIdentityProvider KVS *kvs.KVS Publisher events.Publisher - Hasher hash.Hasher TracerProvider tracing.Provider Drivers multiplexed.Driver }) core.NamedDriver { @@ -55,7 +53,6 @@ func NewDriver(in struct { in.IdProvider, in.KVS, in.Publisher, - in.Hasher, in.TracerProvider, in.Drivers, ), diff --git a/integration/fabric/atsa/states/states_test.go b/integration/fabric/atsa/states/states_test.go index e40719c6c..cc0c1092a 100644 --- a/integration/fabric/atsa/states/states_test.go +++ b/integration/fabric/atsa/states/states_test.go @@ -28,10 +28,8 @@ func TestJson(t *testing.T) { o, err := json.MarshalIndent(asset, "", " ") assert.NoError(err) fmt.Println(string(o)) - hash := sha256.New() - hash.Write([]byte("Hello World!!!")) - rawHashed := hash.Sum(nil) - asset.PrivateProperties = []byte(base64.StdEncoding.EncodeToString(rawHashed)) + rawHashed := sha256.Sum256([]byte("Hello World!!!")) + asset.PrivateProperties = []byte(base64.StdEncoding.EncodeToString(rawHashed[:])) o, err = json.MarshalIndent(asset, "", " ") assert.NoError(err) fmt.Println(string(o)) diff --git a/integration/fabric/atsachaincode/chaincode/asset_transfer.go b/integration/fabric/atsachaincode/chaincode/asset_transfer.go index 779bcf715..ef4d3c4f1 100644 --- a/integration/fabric/atsachaincode/chaincode/asset_transfer.go +++ b/integration/fabric/atsachaincode/chaincode/asset_transfer.go @@ -221,9 +221,8 @@ func (s *SmartContract) VerifyAssetProperties(ctx contractapi.TransactionContext return false, fmt.Errorf("asset private properties hash does not exist: %s", assetID) } - hash := sha256.New() - hash.Write(immutablePropertiesJSON) - calculatedPropertiesHash := hash.Sum(nil) + h := sha256.Sum256(immutablePropertiesJSON) + calculatedPropertiesHash := h[:] // verify that the hash of the passed immutable properties matches the on-chain hash if !bytes.Equal(immutablePropertiesOnChainHash, calculatedPropertiesHash) { diff --git a/integration/fabricx/iou/iou_test.go b/integration/fabricx/iou/iou_test.go index d4305976d..8166b348e 100644 --- a/integration/fabricx/iou/iou_test.go +++ b/integration/fabricx/iou/iou_test.go @@ -14,10 +14,10 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/integration" "github.com/hyperledger-labs/fabric-smart-client/integration/fabricx/iou" + "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/common" nwofabricx "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabricx" "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabricx/fxconfig" nwofsc "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fsc" - "github.com/hyperledger/fabric/integration/nwo" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -76,7 +76,7 @@ func updateEP(s *TestSuite) { Version: 0, } - cmd := nwo.NewCommand(fxconfig.CMDPath(), command) + cmd := common.NewCommand(fxconfig.CMDPath(), command) cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout err := cmd.Run() diff --git a/integration/nwo/common/images.go b/integration/nwo/common/images.go index 99573cd86..8bfef976a 100644 --- a/integration/nwo/common/images.go +++ b/integration/nwo/common/images.go @@ -10,11 +10,11 @@ import ( "encoding/base32" "strings" - "github.com/hyperledger/fabric/common/util" + "github.com/hyperledger-labs/fabric-smart-client/pkg/utils" ) // UniqueName generates base-32 enocded UUIDs for container names. func UniqueName() string { - name := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(util.GenerateBytesUUID()) + name := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(utils.GenerateBytesUUID()) return strings.ToLower(name) } diff --git a/integration/nwo/fabric/topology/chaincode.go b/integration/nwo/fabric/topology/chaincode.go index a0e3939b0..3a1a3b1df 100644 --- a/integration/nwo/fabric/topology/chaincode.go +++ b/integration/nwo/fabric/topology/chaincode.go @@ -7,10 +7,10 @@ SPDX-License-Identifier: Apache-2.0 package topology import ( + "crypto/sha256" "fmt" "os" - "github.com/hyperledger/fabric/common/util" "github.com/onsi/gomega" ) @@ -37,7 +37,7 @@ type Chaincode struct { func (c *Chaincode) SetPackageIDFromPackageFile() { fileBytes, err := os.ReadFile(c.PackageFile) gomega.Expect(err).NotTo(gomega.HaveOccurred()) - hashStr := fmt.Sprintf("%x", util.ComputeSHA256(fileBytes)) + hashStr := fmt.Sprintf("%x", sha256.Sum256(fileBytes)) c.PackageID = c.Label + ":" + hashStr } diff --git a/integration/nwo/fabricx/network/network.go b/integration/nwo/fabricx/network/network.go index fb742302a..f1cfb717d 100644 --- a/integration/nwo/fabricx/network/network.go +++ b/integration/nwo/fabricx/network/network.go @@ -11,6 +11,7 @@ import ( "time" "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" fabric_network "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/network" "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fabric/topology" @@ -18,7 +19,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/integration/nwo/fsc/node" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" - "github.com/hyperledger/fabric/integration/nwo" "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" @@ -168,7 +168,7 @@ func (n *Network) PostRun(load bool) { gomega.Eventually(func(g gomega.Gomega) { // TODO: set the correct query service endpoint cmd := &fxconfig.ListNamespaces{QueryServiceEndpoint: "127.0.0.1:7001"} - sess, err := n.StartSession(nwo.NewCommand(fxconfig.CMDPath(), cmd), cmd.SessionName()) + sess, err := n.StartSession(common.NewCommand(fxconfig.CMDPath(), cmd), cmd.SessionName()) g.Expect(err).NotTo(gomega.HaveOccurred()) g.Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit(0)) @@ -211,7 +211,7 @@ func (n *Network) DeployNamespace(chaincode *topology.ChannelChaincode) { }, }, } - sess, err := n.StartSession(nwo.NewCommand(fxconfig.CMDPath(), cmd), cmd.SessionName()) + sess, err := n.StartSession(common.NewCommand(fxconfig.CMDPath(), cmd), cmd.SessionName()) gomega.Expect(err).NotTo(gomega.HaveOccurred()) gomega.Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit(0)) } @@ -223,7 +223,7 @@ func (n *Network) UpdateNamespace(chaincodeID, version, path, packageFile string func (n *Network) ListInstalledNames() { cmd := &fxconfig.ListNamespaces{QueryServiceEndpoint: "127.0.0.1:7001"} - sess, err := n.StartSession(nwo.NewCommand(fxconfig.CMDPath(), cmd), cmd.SessionName()) + sess, err := n.StartSession(common.NewCommand(fxconfig.CMDPath(), cmd), cmd.SessionName()) gomega.Expect(err).NotTo(gomega.HaveOccurred()) gomega.Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit(0)) } diff --git a/integration/nwo/fsc/fsc.go b/integration/nwo/fsc/fsc.go index b3ea57d71..1af3600e0 100755 --- a/integration/nwo/fsc/fsc.go +++ b/integration/nwo/fsc/fsc.go @@ -33,7 +33,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/collections" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/grpc" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/storage/driver" common2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/storage/driver/common" @@ -264,7 +263,6 @@ func (p *Platform) PostRun(bool) { ConnectionConfig: p.Context.ConnectionConfig(node.UniqueName), }, p.Context.ClientSigningIdentity(node.Name), - hash.NewSHA256Provider(), tracerProvider, ) gomega.Expect(err).NotTo(gomega.HaveOccurred()) diff --git a/platform/common/core/generic/vault/interceptor.go b/platform/common/core/generic/vault/interceptor.go index 4ae3a6169..6558bf25e 100644 --- a/platform/common/core/generic/vault/interceptor.go +++ b/platform/common/core/generic/vault/interceptor.go @@ -12,7 +12,7 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" + "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" ) type VersionedQueryExecutor interface { @@ -200,7 +200,7 @@ func (i *Interceptor[V]) SetState(namespace string, key string, value []byte) er if i.IsClosed() { return errors.New("this instance was closed") } - i.logger.Debugf("SetState [%s,%s,%s]", namespace, key, hash.Hashable(value).String()) + i.logger.Debugf("SetState [%s,%s,%s]", namespace, key, logging.SHA256Base64(value)) return i.rws.WriteSet.Add(namespace, key, value) } diff --git a/platform/common/services/identity/identity.go b/platform/common/services/identity/identity.go index e613e8a91..8bd533694 100644 --- a/platform/common/services/identity/identity.go +++ b/platform/common/services/identity/identity.go @@ -8,9 +8,8 @@ package identity import ( "bytes" + "crypto/sha256" "encoding/base64" - - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" ) // Identity wraps the byte representation of a lower level identity. @@ -26,7 +25,8 @@ func (id Identity) UniqueID() string { if len(id) == 0 { return "" } - return base64.StdEncoding.EncodeToString(utils.MustGet(utils.SHA256(id))) + h := sha256.Sum256(id) + return base64.StdEncoding.EncodeToString(h[:]) } // Hash returns the hash of this identity @@ -34,7 +34,8 @@ func (id Identity) Hash() string { if len(id) == 0 { return "" } - return string(utils.MustGet(utils.SHA256(id))) + h := sha256.Sum256(id) + return string(h[:]) } // String returns a string representation of this identity diff --git a/platform/common/services/logging/types.go b/platform/common/services/logging/types.go index ebe527939..56fae0317 100644 --- a/platform/common/services/logging/types.go +++ b/platform/common/services/logging/types.go @@ -7,6 +7,7 @@ SPDX-License-Identifier: Apache-2.0 package logging import ( + "crypto/sha256" "encoding/base64" "fmt" "reflect" @@ -15,7 +16,6 @@ import ( "unicode" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/collections" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" ) const ( @@ -33,6 +33,18 @@ func (k keys[K, V]) String() string { return fmt.Sprintf(strings.Join(collections.Repeat("%v", len(k)), ", "), collections.Keys(k)) } +// SHA256Base64 logs lazily a byte slice as sha265 hash in base64 format +func SHA256Base64(b []byte) sha256Base64Enc { + h := sha256.Sum256(b) + return h[:] +} + +type sha256Base64Enc []byte + +func (b sha256Base64Enc) String() string { + return Base64(b).String() +} + // Base64 logs lazily a byte array in base64 format func Base64(b []byte) base64Enc { return b @@ -87,7 +99,7 @@ func (w prefix) String() string { if len(res) <= 20 { return res } - return fmt.Sprintf("%s~%s", res[:20], hash.Hashable(res).String()) + return fmt.Sprintf("%s~%s", res[:20], SHA256Base64([]byte(res))) } type printable string diff --git a/platform/common/utils/hash.go b/platform/common/utils/hash.go deleted file mode 100644 index 5e7fbc8b2..000000000 --- a/platform/common/utils/hash.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package utils - -import ( - "crypto/sha256" - "encoding/binary" - - "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" -) - -func HashUInt64(raw []byte) (uint64, error) { - digest, err := SHA256(raw) - if err != nil { - return 0, err - } - return binary.BigEndian.Uint64(digest[:8]), nil -} - -func HashInt64(raw []byte) (int64, error) { - digest, err := HashUInt64(raw) - if err != nil { - return 0, err - } - return int64(digest >> 1), nil -} - -func HashUInt32(raw []byte) (uint32, error) { - digest, err := SHA256(raw) - if err != nil { - return 0, err - } - return binary.BigEndian.Uint32(digest[:4]), nil -} - -func SHA256(raw []byte) ([]byte, error) { - hash := sha256.New() - n, err := hash.Write(raw) - if n != len(raw) { - return nil, errors.Errorf("hash failure") - } - if err != nil { - return nil, err - } - digest := hash.Sum(nil) - - return digest, nil -} diff --git a/platform/common/utils/hash/hash.go b/platform/common/utils/hash/hash.go deleted file mode 100644 index 9001845fc..000000000 --- a/platform/common/utils/hash/hash.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package hash - -import ( - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" -) - -func SHA256(raw []byte) ([]byte, error) { - return utils.SHA256(raw) -} - -func SHA256OrPanic(raw []byte) []byte { - return utils.MustGet(utils.SHA256(raw)) -} diff --git a/platform/common/utils/hash/hashable.go b/platform/common/utils/hash/hashable.go deleted file mode 100644 index b015101ef..000000000 --- a/platform/common/utils/hash/hashable.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package hash - -import ( - "encoding/base64" - - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" -) - -type Hashable []byte - -func (id Hashable) Raw() []byte { - if len(id) == 0 { - return nil - } - return utils.MustGet(utils.SHA256(id)) -} - -func (id Hashable) String() string { return base64.StdEncoding.EncodeToString(id.Raw()) } - -func (id Hashable) RawString() string { return string(id.Raw()) } diff --git a/platform/common/utils/hash/hasher.go b/platform/common/utils/hash/hasher.go deleted file mode 100644 index be8ac59fa..000000000 --- a/platform/common/utils/hash/hasher.go +++ /dev/null @@ -1,11 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package hash - -type Hasher interface { - Hash(msg []byte) ([]byte, error) -} diff --git a/platform/common/utils/hash/provider.go b/platform/common/utils/hash/provider.go deleted file mode 100644 index 7dcba2069..000000000 --- a/platform/common/utils/hash/provider.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package hash - -import ( - "crypto/sha256" - "hash" - - "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" -) - -type SHA256Provider struct { -} - -func NewSHA256Provider() *SHA256Provider { - return &SHA256Provider{} -} - -func (p *SHA256Provider) Hash(msg []byte) ([]byte, error) { - hash := sha256.New() - n, err := hash.Write(msg) - if n != len(msg) { - return nil, errors.Errorf("hash failure") - } - if err != nil { - return nil, err - } - digest := hash.Sum(nil) - - return digest, nil -} - -func (p *SHA256Provider) GetHash() hash.Hash { - return sha256.New() -} diff --git a/platform/common/utils/hash_test.go b/platform/common/utils/hash_test.go deleted file mode 100644 index d5660010f..000000000 --- a/platform/common/utils/hash_test.go +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package utils - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestHashUInt64(t *testing.T) { - digest, err := HashUInt64([]byte("any_string?!")) - assert.NoError(t, err) - assert.Equal(t, uint64(12901064304492776662), digest) -} - -func TestHashInt64(t *testing.T) { - digest, err := HashInt64([]byte("any_string?!")) - assert.NoError(t, err) - assert.Equal(t, int64(6450532152246388331), digest) -} - -func TestHashUInt32(t *testing.T) { - digest, err := HashUInt32([]byte("any_string?!")) - assert.NoError(t, err) - assert.Equal(t, uint32(3003763105), digest) -} diff --git a/platform/fabric/core/generic/chaincode/discovery.go b/platform/fabric/core/generic/chaincode/discovery.go index 7bff5052b..5c031defb 100644 --- a/platform/fabric/core/generic/chaincode/discovery.go +++ b/platform/fabric/core/generic/chaincode/discovery.go @@ -8,6 +8,7 @@ package chaincode import ( "context" + "crypto/sha256" "strings" "sync" "time" @@ -19,7 +20,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" discovery2 "github.com/hyperledger/fabric-protos-go-apiv2/discovery" "github.com/hyperledger/fabric-protos-go-apiv2/peer" - "github.com/hyperledger/fabric/common/util" discovery "github.com/hyperledger/fabric/discovery/client" ) @@ -239,7 +239,8 @@ func (d *Discovery) query(req *discovery.Request) (discovery.Response, error) { } var ClientTLSCertHash []byte if len(pc.Certificate().Certificate) != 0 { - ClientTLSCertHash = util.ComputeSHA256(pc.Certificate().Certificate[0]) + h := sha256.Sum256(pc.Certificate().Certificate[0]) + ClientTLSCertHash = h[:] } req.Authentication = &discovery2.AuthInfo{ ClientIdentity: signerRaw, diff --git a/platform/fabric/core/generic/channelprovider.go b/platform/fabric/core/generic/channelprovider.go index 8fa6b174d..ed0cc556c 100644 --- a/platform/fabric/core/generic/channelprovider.go +++ b/platform/fabric/core/generic/channelprovider.go @@ -11,7 +11,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" driver3 "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/chaincode" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/committer" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/delivery" @@ -78,7 +77,6 @@ type provider struct { envelopeKVS driver.EnvelopeStore metadataKVS driver.MetadataStore endorserTxKVS driver.EndorseTxStore - hasher hash.Hasher newVault VaultConstructor drivers multiplexed.Driver channelConfigProvider driver.ChannelConfigProvider @@ -95,7 +93,6 @@ func NewChannelProvider( envelopeKVS driver.EnvelopeStore, metadataKVS driver.MetadataStore, endorserTxKVS driver.EndorseTxStore, - hasher hash.Hasher, drivers multiplexed.Driver, newVault VaultConstructor, channelConfigProvider driver.ChannelConfigProvider, @@ -111,7 +108,6 @@ func NewChannelProvider( envelopeKVS: envelopeKVS, metadataKVS: metadataKVS, endorserTxKVS: endorserTxKVS, - hasher: hasher, newVault: newVault, drivers: drivers, channelConfigProvider: channelConfigProvider, @@ -152,7 +148,6 @@ func (p *provider) NewChannel(nw driver.FabricNetworkService, channelName string nw.ConfigService(), peerService, nw.LocalMembership().DefaultSigningIdentity(), - p.hasher, channelConfig.FinalityWaitTimeout(), p.useFilteredDelivery, ) diff --git a/platform/fabric/core/generic/delivery/deliverclient.go b/platform/fabric/core/generic/delivery/deliverclient.go index 4ed9cee51..fdafcc7df 100644 --- a/platform/fabric/core/generic/delivery/deliverclient.go +++ b/platform/fabric/core/generic/delivery/deliverclient.go @@ -26,10 +26,6 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) -type Hasher interface { - Hash(msg []byte) (hash []byte, err error) -} - // TxEvent contains information for token transaction commit type TxEvent struct { TxID string @@ -116,7 +112,7 @@ func (d *deliverClient) Certificate() *tls.Certificate { } // CreateDeliverEnvelope creates a signed envelope with SeekPosition_Newest for block -func CreateDeliverEnvelope(channelID string, signingIdentity driver.SigningIdentity, cert *tls.Certificate, hasher Hasher, start *ab.SeekPosition) (*common.Envelope, error) { +func CreateDeliverEnvelope(channelID string, signingIdentity driver.SigningIdentity, cert *tls.Certificate, start *ab.SeekPosition) (*common.Envelope, error) { logger.Debugf("create delivery envelope starting from: [%s]", start) creator, err := signingIdentity.Serialize() if err != nil { @@ -124,7 +120,7 @@ func CreateDeliverEnvelope(channelID string, signingIdentity driver.SigningIdent } // check for client certificate and compute SHA2-256 on certificate if present - tlsCertHash, err := grpc2.GetTLSCertHash(cert, hasher) + tlsCertHash, err := grpc2.GetTLSCertHash(cert) if err != nil { return nil, err } diff --git a/platform/fabric/core/generic/delivery/delivery.go b/platform/fabric/core/generic/delivery/delivery.go index 25d6c2b87..7352dd015 100644 --- a/platform/fabric/core/generic/delivery/delivery.go +++ b/platform/fabric/core/generic/delivery/delivery.go @@ -67,7 +67,6 @@ type Services interface { type Delivery struct { channel string channelConfig driver.ChannelConfig - hasher Hasher NetworkName string LocalMembership driver.LocalMembership ConfigService driver.ConfigService @@ -90,7 +89,6 @@ var ( func New( networkName string, channelConfig driver.ChannelConfig, - hasher Hasher, LocalMembership driver.LocalMembership, ConfigService driver.ConfigService, PeerManager Services, @@ -110,7 +108,6 @@ func New( NetworkName: networkName, channel: channelConfig.ID(), channelConfig: channelConfig, - hasher: hasher, LocalMembership: LocalMembership, ConfigService: ConfigService, Services: PeerManager, @@ -326,7 +323,6 @@ func (d *Delivery) connect(ctx context.Context) (DeliverStream, context.CancelFu d.channel, d.LocalMembership.DefaultSigningIdentity(), deliverClient.Certificate(), - d.hasher, d.GetStartPosition(newCtx), ) if err != nil { diff --git a/platform/fabric/core/generic/delivery/service.go b/platform/fabric/core/generic/delivery/service.go index 2ff6a2221..6cd569c23 100644 --- a/platform/fabric/core/generic/delivery/service.go +++ b/platform/fabric/core/generic/delivery/service.go @@ -11,7 +11,6 @@ import ( "time" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/collections" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/fabricutils" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/driver" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/metrics" @@ -25,7 +24,6 @@ type ValidationFlags []uint8 type Service struct { channel string channelConfig driver.ChannelConfig - hasher hash.Hasher NetworkName string LocalMembership driver.LocalMembership ConfigService driver.ConfigService @@ -42,7 +40,6 @@ type Service struct { func NewService( channel string, channelConfig driver.ChannelConfig, - hasher hash.Hasher, networkName string, localMembership driver.LocalMembership, configService driver.ConfigService, @@ -58,7 +55,6 @@ func NewService( deliveryService, err := New( networkName, channelConfig, - hasher, localMembership, configService, peerManager, @@ -77,7 +73,6 @@ func NewService( return &Service{ channel: channel, channelConfig: channelConfig, - hasher: hasher, NetworkName: networkName, LocalMembership: localMembership, ConfigService: configService, @@ -105,7 +100,6 @@ func (c *Service) scanBlock(ctx context.Context, vault Vault, callback driver.Bl deliveryService, err := New( c.NetworkName, c.channelConfig, - c.hasher, c.LocalMembership, c.ConfigService, c.PeerManager, diff --git a/platform/fabric/core/generic/finality/deliveryqs.go b/platform/fabric/core/generic/finality/deliveryqs.go index 5e79def46..71b151c2d 100644 --- a/platform/fabric/core/generic/finality/deliveryqs.go +++ b/platform/fabric/core/generic/finality/deliveryqs.go @@ -36,7 +36,7 @@ func (q *DeliveryScanQueryByID[T]) QueryByID(ctx context.Context, lastBlock driv func (q *DeliveryScanQueryByID[T]) queryByID(ctx context.Context, results collections.Set[string], ch chan []T, lastBlock uint64) { defer close(ch) - startingBlock := MaxUint64(1, lastBlock-10) + startingBlock := max(1, lastBlock-10) err := q.Delivery.ScanFromBlock(ctx, startingBlock, func(tx *fabric.ProcessedTransaction) (bool, error) { if !results.Contains(tx.TxID()) { return false, nil @@ -57,10 +57,3 @@ func (q *DeliveryScanQueryByID[T]) queryByID(ctx context.Context, results collec q.Logger.Errorf("failed scanning: %v", err) } } - -func MaxUint64(a, b uint64) uint64 { - if a > b { - return a - } - return b -} diff --git a/platform/fabric/core/generic/finality/fabric.go b/platform/fabric/core/generic/finality/fabric.go index 498ecd756..9051a7e40 100644 --- a/platform/fabric/core/generic/finality/fabric.go +++ b/platform/fabric/core/generic/finality/fabric.go @@ -24,17 +24,12 @@ type Services interface { NewPeerClient(cc grpc.ConnectionConfig) (services.PeerClient, error) } -type Hasher interface { - Hash(msg []byte) (hash []byte, err error) -} - type FabricFinality struct { Logger logging.Logger Channel string ConfigService driver.ConfigService Services Services DefaultSigningIdentity driver.SigningIdentity - Hasher Hasher WaitForEventTimeout time.Duration useFiltered bool } @@ -45,7 +40,6 @@ func NewFabricFinality( ConfigService driver.ConfigService, peerService Services, defaultSigningIdentity driver.SigningIdentity, - hasher Hasher, waitForEventTimeout time.Duration, useFiltered bool, ) (*FabricFinality, error) { @@ -59,7 +53,6 @@ func NewFabricFinality( ConfigService: ConfigService, Services: peerService, DefaultSigningIdentity: defaultSigningIdentity, - Hasher: hasher, WaitForEventTimeout: waitForEventTimeout, useFiltered: useFiltered, } @@ -100,7 +93,6 @@ func (d *FabricFinality) IsFinal(txID string, address string) error { d.Channel, d.DefaultSigningIdentity, deliverClient.Certificate(), - d.Hasher, &ab.SeekPosition{ Type: &ab.SeekPosition_Newest{ Newest: &ab.SeekNewest{}, diff --git a/platform/fabric/core/generic/msp/idemix/deserializer.go b/platform/fabric/core/generic/msp/idemix/deserializer.go index 8956c19e2..3fc189d7a 100644 --- a/platform/fabric/core/generic/msp/idemix/deserializer.go +++ b/platform/fabric/core/generic/msp/idemix/deserializer.go @@ -14,7 +14,7 @@ import ( math "github.com/IBM/mathlib" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" + "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" ) @@ -121,5 +121,5 @@ func (i *Deserializer) Info(raw []byte, auditInfo []byte) (string, error) { } func (i *Deserializer) String() string { - return fmt.Sprintf("Idemix with IPK [%s]", hash.Hashable(i.Ipk).String()) + return fmt.Sprintf("Idemix with IPK [%s]", logging.SHA256Base64(i.Ipk)) } diff --git a/platform/fabric/core/generic/msp/idemix/provider.go b/platform/fabric/core/generic/msp/idemix/provider.go index 9b4fa00e7..f6407300f 100644 --- a/platform/fabric/core/generic/msp/idemix/provider.go +++ b/platform/fabric/core/generic/msp/idemix/provider.go @@ -18,7 +18,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/proto" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" mspdriver "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/msp/driver" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/driver" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" @@ -334,7 +333,7 @@ func (p *Provider) Identity(opts *driver.IdentityOptions) (view.Identity, []byte []byte(rh), }, } - logger.Debugf("new idemix identity generated with [%s:%s]", enrollmentID, hash.Hashable(rh)) + logger.Debugf("new idemix identity generated with [%s:%s]", enrollmentID, logging.SHA256Base64([]byte(rh))) infoRaw, err = auditInfo.Bytes() if err != nil { return nil, nil, err @@ -412,7 +411,7 @@ func (p *Provider) Info(raw []byte, auditInfo []byte) (string, error) { } func (p *Provider) String() string { - return fmt.Sprintf("Idemix Provider [%s]", hash.Hashable(p.Ipk).String()) + return fmt.Sprintf("Idemix Provider [%s]", logging.SHA256Base64(p.Ipk)) } func (p *Provider) EnrollmentID() string { diff --git a/platform/fabric/core/generic/msp/x509/ecdsa.go b/platform/fabric/core/generic/msp/x509/ecdsa.go index 3255a3f78..af0b10c64 100644 --- a/platform/fabric/core/generic/msp/x509/ecdsa.go +++ b/platform/fabric/core/generic/msp/x509/ecdsa.go @@ -20,7 +20,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/proto" "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" - utils2 "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" "github.com/hyperledger/fabric-lib-go/bccsp/utils" "github.com/hyperledger/fabric-protos-go-apiv2/msp" @@ -74,10 +73,7 @@ func (d *edsaVerifier) Verify(message, sigma []byte) error { return err } - digest, err := utils2.SHA256(message) - if err != nil { - return err - } + digest := sha256.Sum256(message) lowS, err := IsLowS(d.pk, signature.S) if err != nil { @@ -87,7 +83,7 @@ func (d *edsaVerifier) Verify(message, sigma []byte) error { return errors.New("signature is not in lowS") } - valid := ecdsa.Verify(d.pk, digest, signature.R, signature.S) + valid := ecdsa.Verify(d.pk, digest[:], signature.R, signature.S) if !valid { return errors.Errorf("signature not valid") } diff --git a/platform/fabric/core/generic/msp/x509/setup.go b/platform/fabric/core/generic/msp/x509/setup.go index c1b7165d7..5ff04b2cf 100644 --- a/platform/fabric/core/generic/msp/x509/setup.go +++ b/platform/fabric/core/generic/msp/x509/setup.go @@ -7,7 +7,9 @@ SPDX-License-Identifier: Apache-2.0 package x509 import ( + "crypto/sha256" x5092 "crypto/x509" + "encoding/base64" "encoding/hex" "encoding/pem" "os" @@ -15,7 +17,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/proto" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/config" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/msp/driver" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/msp/x509/pkcs11" @@ -226,7 +227,8 @@ func GetRevocationHandle(id []byte) ([]byte, error) { if err != nil { return nil, errors.WithMessage(err, "Failed to marshal PKI public key") } - return []byte(hash.Hashable(encoded).String()), nil + h := sha256.Sum256(encoded) + return []byte(base64.StdEncoding.EncodeToString(h[:])), nil default: return nil, errors.Errorf("bad block type %s, expected CERTIFICATE", block.Type) } diff --git a/platform/fabric/core/generic/transaction/manager.go b/platform/fabric/core/generic/transaction/manager.go index 213fd9c07..a96963a5f 100644 --- a/platform/fabric/core/generic/transaction/manager.go +++ b/platform/fabric/core/generic/transaction/manager.go @@ -53,7 +53,7 @@ func (m *Manager) NewTransaction(ctx context.Context, transactionType driver.Tra } func (m *Manager) NewTransactionFromBytes(ctx context.Context, channel string, raw []byte) (driver.Transaction, error) { - // logger.Debugf("new transaction from bytes [%s]", hash.Hashable(raw)) + // logger.Debugf("new transaction from bytes [%s]", logging.Sha256Base64(raw)) txRaw := &SerializedTransaction{} if err := json.Unmarshal(raw, txRaw); err != nil { return nil, err @@ -164,7 +164,7 @@ func (w *WrappedTransaction) Bytes() ([]byte, error) { Type: w.TransactionType, Raw: raw, }) - // logger.Debugf("new transaction from bytes [%s]", hash.Hashable(out)) + // logger.Debugf("new transaction from bytes [%s]", logging.Sha256Base64(out)) return out, err } diff --git a/platform/fabric/sdk/dig/generic/providers.go b/platform/fabric/sdk/dig/generic/providers.go index 98b4ff8ec..27555d56c 100644 --- a/platform/fabric/sdk/dig/generic/providers.go +++ b/platform/fabric/sdk/dig/generic/providers.go @@ -11,7 +11,6 @@ import ( committer2 "github.com/hyperledger-labs/fabric-smart-client/platform/common/core/generic/committer" driver2 "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" digutils "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/dig" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/committer" @@ -90,7 +89,6 @@ func NewChannelProvider(in struct { MetadataKVS driver.MetadataStore EndorseTxKVS driver.EndorseTxStore Publisher events.Publisher - Hasher hash.Hasher TracerProvider tracing.Provider Drivers multiplexed.Driver MetricsProvider metrics.Provider @@ -102,7 +100,6 @@ func NewChannelProvider(in struct { in.EnvelopeKVS, in.MetadataKVS, in.EndorseTxKVS, - in.Hasher, in.Drivers, func(_ string, configService driver.ConfigService, vaultStore driver2.VaultStore) (*vault.Vault, error) { cachedVault := vault2.NewCachedVault(vaultStore, configService.VaultTXStoreCacheSize()) @@ -192,7 +189,6 @@ func NewChannelProvider(in struct { return delivery.NewService( channel, channelConfig, - in.Hasher, nw.Name(), nw.LocalMembership(), nw.ConfigService(), diff --git a/platform/fabric/services/endorser/builder.go b/platform/fabric/services/endorser/builder.go index c4dee7543..b0d944d4b 100644 --- a/platform/fabric/services/endorser/builder.go +++ b/platform/fabric/services/endorser/builder.go @@ -10,12 +10,10 @@ import ( "context" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" - view2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/services" - "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/comm/session" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" + view2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/services" + "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/comm/session" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" ) @@ -91,7 +89,7 @@ func (t *Builder) newTransaction(ctx context.Context, creator []byte, network, c } func (t *Builder) newTransactionWithType(ctx context.Context, creator []byte, network, channel string, nonce, raw []byte, envelope bool, rawRequest []byte, tType *fabric.TransactionType) (*Transaction, error) { - logger.Debugf("NewTransaction [%s,%s,%s]", view.Identity(creator).UniqueID(), channel, hash.Hashable(raw).String()) + logger.Debugf("NewTransaction [%s,%s,%s]", view.Identity(creator).UniqueID(), channel, logging.SHA256Base64(raw)) defer logger.Debugf("NewTransaction...done.") fNetwork, err := fabric.GetFabricNetworkService(t.sp, network) diff --git a/platform/fabric/services/endorser/transaction.go b/platform/fabric/services/endorser/transaction.go index 648a6d79c..535777ae6 100644 --- a/platform/fabric/services/endorser/transaction.go +++ b/platform/fabric/services/endorser/transaction.go @@ -8,9 +8,9 @@ package endorser import ( "bytes" + "crypto/sha256" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" view2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/services" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" @@ -82,7 +82,8 @@ func (t *Transaction) Hash() ([]byte, error) { if err != nil { return nil, err } - return hash.SHA256(raw) + h := sha256.Sum256(raw) + return h[:], nil } func (t *Transaction) SetFromBytes(raw []byte) error { diff --git a/platform/fabric/services/state/transaction.go b/platform/fabric/services/state/transaction.go index f2dd7c69f..b149ffa75 100755 --- a/platform/fabric/services/state/transaction.go +++ b/platform/fabric/services/state/transaction.go @@ -7,11 +7,10 @@ SPDX-License-Identifier: Apache-2.0 package state import ( - "encoding/base64" "time" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" + "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/endorser" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" @@ -169,10 +168,10 @@ func NewSendTransactionView(tx *Transaction, parties ...view.Identity) *sendTran func (f *sendTransactionView) Call(context view.Context) (interface{}, error) { for _, party := range f.parties { - logger.Debugf("Send transaction to [%s]", base64.StdEncoding.EncodeToString(hash.SHA256OrPanic(party))) + logger.Debugf("Send transaction to [%s]", logging.SHA256Base64(party)) if context.IsMe(party) { - logger.Debugf("This is me %s, do not send.", base64.StdEncoding.EncodeToString(party)) + logger.Debugf("This is me %s, do not send.", logging.Base64(party)) continue } diff --git a/platform/fabricx/core/transaction/envelope.go b/platform/fabricx/core/transaction/envelope.go index b5e7da6d8..dca6cc9a9 100644 --- a/platform/fabricx/core/transaction/envelope.go +++ b/platform/fabricx/core/transaction/envelope.go @@ -13,7 +13,7 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/proto" cb "github.com/hyperledger/fabric-protos-go-apiv2/common" - "github.com/hyperledger/fabric/protoutil" + "github.com/hyperledger/fabric-x-common/protoutil" ) type Envelope struct { diff --git a/platform/fabricx/core/transaction/factory.go b/platform/fabricx/core/transaction/factory.go index 236963b67..d1e638731 100644 --- a/platform/fabricx/core/transaction/factory.go +++ b/platform/fabricx/core/transaction/factory.go @@ -12,7 +12,7 @@ import ( driver2 "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" ftransaction "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/transaction" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/driver" - "github.com/hyperledger/fabric/protoutil" + "github.com/hyperledger/fabric-x-common/protoutil" ) type Factory struct { diff --git a/platform/fabricx/core/transaction/manager.go b/platform/fabricx/core/transaction/manager.go index 5fe7de13f..a30c7b61b 100644 --- a/platform/fabricx/core/transaction/manager.go +++ b/platform/fabricx/core/transaction/manager.go @@ -19,7 +19,7 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" pb "github.com/hyperledger/fabric-protos-go-apiv2/peer" "github.com/hyperledger/fabric-x-committer/api/protoblocktx" - "github.com/hyperledger/fabric/protoutil" + "github.com/hyperledger/fabric-x-common/protoutil" ) type Manager struct { diff --git a/platform/fabricx/core/transaction/marshal.go b/platform/fabricx/core/transaction/marshal.go index 6b3841a05..74de3d401 100644 --- a/platform/fabricx/core/transaction/marshal.go +++ b/platform/fabricx/core/transaction/marshal.go @@ -14,7 +14,7 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/fabricutils" cb "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/hyperledger/fabric-x-committer/api/protoblocktx" - "github.com/hyperledger/fabric/protoutil" + "github.com/hyperledger/fabric-x-common/protoutil" "go.uber.org/zap/zapcore" ) diff --git a/platform/fabricx/core/transaction/transaction.go b/platform/fabricx/core/transaction/transaction.go index 32207e52d..dc8814cca 100644 --- a/platform/fabricx/core/transaction/transaction.go +++ b/platform/fabricx/core/transaction/transaction.go @@ -21,7 +21,7 @@ import ( pb "github.com/hyperledger/fabric-protos-go-apiv2/peer" "github.com/hyperledger/fabric-x-committer/api/protoblocktx" "github.com/hyperledger/fabric-x-committer/utils/signature" - "github.com/hyperledger/fabric/protoutil" + "github.com/hyperledger/fabric-x-common/protoutil" "go.opentelemetry.io/otel/trace" "go.uber.org/zap/zapcore" "golang.org/x/net/context" diff --git a/platform/fabricx/core/vault/marshal.go b/platform/fabricx/core/vault/marshal.go index 4045e5e55..d958aa156 100644 --- a/platform/fabricx/core/vault/marshal.go +++ b/platform/fabricx/core/vault/marshal.go @@ -14,7 +14,7 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/proto" "github.com/hyperledger-labs/fabric-smart-client/platform/common/core/generic/vault" "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" + "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger/fabric-x-committer/api/protoblocktx" "go.uber.org/zap" ) @@ -173,7 +173,7 @@ func (m *Marshaller) RWSetFromBytes(raw []byte, namespaces ...string) (*vault.Re func (m *Marshaller) Append(destination *vault.ReadWriteSet, raw []byte, namespaces ...string) error { var txIn protoblocktx.Tx if err := proto.Unmarshal(raw, &txIn); err != nil { - return errors.Wrapf(err, "failed unmarshalling tx from (%d)[%s]", len(raw), hash.Hashable(raw)) + return errors.Wrapf(err, "failed unmarshalling tx from (%d)[%s]", len(raw), logging.SHA256Base64(raw)) } if logger.IsEnabledFor(zap.DebugLevel) { diff --git a/platform/fabricx/sdk/dig/providers.go b/platform/fabricx/sdk/dig/providers.go index de17fdbfc..b3de02814 100644 --- a/platform/fabricx/sdk/dig/providers.go +++ b/platform/fabricx/sdk/dig/providers.go @@ -11,7 +11,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/platform/common/core/generic/committer" "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic" fcommitter "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/committer" @@ -84,7 +83,6 @@ func NewChannelProvider(in struct { LedgerProvider ledger.Provider Publisher events.Publisher BlockDispatcherProvider *ledger.BlockDispatcherProvider - Hasher hash.Hasher TracerProvider trace.TracerProvider MetricsProvider metrics.Provider QueryServiceProvider queryservice.Provider @@ -104,7 +102,6 @@ func NewChannelProvider(in struct { in.EnvelopeStore, in.MetadataStore, in.EndorseTxStore, - in.Hasher, in.Drivers, func(channelName string, configService fdriver.ConfigService, vaultStore driver.VaultStore) (*vault2.Vault, error) { return vault.New(configService, vaultStore, channelName, in.QueryServiceProvider, in.MetricsProvider, in.TracerProvider) @@ -148,7 +145,6 @@ func NewChannelProvider(in struct { return delivery.NewService( channel, channelConfig, - in.Hasher, nw.Name(), nw.LocalMembership(), nw.ConfigService(), diff --git a/platform/view/sdk/dig/sdk.go b/platform/view/sdk/dig/sdk.go index 7b8d2f34c..07591f534 100644 --- a/platform/view/sdk/dig/sdk.go +++ b/platform/view/sdk/dig/sdk.go @@ -15,7 +15,6 @@ import ( dig2 "github.com/hyperledger-labs/fabric-smart-client/platform/common/sdk/dig" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" digutils "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/dig" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" endpoint2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/sdk/dig/support/endpoint" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/comm" @@ -83,9 +82,6 @@ func NewSDKFrom(baseSDK dig2.SDK, registry services.Registry) *SDK { func (p *SDK) Install() error { err := errors.Join( - // Hasher - p.Container().Provide(hash.NewSHA256Provider, dig.As(new(hash.Hasher), new(server2.Hasher))), - // Events p.Container().Provide(simple.NewEventBus, dig.As(new(events.EventSystem), new(events.Publisher), new(events.Subscriber))), p.Container().Provide(func(system events.EventSystem) *events.Service { return &events.Service{EventSystem: system} }), diff --git a/platform/view/services/comm/host/libp2p/pki.go b/platform/view/services/comm/host/libp2p/pki.go index d06311aec..7e1115a18 100644 --- a/platform/view/services/comm/host/libp2p/pki.go +++ b/platform/view/services/comm/host/libp2p/pki.go @@ -8,9 +8,9 @@ package libp2p import ( "crypto/ecdsa" + "crypto/sha256" "crypto/x509" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" ) @@ -34,7 +34,8 @@ func (p PKIDSynthesizer) PublicKeyID(key any) []byte { } return []byte(ID.String()) case []byte: - return hash.Hashable(d).Raw() + h := sha256.Sum256(d) + return h[:] } panic("unsupported key") } diff --git a/platform/view/services/comm/host/rest/pki.go b/platform/view/services/comm/host/rest/pki.go index f8647e4b0..11b707e67 100644 --- a/platform/view/services/comm/host/rest/pki.go +++ b/platform/view/services/comm/host/rest/pki.go @@ -8,10 +8,10 @@ package rest import ( "crypto/ecdsa" + "crypto/sha256" "crypto/x509" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" - hash2 "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/mr-tron/base58/base58" ) @@ -26,7 +26,8 @@ func (p PKIDSynthesizer) PublicKeyID(key any) []byte { } return id case []byte: - return hash2.Hashable(d).Raw() + h := sha256.Sum256(d) + return h[:] } panic("unsupported key") } @@ -37,9 +38,6 @@ func ecdsaPubKeyID(key *ecdsa.PublicKey) ([]byte, error) { return nil, errors.Wrapf(err, "failed to marshal PK") } - h, err := hash2.SHA256(marshaledPubKey) - if err != nil { - return nil, errors.Errorf("hash failure") - } - return []byte(base58.Encode(h)), nil + h := sha256.Sum256(marshaledPubKey) + return []byte(base58.Encode(h[:])), nil } diff --git a/platform/view/services/comm/ids.go b/platform/view/services/comm/ids.go index 58d6a8dc4..95abf9331 100644 --- a/platform/view/services/comm/ids.go +++ b/platform/view/services/comm/ids.go @@ -12,7 +12,6 @@ import ( ) func computeInternalSessionID(topic string, pkid []byte) string { - hasher := sha256.New() - hasher.Write(pkid) - return topic + "." + hex.EncodeToString(hasher.Sum(nil)) + h := sha256.Sum256(pkid) + return topic + "." + hex.EncodeToString(h[:]) } diff --git a/platform/view/services/comm/session/json.go b/platform/view/services/comm/session/json.go index 5680b1ede..579f59fda 100644 --- a/platform/view/services/comm/session/json.go +++ b/platform/view/services/comm/session/json.go @@ -13,7 +13,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" ) @@ -103,7 +102,7 @@ func (j *jsonSession) ReceiveRawWithTimeout(d time.Duration) ([]byte, error) { logger.ErrorfContext(j.context, "context done: %w", j.context.Err()) return nil, errors.Errorf("context done [%s]", j.context.Err()) } - logger.DebugfContext(j.context, "json session, received message [%s]", hash.Hashable(raw)) + logger.DebugfContext(j.context, "json session, received message [%s]", logging.SHA256Base64(raw)) return raw, nil } @@ -116,12 +115,12 @@ func (j *jsonSession) SendWithContext(ctx context.Context, state interface{}) er if err != nil { return err } - logger.DebugfContext(ctx, "json session, send message [%s]", hash.Hashable(v).String()) + logger.DebugfContext(ctx, "json session, send message [%s]", logging.SHA256Base64(v)) return j.s.SendWithContext(ctx, v) } func (j *jsonSession) SendRaw(ctx context.Context, raw []byte) error { - logger.DebugfContext(ctx, "json session, send raw message [%s]", hash.Hashable(raw).String()) + logger.DebugfContext(ctx, "json session, send raw message [%s]", logging.SHA256Base64(raw)) return j.s.SendWithContext(ctx, raw) } diff --git a/platform/view/services/config/provider.go b/platform/view/services/config/provider.go index 8adc3388a..3c2a8939d 100644 --- a/platform/view/services/config/provider.go +++ b/platform/view/services/config/provider.go @@ -18,7 +18,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services" viperutil "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/config/viper" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/events" @@ -206,7 +205,7 @@ func (p *Provider) loadFromRaw(raw []byte) error { // read configuration if err := p.Backend.ReadConfig(bytes.NewReader(raw)); err != nil { - return errors.Wrapf(err, "failed to read configuration from raw [%s]", hash.Hashable(raw)) + return errors.Wrapf(err, "failed to read configuration from raw [%s]", logging.SHA256Base64(raw)) } // post process if err := p.substituteEnv(); err != nil { diff --git a/platform/view/services/endpoint/pki.go b/platform/view/services/endpoint/pki.go index f0da2dac5..87407b7f7 100644 --- a/platform/view/services/endpoint/pki.go +++ b/platform/view/services/endpoint/pki.go @@ -7,9 +7,8 @@ SPDX-License-Identifier: Apache-2.0 package endpoint import ( + "crypto/sha256" "crypto/x509" - - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" ) type DefaultPublicKeyIDSynthesizer struct{} @@ -19,5 +18,6 @@ func (d DefaultPublicKeyIDSynthesizer) PublicKeyID(key any) []byte { if err != nil { return nil } - return hash.Hashable(raw).Raw() + h := sha256.Sum256(raw) + return h[:] } diff --git a/platform/view/services/grpc/client.go b/platform/view/services/grpc/client.go index 789c5f74a..fac4fca91 100644 --- a/platform/view/services/grpc/client.go +++ b/platform/view/services/grpc/client.go @@ -8,6 +8,7 @@ package grpc import ( "context" + "crypto/sha256" "crypto/tls" "crypto/x509" "os" @@ -38,22 +39,14 @@ func CertPoolOverride(pool *x509.CertPool) TLSOption { } } -// Hasher is the interface provides the hash function should be used for all token components. -type Hasher interface { - Hash(msg []byte) (hash []byte, err error) -} - // GetTLSCertHash computes SHA2-256 on tls certificate -func GetTLSCertHash(cert *tls.Certificate, hasher Hasher) ([]byte, error) { +func GetTLSCertHash(cert *tls.Certificate) ([]byte, error) { if cert == nil || len(cert.Certificate) == 0 { return nil, nil } - tlsCertHash, err := hasher.Hash(cert.Certificate[0]) - if err != nil { - return nil, errors.WithMessage(err, "failed to compute SHA256 on client certificate") - } - return tlsCertHash, nil + tlsCertHash := sha256.Sum256(cert.Certificate[0]) + return tlsCertHash[:], nil } // Client models a GRPC client diff --git a/platform/view/services/id/ecdsa/ecdsa.go b/platform/view/services/id/ecdsa/ecdsa.go index b0811da07..0c9732d58 100644 --- a/platform/view/services/id/ecdsa/ecdsa.go +++ b/platform/view/services/id/ecdsa/ecdsa.go @@ -57,17 +57,9 @@ func (e *Signer) Public() crypto.PublicKey { // Sign signs the digest and ensures that signatures use the Low S value. func (e *Signer) Sign(message []byte) ([]byte, error) { - hash := sha256.New() - n, err := hash.Write(message) - if err != nil { - return nil, errors.Wrap(err, "failed to write message to hash") - } - if n != len(message) { - return nil, errors.Errorf("hash failure") - } - digest := hash.Sum(nil) + digest := sha256.Sum256(message) - r, s, err := ecdsa.Sign(rand.Reader, e.PrivateKey, digest) + r, s, err := ecdsa.Sign(rand.Reader, e.PrivateKey, digest[:]) if err != nil { return nil, err } @@ -105,17 +97,9 @@ func (d Verifier) Verify(message, sigma []byte) error { return errors.Errorf("invalid s, must be smaller than half the order [%s][%s]", signature.S, GetCurveHalfOrdersAt(d.pk.Curve)) } - hash := sha256.New() - n, err := hash.Write(message) - if n != len(message) { - return errors.Errorf("hash failure") - } - if err != nil { - return err - } - digest := hash.Sum(nil) + digest := sha256.Sum256(message) - valid := ecdsa.Verify(d.pk, digest, signature.R, signature.S) + valid := ecdsa.Verify(d.pk, digest[:], signature.R, signature.S) if !valid { return errors.Errorf("signature not valid") } diff --git a/platform/view/services/id/x509/ecdsa.go b/platform/view/services/id/x509/ecdsa.go index 83e0fb2a1..8ebd307ac 100644 --- a/platform/view/services/id/x509/ecdsa.go +++ b/platform/view/services/id/x509/ecdsa.go @@ -9,13 +9,13 @@ package x509 import ( "crypto/ecdsa" "crypto/elliptic" + "crypto/sha256" "crypto/x509" "encoding/asn1" "encoding/pem" "math/big" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" ) var ( @@ -50,10 +50,7 @@ func (d *EdsaVerifier) Verify(message, sigma []byte) error { return err } - digest, err := utils.SHA256(message) - if err != nil { - return err - } + digest := sha256.Sum256(message) lowS, err := IsLowS(d.pk, signature.S) if err != nil { @@ -63,7 +60,7 @@ func (d *EdsaVerifier) Verify(message, sigma []byte) error { return errors.New("signature is not in lowS") } - valid := ecdsa.Verify(d.pk, digest, signature.R, signature.S) + valid := ecdsa.Verify(d.pk, digest[:], signature.R, signature.S) if !valid { return errors.Errorf("signature not valid") } diff --git a/platform/view/services/storage/driver/sql/postgres/notifier.go b/platform/view/services/storage/driver/sql/postgres/notifier.go index e15bc3bfb..2bed0e329 100644 --- a/platform/view/services/storage/driver/sql/postgres/notifier.go +++ b/platform/view/services/storage/driver/sql/postgres/notifier.go @@ -8,7 +8,9 @@ package postgres import ( "context" + "crypto/sha256" "database/sql" + "encoding/binary" "fmt" "strconv" "strings" @@ -16,7 +18,6 @@ import ( "time" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/collections" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/storage/driver" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/storage/driver/sql/common" @@ -142,7 +143,7 @@ func (db *Notifier) GetSchema() string { primaryKeys[i] = key.name } funcName := triggerFuncName(primaryKeys) - lock := utils.MustGet(utils.HashInt64([]byte(funcName))) + lock := createLockTag(funcName) return fmt.Sprintf(` SELECT pg_advisory_xact_lock(%d); CREATE OR REPLACE FUNCTION %s() RETURNS TRIGGER AS $$ @@ -212,3 +213,8 @@ func concatenateIDs(keys []string) string { } return strings.Join(fields, fmt.Sprintf(" || '%s' || ", keySeparator)) } + +func createLockTag(m string) uint64 { + h := sha256.Sum256([]byte(m)) + return binary.BigEndian.Uint64(h[:]) +} diff --git a/platform/view/services/storage/kvs/kvs_test.go b/platform/view/services/storage/kvs/kvs_test.go index 8cba4e2f0..149af6a09 100644 --- a/platform/view/services/storage/kvs/kvs_test.go +++ b/platform/view/services/storage/kvs/kvs_test.go @@ -8,6 +8,7 @@ package kvs_test import ( "context" + "crypto/sha256" "fmt" "os" "path" @@ -16,7 +17,6 @@ import ( "time" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" - "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/storage/driver" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/storage/driver/common" mem "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/storage/driver/memory" @@ -102,7 +102,8 @@ func testRound(t *testing.T, driver driver.Driver) { S: "hello", I: 100, } - k, err := sanitizer.Encode(hash.Hashable("Hello World").RawString()) + h := sha256.Sum256([]byte("Hello World")) + k, err := sanitizer.Encode(string(h[:])) assert.NoError(t, err) assert.NoError(t, kvstore.Put(context.Background(), k, val)) assert.True(t, kvstore.Exists(context.Background(), k)) diff --git a/platform/view/services/view/context.go b/platform/view/services/view/context.go index abcacae7b..d4daa707a 100644 --- a/platform/view/services/view/context.go +++ b/platform/view/services/view/context.go @@ -11,6 +11,7 @@ import ( "reflect" "runtime/debug" + "github.com/hyperledger-labs/fabric-smart-client/pkg/utils" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/lazy" @@ -82,7 +83,7 @@ func NewContextForInitiator( return nil, errors.Errorf("a context should not be nil [%s]", string(debug.Stack())) } if len(contextID) == 0 { - contextID = GenerateUUID() + contextID = utils.GenerateUUID() } ctx, err := NewContext( context, diff --git a/platform/view/services/view/context_test.go b/platform/view/services/view/context_test.go index 0d2a08e86..c2032c49b 100644 --- a/platform/view/services/view/context_test.go +++ b/platform/view/services/view/context_test.go @@ -11,6 +11,7 @@ import ( "sync" "testing" + "github.com/hyperledger-labs/fabric-smart-client/pkg/utils" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/endpoint" view2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/view" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/view/mock" @@ -106,7 +107,7 @@ func getSession(t *testing.T, wg *sync.WaitGroup, m Context) { } func getSessionByID(t *testing.T, wg *sync.WaitGroup, m Context) { - _, err := m.GetSessionByID(view2.GenerateUUID(), []byte("alice")) + _, err := m.GetSessionByID(utils.GenerateUUID(), []byte("alice")) wg.Done() assert.NoError(t, err) } diff --git a/platform/view/services/view/grpc/client/client.go b/platform/view/services/view/grpc/client/client.go index 5ce43437b..aeae8083d 100644 --- a/platform/view/services/view/grpc/client/client.go +++ b/platform/view/services/view/grpc/client/client.go @@ -17,7 +17,6 @@ import ( "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/proto" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" - hash2 "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils/hash" grpc2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/grpc" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/tracing" protos2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/view/grpc/server/protos" @@ -78,11 +77,10 @@ type client struct { RandomnessReader io.Reader Time TimeFunc SigningIdentity SigningIdentity - hasher hash2.Hasher tracer trace.Tracer } -func NewClient(config *Config, sID SigningIdentity, hasher hash2.Hasher, tracerProvider tracing.Provider) (*client, error) { +func NewClient(config *Config, sID SigningIdentity, tracerProvider tracing.Provider) (*client, error) { // create a grpc client for view peer grpcClient, err := grpc2.CreateGRPCClient(config.ConnectionConfig) if err != nil { @@ -99,7 +97,6 @@ func NewClient(config *Config, sID SigningIdentity, hasher hash2.Hasher, tracerP GRPCClient: grpcClient, }, SigningIdentity: sID, - hasher: hasher, tracer: tracerProvider.Tracer("client", tracing.WithMetricsOpts(tracing.MetricsOpts{})), }, nil } @@ -176,7 +173,7 @@ func (s *client) processCommand(ctx context.Context, sc *protos2.SignedCommand) return nil, errors.Wrap(err, "failed view client process command") } - logger.Debugf("parse answer [%s]", hash2.Hashable(scr.Response)) + logger.Debugf("parse answer [%s]", logging.SHA256Base64(scr.Response)) commandResp := &protos2.CommandResponse{} err = proto.Unmarshal(scr.Response, commandResp) if err != nil { @@ -241,7 +238,7 @@ func (s *client) CreateSignedCommand(payload interface{}, signingIdentity Signin } // check for client certificate and compute SHA2-256 on certificate if present - tlsCertHash, err := grpc2.GetTLSCertHash(s.ViewServiceClient.Certificate(), s.hasher) + tlsCertHash, err := grpc2.GetTLSCertHash(s.ViewServiceClient.Certificate()) if err != nil { return nil, err } diff --git a/platform/view/services/view/grpc/client/cmd/view.go b/platform/view/services/view/grpc/client/cmd/view.go index be597eb74..12e614af4 100644 --- a/platform/view/services/view/grpc/client/cmd/view.go +++ b/platform/view/services/view/grpc/client/cmd/view.go @@ -7,10 +7,8 @@ SPDX-License-Identifier: Apache-2.0 package view import ( - "crypto/sha256" "encoding/base64" "fmt" - "hash" "io" "os" "path" @@ -43,18 +41,6 @@ var ( userCert string ) -type hasher struct{} - -func (*hasher) GetHash() hash.Hash { - return sha256.New() -} - -func (*hasher) Hash(msg []byte) ([]byte, error) { - h := sha256.New() - h.Write(msg) - return h.Sum(nil), nil -} - func NewCmd() *cobra.Command { cmd := &cobra.Command{ Use: "view", @@ -180,7 +166,6 @@ func invoke() error { ConnectionConfig: cc, }, signer, - &hasher{}, tracerProvider, ) if err != nil { diff --git a/platform/view/services/view/grpc/server/marshal.go b/platform/view/services/view/grpc/server/marshal.go index aa6604ef3..b82daf49c 100644 --- a/platform/view/services/view/grpc/server/marshal.go +++ b/platform/view/services/view/grpc/server/marshal.go @@ -7,6 +7,7 @@ SPDX-License-Identifier: Apache-2.0 package server import ( + "crypto/sha256" "time" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" @@ -34,21 +35,15 @@ type SignerProvider interface { GetSigner(identity view2.Identity) (sig.Signer, error) } -type Hasher interface { - Hash(msg []byte) ([]byte, error) -} - // ResponseMarshaler produces SignedCommandResponse type ResponseMarshaler struct { - hasher Hasher identityProvider IdentityProvider sigService SignerProvider time TimeFunc } -func NewResponseMarshaler(hasher Hasher, identityProvider IdentityProvider, sigService SignerProvider) (*ResponseMarshaler, error) { +func NewResponseMarshaler(identityProvider IdentityProvider, sigService SignerProvider) (*ResponseMarshaler, error) { return &ResponseMarshaler{ - hasher: hasher, identityProvider: identityProvider, sigService: sigService, time: time.Now, @@ -99,11 +94,8 @@ func (s *ResponseMarshaler) createSignedCommandResponse(cr *protos.CommandRespon } func (s *ResponseMarshaler) computeHash(data []byte) (hash []byte) { - hash, err := s.hasher.Hash(data) - if err != nil { - panic(errors.Errorf("failed computing hash on [% x]", data)) - } - return + h := sha256.Sum256(data) + return h[:] } func commandResponseFromPayload(payload interface{}) (*protos.CommandResponse, error) { diff --git a/platform/view/services/view/manager_test.go b/platform/view/services/view/manager_test.go index fb43a6c55..b1bbcc889 100644 --- a/platform/view/services/view/manager_test.go +++ b/platform/view/services/view/manager_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/hyperledger-labs/fabric-smart-client/pkg/utils" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/metrics/disabled" view2 "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/view" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/view/mock" @@ -136,7 +137,7 @@ func TestRegisterResponderWithViewIdentifier(t *testing.T) { } func registerFactory(t *testing.T, wg *sync.WaitGroup, m Manager) { - err := m.RegisterFactory(view2.GenerateUUID(), &DummyFactory{}) + err := m.RegisterFactory(utils.GenerateUUID(), &DummyFactory{}) wg.Done() assert.NoError(t, err) } @@ -153,13 +154,13 @@ func callView(t *testing.T, wg *sync.WaitGroup, m Manager) { } func newView(t *testing.T, wg *sync.WaitGroup, m Manager) { - _, err := m.NewView(view2.GenerateUUID(), nil) + _, err := m.NewView(utils.GenerateUUID(), nil) wg.Done() assert.Error(t, err) } func initiateView(t *testing.T, wg *sync.WaitGroup, m Manager) { - _, err := m.Initiate(view2.GenerateUUID(), context.Background()) + _, err := m.Initiate(utils.GenerateUUID(), context.Background()) wg.Done() assert.Error(t, err) } diff --git a/platform/view/services/view/uuid.go b/platform/view/services/view/uuid.go deleted file mode 100644 index 37bed4d25..000000000 --- a/platform/view/services/view/uuid.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package view - -import ( - "crypto/rand" - "fmt" - "io" -) - -// GenerateBytesUUID returns a UUID based on RFC 4122 returning the generated bytes -func GenerateBytesUUID() []byte { - uuid := make([]byte, 16) - _, err := io.ReadFull(rand.Reader, uuid) - if err != nil { - panic(fmt.Sprintf("Error generating UUID: %s", err)) - } - - // variant bits; see section 4.1.1 - uuid[8] = uuid[8]&^0xc0 | 0x80 - - // version 4 (pseudo-random); see section 4.1.3 - uuid[6] = uuid[6]&^0xf0 | 0x40 - - return uuid -} - -// GenerateUUID returns a UUID based on RFC 4122 -func GenerateUUID() string { - uuid := GenerateBytesUUID() - return idBytesToStr(uuid) -} - -func idBytesToStr(id []byte) string { - return fmt.Sprintf("%x-%x-%x-%x-%x", id[0:4], id[4:6], id[6:8], id[8:10], id[10:]) -} diff --git a/platform/view/services/web/server/server.go b/platform/view/services/web/server/server.go index 2fe250847..01ed4d4aa 100644 --- a/platform/view/services/web/server/server.go +++ b/platform/view/services/web/server/server.go @@ -15,6 +15,7 @@ import ( "os" "time" + utils2 "github.com/hyperledger-labs/fabric-smart-client/pkg/utils" "github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors" "github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging" "github.com/hyperledger-labs/fabric-smart-client/platform/common/utils" @@ -147,9 +148,9 @@ func (s *Server) initializeServer() { func (s *Server) HandlerChain(h http.Handler, secure bool) http.Handler { if secure { - return middleware2.NewChain(middleware2.RequireCert(), middleware2.WithRequestID(GenerateUUID)).Handler(h) + return middleware2.NewChain(middleware2.RequireCert(), middleware2.WithRequestID(utils2.GenerateUUID)).Handler(h) } - return middleware2.NewChain(middleware2.WithRequestID(GenerateUUID)).Handler(h) + return middleware2.NewChain(middleware2.WithRequestID(utils2.GenerateUUID)).Handler(h) } // RegisterHandler registers into the ServeMux a handler chain that borrows diff --git a/platform/view/services/web/server/uuid.go b/platform/view/services/web/server/uuid.go deleted file mode 100644 index c59215d63..000000000 --- a/platform/view/services/web/server/uuid.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package server - -import ( - "crypto/rand" - "fmt" - "io" -) - -// GenerateBytesUUID returns a UUID based on RFC 4122 returning the generated bytes -func GenerateBytesUUID() []byte { - uuid := make([]byte, 16) - _, err := io.ReadFull(rand.Reader, uuid) - if err != nil { - panic(fmt.Sprintf("Error generating UUID: %s", err)) - } - - // variant bits; see section 4.1.1 - uuid[8] = uuid[8]&^0xc0 | 0x80 - - // version 4 (pseudo-random); see section 4.1.3 - uuid[6] = uuid[6]&^0xf0 | 0x40 - - return uuid -} - -// GenerateUUID returns a UUID based on RFC 4122 -func GenerateUUID() string { - uuid := GenerateBytesUUID() - return idBytesToStr(uuid) -} - -func idBytesToStr(id []byte) string { - return fmt.Sprintf("%x-%x-%x-%x-%x", id[0:4], id[4:6], id[6:8], id[8:10], id[10:]) -}