Skip to content

Commit

Permalink
[FAB-6477] Reduce imported Fabric code
Browse files Browse the repository at this point in the history
Change-Id: Ia0e978a10e167d90614c6c279ec016de7efa23ee
Signed-off-by: Troy Ronda <troy@troyronda.com>
  • Loading branch information
troyronda committed Oct 6, 2017
1 parent e216f82 commit db3029c
Show file tree
Hide file tree
Showing 24 changed files with 154 additions and 2,571 deletions.
2 changes: 1 addition & 1 deletion Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

152 changes: 0 additions & 152 deletions internal/github.com/hyperledger/fabric/common/attrmgr/attrmgr.go
Expand Up @@ -26,13 +26,7 @@ Please review third_party pinning scripts and patches for more details.
package attrmgr

import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/json"
"fmt"

"github.com/hyperledger/fabric-sdk-go/pkg/errors"
)

var (
Expand All @@ -59,156 +53,10 @@ type AttributeRequest interface {
IsRequired() bool
}

// New constructs an attribute manager
func New() *Mgr { return &Mgr{} }

// Mgr is the attribute manager and is the main object for this package
type Mgr struct{}

// ProcessAttributeRequestsForCert add attributes to an X509 certificate, given
// attribute requests and attributes.
func (mgr *Mgr) ProcessAttributeRequestsForCert(requests []AttributeRequest, attributes []Attribute, cert *x509.Certificate) error {
attrs, err := mgr.ProcessAttributeRequests(requests, attributes)
if err != nil {
return err
}
return mgr.AddAttributesToCert(attrs, cert)
}

// ProcessAttributeRequests takes an array of attribute requests and an identity's attributes
// and returns an Attributes object containing the requested attributes.
func (mgr *Mgr) ProcessAttributeRequests(requests []AttributeRequest, attributes []Attribute) (*Attributes, error) {
attrsMap := map[string]string{}
attrs := &Attributes{Attrs: attrsMap}
missingRequiredAttrs := []string{}
// For each of the attribute requests
for _, req := range requests {
// Get the attribute
name := req.GetName()
attr := getAttrByName(name, attributes)
if attr == nil {
if req.IsRequired() {
// Didn't find attribute and it was required; return error below
missingRequiredAttrs = append(missingRequiredAttrs, name)
}
// Skip attribute requests which aren't required
continue
}
attrsMap[name] = attr.GetValue()
}
if len(missingRequiredAttrs) > 0 {
return nil, errors.Errorf("The following required attributes are missing: %+v",
missingRequiredAttrs)
}
return attrs, nil
}

// AddAttributesToCert adds public attribute info to an X509 certificate.
func (mgr *Mgr) AddAttributesToCert(attrs *Attributes, cert *x509.Certificate) error {
buf, err := json.Marshal(attrs)
if err != nil {
return errors.Wrap(err, "Failed to marshal attributes")
}
ext := pkix.Extension{
Id: AttrOID,
Critical: false,
Value: buf,
}
cert.Extensions = append(cert.Extensions, ext)
return nil
}

// GetAttributesFromCert gets the attributes from a certificate.
func (mgr *Mgr) GetAttributesFromCert(cert *x509.Certificate) (*Attributes, error) {
// Get certificate attributes from the certificate if it exists
buf, err := getAttributesFromCert(cert)
if err != nil {
return nil, err
}
// Unmarshal into attributes object
attrs := &Attributes{}
if buf != nil {
err := json.Unmarshal(buf, attrs)
if err != nil {
return nil, errors.Wrap(err, "Failed to unmarshal attributes from certificate")
}
}
return attrs, nil
}

// Attributes contains attribute names and values
type Attributes struct {
Attrs map[string]string `json:"attrs"`
}

// Names returns the names of the attributes
func (a *Attributes) Names() []string {
i := 0
names := make([]string, len(a.Attrs))
for name := range a.Attrs {
names[i] = name
i++
}
return names
}

// Contains returns true if the named attribute is found
func (a *Attributes) Contains(name string) bool {
_, ok := a.Attrs[name]
return ok
}

// Value returns an attribute's value
func (a *Attributes) Value(name string) (string, bool, error) {
attr, ok := a.Attrs[name]
return attr, ok, nil
}

// True returns nil if the value of attribute 'name' is true;
// otherwise, an appropriate error is returned.
func (a *Attributes) True(name string) error {
val, ok, err := a.Value(name)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("Attribute '%s' was not found", name)
}
if val != "true" {
return fmt.Errorf("Attribute '%s' is not true", name)
}
return nil
}

// Get the attribute info from a certificate extension, or return nil if not found
func getAttributesFromCert(cert *x509.Certificate) ([]byte, error) {
for _, ext := range cert.Extensions {
if isAttrOID(ext.Id) {
return ext.Value, nil
}
}
return nil, nil
}

// Is the object ID equal to the attribute info object ID?
func isAttrOID(oid asn1.ObjectIdentifier) bool {
if len(oid) != len(AttrOID) {
return false
}
for idx, val := range oid {
if val != AttrOID[idx] {
return false
}
}
return true
}

// Get an attribute from 'attrs' by its name, or nil if not found
func getAttrByName(name string, attrs []Attribute) Attribute {
for _, attr := range attrs {
if attr.GetName() == name {
return attr
}
}
return nil
}
116 changes: 0 additions & 116 deletions internal/github.com/hyperledger/fabric/common/util/utils.go
Expand Up @@ -21,15 +21,10 @@ Please review third_party pinning scripts and patches for more details.
package util

import (
"crypto/rand"
"fmt"
"io"
"math/big"
"strings"
"time"

"github.com/golang/protobuf/ptypes/timestamp"
"github.com/hyperledger/fabric-sdk-go/internal/github.com/hyperledger/fabric/common/metadata"
"github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/bccsp/factory"
)
Expand All @@ -53,45 +48,6 @@ func ComputeSHA256(data []byte) (hash []byte) {
return
}

// ComputeSHA3256 returns SHA3-256 on data
func ComputeSHA3256(data []byte) (hash []byte) {
hash, err := factory.GetDefault().Hash(data, &bccsp.SHA3_256Opts{})
if err != nil {
panic(fmt.Errorf("Failed computing SHA3_256 on [% x]", data))
}
return
}

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

// GenerateIntUUID returns a UUID based on RFC 4122 returning a big.Int
func GenerateIntUUID() *big.Int {
uuid := GenerateBytesUUID()
z := big.NewInt(0)
return z.SetBytes(uuid)
}

// GenerateUUID returns a UUID based on RFC 4122
func GenerateUUID() string {
uuid := GenerateBytesUUID()
return idBytesToStr(uuid)
}

// CreateUtcTimestamp returns a google/protobuf/Timestamp in UTC
func CreateUtcTimestamp() *timestamp.Timestamp {
now := time.Now().UTC()
Expand All @@ -100,86 +56,14 @@ func CreateUtcTimestamp() *timestamp.Timestamp {
return &(timestamp.Timestamp{Seconds: secs, Nanos: nanos})
}

//GenerateHashFromSignature returns a hash of the combined parameters
func GenerateHashFromSignature(path string, args []byte) []byte {
return ComputeSHA256(args)
}

// GenerateIDfromTxSHAHash generates SHA256 hash using Tx payload
func GenerateIDfromTxSHAHash(payload []byte) string {
return fmt.Sprintf("%x", ComputeSHA256(payload))
}

// GenerateIDWithAlg generates an ID using a custom algorithm
func GenerateIDWithAlg(customIDgenAlg string, payload []byte) (string, error) {
if customIDgenAlg == "" {
customIDgenAlg = defaultAlg
}
var alg = availableIDgenAlgs[customIDgenAlg]
if alg.hashFun != nil {
return alg.hashFun(payload), nil
}
return "", fmt.Errorf("Wrong ID generation algorithm was given: %s", customIDgenAlg)
}

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

// FindMissingElements identifies the elements of the first slice that are not present in the second
// The second slice is expected to be a subset of the first slice
func FindMissingElements(all []string, some []string) (delta []string) {
all:
for _, v1 := range all {
for _, v2 := range some {
if strings.Compare(v1, v2) == 0 {
continue all
}
}
delta = append(delta, v1)
}
return
}

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

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

const testchainid = "testchainid"
const testorgid = "**TEST_ORGID**"

//GetTestChainID returns the CHAINID constant in use by orderer
func GetTestChainID() string {
return testchainid
}

//GetTestOrgID returns the ORGID constant in use by gossip join message
func GetTestOrgID() string {
return testorgid
}

//GetSysCCVersion returns the version of all system chaincodes
//This needs to be revisited on policies around system chaincode
//"upgrades" from user and relationship with "fabric" upgrade. For
//now keep it simple and use the fabric's version stamp
func GetSysCCVersion() string {
return metadata.Version
}

// ConcatenateBytes is useful for combining multiple arrays of bytes, especially for
// signatures or digests over multiple fields
func ConcatenateBytes(data ...[]byte) []byte {
Expand Down
52 changes: 0 additions & 52 deletions internal/github.com/hyperledger/fabric/core/comm/config.go
Expand Up @@ -11,11 +11,7 @@ Please review third_party pinning scripts and patches for more details.
package comm

import (
"time"

"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
)

var (
Expand Down Expand Up @@ -76,56 +72,8 @@ func MaxRecvMsgSize() int {
return maxRecvMsgSize
}

// SetMaxRecvMsgSize sets the maximum message size in bytes that gRPC clients
// and servers can receive
func SetMaxRecvMsgSize(size int) {
maxRecvMsgSize = size
}

// MaxSendMsgSize returns the maximum message size in bytes that gRPC clients
// and servers can send
func MaxSendMsgSize() int {
return maxSendMsgSize
}

// SetMaxSendMsgSize sets the maximum message size in bytes that gRPC clients
// and servers can send
func SetMaxSendMsgSize(size int) {
maxSendMsgSize = size
}

// SetKeepaliveOptions sets the gRPC keepalive options for both clients and
// servers
func SetKeepaliveOptions(ka KeepaliveOptions) {
keepaliveOptions = ka
}

// ServerKeepaliveOptions returns the gRPC keepalive options for servers
func ServerKeepaliveOptions() []grpc.ServerOption {
var serverOpts []grpc.ServerOption
kap := keepalive.ServerParameters{
Time: time.Duration(keepaliveOptions.ServerKeepaliveTime) * time.Second,
Timeout: time.Duration(keepaliveOptions.ServerKeepaliveTimeout) * time.Second,
}
serverOpts = append(serverOpts, grpc.KeepaliveParams(kap))
kep := keepalive.EnforcementPolicy{
// needs to match clientKeepalive
MinTime: time.Duration(keepaliveOptions.ClientKeepaliveTime) * time.Second,
// allow keepalive w/o rpc
PermitWithoutStream: true,
}
serverOpts = append(serverOpts, grpc.KeepaliveEnforcementPolicy(kep))
return serverOpts
}

// ClientKeepaliveOptions returns the gRPC keepalive options for clients
func ClientKeepaliveOptions() []grpc.DialOption {
var dialOpts []grpc.DialOption
kap := keepalive.ClientParameters{
Time: time.Duration(keepaliveOptions.ClientKeepaliveTime) * time.Second,
Timeout: time.Duration(keepaliveOptions.ClientKeepaliveTimeout) * time.Second,
PermitWithoutStream: true,
}
dialOpts = append(dialOpts, grpc.WithKeepaliveParams(kap))
return dialOpts
}

0 comments on commit db3029c

Please sign in to comment.