add test

parent b87d95a6

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
#
# Copyright SecureKey Technologies Inc. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
ignored = ["github.com/fabric-sdk-sample/fabric-sdk-go/test/*"]
[[constraint]]
name = "github.com/golang/mock"
branch = "master"
[[constraint]]
name = "github.com/spf13/viper"
branch = "master"
[[constraint]]
name = "google.golang.org/grpc"
version = "1.19.0"
[[constraint]]
name = "github.com/golang/protobuf"
version = "1.1.0"
[[constraint]]
name = "golang.org/x/net"
branch = "master"
[[constraint]]
name = "github.com/cloudflare/cfssl"
version = "1.3.1"
[[constraint]]
name = "github.com/Knetic/govaluate"
version = "3.0.0"
[[constraint]]
name = "github.com/miekg/pkcs11"
branch = "master"
[[constraint]]
name = "github.com/mitchellh/mapstructure"
branch = "master"
[[constraint]]
name = "github.com/pkg/errors"
version = "0.8.0"
[[constraint]]
name = "golang.org/x/crypto"
branch = "master"
[[constraint]]
name = "github.com/stretchr/testify"
version = "1.2.0"
[[constraint]]
name = "github.com/hyperledger/fabric-lib-go"
version = "1.0.0"
This diff is collapsed.
## Maintainers
### Active Maintainers
| Name | GitHub | Gerrit | email |
|---|---|---|---|
| Aleksandar Likic | alikic | aleksandar.likic | aleksandar.likic@securekey.com |
| Bob Stasyszyn | bstasyszyn | bstasyszyn | bob.stasyszyn@securekey.com |
| Firas.Qutishat | fqutishat | firas.qutishat | firas.qutishat@securekey.com |
| Gari Singh | mastersingh24 | mastersingh24 | gari.r.singh@gmail.com |
| Troy Ronda | troyronda | troyronda | troy@troyronda.com |
### Retired Maintainers
| Name | GitHub | Gerrit | email |
|---|---|---|---|
| Jim Zhang | jimthematrix | jimthematrix | jim_the_matrix@hotmail.com |
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>
\ No newline at end of file
This diff is collapsed.
# Hyperledger Fabric Client SDK for Go
[![Build Status](https://jenkins.hyperledger.org/buildStatus/icon?job=fabric-sdk-go-tests-merge-x86_64)](https://jenkins.hyperledger.org/job/fabric-sdk-go-tests-merge-x86_64)
[![Go Report Card](https://goreportcard.com/badge/github.com/fabric-sdk-sample/fabric-sdk-go)](https://goreportcard.com/report/github.com/fabric-sdk-sample/fabric-sdk-go)
[![GoDoc](https://godoc.org/github.com/fabric-sdk-sample/fabric-sdk-go?status.svg)](https://godoc.org/github.com/fabric-sdk-sample/fabric-sdk-go)
This SDK enables Go developers to build solutions that interact with [Hyperledger Fabric](http://hyperledger-fabric.readthedocs.io/en/latest/).
## Getting started
Obtain the client SDK packages for Fabric and Fabric CA.
```bash
go get github.com/fabric-sdk-sample/fabric-sdk-go
```
You're good to go, happy coding! Check out the examples for usage demonstrations.
### Examples
- [E2E Test](test/integration/e2e/end_to_end.go): Basic example that uses SDK to query and execute transaction
- [Ledger Query Test](test/integration/pkg/client/ledger/ledger_queries_test.go): Basic example that uses SDK to query a channel's underlying ledger
- [Multi Org Test](test/integration/e2e/orgs/multiple_orgs_test.go): An example that has multiple organisations involved in transaction
- [Dynamic Endorser Selection](test/integration/pkg/fabsdk/provider/sdk_provider_test.go): An example that uses dynamic endorser selection (based on chaincode policy)
- [E2E PKCS11 Test](test/integration/e2e/pkcs11/e2e_test.go): E2E Test using a PKCS11 crypto suite and configuration
- [CLI](https://github.com/securekey/fabric-examples/tree/master/fabric-cli/): An example CLI for Fabric built with the Go SDK.
- More examples needed!
### Community
- Discussion is happening in [Rocket Chat](https://chat.hyperledger.org/channel/fabric-sdk-go).
- Issue tracking is handled in [Jira](https://jira.hyperledger.org/secure/RapidBoard.jspa?projectKey=FAB&rapidView=7&view=planning).
- Active development occurs in the [Gerrit](https://gerrit.hyperledger.org/r/#/admin/projects/fabric-sdk-go) repository.
## Client SDK
### Current Compatibility
The SDK's integration tests run against three tagged Fabric versions:
- prev (currently v1.3.0)
- stable (currently v1.4.0)
- prerelease (currently disabled)
Additionally for development purposes integration tests also run against the devstable Fabric version as needed.
### Retired versions
When the 'prev' code level is updated, the last tested fabric-sdk-go commit or tag is listed below.
- fabric v1.2: 5e291d3
- fabric v1.1: f7ae259
- fabric v1.0: 5ac5226
### Auth Token payload compatibility between Fabric CA v1.4 and earlier releases
Fabric CA v1.4 introduced a more secure Auth Token payload signing which requires a non compatible update.
In order to maintain compatibility with Fabric CA v1.3, the CA client queries the server to fetch the version and
determine if compatibility with pre v1.4 is required.
Once v1.3 is retired, the above client code logic will need to be removed as well. No change is required from the Go SDK users.
### Running the test suite
Obtain the client SDK packages for Fabric and Fabric CA.
```bash
git clone https://github.com/fabric-sdk-sample/fabric-sdk-go.git
# Alternatively, you should clone from gerrit to contribute. For example:
# git clone ssh://<username>@gerrit.hyperledger.org:29418/fabric-sdk-go && scp -p -P 29418 <username>@gerrit.hyperledger.org:hooks/commit-msg fabric-sdk-go/.git/hooks/
#
# See https://gerrit.hyperledger.org/
```
```bash
# In the Fabric SDK Go directory
cd fabric-sdk-go/
# Optional - Automatically install Go tools used by test suite
# make depend
# Running test suite
make
# Clean test suite run artifacts
make clean
```
### Go Tags
The following Go tags can be supplied to enable additional functionality:
- experimental: includes support for experimental features.
## Contributing to the Go SDK
If you want to contribute to the Go SDK, please run the test suite and submit patches to the Gerrit git repostory for review. For general guidelines, please refer to the Fabric project's [contribution page](http://hyperledger-fabric.readthedocs.io/en/latest/CONTRIBUTING.html).
You need:
- Go 1.11
- Make
- Docker
- Docker Compose
- Git
- gobin (GO111MODULE=off go get -u github.com/myitcv/gobin)
- libtool
Notes:
- Dep is deprecated and replaced with Go modules.
### Gerrit Git repository
To contribute patches, you will need to clone (or add a remote) from [Gerrit](https://gerrit.hyperledger.org/r/#/admin/projects/fabric-sdk-go) with authentication.
### Running a portion of the test suite
```bash
# In the Fabric SDK Go directory
cd fabric-sdk-go/
# Optional - Automatically install Go tools used by test suite
# make depend
# Optional - Running only code checks (linters, license, spelling, etc)
# make checks
# Running all unit tests and checks
make unit-test
# Running all integration tests
make integration-test
```
### Running package unit tests manually
```bash
# In a package directory
go test
```
### Running integration tests manually
You need:
- A working fabric and fabric-ca set up. It is recommended that you use the docker-compose file provided in `test/fixtures/dockerenv`. It is also recommended that you use the default .env settings provided in `test/fixtures/dockerenv`. See steps below.
- Customized settings in the `test/fixtures/config/config_test.yaml` in case your Hyperledger Fabric network is not running on `localhost` or is using different ports.
#### Testing with Fabric Images at Docker Hub
The test suite defaults to the latest compatible tag of fabric images at Docker Hub.
The following commands starts Fabric:
```bash
# In the Fabric SDK Go directory
cd fabric-sdk-go
# Start fabric (stable tag)
make dockerenv-stable-up
# Or more generally, start fabric at a different code level (prev, stable, prerelease, devstable)
# make dockerenv-[CODELEVEL]-up
```
#### Running Integration Tests
Fabric should now be running. In a different shell, run integration tests
```bash
# In the Fabric SDK Go directory
cd fabric-sdk-go
# Use script to setup parameters for integration tests and execute them
# Previously we use to have hostnames like Fabric CA server, orderer and peer pointed to localhost
# Now since we removed this now, We will be using a different configuration
make integration-tests-local
# Or more generally, run integration tests at a different code level (prev, stable, prerelease, devstable)
# and fixture target version
# FABRIC_CODELEVEL_VER=[VER] FABRIC_CODELEVEL_TAG=[CODELEVEL] make integration-tests-local
```
```bash
# Previously we use to have hostnames like Fabric CA server, orderer and peer pointed to localhost
# Now since we removed this now, We will be using a different config file config_test_local.yaml
# which has the Fabric CA server, orderer and peers pointed to localhost
# It is also possible to run integration tests using go test directly. For example:
#cd fabric-sdk-go/test/integration/
#go test -args testLocal=true
#cd fabric-sdk-go/test/integration/orgs
#go test -args testLocal=true
# You should review test/scripts/integration.sh for options and details.
# Note: you should generally prefer the scripted version to setup parameters for you.
```
#### Testing with Local Build of Fabric (Advanced)
Alternatively you can use a local build of Fabric using the following commands:
```bash
# Start fabric (devstable codelevel with latest docker tags)
make dockerenv-latest-up
```
## License
Hyperledger Fabric SDK Go software is licensed under the [Apache License Version 2.0](LICENSE).
---
This document is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>.
#
# Copyright SecureKey Technologies Inc. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
GO_VER=1.11.5
GO_MIN_VER=1.11
GO_MAX_VER=1.12.3
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package fabricsdk enables Go developers to build solutions that interact with Hyperledger Fabric.
//
// Packages for end developer usage
//
// pkg/fabsdk: The main package of the Fabric SDK. This package enables creation of contexts based on
// configuration. These contexts are used by the client packages listed below.
// Reference: https://godoc.org/github.com/fabric-sdk-sample/fabric-sdk-go/pkg/fabsdk
//
// pkg/client/channel: Provides channel transaction capabilities.
// Reference: https://godoc.org/github.com/fabric-sdk-sample/fabric-sdk-go/pkg/client/channel
//
// pkg/client/event: Provides channel event capabilities.
// Reference: https://godoc.org/github.com/fabric-sdk-sample/fabric-sdk-go/pkg/client/event
//
// pkg/client/ledger: Enables queries to a channel's underlying ledger.
// Reference: https://godoc.org/github.com/fabric-sdk-sample/fabric-sdk-go/pkg/client/ledger
//
// pkg/client/resmgmt: Provides resource management capabilities such as installing chaincode.
// Reference: https://godoc.org/github.com/fabric-sdk-sample/fabric-sdk-go/pkg/client/resmgmt
//
// pkg/client/msp: Enables identity management capability.
// Reference: https://godoc.org/github.com/fabric-sdk-sample/fabric-sdk-go/pkg/client/msp
//
// Basic workflow
//
// 1) Instantiate a fabsdk instance using a configuration.
// Note: fabsdk maintains caches so you should minimize instances of fabsdk itself.
// 2) Create a context based on a user and organization, using your fabsdk instance.
// Note: A channel context additionally requires the channel ID.
// 3) Create a client instance using its New func, passing the context.
// Note: you create a new client instance for each context you need.
// 4) Use the funcs provided by each client to create your solution!
// 5) Call fabsdk.Close() to release resources and caches.
package fabricsdk
// Copyright SecureKey Technologies Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
module github.com/hyperledger/fabric-sdk-go
require (
github.com/Knetic/govaluate v3.0.0+incompatible
github.com/VividCortex/gohistogram v1.0.0 // indirect
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 // indirect
github.com/cloudflare/cfssl v0.0.0-20180223231731-4e2dcbde5004
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-kit/kit v0.8.0
github.com/go-logfmt/logfmt v0.4.0 // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/gogo/protobuf v1.1.1
github.com/golang/mock v1.2.0
github.com/golang/protobuf v1.2.0
github.com/google/certificate-transparency-go v0.0.0-20180222191210-5ab67e519c93 // indirect
github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce // indirect
github.com/hyperledger/fabric-lib-go v1.0.0
github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric v0.0.0-20190524192706-bfae339c63bf // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/magiconair/properties v1.7.6 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/miekg/pkcs11 v0.0.0-20190329070431-55f3fac3af27
github.com/mitchellh/mapstructure v0.0.0-20180220230111-00c29f56e238
github.com/onsi/gomega v1.4.2 // indirect
github.com/pelletier/go-toml v1.1.0 // indirect
github.com/pkg/errors v0.8.1
github.com/prometheus/client_golang v0.8.0
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 // indirect
github.com/prometheus/common v0.0.0-20180518154759-7600349dcfe1 // indirect
github.com/prometheus/procfs v0.0.0-20180705121852-ae68e2d4c00f // indirect
github.com/spf13/afero v1.1.0 // indirect
github.com/spf13/cast v1.2.0
github.com/spf13/jwalterweatherman v0.0.0-20180109140146-7c0cea34c8ec // indirect
github.com/spf13/pflag v1.0.1 // indirect
github.com/spf13/viper v1.0.2
github.com/stretchr/testify v1.3.0
golang.org/x/crypto v0.0.0-20180505025534-4ec37c66abab
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd
google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d // indirect
google.golang.org/grpc v1.19.0
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v2 v2.2.1
)
go 1.13
This diff is collapsed.
#
# Copyright SecureKey Technologies Inc. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
run:
concurrency: 4
deadline: 1m
issues-exit-code: 1
tests: true
build-tags: []
skip-dirs: []
skip-files:
- ^(.*_test.go.*$)$
output:
format: colored-line-number
print-issued-lines: true
print-linter-name: true
linters-settings:
errcheck:
check-type-assertions: false
check-blank: false
ignore: fmt:.*,io/ioutil:^Read.*
govet:
check-shadowing: true
settings:
printf:
funcs:
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
golint:
min-confidence: 0.8
gofmt:
simplify: true
goimports:
local-prefixes:
gocyclo:
min-complexity: 10
maligned:
suggest-new: true
dupl:
threshold: 100
goconst:
min-len: 3
min-occurrences: 3
misspell:
locale:
ignore-words: []
lll:
line-length: 120
tab-width: 1
unused:
check-exported: false
unparam:
check-exported: false
nakedret:
max-func-lines: 30
linters:
disable-all: true
enable:
- deadcode
- gocyclo
- gofmt
- goimports
- golint
- gosimple
- ineffassign
- misspell
- unconvert
- unused
- vet
- varcheck
- maligned
- errcheck
- megacheck
- goconst
- gas
- structcheck
enable-all: false
disable: []
presets:
- bugs
- unused
fast: false
issues:
exclude-use-default: false
\ No newline at end of file
/*
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.
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package api
import (
"github.com/cloudflare/cfssl/signer"
)
/*
* This file contains the structure definitions for the request
* and responses which flow over the network between a fabric-ca client
* and the fabric-ca server.
*/
// RegistrationRequestNet is the registration request for a new identity
type RegistrationRequestNet struct {
RegistrationRequest
}
// RegistrationResponseNet is a registration response
type RegistrationResponseNet struct {
RegistrationResponse
}
// EnrollmentRequestNet is a request to enroll an identity
type EnrollmentRequestNet struct {
signer.SignRequest
CAName string
AttrReqs []*AttributeRequest `json:"attr_reqs,omitempty"`
}
// ReenrollmentRequestNet is a request to reenroll an identity.
// This is useful to renew a certificate before it has expired.
type ReenrollmentRequestNet struct {
signer.SignRequest
CAName string
AttrReqs []*AttributeRequest `json:"attr_reqs,omitempty"`
}
// RevocationRequestNet is a revocation request which flows over the network
// to the fabric-ca server.
// To revoke a single certificate, both the Serial and AKI fields must be set;
// otherwise, to revoke all certificates and the identity associated with an enrollment ID,
// the Name field must be set to an existing enrollment ID.
// A RevocationRequest can only be performed by a user with the "hf.Revoker" attribute.
type RevocationRequestNet struct {
RevocationRequest
}
// GetTCertBatchRequestNet is a network request for a batch of transaction certificates
type GetTCertBatchRequestNet struct {
GetTCertBatchRequest
// KeySigs is an optional array of public keys and corresponding signatures.
// If not set, the server generates it's own keys based on a key derivation function
// which cryptographically relates the TCerts to an ECert.
KeySigs []KeySig `json:"key_sigs,omitempty"`
}
// GetTCertBatchResponseNet is the network response for a batch of transaction certificates
type GetTCertBatchResponseNet struct {
GetTCertBatchResponse
}
// AddIdentityRequestNet is a network request for adding a new identity
type AddIdentityRequestNet struct {
AddIdentityRequest
}
// ModifyIdentityRequestNet is a network request for modifying an existing identity
type ModifyIdentityRequestNet struct {
ModifyIdentityRequest
}
// AddAffiliationRequestNet is a network request for adding a new affiliation
type AddAffiliationRequestNet struct {
AddAffiliationRequest
}
// ModifyAffiliationRequestNet is a network request for modifying an existing affiliation
type ModifyAffiliationRequestNet struct {
ModifyAffiliationRequest
}
// GetCertificatesRequestNet is a network request for getting certificates
type GetCertificatesRequestNet struct {
GetCertificatesRequest
}
// KeySig is a public key, signature, and signature algorithm tuple
type KeySig struct {
// Key is a public key
Key []byte `json:"key"`
// Sig is a signature over the PublicKey
Sig []byte `json:"sig"`
// Alg is the signature algorithm
Alg string `json:"alg"`
}
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
/*
* The attrmgr package contains utilities for managing attributes.
* Attributes are added to an X509 certificate as an extension.
*/
package attrmgr
import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/json"
"fmt"
"github.com/pkg/errors"
)
var (
// AttrOID is the ASN.1 object identifier for an attribute extension in an
// X509 certificate
AttrOID = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 7, 8, 1}
// AttrOIDString is the string version of AttrOID
AttrOIDString = "1.2.3.4.5.6.7.8.1"
)
// Attribute is a name/value pair
type Attribute interface {
// GetName returns the name of the attribute
GetName() string
// GetValue returns the value of the attribute
GetValue() string
}
// AttributeRequest is a request for an attribute
type AttributeRequest interface {
// GetName returns the name of an attribute
GetName() string
// IsRequired returns true if the attribute is required
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
}
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package credential
import (
"net/http"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/api"
)
// Credential represents an credential of an identity
type Credential interface {
// Type returns type of this credential
Type() string
// EnrollmentID returns enrollment ID associated with this credential
// Returns an error if the credential value is not set (SetVal is not called)
// or not loaded from the disk (Load is not called)
EnrollmentID() (string, error)
// Val returns credential value.
// Returns an error if the credential value is not set (SetVal is not called)
// or not loaded from the disk (Load is not called)
Val() (interface{}, error)
// Sets the credential value
SetVal(val interface{}) error
// Stores the credential value to disk
Store() error
// Loads the credential value from disk and sets the value of this credential
Load() error
// CreateToken returns authorization token for the specified request with
// specified body
CreateToken(req *http.Request, reqBody []byte, fabCACompatibilityMode bool) (string, error)
// Submits revoke request to the Fabric CA server to revoke this credential
RevokeSelf() (*api.RevocationResponse, error)
}
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package x509
import (
"encoding/hex"
"net/http"
"github.com/fabric-sdk-sample/fabric-sdk-go/pkg/common/providers/core"
factory "github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/sdkpatch/cryptosuitebridge"
log "github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/sdkpatch/logbridge"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/api"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/lib/client/credential"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/util"
"github.com/pkg/errors"
)
const (
// CredType is the string that represents X509 credential type
CredType = "X509"
)
// Client represents a client that will load/store an Idemix credential
type Client interface {
NewX509Identity(name string, creds []credential.Credential) Identity
GetCSP() core.CryptoSuite
}
// Identity represents an identity
type Identity interface {
Revoke(req *api.RevocationRequest) (*api.RevocationResponse, error)
}
// Credential represents a X509 credential. Implements Credential interface
type Credential struct {
client Client
certFile []byte
keyFile core.Key
val *Signer
}
// NewCredential is constructor for X509 Credential
func NewCredential(keyFile core.Key, certFile []byte, c Client) *Credential {
return &Credential{
c, certFile, keyFile, nil,
}
}
// Type returns X509
func (cred *Credential) Type() string {
return CredType
}
// Val returns *Signer associated with this X509 credential
func (cred *Credential) Val() (interface{}, error) {
if cred.val == nil {
return nil, errors.New("X509 Credential value is not set")
}
return cred.val, nil
}
// EnrollmentID returns enrollment ID of this X509 credential
func (cred *Credential) EnrollmentID() (string, error) {
if cred.val == nil {
return "", errors.New("X509 Credential value is not set")
}
return cred.val.GetName(), nil
}
// SetVal sets *Signer for this X509 credential
func (cred *Credential) SetVal(val interface{}) error {
s, ok := val.(*Signer)
if !ok {
return errors.New("The X509 credential value must be of type *Signer for X509 credential")
}
cred.val = s
return nil
}
// Load loads the certificate and key from the location specified by
// certFile attribute using the BCCSP of the client. The private key is
// loaded from the location specified by the keyFile attribute, if the
// private key is not found in the keystore managed by BCCSP
func (cred *Credential) Load() error {
var err error
cred.val, err = NewSigner(cred.keyFile, cred.certFile)
if err != nil {
return err
}
return nil
}
// Store stores the certificate associated with this X509 credential to the location
// specified by certFile attribute
func (cred *Credential) Store() error {
log.Debugf("Credential.Store() not supported")
return nil
}
// CreateToken creates token based on this X509 credential
func (cred *Credential) CreateToken(req *http.Request, reqBody []byte, fabCACompatibilityMode bool) (string, error) {
return util.CreateToken(cred.getCSP(), cred.val.certBytes, cred.val.key, req.Method, req.URL.RequestURI(), reqBody, fabCACompatibilityMode)
}
// RevokeSelf revokes this X509 credential
func (cred *Credential) RevokeSelf() (*api.RevocationResponse, error) {
name, err := cred.EnrollmentID()
if err != nil {
return nil, err
}
val := cred.val
serial := util.GetSerialAsHex(val.cert.SerialNumber)
aki := hex.EncodeToString(val.cert.AuthorityKeyId)
req := &api.RevocationRequest{
Serial: serial,
AKI: aki,
}
id := cred.client.NewX509Identity(name, []credential.Credential{cred})
return id.Revoke(req)
}
func (cred *Credential) getCSP() core.CryptoSuite {
if cred.client != nil && cred.client.GetCSP() != nil {
return cred.client.GetCSP()
}
return factory.GetDefault()
}
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package x509
import (
"crypto/x509"
"fmt"
"github.com/fabric-sdk-sample/fabric-sdk-go/pkg/common/providers/core"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/lib/attrmgr"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/util"
"github.com/pkg/errors"
)
// NewSigner is constructor for Signer
func NewSigner(key core.Key, cert []byte) (*Signer, error) {
s := &Signer{
key: key,
certBytes: cert,
}
var err error
s.cert, err = util.GetX509CertificateFromPEM(s.certBytes)
if err != nil {
return nil, errors.WithMessage(err, "Failed to unmarshal X509 certificate bytes")
}
s.name = util.GetEnrollmentIDFromX509Certificate(s.cert)
return s, nil
}
// Signer represents a signer
// Each identity may have multiple signers, currently one ecert and multiple tcerts
type Signer struct {
// Private key
key core.Key
// Certificate bytes
certBytes []byte
// X509 certificate that is constructed from the cert bytes associated with this signer
cert *x509.Certificate
// Common name from the certificate associated with this signer
name string
}
// Key returns the key bytes of this signer
func (s *Signer) Key() core.Key {
return s.key
}
// Cert returns the cert bytes of this signer
func (s *Signer) Cert() []byte {
return s.certBytes
}
// GetX509Cert returns the X509 certificate for this signer
func (s *Signer) GetX509Cert() *x509.Certificate {
return s.cert
}
// GetName returns common name that is retrieved from the Subject of the certificate
// associated with this signer
func (s *Signer) GetName() string {
return s.name
}
// Attributes returns the attributes that are in the certificate
func (s *Signer) Attributes() (*attrmgr.Attributes, error) {
cert := s.GetX509Cert()
attrs, err := attrmgr.New().GetAttributesFromCert(cert)
if err != nil {
return nil, fmt.Errorf("Failed getting attributes for '%s': %s", s.name, err)
}
return attrs, nil
}
/*
Copyright IBM Corp. 2017 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.
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package lib
import (
"github.com/fabric-sdk-sample/fabric-sdk-go/pkg/common/providers/core"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/api"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/lib/tls"
)
// ClientConfig is the fabric-ca client's config
type ClientConfig struct {
URL string `def:"http://localhost:7054" opt:"u" help:"URL of fabric-ca-server"`
MSPDir string `def:"msp" opt:"M" help:"Membership Service Provider directory"`
TLS tls.ClientTLSConfig
Enrollment api.EnrollmentRequest
CSR api.CSRInfo
ID api.RegistrationRequest
Revoke api.RevocationRequest
CAInfo api.GetCAInfoRequest
CAName string `help:"Name of CA"`
CSP core.CryptoSuite `mapstructure:"bccsp" hide:"true"`
ServerName string `help:"CA server name to be used in case of host name override"`
Debug bool `opt:"d" help:"Enable debug level logging" hide:"true"`
LogLevel string `help:"Set logging level (info, warning, debug, error, fatal, critical)"`
}
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package common
const (
// IdemixTokenVersion1 represents version 1 of the authorization token created using Idemix credential
IdemixTokenVersion1 = "1"
)
// CAInfoResponseNet is the response to the GET /info request
type CAInfoResponseNet struct {
// CAName is a unique name associated with fabric-ca-server's CA
CAName string
// Base64 encoding of PEM-encoded certificate chain
CAChain string
// Base64 encoding of Idemix issuer public key
IssuerPublicKey string
// Base64 encoding of PEM-encoded Idemix issuer revocation public key
IssuerRevocationPublicKey string
// Version of the server
Version string
}
// EnrollmentResponseNet is the response to the /enroll request
type EnrollmentResponseNet struct {
// Base64 encoded PEM-encoded ECert
Cert string
// The server information
ServerInfo CAInfoResponseNet
}
// IdemixEnrollmentResponseNet is the response to the /idemix/credential request
type IdemixEnrollmentResponseNet struct {
// Base64 encoding of proto bytes of idemix.Credential
Credential string
// Attribute name-value pairs
Attrs map[string]interface{}
// Base64 encoding of proto bytes of idemix.CredentialRevocationInformation
CRI string
// Base64 encoding of the issuer nonce
Nonce string
// The CA information
CAInfo CAInfoResponseNet
}
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package lib
// CAConfig ...
type CAConfig struct {
}
// ServerConfig ...
type ServerConfig struct {
CAcfg CAConfig `skip:"true"`
}
type serverInfoResponseNet struct {
// CAName is a unique name associated with fabric-ca-server's CA
CAName string
// Base64 encoding of PEM-encoded certificate chain
CAChain string
// Base64 encoding of idemix issuer public key
IssuerPublicKey string
// Version of the server
Version string
}
type enrollmentResponseNet struct {
// Base64 encoded PEM-encoded ECert
Cert string
// The server information
ServerInfo serverInfoResponseNet
}
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package lib
import (
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/api"
)
type revocationResponseNet struct {
RevokedCerts []api.RevokedCert
CRL string
}
// CertificateStatus represents status of an enrollment certificate
type CertificateStatus string
const (
// Revoked is the status of a revoked certificate
Revoked CertificateStatus = "revoked"
// Good is the status of a active certificate
Good = "good"
)
/*
Copyright IBM Corp. 2017 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.
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
// StreamJSONArray scans the JSON stream associated with 'decoder' to find
// an array value associated with the json element at 'pathToArray'.
// It then calls the 'cb' callback function so that it can decode one element
// in the stream at a time.
package streamer
import (
"encoding/json"
"fmt"
"os"
"reflect"
"strings"
"github.com/cloudflare/cfssl/api"
log "github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/sdkpatch/logbridge"
"github.com/pkg/errors"
)
// SearchElement defines the JSON arrays for which to search
type SearchElement struct {
Path string
CB func(*json.Decoder) error
}
// StreamJSONArray searches the JSON stream for an array matching 'path'.
// For each element of this array, it streams one element at a time.
func StreamJSONArray(decoder *json.Decoder, path string, cb func(*json.Decoder) error) (bool, error) {
ses := []SearchElement{
SearchElement{Path: path, CB: cb},
SearchElement{Path: "errors", CB: errCB},
}
return StreamJSON(decoder, ses)
}
// StreamJSON searches the JSON stream for arrays matching a search element.
// For each array that it finds, it streams them one element at a time.
func StreamJSON(decoder *json.Decoder, search []SearchElement) (bool, error) {
js := &jsonStream{decoder: decoder, search: search, stack: []string{}}
err := js.stream()
return js.gotResults, err
}
type jsonStream struct {
decoder *json.Decoder
search []SearchElement
stack []string
gotResults bool
}
func (js *jsonStream) stream() error {
t, err := js.getToken()
if err != nil {
return err
}
if _, ok := t.(json.Delim); !ok {
return nil
}
path := strings.Join(js.stack, ".")
se := js.getSearchElement(path)
d := fmt.Sprintf("%s", t)
switch d {
case "[":
if se != nil {
for js.decoder.More() {
err = se.CB(js.decoder)
if err != nil {
return err
}
js.gotResults = true
}
}
err = js.skipToDelim("]")
if err != nil {
return err
}
case "]":
return errors.Errorf("Unexpected '%s'", d)
case "{":
if se != nil {
return errors.Errorf("Expecting array for value of '%s'", path)
}
for {
name, err := js.getNextName()
if err != nil {
return err
}
if name == "" {
return nil
}
stack := js.stack
js.stack = append(stack, name)
err = js.stream()
if err != nil {
return err
}
js.stack = stack
}
case "}":
return errors.Errorf("Unexpected '%s'", d)
default:
return errors.Errorf("unknown JSON delimiter: '%s'", d)
}
return nil
}
// Find a search element named 'path'
func (js *jsonStream) getSearchElement(path string) *SearchElement {
for _, ele := range js.search {
if ele.Path == path {
return &ele
}
}
return nil
}
// Skip over tokens until we hit the delimiter
func (js *jsonStream) skipToDelim(delim string) error {
for {
t, err := js.getToken()
if err != nil {
return err
}
// Skip anything that isn't a delimiter
if _, ok := t.(json.Delim); !ok {
continue
}
// It is a delimiter
d := fmt.Sprintf("%s", t)
if d == delim {
return nil
}
switch d {
case "[":
err = js.skipToDelim("]")
case "]":
err = errors.Errorf("Expecting '%s' but found '%s'", delim, d)
case "{":
err = js.skipToDelim("}")
case "}":
err = errors.Errorf("Expecting '%s' but found '%s'", delim, d)
default:
err = errors.Errorf("unknown JSON delimiter: '%s'", d)
}
if err != nil {
return err
}
}
}
func (js *jsonStream) getNextName() (string, error) {
token, err := js.getToken()
if err != nil {
return "", err
}
switch v := token.(type) {
case string:
return v, nil
case json.Delim:
d := fmt.Sprintf("%s", v)
if d == "}" {
return "", nil
}
return "", errors.Errorf("Expecting '}' delimiter but found '%s'", d)
default:
return "", errors.Errorf("Expecting string or delimiter but found '%s'", v)
}
}
func (js *jsonStream) getToken() (interface{}, error) {
token, err := js.decoder.Token()
if os.Getenv("FABRIC_CA_JSON_STREAM_DEBUG") != "" {
log.Debugf("TOKEN: type=%s, %+v\n", reflect.TypeOf(token), token)
}
return token, err
}
func errCB(decoder *json.Decoder) error {
errMsg := &api.ResponseMessage{}
err := decoder.Decode(errMsg)
if err != nil {
return errors.Errorf("Invalid JSON error format: %s", err)
}
return errors.Errorf("%+v", errMsg)
}
/*
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.
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package tls
import (
"crypto/tls"
"crypto/x509"
"time"
"github.com/fabric-sdk-sample/fabric-sdk-go/pkg/common/providers/core"
factory "github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/sdkpatch/cryptosuitebridge"
log "github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/sdkpatch/logbridge"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/util"
"github.com/pkg/errors"
)
// DefaultCipherSuites is a set of strong TLS cipher suites
var DefaultCipherSuites = []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
}
// ClientTLSConfig defines the key material for a TLS client
type ClientTLSConfig struct {
Enabled bool `skip:"true"`
CertFiles [][]byte `help:"A list of comma-separated PEM-encoded trusted certificate bytes"`
Client KeyCertFiles
}
// KeyCertFiles defines the files need for client on TLS
type KeyCertFiles struct {
KeyFile []byte `help:"PEM-encoded key bytes when mutual authentication is enabled"`
CertFile []byte `help:"PEM-encoded certificate bytes when mutual authenticate is enabled"`
}
// GetClientTLSConfig creates a tls.Config object from certs and roots
func GetClientTLSConfig(cfg *ClientTLSConfig, csp core.CryptoSuite) (*tls.Config, error) {
var certs []tls.Certificate
if csp == nil {
csp = factory.GetDefault()
}
if cfg.Client.CertFile != nil {
err := checkCertDates(cfg.Client.CertFile)
if err != nil {
return nil, err
}
clientCert, err := util.LoadX509KeyPair(cfg.Client.CertFile, cfg.Client.KeyFile, csp)
if err != nil {
return nil, err
}
certs = append(certs, *clientCert)
} else {
log.Debug("Client TLS certificate and/or key file not provided")
}
rootCAPool := x509.NewCertPool()
if len(cfg.CertFiles) == 0 {
return nil, errors.New("No trusted root certificates for TLS were provided")
}
for _, cacert := range cfg.CertFiles {
ok := rootCAPool.AppendCertsFromPEM(cacert)
if !ok {
return nil, errors.New("Failed to process certificate")
}
}
config := &tls.Config{
Certificates: certs,
RootCAs: rootCAPool,
}
return config, nil
}
func checkCertDates(certPEM []byte) error {
log.Debug("Check client TLS certificate for valid dates")
cert, err := util.GetX509CertificateFromPEM(certPEM)
if err != nil {
return err
}
notAfter := cert.NotAfter
currentTime := time.Now().UTC()
if currentTime.After(notAfter) {
return errors.New("Certificate provided has expired")
}
notBefore := cert.NotBefore
if currentTime.Before(notBefore) {
return errors.New("Certificate provided not valid until later date")
}
return nil
}
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package lib
import (
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"net/http"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric-ca/util"
"github.com/pkg/errors"
)
var clientAuthTypes = map[string]tls.ClientAuthType{
"noclientcert": tls.NoClientCert,
"requestclientcert": tls.RequestClientCert,
"requireanyclientcert": tls.RequireAnyClientCert,
"verifyclientcertifgiven": tls.VerifyClientCertIfGiven,
"requireandverifyclientcert": tls.RequireAndVerifyClientCert,
}
// GetCertID returns both the serial number and AKI (Authority Key ID) for the certificate
func GetCertID(bytes []byte) (string, string, error) {
cert, err := BytesToX509Cert(bytes)
if err != nil {
return "", "", err
}
serial := util.GetSerialAsHex(cert.SerialNumber)
aki := hex.EncodeToString(cert.AuthorityKeyId)
return serial, aki, nil
}
// BytesToX509Cert converts bytes (PEM or DER) to an X509 certificate
func BytesToX509Cert(bytes []byte) (*x509.Certificate, error) {
dcert, _ := pem.Decode(bytes)
if dcert != nil {
bytes = dcert.Bytes
}
cert, err := x509.ParseCertificate(bytes)
if err != nil {
return nil, errors.Wrap(err, "Buffer was neither PEM nor DER encoding")
}
return cert, err
}
func addQueryParm(req *http.Request, name, value string) {
url := req.URL.Query()
url.Add(name, value)
req.URL.RawQuery = url.Encode()
}
// CertificateDecoder is needed to keep track of state, to see how many certificates
// have been returned for each enrollment ID.
type CertificateDecoder struct {
certIDCount map[string]int
storePath string
}
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package cryptosuitebridge
import (
"crypto"
"crypto/ecdsa"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric/bccsp"
cspsigner "github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric/bccsp/signer"
"github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric/bccsp/utils"
"github.com/fabric-sdk-sample/fabric-sdk-go/pkg/common/providers/core"
"github.com/fabric-sdk-sample/fabric-sdk-go/pkg/core/cryptosuite"
)
const (
ECDSA = bccsp.ECDSA
ECDSAP256 = bccsp.ECDSAP256
ECDSAP384 = bccsp.ECDSAP384
ECDSAReRand = bccsp.ECDSAReRand
RSA = bccsp.RSA
RSA1024 = bccsp.RSA1024
RSA2048 = bccsp.RSA2048
RSA3072 = bccsp.RSA3072
RSA4096 = bccsp.RSA4096
AES = bccsp.AES
AES128 = bccsp.AES128
AES192 = bccsp.AES192
AES256 = bccsp.AES256
HMAC = bccsp.HMAC
HMACTruncated256 = bccsp.HMACTruncated256
SHA = bccsp.SHA
SHA2 = bccsp.SHA2
SHA3 = bccsp.SHA3
SHA256 = bccsp.SHA256
SHA384 = bccsp.SHA384
SHA3_256 = bccsp.SHA3_256
SHA3_384 = bccsp.SHA3_384
X509Certificate = bccsp.X509Certificate
)
// NewCspSigner is a bridge for bccsp signer.New call
func NewCspSigner(csp core.CryptoSuite, key core.Key) (crypto.Signer, error) {
return cspsigner.New(csp, key)
}
// PEMtoPrivateKey is a bridge for bccsp utils.PEMtoPrivateKey()
func PEMtoPrivateKey(raw []byte, pwd []byte) (interface{}, error) {
return utils.PEMtoPrivateKey(raw, pwd)
}
// PrivateKeyToDER marshals is bridge for utils.PrivateKeyToDER
func PrivateKeyToDER(privateKey *ecdsa.PrivateKey) ([]byte, error) {
return utils.PrivateKeyToDER(privateKey)
}
//GetDefault returns default cryptosuite from bccsp factory default
func GetDefault() core.CryptoSuite {
return cryptosuite.GetDefault()
}
//GetSHAOpts returns options for computing SHA.
func GetSHAOpts() core.HashOpts {
return &bccsp.SHAOpts{}
}
//GetSHA256Opts returns options relating to SHA-256.
func GetSHA256Opts() core.HashOpts {
return &bccsp.SHA256Opts{}
}
//GetRSA2048KeyGenOpts returns options for RSA key generation at 2048 security.
func GetRSA2048KeyGenOpts(ephemeral bool) core.KeyGenOpts {
return &bccsp.RSA2048KeyGenOpts{Temporary: ephemeral}
}
//GetRSA3072KeyGenOpts returns options for RSA key generation at 3072 security.
func GetRSA3072KeyGenOpts(ephemeral bool) core.KeyGenOpts {
return &bccsp.RSA3072KeyGenOpts{Temporary: ephemeral}
}
//GetRSA4096KeyGenOpts returns options for RSA key generation at 4096 security.
func GetRSA4096KeyGenOpts(ephemeral bool) core.KeyGenOpts {
return &bccsp.RSA4096KeyGenOpts{Temporary: ephemeral}
}
// GetECDSAKeyGenOpts returns options for ECDSA key generation.
func GetECDSAKeyGenOpts(ephemeral bool) core.KeyGenOpts {
return &bccsp.ECDSAKeyGenOpts{Temporary: ephemeral}
}
//GetECDSAP256KeyGenOpts returns options for ECDSA key generation with curve P-256.
func GetECDSAP256KeyGenOpts(ephemeral bool) core.KeyGenOpts {
return &bccsp.ECDSAP256KeyGenOpts{Temporary: ephemeral}
}
//GetECDSAP384KeyGenOpts options for ECDSA key generation with curve P-384.
func GetECDSAP384KeyGenOpts(ephemeral bool) core.KeyGenOpts {
return &bccsp.ECDSAP384KeyGenOpts{Temporary: ephemeral}
}
//GetX509PublicKeyImportOpts options for importing public keys from an x509 certificate
func GetX509PublicKeyImportOpts(ephemeral bool) core.KeyImportOpts {
return &bccsp.X509PublicKeyImportOpts{Temporary: ephemeral}
}
//GetECDSAPrivateKeyImportOpts options for ECDSA secret key importation in DER format
// or PKCS#8 format.
func GetECDSAPrivateKeyImportOpts(ephemeral bool) core.KeyImportOpts {
return &bccsp.ECDSAPrivateKeyImportOpts{Temporary: ephemeral}
}
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package logbridge
import (
clog "github.com/cloudflare/cfssl/log"
"github.com/fabric-sdk-sample/fabric-sdk-go/pkg/common/logging"
)
var logger *logging.Logger
var cfLogBridge *cLogger
func init() {
logger = logging.NewLogger("fabsdk/fab")
cfLogBridge = &cLogger{}
clog.SetLogger(cfLogBridge)
}
// Debug bridges calls to the Go SDK logger's Debug.
func Debug(args ...interface{}) {
logger.Debug(args...)
}
// Debugf bridges calls to the Go SDK logger's Debugf.
func Debugf(format string, args ...interface{}) {
logger.Debugf(format, args)
}
// Info bridges calls to the Go SDK logger's Info.
func Info(args ...interface{}) {
logger.Info(args...)
}
// Infof bridges calls to the Go SDK logger's Debugf.
func Infof(format string, args ...interface{}) {
logger.Infof(format, args...)
}
// Warning bridges calls to the Go SDK logger's Warn.
func Warning(args ...interface{}) {
logger.Warn(args...)
}
// Fatalf bridges calls to the Go SDK logger's Debugf.
func Fatalf(format string, args ...interface{}) {
logger.Fatalf(format, args...)
}
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package logbridge
// cLogger implements CFSSL's SyslogWriter interface
type cLogger struct {
}
// Debug bridges calls to the Go SDK logger's Debug.
func (log *cLogger) Debug(s string) {
logger.Debug(s)
}
// Info bridges calls to the Go SDK logger's Info.
func (log *cLogger) Info(s string) {
logger.Info(s)
}
// Warning bridges calls to the Go SDK logger's Warn.
func (log *cLogger) Warning(s string) {
logger.Warn(s)
}
// Err bridges calls to the Go SDK logger's Error.
func (log *cLogger) Err(s string) {
logger.Error(s)
}
// Crit bridges calls to the Go SDK logger's Error.
func (log *cLogger) Crit(s string) {
logger.Error(s)
}
// Emerg bridges calls to the Go SDK logger's Error.
func (log *cLogger) Emerg(s string) {
logger.Error(s)
}
/*
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.
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package bccsp
import "io"
// AES128KeyGenOpts contains options for AES key generation at 128 security level
type AES128KeyGenOpts struct {
Temporary bool
}
// Algorithm returns the key generation algorithm identifier (to be used).
func (opts *AES128KeyGenOpts) Algorithm() string {
return AES128
}
// Ephemeral returns true if the key to generate has to be ephemeral,
// false otherwise.
func (opts *AES128KeyGenOpts) Ephemeral() bool {
return opts.Temporary
}
// AES192KeyGenOpts contains options for AES key generation at 192 security level
type AES192KeyGenOpts struct {
Temporary bool
}
// Algorithm returns the key generation algorithm identifier (to be used).
func (opts *AES192KeyGenOpts) Algorithm() string {
return AES192
}
// Ephemeral returns true if the key to generate has to be ephemeral,
// false otherwise.
func (opts *AES192KeyGenOpts) Ephemeral() bool {
return opts.Temporary
}
// AES256KeyGenOpts contains options for AES key generation at 256 security level
type AES256KeyGenOpts struct {
Temporary bool
}
// Algorithm returns the key generation algorithm identifier (to be used).
func (opts *AES256KeyGenOpts) Algorithm() string {
return AES256
}
// Ephemeral returns true if the key to generate has to be ephemeral,
// false otherwise.
func (opts *AES256KeyGenOpts) Ephemeral() bool {
return opts.Temporary
}
// AESCBCPKCS7ModeOpts contains options for AES encryption in CBC mode
// with PKCS7 padding.
// Notice that both IV and PRNG can be nil. In that case, the BCCSP implementation
// is supposed to sample the IV using a cryptographic secure PRNG.
// Notice also that either IV or PRNG can be different from nil.
type AESCBCPKCS7ModeOpts struct {
// IV is the initialization vector to be used by the underlying cipher.
// The length of IV must be the same as the Block's block size.
// It is used only if different from nil.
IV []byte
// PRNG is an instance of a PRNG to be used by the underlying cipher.
// It is used only if different from nil.
PRNG io.Reader
}
/*
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.
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package bccsp
// ECDSAP256KeyGenOpts contains options for ECDSA key generation with curve P-256.
type ECDSAP256KeyGenOpts struct {
Temporary bool
}
// Algorithm returns the key generation algorithm identifier (to be used).
func (opts *ECDSAP256KeyGenOpts) Algorithm() string {
return ECDSAP256
}
// Ephemeral returns true if the key to generate has to be ephemeral,
// false otherwise.
func (opts *ECDSAP256KeyGenOpts) Ephemeral() bool {
return opts.Temporary
}
// ECDSAP384KeyGenOpts contains options for ECDSA key generation with curve P-384.
type ECDSAP384KeyGenOpts struct {
Temporary bool
}
// Algorithm returns the key generation algorithm identifier (to be used).
func (opts *ECDSAP384KeyGenOpts) Algorithm() string {
return ECDSAP384
}
// Ephemeral returns true if the key to generate has to be ephemeral,
// false otherwise.
func (opts *ECDSAP384KeyGenOpts) Ephemeral() bool {
return opts.Temporary
}
/*
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.
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package bccsp
// KeyStore represents a storage system for cryptographic keys.
// It allows to store and retrieve bccsp.Key objects.
// The KeyStore can be read only, in that case StoreKey will return
// an error.
type KeyStore interface {
// ReadOnly returns true if this KeyStore is read only, false otherwise.
// If ReadOnly is true then StoreKey will fail.
ReadOnly() bool
// GetKey returns a key object whose SKI is the one passed.
GetKey(ski []byte) (k Key, err error)
// StoreKey stores the key k in this KeyStore.
// If this KeyStore is read only then the method will fail.
StoreKey(k Key) (err error)
}
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package channelconfig
import (
flogging "github.com/fabric-sdk-sample/fabric-sdk-go/internal/github.com/hyperledger/fabric/sdkpatch/logbridge"
)
var logger = flogging.MustGetLogger("common.channelconfig")
// RootGroupKey is the key for namespacing the channel config, especially for
// policy evaluation.
const RootGroupKey = "Channel"
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment