Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import protoutils from core fabric #23

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ fabric-lib-go is a home for go code that is common across fabric repositories.

It contains:
- health check logic that is used by fabric and fabric-ca
- protobuf utilities for fabric core or API developer
45 changes: 45 additions & 0 deletions common/crypto/random.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright IBM Corp. 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package crypto

import (
"crypto/rand"

"github.com/pkg/errors"
)

const (
// NonceSize is the default NonceSize
NonceSize = 24
)

// GetRandomBytes returns len random looking bytes
func GetRandomBytes(len int) ([]byte, error) {
key := make([]byte, len)

_, err := rand.Read(key)
if err != nil {
return nil, errors.Wrap(err, "error getting random bytes")
}

return key, nil
}

// GetRandomNonce returns a random byte array of length NonceSize
func GetRandomNonce() ([]byte, error) {
return GetRandomBytes(NonceSize)
}
25 changes: 25 additions & 0 deletions common/crypto/random_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Copyright IBM Corp. 2017 All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package crypto

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestGetRandomBytes(t *testing.T) {
_, err := GetRandomBytes(10)

require.NoError(t, err, "GetRandomBytes fails")
}

func TestGetRandomNonce(t *testing.T) {
_, err := GetRandomNonce()

require.NoError(t, err, "GetRandomNonce fails")
}
15 changes: 15 additions & 0 deletions common/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module github.com/hyperledger/fabric-lib-go/common

go 1.20

require (
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.8.4
google.golang.org/protobuf v1.32.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
16 changes: 16 additions & 0 deletions common/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
76 changes: 76 additions & 0 deletions common/util/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
Copyright IBM Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package util

import (
"crypto/rand"
"fmt"
"io"
"time"

timestamp "google.golang.org/protobuf/types/known/timestamppb"
)

// 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)
}

// CreateUtcTimestamp returns a Timestamp protobuf in UTC
func CreateUtcTimestamp() *timestamp.Timestamp {
now := time.Now().UTC()
secs := now.Unix()
nanos := int32(now.UnixNano() - (secs * 1000000000))
return &(timestamp.Timestamp{Seconds: secs, Nanos: nanos})
}

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:])
}

// ToChaincodeArgs converts string args to []byte args
func ToChaincodeArgs(args ...string) [][]byte {
bargs := make([][]byte, len(args))
for i, arg := range args {
bargs[i] = []byte(arg)
}
return bargs
}

// ConcatenateBytes is useful for combining multiple arrays of bytes, especially for
// signatures or digests over multiple fields
// This way is more efficient in speed
func ConcatenateBytes(data ...[]byte) []byte {
finalLength := 0
for _, slice := range data {
finalLength += len(slice)
}
result := make([]byte, finalLength)
last := 0
for _, slice := range data {
last += copy(result[last:], slice)
}
return result
}
78 changes: 78 additions & 0 deletions common/util/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
Copyright IBM Corp. 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package util

import (
"bytes"
"testing"
"time"
)

func TestUUIDGeneration(t *testing.T) {
uuid := GenerateUUID()
if len(uuid) != 36 {
t.Fatalf("UUID length is not correct. Expected = 36, Got = %d", len(uuid))
}
uuid2 := GenerateUUID()
if uuid == uuid2 {
t.Fatalf("Two UUIDs are equal. This should never occur")
}
}

func TestTimestamp(t *testing.T) {
for i := 0; i < 10; i++ {
t.Logf("timestamp now: %v", CreateUtcTimestamp())
time.Sleep(200 * time.Millisecond)
}
}

func TestToChaincodeArgs(t *testing.T) {
expected := [][]byte{[]byte("foo"), []byte("bar")}
actual := ToChaincodeArgs("foo", "bar")
if len(expected) != len(actual) {
t.Fatalf("Got %v, expected %v", actual, expected)
}
for i := range expected {
if !bytes.Equal(expected[i], actual[i]) {
t.Fatalf("Got %v, expected %v", actual, expected)
}
}
}

func TestConcatenateBytesNormal(t *testing.T) {
first := []byte("first")
second := []byte("second")
third := []byte("third")

result := ConcatenateBytes(first, second, third)
expected := []byte("firstsecondthird")
if !bytes.Equal(result, expected) {
t.Errorf("Did not concatenate bytes correctly, expected %s, got %s", expected, result)
}
}

func TestConcatenateBytesNil(t *testing.T) {
first := []byte("first")
second := []byte(nil)
third := []byte("third")

result := ConcatenateBytes(first, second, third)
expected := []byte("firstthird")
if !bytes.Equal(result, expected) {
t.Errorf("Did not concatenate bytes correctly, expected %s, got %s", expected, result)
}
}
7 changes: 7 additions & 0 deletions protoutil/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# protoutil

This originates as a copy of github.com/hyperledger/fabric/protoutil

## Prepare
to use `counterfeiter`
- install by running `go install github.com/maxbrunsfeld/counterfeiter/v6@latest` outside of go module
Loading